code stringlengths 2 1.05M | repo_name stringlengths 5 101 | path stringlengths 4 991 | language stringclasses 3 values | license stringclasses 5 values | size int64 2 1.05M |
|---|---|---|---|---|---|
#!/usr/bin/env perl
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016] EMBL-European Bioinformatics Institute
#
# 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.
=head1 NAME
mapping_stats.pl - print some statistics about a whole genome alignment between
two assemblies.
=head1 SYNOPSIS
mapping_stats.pl [arguments]
Required arguments:
--dbname, db_name=NAME database name NAME
--host, --dbhost, --db_host=HOST database host HOST
--port, --dbport, --db_port=PORT database port PORT
--user, --dbuser, --db_user=USER database username USER
--pass, --dbpass, --db_pass=PASS database passwort PASS
--assembly=ASSEMBLY assembly version ASSEMBLY
--altdbname=NAME alternative database NAME
--altassembly=ASSEMBLY alternative assembly version ASSEMBLY
Optional arguments:
--althost=HOST alternative databases host HOST
--altport=PORT alternative database port PORT
--altuser=USER alternative database username USER
--altpass=PASS alternative database password PASS
--chromosomes, --chr=LIST only process LIST toplevel seq_regions
--conffile, --conf=FILE read parameters from FILE
(default: conf/Conversion.ini)
--logfile, --log=FILE log to FILE (default: *STDOUT)
--logpath=PATH write logfile to PATH (default: .)
--logappend, --log_append append to logfile (default: truncate)
-v, --verbose=0|1 verbose logging (default: false)
-i, --interactive=0|1 run script interactively (default: true)
-n, --dry_run, --dry=0|1 don't write results to database
-h, --help, -? print help (this message)
=head1 DESCRIPTION
This script prints some statistics about a whole genome alignment between two
assemblies, like the alignment coverage and length of alignment blocks.
=cut
use strict;
use warnings;
no warnings 'uninitialized';
use FindBin qw($Bin);
use vars qw($SERVERROOT);
BEGIN {
$SERVERROOT = "$Bin/../../..";
unshift(@INC, "$SERVERROOT/ensembl/modules");
unshift(@INC, "$SERVERROOT/bioperl-live");
}
use Getopt::Long;
use Pod::Usage;
use Bio::EnsEMBL::Utils::ConversionSupport;
$| = 1;
my $support = new Bio::EnsEMBL::Utils::ConversionSupport($SERVERROOT);
# parse options
$support->parse_common_options(@_);
$support->parse_extra_options(
'assembly=s',
'altdbname=s',
'altassembly=s',
'althost=s',
'altport=n',
'altpass=s',
'chromosomes|chr=s@',
);
$support->allowed_params(
$support->get_common_params,
'assembly',
'altdbname',
'altassembly',
'althost',
'altport',
'chromosomes',
'altpass',
);
if ($support->param('help') or $support->error) {
warn $support->error if $support->error;
pod2usage(1);
}
$support->comma_to_list('chromosomes');
# ask user to confirm parameters to proceed
# $support->confirm_params;
# get log filehandle and print heading and parameters to logfile
$support->init_log;
$support->check_required_params(
'assembly',
'altdbname',
'altassembly'
);
# first set connection parameters for alternative db if not different from
# reference db
map { $support->param("alt$_", $support->param($_)) unless ($support->param("alt$_")) } qw(host port user);
# reference database
my $R_dba = $support->get_database('ensembl');
my $R_sa = $R_dba->get_SliceAdaptor;
# database containing the alternative assembly
my $A_dba = $support->get_database('core', 'alt');
my $A_sa = $A_dba->get_SliceAdaptor;
my $fmt1 = "%-40s%12s\n";
my $fmt2 = "%-40s%11.1f%%\n";
my $fmt3 = "%-44s%8.0f (%2.0f%%)\n";
my $fmt4 = "%-40s%12s%10s\n";
$support->log("Looping over toplevel seq_regions...\n\n");
foreach my $chr ($support->sort_chromosomes(undef, $support->param('assembly'), 1)) {
$support->log_stamped("Toplevel seq_region $chr...\n", 1);
# determine non-N sequence length of alternative toplevel seq_region
my $A_slice = $A_sa->fetch_by_region('toplevel', $chr);
unless ($A_slice) {
$support->log("Not found in alternative db. Skipping.\n", 2);
next;
}
my $cs_name = $A_slice->coord_system_name;
my $start = 1;
my $A_chr_length = $A_slice->length;
my $n;
my $end;
while ($start < $A_chr_length) {
$end = $start + 10000000;
$end = $A_chr_length if ($end > $A_chr_length);
my $sub_slice = $A_slice->sub_Slice($start, $end);
my $seq = $sub_slice->seq;
$n += $seq =~ tr/N/N/;
$start = $end + 1;
}
my $A_length = $A_chr_length - $n;
# determine total length of mapping to alternative assembly
my $mapping_length = 0;
my %blocks;
my %blocklength;
my %cont_mapping_blocks;
my %cont_mapping_length;
# toplevel seq_region length order of magnitude
my $oom = length($A_length);
#seq region on the alternative assembly
my $R_slice = $R_sa->fetch_by_region($cs_name, $chr,undef, undef, undef,$support->param('altassembly'));
#seq region on the latest assembly
my $R_new_assembly_slice = $R_sa->fetch_by_region($cs_name, $chr);
#map alternative assembly to latest
my @segments = @{ $R_slice->project($cs_name, $support->param('assembly')) };
my $alignments = 0;
my $alignment_runs = 0;
my $previous_sl;
my $cont_mapping_length = 0;
foreach my $seg (@segments) {
my $sl = $seg->to_Slice;
# ignore PAR region (i.e. we project to the symlinked seq_region)
#next if ($sl->seq_region_name ne $chr);
my $l = $sl->length;
$mapping_length += $l;
if ($previous_sl) {
#if current slice is on the same chromosome and within 10bps of the previous slice
#add it to the continuous mapping length
if ($previous_sl->seq_region_name eq $sl->seq_region_name && abs ($previous_sl->end - $sl->start) <= 10) {
$cont_mapping_length += $l;
} else {
my $c_oom = $oom;
while ($c_oom) {
if ($cont_mapping_length > 10**($c_oom-1) and $cont_mapping_length <= 10**$c_oom) {
$cont_mapping_blocks{10**$c_oom}++;
$cont_mapping_length{10**$c_oom} += $cont_mapping_length;
}
$c_oom--;
}
if ($cont_mapping_length == 1) {
$cont_mapping_blocks{10}++;
$cont_mapping_length{10}++
}
$cont_mapping_length = $l;
$alignment_runs ++;
}
} else {
$cont_mapping_length = $l;
}
my $c_oom = $oom;
while ($c_oom) {
if ($l > 10**($c_oom-1) and $l <= 10**$c_oom) {
$blocks{10**$c_oom}++;
$blocklength{10**$c_oom} += $l;
}
$c_oom--;
}
if ($l == 1) {
$blocks{10}++ ;
$blocklength{10}++;
}
$previous_sl = $sl;
$alignments++;
}
# print stats
$support->log("\n");
$support->log(sprintf($fmt1, "Reference toplevel seq_region length:",
$support->commify($R_new_assembly_slice->length)), 2);
$support->log(sprintf($fmt1, "Alternative toplevel seq_region length:",
$support->commify($A_chr_length)), 2);
$support->log(sprintf($fmt1, "Non-N sequence length (alternative):",
$support->commify($A_length)), 2);
$support->log(sprintf($fmt1, "Alternative mapping length:",
$support->commify($mapping_length)), 2);
$support->log(sprintf($fmt2, "Mapping percentage:",
$mapping_length/$A_length*100), 2);
$support->log("\n");
$support->log(sprintf($fmt4, "Total alignments:", $alignments, "Mapping %"), 2);
if ($alignments) {
for (my $i = 0; $i < $oom; $i++) {
my $from = 10**$i;
my $to = 10**($i+1);
$support->log(sprintf($fmt3, " ".$support->commify($from)." - ".$support->commify($to)." bp:", $blocks{$to}, $blocklength{$to}/$A_length*100), 2);
}
}
$support->log("\n");
$support->log(sprintf($fmt4, "Continuous alignment runs:", $alignment_runs, "Mapping %"), 2);
$support->log("(gaps up to 10bp)\n",2);
if ($alignments) {
for (my $i = 0; $i < $oom; $i++) {
my $from = 10**$i;
my $to = 10**($i+1);
$support->log(sprintf($fmt3, " ".$support->commify($from)." - ".$support->commify($to)." bp:", $cont_mapping_blocks{$to}, $cont_mapping_length{$to}/$A_length*100), 2);
}
}
$support->log("\n");
}
# finish logfile
$support->finish_log;
| danstaines/ensembl | misc-scripts/assembly/mapping_stats.pl | Perl | apache-2.0 | 8,879 |
package GistTokenizer;
use strict;
use warnings;
#use Moose;
use Text::Trim;
sub tokenize {
my $string = shift;
my @tokens;
# my @tokens = grep { length( $_ ); } split / |\p{Punct}/, $string;
@tokens = map { trim($_); } split /(\W)/, $string;
@tokens = grep { length( $_ ); } @tokens;
return \@tokens;
}
#no Moose;
1;
| ypetinot/web-summarization | src/perl/GistTokenizer.pm | Perl | apache-2.0 | 352 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V9::Services::AdService;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseService);
sub get {
my $self = shift;
my $request_body = shift;
my $http_method = 'GET';
my $request_path = 'v9/{+resourceName}';
my $response_type = 'Google::Ads::GoogleAds::V9::Resources::Ad';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
sub mutate {
my $self = shift;
my $request_body = shift;
my $http_method = 'POST';
my $request_path = 'v9/customers/{+customerId}/ads:mutate';
my $response_type =
'Google::Ads::GoogleAds::V9::Services::AdService::MutateAdsResponse';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Services/AdService.pm | Perl | apache-2.0 | 1,372 |
package VMOMI::VslmCloneSpec;
use parent 'VMOMI::VslmMigrateSpec';
use strict;
use warnings;
our @class_ancestors = (
'VslmMigrateSpec',
'DynamicData',
);
our @class_members = (
['name', undef, 0, ],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/VslmCloneSpec.pm | Perl | apache-2.0 | 437 |
g(X1,X2,X3) :- p(X1,X2), q(X2,X3), r(X1,X3).
p(a,b). q(b,c). r(a,d).
p(b,c). q(c,d). r(b,c).
r(a,W).
| leuschel/logen | old_logen/filter_prop/Tests/pqr.pl | Perl | apache-2.0 | 157 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V9::Services::ConversionValueRuleSetService;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseService);
sub get {
my $self = shift;
my $request_body = shift;
my $http_method = 'GET';
my $request_path = 'v9/{+resourceName}';
my $response_type =
'Google::Ads::GoogleAds::V9::Resources::ConversionValueRuleSet';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
sub mutate {
my $self = shift;
my $request_body = shift;
my $http_method = 'POST';
my $request_path =
'v9/customers/{+customerId}/conversionValueRuleSets:mutate';
my $response_type =
'Google::Ads::GoogleAds::V9::Services::ConversionValueRuleSetService::MutateConversionValueRuleSetsResponse';
return $self->SUPER::call($http_method, $request_path, $request_body,
$response_type);
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Services/ConversionValueRuleSetService.pm | Perl | apache-2.0 | 1,472 |
=head1 LICENSE
See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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.
=head1 NAME
Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::MercatorPecan_conf
=head1 SYNOPSIS
init_pipeline.pl Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::MercatorPecan_conf -host mysql-ens-compara-prod-X -port XXXX
=head1 DESCRIPTION
The Vertebrates PipeConfig file for MercatorPecan pipeline that should
automate most of the pre-execution tasks.
=cut
package Bio::EnsEMBL::Compara::PipeConfig::Vertebrates::MercatorPecan_conf;
use strict;
use warnings;
use Bio::EnsEMBL::Hive::Version 2.4;
use base ('Bio::EnsEMBL::Compara::PipeConfig::MercatorPecan_conf');
sub default_options {
my ($self) = @_;
return {
%{$self->SUPER::default_options}, # inherit the generic ones
# parameters that are likely to change from execution to another:
'species_set_name' => 'amniotes',
'division' => 'vertebrates',
'do_not_reuse_list' => [ ],
# previous release data location for reuse
'reuse_db' => 'amniotes_pecan_prev', # Cannot be the release db because we need exon members and the peptide_align_feature tables
};
}
1;
| Ensembl/ensembl-compara | modules/Bio/EnsEMBL/Compara/PipeConfig/Vertebrates/MercatorPecan_conf.pm | Perl | apache-2.0 | 1,772 |
=head1 LICENSE
# Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
#
# 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.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::Analysis::Runnable::DustMasker
=head1 SYNOPSIS
my $dust = Bio::EnsEMBL::Analysis::Runnable::DustMasker->
new(
-query => $slice,
-program => 'dustmasker',
);
$dust->run;
my @repeats = @{$dust->output};
=head1 DESCRIPTION
Dust is a wrapper for the NCBI dustmasker program which runs the dust
algorithm to identify and mask simple repeats.
=cut
package Bio::EnsEMBL::Analysis::Runnable::DustMasker;
use strict;
use warnings;
use Bio::EnsEMBL::Analysis::Runnable;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::Argument qw( rearrange );
use vars qw(@ISA);
@ISA = qw(Bio::EnsEMBL::Analysis::Runnable);
=head2 new
Arg [1] : Bio::EnsEMBL::Analysis::Runnable::DustMasker
Arg [2] : int, level
Arg [3] : int, linker
Arg [4] : int, window size
Arg [5] : int, split length
Function : create a new Bio::EnsEMBL::Analysis::Runnable::DustMasker
Returntype: Bio::EnsEMBL::Analysis::Runnable::DustMasker
Exceptions:
Example :
=cut
sub new {
my ($class,@args) = @_;
my $self = $class->SUPER::new(@args);
my ($level, $linker, $window_size, $split_length) =
rearrange(['LEVEL', 'LINKER', 'WINDOW_SIZE', 'SPLIT_LENGTH',], @args);
$self->program('dustmasker') if (!$self->program);
$self->level($level) if ($level);
$self->linker($linker) if ($linker);
$self->window_size($window_size) if ($window_size);
$split_length = 50000 unless defined $split_length;
$self->split_length($split_length);
return $self;
}
sub level {
my $self = shift;
$self->{'level'} = shift if (@_);
return $self->{'level'};
}
sub linker {
my $self = shift;
$self->{'linker'} = shift if (@_);
return $self->{'linker'};
}
sub window_size {
my $self = shift;
$self->{'window_size'} = shift if (@_);
return $self->{'window_size'};
}
sub split_length {
my $self = shift;
$self->{'split_length'} = shift if (@_);
return $self->{'split_length'};
}
=head2 run_analysis
Arg [1] : Bio::EnsEMBL::Analysis::Runnable::DustMasker
Arg [2] : string, program name
Function : constructs a commandline and runs the program passed
in, the generic method in Runnable isnt used as Dust doesnt
fit this module
Returntype: none
Exceptions: throws if run failed because system doesnt
return 0
Example :
=cut
sub run_analysis {
my ($self, $program) = @_;
if (!$program) {
$program = $self->program;
}
throw($program." is not executable Dust::run_analysis ")
unless($program && -x $program);
my $command = $self->program;
my $options = "";
$options .= " -level ".$self->level if ($self->level);
$options .= " -linker ".$self->linker if ($self->linker);
$options .= " -window ".$self->window_size if ($self->window_size);
$self->options($options);
$command .= "$options -in ".$self->queryfile." -out ".$self->resultsfile;
system($command) == 0 or throw("FAILED to run ".$command);
}
=head2 parse_results
Arg [1] : Bio::EnsEMBL::Analysis::Runnable::DustMasker
Arg [2] : string, filename
Function : open and parse the results file into repeat features
Returntype: none
Exceptions: throws on failure to open or close output file
Example :
=cut
sub parse_results{
my ($self, $results) = @_;
if(!$results){
$results = $self->resultsfile;
}
my $ff = $self->feature_factory;
my @output;
open(DUST, $results) or throw("FAILED to open ".$results);
LINE: while(<DUST>) {
next LINE if (/^>/);
if (/(\d+)\s\-\s(\d+)/) {
my ($start, $end) = ($1, $2);
# Dust results have 0-based start and end co-ordinates.
$start++;
$end++;
my $rc = $ff->create_repeat_consensus('dust', 'dust', 'simple', 'N');
my $rf = $ff->create_repeat_feature(
$start, $end, 0, 0, $start, $end, $rc, $self->query->name, $self->query);
if ($rf->length > $self->split_length) {
my $converted_features = $self->convert_feature($rf);
push(@output, @$converted_features) if ($converted_features);
} else {
push(@output, $rf);
}
}
}
$self->output(\@output);
close(DUST) or throw("FAILED to close ".$results);
}
sub convert_feature {
my ($self, $rf) = @_;
my $ff = $self->feature_factory;
my $projections = $rf->project('seqlevel');
my @converted;
my $feature_length = $rf->length;
my $projected_length = 0;
PROJECT:foreach my $projection (@$projections) {
$projected_length += ($projection->from_end - $projection->from_start) +1;
}
my $percentage = 100;
if($projected_length != 0) {
$percentage = ($projected_length / $feature_length)*100;
}
if($percentage <= 75){
return;
}
REPEAT:foreach my $projection (@$projections) {
my $start = 1;
my $end = $projection->to_Slice->length;
my $slice = $projection->to_Slice;
my $rc = $ff->create_repeat_consensus('dust', 'dust', 'simple', 'N');
my $rf = $ff->create_repeat_feature($start, $end, 0, 0, $start,
$end, $rc, $slice->name,
$slice);
my $transformed = $rf->transform($self->query->coord_system->name,
$self->query->coord_system->version);
if (!$transformed) {
$self->throw("Failed to transform Dust region".
$rf->seq_region_name.":".$rf->start."-".$rf->end);
} else {
$self->warning("Transformed Dust region".
$rf->seq_region_name.":".$rf->start."-".$rf->end);
}
push(@converted, $transformed);
}
return \@converted;
}
| navygit/ncRNA_Pipeline | modules/Bio/EnsEMBL/Analysis/Runnable/DustMasker.pm | Perl | apache-2.0 | 6,532 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V10::Services::ReachPlanService::Targeting;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
ageRange => $args->{ageRange},
devices => $args->{devices},
genders => $args->{genders},
network => $args->{network},
plannableLocationId => $args->{plannableLocationId}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V10/Services/ReachPlanService/Targeting.pm | Perl | apache-2.0 | 1,242 |
package VMOMI::BoolOption;
use parent 'VMOMI::OptionType';
use strict;
use warnings;
our @class_ancestors = (
'OptionType',
'DynamicData',
);
our @class_members = (
['supported', 'boolean', 0, ],
['defaultValue', 'boolean', 0, ],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/BoolOption.pm | Perl | apache-2.0 | 471 |
#!/opt/local/bin/perl
my %q ;
my $file = $ARGV[0]; # 'queryCount.txt';
open FILE, $file ;
foreach $line ( <FILE> ) {
($val, $query) = ($line =~ /^(\d+)\s+(.*)$/);
$query =~ s/(\d+)/D/g;
$q{$query} = $q{$query} + $val ;
}
foreach $key (keys %q ) {
print $q{$key}, "\t$key\n";
}
__END__
#!/opt/local/bin/perl
#
#my %q ;
#open FILE, $file ;
#
##@file = <FILE>;
#foreach $line ( <FILE> ) {
#
# ($val, $query) = ($line =~ /^(\d+)\s+(.*)$/);
#
# $query =~ s/(\d+)/D/g;
#
# $q{$query} = $q{$query} + $val ;
# }
#
# foreach $key (keys %q ) {
# print $q{$key}, "\t$key\n";
# }
#
| dkelsey/dtrace-live-SQL | total.pl | Perl | apache-2.0 | 619 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V10::Enums::ValueRuleGeoLocationMatchTypeEnum;
use strict;
use warnings;
use Const::Exporter enums => [
UNSPECIFIED => "UNSPECIFIED",
UNKNOWN => "UNKNOWN",
ANY => "ANY",
LOCATION_OF_PRESENCE => "LOCATION_OF_PRESENCE"
];
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V10/Enums/ValueRuleGeoLocationMatchTypeEnum.pm | Perl | apache-2.0 | 881 |
package Paws::SimpleWorkflow::RegisterDomain;
use Moose;
has Description => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'description' );
has Name => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'name' , required => 1);
has WorkflowExecutionRetentionPeriodInDays => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'workflowExecutionRetentionPeriodInDays' , required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'RegisterDomain');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::API::Response');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::SimpleWorkflow::RegisterDomain - Arguments for method RegisterDomain on Paws::SimpleWorkflow
=head1 DESCRIPTION
This class represents the parameters used for calling the method RegisterDomain on the
Amazon Simple Workflow Service service. Use the attributes of this class
as arguments to method RegisterDomain.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to RegisterDomain.
As an example:
$service_obj->RegisterDomain(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 Description => Str
A text description of the domain.
=head2 B<REQUIRED> Name => Str
Name of the domain to register. The name must be unique in the region
that the domain is registered in.
The specified string must not start or end with whitespace. It must not
contain a C<:> (colon), C</> (slash), C<|> (vertical bar), or any
control characters (C<\u0000-\u001f> | C<\u007f-\u009f>). Also, it must
not contain the literal string C<arn>.
=head2 B<REQUIRED> WorkflowExecutionRetentionPeriodInDays => Str
The duration (in days) that records and histories of workflow
executions on the domain should be kept by the service. After the
retention period, the workflow execution isn't available in the results
of visibility calls.
If you pass the value C<NONE> or C<0> (zero), then the workflow
execution history isn't retained. As soon as the workflow execution
completes, the execution record and its history are deleted.
The maximum workflow execution retention period is 90 days. For more
information about Amazon SWF service limits, see: Amazon SWF Service
Limits in the I<Amazon SWF Developer Guide>.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method RegisterDomain in L<Paws::SimpleWorkflow>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/SimpleWorkflow/RegisterDomain.pm | Perl | apache-2.0 | 3,001 |
package Moose::Exception::AutoDeRefNeedsArrayRefOrHashRef;
our $VERSION = '2.1404';
use Moose;
extends 'Moose::Exception';
with 'Moose::Exception::Role::InvalidAttributeOptions';
sub _build_message {
my $self = shift;
"You cannot auto-dereference anything other than a ArrayRef or HashRef on attribute (".$self->attribute_name.")";
}
1;
| ray66rus/vndrv | local/lib/perl5/x86_64-linux-thread-multi/Moose/Exception/AutoDeRefNeedsArrayRefOrHashRef.pm | Perl | apache-2.0 | 348 |
#!/usr/bin/perl -w
use strict;
use Text::Trie qw(Trie walkTrie);
print trie_compress( @ARGV );
sub trie_compress {
my ( @strings ) = @_;
my @trie = Trie( @strings );
my @compressed;
for my $entry ( @trie ) {
push @compressed, trie_to_text( $entry );
}
my $results;
if ( scalar @compressed > 1 ) { $results .= "{" };
$results .= join ",", @compressed;
if ( scalar @compressed > 1 ) { $results .= "}" };
return $results;
}
sub trie_to_text {
my ( $trie ) = @_;
my $text = "";
unless ( ref $trie eq "ARRAY" ) {
return $trie;
}
my @subtrie = @$trie;
my @nodes;
for my $idx ( 0 .. $#subtrie ) {
my $node = $subtrie[$idx];
if ( ref $node eq "ARRAY" ) {
push @nodes, trie_to_text( $node );
}
else {
push @nodes, $node;
}
}
$text .= shift @nodes;
if ( scalar @nodes > 1 ) { $text .= "{" };
$text .= join ",", sort @nodes;
if ( scalar @nodes > 1 ) { $text .= "}" };
return $text;
}
sub run_test_cases {
my @cases = (
{ 'strings' => [ qw( aabb aacc ) ],
'results' => "aa{bb,cc}",
},
{ 'strings' => [ qw( aabb aacc aad ) ],
'results' => "aa{bb,cc,d}",
},
{ 'strings' => [ qw( app-xy-02a app-xy-02b ) ],
'results' => "app-xy-02{a,b}",
},
{ 'strings' => [ qw( app-xy-02a app-zz-02b ) ],
'results' => "app-{xy-02a,zz-02b}",
},
{ 'strings' => [ qw( app-xy-02a app-xy-02b app-xy-03a app-xy-03b ) ],
'results' => "app-xy-0{2,3}{a,b}",
},
{ 'strings' => [ qw( app-xy-02a app-xy-02b app-xy-03a app-xy-03b app-xy-09 app-xy-10 ) ],
'results' => "app-xy-{0{2{a,b},3{a,b},9},10}",
},
{ 'strings' => [ qw( app-xy-02a cci-zz-app03 ) ],
'results' => "{app-xy-02a,cci-zz-app03}",
},
{ 'strings' => [ qw( xxbbcc yybbcc ) ],
'results' => "{xx,yy}bbcc",
},
{ 'strings' => [ qw( xxbbcc yybbcc zzbbcc ) ],
'results' => "{xx,yy,zz}bbcc",
},
{ 'strings' => [ qw( app-xy-02a app-zz-02a ) ],
'results' => "app-{xy,zz}-02a",
},
{ 'strings' => [ qw( htadiehtcjnr htheeehtcjnr ) ],
'results' => "ht{adi,hee}ehtcjnr",
},
);
for my $case ( @cases ) {
my $got = compress( @{ $case->{strings} } );
if ( $got eq $case->{results} ) {
print "OK\n";
}
else {
print "GOT: $got\n";
print "EXP: $case->{results}\n";
}
}
}
| gitpan/Compress-BraceExpansion | bin/trie-compress.pl | Perl | bsd-3-clause | 2,621 |
login mortal
run tests:
test('stringsecs.1', $mortal, 'think stringsecs(a)', '#-1 INVALID TIMESTRING');
test('stringsecs.2', $mortal, 'think stringsecs(10)', '10');
test('stringsecs.3', $mortal, 'think stringsecs(10s)', '10');
test('stringsecs.4', $mortal, 'think stringsecs(5m)', '300');
test('stringsecs.5', $mortal, 'think stringsecs(5m 10s)', '310');
test('stringsecs.6', $mortal, 'think stringsecs(1h)', '3600');
test('stringsecs.7', $mortal, 'think stringsecs(10s 5m)', '310');
test('stringsecs.8', $mortal, 'think stringsecs(1d 2h 3m 4s)', '93784');
test('stringsecs.9', $mortal
, 'think stringsecs(h)', '#-1 INVALID TIMESTRING');
| ccubed/MuDocker | Pennmush/Mu2Empty/Penn_Mu2/test/teststringsecs.pl | Perl | mit | 643 |
package Net::PMP;
use strict;
use warnings;
use Net::PMP::Client;
use Net::PMP::CollectionDoc;
our $VERSION = '0.004';
sub client {
my $class = shift;
return Net::PMP::Client->new_with_config(@_);
}
1;
__END__
=head1 NAME
Net::PMP - Perl SDK for the Public Media Platform
=head1 SYNOPSIS
use Net::PMP;
my $host = 'https://api-sandbox.pmp.io';
my $client_id = 'i-am-a-client';
my $client_secret = 'i-am-a-secret';
# instantiate a client
my $client = Net::PMP->client(
host => $host,
id => $client_id,
secret => $client_secret,
);
# search
my $search_results = $client->search({ tag => 'samplecontent', profile => 'story' });
my $results = $search_results->get_items();
printf( "total: %s\n", $results->total );
while ( my $r = $results->next ) {
printf( '%s: %s [%s]', $results->count, $r->get_uri, $r->get_title, ) );
}
=cut
=head1 DESCRIPTION
Net::PMP is a Perl client for the Public Media Platform API (http://docs.pmp.io/).
This class is mostly a namespace-holder and documentation, with one convenience method: client().
=head1 METHODS
=head2 client( I<args> )
Returns a new Net::PMP::Client object.
See L<Net::PMP::Client> new() method for I<args> details.
Note that new_with_config() is the actual method called, as a convenience
via L<MooseX::SimpleConfig>. You can define a config file in
$ENV{HOME}/.pmp.yaml (default) and it will be read automatically when
instantiating a Client. See L<MooseX::SimpleConfig> and L<Net::PMP::CLI> for
examples.
=head1 AUTHOR
Peter Karman, C<< <karman at cpan.org> >>
=head1 BUGS
Please report any bugs or feature requests to C<bug-net-pmp at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-PMP>. I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.
=head1 SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Net::PMP
You can also look for information at:
=over 4
=item * IRC
Join #pmp on L<http://freenode.net>.
=item * RT: CPAN's request tracker (report bugs here)
L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-PMP>
=item * AnnoCPAN: Annotated CPAN documentation
L<http://annocpan.org/dist/Net-PMP>
=item * CPAN Ratings
L<http://cpanratings.perl.org/d/Net-PMP>
=item * Search CPAN
L<http://search.cpan.org/dist/Net-PMP/>
=back
=head1 ACKNOWLEDGEMENTS
American Public Media and the Public Media Platform sponsored the development of this module.
=head1 LICENSE AND COPYRIGHT
Copyright 2013 American Public Media Group
See the LICENSE file that accompanies this module.
=cut
| gitpan/Net-PMP | lib/Net/PMP.pm | Perl | mit | 2,665 |
#!/usr/bin/env perl
#
#-------------------------------------------------------------------------------
# Copyright (c) 2014-2019 René Just, Darioush Jalali, and Defects4J contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROBIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#-------------------------------------------------------------------------------
=pod
=head1 NAME
get_relevant_tests.pl -- determine the set of relevant tests for a set of bugs of a given project.
=head1 SYNOPSIS
get_relevant_tests.pl -p project_id [-b bug_id] [-t tmp_dir] [-o out_dir]
=head1 OPTIONS
=over 4
=item -p C<project_id>
The id of the project for which the relevant tests are determined.
=item -b C<bug_id>
Only determine relevant tests for this bug id (optional). Format: C<\d+>
=item B<-t F<tmp_dir>>
The temporary root directory to be used to check out revisions (optional).
The default is F</tmp>.
=item B<-o F<out_dir>>
The output directory to be used (optional).
The default is F<relevant_tests> in Defects4J's project directory.
=back
=head1 DESCRIPTION
Determines the set of relevant tests for each bug (or a particular bug) of a
given project. The script stops as soon as an error occurs for any project version.
=cut
use warnings;
use strict;
use FindBin;
use File::Basename;
use Cwd qw(abs_path);
use Getopt::Std;
use Pod::Usage;
use lib abs_path("$FindBin::Bin/../core");
use Constants;
use Project;
#
# Process arguments and issue usage message if necessary.
#
my %cmd_opts;
getopts('p:b:t:o:', \%cmd_opts) or pod2usage(1);
pod2usage(1) unless defined $cmd_opts{p};
my $PID = $cmd_opts{p};
my $BID = $cmd_opts{b};
# Set up project
my $TMP_DIR = Utils::get_tmp_dir($cmd_opts{t});
system("mkdir -p $TMP_DIR");
my $project = Project::create_project($PID);
$project->{prog_root} = $TMP_DIR;
my $project_dir = "$PROJECTS_DIR/$PID";
my $out_dir = $cmd_opts{o} // "$project_dir/relevant_tests";
my @ids;
if (defined $BID) {
$BID =~ /^(\d+)$/ or die "Wrong bug_id format: $BID! Expected: \\d+";
@ids = ($BID);
} else {
@ids = $project->get_bug_ids();
}
foreach my $id (@ids) {
printf ("%4d: $project->{prog_name}\n", $id);
my $vid = "${id}f";
$project->checkout_vid($vid) or die "Could not checkout ${vid}";
$project->fix_tests($vid);
$project->compile() or die "Could not compile";
$project->compile_tests() or die "Could not compile tests";
# Hash all modified classes
my %mod_classes = ();
open(IN, "<${project_dir}/modified_classes/${id}.src") or die "Cannot read modified classes";
while(<IN>) {
chomp;
$mod_classes{$_} = 1;
}
close(IN);
# Result: list of relevant tests
my @relevant = ();
my $error = 0;
# Iterate over all tests and determine whether or not a test is relevant
my @all_tests = `cd $TMP_DIR && $SCRIPT_DIR/bin/defects4j export -ptests.all`;
foreach my $test (@all_tests) {
chomp($test);
print(STDERR "Analyze test: $test\n");
my $loaded = $project->monitor_test($test, $vid);
unless (defined $loaded) {
print(STDERR "Failed test: $test\n");
# Indicate error and skip all remaining tests
$error = 1;
last;
}
foreach my $class (@{$loaded->{src}}) {
if (defined $mod_classes{$class}) {
push(@relevant, $test);
# A test is relevant if it loads at least one of the modified
# classes!
last;
}
}
}
if ($error == 1) {
print(STDERR "Failed version: $id\n");
} else {
open(OUT, ">${out_dir}/${id}") or die "Cannot write relevant tests";
for (@relevant) {
print(OUT $_, "\n");
}
close(OUT);
}
}
# Clean up
system("rm -rf $TMP_DIR");
| rjust/defects4j | framework/util/get_relevant_tests.pl | Perl | mit | 4,801 |
package Google::Ads::AdWords::v201409::IncomeOperand;
use strict;
use warnings;
__PACKAGE__->_set_element_form_qualified(1);
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409' };
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use base qw(Google::Ads::AdWords::v201409::FunctionArgumentOperand);
# Variety: sequence
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %FunctionArgumentOperand__Type_of :ATTR(:get<FunctionArgumentOperand__Type>);
my %tier_of :ATTR(:get<tier>);
__PACKAGE__->_factory(
[ qw( FunctionArgumentOperand__Type
tier
) ],
{
'FunctionArgumentOperand__Type' => \%FunctionArgumentOperand__Type_of,
'tier' => \%tier_of,
},
{
'FunctionArgumentOperand__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'tier' => 'Google::Ads::AdWords::v201409::IncomeTier',
},
{
'FunctionArgumentOperand__Type' => 'FunctionArgumentOperand.Type',
'tier' => 'tier',
}
);
} # end BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201409::IncomeOperand
=head1 DESCRIPTION
Perl data type class for the XML Schema defined complexType
IncomeOperand from the namespace https://adwords.google.com/api/adwords/cm/v201409.
This operand specifies the income bracket a household falls under.
=head2 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=item * tier
=back
=head1 METHODS
=head2 new
Constructor. The following data structure may be passed to new():
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| gitpan/GOOGLE-ADWORDS-PERL-CLIENT | lib/Google/Ads/AdWords/v201409/IncomeOperand.pm | Perl | apache-2.0 | 1,762 |
#!/usr/bin/perl -w
#
# Copyright 2012, Google Inc. All Rights Reserved.
#
# 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.
#
# This example gets all campaigns. To add a campaign, run
# basic_operations/add_campaign.pl.
#
# Tags: CampaignService.get
# Author: David Torres <api.davidtorres@gmail.com>
use strict;
use lib "../../../lib";
use Google::Ads::AdWords::Client;
use Google::Ads::AdWords::Logging;
use Google::Ads::AdWords::v201406::OrderBy;
use Google::Ads::AdWords::v201406::Paging;
use Google::Ads::AdWords::v201406::Predicate;
use Google::Ads::AdWords::v201406::Selector;
use constant PAGE_SIZE => 500;
use Cwd qw(abs_path);
# Example main subroutine.
sub get_campaigns {
my $client = shift;
# Create selector.
my $paging = Google::Ads::AdWords::v201406::Paging->new({
startIndex => 0,
numberResults => PAGE_SIZE
});
my $selector = Google::Ads::AdWords::v201406::Selector->new({
fields => ["Id", "Name"],
ordering => [Google::Ads::AdWords::v201406::OrderBy->new({
field => "Name",
sortOrder => "ASCENDING"
})],
paging => $paging
});
# Paginate through results.
my $page;
do {
# Get all campaigns.
$page = $client->CampaignService()->get({serviceSelector => $selector});
# Display campaigns.
if ($page->get_entries()) {
foreach my $campaign (@{$page->get_entries()}) {
printf "Campaign with name \"%s\" and id \"%d\" was found.\n",
$campaign->get_name(), $campaign->get_id();
}
}
$paging->set_startIndex($paging->get_startIndex() + PAGE_SIZE);
} while ($paging->get_startIndex() < $page->get_totalNumEntries());
return 1;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Log SOAP XML request, response and API errors.
Google::Ads::AdWords::Logging::enable_all_logging();
# Get AdWords Client, credentials will be read from ~/adwords.properties.
my $client = Google::Ads::AdWords::Client->new({version => "v201406"});
# By default examples are set to die on any server returned fault.
$client->set_die_on_faults(1);
# Call the example
get_campaigns($client);
| gitpan/Google-Ads-AdWords-Client | examples/v201406/basic_operations/get_campaigns.pl | Perl | apache-2.0 | 2,660 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 8.0.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly. Use Unicode::UCD to access the Unicode character data
# base.
return <<'END';
V28
4352
4608
12334
12336
12593
12687
12800
12831
12896
12927
43360
43389
44032
55204
55216
55239
55243
55292
65440
65471
65474
65480
65482
65488
65490
65496
65498
65501
END
| operepo/ope | bin/usr/share/perl5/core_perl/unicore/lib/Sc/Hang.pl | Perl | mit | 656 |
#------------------------------------------------------------------------------
# File: NikonCapture.pm
#
# Description: Read/write Nikon Capture information
#
# Revisions: 11/08/2005 - P. Harvey Created
# 10/10/2008 - P. Harvey Updated for Capture NX 2
# 16/04/2011 - P. Harvey Decode NikonCaptureEditVersions
#
# References: 1) http://www.cybercom.net/~dcoffin/dcraw/
#------------------------------------------------------------------------------
package Image::ExifTool::NikonCapture;
use strict;
use vars qw($VERSION);
use Image::ExifTool qw(:DataAccess :Utils);
use Image::ExifTool::Exif;
$VERSION = '1.09';
sub ProcessNikonCapture($$$);
# common print conversions
my %offOn = ( 0 => 'Off', 1 => 'On' );
my %noYes = ( 0 => 'No', 1 => 'Yes' );
my %unsharpColor = (
0 => 'RGB',
1 => 'Red',
2 => 'Green',
3 => 'Blue',
4 => 'Yellow',
5 => 'Magenta',
6 => 'Cyan',
);
# Nikon Capture data (ref PH)
%Image::ExifTool::NikonCapture::Main = (
PROCESS_PROC => \&ProcessNikonCapture,
WRITE_PROC => \&WriteNikonCapture,
CHECK_PROC => \&Image::ExifTool::Exif::CheckExif,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
NOTES => q{
This information is written by the Nikon Capture software in tag 0x0e01 of
the maker notes of NEF images.
},
# 0x007ddc9d contains contrast information
0x008ae85e => {
Name => 'LCHEditor',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x0c89224b => {
Name => 'ColorAberrationControl',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x116fea21 => {
Name => 'HighlightData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::HighlightData',
},
},
0x2175eb78 => {
Name => 'D-LightingHQ',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x2fc08431 => {
Name => 'StraightenAngle',
Writable => 'double',
},
0x374233e0 => {
Name => 'CropData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::CropData',
},
},
0x39c456ac => {
Name => 'PictureCtrl',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::PictureCtrl',
},
},
0x3cfc73c6 => {
Name => 'RedEyeData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::RedEyeData',
},
},
0x3d136244 => {
Name => 'EditVersionName',
Writable => 'string', # (null terminated)
},
# 0x3e726567 added when I rotated by 90 degrees
0x56a54260 => {
Name => 'Exposure',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::Exposure',
},
},
0x5f0e7d23 => {
Name => 'ColorBooster',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x6a6e36b6 => {
Name => 'D-LightingHQSelected',
Writable => 'int8u',
PrintConv => \%noYes,
},
0x753dcbc0 => {
Name => 'NoiseReduction',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x76a43200 => {
Name => 'UnsharpMask',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x76a43201 => {
Name => 'Curves',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x76a43202 => {
Name => 'ColorBalanceAdj',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x76a43203 => {
Name => 'AdvancedRaw',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x76a43204 => {
Name => 'WhiteBalanceAdj',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x76a43205 => {
Name => 'VignetteControl',
Writable => 'int8u',
PrintConv => \%offOn,
},
0x76a43206 => {
Name => 'FlipHorizontal',
Writable => 'int8u',
PrintConv => \%noYes,
},
0x76a43207 => { # rotation angle in degrees
Name => 'Rotation',
Writable => 'int16u',
},
0x083a1a25 => {
Name => 'HistogramXML',
Writable => 'undef',
Binary => 1,
AdjustSize => 4, # patch Nikon bug
},
0x84589434 => {
Name => 'BrightnessData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::Brightness',
},
},
0x890ff591 => {
Name => 'D-LightingHQData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::DLightingHQ',
},
},
0x926f13e0 => {
Name => 'NoiseReductionData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::NoiseReduction',
},
},
0x9ef5f6e0 => {
Name => 'IPTCData',
SubDirectory => {
TagTable => 'Image::ExifTool::IPTC::Main',
},
},
# 0xa7264a72, 0x88f55e48 and 0x416391c6 all change from 0 to 1 when QuickFix is turned on
0xab5eca5e => {
Name => 'PhotoEffects',
Writable => 'int8u',
PrintConv => \%offOn,
},
0xac6bd5c0 => {
Name => 'VignetteControlIntensity',
Writable => 'int16s',
},
0xb0384e1e => {
Name => 'PhotoEffectsData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::PhotoEffects',
},
},
0xb999a36f => {
Name => 'ColorBoostData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::ColorBoost',
},
},
0xbf3c6c20 => {
Name => 'WBAdjData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::WBAdjData',
},
},
0xce5554aa => {
Name => 'D-LightingHS',
Writable => 'int8u',
PrintConv => \%offOn,
},
0xe2173c47 => {
Name => 'PictureControl',
Writable => 'int8u',
PrintConv => \%offOn,
},
0xe37b4337 => {
Name => 'D-LightingHSData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::DLightingHS',
},
},
0xe42b5161 => {
Name => 'UnsharpData',
SubDirectory => {
TagTable => 'Image::ExifTool::NikonCapture::UnsharpData',
},
},
0xe9651831 => {
Name => 'PhotoEffectHistoryXML',
Binary => 1,
Writable => 'undef',
},
0xfe28a44f => {
Name => 'AutoRedEye',
Writable => 'int8u',
PrintConv => \%offOn, # (have seen a value of 28 here for older software?)
},
0xfe443a45 => {
Name => 'ImageDustOff',
Writable => 'int8u',
PrintConv => \%offOn,
},
);
%Image::ExifTool::NikonCapture::UnsharpData = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => 'UnsharpCount',
19 => { Name => 'Unsharp1Color', Format => 'int16u', PrintConv => \%unsharpColor },
23 => { Name => 'Unsharp1Intensity', Format => 'int16u' },
25 => { Name => 'Unsharp1HaloWidth', Format => 'int16u' },
27 => 'Unsharp1Threshold',
46 => { Name => 'Unsharp2Color', Format => 'int16u', PrintConv => \%unsharpColor },
50 => { Name => 'Unsharp2Intensity', Format => 'int16u' },
52 => { Name => 'Unsharp2HaloWidth', Format => 'int16u' },
54 => 'Unsharp2Threshold',
73 => { Name => 'Unsharp3Color', Format => 'int16u', PrintConv => \%unsharpColor },
77 => { Name => 'Unsharp3Intensity', Format => 'int16u' },
79 => { Name => 'Unsharp3HaloWidth', Format => 'int16u' },
81 => 'Unsharp3Threshold',
100 => { Name => 'Unsharp4Color', Format => 'int16u', PrintConv => \%unsharpColor },
104 => { Name => 'Unsharp4Intensity', Format => 'int16u' },
106 => { Name => 'Unsharp4HaloWidth', Format => 'int16u' },
108 => 'Unsharp4Threshold',
# there could be more, but I grow bored of this... :P
);
%Image::ExifTool::NikonCapture::DLightingHS = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int32u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => 'D-LightingHSAdjustment',
1 => 'D-LightingHSColorBoost',
);
%Image::ExifTool::NikonCapture::DLightingHQ = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int32u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => 'D-LightingHQShadow',
1 => 'D-LightingHQHighlight',
2 => 'D-LightingHQColorBoost',
);
%Image::ExifTool::NikonCapture::ColorBoost = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => {
Name => 'ColorBoostType',
PrintConv => {
0 => 'Nature',
1 => 'People',
},
},
1 => {
Name => 'ColorBoostLevel',
Format => 'int32u',
},
);
%Image::ExifTool::NikonCapture::WBAdjData = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0x00 => {
Name => 'WBAdjRedBalance',
Format => 'double',
},
0x08 => {
Name => 'WBAdjBlueBalance',
Format => 'double',
},
0x10 => {
Name => 'WBAdjMode',
PrintConv => {
1 => 'Use Gray Point',
2 => 'Recorded Value',
3 => 'Use Temperature',
4 => 'Calculate Automatically'
},
},
0x14 => {
Name => 'WBAdjLightingSubtype',
# this varies for different lighting types
# (ie. for Daylight, this is 0 => 'Direct', 1 => 'Shade', 2 => 'Cloudy')
},
0x15 => {
Name => 'WBAdjLighting',
PrintConv => {
0 => 'None',
1 => 'Incandescent',
2 => 'Daylight',
3 => 'Standard Fluorescent',
4 => 'High Color Rendering Fluorescent',
5 => 'Flash',
},
},
0x18 => {
Name => 'WBAdjTemperature',
Format => 'int16u',
},
0x25 => {
Name => 'WBAdjTint',
Format => 'int32s',
},
);
%Image::ExifTool::NikonCapture::PhotoEffects = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => {
Name => 'PhotoEffectsType',
PrintConv => {
0 => 'None',
1 => 'B&W',
2 => 'Sepia',
3 => 'Tinted',
},
},
4 => {
Name => 'PhotoEffectsRed',
Format => 'int16s',
},
6 => {
Name => 'PhotoEffectsGreen',
Format => 'int16s',
},
8 => {
Name => 'PhotoEffectsBlue',
Format => 'int16s',
},
);
%Image::ExifTool::NikonCapture::Brightness = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => {
Name => 'BrightnessAdj',
Format => 'double',
ValueConv => '$val * 50',
ValueConvInv => '$val / 50',
},
8 => {
Name => 'EnhanceDarkTones',
PrintConv => \%offOn,
},
);
%Image::ExifTool::NikonCapture::NoiseReduction = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0x04 => {
Name => 'EdgeNoiseReduction',
PrintConv => \%offOn,
},
0x05 => {
Name => 'ColorMoireReductionMode',
PrintConv => {
0 => 'Off',
1 => 'Low',
2 => 'Medium',
3 => 'High',
},
},
0x09 => {
Name => 'NoiseReductionIntensity',
Format => 'int32u',
},
0x0d => {
Name => 'NoiseReductionSharpness',
Format => 'int32u',
},
0x11 => {
Name => 'NoiseReductionMethod',
Format => 'int16u',
PrintConv => {
0 => 'Faster',
1 => 'Better Quality',
},
},
0x15 => {
Name => 'ColorMoireReduction',
PrintConv => \%offOn,
},
0x17 => {
Name => 'NoiseReduction',
PrintConv => \%offOn,
},
0x18 => {
Name => 'ColorNoiseReductionIntensity',
Format => 'int32u',
},
0x1c => {
Name => 'ColorNoiseReductionSharpness',
Format => 'int32u',
},
);
%Image::ExifTool::NikonCapture::CropData = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0x1e => {
Name => 'CropLeft',
Format => 'double',
ValueConv => '$val / 2',
ValueConvInv => '$val * 2',
},
0x26 => {
Name => 'CropTop',
Format => 'double',
ValueConv => '$val / 2',
ValueConvInv => '$val * 2',
},
0x2e => {
Name => 'CropRight',
Format => 'double',
ValueConv => '$val / 2',
ValueConvInv => '$val * 2',
},
0x36 => {
Name => 'CropBottom',
Format => 'double',
ValueConv => '$val / 2',
ValueConvInv => '$val * 2',
},
0x8e => {
Name => 'CropOutputWidthInches',
Format => 'double',
},
0x96 => {
Name => 'CropOutputHeightInches',
Format => 'double',
},
0x9e => {
Name => 'CropScaledResolution',
Format => 'double',
},
0xae => {
Name => 'CropSourceResolution',
Format => 'double',
ValueConv => '$val / 2',
ValueConvInv => '$val * 2',
},
0xb6 => {
Name => 'CropOutputResolution',
Format => 'double',
},
0xbe => {
Name => 'CropOutputScale',
Format => 'double',
},
0xc6 => {
Name => 'CropOutputWidth',
Format => 'double',
},
0xce => {
Name => 'CropOutputHeight',
Format => 'double',
},
0xd6 => {
Name => 'CropOutputPixels',
Format => 'double',
},
);
%Image::ExifTool::NikonCapture::PictureCtrl = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0x00 => {
Name => 'PictureControlActive',
PrintConv => \%offOn,
},
0x13 => {
Name => 'PictureControlMode',
Format => 'string[16]',
},
# 0x29 changes with Hue and Sharpening
0x2a => {
Name => 'QuickAdjust',
ValueConv => '$val - 128',
ValueConvInv => '$val + 128',
},
0x2b => {
Name => 'SharpeningAdj',
ValueConv => '$val ? $val - 128 : "Auto"',
ValueConvInv => '$val=~/\d/ ? $val + 128 : 0',
},
0x2c => {
Name => 'ContrastAdj',
ValueConv => '$val ? $val - 128 : "Auto"',
ValueConvInv => '$val=~/\d/ ? $val + 128 : 0',
},
0x2d => {
Name => 'BrightnessAdj',
ValueConv => '$val ? $val - 128 : "Auto"', # no "Auto" mode (yet) for this setting
ValueConvInv => '$val=~/\d/ ? $val + 128 : 0',
},
0x2e => {
Name => 'SaturationAdj',
ValueConv => '$val ? $val - 128 : "Auto"',
ValueConvInv => '$val=~/\d/ ? $val + 128 : 0',
},
0x2f => {
Name => 'HueAdj',
ValueConv => '$val - 128',
ValueConvInv => '$val + 128',
},
# 0x37 changed from 0 to 2 when Picture Control is enabled (and no active DLighting)
);
%Image::ExifTool::NikonCapture::RedEyeData = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => {
Name => 'RedEyeCorrection',
PrintConv => {
0 => 'Off',
1 => 'Automatic',
2 => 'Click on Eyes',
},
},
);
%Image::ExifTool::NikonCapture::Exposure = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0x00 => {
Name => 'ExposureAdj',
Format => 'int16s',
ValueConv => '$val / 100',
ValueConvInv => '$val * 100',
},
0x12 => {
Name => 'ExposureAdj2',
Format => 'double',
PrintConv => 'sprintf("%.4f", $val)',
PrintConvInv => '$val',
},
0x24 => {
Name => 'ActiveD-Lighting',
PrintConv => \%offOn,
},
0x25 => {
Name => 'ActiveD-LightingMode',
PrintConv => {
0 => 'Unchanged',
1 => 'Off',
2 => 'Low',
3 => 'Normal',
4 => 'High',
6 => 'Extra High',
},
},
);
%Image::ExifTool::NikonCapture::HighlightData = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int8s',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => 'ShadowProtection',
1 => 'SaturationAdj',
6 => 'HighlightProtection',
);
#------------------------------------------------------------------------------
# write Nikon Capture data (ref 1)
# Inputs: 0) ExifTool object reference, 1) reference to directory information
# 2) pointer to tag table
# Returns: 1 on success
sub WriteNikonCapture($$$)
{
my ($exifTool, $dirInfo, $tagTablePtr) = @_;
$exifTool or return 1; # allow dummy access to autoload this package
# no need to edit this information unless necessary
unless ($exifTool->{EDIT_DIRS}->{MakerNotes} or $exifTool->{EDIT_DIRS}->{IPTC}) {
return undef;
}
my $dataPt = $$dirInfo{DataPt};
my $dirStart = $$dirInfo{DirStart};
my $dirLen = $$dirInfo{DirLen};
if ($dirLen < 22) {
$exifTool->Warn('Short Nikon Capture Data',1);
return undef;
}
# make sure the capture data is properly contained
SetByteOrder('II');
my $tagID = Get32u($dataPt, $dirStart);
# sometimes size includes 18 header bytes, and other times it doesn't (ie. ViewNX 2.1.1)
my $size = Get32u($dataPt, $dirStart + 18);
my $pad = $dirLen - $size - 18;
unless ($tagID == 0x7a86a940 and ($pad >= 0 or $pad == -18)) {
$exifTool->Warn('Unrecognized Nikon Capture Data header');
return undef;
}
# determine if there is any data after this block
if ($pad > 0) {
$pad = substr($$dataPt, $dirStart + 18 + $size, $pad);
$dirLen = $size + 18;
} else {
$pad = '';
}
my $outBuff = '';
my $pos;
my $newTags = $exifTool->GetNewTagInfoHash($tagTablePtr);
my $dirEnd = $dirStart + $dirLen;
# loop through all entries in the Nikon Capture data
for ($pos=$dirStart+22; $pos+22<$dirEnd; $pos+=22+$size) {
$tagID = Get32u($dataPt, $pos);
$size = Get32u($dataPt, $pos + 18) - 4;
last if $size < 0 or $pos + 22 + $size > $dirEnd;
my $tagInfo = $exifTool->GetTagInfo($tagTablePtr, $tagID);
if ($tagInfo) {
my $newVal;
if ($$tagInfo{SubDirectory}) {
# rewrite the subdirectory
my %subdirInfo = (
DataPt => $dataPt,
DirStart => $pos + 22,
DirLen => $size,
);
my $subTable = GetTagTable($tagInfo->{SubDirectory}->{TagTable});
# ignore minor errors in IPTC since there is typically trailing garbage
my $oldSetting = $exifTool->Options('IgnoreMinorErrors');
$$tagInfo{Name} =~ /IPTC/ and $exifTool->Options(IgnoreMinorErrors => 1);
# rewrite the directory
$newVal = $exifTool->WriteDirectory(\%subdirInfo, $subTable);
# restore our original options
$exifTool->Options(IgnoreMinorErrors => $oldSetting);
} elsif ($$newTags{$tagID}) {
# get new value for this tag if we are writing it
my $format = $$tagInfo{Format} || $$tagInfo{Writable};
my $oldVal = ReadValue($dataPt,$pos+22,$format,1,$size);
my $nvHash = $exifTool->GetNewValueHash($tagInfo);
if ($exifTool->IsOverwriting($nvHash, $oldVal)) {
my $val = $exifTool->GetNewValues($tagInfo);
$newVal = WriteValue($val, $$tagInfo{Writable}) if defined $val;
if (defined $newVal and length $newVal) {
++$exifTool->{CHANGED};
} else {
undef $newVal;
$exifTool->Warn("Can't delete $$tagInfo{Name}");
}
}
}
if (defined $newVal) {
next unless length $newVal; # don't write zero length information
# write the new value
$outBuff .= substr($$dataPt, $pos, 18);
$outBuff .= Set32u(length($newVal) + 4);
$outBuff .= $newVal;
next;
}
}
# rewrite the existing information
$outBuff .= substr($$dataPt, $pos, 22 + $size);
}
unless ($pos == $dirEnd) {
if ($pos == $dirEnd - 4) {
# it seems that sometimes (NX2) the main block size is wrong by 4 bytes
# (did they forget to include the size word?)
$outBuff .= substr($$dataPt, $pos, 4);
} else {
$exifTool->Warn('Nikon Capture Data improperly terminated',1);
return undef;
}
}
# add the header and return the new directory
return substr($$dataPt, $dirStart, 18) .
Set32u(length($outBuff) + 4) .
$outBuff . $pad;
}
#------------------------------------------------------------------------------
# process Nikon Capture data (ref 1)
# Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref
# Returns: 1 on success
sub ProcessNikonCaptureEditVersions($$$)
{
my ($exifTool, $dirInfo, $tagTablePtr) = @_;
my $dataPt = $$dirInfo{DataPt};
my $dirStart = $$dirInfo{DirStart};
my $dirLen = $$dirInfo{DirLen};
my $dirEnd = $dirStart + $dirLen;
my $verbose = $exifTool->Options('Verbose');
SetByteOrder('II');
return 0 unless $dirLen > 4;
my $num = Get32u($dataPt, $dirStart);
my $pos = $dirStart + 4;
$verbose and $exifTool->VerboseDir('NikonCaptureEditVersions', $num);
while ($num) {
last if $pos + 4 > $dirEnd;
my $len = Get32u($dataPt, $pos);
last if $pos + $len + 4 > $dirEnd;
my %dirInfo = (
DirName => 'NikonCapture',
Parent => 'NikonCaptureEditVersions',
DataPt => $dataPt,
DirStart => $pos + 4,
DirLen => $len,
);
$$exifTool{DOC_NUM} = ++$$exifTool{DOC_COUNT};
$exifTool->ProcessDirectory(\%dirInfo, $tagTablePtr);
--$num;
$pos += $len + 4;
}
delete $$exifTool{DOC_NUM};
return 1;
}
#------------------------------------------------------------------------------
# process Nikon Capture data (ref 1)
# Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref
# Returns: 1 on success
sub ProcessNikonCapture($$$)
{
my ($exifTool, $dirInfo, $tagTablePtr) = @_;
my $dataPt = $$dirInfo{DataPt};
my $dirStart = $$dirInfo{DirStart};
my $dirLen = $$dirInfo{DirLen};
my $dirEnd = $dirStart + $dirLen;
my $verbose = $exifTool->Options('Verbose');
my $success = 0;
SetByteOrder('II');
$verbose and $exifTool->VerboseDir('NikonCapture', 0, $dirLen);
my $pos;
for ($pos=$dirStart+22; $pos+22<$dirEnd; ) {
my $tagID = Get32u($dataPt, $pos);
my $size = Get32u($dataPt, $pos + 18) - 4;
$pos += 22;
last if $size < 0 or $pos + $size > $dirEnd;
my $tagInfo = $exifTool->GetTagInfo($tagTablePtr, $tagID);
if ($tagInfo or $verbose) {
my ($format, $value);
# (note that Writable will be 0 for Unknown tags)
$tagInfo and $format = ($$tagInfo{Format} || $$tagInfo{Writable});
# generate a reasonable default format type for short values
if (not $format and ($size == 1 or $size == 2 or $size == 4)) {
$format = 'int' . ($size * 8) . 'u';
}
if ($format) {
my $count = 1;
if ($format eq 'string' or $format eq 'undef') {
# patch Nikon bug in size of some values (HistogramXML)
$size += $$tagInfo{AdjustSize} if $tagInfo and $$tagInfo{AdjustSize};
$count = $size;
}
$value = ReadValue($dataPt,$pos,$format,$count,$size);
} elsif ($size == 1) {
$value = substr($$dataPt, $pos, $size);
}
$exifTool->HandleTag($tagTablePtr, $tagID, $value,
DataPt => $dataPt,
Start => $pos,
Size => $size,
) and $success = 1;
}
$pos += $size;
}
return $success;
}
1; # end
__END__
=head1 NAME
Image::ExifTool::NikonCapture - Read/write Nikon Capture information
=head1 SYNOPSIS
This module is loaded automatically by Image::ExifTool when required.
=head1 DESCRIPTION
This module contains routines to read and write Nikon Capture information in
the maker notes of NEF images.
=head1 AUTHOR
Copyright 2003-2013, Phil Harvey (phil at owl.phy.queensu.ca)
This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=head1 REFERENCES
=over 4
=item L<http://www.cybercom.net/~dcoffin/dcraw/>
=back
=head1 SEE ALSO
L<Image::ExifTool::TagNames/NikonCapture Tags>,
L<Image::ExifTool::TagNames/Nikon Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>
=cut
| wilg/mini_exiftool_vendored | vendor/Image-ExifTool-9.27/lib/Image/ExifTool/NikonCapture.pm | Perl | mit | 27,654 |
#!/usr/bin/perl
use warnings;
use strict;
use Test::More;
my $rc = 0;
$rc = plan tests => 1;
diag("Returned: " . sprintf("%d", $rc));
$rc = ok(1);
diag("Returned: $rc");
| pozorvlak/libtap | tests/plan/sane/test.pl | Perl | bsd-2-clause | 175 |
#!/usr/bin/perl -w
#
# The MIT License (MIT)
#
# Copyright (c) 2016 Michael J. Wouters
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# 2016-05-02 MJW First version. A minimal script
# 2016-08-18 MJW Generate missing RINEX
use POSIX;
use Getopt::Std;
use TFLibrary;
use vars qw($opt_a $opt_c $opt_d $opt_h $opt_v $opt_x);
$VERSION="0.1.1";
$AUTHORS="Michael Wouters";
$MAX_AGE=7; # number of days to look backwards for missing files
# Check command line
if ($0=~m#^(.*/)#) {$path=$1} else {$path="./"} # read path info
$0=~s#.*/##; # then strip it
$home=$ENV{HOME};
if (-d "$home/etc") {
$configPath="$home/etc";
}
else{
ErrorExit("No ~/etc directory found!\n");
}
if (!(getopts('a:c:dhvx')) || $opt_h){
&ShowHelp();
exit;
}
if ($opt_v){
print "$0 version $VERSION\n";
print "Written by $AUTHORS\n";
exit;
}
if (-d "$home/bin") {
$binPath="$home/bin";
}
else{
ErrorExit("No ~/bin directory found!\n");
}
$configFile=$configPath."/gpscv.conf";
if ($opt_c){
$configFile=$opt_c;
}
if (!(-e $configFile)){
ErrorExit("The configuration file $configFile was not found!\n");
}
$maxAge = $MAX_AGE;
if (defined $opt_a){
$maxAge=$opt_a;
}
$mjdPrev = int(time()/86400 + 40587-1); # yesterday
$mjdStart = $mjdStop= $mjdPrev;
if ($#ARGV == -1){
# process previous day
}
elsif ($#ARGV == 0){
$mjdStart = $ARGV[0];
$mjdStop = $mjdStart;
}
elsif ($#ARGV == 1){
$mjdStart = $ARGV[0];
$mjdStop = $ARGV[1];
}
else{
ShowHelp();
exit;
}
if (!$opt_x){
for ($mjd=$mjdStart;$mjd <= $mjdStop;$mjd++){
Debug("Processing $mjd");
`$binPath/mktimetx --configuration $configFile -m $mjd`;
}
}
else{
%Init = &TFMakeHash2($configFile,(tolower=>1));
# Check we got the info we need from the config file
@check=("cggtts:create","cggtts:outputs","cggtts:naming convention",
"counter:file extension","paths:counter data",
"receiver:file extension","paths:receiver data"
);
foreach (@check) {
$tag=$_;
$tag=~tr/A-Z/a-z/;
unless (defined $Init{$tag}) {ErrorExit("No entry for $_ found in $configFile")}
}
$ctrExt = $Init{"counter:file extension"};
if (!($ctrExt =~ /^\./)){ # do we need a period ?
$ctrExt = ".".$ctrExt;
}
$ctrDataPath = TFMakeAbsolutePath($Init{"paths:counter data"},$home);
if (!($Init{"receiver:file extension"} =~ /^\./)){ # do we need a period ?
$rxExt = ".".$Init{"receiver:file extension"};
}
$rxDataPath = TFMakeAbsolutePath($Init{"paths:receiver data"},$home);
$createRINEX=lc($Init{"rinex:create"}) eq 'yes';
$rnxDataPath="";
if ($createRINEX){
$rnxDataPath= TFMakeAbsolutePath($Init{"paths:rinex"},$home);
}
if (lc($Init{"cggtts:create"}) eq 'yes'){
# Just search within the last 7 days for missed processing
for ($mjd=$mjdPrev-$maxAge;$mjd<=$mjdPrev;$mjd++){
Debug("Checking $mjd");
# If there is a missing raw data file, then just skip
$f = $ctrDataPath.$mjd.$ctrExt;
if (!(-e $f || -e "$f.gz")){
Debug("$f is missing - skipping");
next;
}
$f = $rxDataPath.$mjd.$rxExt;
if (!(-e $f || -e "$f.gz")){
Debug("$f is missing - skipping");
next;
}
# Look for missing CGGTTS files
@outputs=split /,/,$Init{"cggtts:outputs"};
foreach (@outputs)
{
$output = lc $_;
$output=~ s/^\s+//;
$output=~ s/\s+$//;
Debug("\tchecking CGGTTS output $output");
$cggttsPath = TFMakeAbsolutePath($Init{"$output:path"},$home);
if (lc($Init{"cggtts:naming convention"}) eq "plain"){
$cggttsFile = $cggttsPath.$mjd.".cctf";
}
elsif (lc($Init{"cggtts:naming convention"}) eq "bipm"){
$c=lc $Init{"$output:constellation"};
if ( $c eq 'gps'){
$constellation='G';
}
elsif ($c eq 'glonass'){
$constellation='R';
}
$ext = sprintf "%2d.%03d",int ($mjd/1000),$mjd - (int $mjd/1000)*1000;
$cggttsFile = $cggttsPath.$constellation."M".$Init{"cggtts:lab id"}.$Init{"cggtts:receiver id"}.$ext;
}
Debug("\tchecking $cggttsFile");
if (!(-e $cggttsFile)){ # only attempt to regenerate missing files
Debug("\t-->missing");
Debug("\t-->processing $mjd");
`$binPath/mktimetx --configuration $configFile -m $mjd`;
}
else{
Debug("\t-->exists");
}
}
# Look for missing RINEX files
# TODO this will regenerate CGGTTS files
next unless ($createRINEX);
# Convert MJD to YY and DOY
$t=($mjd-40587)*86400.0;
@tod = gmtime($t);
$yy = $tod[5]-(int($tod[5]/100))*100;
$doy = $tod[7]+1;
$rnxFile = sprintf "%s%s%03d0.%02dO", $rnxDataPath,$Init{"antenna:marker name"},$doy,$yy;
$rnxFilegzip = $rnxFile.'.gz';
Debug("\tchecking $rnxFile(.gz)");
if (!(-e $rnxFile || -e $rnxFilegzip)){
Debug("\t-->missing");
Debug("\t-->processing $mjd");
`$binPath/mktimetx --configuration $configFile -m $mjd`;
}
else{
Debug("\t-->exists");
}
}
}
}
# End of main program
#-----------------------------------------------------------------------
sub ShowHelp
{
print "Usage: $0 [OPTION] ... [startMJD] [stopMJD]\n";
print "\t-a <num> maximum age of files to look for when reprocessing\n";
print " missing files, in days (default $MAX_AGE)\n";
print "\t-c <file> use the specified configuration file\n";
print "\t-d debug\n";
print "\t-h show this help\n";
print "\t-x run missed processing\n";
print "\t-v print version\n";
print "\nIf an MJD range is not specified, the previous day is processed\n";
}
#-----------------------------------------------------------------------
sub ErrorExit {
my $message=shift;
@_=gmtime(time());
printf "%02d/%02d/%02d %02d:%02d:%02d $message\n",
$_[3],$_[4]+1,$_[5]%100,$_[2],$_[1],$_[0];
exit;
}
# -------------------------------------------------------------------------
sub Debug
{
if ($opt_d){
printf STDERR "$_[0]\n";
}
} | openttp/openttp | software/gpscv/common/bin/runmktimetx.pl | Perl | mit | 6,811 |
#!/usr/bin/perl
require 'quickies.pl'
($User,$Planet,$AuthCode,$CityName,$TempMode)=split(/&/,$ENV{QUERY_STRING});
$PlanetDir = $MasterPath . "/se/Planets/$Planet";
$UserDir = "$PlanetDir/users/$User";
if (-e "$UserDir/Dead.txt") {
print "Location: http://www.bluewand.com/cgi-bin/classic/Dead.pl?$User&$Planet&$AuthCode\n\n";
die;
}
if (-e "$UserDir/dupe.txt") {
print "<SCRIPT>alert(\"Your nation has been locked down for security reasons. Please contact the Bluewand team at shattered.empires\@canada.com for details.\");history.back();</SCRIPT>";
die;
}
if (-e "$UserDir/notallowed.txt") {
print "<SCRIPT>alert(\"Your nation has been taken off-line temporarily. Please contact the Bluewand team for details.\");history.back();</SCRIPT>";
$flags = 1;
die;
}
print "Content-type: text/html\n\n";
$user_information = $MasterPath . "/User Information";
dbmopen(%authcode, "$user_information/accesscode", 0777);
if(($AuthCode ne $authcode{$User}) || ($AuthCode eq "")){
print "<SCRIPT>alert(\"Security Failure. Please notify the GSD team immediately.\");history.back();</SCRIPT>";
die;
}
dbmclose(%authcode);
$Header = "#333333";$HeaderFont = "#CCCCCC";$Sub = "#999999";$SubFont = "#000000";$Content = "#666666";$ContentFont = "#FFFFFF";
$BaseHealth = 2000000;
$BaseLearn = 1000000;
$FortificationCost = 5000000;
$CityNames = $CityName;
$CityName =~ tr/_/ /;
$CityPath = $MasterPath . "/se/Planets/$Planet/users/$User";
open (IN, "$CityPath/research/TechData.tk");
flock (IN, 1);
@TechData = <IN>;
close (IN);
&chopper (@TechData);
#Index Technologies
foreach $Tech (@TechData) {
(@TechInfo) = split(/\|/,$Tech);
# if ($User eq "Admin_One") {print qq!@TechInfo[2] >= @TechInfo[3]) {$Storage{@TechInfo[1]} = @TechInfo[1]!}
if (@TechInfo[2] >= @TechInfo[3]) {$Storage{@TechInfo[1]} = 1}
}
$Storage{""} = 1;
open (IN, "$CityPath/userinfo.txt") or print "Cannot open";
flock (IN, 1);
@Inf = <IN>;
close (IN);
&chopper (@Inf);
&Display2;
$SF = qq!<font face=verdana size=-1>!;
print qqÞ
<BODY BGCOLOR="#000000" text="#FFFFFF">$SF
<form method=POST action="http://www.bluewand.com/cgi-bin/classic/CityMod.pl?$User&$Planet&$AuthCode&$CityNames&1">
<table width=100% border=1 cellspacing=0 bgcolor="$Header"><TD><Font face=verdana size=-1><B><Center>$CityName Control</table>Þ;
if ($TempMode == 1) {
$LearnCost = 1000000;
$HealthCost = 2000000;
open (IN, "$CityPath/money.txt");
$Money = <IN>;
close (IN);
chop($Money);
open (IN, "$CityPath/City.txt");
@Cities = <IN>;
close (IN);
&chopper (@Cities);
open (OUT, ">$CityPath/City.txt") or print "Cannot Write<BR>";
&parse_form;
foreach $City (@Cities) {
($Name,$Population,$Status,$BorderLevel,$Acceptance,$Feature,$Hospitals,$Barracks,$Agriculture,$Ag,$Commercial,$Co,$Industrial,$In,$Residential,$Re,$LandSize,$FormerOwner,$CityPlanet,$Worth,$Modern,$CityType,$Schools,$PercentLeft,$TurnsLeft) = split(/\|/, $City);
unless ($Name eq $CityName) {
print OUT "$City\n";
}
else {
$Agriculture = int(abs($data{'Agr'}));
$Commercial = int(abs($data{'Com'}));
$Industrial = int(abs($data{'Ind'}));
$Residential = int(abs($data{'Res'}));
if ($GovType == 2) {
$a = abs($Agriculture) + abs($Commercial) + abs($Industrial) + abs($Residential);
if ($a > 100 or $a < 0) {
print qqÞ
$SF<BR><Center> You cannot allocate more than 100% to buildings.<BR></center>
Þ;
$Agriculture=0;
$Commercial = 0;
$Industrial=0;
$Residential=0;
}
}
$Acceptance = (int($Acceptance * 100)/ 100);
if ($data{'health'} > 0) {
if ($Money >= ($HealthCost * $data{'health'})) {
$Hospitals += abs($data{'health'});
$Money -= ($HealthCost * $data{'health'});
$HealthMessage = qq!$data{'health'} hospitals have been constructed.<BR>!;
} else {
$HealthMessage = qq!You cannot construct more hospitals than you have funds for.<BR>!;
}
}
if ($data{'health'} < 0) {
if ($Hospitals - abs($data{'health'}) < 0) {
$HealthMessage = qq!You cannot demolish more hospitals than $Name has constructed.<BR>!;
} else {
$Hospitals += $data{'health'};
$HealthMessage = qq!$data{'health'} hospitals have been demolished.<BR>!;
}
}
if ($data{'fort'} > 0) {
if ($Money >= ($data{'fort'} * $FortificationCost)) {
$Barracks += $data{'fort'};
$Money -= ($data{'fort'} * $FortificationCost);
$FortMessage = qq!$data{'fort'} fortifications have been constructed.<BR>!;
} else {
$FortMessage = qq!You cannot construct more fortifications than you have funds for.<BR>!;
}
}
if ($data{'fort'} < 0) {
if ($Barracks - abs($data{'fort'}) < 0) {
$FortMessage = qq!You cannot demolish more fortifications than $Name has constructed.<BR>!;
} else {
$Barracks += $data{'fort'};
$FortMessage = qq!$data{'fort'} fortifications have been demolished.<BR>!;
}
}
if ($data{'education'} > 0) {
if ($Money >= ($data{'education'} * $LearnCost)) {
$Schools += $data{'education'};
$Money -= ($data{'education'} * $LearnCost);
$LearnMessage = qq!$data{'education'} schools have been constructed.<BR>!;
} else {
$LearnMessage = qq!You cannot construct more schools than you have funds for.<BR>!;
}
}
if ($data{'education'} < 0) {
if ($Schools - abs($data{'education'}) < 0) {
$LearnMessage = qq!You cannot demolish more schools than $Name has constructed.<BR>!;
} else {
$Schools += $data{'education'};
$LearnMessage = qq!$data{'education'} schools have been demolished.<BR>!;
}
}
print OUT qqÞ$Name|$Population|$Status|$BorderLevel|$Acceptance|$Feature|$Hospitals|$Barracks|$Agriculture|$Ag|$Commercial|$Co|$Industrial|$In|$Residential|$Re|$LandSize|$FormerOwner|$CityPlanet|$Worth|$Modern|$CityType|$Schools|$PercentLeft|$TurnsLeft\nÞ;
}
}
close (OUT);
open (OUT, ">$CityPath/money.txt");
print OUT "$Money\n";
close (OUT);
}
open (IN, "$CityPath/City.txt");
@Cities = <IN>;
close (IN);
&chopper (@Cities);
foreach $City (@Cities) {
($Name,$Population,$Status,$BorderLevel,$Acceptance,$Feature,$Hospitals,$Barracks,$Agriculture,$Ag,$Commercial,$Co,$Industrial,$In,$Residential,$Re,$LandSize,$FormerOwner,$CityPlanet,$Worth,$Modern,$CityType,$Schools,$PercentLeft,$TurnsLeft) = split(/\|/, $City);
if ($Name eq $CityName) {
if ($Obey == 0) {
$Obey = 1;
$HospitalCost = &Space($BaseHealth);
$SchoolCost = &Space($BaseLearn);
$FortificationsCost = &Space($FortificationCost);
$Population = &Space($Population);
$Acceptance = int($Acceptance * 100);
$Modern = $Modern * 100;
if ($Feature == 0) {$Features = "None"}
if ($Feature == 1) {$Features = "Coastal City"}
if ($CityType eq "Settlement") {if ($LandSize >= 36) {$CitySizePass=1;}}
if ($CityType eq "Village") {if ($LandSize >= 121) {$CitySizePass=1;}}
if ($CityType eq "Town") {if ($LandSize >= 594) {$CitySizePass=2;}}
if ($CityType eq "City") {if ($LandSize >= 2990) {$CitySizePass=3;}}
if ($CityType eq "Metropolis") {if ($LandSize >= 8980) {$CitySizePass=5;}}
if ($CityType eq "Megalopolis") {if ($LandSize >= 19940) {$CitySizePass=8;}}
$UpCost = &Space($CitySizePass * $Worth);
$Worth = &Space($Worth);
if ($CitySizePass >= 1) {$PossUp = "$Name can be upgraded to the next city class. It will cost \$$UpCost for this upgrade.<BR>"}
if ($CitySizePass >= 1) {$UpgradeLink = qq!<a href="http://www.bluewand.com/cgi-bin/classic/UpgradeCity.pl?$User&$Planet&$AuthCode&$CityNames&1" STYLE="text-decoration:none;color:000000">Click to Upgrade</a>!} else {$UpgradeLink = qq!Not Available!}
$LandSize = &Space($LandSize);
$FormerOwner =~ tr/_/ /;
open (DATAIN, "$CityPath/money.txt");
$money = <DATAIN>;
close (DATAIN);
chop ($money);
open (DATAIN, "$CityPath/turns.txt");
$turns = <DATAIN>;
close (DATAIN);
chop ($turns);
$money = &Space($money);
print qqÞ<SCRIPT>
parent.frames[1].location.reload()
</SCRIPT><BR>
<TABLE BORDER="1" WIDTH="100%" BORDER=1 CELLSPACING=0>
<TR>
<TD BGCOLOR="$Header" WIDTH="25%"><FONT FACE="Arial, Helvetica, sans-serif" size="-1">Current Funds:</FONT></TD>
<TD BGCOLOR="$Content" WIDTH="25%"><FONT FACE="Arial, Helvetica, sans-serif" size="-1">\$$money</TD>
<TD BGCOLOR="$Header" WIDTH="25%"><FONT FACE="Arial, Helvetica, sans-serif" size="-1">Turns Remaining:</FONT></TD>
<TD BGCOLOR="$Content" WIDTH="25%"><FONT FACE="Arial, Helvetica, sans-serif" size="-1">$turns</TD>
</TR>
</TABLE><center>
$HealthMessage
$LearnMessage
$FortMessage
$PossUp</center>
<BR><table border=1 cellspacing=0 width=80%>
<TR bgcolor="$Header"><TD colspan=4>$SF $CityName</TD></TR>
<TR bgcolor="$Content"><TD width=25% bgcolor="$Header">$SF City Size</TD><TD width=25%>$SF$LandSize</TD><TD width=25% bgcolor="$Header">$SF Value</TD><TD width=25%>$SF \$$Worth</TD></TR>
<TR bgcolor="$Content"><TD width=25% bgcolor="$Header">$SF Population</TD><TD width=25%>$SF$Population</TD><TD bgcolor="$Header">$SF Continent</TD><TD>$SF$BorderLevel</TD></TR>
<TR bgcolor="$Content"><TD width=25% bgcolor="$Header">$SF Morale</TD><TD width=25%>$SF$Acceptance%</TD><TD bgcolor="$Header">$SF Specialization</TD><TD>$SF $Features</TD></TR>
<TR bgcolor="$Content"><TD width=25% bgcolor="$Header">$SF Modernization</TD><TD width=25%>$SF$Modern%</TD><TD width=25% bgcolor="$Header">$SF Previous Nation</TD><TD width=25%>$SF $FormerOwner</TD></TR>
<TR bgcolor="$Content"><TD width=25% bgcolor="$Header">$SF Class</TD><TD width=25%>$SF$CityType</TD><TD width=25% bgcolor="$Header">$SF Upgrade</TD><TD width=25%>$SF $UpgradeLink</TD></TR>
</table>
<BR><table border=1 cellspacing=0 bgcolor="$Content" width=80%>
<TR bgcolor="$Header"><TD>$SF Building Type</TD><TD>$SF Existing</TD><TD>$SF Construction Cost</TD><TD>$SF Construct</TD></TR>Þ;
#if ($Storage{Basic_Schooling} == 1) {
print qqÞ<TR><TD>$SF Schools</TD><TD>$SF $Schools</TD><TD>$SF\$$SchoolCost<TD>$SF<input type=text name="education" size=9></TD></TR>Þ;
#}
#if ($Storage{Basic_Medicine} == 1) {
print qq!<TR><TD>$SF Hospitals</TD><TD>$SF $Hospitals</TD><TD>$SF\$$HospitalCost</TD><TD>$SF<input type=text name="health" size=9></TD></TR>!;
#}
$Co = int($Co);
$Re = int($Re);
$Ag = int($Ag);
$In = int($In);
print qqÞ
<TR><TD>$SF Barracks</TD><TD>$SF $Barracks</TD><TD>$SF\$$FortificationsCost</TD><TD>$SF<input type=text name="fort" size=9></TD></TR>
</table>
<BR>
Land
<table border=1 cellspacing=0 bgcolor="$Content" width=80%>
<TR bgcolor=$Header><TD> </TD><TD>$SF Agricultural</td><TD>$SF Commercial</td><TD>$SF Industrial</TD><TD>$SF Residential</TD></TR>
<TR><TD bgcolor="$Header">$SF Actual</TD><TD>$SF $Ag</td><TD>$SF $Co</td><TD>$SF $In</TD><TD>$SF $Re</TD></TR>Þ;
$SF = qq!<font face=verdana size=-1>!;
if ($GovType == 2) {print qqÞ<TR><TD bgcolor="$Header">$SF</center>Ideal Percentages</TD><TD>$SF<input type=text value="$Agriculture" name=Agr size=9>%</td><TD>$SF<input type=text value="$Commercial" name=Com size=9>%</td><TD>$SF<input type=text value="$Industrial" name=Ind size=9>%</TD><TD>$SF<input type=text value="$Residential" name=Res size=9>%</TD></TR>Þ;}
if ($GovType == 1) {print qqÞ<TR><TD bgcolor="$Header">$SF</center>Ideal Ratio</TD><TD>$SF<input type=text value="$Agriculture" name=Agr size=9></td><TD>$SF<input type=text value="$Commercial" name=Com size=9></td><TD>$SF<input type=text value="$Industrial" name=Ind size=9></TD><TD>$SF<input type=text value="$Residential" name=Res size=9></TD></TR>Þ;}
if ($GovType == 0) {print qqÞ<TR><TD bgcolor="$Header">$SF</center>Goal</TD><TD>$SF<input type=text value="$Agriculture" name=Agr size=9></td><TD>$SF<input type=text value="$Commercial" name=Com size=9></td><TD>$SF<input type=text value="$Industrial" name=Ind size=9></TD><TD>$SF<input type=text value="$Residential" name=Res size=9></TD></TR>Þ;}
print qqÞ
</table><BR>
<font size=-2><Center><input type=submit value="Modify City Options" name=submit>
Þ;
}
}
}
sub parse_form {
# Get the input
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
# Split the name-value pairs
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
# Un-Webify plus signs and %-encoding
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ s/<!--(.|\n)*-->//g;
$value =~ s/<([^>]|\n)*>//g;
$data{$name} = $value;
}
}
#sub chopper{
# foreach $k(@_){
# chop($k);
# }
#}
#
#sub Space {
# local($_) = @_;
# 1 while s/^(-?\d+)(\d{3})/$1 $2/;
# return $_;
#}
sub Display2 {
if (@Inf[4] eq "DE" or @Inf[4] eq "RE") {$GovType = 2}
if (@Inf[4] eq "DI" or @Inf[4] eq "TH" or @Inf[4] eq "MO") {$GovType = 0}
}
| cpraught/shattered-empires | CityMod.pl | Perl | mit | 12,744 |
# -*- perl -*-
# !!! DO NOT EDIT !!!
# This file was automatically generated.
package Net::Amazon::Validate::ItemSearch::jp::Manufacturer;
use 5.006;
use strict;
use warnings;
sub new {
my ($class , %options) = @_;
my $self = {
'_default' => 'Apparel',
%options,
};
push @{$self->{_options}}, 'Apparel';
push @{$self->{_options}}, 'Baby';
push @{$self->{_options}}, 'HealthPersonalCare';
push @{$self->{_options}}, 'Hobbies';
push @{$self->{_options}}, 'Kitchen';
push @{$self->{_options}}, 'SportingGoods';
push @{$self->{_options}}, 'Toys';
push @{$self->{_options}}, 'VideoGames';
bless $self, $class;
}
sub user_or_default {
my ($self, $user) = @_;
if (defined $user && length($user) > 0) {
return $self->find_match($user);
}
return $self->default();
}
sub default {
my ($self) = @_;
return $self->{_default};
}
sub find_match {
my ($self, $value) = @_;
for (@{$self->{_options}}) {
return $_ if lc($_) eq lc($value);
}
die "$value is not a valid value for jp::Manufacturer!\n";
}
1;
__END__
=head1 NAME
Net::Amazon::Validate::ItemSearch::jp::Manufacturer;
=head1 DESCRIPTION
The default value is Apparel, unless mode is specified.
The list of available values are:
Apparel
Baby
HealthPersonalCare
Hobbies
Kitchen
SportingGoods
Toys
VideoGames
=cut
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/Net/Amazon/Validate/ItemSearch/jp/Manufacturer.pm | Perl | mit | 1,426 |
#PODNAME: DBD::Oracle::Troubleshooting::Cygwin
#ABSTRACT: Tips and Hints to Troubleshoot DBD::Oracle on Cygwin
__END__
=pod
=head1 NAME
DBD::Oracle::Troubleshooting::Cygwin - Tips and Hints to Troubleshoot DBD::Oracle on Cygwin
=head1 VERSION
version 1.50
=head1 General Info
Makefile.PL should find and make use of OCI include
files, but you have to build an import library for
OCI.DLL and put it somewhere in library search path.
one of the possible ways to do this is issuing command
dlltool --input-def oci.def --output-lib liboci.a
in the directory where you unpacked DBD::Oracle distribution
archive. this will create import library for Oracle 8.0.4.
Note: make clean removes '*.a' files, so put a copy in a safe place.
=head1 Compiling DBD::Oracle using the Oracle Instant Client, Cygwin Perl and gcc
=over
=item 1
Download these two packages from Oracle's Instant Client for
Windows site
(http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html):
Instant Client Package - Basic: All files required to run OCI,
OCCI, and JDBC-OCI applications
Instant Client Package - SDK: Additional header files and an
example makefile for developing Oracle applications with Instant Client
(I usually just use the latest version of the client)
=item 2
Unpack both into C:\oracle\instantclient_11_1
=item 3
Download and unpack DBD::Oracle from CPAN to some place with no
spaces in the path (I used /tmp/DBD-Oracle) and cd to it.
=item 4
Set up some environment variables (it didn't work until I got the
DSN right):
ORACLE_DSN=DBI:Oracle:host=oraclehost;sid=oracledb1
ORACLE_USERID=username/password
=item 5
perl Makefile.PL
make
make test
make install
=back
Note, the TNS Names stuff doesn't always seem to work with the instant
client so Perl scripts need to explicitly use host/sid in the DSN, like
this:
my $dbh = DBI->connect('dbi:Oracle:host=oraclehost;sid=oracledb1',
'username', 'password');
=head1 AUTHORS
=over 4
=item *
Tim Bunce <timb@cpan.org>
=item *
John Scoles
=item *
Yanick Champoux <yanick@cpan.org>
=item *
Martin J. Evans <mjevans@cpan.org>
=back
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 1994 by Tim Bunce.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
| amidoimidazol/bio_info | Beginning Perl for Bioinformatics/lib/DBD/Oracle/Troubleshooting/Cygwin.pod | Perl | mit | 2,402 |
:- expects_dialect(lps).
/*
Original first example from https://nakamotoinstitute.org/contract-language/ :
future(rightA="1 round lot pork bellies",
rightB="$1,500.00",
p = "for delivery in July 2002") =
when withinPeriod(p)
to Holder rightA with to Counterparty rightB
then terminate
Fully working logical contract:
*/
:- include(system('date_utils.pl')).
% Rather then run live, we'll simulate real time by mapping its time points to simulation cycles:
simulatedRealTimeBeginning('2002-07-01').
simulatedRealTimePerCycle(RTPC) :- RTPC is 3600*12. % just 2 LPS cycles per calendar day
maxRealTime(M) :- M is 24*3600*90. % 90 days max lifetime of the contract
events to(_Agent,_Right).
future(RightA,RightB) from _Begin to _End if
to(holder,RightA) from T, to(counterParty,RightB) from T.
% Note that the time interval of a composite event head implicitly includes all times in its body
% The contract must be enforced:
if true then
future("1 round lot pork bellies", usd(1500)) from 2002/7/2 to 2002/7/4.
% If these timely observations come in, the world complies to the contract and the program succeeds
% Otherwise, the program fails, because the contract is violated
observe to(holder,"1 round lot pork bellies") at '2002-07-02T11:00'.
observe to(counterParty,usd(1500)) at '2002-07-02T11:00'.
% alternate form, denoting the first instant of the following moments:
% observe to(counterParty,usd(1500)) at 2002/7/2/11.
/** <examples>
?- go(Timeline).
*/ | TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_lps/examples/CLOUT_workshop/SzaboLanguage_futures.pl | Perl | mit | 1,509 |
%query: conf(i).
/* from Stefaan Decorte, Danny De Schreye, Henk Vandecasteele, 1997 */
conf(X) :- del2(X,Z), del(U,Y,Z), conf(Y).
del2(X,Y) :- del(U,X,Z), del(V,Z,Y).
del(X,[X|T],T).
del(X,[H|T],[H|T1]) :- del(X,T,T1).
s2l(s(X),[Y|Xs]):- s2l(X,Xs).
s2l(0, []).
goal(X) :- s2l(X,XS), conf(XS).
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Logic_Programming/SGST06/confdel.pl | Perl | mit | 302 |
use strict;
use warnings;
use 5.010;
use Data::Dumper qw(Dumper);
my %aHash = (
one => 1,
two => 2,
three => 3,
);
print Dumper(\%aHash);
my %rHash = ();
for my $key (keys %aHash) {
$rHash{$aHash{$key}} = $key;
}
print Dumper(\%rHash);
| dimir2/hse12pi2-scripts | IvanovV/perl/scr2.pl | Perl | mit | 248 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V9::Services::ReachPlanService::PlannableLocation;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
countryCode => $args->{countryCode},
id => $args->{id},
locationType => $args->{locationType},
name => $args->{name},
parentCountryId => $args->{parentCountryId}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V9/Services/ReachPlanService/PlannableLocation.pm | Perl | apache-2.0 | 1,225 |
package WordGraph::ReferenceRanker;
use strict;
use warnings;
use Moose;
use namespace::autoclean;
use File::Basename;
use File::Path;
with( 'DMOZ' );
# Note : we are ranking "sentences" ==> our framework operates on sentences but extends beyond previous systems that where limited on sentences that were (up to a certain level) known to be clearly associated with a target object. Our framework aims at allowing a soft notion of association between a reference sentence and an object to summarize.
#extends 'WordGraph::ReferenceOperator';
with 'WordGraph::ReferenceOperator';
# Overall approach : the more I can featurize (preferably in an abstract way) the more we can learn, however it is possible to incrementally featurize the process while leaving other parts non-featuized/optimized, i.e. ad hoc (e.g. the raw search component, which nonetheless could ultimately be featurized and thus optimized).
# CURRENT : must define a (potentially abstract) featurization space that can later support learning
# => assuming : I want to (rank) what type of features should we be able to operate on ? => i.e. what kind on space ?
# => overlap between input and output
# CURRENT : abstract task definitions in terms of feature spaces object/summary/both
# 1 - Ranking
# CURRENT : if I adopt kernel-based approach, do I need to arbitrarily assign a summary to the target ? => i don't think so because all we need to achieve here is a conditioning of the ranking function on the target object ?
# ==> target object / reference summary - based ranking => same space => ok
# ==> target object / reference object - based ranking => same space => ok
# ==> target object / reference object+summary - based ranking => i don't think object/summary combination necessarily makes sense for ranking, it does though for generation/summarization as a while
# 1 - featurized representation of target object (i.e. signature) => maybe could factor on a "predicted" summary based on features of the target object, making the comparison between the target and reference pairs truly in the same space
# 2 - featurized representation of (reference object + summary)
# 4 - similarity function (maybe asymmetric, i.e. comparing 2 different spaces)
# CURRENT : overall task is to parameterize the summarization process to maximize a given metric, e.g. ROUGE (but could be any other automatic or even manual objective)
# 0 - learn to search (hence I wouldn't even need to learn to re-rank)
# => parameters are controlling the amount of boost given to terms based on where/how they appear across modalities
# 1 - learn to (re)rank => should be learnable if search is given
# => generate search lists for a lot of (object,summary) pairs
# => optimize parameters to maximize ROUGE objective => this is applicable to all steps
# => featurized representation of summary+object,
# => fe
# 2 - Adaptation => should be learnable if search is given
# => featurized representation of raw reference summary (so factors in features of the associaed object)
# => featurized representation of output summary
# CURRENT : generic view ?
# => featurized representation of (object,summary pair) => define similarity (energy) based on this representation only => ranking
# => is there any case where this doesn't apply ?
sub summary_lcs_similarity {
my $this = shift;
my $summary_utterance_1 = shift;
my $summary_utterance_2 = shift;
# TODO : to be removed
=pod
# TODO : reduce code redudancy
my @summary_sequence_1 = map { $_->surface } @{ $summary_utterance_1->object_sequence };
my @summary_sequence_2 = map { $_->surface } @{ $summary_utterance_2->object_sequence };
return Similarity->lcs_similarity( \@summary_sequence_1 , \@summary_sequence_2 );
=cut
return $summary_utterance_1->lcs_similarity( $summary_utterance_2 , normalize => 1 , keep_punctuation => 0 );
}
# max count
has 'max_count' => ( is => 'ro' , isa => 'Num' , required => 0 , predicate => 'has_max_count' );
# object featurizer
has '_object_featurizer' => ( is => 'ro' , does => 'Featurizer' , init_arg => undef , lazy => 1 , builder => '_object_featurizer_builder' );
# reversed ranking ?
has 'reversed' => ( is => 'ro' , isa => 'Bool' , default => 0 );
sub _serialization_id {
my $this = shift;
my $reference_object = shift;
my @parameters = ( $reference_object->url , $this->reversed );
return [ 'reference-ranked' , \@parameters ];
}
sub _run {
my $this = shift;
my $ret = $this->_run_implementation( @_ );
# Note: we map the original sequence of entries to allow for a stable sort
my $reversed = $this->reversed;
my @sorted_sentence_entries = sort { $reversed ? ( $a->[ 1 ] <=> $b->[ 1 ] ) : ( $b->[ 1 ] <=> $a->[ 1 ] ) } @{ $ret };
# cut off reference set if requested
if ( $this->has_max_count && $#sorted_sentence_entries >= $this->max_count ) {
splice @sorted_sentence_entries , $this->max_count;
}
# Note : output ranking
print STDERR "\n\n*************************************************************************************\n";
print STDERR "Ranked references:\n";
map {
print STDERR join( "\t" , '__RANKED_REFERENCES__' , $_->[ 0 ]->object->url , @{ $_ } ) . "\n";
} @sorted_sentence_entries;
print STDERR "*************************************************************************************\n\n";
return \@sorted_sentence_entries;
}
# TODO : not yet integrated
sub serialize {
my $full_serialization_path = shift;
my @sorted_sentence_entries;
# output reference data
if ( $full_serialization_path ) {
# TODO : should this be done somewhere else ?
mkpath dirname( $full_serialization_path );
# TODO : merge into a single statement ?
open REFERENCE_OUTPUT, ">$full_serialization_path" or die "Unable to create output file ($full_serialization_path): $!";
binmode(REFERENCE_OUTPUT,':utf8');
foreach my $sentence_entry (@sorted_sentence_entries) {
my $sentence_object = $sentence_entry->[ 0 ];
my $sentence_entry_object = $sentence_object->object;
my $sentence_entry_score = $sentence_entry->[ 1 ];
my $sentence_entry_url = $sentence_entry_object->url;
if ( defined( $sentence_entry_score ) ) {
# Or, we can consider this information as a source, which would turn into 'content'/'context' for sentences directly obtained from the target object or its context
print REFERENCE_OUTPUT join( "\t" , $sentence_entry_url ,
#$category ,
$sentence_object , $sentence_entry_score ) . "\n";
}
}
close REFERENCE_OUTPUT;
}
}
# symmetric
has 'symmetric' => ( is => 'ro' , isa => 'Bool' , init_arg => undef , lazy => 1 , builder => '_symmetric_builder' );
# Note : it might become necessary to specify this function as a full-blown class instance
# TODO/Note : the reason for having this here instead of a method/role applied on the (target) object itself is that at different stages of the summarization process we may wish work with a different type of featurization .... but still this should be object-centric ...
has 'object_featurizer' => ( is => 'ro' , does => 'Featurizer' , init_arg => undef , lazy => 1 , builder => '_object_featurizer_builder' );
sub _object_featurizer_builder {
my $this = shift;
#return $this->_object_featurizer_builder( sub { return $_[ 0 ] } );
# Note : original version (no weighter)
##return new Web::UrlData::Featurizer::ModalityFeaturizer( modality => $this->similarity_field );
# TODO : problably want to make this configurable / also if multiple fields are considered for the featurization, namespaces need to be added (at least for symmetric similarity computations)
return new Web::UrlData::Featurizer::ModalityFeaturizer( modality => $this->similarity_field , coordinate_weighter => $this->_summary_idf_weighter );
}
# Note : it might become necessary to specify this function as a full-blown class instance
has 'reference_featurizer' => ( is => 'ro' , does => 'Featurizer' , init_arg => undef , lazy => 1 , builder => '_reference_featurizer_builder' );
sub _reference_featurizer_builder {
my $this = shift;
return new Web::Summarizer::Sequence::Featurizer;
}
sub _summary_idf_weighter {
my $this = shift;
return sub {
# TODO : parameterize max order
# TODO : use global count in similarity_field
# CURRENT : we need to be able to produce representations that are more than just unigrams
#return 1 / log( 1 + $this->global_data->field_count_data( 'summary' , 1 , $_[ 0 ] ) );
return 1 / ( 1 + log( 1 + $this->global_data->global_count( 'summary' , 1 , $_[ 0 ] ) ) );
};
}
sub object_similarity {
my $this = shift;
my $target_object = shift;
my $reference_sentence = shift;
my $target_featurized = $target_object->featurize( $this->object_featurizer );
my $reference_featurized = $this->symmetric ?
$reference_sentence->object->featurize( $this->object_featurizer ) :
$reference_sentence->featurize( $this->reference_featurizer );
my $object_similarity = Vector::cosine( $target_featurized , $reference_featurized );
return $object_similarity;
}
# TODO : re-enable ?
##__PACKAGE__->meta->make_immutable;
1;
| ypetinot/web-summarization | summarizers/graph-summarizer-4/src/WordGraph/ReferenceRanker.pm | Perl | apache-2.0 | 9,274 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::protocols::bgp::4::mode::bgppeerstate;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
my $instance_mode;
sub custom_status_threshold {
my ($self, %options) = @_;
my $status = 'ok';
my $message;
eval {
local $SIG{__WARN__} = sub { $message = $_[0]; };
local $SIG{__DIE__} = sub { $message = $_[0]; };
if (defined($instance_mode->{option_results}->{critical_status}) && $instance_mode->{option_results}->{critical_status} ne '' &&
eval "$instance_mode->{option_results}->{critical_status}") {
$status = 'critical';
} elsif (defined($instance_mode->{option_results}->{warning_status}) && $instance_mode->{option_results}->{warning_status} ne '' &&
eval "$instance_mode->{option_results}->{warning_status}") {
$status = 'warning';
}
};
if (defined($message)) {
$self->{output}->output_add(long_msg => 'filter status issue: ' . $message);
}
return $status;
}
sub custom_status_output {
my ($self, %options) = @_;
my $msg = "AS:'" . $self->{result_values}->{as} . "' ";
$msg .= " Local: '" . $self->{result_values}->{local} . "'";
$msg .= " Remote: '" . $self->{result_values}->{remote} . "'";
$msg .= " Peer State: '" . $self->{result_values}->{peerstate} . "'";
$msg .= " Admin State : '" . $self->{result_values}->{adminstate} . "'";
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{adminstate} = $options{new_datas}->{$self->{instance} . '_adminstate'};
$self->{result_values}->{peerstate} = $options{new_datas}->{$self->{instance} . '_peerstate'};
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
$self->{result_values}->{local} = $options{new_datas}->{$self->{instance} . '_local'};
$self->{result_values}->{remote} = $options{new_datas}->{$self->{instance} . '_remote'};
$self->{result_values}->{as} = $options{new_datas}->{$self->{instance} . '_as'};
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'peers', type => 1, cb_prefix_output => 'prefix_peers_output', message_multiple => 'All BGP peers are ok' },
];
$self->{maps_counters}->{peers} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'adminstate' }, { name => 'peerstate' }, { name => 'display' },
{ name => 'local' }, { name => 'remote' }, { name => 'as' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => $self->can('custom_status_threshold'),
}
},
{ label => 'updates', set => {
key_values => [ { name => 'seconds' }, { name => 'display' } ],
output_template => 'Last update : %ss',
perfdatas => [
{ label => 'seconds', value => 'seconds_absolute', template => '%s',
unit => 's', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
];
}
sub prefix_peers_output {
my ($self, %options) = @_;
return "Peer: '" . $options{instance_value}->{display} . "' ";
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"filter-peer:s" => { name => 'filter_peer' },
"filter-as:s" => { name => 'filter_as' },
"warning-status:s" => { name => 'warning_status', default => '' },
"critical-status:s" => { name => 'critical_status', default => '' },
});
return $self;
}
sub change_macros {
my ($self, %options) = @_;
foreach (('warning_status', 'critical_status')) {
if (defined($self->{option_results}->{$_})) {
$self->{option_results}->{$_} =~ s/%\{(.*?)\}/\$self->{result_values}->{$1}/g;
}
}
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$instance_mode = $self;
$self->change_macros();
}
my %map_peer_state = (
1 => 'idle',
2 => 'connect',
3 => 'active',
4 => 'opensent',
5 => 'openconfirm',
6 => 'established',
);
my %map_admin_state = (
1 => 'stop',
2 => 'start',
);
my $oid_bgpPeerTable = '.1.3.6.1.2.1.15.3';
my $mapping = {
bgpPeerState => { oid => '.1.3.6.1.2.1.15.3.1.2', map => \%map_peer_state },
bgpPeerAdminStatus => { oid => '.1.3.6.1.2.1.15.3.1.3', map => \%map_admin_state },
bgpPeerRemoteAs => { oid => '.1.3.6.1.2.1.15.3.1.9' },
bgpPeerLocalAddr => { oid => '.1.3.6.1.2.1.15.3.1.5' },
bgpPeerLocalPort => { oid => '.1.3.6.1.2.1.15.3.1.6' },
bgpPeerRemoteAddr => { oid => '.1.3.6.1.2.1.15.3.1.7' },
bgpPeerRemotePort => { oid => '.1.3.6.1.2.1.15.3.1.8' },
bgpPeerInUpdateElpasedTime => { oid => '.1.3.6.1.2.1.15.3.1.24' },
};
sub manage_selection {
my ($self, %options) = @_;
$self->{peers} = {};
my $result = $options{snmp}->get_table(oid => $oid_bgpPeerTable, nothing_quit => 1);
foreach my $oid (keys %{$result}) {
next if ($oid !~ /^$mapping->{bgpPeerState}->{oid}\.(.*)$/);
my $instance = $1;
my $mapped_value = $options{snmp}->map_instance(mapping => $mapping, results => $result, instance => $instance);
my $local_addr = $mapped_value->{bgpPeerLocalAddr} . ':' . $mapped_value->{bgpPeerLocalPort};
my $remote_addr = $mapped_value->{bgpPeerRemoteAddr} . ':' . $mapped_value->{bgpPeerRemotePort};
if (defined($self->{option_results}->{filter_peer}) && $self->{option_results}->{filter_peer} ne '' &&
$instance !~ /$self->{option_results}->{filter_peer}/) {
$self->{output}->output_add(long_msg => "skipping peer '" . $instance . "': no matching filter.", debug => 1);
next;
}
if (defined($self->{option_results}->{filter_as}) && $self->{option_results}->{filter_as} ne '' &&
$instance !~ /$self->{option_results}->{filter_as}/) {
$self->{output}->output_add(long_msg => "skipping AS '" . $mapped_value->{bgpPeerRemoteAs} . "': no matching filter.", debug => 1);
next;
}
$self->{peers}->{$instance} = { adminstate => $mapped_value->{bgpPeerAdminStatus}, local => $local_addr,
peerstate => $mapped_value->{bgpPeerState}, remote => $remote_addr,
seconds => $mapped_value->{bgpPeerInUpdateElpasedTime}, as => $mapped_value->{bgpPeerRemoteAs},
display => $instance };
}
if (scalar(keys %{$self->{peers}}) <= 0) {
$self->{output}->add_option_msg(short_msg => 'No peers detected, check your filter ? ');
$self->{output}->option_exit();
}
}
1;
__END__
=head1 MODE
Check BGP basic infos (BGP4-MIB.mib and rfc4273)
=over 8
=item B<--filter-as>
Filter based on AS number (regexp allowed)
=item B<--filter-peer>
Filter based on IP of peers (regexp allowed)
=item B<--warning-updates>
Warning threshold on last update (seconds)
=item B<--critical-updates>
Critical threshold on last update (seconds)
=item B<--warning-status>
Specify admin and peer state that trigger a warning. Can use %{adminstate} and %{peerstate}
e.g --warning-status "%{adminstate} =~ /stop"
=item B<--critical-status>
Specify admin and peer state that trigger a critical. Can use %{adminstate} and %{peerstate}
=back
=cut
| wilfriedcomte/centreon-plugins | apps/protocols/bgp/4/mode/bgppeerstate.pm | Perl | apache-2.0 | 8,900 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2021] EMBL-European Bioinformatics Institute
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.
=cut
package EnsEMBL::Draw::GlyphSet::genetree;
### Draws Gene/Compara_Tree (tree + alignments) and
### Gene/SpeciesTree (tree only) images
use strict;
use base qw(EnsEMBL::Draw::GlyphSet);
sub fixed {
# ...No idea what this method is for...
return 1;
}
# Colours of connectors; affected by scaling
my %connector_colours = (
0 => 'blue',
1 => 'blue',
2 => 'green',
3 => 'red',
);
my $CURRENT_ROW;
my $CURRENT_Y;
my $MIN_ROW_HEIGHT = 20;
my $EXON_TICK_SIZE = 4;
my $EXON_TICK_COLOUR = "#333333";
sub _init {
# Populate the canvas with feaures represented as glyphs
my ($self) = @_;
my $current_gene = $self->{highlights}->[0];
my $current_genome_db_id = $self->{highlights}->[1] || ' ';
my $collapsed_nodes_str = $self->{highlights}->[2] || '';
my $coloured_nodes = $self->{highlights}->[3] || [];
my $other_genome_db_id = $self->{highlights}->[4];
my $other_gene = $self->{highlights}->[5];
my $highlight_ancestor = $self->{highlights}->[6];
my $show_exons = $self->{highlights}->[7];
my $slice_cigar_lines = $self->{highlights}->[8] || [];
my $low_coverage_species = $self->{highlights}->[9] || {};
my $tree = $self->{'container'};
my $Config = $self->{'config'};
my $bitmap_width = $Config->image_width();
my $cdb = $Config->get_parameter('cdb');
my $skey = $cdb =~ /pan/ ? "_pan_compara" : '';
$CURRENT_ROW = 1;
$CURRENT_Y = 1;
# warn ("A-0:".localtime());
# Handle collapsed/removed nodes
my %collapsed_nodes = ( map{$_=>1} split( ',', $collapsed_nodes_str ) );
$self->{_collapsed_nodes} = \%collapsed_nodes;
# $coloured_nodes is an array. It is sorted such as the largest clades
# are used first. In case or a tie (i.e. all the genes are mammals and
# vertebrates), the smallest clade overwrites the colour.
foreach my $hash (@$coloured_nodes) {
my $node_ids = $hash->{'node_ids'};
my $mode = $hash->{'mode'};
my $colour = $hash->{'colour'};
my $clade = $hash->{'clade'};
foreach my $node_id (@$node_ids) {
$self->{"_${mode}_coloured_nodes"}->{$node_id} =
{'clade' => $clade, 'colour' => $colour};
}
}
# Create a sorted list of tree nodes sorted by rank then id
my @nodes = ( sort { ($a->{_rank} <=> $b->{_rank}) * 10
+ ( $a->{_id} <=> $b->{_id}) }
@{$self->features($tree, 0, 0, 0, $show_exons, $slice_cigar_lines, $low_coverage_species) || [] } );
# warn ("B-0:".localtime());
#----------
# Calculate pixel widths for the components of the image;
# +----------------------------------------------------+
# | bitmap_width |
# | tree_width (60%) | alignment_width (40%) |
# | nodes_width | labels_width | |
# +----------------------------------------------------+
# Set 60% to the tree, and 40% to the alignments
my $tree_bitmap_width = $tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') ? int( $bitmap_width * 0.95 ) : int( $bitmap_width * 0.6 );
my $align_bitmap_width = $bitmap_width - $tree_bitmap_width;
# Calculate space to reserve for the labels
my( $fontname, $fontsize ) = $self->get_font_details( 'small' );
$fontsize = 7; # make default font size 7 instead of the 'small' font size of 6.4 which takes the floor value
$fontsize = 8 if($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode'));
my( $longest_label ) = ( sort{ length($b) <=> length($a) }
map{$_->{label}} @nodes );
my @res = $self->get_text_width( 0, $longest_label, '',
'font'=>$fontname, 'ptsize' => $fontsize );
my $font_height = $res[3];
my $font_width = $res[2];
# And assign the rest to the nodes
my $labels_bitmap_width = $font_width;
my $nodes_bitmap_width;
#Need to decrease the node_width region by the number of nodes (width 5) to ensure the
#labels don't extend into the alignment_width. Only noticable on Alignments (text) pages
if ($tree->isa('Bio::EnsEMBL::Compara::GenomicAlignTree')) {
#find the max_rank ie the highest number of nodes in a branch
my $max_rank = (sort { $b->{_rank} <=> $a->{_rank} } @nodes)[0]->{_rank};
$nodes_bitmap_width = $tree_bitmap_width-$labels_bitmap_width-($max_rank*5);
} else {
$nodes_bitmap_width = $tree_bitmap_width-$labels_bitmap_width;
}
#----------
# Calculate phylogenetic distance to px scaling
#my $max_distance = $tree->max_distance;
# warn Data::Dumper::Dumper( @nodes );
my( $max_x_offset ) = ( sort{ $b <=> $a }
map{$_->{_x_offset} + ($_->{_collapsed_distance}||0)}
@nodes );
my $nodes_scale = ($nodes_bitmap_width) / ($max_x_offset||1);
#----------
# Draw each node
my %Nodes;
map { $Nodes{$_->{_id}} = $_} @nodes;
my @alignments;
my @node_glyphs;
my @bg_glyphs;
my @labels;
my $node_href;
my $border_colour;
foreach my $f (@nodes) {
# Ensure connector enters at base of node glyph
my $parent_node = $Nodes{$f->{_parent}} || {x=>0};
my $min_x = $parent_node->{x} + 4;
$f->{_x_offset} = $max_x_offset if ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') && $f->{label}); #Align all the ending nodes with labels in the cafe tree
($f->{x}) = sort{$b<=>$a} int($f->{_x_offset} * $nodes_scale), $min_x;
if ($f->{_cigar_line}){
push @alignments, [ $f->{y} , $f->{_cigar_line}, $f->{_collapsed}, $f->{_aligned_exon_coords}] ;
}
# Node glyph, coloured for for duplication/speciation
my ($node_colour, $label_colour, $collapsed_colour);
my $bold = 0;
if (defined $f->{_node_type}) {
if ($f->{_node_type} eq 'duplication') {
$node_colour = 'red3';
} elsif ($f->{_node_type} eq 'dubious') {
$node_colour = 'turquoise';
} elsif ($f->{_node_type} eq 'gene_split') {
$node_colour = 'SandyBrown';
}
}
#node colour categorisation for cafetree/speciestree/gainloss tree
if($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode')) {
$border_colour = 'black';
$node_colour = 'grey' if($f->{_n_members} == 0 );
$node_colour = '#FEE391' if($f->{_n_members} >= 1 && $f->{_n_members} <= 5);
$node_colour = '#FEC44F' if($f->{_n_members} >= 6 && $f->{_n_members} <= 10);
$node_colour = '#FE9929' if($f->{_n_members} >= 11 && $f->{_n_members} <= 15);
$node_colour = '#EC7014' if($f->{_n_members} >= 16 && $f->{_n_members} <= 20);
$node_colour = '#CC4C02' if($f->{_n_members} >= 21 && $f->{_n_members} <= 25);
$node_colour = '#8C2D04' if($f->{_n_members} >= 25);
}
if ( $f->{label} ) {
if( $other_gene && $f->{_genes}->{$other_gene} ){
$bold = 1;
$label_colour = "ff6666";
} elsif( $other_genome_db_id && $f->{_genome_dbs}->{$other_genome_db_id} ){
$bold = 1;
} elsif( $f->{_genes}->{$current_gene} ){
$label_colour = 'red';
$collapsed_colour = 'red';
$node_colour = 'navyblue';
$bold = defined($other_genome_db_id);
} elsif( $f->{_genome_dbs}->{$current_genome_db_id} ){
$label_colour = 'blue';
$collapsed_colour = 'blue';
$bold = defined($other_genome_db_id);
}
}
if ($f->{_fg_colour}) {
# Use this foreground colour for this node if not already set
$node_colour = $f->{_fg_colour} if (!$node_colour);
$label_colour = $f->{_fg_colour} if (!$label_colour);
$collapsed_colour = $f->{_fg_colour} if (!$collapsed_colour);
}
if ($highlight_ancestor and $highlight_ancestor == $f->{'_id'}) {
$bold = 1;
}
$label_colour = 'red' if exists $f->{_subtree_ref};
$label_colour = "red" if($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') && $f->{label} =~ /$current_gene/ );
$node_colour = "navyblue" if (!$node_colour); # Default colour
$label_colour = "black" if (!$label_colour); # Default colour
$collapsed_colour = 'grey' if (!$collapsed_colour); # Default colour
#cafetree zmenu else comparatree zmenu
if ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode')){
$node_href = $self->_url({
action => "SpeciesTree",
node => $f->{'_id'},
genetree_id => $Config->get_parameter('genetree_id'),
collapse => $collapsed_nodes_str
});
} elsif (!$tree->isa('Bio::EnsEMBL::Compara::GenomicAlignTree')) {
$node_href = $self->_url({
action => "ComparaTreeNode$skey",
node => $f->{'_id'},
genetree_id => $Config->get_parameter('genetree_id'),
collapse => $collapsed_nodes_str
});
}
my $collapsed_xoffset = 0;
if ($f->{_bg_colour}) {
my $y = $f->{y_from} + 2;
my $height = $f->{y_to} - $f->{y_from} - 1;
my $x = $f->{x};
my $width = $bitmap_width - $x - 5;
push @bg_glyphs, $self->Rect({
'x' => $x,
'y' => $y,
'width' => $width,
'height' => $height,
'colour' => $f->{_bg_colour},
});
}
if( $f->{_collapsed} ){ # Collapsed
my $height = $f->{_height};
my $width = $f->{_collapsed_distance} * $nodes_scale + 10;
my $y = $f->{y} + 2;
my $x = $f->{x} + 2;
$collapsed_xoffset = $width;
push @node_glyphs, $self->Poly({
'points' => [ $x, $y,
$x + $width, $y - ($height / 2 ),
$x + $width, $y + ($height / 2 ) ],
$f->{_collapsed_cut} ? ('patterncolour' => $collapsed_colour, 'pattern' => ($f->{_collapsed_cut} == 1 ? 'hatch_vert' : 'pin_vert'))
: ('colour' => $collapsed_colour),
'href' => $node_href,
});
my $node_glyph = $self->Rect({
'x' => $f->{x},
'y' => $f->{y},
'width' => 5,
'height' => 5,
'colour' => $node_colour,
'href' => $node_href,
});
push @node_glyphs, $node_glyph;
if ($f->{_node_type} eq 'gene_split') {
push @node_glyphs, $self->Rect({
'x' => $f->{x},
'y' => $f->{y},
'width' => 5,
'height' => 5,
'bordercolour' => 'navyblue',
'href' => $node_href,
});
}
}
elsif( $f->{_child_count} ){ # Expanded internal node
# Draw n_members label on top of the node
$f->{_n_members} = ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') && !$f->{_n_members}) ? '0 ' : $f->{_n_members}; #adding a space hack to get it display 0 as label
my $nodes_label = $self->Text
({
'text' => $f->{_n_members},
'height' => $font_height,
'width' => $labels_bitmap_width,
'font' => $fontname,
'ptsize' => $fontsize,
'halign' => 'left',
'colour' => $label_colour,
'y' => $f->{y}-10,
'x' => $f->{x}-10,
'zindex' => 40,
});
push(@labels, $nodes_label);
# Add a 'collapse' href
my $node_glyph = $self->Rect({
'x' => $f->{x} - $bold,
'y' => $f->{y} - $bold,
'width' => 5 + 2 * $bold,
'height' => 5 + 2 * $bold,
'colour' => $node_colour,
'bordercolour' => $tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') ? 'black' : $node_colour,
'zindex' => ($f->{_node_type} !~ /speciation/ ? 40 : -20),
'href' => $node_href
});
push @node_glyphs, $node_glyph;
if ($bold) {
my $node_glyph = $self->Rect({
'x' => $f->{x},
'y' => $f->{y},
'width' => 5,
'height' => 5,
'bordercolour' => "white",
'zindex' => ($f->{_node_type} !~ /speciation/ ? 40 : -20),
'href' => $node_href
});
push @node_glyphs, $node_glyph;
}
if ($f->{_node_type} eq 'gene_split') {
push @node_glyphs, $self->Rect({
'x' => $f->{x},
'y' => $f->{y},
'width' => 5,
'height' => 5,
'bordercolour' => 'navyblue',
'zindex' => -20,
'href' => $node_href,
});
}
}
else{ # Leaf node
my $type = $f->{_node_type};
my $colour = $tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') ? $node_colour : '';
my $bordercolour = $tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') ? "black" : $node_colour;
push @node_glyphs, $self->Rect({
'x' => $f->{x},
'y' => $f->{y},
'width' => 5,
'height' => 5,
'colour' => $tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') ? $node_colour : 'white',
'bordercolour' => $tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') ? "black" : $bordercolour,
'zindex' => -20,
'href' => $node_href,
});
}
# Leaf label or collapsed node label, coloured for focus gene/species
if ($f->{label}) {
$label_colour = ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') && !$f->{_n_members}) ? 'Grey' : $label_colour;
# Draw the label
my $txt = $self->Text({
'text' => $f->{label},
'height' => $font_height,
'width' => $labels_bitmap_width,
'font' => $fontname,
'ptsize' => $fontsize,
'halign' => 'left',
'colour' => $label_colour,
'y' => $f->{y} - int($font_height/2),
'x' => $f->{x} + 10 + $collapsed_xoffset,
'zindex' => 40,
});
# increase the size of the text that has been flagged as bold
$txt->{'ptsize'} = 8 if ($bold);
if ($f->{'_gene'}) {
$txt->{'href'} = $self->_url({
species => $f->{'_species'},
type => 'Gene',
action => 'ComparaTree',
__clear => 1,
g => $f->{'_gene'}
});
} elsif (exists $f->{_subtree}) {
$txt->{'href'} = $node_href;
} elsif ($f->{'_gat'}) {
$txt->{'colour'} = $f->{'_gat'}{'colour'};
}
push(@labels, $txt);
}
}
$self->push( @bg_glyphs );
my $max_x = (sort {$a->{x} <=> $b->{x}} @nodes)[-1]->{x};
my $min_y = (sort {$a->{y} <=> $b->{y}} @nodes)[0]->{y};
# warn ("MAX X: $max_x" );
# warn ("C-0:".localtime());
#----------
# DRAW THE TREE CONNECTORS
$self->_draw_tree_connectors(%Nodes);
# Push the nodes afterwards, so they show above the connectors
$self->push( @node_glyphs );
$self->push(@labels);
#----------
# DRAW THE ALIGNMENTS
# Display only those gaps that amount to more than 1 pixel on screen,
# otherwise screen gets white when you zoom out too much ..
# Global alignment settings
my $fy = $min_y;
#my $alignment_start = $max_x + $labels_bitmap_width + 20;
#my $alignment_width = $bitmap_width - $alignment_start;
my $alignment_start = $tree_bitmap_width;
my $alignment_width = $align_bitmap_width - 20;
my $alignment_length = 0;
if ($tree->isa('Bio::EnsEMBL::Compara::GeneTreeNode')) {
$alignment_length = $tree->tree->aln_length;
} else {
#Find the alignment length from the first alignment
my @cigar = grep {$_} split(/(\d*[GDMmXI])/, $alignments[0]->[1]);
for my $cigElem ( @cigar ) {
my $cigType = substr( $cigElem, -1, 1 );
my $cigCount = substr( $cigElem, 0 ,-1 );
$cigCount = 1 unless ($cigCount =~ /^\d+$/);
#Do not include I in the alignment length
if ($cigType =~ /[GDMmX]/) {
$alignment_length += $cigCount;
}
}
}
$alignment_length ||= $alignment_width; # All nodes collapsed
my $min_length = int($alignment_length / $alignment_width);
my $alignment_scale = $alignment_width / $alignment_length;
#warn("==> AL: START: $alignment_start, LENGTH: $alignment_length, ",
# "WIDTH: $alignment_width, MIN: $min_length");
foreach my $a (@alignments) {
if(@$a) {
my ($yc, $al, $collapsed, $exon_coords) = @$a;
# Draw the exon splits under the boxes
foreach my $exon_end (@$exon_coords) {
my $e = $self->Line({
'x' => $alignment_start + $exon_end * $alignment_scale,
'y' => $yc - 3 - $EXON_TICK_SIZE,
'width' => 0,
'height' => $font_height + (2 * $EXON_TICK_SIZE),
'colour' => $EXON_TICK_COLOUR,
'zindex' => 0,
});
$self->push( $e );
}
#Use a different colour for DNA (GenomicAlignTree) and proteins
my $box_colour;
if ($tree->isa('Bio::EnsEMBL::Compara::GenomicAlignTree')) {
$box_colour = '#3366FF'; #blue
} else {
$box_colour = $collapsed ? 'darkgreen' : 'yellowgreen';
}
my $t = $self->Rect({
'x' => $alignment_start,
'y' => $yc - 3,
'width' => $alignment_width,
'height' => $font_height,
'colour' => $box_colour,
'zindex' => 0,
});
$self->push( $t );
my @inters = split (/([MmDGXI])/, $al);
my $ms = 0;
my $ds = 0;
my $box_start = 0;
my $box_end = 0;
my $colour = 'white';
my $zc = 10;
while (@inters) {
$ms = (shift (@inters) || 1);
my $mtype = shift (@inters);
#Skip I elements
next if ($mtype eq "I");
$box_end = $box_start + $ms -1;
if ($mtype =~ /G|M/) {
# Skip normal alignment and gaps in alignments
$box_start = $box_end + 1;
next;
}
if ($ms >= $min_length ) {
my $t = $self->Rect({
'x' => $alignment_start + ($box_start * $alignment_scale),
'y' => $yc - 2,
'z' => $zc,
'width' => abs( $box_end - $box_start + 1 ) * $alignment_scale,
'height' => $font_height - 2,
'colour' => ($mtype eq "m"?"yellowgreen":$colour),
'absolutey' => 1,
});
$self->push($t);
}
$box_start = $box_end + 1;
}
}
}
# warn ("E-0:".localtime());
return 1;
}
sub _draw_tree_connectors {
my ($self, %Nodes) = @_;
foreach my $f (keys %Nodes) {
if (my $pid = $Nodes{$f}->{_parent}) {
my $xc = $Nodes{$f}->{x} + 2;
my $yc = $Nodes{$f}->{y} + 2;
my $p = $Nodes{$pid};
my $xp = $p->{x} + 3;
my $yp = $p->{y} + 2;
my $node_type = $Nodes{$f}->{_node_type};
# Connector colour depends on scaling
my $col = $connector_colours{ ($Nodes{$f}->{_cut} || 0) } || 'red';
$col = $Nodes{$f}->{_fg_colour} if ($Nodes{$f}->{_fg_colour});
$col = '#800000' if($Nodes{$f}->{_cafetree} && $node_type eq 'expansion');
$col = '#008000' if($Nodes{$f}->{_cafetree} && $node_type eq 'contractions');
$col = 'blue' if($Nodes{$f}->{_cafetree} && $node_type eq 'default');
$col = '#c3ceff' if($Nodes{$f}->{_cafetree} && !$Nodes{$f}->{_n_members}|| $Nodes{$f}->{_n_members} eq '0 '); # fade branch for node with n-members 0
#for cafe tree we have thicker lines for expansion/contraction node. node_type is not used in if statement because for some unknown reason the first two connectors always go in there even if they are not contraction or expansion.
if($col eq '#800000' || $col eq '#008000') {#$node_type && ($node_type eq 'expansion' || $node_type eq 'contractions') {
# thicker vertical connectors
$self->push($self->Rect({
'x' => $xp,
'y' => $yp,
'width' => 1,
'height' => ($yc - $yp),
'bordercolour' => $col,
})
);
# thicker horizontal connectors
$self->push($self->Rect({
'x' => $xp,
'y' => $yc,
'width' => ($xc - $xp - 2),
'height' => 1,
'bordercolour' => $col,
})
);
} else {
# Vertical connector
my $v_line = $self->Line
({
'x' => $xp,
'y' => $yp,
'width' => 0,
'height' => ($yc - $yp),
'colour' => $col,
'zindex' => 0,
});
$self->push( $v_line );
# Horizontal connector
my $width = $xc - $xp - 2;
if( $width ){
my $h_line = $self->Line
({
'x' => $xp,
'y' => $yc,
'width' => $width,
'height' => 0,
'colour' => $col,
'zindex' => 0,
'dotted' => $Nodes{$f}->{_cut} || undef,
});
$self->push( $h_line );
}
}
}
}
}
sub features {
my $self = shift;
my $tree = shift;
my $rank = shift || 0;
my $parent_id = shift || 0;
my $x_offset = shift || 0;
my $show_exons = shift || 0;
my $slice_cigar_lines = shift;
my $low_coverage_species = shift || {};
my $node_type;
# Scale the branch length
my $distance = $tree->distance_to_parent;
my $cut = 0;
while ($distance > 1) {
$distance /= 10;
$cut++;
}
$x_offset += $distance;
if ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode')) {
if ($tree->is_node_significant) {
if ($tree->is_expansion) {
#print "expansion\n";
$node_type = 'expansion';
} elsif ($tree->is_contraction) {
#print "contraction\n";
$node_type = 'contractions';
}
} else {
$node_type = 'default';
}
}
# Create the feature for this recursion
my $node_id = $tree->node_id;
my @features;
my $n_members = ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode'))? $tree->n_members : '';
$cut = 0 if ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode')); #only for cafe tree, cut is 0 so that the branch are single blue line (no dotted or other colours)
$n_members = $tree->{_counter_position} if $tree->isa('Bio::EnsEMBL::Compara::GenomicAlignTree');
my $f = {
_distance => $distance,
_x_offset => $x_offset,
_node_type => $node_type ? $node_type : $tree->get_tagvalue('node_type'),
_id => $node_id,
_rank => $rank++,
_parent => $parent_id,
_cut => $cut,
_n_members => $n_members,
_cafetree => ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode')) ? 1 : 0,
};
# Initialised colouring
$f->{'_fg_colour'} = $self->{'_fg_coloured_nodes'}->{$node_id}->{'colour'} if $self->{'_fg_coloured_nodes'}->{$node_id};
$f->{'_bg_colour'} = $self->{'_bg_coloured_nodes'}->{$node_id}->{'colour'} if $self->{'_bg_coloured_nodes'}->{$node_id};
# Initialised collapsed nodes
if ($self->{'_collapsed_nodes'}->{$node_id}) {
# What is the size of the collapsed node?
my $leaf_count = 0;
my $paralog_count = 0;
my $sum_dist = 0;
my %genome_dbs;
my %genes;
my %leaves;
my $species_tree_node = $tree->species_tree_node();
my $node_name;
if (defined $species_tree_node) {
$node_name = $species_tree_node->get_common_name() || $species_tree_node->get_scientific_name;
}
foreach my $leaf (@{$tree->get_all_leaves}) {
my $dist = $leaf->distance_to_ancestor($tree);
$leaf_count++;
$sum_dist += $dist || 0;
$genome_dbs{$leaf->genome_db->dbID}++;
$genes{$leaf->gene_member->stable_id}++;
$leaves{$leaf->node_id}++;
}
$f->{'_collapsed'} = 1,
$f->{'_collapsed_count'} = $leaf_count;
$f->{'_collapsed_cut'} = 0;
while ($sum_dist > $leaf_count) {
$sum_dist /= 10;
$f->{'_collapsed_cut'}++;
}
$f->{'_collapsed_distance'} = $sum_dist/$leaf_count;
$f->{'_height'} = 12 * log($f->{'_collapsed_count'});
$f->{'_genome_dbs'} = \%genome_dbs;
$f->{'_genes'} = \%genes;
$f->{'_leaves'} = \%leaves;
$f->{'label'} = sprintf '%s: %d homologs', ($node_name, $leaf_count);
}
# Recurse for each child node
if ($tree->isa('Bio::EnsEMBL::Compara::GenomicAlignTree')) {
if (!$f->{'_collapsed'} && @{$tree->sorted_children}) {
foreach my $child_node (@{$tree->sorted_children}) {
$f->{'_child_count'}++;
push @features, @{$self->features($child_node, $rank, $node_id, $x_offset, $show_exons, $slice_cigar_lines, $low_coverage_species)};
}
}
} else {
if (!$f->{'_collapsed'} && @{$tree->sorted_children}) {
foreach my $child_node (@{$tree->sorted_children}) {
$f->{'_child_count'}++;
push @features, @{$self->features($child_node, $rank, $node_id, $x_offset, $show_exons, $slice_cigar_lines, $low_coverage_species)};
}
}
}
# Assign 'y' coordinates
if (@features > 0) { # Internal node
$f->{'y'} = ($features[0]->{'y'} + $features[-1]->{'y'}) / 2;
$f->{'y_from'} = $features[0]->{'y_from'};
$f->{'y_to'} = $features[-1]->{'y_to'};
} else { # Leaf node or collapsed
my $height = int($f->{'_height'} || 0) + 1;
$height = $MIN_ROW_HEIGHT if $height < $MIN_ROW_HEIGHT;
$f->{'y'} = $CURRENT_Y + ($height/2);
$f->{'y_from'} = $CURRENT_Y;
$CURRENT_Y += $height;
$f->{'y_to'} = $CURRENT_Y;
}
if ($tree->isa('Bio::EnsEMBL::Compara::CAFEGeneFamilyNode') && $tree->genome_db) {
$f->{'_species'} = $self->species_defs->production_name_mapping($tree->genome_db->name); # This will be used in URLs
#adding extra space after the n members so as to align the species name
my $n_members = $tree->n_members;
$n_members = $n_members < 10 ? (sprintf '%-8s', $n_members) : (sprintf '%-7s', $n_members);
$f->{'_species_label'} = $self->species_defs->get_config($f->{'_species'}, 'SPECIES_SCIENTIFIC_NAME') || $self->species_defs->species_label($f->{'_species'}) || $f->{'_species'};
$f->{'label'} = $f->{'_display_id'} = $n_members."$f->{'_species_label'}";
}
# Process alignment
if ($tree->isa('Bio::EnsEMBL::Compara::AlignedMember')) {
if ($tree->genome_db) {
$f->{'_species'} = $self->species_defs->production_name_mapping($tree->genome_db->name); # This will be used in URLs
# This will be used for display
$f->{'_species_label'} = $self->species_defs->get_config($f->{'_species'}, 'SPECIES_DISPLAY_NAME') || $self->species_defs->species_label($f->{'_species'}) || $f->{'_species'};
$f->{'_genome_dbs'} ||= {};
$f->{'_genome_dbs'}->{$tree->genome_db->dbID}++;
}
if ($tree->stable_id) {
$f->{'_protein'} = $tree->stable_id;
$f->{'label'} = "$f->{'_stable_id'} $f->{'_species_label'}";
}
if (my $member = $tree->gene_member) {
my $stable_id = $member->stable_id;
my $chr_name = $member->dnafrag->name;
my $chr_start = $member->dnafrag_start;
my $chr_end = $member->dnafrag_end;
$f->{'_gene'} = $stable_id;
$f->{'_genes'} ||= {};
$f->{'_genes'}->{$stable_id}++;
my $treefam_link = "http://www.treefam.org/cgi-bin/TFseq.pl?id=$stable_id";
$f->{'label'} = "$stable_id, $f->{'_species_label'}";
push @{$f->{'_link'}}, { text => 'View in TreeFam', href => $treefam_link };
$f->{'_location'} = "$chr_name:$chr_start-$chr_end";
$f->{'_length'} = $chr_end - $chr_start;
$f->{'_cigar_line'} = $tree->cigar_line;
if ($show_exons) {
my $ref_genetree = $tree->tree;
$ref_genetree = $ref_genetree->alternative_trees->{default} if $ref_genetree->ref_root_id;
unless ($ref_genetree->{_exon_boundaries_hash}) {
my $gtos_adaptor = $tree->adaptor->db->get_GeneTreeObjectStoreAdaptor;
my $json_string = $gtos_adaptor->fetch_by_GeneTree_and_label($ref_genetree, 'exon_boundaries');
if ($json_string) {
$ref_genetree->{_exon_boundaries_hash} = JSON->new->decode($json_string);
} else {
$ref_genetree->{_exon_boundaries_hash} = {};
}
}
$f->{'_aligned_exon_coords'} = $ref_genetree->{_exon_boundaries_hash}->{$tree->seq_member_id}->{positions};
}
if (my $display_label = $member->display_label) {
$f->{'label'} = $f->{'_display_id'} = "$display_label, $f->{'_species_label'}";
}
}
} elsif ($f->{'_collapsed'}) { # Collapsed node
unless ($tree->tree->{_consensus_cigar_line_hash}) {
my $gtos_adaptor = $tree->adaptor->db->get_GeneTreeObjectStoreAdaptor;
my $json_string = $gtos_adaptor->fetch_by_GeneTree_and_label($tree->tree, 'consensus_cigar_line');
if ($json_string) {
$tree->tree->{_consensus_cigar_line_hash} = JSON->new->decode($json_string);
} else {
$tree->tree->{_consensus_cigar_line_hash} = {};
}
}
$f->{'_name'} = $tree->name;
$f->{'_cigar_line'} = $tree->tree->{_consensus_cigar_line_hash}->{$tree->node_id};
$f->{'_cigar_line'} ||= $tree->consensus_cigar_line if UNIVERSAL::can($tree, 'consensus_cigar_line'); # Until all the EG divisions have updated their database
} elsif ($tree->is_leaf && $tree->isa('Bio::EnsEMBL::Compara::GeneTreeNode')) {
my $name = $tree->{_subtree}->stable_id;
$name = $tree->{_subtree}->get_tagvalue('model_id') unless $name;
$f->{label} = $f->{'_display_id'} = sprintf('%s (%d genes)', $name, $tree->{_subtree_size});
$f->{_subtree_ref} = 1 if exists $tree->{_subtree}->{_supertree};
} elsif ($tree->is_leaf && $tree->isa('Bio::EnsEMBL::Compara::GenomicAlignTree')) {
my $genomic_align = $tree->get_all_genomic_aligns_for_node->[0];
my $name = $genomic_align->genome_db->name;
#Get the cigar_line for the GenomicAlignGroup (passed in via highlights structure)
my $cigar_line = shift @$slice_cigar_lines;
#Only display cigar glyphs if there is an alignment in this region
if ($cigar_line =~ /M/) {
$f->{'_cigar_line'} = $cigar_line;
}
$f->{'label'} = $self->species_defs->get_config($self->species_defs->production_name_mapping($name), 'SPECIES_DISPLAY_NAME');
if ($low_coverage_species && $low_coverage_species->{$genomic_align->genome_db->dbID}) {
$f->{'_gat'}{'colour'} = 'brown';
}
$f->{'_species'} = $self->species_defs->production_name_mapping($name); # This will be used in URLs;
} else { # Internal node
$f->{'_name'} = $tree->name;
}
push @features, $f;
return \@features;
}
sub colour {
my ($self, $f) = @_;
return $f->{colour}, $f->{type} =~ /_snp/ ? 'white' : 'black', 'align';
}
sub image_label {
my ($self, $f ) = @_;
return $f->seqname(), $f->{type} || 'overlaid';
}
1;
| Ensembl/ensembl-webcode | modules/EnsEMBL/Draw/GlyphSet/genetree.pm | Perl | apache-2.0 | 32,398 |
package HTTP::Body::OctetStream;
{
$HTTP::Body::OctetStream::VERSION = '1.19';
}
use strict;
use base 'HTTP::Body';
use bytes;
use File::Temp 0.14;
=head1 NAME
HTTP::Body::OctetStream - HTTP Body OctetStream Parser
=head1 SYNOPSIS
use HTTP::Body::OctetStream;
=head1 DESCRIPTION
HTTP Body OctetStream Parser.
=head1 METHODS
=over 4
=item spin
=cut
sub spin {
my $self = shift;
unless ( $self->body ) {
$self->body( File::Temp->new( DIR => $self->tmpdir ) );
}
if ( my $length = length( $self->{buffer} ) ) {
$self->body->write( substr( $self->{buffer}, 0, $length, '' ), $length );
}
if ( $self->length == $self->content_length ) {
seek( $self->body, 0, 0 );
$self->state('done');
}
}
=back
=head1 AUTHOR
Christian Hansen, C<ch@ngmedia.com>
=head1 LICENSE
This library is free software . You can redistribute it and/or modify
it under the same terms as perl itself.
=cut
1;
| MorganCabral/cabralcc.com | app/cgi-bin/lib/HTTP/Body/OctetStream.pm | Perl | apache-2.0 | 964 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2021] EMBL-European Bioinformatics Institute
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.
=cut
package EnsEMBL::Web::Component::Info::SpeciesBlurb;
use strict;
sub content {
## Simple template that we can populate differently in plugins
my $self = shift;
my $html;
if ($self->hub->species eq 'Sars_cov_2') {
$html = sprintf('
<div class="column-wrapper">
<div class="column-one">
%s
</div>
</div>', $self->page_header);
$html .= sprintf('
<div class="column-wrapper">
<div class="column-two">
%s
</div>
<div class="column-two">
%s
</div>
</div>',
$self->column_left, $self->column_right);
}
else {
$html = sprintf('
<div class="column-wrapper">
<div class="column-one">
%s
%s
</div>
</div>', $self->page_header, $self->column_right);
}
}
sub _wikipedia_link {
return '';
}
1;
| Ensembl/public-plugins | covid19/modules/EnsEMBL/Web/Component/Info/SpeciesBlurb.pm | Perl | apache-2.0 | 1,491 |
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2017] EMBL-European Bioinformatics Institute
#
# 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.
=pod
=head1 NAME
Bio::EnsEMBL::Analysis::RunnableDB::Finished::HalfwiseHMM
=head1 SYNOPSIS
my $obj = Bio::EnsEMBL::Analysis::RunnableDB::Finished::HalfwiseHMM->new(
-db => $db,
-input_id => $id
);
$obj->fetch_input
$obj->run
my @newfeatures = $obj->output;
=head1 DESCRIPTION
runs HalfwiseHMM runnable and converts it output into genes which can be stored in an ensembl database
=head1 CONTACT
lec@sanger.ac.uk
refactored by Sindhu K. Pillai sp1@sanger.ac.uk
=head1 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _
=cut
# Let the code begin...
package Bio::EnsEMBL::Analysis::RunnableDB::Finished::HalfwiseHMM;
use warnings ;
use Bio::EnsEMBL::Analysis::RunnableDB::Finished;
use vars qw(@ISA);
use strict;
use Bio::EnsEMBL::Analysis::Runnable::Finished::HalfwiseHMM;
use Bio::EnsEMBL::Analysis::Tools::BlastDBTracking;
use Bio::EnsEMBL::Exon;
use Bio::EnsEMBL::Transcript;
use Bio::EnsEMBL::Translation;
use Bio::EnsEMBL::Gene;
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::DBSQL::DBConnection;
use Bio::EnsEMBL::Utils::Argument qw( rearrange );
use Bio::EnsEMBL::Utils::Exception qw(verbose throw warning);
use Bio::EnsEMBL::Analysis::Config::General;
use Bio::EnsEMBL::DBEntry;
use Bio::EnsEMBL::Analysis::Config::GeneBuild::Similarity qw (
GB_SIMILARITY_DATABASES
);
use Data::Dumper;
@ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB::Finished);
=head2 new
Arg : all those inherited from RunnableDB
Function : Make a new HalfwiseHMM object defining the above variables
Exception: thrown if no input id is provided, this is found in RunnableDB
Caller :
Example : $runnable = Bio::EnsEMBL::Analysis::RunnableDB::HalfwiseHMM new->(-db => $db
-INPUT_ID => $id
-ANALYSIS => $analysis);
=cut
sub new {
my ( $new, @args ) = @_;
my $self = $new->SUPER::new(@args);
# db, input_id, seqfetcher, and analysis objects are all set in
# in superclass constructor (RunnableDB.pm)
my ( $type, $threshold ) = rearrange( [qw(TYPE THRESHOLD)], @args );
$self->{' '} = []; #create key to an array of feature pairs
return $self;
}
sub type {
my ( $self, $type ) = @_;
if ( defined($type) ) {
$self->{_type} = $type;
}
return $self->{_type};
}
sub threshold {
my ( $self, $threshold ) = @_;
if ( defined($threshold) ) {
$self->{_threshold} = $threshold;
}
return $self->{_threshold};
}
=head2 fetch_input
Arg : none
Function : fetches the repeatmasked sequence and the uniprot features for the slice being run on and creates the HalfwiseHMM Runnable
Exception: throws if no input_id has been provided
Caller :
Example :
=cut
sub fetch_input {
my ($self) = @_;
my %ests;
my @estseqs;
throw("No input id") unless defined( $self->input_id );
my $sliceid = $self->input_id;
my $sa = $self->db->get_SliceAdaptor();
my $slice = $sa->fetch_by_name($sliceid);
$slice->{'seq'} = $slice->seq();
$self->query($slice);
my $maskedslice =
$slice->get_repeatmasked_seq( $ANALYSIS_REPEAT_MASKING, $SOFT_MASKING )
or throw("Unable to fetch contig");
my $alignAdaptor = $self->db->get_ProteinAlignFeatureAdaptor();
my $stateinfocontainer = $self->db->get_StateInfoContainer;
my $analysis_adaptor = $self->db->get_AnalysisAdaptor();
foreach my $database ( @{$GB_SIMILARITY_DATABASES} ) {
my $analysis_ln = $database->{'type'};
my $threshold = $database->{'threshold'};
my $fps = [];
my $features =
$alignAdaptor->fetch_all_by_Slice_and_pid( $slice,
$threshold,
$analysis_ln );
print STDERR
"Number of features matching threshold $database->{'threshold'} = "
. scalar(@$features) . "\n";
foreach my $f (@$features) {
if ( UNIVERSAL::isa( $f, "Bio::EnsEMBL::FeaturePair" )
&& defined( $f->hseqname ) )
{
push( @$fps, $f );
}
}
my $runnable =
Bio::EnsEMBL::Analysis::Runnable::Finished::HalfwiseHMM->new(
'-query' => $maskedslice,
'-features' => $fps,
'-pfamdb' => $self->getPfamDB(),
'-hmmdb' => $self->analysis->db_file,
'-options' => $self->analysis->parameters(),
'-program' => $self->analysis->program(),
'-analysis' => $self->analysis
);
$self->runnable($runnable);
# set the db version searched which is a concatenation of Uniprot and Pfam db versions
my $ana = $analysis_adaptor->fetch_by_logic_name($analysis_ln);
my $uniprot_db_version = $stateinfocontainer->fetch_db_version($self->input_id,$ana);
my $pfam_db_version = $self->get_db_version();
$self->db_version_searched(join('_',$uniprot_db_version,$pfam_db_version));
}
}
sub make_hash_from_meta_value {
my ( $self, $string ) = @_;
if ($string) {
my $hash = { eval $string };
if($@) {
die "error evaluating $string [$@]";
} else {
return $hash || {};
}
}
return {};
}
sub getPfamDB {
my ($self) = @_;
unless ( $self->{'_pfam_db'} ) {
my $pfam_meta = $self->db->get_MetaContainer();
my $value = $pfam_meta->list_value_by_key('pfam_db')
|| throw("please enter pfam_db key - value into meta table\n");
my $pfam_db_conn = $self->make_hash_from_meta_value( $value->[0] );
$pfam_db_conn->{-reconnect_when_connection_lost} = 1;
$pfam_db_conn->{-disconnect_when_inactive} = 1;
# Use the Blast tracking system to set the correct Pfam DB name
my $db_file_path = $self->analysis->db_file;
my $db_file_version = $self->get_db_version($db_file_path);
if ( $db_file_version =~ /^(\d+).(\d+)$/ ) {
$pfam_db_conn->{'-dbname'} = "pfam_$1_$2";
}
elsif ( $db_file_version =~ /^(\d+)$/ ) {
$pfam_db_conn->{'-dbname'} = "pfam_$1_0";
}
$self->{'_pfam_db'} =
Bio::EnsEMBL::DBSQL::DBConnection->new(%$pfam_db_conn);
# nb. there is not yet a db_handle (DBI connection)
}
return $self->{'_pfam_db'};
}
=head2 get_db_version
Title : get_db_version
[ distinguished from RunnableDB::*::db_version_searched() ]
Useage : $self->get_db_version('/data/base/path')
$obj->get_db_version()
Function: Set a blast database version from the supplied path
Get a blast database version from previously supplied path
Returns : String
Args : String (should be a full database path)
Caller : $self::fetch_databases()
RunnableDB::Finished_EST::db_version_searched()
=cut
sub get_db_version {
my ( $self, $db ) = @_;
my $ver = Bio::EnsEMBL::Analysis::Tools::BlastDBTracking::get_db_version_mixin(
$self, '_pfam_db_version', $db,
);
return $ver;
}
sub db_version_searched {
my ( $self, $arg ) = @_;
$self->{'_db_version_searched'} = $arg if $arg;
return $self->{'_db_version_searched'};
}
=head2 runnable
Arg : a Bio::EnsEMBL::Analysis::Runnable
Function : Gets/sets the runnable
Exception: throws if argument passed isn't a runnable
Caller :
Example :'
=cut
sub runnable {
my ( $self, $arg ) = @_;
if ( !defined( $self->{'_seqfetchers'} ) ) {
$self->{'_seqfetchers'} = [];
}
if ( defined($arg) ) {
throw("[$arg] is not a Bio::EnsEMBL::Analysis::Runnable")
unless $arg->isa("Bio::EnsEMBL::Analysis::Runnable");
push( @{ $self->{_runnable} }, $arg );
}
return @{ $self->{_runnable} };
}
sub run {
my ($self) = @_;
foreach my $runnable ( $self->runnable ) {
$runnable || throw("Can't run - no runnable object");
print STDERR "using " . $runnable . "\n";
eval { $runnable->run; };
if ( my $err = $@ ) {
chomp $err;
$self->failing_job_status($1)
if $err =~ /^\"([A-Z_]{1,40})\"$/i; # only match '"ABC_DEFGH"'
throw("$@");
}
}
$self->_convert_output();
}
=head2 write_output
Arg : none
Function : writes the converted output to the database as genes
Exception: none
Caller :
Example :
=cut
sub write_output {
my ($self) = @_;
my @times = times;
print STDERR "started writing @times \n";
my @genes = $self->output();
my $db = $self->db();
my $gene_adaptor = $db->get_GeneAdaptor;
my $sliceid = $self->input_id;
my $sa = $self->db->get_SliceAdaptor();
my $slice = $sa->fetch_by_name($sliceid);
my $dbh = $db->dbc->db_handle;
$dbh->begin_work;
eval {
# delete old genes first
foreach my $gene (@{$slice->get_all_Genes($self->analysis->logic_name)})
{
$gene_adaptor->remove($gene);
}
# now save new genes
foreach my $gene (@genes)
{
$gene_adaptor->store($gene,0);
}
$dbh->commit;
};
if ($@) {
$dbh->rollback;
throw("UNABLE TO WRITE GENES IN DATABASE\n[$@]\n");
}
@times = times;
print STDERR "finished writing @times \n";
return 1;
}
=head2 _convert_output
Arg : none
Function : takes the features from the halfwise runnable and runs _make_genes to convert them into Bio::EnsEMBL::Genes with appropriately attached exons and supporting evidence
Exception: thows if there are no analysis types
Caller :
Example :
=cut
sub _convert_output {
my ($self) = @_;
my @genes;
my $analysis = $self->analysis();
my $genetype = 'Halfwise';
# make an array of genes for each runnable
my @out;
foreach my $runnable ( $self->runnable ) {
push( @out, $runnable->output );
$self->pfam_lookup( $runnable->pfam_lookup )
if $runnable->can('pfam_lookup');
}
my @g = $self->_make_genes( $genetype, $analysis, \@out );
push( @genes, @g );
$self->output(@genes);
}
# get/set for lookup multi-valued hash { pfam_id => [pfam_acc, pfam_desc], ... }
# can append multiple to the lookup (see { %{$self->{'_pfam_lookup'}}, %{$hash_ref} })
sub pfam_lookup {
my ( $self, $hash_ref ) = @_;
if ( ref($hash_ref) eq 'HASH' ) {
$self->{'_pfam_lookup'} ||= {};
$self->{'_pfam_lookup'} =
{ %{ $self->{'_pfam_lookup'} }, %{$hash_ref} };
}
return $self->{'_pfam_lookup'};
}
=head2 _make_genes
Arg : runnable being run and analysis object being used
Function : converts the seqfeatures outputed by the runnable and actually converts them into Bio::EnsEMBL::Genes
Exception: none
Caller :
Example :
=cut
=head2 _make_genes
Title : make_genes
Usage : $self->make_genes
Function: makes Bio::EnsEMBL::Genes out of the output from runnables
Returns : array of Bio::EnsEMBL::Gene
Args : $genetype: string
$analysis_obj: Bio::EnsEMBL::Analysis
$results: reference to an array of FeaturePairs
=cut
sub _make_genes {
my ( $self, $genetype, $analysis_obj, $results ) = @_;
my $sliceid = $self->input_id;
my $sa = $self->db->get_SliceAdaptor();
my $slice = $sa->fetch_by_name($sliceid);
my @genes;
my $info_type = 'MISC';
my $info_text = 'Relationship generated from genewisedb search';
# fetch lookup multi-valued hash { pfam_id => [pfam_acc, pfam_desc], ... }
my $pfam_lookup = $self->pfam_lookup();
my $pfam_release = $self->get_db_version();
$self->_check_that_external_db_table_populated( $pfam_release, 'PFAM',
'XREF' );
foreach my $tmp_gene (@$results) {
my $pfam_id = $tmp_gene->seqname();
my $acc_ver = $pfam_lookup->{$pfam_id}->[0];
my @pfamacc_ver = split /\./, $acc_ver;
my $dbentry = Bio::EnsEMBL::DBEntry->new(
-primary_id => $pfamacc_ver[0],
-display_id => $pfam_id,
-version => $pfamacc_ver[1],
-release => $pfam_release,
-dbname => "PFAM",
-description => $pfam_lookup->{$pfam_id}->[1],
-info_type => $info_type,
-info_text => $info_text
);
$dbentry->status('XREF');
my $gene = Bio::EnsEMBL::Gene->new();
my $transcript =
$self->_make_transcript( $tmp_gene, $slice, $genetype,
$analysis_obj );
$gene->biotype($genetype);
$gene->analysis($analysis_obj);
$gene->add_Transcript($transcript);
# Add XRef to DBEntry list and as the display XREf to ensure
# compatibility with both old and new (GFF based) fetching for otterlace
$gene->add_DBEntry($dbentry);
$gene->display_xref($dbentry);
push( @genes, $gene );
}
return @genes;
}
sub _check_that_external_db_table_populated {
my ( $self, $release, $name, $status ) = @_;
$status ||= 'XREF';
my $db = $self->db();
my $find_tuple_sql = qq(SELECT count(*) AS tuple_exists
FROM external_db
WHERE db_name = ?
&& db_release = ?);
my $sth = $db->prepare($find_tuple_sql);
$sth->execute( $name, $release );
my $tuple = $sth->fetchrow_hashref() || {};
$sth->finish();
# if there is one return do nothing and the job can get on as normal
return if $tuple->{'tuple_exists'};
# else lock table external_db write
$sth = $db->prepare("LOCK TABLES external_db WRITE");
$sth->execute();
$sth->finish();
# get the next external_db_id
my $max_db_id_sql =
q`SELECT MAX(external_db_id) + 1 AS next_db_id from external_db`;
$sth = $db->prepare($max_db_id_sql);
$sth->execute();
my $row = $sth->fetchrow_hashref || {};
my $max_db_id = $row->{'next_db_id'} || warning "Error";
# insert the row
my $insert_sql =
q`INSERT INTO external_db (external_db_id, db_name, db_release, status, priority) VALUES(?, ?, ?, ?, 5)`;
$sth = $db->prepare($insert_sql);
$sth->execute( $max_db_id, $name, $release, $status );
$sth->finish();
# unlock tables;
$sth = $db->prepare("UNLOCK TABLES");
$sth->execute();
return $max_db_id;
}
=head2 _make_transcript
Title : make_transcript
Usage : $self->make_transcript($gene, $slice, $genetype)
Function: makes a Bio::EnsEMBL::Transcript from a SeqFeature representing a gene,
with sub_SeqFeatures representing exons.
Example :
Returns : Bio::EnsEMBL::Transcript with Bio::EnsEMBL:Exons(with supporting feature
data), and a Bio::EnsEMBL::translation
Args : $gene: Bio::EnsEMBL::SeqFeatureI, $contig: Bio::EnsEMBL::RawContig,
$genetype: string, $analysis_obj: Bio::EnsEMBL::Analysis
=cut
sub _make_transcript {
my ( $self, $gene, $slice, $genetype, $analysis_obj ) = @_;
$genetype = 'unspecified' unless defined($genetype);
unless ( $gene->isa("Bio::EnsEMBL::SeqFeatureI") ) {
print "$gene must be Bio::EnsEMBL::SeqFeatureI\n";
}
my $transcript = Bio::EnsEMBL::Transcript->new();
my $translation = Bio::EnsEMBL::Translation->new();
$transcript->translation($translation);
$transcript->analysis($analysis_obj);
my $excount = 1;
my @exons;
foreach my $exon_pred ( $gene->sub_SeqFeature ) {
# make an exon
my $exon = Bio::EnsEMBL::Exon->new();
my $sa = $slice->adaptor();
$exon->display_id( $sa->get_seq_region_id($slice) );
$exon->start( $exon_pred->start );
$exon->end( $exon_pred->end );
$exon->strand( $exon_pred->strand );
$exon->phase( $exon_pred->phase || 0 );
$exon->end_phase(0);
$exon->slice($slice);
# sort out supporting evidence for this exon prediction
foreach my $subf ( $exon_pred->sub_SeqFeature ) {
$subf->feature1->seqname( $slice->get_seq_region_id );
$subf->feature1->score(100);
$subf->feature1->analysis($analysis_obj);
$subf->feature2->score(100);
$subf->feature2->analysis($analysis_obj);
$exon->add_Supporting_Feature($subf);
}
push( @exons, $exon );
$excount++;
}
if ( @exons < 0 ) {
# printSTDERR "Odd. No exons found\n";
}
else {
if ( $exons[0]->strand == -1 ) {
@exons = sort { $b->start <=> $a->start } @exons;
}
else {
@exons = sort { $a->start <=> $b->start } @exons;
}
foreach my $exon (@exons) {
$transcript->add_Exon($exon);
}
$translation->start_Exon( $exons[0] );
$translation->end_Exon( $exons[$#exons] );
if ( $exons[0]->phase == 0 ) {
$translation->start(1);
}
elsif ( $exons[0]->phase == 1 ) {
$translation->start(3);
}
elsif ( $exons[0]->phase == 2 ) {
$translation->start(2);
}
$translation->end( $exons[$#exons]->end - $exons[$#exons]->start + 1 );
}
return $transcript;
}
=head2 output
Title : output
Usage :
Function: get/set for output array
Example :
Returns : array of Bio::EnsEMBL::Gene
Args :
=cut
sub output {
my ( $self, @genes ) = @_;
if ( !defined( $self->{'_output'} ) ) {
$self->{'_output'} = [];
}
if ( scalar(@genes) ) {
push( @{ $self->{'_output'} }, @genes );
}
return @{ $self->{'_output'} };
}
1;
| james-monkeyshines/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/RunnableDB/Finished/HalfwiseHMM.pm | Perl | apache-2.0 | 17,098 |
package VMOMI::ArrayOfDistributedVirtualSwitchKeyedOpaqueBlob;
use parent 'VMOMI::ComplexType';
use strict;
use warnings;
our @class_ancestors = ( );
our @class_members = (
['DistributedVirtualSwitchKeyedOpaqueBlob', 'DistributedVirtualSwitchKeyedOpaqueBlob', 1, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/ArrayOfDistributedVirtualSwitchKeyedOpaqueBlob.pm | Perl | apache-2.0 | 495 |
#!/usr/bin/env perl
#############################################################################
##
## File : build.pl
## Copyright : (c) David Harley 2010
## Project : qtHaskell
## Version : 1.1.4
## Modified : 2010-09-02 17:01:40
##
## Warning : this file is machine generated - do not modify.
##
#############################################################################
sub usage {
print "usage: perl build.pl [options]\n";
print "options:\n";
print " -c, [--[(only|no)-]]cpp enable/disable all cpp processing\n";
print " -h, [--[(only|no)-]](haskell|hsk) enable/disable all haskell processing\n";
print " -q, [--[(only|no)-]]qmake enable/disable qmake phase of cpp processing\n";
print " -m, [--[(only|no)-]](cpp-|c)make enable/disable make phase of cpp processing\n";
print " -f, [--[(only|no)-]]configure enable/disable cabal configure phase of haskell processing\n";
print " -b, [--[(only|no)-]]build enable/disable cabal build phase of haskell processing\n";
print " -i, [--[(only|no)-]]install enable/disable install phase of both cpp and haskell processing\n";
print " -y, [--[(only|no)-]](cpp-|c)install\n";
print " enable/disable install phase of cpp processing\n";
print " -z, [--[(only|no)-]]((haskell|hsk)-|h)install\n";
print " enable/disable cabal install phase of haskell processing\n";
print " -s, [--[(only|no)-]]samples enable/disable all sample code processing\n";
print " -e, [--[(only|no)-]]examples enable/disable example code processing\n";
print " -d, [--[(only|no)-]]demos enable/disable demo code processing\n";
print " -x, [--[(only|no)-]]extra-pkgs enable/disable all extra package code processing\n";
print " -r, [--[(only|no)-]](extra-pkgs-|x)configure\n";
print " enable/disable all extra package cabal configure phase\n";
print " -u, [--[(only|no)-]](extra-pkgs-|x)build\n";
print " enable/disable all extra package cabal build phase\n";
print " -w, [--[(only|no)-]](extra-pkgs-|x)install\n";
print " enable/disable all extra package cabal install phase\n";
print " -p, [--[(only|no)-]](extra-pkgs-|x)samples\n";
print " enable/disable all extra package sample code processing\n";
print " -l, [--[(only|no)-]](extra-pkgs-|x)examples\n";
print " enable/disable all extra package example code processing\n";
print " -o, [--[(only|no)-]](extra-pkgs-|x)demos\n";
print " enable/disable all extra package demo code processing\n";
print " [--[(only|no)-]]cpp-clean enable/disable cpp cleaning\n";
print " [--[(only|no)-]](haskell|hsk)-clean\n";
print " enable/disable haskell cleaning\n";
print " [--[(only|no)-]]samples-clean enable/disable samples cleaning\n";
print " [--[(only|no)-]]examples-clean enable/disable examples cleaning\n";
print " [--[(only|no)-]]demos-clean enable/disable demos cleaning\n";
print " [--[(only|no)-]]extra-pkgs-clean\n";
print " enable/disable cleaning of all phases of extra package code\n";
print " [--[(only|no)-]](extra-pkgs-|x)build-clean\n";
print " enable/disable cleaning of cabal build phase of extra package code\n";
print " [--[(only|no)-]](extra-pkgs-|x)samples-clean\n";
print " enable/disable cleaning of all extra package samples code\n";
print " [--[(only|no)-]](extra-pkgs-|x)examples-clean\n";
print " enable/disable cleaning of all extra package examples code\n";
print " [--[(only|no)-]](extra-pkgs-|x)demos-clean\n";
print " enable/disable cleaning of all extra package demo code\n";
print " [--[(only|no)-]](extra-pkgs=packagename[options][,packagename[options]]+\n";
print " sets above options for extra packages on a per package basis (using single letter sequences)\n";
print " -j[[ ]jobs], --jobs=jobs set j/jobs option for makefile processing in all phases\n";
print " -jc[[ ]jobs], --(cpp-|c)jobs=jobs\n";
print " set j/jobs option for makefile processing in cpp build phase\n";
print " -jh[[ ]jobs], --((haskell|hsk)-|h)jobs=jobs\n";
print " set j/jobs option for makefile processing in haskell build phase\n";
print " -v[[ ]level], --verbose=level set verbosity level in all phases\n";
print " -vc[[ ]level], --(cpp-|c)verbose=level\n";
print " set verbosity level in cpp phase\n";
print " -vh[[ ]level], --((haskell|hsk)-|h)verbose=level\n";
print " set verbosity level in haskell phase\n";
print " --[no-]sudo enable/disable sudo command for cpp and haskell install phases on non-windows systems. Enabled by default\n";
print " --[no-]cpp-sudo enable/disable sudo command for cpp install phase on non-windows systems. Enabled by default\n";
print " --[no-](haskell|hsl)-sudo enable/disable sudo command for haskell install phase on non-windows systems. Enabled by default unless --user flag is enabled\n";
print " --[no-]ldconfig enable/disable ldconfig command for cpp and install phases on non-windows systems. Enabled by default\n";
print " --[no-]user enable/disable --user flag for haskell cabal configure command. Disabled by default\n";
print " --(disable|enable)-shared enable/disable build of dynamic linking package (currently linux only). Disabled by default\n";
print " --(disable|enable)-ld enable/disable full ld build on windows (disabled by default as very slow)\n";
print " --[no-](extra-|x)ld-opt=ldoption sets extra ld option to pass to haskell build makefile\n";
print "Notes: All configure, build and install phases are enabled by default.\n";
print " The first phase control flag encountered, if not prefixed by \"--no-,\n";
print " -- or -n in a single letter sequence\" will negate all other phase\n";
print " control flags.\n";
print " Similarly a phase control flag prefixed by \"--only-\" will negate\n";
print " all other phase control flags whenever it is encountered.\n";
print " Single letter phase control flags can be combined into one sequence.\n";
print "Examples:\n";
print " build demos - will only build demo programs.\n";
print " build -d or build --only-demos - will also only build demo programs.\n";
print " build -nd or build --no-demos - will build everything except demo programs.\n";
print " build -ncs will disable all cpp and sample code phases.\n";
}
if ($ARGV[0] eq "--help") {
usage;
exit;
}
use Cwd;
use File::Copy;
use feature switch;
my $iswin = ($^O eq "MSWin32") ? 1 : 0;
my $islinux = ($^O ne "MSWin32") ? 1 : 0;
my $ismacos = (($^O eq "MacOS") || ($^O eq "rhapsody") || ($^O eq "darwin")) ? 1 : 0;
my $gvl = 1;
my $cgvl = 1;
my $hgvl = 1;
my $in_cpp = 0;
my $in_hsk = 0;
my $qhc = "";
my $cj = "";
my $hj = "";
my %xp = ();
my $ep = "extra-pkgs";
my $xpu = 1;
my $xp_no = 0b0111111111;
my $xp_na = 0b1011111111;
my $xp_nc = 0b1101111111;
my $xp_nb = 0b1110111111;
my $xp_ni = 0b1111011111;
my $xp_ne = 0b1111101111;
my $xp_nd = 0b1111110111;
my $xp_ncc = 0b1111111011;
my $xp_nce = 0b1111111101;
my $xp_ncd = 0b1111111110;
my $xp_o = 0b1000000000;
my $xp_a = 0b0100000000;
my $xp_c = 0b0010000000;
my $xp_b = 0b0001000000;
my $xp_i = 0b0000100000;
my $xp_e = 0b0000010000;
my $xp_d = 0b0000001000;
my $xp_cc = 0b0000000100;
my $xp_ce = 0b0000000010;
my $xp_cd = 0b0000000001;
my $in_xp = 0;
my @xsl = ();
my $cfusr = "";
sub pv {
my ($vl, $ps) = @_;
if (((not $in_cpp) || (($gvl >= $vl) && ($cgvl == -1)) || ($cgvl >= $vl)) && ((not $in_hsk) || (($gvl >= $vl) && ($hgvl == -1)) || ($hgvl >= $vl))) {
print "$ps\n";
}
}
sub sys_ds {
my ($cds) = @_;
if ($iswin) {
$cds =~ s/\//\\/g;
}
pv(2, $cds);
system ($cds) == 0 or die "$cds: $!\n";
}
sub sys_ds_pmf {
my ($mk, $mk612, $xld, $hp, $hpv, $vogl, $vbse, $vh98, $vw, $way, $ar, $ld, $clean) = @_;
my $cfuyn = $cfusr eq "--user" ? "" : "-no-user-package-conf";
sys_ds "$mk$hj -f $mk612 CFUSR=$cfuyn EXTRA_LD_OPTS=$xld GHC=$hp GHC_VERSION=$hpv OpenGL_VERSION=$vogl base_VERSION=$vbse haskell98_VERSION=$vh98 VANILLA_WAY=$vw $way AR=$ar LD=$ld $clean";
}
sub cbtod {
my ($rv, $btc) = @_;
chomp ($$rv = `$btc`) or die "$btc $!\n";
}
sub cdod {
my ($nd) = @_;
chdir "$nd" or die "can't change to directory $nd: $!\n";
}
sub cdup {
chdir ".." or die "..: $!\n";
}
sub od_ds {
my ($dh, $ds) = @_;
opendir ($$dh, $ds) or die "can't opendir $ds: $!\n";
}
sub ul_ds {
my ($fn) = @_;
if (-e $fn) {unlink $fn or die "can't unlink $fn: $!\n"}
}
sub qbe {
my ($dr, $dn) = @_;
$dn = defined $dn ? $dn : $dr;
od_ds \my $dh, $dr;
my @hs = grep { s/(.*)\.hs/$1/ } readdir($dh);
closedir $dh;
cdod $dr;
if ($#hs >= 0) {
print "building $dn for qt-1.1.4\n";
foreach (sort @hs) {
print "\. $_\n";
sys_ds("$qhc $_ -v0");
}
}
cdup;
}
sub qbex {
my ($d1, $d2) = @_;
if (-d "$d1/$d2") {
cdod $d1;
qbe "$d2","$d1/$d2";
cdup;
}
}
sub cln_hsa {
my ($dr) = @_;
od_ds \my $dh, $dr;
my @hs = grep { s/(.*)\.hs/$1/} readdir($dh);
closedir $dh;
cdod $dr;
foreach (@hs) {
if ($iswin) {
ul_ds "$_.exe";
} else {
ul_ds $_;
}
ul_ds "$_.hi";
ul_ds "$_.o";
}
cdup;
}
sub cln_dsa {
my ($dr) = @_;
cln_hsa $dr;
od_ds \my $dh, $dr;
my @ds = grep { /^[^.].*/ && -d "$dr/$_" && (not exists $xp{$_})} readdir($dh);
closedir $dh;
cdod $dr;
foreach my $ccd (@ds) {
cln_dsa($ccd);
}
cdup;
}
sub cln_dsax {
my ($d1, $d2) = @_;
if (-d "$d1/$d2") {
cdod $d1;
cln_dsa $d2;
cdup;
}
}
my $isdynos = $islinux ? 1 : 0;
my $sudo = "sudo";
my $sudoc = not $iswin;
my $cppsudoc = not $iswin;
my $hsksudoc= -1;
my $cppsudo = "";
my $hsksudo = "";
my $ldconfig = ($iswin || $ismacos) ? "" : "ldconfig";
my $cd = getcwd; $cd =~ s/\//\\/g if $iswin;
my $cdir = "qws";
my $rgSu = "cabal";
my $cfn = "qt\.cabal";
my $winmk = "mingw32-make";
my $lingmk = "gmake";
my $linmk = "make";
my $mk = "";
my $mk612 = "";
my $mk612d = "";
if ($iswin) {
my @makeversion = split /\n/, `$winmk --version 2>&1`;
if ($makeversion[0] =~ m/^GNU Make \d+\.\d+$/) {
$mk = $winmk;
}
else { die "$winmk not found" }
$mk612 = "Makefile_612px_MSWin32";
}
else {
my @makeversion = split /\n/, `$lingmk --version 2>&1`;
if ($makeversion[0] =~ m/^GNU Make \d+\.\d+$/) {
$mk = $lingmk;
}
else {
@makeversion = split/\n/, `$linmk --version 2>&1`;
print "$makeversion[0]\n";
if ($makeversion[0] =~ m/^(.+)ake \d+\.\d+$/) {
$mk = $linmk;
}
else { die "neither $lingmk nor $linmk found" }
}
$mk612 = "Makefile_612px";
$mk612d = "Makefile_612pxd";
}
my $ghc = "ghc";
my $ghcv = "";
my $ghcmv = "";
my $ghcsv = "";
my $ghcdv = 0;
my $ghcfv = 0;
my @ghcversion = split /\n/, `$ghc --version 2>&1`;
if ($ghcversion[0] =~ m/^The Glorious Glasgow Haskell Compilation System, version ((\d+)\.(\d+)\.\d+)$/) {
$ghcv = $1;
$ghcmv = $2;
$ghcsv = $3;
die "$ghc version $ghcv too old" if (($ghcmv < 6) || (($ghcmv == 6) && ($ghcsv < 8)));
$ghcdv = (($ghcmv >= 6) && ($ghcsv >= 12)) ? 1 : 0;
$ghcfv = (($ghcmv >= 6) && ($ghcsv < 12)) ? 1 : 0;
}
else { die "$ghc not found" };
my $ghclib = `$ghc --print-libdir`;
if ($ghclib =~ m/(.*)lib$/) {
$ghclib = $1;
} else {
$ghclib = "";
}
my $ghcmng = "";
my $mngbd = "mingw\\bin";
my $are = "ar.exe";
my $lde = "ld.exe";
my $mngar = "ar";
my $mngld = "ld";
if ($iswin && not $ghcfv) {
if (not -d $ghclib) {die "$ghclib not found: $!\n"};
$ghcmng = $ghclib . $mngbd;
if (not -d $ghcmng) {die "$ghcmng not found: $!\n"};
$mngar = $ghcmng . "\\" . $are;
if (not -e $mngar) {die "$mngar not found: $!\n"};
$mngld = $ghcmng . "\\" . $lde;
if (not -e $mngld) {die "$mngld not found: $!\n"};
}
my $hp = "ghc";
if ($islinux) {cbtod \$hp, "which ghc"}
my $rgfSu = $rgSu; $rgfSu =~ s/runghc/runghc -f $hp/;
cbtod \my $hpv, "cabal exec -- ghc --numeric-version";
cbtod \my $vogl, "cabal exec -- ghc-pkg latest OpenGL";
cbtod \my $vbse, "cabal exec -- ghc-pkg latest base";
cbtod \my $vh98, "cabal exec -- ghc-pkg latest haskell98";
if ($iswin) {
my $eld = "Extra-lib-dirs";
open(CFH, '<', $cfn) or die "$cfn not found";
my @cls = <CFH>;
close CFH;
if ($cls[$#cls] !~ m/^$eld: .*/) {
open(CFH, ">>", $cfn) or die "$cfn not found";
print CFH "$eld: $cd\\$cdir\\bin\n";
close CFH;
}
}
if ($iswin) {
$ENV{PATH} = "$cd\\qws\\bin;$cd\\bin;" . $ENV{PATH};
$qhc = "call qhcc";
} else {
$qhc = "$cd/bin/qhc";
}
sub get_xps {
my $dr = "$cd/$ep";
od_ds \my $dh, $dr;
my @ds = grep { /^[A-Z].*/ && -d "$dr/$_" } readdir($dh);
closedir $dh;
foreach my $ccd (@ds) {
$xp{$ccd} = 0b1000000000;
}
}
get_xps;
my $cpp = 1;
my $hsk = 1;
my $xxx = 1;
my $qmk = 1;
my $spec = $ismacos ? "-spec macx-g++" : "";
my $cmk = 1;
my $cin = 1;
my $dst = "";
my $vs = 0;
my $cvs = 0;
my $hvs = 0;
my $tgvl = 1;
my $tcgvl = -1;
my $thgvl = -1;
my $jt1 = "";
my $jt2 = "";
my $cjt1 = "";
my $cjt2 = "";
my $hjt1 = "";
my $hjt2 = "";
my $con = 1;
my $bld = 1;
my $hin = 1;
my $ins = 1;
my $rs = 0;
my $rsp = "";
my $rx = 1;
my $rxx = 1;
my $rd = 1;
my $rxp = 1;
my $cln = 0;
my $ccln = 0;
my $hcln = 0;
my $bcln = 0;
my $ecln = 0;
my $eecln = 0;
my $dcln = 0;
my $xcln = 0;
my $only = 0;
my $ssonly = 1;
my $sxonly = 1;
my $rxw = 1;
my $rxu = 1;
my $rxr = 1;
my $rxe = 1;
my $rxd = 1;
my $rxc = 0;
my $rxcd = 0;
my $rxce = 0;
my $weld = 0;
my $weld = 0;
my $xld = $ismacos ? "'-arch x86_64'" : "";
my %kwh = ( "c" => "cpp",
"h" => "haskell",
"q" => "qmake",
"m" => "cmake",
"M" => "cpp-clean",
"y" => "cinstall",
"f" => "configure",
"b" => "build",
"B" => "haskell-clean",
"z" => "hinstall",
"i" => "install",
"s" => "samples",
"S" => "samples-clean",
"e" => "examples",
"E" => "examples-clean",
"d" => "demos",
"D" => "demos-clean",
"x" => "extra-pkgs",
"X" => "extra-pkgs-clean",
"w" => "xinstall",
"u" => "xbuild",
"U" => "xbuild-clean",
"r" => "xconfigure",
"p" => "xsamples",
"P" => "xsamples-clean",
"o" => "xexamples",
"O" => "xexamples-clean",
"l" => "xdemos",
"L" => "xdemos-clean"
);
sub oo {
my ($gv) = @_;
$$gv = $only ? 1 : $$gv;
}
sub coo {oo \$cpp};
sub hoo {oo \$hsk};
sub xoo {oo \$xxx};
sub sto {
my($rv) = @_;
$cpp = $hsk = $qmk = $cmk = $cin = $con = $bld = $ins = $hin = $rv;
$rx = $rd = $rxp = $rxx = $rv;
if ($rv == 0) {
$cln = $hcln = $bcln = $ecln = $eecln = $dcln = $xcln = $rv;
}
}
sub stox {
my($rv) = @_;
$rxw = $rxu = $rxr = $rxe = $rxd = $rv;
if ($rv == 0) {
$rxce = $rxcd = $rv;
}
}
sub pp {
my ($d2, $no) = @_;
my $fnd = 1;
$d2 =~ s/hsk/haskell/;
$d2 =~ s/cpp-install/cinstall/;
$d2 =~ s/haskell-install/hinstall/;
$d2 =~ s/extra-pkgs-install/xinstall/;
$d2 =~ s/extra-pkgs-build/xbuild/;
$d2 =~ s/extra-pkgs-build-clean/xbuild-clean/;
$d2 =~ s/extra-pkgs-configure/xconfigure/;
$d2 =~ s/extra-pkgs-samples/xsamples/;
$d2 =~ s/extra-pkgs-samples-clean/xsamples-clean/;
$d2 =~ s/extra-pkgs-examples/xexamples/;
$d2 =~ s/extra-pkgs-examples-clean/xexamples-clean/;
$d2 =~ s/extra-pkgs-demos/xdemos/;
$d2 =~ s/extra-pkgs-demos-clean/xdemos-clean/;
given($d2) {
when("cpp") {$cpp = $no}
when("haskell") {$hsk = $no}
when("qmake") {$qmk = $no; coo}
when("cmake") {$cmk = $no; coo}
when("cinstall") {$cin = $no; $ins = $no ? 1 : $ins; coo}
when("configure") {$con = $no; hoo}
when("build") {$bld = $no; hoo}
when("hinstall") {$hin = $no; $ins = $no ? 1 : $ins; hoo}
when("install") {
$cin = $hin = $ins = $no;
coo; hoo;
}
when("sudo") {
if (not $iswin) {$sudoc = $no ? 1 : 0}
}
when("cpp-sudo") {
if (not $iswin) {$cppsudoc = $no ? 1 : 0}
}
when("haskell-sudo") {
if (not $iswin) {$hsksudoc = $no ? 1 : 0}
}
when("ldconfig") {
if (not $iswin) {$ldconfig = $no ? "ldconfig" : ""}
print "$ldconfig\n";
}
when("user") {
if (not $iswin) {$cfusr = $no ? "--user" : ""}
}
when("samples") {
if ($no) {$rx = $rd = $rxp = $rxx = 1}
else {$rx = $rd = $rxp = $rxx = 0}
hoo;
}
when("examples") {
if ($no) {$rx = $rxx = 1}
else {$rxx = 0}
hoo;
}
when("demos") {
if ($no) {$rd = $rx = 1}
else {$rd = 0}
hoo;
}
when("extra-pkgs") {
if ($no) {$rxp = $rx = 1}
else {$rxp = 0}
hoo;
}
when("xconfigure") {
if ($no) {$rxp = $rx = $rxr = 1}
else {$rxr = 0}
hoo;
}
when("xbuild") {
if ($no) {$rxp = $rx = $rxu = 1}
else {$rxu = 0}
hoo;
}
when("xinstall") {
if ($no) {$rxp = $rx = $rxw = 1}
else {$rxw = 0}
hoo;
}
when("xsamples") {
if ($no) {$rxp = $rx = $rxe = $rxd = 1}
else {$rxe = $rxd = 0}
hoo;
}
when("xexamples") {
if ($no) {$rxp = $rx = $rxe = 1}
else {$rxe = 0}
hoo;
}
when("xdemos") {
if ($no) {$rxp = $rx = $rxd = 1}
else {$rxd = 0}
hoo;
}
when("clean") {
if ($no) {$cln = $ccln = $hcln = $bcln = $ecln = $eecln = $dcln = $xcln = 1}
else {$cln = 0}
coo; hoo;
}
when("cpp-clean") {
if ($no) {$cln = $ccln = 1}
else {$ccln = 0}
coo;
}
when("haskell-clean") {
if ($no) {$cln = $hcln = $bcln = $ecln = $eecln = $dcln = $xcln = 1}
else {$hcln = 0}
hoo;
}
when("samples-clean") {
if ($no) {$cln = $hcln = $ecln = $eecln = $dcln = $xcln = 1}
else {$ecln = 0}
hoo;
}
when("examples-clean") {
if ($no) {$cln = $hcln = $ecln = $eecln = 1}
else {$eecln = 0}
hoo;
}
when("demos-clean") {
if ($no) {$cln = $hcln = $ecln = $dcln = 1}
else {$dcln = 0}
hoo;
}
when("extra-pkgs-clean") {
if ($no) {$cln = $hcln = $ecln = $xcln = $rxc = $rxce = $rxcd = 1}
else {$xcln = 0}
hoo;
}
when("xbuild-clean") {
if ($no) {$cln = $hcln = $ecln = $xcln = $rxc = 1}
else {$rxc = 0}
hoo;
}
when("xsamples-clean") {
if ($no) {$cln = $hcln = $ecln = $xcln = $rxce = $rxcd = 1}
else {$rxce = $rxcd = 0}
hoo;
}
when("xexamples-clean") {
if ($no) {$cln = $hcln = $ecln = $xcln = $rxce = 1}
else {$rxce = 0}
hoo;
}
when("xdemos-clean") {
if ($no) {$cln = $hcln = $ecln = $xcln = $rxcd = 1}
else {$rxcd = 0}
hoo;
}
default {$fnd = 0;}
}
return $fnd;
}
sub sos {
my ($dst, $nv, $nj) = @_;
my $s2 = "-" . (substr $dst, 0, 1);
given($dst) {
when("v") {$tgvl = $nv}
when("vc") {$tcgvl = $nv}
when("vh") {$thgvl = $nv}
when("j") {$jt1 = $s2; $jt2 = $nj}
when("jc") {$cjt1 = $s2; $cjt2 = $nj}
when("jh") {$hjt1 = $s2; $hjt2 = $nj}
}
}
foreach my $arg (@ARGV) {
if ($arg =~ m/^\d+$/) {
sos $dst, $arg, $arg;
$dst = ""; next;
}
$dst = "";
if ($arg =~ m/^-(v|j)(c|h)?(\d*)$/) {
my $ot = $1.$2;
my $nv = $3 ? $3 : 1;
my $nj = $3 ? $3 : "";
sos $ot, $nv, $nj;
$dst = $3 ? "" : $ot; next;
}
elsif ($arg =~ m/^--(?<t1>c|h|((cpp|hsk|haskell)-))?(?<t2>verbose|jobs)(=(?<t3>\d+))?$/) {
my $t1 = $+{t1};
my $t2 = $+{t2};
my $t3 = $+{t3};
$t1 =~ s/-//;
$t1 =~ s/cpp/c/;
$t1 =~ s/hsk/h/;
$t1 =~ s/haskell/h/;
given($t2) {
when("verbose") {
my $cvl = $t3 ? $t3 : 1;
given($t1) {
when(/^$/) {$tgvl = $cvl}
when("c") {$tcgvl = $cvl}
when("h") {$thgvl = $cvl}
}
}
when("jobs") {
given($t1) {
when(/^$/) {$jt1 = $arg; $jt2 = ""}
when("c") {$cjt1 = $arg; $cjt2 = ""}
when("h") {$hjt1 = $arg; $hjt2 = ""}
}
}
}
next;
}
if ($arg =~ m/^--(no-|only-)?([a-z|\-]+)(=[a-z|A-Z|,|\-]+)?$/) {
my $sx = 0;
my $p1 = $1;
my $p2 = $2;
my $p3 = $3;
if ($p2 =~ m/^x/) {
$sx = 1;
}
my $no = ($p1 eq "no-") ? 0 : 1;
$only = ($p1 eq "only-") ? 1 : 0;
if (($p2 =~ m/^extra-pkgs$/) && ($p3 =~ m/^=([a-z|A-Z].*)$/)) {
if ($only) {
sto 0;
stox 0;
}
my $p1 = 1;
@xsl = split /,/, $1;
my $lonly = 1;
foreach my $csl (sort @xsl) {
my @cssl = split /-/, $csl;
my $cpkg = $cssl[0];
if (exists $xp{$cpkg}) {
if (($sxonly && $xpu && $no) || ($only && $lonly)) {
foreach my $ocsl (sort @xsl) {
$xp{$cpkg} &= $xp_na;
}
}
$xpu = 0;
$lonly = 0;
my $cs = $#cssl;
my $cv = $xp{$cpkg};
my $co = $cv & $xp_o;
if ($co) {
if (($cs == 0) || (($cs > 0) && ($cssl[1] =~ m/^n/))) {
$cv = $xp_no;
} elsif (not $sxonly) {
$cv |= $xp_c if $rxr;
$cv |= $xp_b if $rxu;
$cv |= $xp_i if $rxw;
$cv |= $xp_e if $rxe;
$cv |= $xp_d if $rxd;
$cv |= $xp_cc if $rxc;
$cv |= $xp_ce if $rxce;
$cv |= $xp_cd if $rxcd;
}
$cv &= $xp_no;
$co = $cv & $xp_o;
}
$cv = $no ? $cv | $xp_a : $cv & $xp_na;
my $i = 0;
for ($i = 1; $i <= $cs; $i++) {
my $csl = $cssl[$i];
if ($csl !~ m/^(n)?([wurplo|UPLO]+)$/) {
last;
} else {
my $ln = $1 ? 1 : 0;
my $lv = $2;
foreach my $cp (split //, $lv) {
given($cp) {
when(/^w$/) {$cv = $ln ? $cv & $xp_ni : $cv | $xp_i}
when(/^u$/) {$cv = $ln ? $cv & $xp_nb : $cv | $xp_b}
when(/^r$/) {$cv = $ln ? $cv & $xp_nc : $cv | $xp_c}
when(/^p$/) {$cv = $ln ? $cv & $xp_ne & $xp_nd : $cv | $xp_e | $xp_d}
when(/^o$/) {$cv = $ln ? $cv & $xp_ne : $cv | $xp_e}
when(/^l$/) {$cv = $ln ? $cv & $xp_ne : $cv | $xp_d}
when(/^U$/) {$cv = $ln ? $cv & $xp_ncc & $xp_nb : $cv | $xp_cc | $xp_b}
when(/^P$/) {$cv = $ln ? $cv & $xp_nce &$xp_ncd & $xp_ne & $xp_nd : $cv | $xp_ce | $xp_cd | $xp_e | $xp_d}
when(/^O$/) {$cv = $ln ? $cv & $xp_nce & $xp_ne : $cv | $xp_ce | $xp_e}
when(/^L$/) {$cv = $ln ? $cv & $xp_ncd & $xp_nd : $cv | $xp_cd | $xp_d}
}
if (not $ln) {
pp $kwh{$cp}, 1;
if ($cp =~ m/[UPLO]/) {
pp $kwh{lc $cp}, 1;
}
}
}
}
}
$p1 = ($p1 && ($i > $cs)) ? 1 : 0;
$xp{$cpkg} = $cv if $p1;
} else {
$p1 = 0;
}
}
$ssonly = 0;
$sxonly = 0;
if ($p1) {
next if pp $p2, $no;
}
}
elsif ($no && ($p2 eq "all")) {
sto 1; next;
} else {
sto 0 if ($only || ((not $no) && ($p2 eq "all")));
stox 0 if ($only && $sx);
next if pp $p2, $no;
}
$ssonly = 0;
$sxonly = 0 if $sx;
}
elsif ($arg =~ m/^(-)?([a-z|A-Z][a-z|A-Z|\-]*)$/) {
$no = 1;
$only = 1;
my $ls = $1 ? 1 : 0;
my $ckw = $2;
my $sx = 0;
if (($ls && $ckw =~ m/[wuUrpPoOlL]/) || ((not $ls) && $ckw =~ m/^x/)) {
$sx = 1;
}
if ($ls && $ckw =~ m/^n([a-z|A-Z]+)$/) {
$ckw = $1;
$no = 0;
$only = 0;
} else {
sto 0 if $ssonly;
if ($sx) {
stox 0 if $sxonly;
}
}
$ssonly = 0;
$sxonly = 0 if $sx;
if (not $ls) {
if (pp $ckw, 1) {
next;
}
}
elsif ($ckw =~ m/^[qmMcfbBhisSeEdDxXyzwuUrpPlLoO]+$/) {
foreach my $cc (split //, $ckw) {
pp $kwh{$cc}, $no;
if ($cc =~ m/[MBSEDXUPLO]/) {
pp $kwh{lc $cc}, $no;
}
}
next;
}
}
if ($isdynos && ($arg =~ m/^--(disable|enable)-shared$/)) {
if ($1 eq "disable") {$rs = 0}
elsif ($1 eq "enable") {$rs = 1}
next;
}
if ($iswin && ($arg =~ m/^--(disable|enable)-ld$/)) {
if ($1 eq "disable") {$weld = 0}
elsif ($1 eq "enable") {$weld = 1}
next;
}
$arg =~ s/extra-ld-opt/xld-opt/;
if ($arg =~ m/^--(no-)?xld-opt(=(.*))?$/) {
if ($1 && not $2) {
$xld = "";
next;
} elsif ($2 && not $1) {
$xld .= " " if ($xld ne "");
$xld .= $3;
next;
}
}
usage;
die "unrecognized parameter $arg\n";
}
if ($sudoc && $cppsudoc) {
$cppsudo = $sudo;
}
if ($sudoc && (($hsksudoc > 0) || (($hsksudoc == -1) && ($cfusr eq "")))) {
$hsksudo = $sudo;
}
$gvl = $tgvl;
$cgvl = $tcgvl;
$hgvl = $thgvl;
if ($jt1 ne "") {
if ($cjt1 eq "") {
$cjt1 = $jt1;
$cjt2 = $jt2;
}
if ($hjt1 eq "") {
$hjt1 = $jt1;
$hjt2 = $jt2;
}
}
$cj = $cjt2 ? "$cjt1 $cjt2" : $cjt1;
$hj = $hjt2 ? "$hjt1 $hjt2" : $hjt1;
$cj = $cj ? " $cj" : $cj;
$hj = $hj ? " $hj" : $hj;
$rsp = "--enable-shared" if $rs == 1;
if ($ghcdv && $rs) {
$qhc .= "d";
}
print "building qtHaskell-1.1.4\n";
if ($cpp) {
$in_cpp = 1; $in_hsk = 0;
cdod "$cdir";
if ($cln && $ccln) {
sys_ds "$mk$cj clean";
}
if ($qmk) {
sys_ds "qmake $spec -recursive";
}
if ($cmk) {
sys_ds "$mk$cj release";
}
if ($islinux && $ins && $cin) {
sys_ds "$cppsudo $mk$cj install";
if ($ldconfig) {
cbtod \my $tldc, "$cppsudo which $ldconfig";
sys_ds "$cppsudo $tldc";
}
}
cdup;
}
if ($hsk) {
$in_cpp = 0; $in_hsk = 1;
if ($cln && $hcln && $bcln) {
if ((not $ghcfv) or $iswin) {
sys_ds_pmf $mk, $mk612, $xld, $hp, $hpv, $vogl, $vbse, $vh98, "YES", "", $mngar, $mngld, "clean";
if ($ghcdv && $rs) {
sys_ds_pmf $mk, $mk612d, $xld, $hp, $hpv, $vogl, $vbse, $vh98, "NO", "way=dyn", $mngar, $mngld, "clean";
}
}
else {
sys_ds "$mk$hj EXTRA-LD-OPTS=$xld VANILLA_WAY=YES clean";
if (-e "Makefile") {unlink "Makefile"};
}
}
if ($con) {
sys_ds "$rgSu configure $cfusr $rsp";
if ((not $ghcfv) or $iswin) {
my $at = my $mt = time;
utime $at, $mt, $mk612 or die "utime $mk612: $!\n";
if ($ghcdv && $rs) {
utime $at, $mt, $mk612d or die "utime $mk612d: $!\n";
}
}
}
if ($bld) {
if ((not $ghcfv) or $iswin) {
sys_ds_pmf $mk, $mk612, $xld, $hp, $hpv, $vogl, $vbse, $vh98, "YES", "", $mngar, $mngld;
if ($ghcdv && $rs) {
sys_ds_pmf $mk, $mk612d, $xld, $hp, $hpv, $vogl, $vbse, $vh98, "NO", "way=dyn", $mngar, $mngld;
}
if ($iswin && $weld) {
sys_ds "$rgSu build";
}
}
else {
if (-e "Makefile") {unlink "Makefile"};
sys_ds "$rgSu build";
sys_ds "$rgSu install";
# sys_ds "$mk$hj EXTRA-LD-OPTS=$xld VANILLA_WAY=YES";
}
}
if ($ins && $hin) {
if (not $iswin) {
sys_ds "$hsksudo $rgfSu install";
}
else {
sys_ds "$rgSu install";
}
}
if ($cln && $hcln && $ecln) {
if ($eecln) {
cln_dsa("examples");
}
if ($dcln) {
cln_dsa("demos");
}
if ($xcln) {
cdod $ep;
foreach my $cdd (sort (keys %xp)) {
my $xpv = $xp{$cdd};
my $xpa = $xpv & $xp_a;
if ($rxc && ($xpu || ($xpa && ($xpv & $xp_cc)))) {
cdod $cdd;
sys_ds "$rgSu clean";
cdup;
}
}
cdup;
foreach my $cdd (sort keys %xp) {
my $xpv = $xp{$cdd};
my $xpa = $xpv & $xp_a;
if ($xpu || $xpa) {
if ($rxce && ($xpu || ($xpa && ($xpv & $xp_ce)))) {
cln_dsax "examples", $cdd;
}
if ($rxcd && ($xpu || ($xpa && ($xpv & $xp_cd)))) {
cln_dsax "demos", $cdd;
}
}
}
}
}
if ($rx) {
cbtod \my $ql, "ghc-pkg latest qt";
$ql == "qt-1.1.4" or die "qt-1.1.4 not found: $!\n";
if ($rxx) {
qbe "examples";
}
if ($rd) {
qbe "demos";
}
if ($rxp) {
cdod "$cd/$ep";
foreach my $cdd (sort keys %xp) {
my $xpv = $xp{$cdd};
my $xpa = $xpv & $xp_a;
if ($xpu || $xpa) {
cdod $cdd;
if ($rxr && ($xpu || ($xpa && ($xpv & $xp_f)))) {
sys_ds "$rgSu configure $cfusr $rsp";
}
if ($rxu && ($xpu || ($xpa && ($xpv & $xp_b)))) {
sys_ds "$rgSu build";
}
if ($rxw && ($xpu || ($xpa && ($xpv & $xp_i)))) {
if (not $iswin) {
sys_ds "$hsksudo $rgfSu install";
} else {
sys_ds "$rgSu install";
}
}
cdup;
}
}
cdup;
foreach my $cdd (sort keys %xp) {
my $xpv = $xp{$cdd};
my $xpa = $xpv & $xp_a;
if ($xpu || $xpa) {
if ($rxe && ($xpu || ($xpa && ($xpv & $xp_e)))) {
qbex "examples","Glome";
}
if ($rxd && ($xpu || ($xpa && ($xpv & $xp_d)))) {
qbex "demos","Glome";
}
}
}
}
}
}
| keera-studios/hsQt | build.pl | Perl | bsd-2-clause | 28,076 |
=head1 webminlog-lib.pl
This module contains functions for parsing the Webmin actions log file.
foreign_require("webminlog", "webminlog-lib.pl");
@actions = webminlog::list_webmin_log(undef, "useradmin", undef, undef);
foreach $a (@actions) {
print webminlog::get_action_description($a),"\n";
}
=cut
BEGIN { push(@INC, ".."); };
use strict;
use warnings;
use WebminCore;
&init_config();
our %access = &get_module_acl();
our %access_mods = map { $_, 1 } split(/\s+/, $access{'mods'});
our %access_users = map { $_, 1 } split(/\s+/, $access{'users'});
our %parser_cache;
our (%text, $module_config_directory, $root_directory, $webmin_logfile);
=head2 list_webmin_log([only-user], [only-module], [start-time, end-time])
Returns an array of matching Webmin log events, each of which is a hash ref
in the format returned by parse_logline (see below). By default all actions
will be returned, but you can limit it to a subset using by setting the
following parameters :
=item only-user - Only return actions by this Webmin user.
=item only-module - Only actions in this module.
=item start-time - Limit to actions at or after this Unix time.
=item end-time - Limit to actions at or before this Unix time.
=cut
sub list_webmin_log
{
my ($onlyuser, $onlymodule, $start, $end) = @_;
my %index;
&build_log_index(\%index);
my @rv;
open(LOG, $webmin_logfile);
my ($id, $idx);
while(($id, $idx) = each %index) {
my ($pos, $time, $user, $module, $sid) = split(/\s+/, $idx);
next if (defined($onlyuser) && $user ne $onlyuser);
next if (defined($onlymodule) && $module ne $onlymodule);
next if (defined($start) && $time < $start);
next if (defined($end) && $time > $end);
seek(LOG, $pos, 0);
my $line = <LOG>;
my $act = &parse_logline($line);
if ($act) {
push(@rv, $act);
}
}
close(LOG);
return @rv;
}
=head2 parse_logline(line)
Converts a line of text in the format used in /var/webmin/webmin.log into
a hash ref containing the following keys :
=item time - Unix time the action happened.
=item id - A unique ID for the action.
=item user - The Webmin user who did it.
=item sid - The user's session ID.
=item ip - The IP address they were logged in from.
=item module - The Webmin module name in which the action was performed.
=item script - Relative filename of the script that performed the action.
=item action - A short action name, like 'create'.
=item type - The kind of object being operated on, like 'user'.
=item object - Name of the object being operated on, like 'joe'.
=item params - A hash ref of additional information about the action.
=cut
sub parse_logline
{
my ($line) = @_;
if (!$line) {
return undef;
}
if ($line =~ /^(\d+)\.(\S+)\s+\[.*\]\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+"([^"]+)"\s+"([^"]+)"\s+"([^"]+)"(.*)/ ||
$line =~ /^(\d+)\.(\S+)\s+\[.*\]\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(.*)/) {
my $rv = { 'time' => $1, 'id' => "$1.$2",
'user' => $3, 'sid' => $4,
'ip' => $5, 'module' => $6,
'script' => $7, 'action' => $8,
'type' => $9, 'object' => $10 };
my %param;
my $p = $11;
while($p =~ /^\s*([^=\s]+)='([^']*)'(.*)$/) {
if (defined($param{$1})) {
$param{$1} .= "\0".$2;
}
else {
$param{$1} = $2;
}
$p = $3;
}
foreach my $k (keys %param) {
$param{$k} =~ s/%(..)/pack("c",hex($1))/ge;
}
$rv->{'param'} = \%param;
if ($rv->{'script'} =~ /^(\S+):(\S+)$/) {
$rv->{'script'} = $2;
$rv->{'webmin'} = $1;
}
return $rv;
}
else {
return undef;
}
}
=head2 list_diffs(&action)
Returns details of file changes made by this action. Each of which is a
hash ref with the keys :
=item type - The change type, such as create, modify, delete, exec, sql or kill.
=item object - The file or database the change was made to.
=item diff - A diff of the file change made.
=item input - Input to the command run, if available.
=cut
sub list_diffs
{
my ($act) = @_;
my $i = 0;
my @rv;
my $idprefix = substr($act->{'id'}, 0, 5);
my $oldbase = "$ENV{'WEBMIN_VAR'}/diffs/$idprefix/$act->{'id'}";
my $base = "$ENV{'WEBMIN_VAR'}/diffs/$act->{'id'}";
return ( ) if (!-d $base && !-d $oldbase);
my @files = &expand_base_dir(-d $base ? $base : $oldbase);
# Read the diff files
foreach my $file (@files) {
my ($type, $object, $diff, $input);
open(DIFF, $file);
my $line = <DIFF>;
while(<DIFF>) { $diff .= $_; }
close(DIFF);
if ($line =~ /^(\/.*)/) {
$type = 'modify'; $object = $1;
}
elsif ($line =~ /^(\S+)\s+(.*)/) {
$type = $1; $object = $2;
}
if ($type eq "exec") {
open(INPUT, $file.".input");
while(<INPUT>) {
$input .= $_;
}
close(INPUT);
}
push(@rv, { 'type' => $type,
'object' => $object,
'diff' => $diff,
'input' => $input } );
$i++;
}
return @rv;
}
=head2 list_files(&action)
Returns details of original files before this action was taken. Each is a hash
ref containing keys :
=item type - One of create, modify or delete.
=item file - Full path to the file.
=item data - Original file contents, if any.
=cut
sub list_files
{
my ($act) = @_;
my $i = 0;
my @rv;
my $idprefix = substr($act->{'id'}, 0, 5);
my $oldbase = "$ENV{'WEBMIN_VAR'}/files/$idprefix/$act->{'id'}";
my $base = "$ENV{'WEBMIN_VAR'}/files/$act->{'id'}";
return ( ) if (!-d $base && !-d $oldbase);
my @files = &expand_base_dir(-d $base ? $base : $oldbase);
foreach my $file (@files) {
my ($type, $object, $data);
open(FILE, $file);
my $line = <FILE>;
$line =~ s/\r|\n//g;
while(<FILE>) { $data .= $_; }
close(FILE);
if ($line =~ /^(\S+)\s+(.*)/) {
$type = $1;
$file = $2;
}
elsif ($line =~ /^\s+(.*)/) {
$type = -1;
$file = $1;
}
else {
next;
}
push(@rv, { 'type' => $type,
'file' => $file,
'data' => $data });
$i++;
}
return @rv;
}
=head2 get_annotation(&action)
Returns the text of the log annotation for this action, or undef if none.
=cut
sub get_annotation
{
my ($act) = @_;
return &read_file_contents("$ENV{'WEBMIN_VAR'}/annotations/$act->{'id'}");
}
=head2 save_annotation(&action, text)
Updates the annotation for some action.
=cut
sub save_annotation
{
my ($act, $text) = @_;
my $dir = "$ENV{'WEBMIN_VAR'}/annotations";
my $file = "$dir/$act->{'id'}";
if ($text eq '') {
unlink($file);
}
else {
&make_dir($dir, 0700) if (!-d $dir);
my $fh;
&open_tempfile($fh, ">$file");
&print_tempfile($fh, $text);
&close_tempfile($fh);
}
}
=head2 get_action_output(&action)
Returns the text of the page that generated this action, or undef if none.
=cut
sub get_action_output
{
my ($act) = @_;
my $idprefix = substr($act->{'id'}, 0, 5);
return &read_file_contents("$ENV{'WEBMIN_VAR'}/output/$idprefix/$act->{'id'}")
||
&read_file_contents("$ENV{'WEBMIN_VAR'}/output/$act->{'id'}");
}
=head2 expand_base_dir(base)
Finds files either under some dir, or starting with some path in the same
directory.
=cut
sub expand_base_dir
{
my ($base) = @_;
my @files;
if (-d $base) {
# Find files in the dir
opendir(DIR, $base);
@files = map { "$base/$_" } sort { $a <=> $b }
grep { $_ =~ /^\d+$/ } readdir(DIR);
closedir(DIR);
}
else {
# Files are those that start with id
my $i = 0;
while(-r "$base.$i") {
push(@files, "$base.$i");
$i++;
}
}
return @files;
}
=head2 can_user(username)
Returns 1 if the current Webmin user can view log entries for the given user.
=cut
sub can_user
{
return $access_users{'*'} || $access_users{$_[0]};
}
=head2 can_mod(module)
Returns 1 if the current Webmin user can view log entries for the given module.
=cut
sub can_mod
{
return $access_mods{'*'} || $access_mods{$_[0]};
}
=head2 get_action(id)
Returns the structure for some action identified by an ID, in the same format
as returned by parse_logline.
=cut
sub get_action
{
my %index;
&build_log_index(\%index);
open(LOG, $webmin_logfile);
my @idx = split(/\s+/, $index{$_[0]});
seek(LOG, $idx[0], 0);
my $line = <LOG>;
my $act = &parse_logline($line);
close(LOG);
return $act->{'id'} eq $_[0] ? $act : undef;
}
=head2 build_log_index(&index)
Updates the given hash with mappings between action IDs and file positions.
For internal use only really.
=cut
sub build_log_index
{
my ($index) = @_;
my $ifile = "$module_config_directory/logindex";
dbmopen(%$index, $ifile, 0600);
my @st = stat($webmin_logfile);
if ($st[9] > $index->{'lastchange'}) {
# Log has changed .. perhaps need to rebuild
open(LOG, $webmin_logfile);
if ($index->{'lastsize'} && $st[7] >= $index->{'lastsize'}) {
# Gotten bigger .. just add new lines
seek(LOG, $index->{'lastpos'}, 0);
}
else {
# Smaller! Need to rebuild from start
%$index = ( 'lastpos' => 0 );
}
while(<LOG>) {
my $act;
if ($act = &parse_logline($_)) {
$index->{$act->{'id'}} = $index->{'lastpos'}." ".
$act->{'time'}." ".
$act->{'user'}." ".
$act->{'module'}." ".
$act->{'sid'};
}
$index->{'lastpos'} += length($_);
}
close(LOG);
$index->{'lastsize'} = $st[7];
$index->{'lastchange'} = $st[9];
}
}
=head2 get_action_description(&action, [long])
Returns a human-readable description of some action. This is done by
calling the log_parser.pl file in the action's source module. If the long
parameter is set to 1 and the module provides a more detailed description
for the action, it will be returned.
=cut
sub get_action_description
{
my ($act, $long) = @_;
if (!defined($parser_cache{$act->{'module'}})) {
# Bring in module parser library for the first time
if (-r "$root_directory/$act->{'module'}/log_parser.pl") {
&foreign_require($act->{'module'}, "log_parser.pl");
$parser_cache{$act->{'module'}} = 1;
}
else {
$parser_cache{$act->{'module'}} = 0;
}
}
my $d;
if ($parser_cache{$act->{'module'}}) {
# Module can return string
$d = &foreign_call($act->{'module'}, "parse_webmin_log",
$act->{'user'}, $act->{'script'},
$act->{'action'}, $act->{'type'},
$act->{'object'}, $act->{'param'}, $long);
}
elsif ($act->{'module'} eq 'global') {
# This module converts global actions
$d = $text{'search_global_'.$act->{'action'}};
}
return $d ? $d :
$act->{'action'} eq '_config_' ? $text{'search_config'} :
join(" ", $act->{'action'}, $act->{'type'}, $act->{'object'});
}
1;
| xtso520ok/webmin | webminlog/webminlog-lib.pl | Perl | bsd-3-clause | 10,283 |
#!/usr/bin/perl
#
# Copyright (c) 2011, Nokia Corporation
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Nokia nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
#
# @author Dmitry Kolesnikov <dmitry.kolesnikov@nokia.com>
#
use Getopt::Std;
sub usage
{
print STDERR "\n$0 [OPTIONS] OUTPUT\n";
print STDERR "\t-s sec \tsample interval (default 60)\n";
print STDERR "\t-c class\tdata stream class (default GAUGE)\n";
}
my %opts=();
getopts("s:c:",\%opts);
if (!defined $ARGV[0])
{
usage();
exit(-1);
}
my $db = $ARGV[0];
my $hbeat = $opts{s} if (defined $opts{s});
my $hbeat = 60 if (!defined $opts{s});
my $class = $opts{c} if (defined $opts{c});
my $class = "GAUGE" if (!defined $opts{c});
my $tout = $hbeat * 3;
$flags = " -s $hbeat ";
$def = " DS:value:GAUGE:$tout:U:U ";
#
# archive, default schema
# 1 to 1 during week
# 15 min to 1 during month
# 30 min to 1 during year
#
$spw = int(7 * 24 * 3600 / $hbeat); #steps per week
$spq = int(15 * 60 / $hbeat); #steps in quater
$qm = int(31 * 24 * 60 / 15); #quaters in month
$sph = int(30 * 60 / $hbeat); #steps in half
$hy = int(365 * 24 * 60 / 30); #halves in year
$rra = " RRA:AVERAGE:0.9999:1:$spw ";
$rra .= " RRA:AVERAGE:0.9999:$spq:$qm "; #15min to 1
$rra .= " RRA:AVERAGE:0.9999:$spq:$hy ";
system("rrdtool create $db $flags $def $rra");
print "Error: $!\n" if ( $? == -1 );
| fogfish/elata | tsa/src/newdb.pl | Perl | bsd-3-clause | 2,892 |
#
# This file is part of MooseX-Traits-Attribute-MergeHashRef
#
# This software is Copyright (c) 2011 by Moritz Onken.
#
# This is free software, licensed under:
#
# The (three-clause) BSD License
#
package Moose::Meta::Attribute::Custom::Trait::MergeHashRef;
BEGIN {
$Moose::Meta::Attribute::Custom::Trait::MergeHashRef::VERSION = '1.002';
}
use Moose::Role;
use MooseX::Traits::Attribute::MergeHashRef;
has 'clearer' => (is => 'rw', default => sub { 'clear_' . $_[0]->name } );
sub accessor_metaclass { 'MooseX::Traits::Attribute::MergeHashRef' }
after 'install_accessors' => sub {
my $attr = shift;
my $class = $attr->associated_class;
my $method = sub { $_[0]->${\('clear_'.$attr->name)}; shift->${\($attr->name)}(@_); };
$class->add_method( 'set_' . $attr->name, $method );
};
1;
__END__
=pod
=head1 NAME
Moose::Meta::Attribute::Custom::Trait::MergeHashRef
=head1 VERSION
version 1.002
=head1 AUTHOR
Moritz Onken
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2011 by Moritz Onken.
This is free software, licensed under:
The (three-clause) BSD License
=cut
| gitpan/MooseX-Traits-Attribute-MergeHashRef | lib/Moose/Meta/Attribute/Custom/Trait/MergeHashRef.pm | Perl | bsd-3-clause | 1,116 |
package Paws::ECS::ListTaskDefinitionsResponse;
use Moose;
has NextToken => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'nextToken' );
has TaskDefinitionArns => (is => 'ro', isa => 'ArrayRef[Str|Undef]', traits => ['NameInRequest'], request_name => 'taskDefinitionArns' );
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::ECS::ListTaskDefinitionsResponse
=head1 ATTRIBUTES
=head2 NextToken => Str
The C<nextToken> value to include in a future C<ListTaskDefinitions>
request. When the results of a C<ListTaskDefinitions> request exceed
C<maxResults>, this value can be used to retrieve the next page of
results. This value is C<null> when there are no more results to
return.
=head2 TaskDefinitionArns => ArrayRef[Str|Undef]
The list of task definition Amazon Resource Name (ARN) entries for the
C<ListTaskDefinitions> request.
=head2 _request_id => Str
=cut
1; | ioanrogers/aws-sdk-perl | auto-lib/Paws/ECS/ListTaskDefinitionsResponse.pm | Perl | apache-2.0 | 966 |
package BDE::Util::RuntimeFlags;
# ----------------------------------------------------------------------------
# Copyright 2016 Bloomberg Finance L.P.
#
# 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.
# ----------------------------- END-OF-FILE ----------------------------------
use strict;
use Exporter;
use vars qw(@ISA @EXPORT_OK);
@ISA=qw(Exporter);
@EXPORT_OK=qw(
setDeprecationLevel
getDeprecationLevel
setNoMetaMode
getNoMetaMode
);
#==============================================================================
my $deprecationLevel = 0;
my $noMetaMode = 0;
sub setDeprecationLevel($) { $deprecationLevel = $_[0]; }
sub getDeprecationLevel() { return $deprecationLevel; }
sub setNoMetaMode() {
$noMetaMode = 1;
#setDeprecationLevel(1);
}
sub getNoMetaMode() { return $noMetaMode; }
#==============================================================================
1;
| che2/bde-tools | contrib/bdedox/lib/perl/BDE/Util/RuntimeFlags.pm | Perl | apache-2.0 | 1,409 |
package #
Date::Manip::Offset::off257;
# Copyright (c) 2008-2014 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
# This file was automatically generated. Any changes to this file will
# be lost the next time 'tzdata' is run.
# Generated on: Fri Nov 21 11:03:45 EST 2014
# Data version: tzdata2014j
# Code version: tzcode2014j
# This module contains data from the zoneinfo time zone database. The original
# data was obtained from the URL:
# ftp://ftp.iana.orgtz
use strict;
use warnings;
require 5.010000;
our ($VERSION);
$VERSION='6.48';
END { undef $VERSION; }
our ($Offset,%Offset);
END {
undef $Offset;
undef %Offset;
}
$Offset = '-01:42:40';
%Offset = (
0 => [
'atlantic/azores',
],
);
1;
| nriley/Pester | Source/Manip/Offset/off257.pm | Perl | bsd-2-clause | 853 |
%% ---
%% Excerpted from "Seven Languages in Seven Weeks",
%% published by The Pragmatic Bookshelf.
%% Copyrights apply to this code. It may not be used to create training material,
%% courses, books, articles, and the like. Contact us if you are in doubt.
%% We make no guarantees that this code is fit for any purpose.
%% Visit http://www.pragmaticprogrammer.com/titles/btlang for more book information.
%%---
factorial(0, 1).
factorial(Index, Fac) :-
Index > 0,
OneBack is Index - 1,
factorial(OneBack, PreviousFac),
Fac is PreviousFac * Index.
fib(1, 1).
fib(2, 1).
fib(Index, Value) :-
Index > 2,
Previous is Index - 1,
PreviousPrevious is Index - 2,
fib(Previous, X),
fib(PreviousPrevious, Y),
Value is X + Y.
| nmcl/scratch | prolog/math.pl | Perl | apache-2.0 | 744 |
#
# Copyright 2017 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package storage::storagetek::sl::snmp::mode::components::controller;
use strict;
use warnings;
use storage::storagetek::sl::snmp::mode::components::resources qw($map_status);
my $mapping = {
slControllerSerialNum => { oid => '.1.3.6.1.4.1.1211.1.15.4.14.1.3' },
slControllerStatus => { oid => '.1.3.6.1.4.1.1211.1.15.4.14.1.4', map => $map_status },
};
my $oid_slControllerEntry = '.1.3.6.1.4.1.1211.1.15.4.14.1';
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $oid_slControllerEntry };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking controllers");
$self->{components}->{controller} = {name => 'controllers', total => 0, skip => 0};
return if ($self->check_filter(section => 'controller'));
foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_slControllerEntry}})) {
next if ($oid !~ /^$mapping->{slControllerStatus}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_slControllerEntry}, instance => $instance);
next if ($self->check_filter(section => 'controller', instance => $instance));
$self->{components}->{controller}->{total}++;
$self->{output}->output_add(long_msg => sprintf("controller '%s' status is '%s' [instance: %s].",
$result->{slControllerSerialNum}, $result->{slControllerStatus},
$instance
));
my $exit = $self->get_severity(label => 'status', section => 'controller', value => $result->{slControllerStatus});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Controller '%s' status is '%s'",
$result->{slControllerSerialNum}, $result->{slControllerStatus}));
}
}
}
1; | nichols-356/centreon-plugins | storage/storagetek/sl/snmp/mode/components/controller.pm | Perl | apache-2.0 | 2,865 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
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.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 NAME
Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::DumpAllTreesOrthoXML
=head1 DESCRIPTION
This Analysis/RunnableDB is designed to dump all the trees of a database
in a single file, with the OrthoXML format
It requires one parameter:
- compara_db: connection parameters to the Compara database
The following parameters are optional:
- file: [string] output file to dump (otherwise: standard output)
=head1 SYNOPSIS
standaloneJob.pl Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::DumpAllTreesOrthoXML
-compara_db 'mysql://ensro:@compara4:3306/mp12_compara_nctrees_66c' -member_type ncrna -file dump_ncrna
=head1 AUTHORSHIP
Ensembl Team. Individual contributions can be found in the GIT log.
=head1 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with an underscore (_)
=cut
package Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::DumpAllTreesOrthoXML;
use strict;
use Bio::EnsEMBL::ApiVersion;
use Bio::EnsEMBL::Compara::Graph::OrthoXMLWriter;
use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');
sub fetch_input {
my ($self) = @_;
# Defines the file handle
my $file_handle = *STDOUT;
if (defined $self->param('file')) {
$file_handle = IO::File->new( $self->param('file'), 'w');
}
$self->param('file_handle', $file_handle);
# Creates the OrthoXML writer
my $w = Bio::EnsEMBL::Compara::Graph::OrthoXMLWriter->new(
-HANDLE => $self->param('file_handle'),
-SOURCE => "Ensembl Compara",
-SOURCE_VERSION => software_version(),
);
$self->param('writer', $w);
# List of all the trees
my $list_trees = $self->compara_dba->get_GeneTreeAdaptor->fetch_all(-clusterset_id => 'default', -member_type => $self->param('member_type'), -tree_type => 'tree');
$self->param('tree_list', $list_trees);
}
sub run {
my ($self) = @_;
my $seq_member_adaptor = $self->compara_dba->get_SeqMemberAdaptor;
my $callback_list_members = sub {
my ($species) = @_;
my $constraint = 'm.genome_db_id = '.($species->dbID);
$constraint .= ' AND gtr.tree_type = "tree"';
$constraint .= ' AND gtr.clusterset_id = "default"';
$constraint .= ' AND gtr.member_type = "'.($self->param('member_type')).'"' if defined $self->param('member_type');
my $join = [[['gene_tree_node', 'gtn'], 'm.seq_member_id = gtn.seq_member_id', undef], [['gene_tree_root', 'gtr'], 'gtn.root_id = gtr.root_id', undef]];
return $seq_member_adaptor->generic_fetch($constraint, $join);
};
my $list_species = $self->compara_dba->get_GenomeDBAdaptor->fetch_all;
# Launches the dump
$self->param('writer')->_write_data($list_species, $callback_list_members, $self->param('tree_list'));
}
sub write_output {
my ($self) = @_;
$self->param('writer')->finish();
$self->param('file_handle')->close();
}
1;
| ckongEbi/ensembl-compara | modules/Bio/EnsEMBL/Compara/RunnableDB/GeneTrees/DumpAllTreesOrthoXML.pm | Perl | apache-2.0 | 3,840 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
0029
005D
END
| efortuna/AndroidSDKClone | ndk_experimental/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Lb/CP.pl | Perl | apache-2.0 | 437 |
#!/usr/bin/env perl
$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
push(@INC, "${dir}.", "${dir}../crypto/perlasm");
require "x86asm.pl";
require "uplink-common.pl";
&asm_init($ARGV[0],"uplink-x86");
&external_label("OPENSSL_Uplink");
&public_label("OPENSSL_UplinkTable");
for ($i=1;$i<=$N;$i++) {
&function_begin_B("_\$lazy${i}");
&lea ("eax",&DWP(&label("OPENSSL_UplinkTable")));
&push ("eax");
&push ($i);
&call (&label("OPENSSL_Uplink"));
&add ("esp",8);
&pop ("eax");
&jmp_ptr(&DWP(4*$i,"eax"));
&function_end_B("_\$lazy${i}");
}
&dataseg();
&align(4);
&set_label("OPENSSL_UplinkTable");
&data_word($N);
for ($i=1;$i<=$N;$i++) {
&data_word(&label("_\$lazy${i}"));
}
&asm_finish();
| caidongyun/nginx-openresty-windows | nginx/objs/lib/openssl-1.0.1g/ms/uplink-x86.pl | Perl | bsd-2-clause | 724 |
# This file is auto-generated by the Perl DateTime Suite time zone
# code generator (0.07) This code generator comes with the
# DateTime::TimeZone module distribution in the tools/ directory
#
# Generated from /tmp/rnClxBLdxJ/northamerica. Olson data version 2013a
#
# Do not edit this file directly.
#
package DateTime::TimeZone::America::Monterrey;
{
$DateTime::TimeZone::America::Monterrey::VERSION = '1.57';
}
use strict;
use Class::Singleton 1.03;
use DateTime::TimeZone;
use DateTime::TimeZone::OlsonDB;
@DateTime::TimeZone::America::Monterrey::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' );
my $spans =
[
[
DateTime::TimeZone::NEG_INFINITY, # utc_start
60620940000, # utc_end 1922-01-01 06:00:00 (Sun)
DateTime::TimeZone::NEG_INFINITY, # local_start
60620915924, # local_end 1921-12-31 23:18:44 (Sat)
-24076,
0,
'LMT',
],
[
60620940000, # utc_start 1922-01-01 06:00:00 (Sun)
62703698400, # utc_end 1988-01-01 06:00:00 (Fri)
60620918400, # local_start 1922-01-01 00:00:00 (Sun)
62703676800, # local_end 1988-01-01 00:00:00 (Fri)
-21600,
0,
'CST',
],
[
62703698400, # utc_start 1988-01-01 06:00:00 (Fri)
62711740800, # utc_end 1988-04-03 08:00:00 (Sun)
62703676800, # local_start 1988-01-01 00:00:00 (Fri)
62711719200, # local_end 1988-04-03 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
62711740800, # utc_start 1988-04-03 08:00:00 (Sun)
62729881200, # utc_end 1988-10-30 07:00:00 (Sun)
62711722800, # local_start 1988-04-03 03:00:00 (Sun)
62729863200, # local_end 1988-10-30 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
62729881200, # utc_start 1988-10-30 07:00:00 (Sun)
62735320800, # utc_end 1989-01-01 06:00:00 (Sun)
62729859600, # local_start 1988-10-30 01:00:00 (Sun)
62735299200, # local_end 1989-01-01 00:00:00 (Sun)
-21600,
0,
'CST',
],
[
62735320800, # utc_start 1989-01-01 06:00:00 (Sun)
62964547200, # utc_end 1996-04-07 08:00:00 (Sun)
62735299200, # local_start 1989-01-01 00:00:00 (Sun)
62964525600, # local_end 1996-04-07 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
62964547200, # utc_start 1996-04-07 08:00:00 (Sun)
62982082800, # utc_end 1996-10-27 07:00:00 (Sun)
62964529200, # local_start 1996-04-07 03:00:00 (Sun)
62982064800, # local_end 1996-10-27 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
62982082800, # utc_start 1996-10-27 07:00:00 (Sun)
62995996800, # utc_end 1997-04-06 08:00:00 (Sun)
62982061200, # local_start 1996-10-27 01:00:00 (Sun)
62995975200, # local_end 1997-04-06 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
62995996800, # utc_start 1997-04-06 08:00:00 (Sun)
63013532400, # utc_end 1997-10-26 07:00:00 (Sun)
62995978800, # local_start 1997-04-06 03:00:00 (Sun)
63013514400, # local_end 1997-10-26 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63013532400, # utc_start 1997-10-26 07:00:00 (Sun)
63027446400, # utc_end 1998-04-05 08:00:00 (Sun)
63013510800, # local_start 1997-10-26 01:00:00 (Sun)
63027424800, # local_end 1998-04-05 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63027446400, # utc_start 1998-04-05 08:00:00 (Sun)
63044982000, # utc_end 1998-10-25 07:00:00 (Sun)
63027428400, # local_start 1998-04-05 03:00:00 (Sun)
63044964000, # local_end 1998-10-25 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63044982000, # utc_start 1998-10-25 07:00:00 (Sun)
63058896000, # utc_end 1999-04-04 08:00:00 (Sun)
63044960400, # local_start 1998-10-25 01:00:00 (Sun)
63058874400, # local_end 1999-04-04 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63058896000, # utc_start 1999-04-04 08:00:00 (Sun)
63077036400, # utc_end 1999-10-31 07:00:00 (Sun)
63058878000, # local_start 1999-04-04 03:00:00 (Sun)
63077018400, # local_end 1999-10-31 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63077036400, # utc_start 1999-10-31 07:00:00 (Sun)
63090345600, # utc_end 2000-04-02 08:00:00 (Sun)
63077014800, # local_start 1999-10-31 01:00:00 (Sun)
63090324000, # local_end 2000-04-02 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63090345600, # utc_start 2000-04-02 08:00:00 (Sun)
63108486000, # utc_end 2000-10-29 07:00:00 (Sun)
63090327600, # local_start 2000-04-02 03:00:00 (Sun)
63108468000, # local_end 2000-10-29 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63108486000, # utc_start 2000-10-29 07:00:00 (Sun)
63124819200, # utc_end 2001-05-06 08:00:00 (Sun)
63108464400, # local_start 2000-10-29 01:00:00 (Sun)
63124797600, # local_end 2001-05-06 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63124819200, # utc_start 2001-05-06 08:00:00 (Sun)
63137516400, # utc_end 2001-09-30 07:00:00 (Sun)
63124801200, # local_start 2001-05-06 03:00:00 (Sun)
63137498400, # local_end 2001-09-30 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63137516400, # utc_start 2001-09-30 07:00:00 (Sun)
63153849600, # utc_end 2002-04-07 08:00:00 (Sun)
63137494800, # local_start 2001-09-30 01:00:00 (Sun)
63153828000, # local_end 2002-04-07 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63153849600, # utc_start 2002-04-07 08:00:00 (Sun)
63171385200, # utc_end 2002-10-27 07:00:00 (Sun)
63153831600, # local_start 2002-04-07 03:00:00 (Sun)
63171367200, # local_end 2002-10-27 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63171385200, # utc_start 2002-10-27 07:00:00 (Sun)
63185299200, # utc_end 2003-04-06 08:00:00 (Sun)
63171363600, # local_start 2002-10-27 01:00:00 (Sun)
63185277600, # local_end 2003-04-06 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63185299200, # utc_start 2003-04-06 08:00:00 (Sun)
63202834800, # utc_end 2003-10-26 07:00:00 (Sun)
63185281200, # local_start 2003-04-06 03:00:00 (Sun)
63202816800, # local_end 2003-10-26 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63202834800, # utc_start 2003-10-26 07:00:00 (Sun)
63216748800, # utc_end 2004-04-04 08:00:00 (Sun)
63202813200, # local_start 2003-10-26 01:00:00 (Sun)
63216727200, # local_end 2004-04-04 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63216748800, # utc_start 2004-04-04 08:00:00 (Sun)
63234889200, # utc_end 2004-10-31 07:00:00 (Sun)
63216730800, # local_start 2004-04-04 03:00:00 (Sun)
63234871200, # local_end 2004-10-31 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63234889200, # utc_start 2004-10-31 07:00:00 (Sun)
63248198400, # utc_end 2005-04-03 08:00:00 (Sun)
63234867600, # local_start 2004-10-31 01:00:00 (Sun)
63248176800, # local_end 2005-04-03 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63248198400, # utc_start 2005-04-03 08:00:00 (Sun)
63266338800, # utc_end 2005-10-30 07:00:00 (Sun)
63248180400, # local_start 2005-04-03 03:00:00 (Sun)
63266320800, # local_end 2005-10-30 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63266338800, # utc_start 2005-10-30 07:00:00 (Sun)
63279648000, # utc_end 2006-04-02 08:00:00 (Sun)
63266317200, # local_start 2005-10-30 01:00:00 (Sun)
63279626400, # local_end 2006-04-02 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63279648000, # utc_start 2006-04-02 08:00:00 (Sun)
63297788400, # utc_end 2006-10-29 07:00:00 (Sun)
63279630000, # local_start 2006-04-02 03:00:00 (Sun)
63297770400, # local_end 2006-10-29 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63297788400, # utc_start 2006-10-29 07:00:00 (Sun)
63311097600, # utc_end 2007-04-01 08:00:00 (Sun)
63297766800, # local_start 2006-10-29 01:00:00 (Sun)
63311076000, # local_end 2007-04-01 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63311097600, # utc_start 2007-04-01 08:00:00 (Sun)
63329238000, # utc_end 2007-10-28 07:00:00 (Sun)
63311079600, # local_start 2007-04-01 03:00:00 (Sun)
63329220000, # local_end 2007-10-28 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63329238000, # utc_start 2007-10-28 07:00:00 (Sun)
63343152000, # utc_end 2008-04-06 08:00:00 (Sun)
63329216400, # local_start 2007-10-28 01:00:00 (Sun)
63343130400, # local_end 2008-04-06 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63343152000, # utc_start 2008-04-06 08:00:00 (Sun)
63360687600, # utc_end 2008-10-26 07:00:00 (Sun)
63343134000, # local_start 2008-04-06 03:00:00 (Sun)
63360669600, # local_end 2008-10-26 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63360687600, # utc_start 2008-10-26 07:00:00 (Sun)
63374601600, # utc_end 2009-04-05 08:00:00 (Sun)
63360666000, # local_start 2008-10-26 01:00:00 (Sun)
63374580000, # local_end 2009-04-05 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63374601600, # utc_start 2009-04-05 08:00:00 (Sun)
63392137200, # utc_end 2009-10-25 07:00:00 (Sun)
63374583600, # local_start 2009-04-05 03:00:00 (Sun)
63392119200, # local_end 2009-10-25 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63392137200, # utc_start 2009-10-25 07:00:00 (Sun)
63406051200, # utc_end 2010-04-04 08:00:00 (Sun)
63392115600, # local_start 2009-10-25 01:00:00 (Sun)
63406029600, # local_end 2010-04-04 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63406051200, # utc_start 2010-04-04 08:00:00 (Sun)
63424191600, # utc_end 2010-10-31 07:00:00 (Sun)
63406033200, # local_start 2010-04-04 03:00:00 (Sun)
63424173600, # local_end 2010-10-31 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63424191600, # utc_start 2010-10-31 07:00:00 (Sun)
63437500800, # utc_end 2011-04-03 08:00:00 (Sun)
63424170000, # local_start 2010-10-31 01:00:00 (Sun)
63437479200, # local_end 2011-04-03 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63437500800, # utc_start 2011-04-03 08:00:00 (Sun)
63455641200, # utc_end 2011-10-30 07:00:00 (Sun)
63437482800, # local_start 2011-04-03 03:00:00 (Sun)
63455623200, # local_end 2011-10-30 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63455641200, # utc_start 2011-10-30 07:00:00 (Sun)
63468950400, # utc_end 2012-04-01 08:00:00 (Sun)
63455619600, # local_start 2011-10-30 01:00:00 (Sun)
63468928800, # local_end 2012-04-01 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63468950400, # utc_start 2012-04-01 08:00:00 (Sun)
63487090800, # utc_end 2012-10-28 07:00:00 (Sun)
63468932400, # local_start 2012-04-01 03:00:00 (Sun)
63487072800, # local_end 2012-10-28 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63487090800, # utc_start 2012-10-28 07:00:00 (Sun)
63501004800, # utc_end 2013-04-07 08:00:00 (Sun)
63487069200, # local_start 2012-10-28 01:00:00 (Sun)
63500983200, # local_end 2013-04-07 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63501004800, # utc_start 2013-04-07 08:00:00 (Sun)
63518540400, # utc_end 2013-10-27 07:00:00 (Sun)
63500986800, # local_start 2013-04-07 03:00:00 (Sun)
63518522400, # local_end 2013-10-27 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63518540400, # utc_start 2013-10-27 07:00:00 (Sun)
63532454400, # utc_end 2014-04-06 08:00:00 (Sun)
63518518800, # local_start 2013-10-27 01:00:00 (Sun)
63532432800, # local_end 2014-04-06 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63532454400, # utc_start 2014-04-06 08:00:00 (Sun)
63549990000, # utc_end 2014-10-26 07:00:00 (Sun)
63532436400, # local_start 2014-04-06 03:00:00 (Sun)
63549972000, # local_end 2014-10-26 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63549990000, # utc_start 2014-10-26 07:00:00 (Sun)
63563904000, # utc_end 2015-04-05 08:00:00 (Sun)
63549968400, # local_start 2014-10-26 01:00:00 (Sun)
63563882400, # local_end 2015-04-05 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63563904000, # utc_start 2015-04-05 08:00:00 (Sun)
63581439600, # utc_end 2015-10-25 07:00:00 (Sun)
63563886000, # local_start 2015-04-05 03:00:00 (Sun)
63581421600, # local_end 2015-10-25 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63581439600, # utc_start 2015-10-25 07:00:00 (Sun)
63595353600, # utc_end 2016-04-03 08:00:00 (Sun)
63581418000, # local_start 2015-10-25 01:00:00 (Sun)
63595332000, # local_end 2016-04-03 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63595353600, # utc_start 2016-04-03 08:00:00 (Sun)
63613494000, # utc_end 2016-10-30 07:00:00 (Sun)
63595335600, # local_start 2016-04-03 03:00:00 (Sun)
63613476000, # local_end 2016-10-30 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63613494000, # utc_start 2016-10-30 07:00:00 (Sun)
63626803200, # utc_end 2017-04-02 08:00:00 (Sun)
63613472400, # local_start 2016-10-30 01:00:00 (Sun)
63626781600, # local_end 2017-04-02 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63626803200, # utc_start 2017-04-02 08:00:00 (Sun)
63644943600, # utc_end 2017-10-29 07:00:00 (Sun)
63626785200, # local_start 2017-04-02 03:00:00 (Sun)
63644925600, # local_end 2017-10-29 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63644943600, # utc_start 2017-10-29 07:00:00 (Sun)
63658252800, # utc_end 2018-04-01 08:00:00 (Sun)
63644922000, # local_start 2017-10-29 01:00:00 (Sun)
63658231200, # local_end 2018-04-01 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63658252800, # utc_start 2018-04-01 08:00:00 (Sun)
63676393200, # utc_end 2018-10-28 07:00:00 (Sun)
63658234800, # local_start 2018-04-01 03:00:00 (Sun)
63676375200, # local_end 2018-10-28 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63676393200, # utc_start 2018-10-28 07:00:00 (Sun)
63690307200, # utc_end 2019-04-07 08:00:00 (Sun)
63676371600, # local_start 2018-10-28 01:00:00 (Sun)
63690285600, # local_end 2019-04-07 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63690307200, # utc_start 2019-04-07 08:00:00 (Sun)
63707842800, # utc_end 2019-10-27 07:00:00 (Sun)
63690289200, # local_start 2019-04-07 03:00:00 (Sun)
63707824800, # local_end 2019-10-27 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63707842800, # utc_start 2019-10-27 07:00:00 (Sun)
63721756800, # utc_end 2020-04-05 08:00:00 (Sun)
63707821200, # local_start 2019-10-27 01:00:00 (Sun)
63721735200, # local_end 2020-04-05 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63721756800, # utc_start 2020-04-05 08:00:00 (Sun)
63739292400, # utc_end 2020-10-25 07:00:00 (Sun)
63721738800, # local_start 2020-04-05 03:00:00 (Sun)
63739274400, # local_end 2020-10-25 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63739292400, # utc_start 2020-10-25 07:00:00 (Sun)
63753206400, # utc_end 2021-04-04 08:00:00 (Sun)
63739270800, # local_start 2020-10-25 01:00:00 (Sun)
63753184800, # local_end 2021-04-04 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63753206400, # utc_start 2021-04-04 08:00:00 (Sun)
63771346800, # utc_end 2021-10-31 07:00:00 (Sun)
63753188400, # local_start 2021-04-04 03:00:00 (Sun)
63771328800, # local_end 2021-10-31 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63771346800, # utc_start 2021-10-31 07:00:00 (Sun)
63784656000, # utc_end 2022-04-03 08:00:00 (Sun)
63771325200, # local_start 2021-10-31 01:00:00 (Sun)
63784634400, # local_end 2022-04-03 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63784656000, # utc_start 2022-04-03 08:00:00 (Sun)
63802796400, # utc_end 2022-10-30 07:00:00 (Sun)
63784638000, # local_start 2022-04-03 03:00:00 (Sun)
63802778400, # local_end 2022-10-30 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63802796400, # utc_start 2022-10-30 07:00:00 (Sun)
63816105600, # utc_end 2023-04-02 08:00:00 (Sun)
63802774800, # local_start 2022-10-30 01:00:00 (Sun)
63816084000, # local_end 2023-04-02 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63816105600, # utc_start 2023-04-02 08:00:00 (Sun)
63834246000, # utc_end 2023-10-29 07:00:00 (Sun)
63816087600, # local_start 2023-04-02 03:00:00 (Sun)
63834228000, # local_end 2023-10-29 02:00:00 (Sun)
-18000,
1,
'CDT',
],
[
63834246000, # utc_start 2023-10-29 07:00:00 (Sun)
63848160000, # utc_end 2024-04-07 08:00:00 (Sun)
63834224400, # local_start 2023-10-29 01:00:00 (Sun)
63848138400, # local_end 2024-04-07 02:00:00 (Sun)
-21600,
0,
'CST',
],
[
63848160000, # utc_start 2024-04-07 08:00:00 (Sun)
63865695600, # utc_end 2024-10-27 07:00:00 (Sun)
63848142000, # local_start 2024-04-07 03:00:00 (Sun)
63865677600, # local_end 2024-10-27 02:00:00 (Sun)
-18000,
1,
'CDT',
],
];
sub olson_version { '2013a' }
sub has_dst_changes { 30 }
sub _max_year { 2023 }
sub _new_instance
{
return shift->_init( @_, spans => $spans );
}
sub _last_offset { -21600 }
my $last_observance = bless( {
'format' => 'C%sT',
'gmtoff' => '-6:00',
'local_start_datetime' => bless( {
'formatter' => undef,
'local_rd_days' => 726103,
'local_rd_secs' => 0,
'offset_modifier' => 0,
'rd_nanosecs' => 0,
'tz' => bless( {
'name' => 'floating',
'offset' => 0
}, 'DateTime::TimeZone::Floating' ),
'utc_rd_days' => 726103,
'utc_rd_secs' => 0,
'utc_year' => 1990
}, 'DateTime' ),
'offset_from_std' => 0,
'offset_from_utc' => -21600,
'until' => [],
'utc_start_datetime' => bless( {
'formatter' => undef,
'local_rd_days' => 726103,
'local_rd_secs' => 21600,
'offset_modifier' => 0,
'rd_nanosecs' => 0,
'tz' => bless( {
'name' => 'floating',
'offset' => 0
}, 'DateTime::TimeZone::Floating' ),
'utc_rd_days' => 726103,
'utc_rd_secs' => 21600,
'utc_year' => 1990
}, 'DateTime' )
}, 'DateTime::TimeZone::OlsonDB::Observance' )
;
sub _last_observance { $last_observance }
my $rules = [
bless( {
'at' => '2:00',
'from' => '2002',
'in' => 'Apr',
'letter' => 'D',
'name' => 'Mexico',
'offset_from_std' => 3600,
'on' => 'Sun>=1',
'save' => '1:00',
'to' => 'max',
'type' => undef
}, 'DateTime::TimeZone::OlsonDB::Rule' ),
bless( {
'at' => '2:00',
'from' => '2002',
'in' => 'Oct',
'letter' => 'S',
'name' => 'Mexico',
'offset_from_std' => 0,
'on' => 'lastSun',
'save' => '0',
'to' => 'max',
'type' => undef
}, 'DateTime::TimeZone::OlsonDB::Rule' )
]
;
sub _rules { $rules }
1;
| liuyangning/WX_web | xampp/perl/vendor/lib/DateTime/TimeZone/America/Monterrey.pm | Perl | mit | 17,954 |
package Moose::Meta::Attribute::Native::Trait::Hash;
BEGIN {
$Moose::Meta::Attribute::Native::Trait::Hash::AUTHORITY = 'cpan:STEVAN';
}
{
$Moose::Meta::Attribute::Native::Trait::Hash::VERSION = '2.0604';
}
use Moose::Role;
with 'Moose::Meta::Attribute::Native::Trait';
sub _helper_type { 'HashRef' }
no Moose::Role;
1;
# ABSTRACT: Helper trait for HashRef attributes
=pod
=head1 NAME
Moose::Meta::Attribute::Native::Trait::Hash - Helper trait for HashRef attributes
=head1 VERSION
version 2.0604
=head1 SYNOPSIS
package Stuff;
use Moose;
has 'options' => (
traits => ['Hash'],
is => 'ro',
isa => 'HashRef[Str]',
default => sub { {} },
handles => {
set_option => 'set',
get_option => 'get',
has_no_options => 'is_empty',
num_options => 'count',
delete_option => 'delete',
option_pairs => 'kv',
},
);
=head1 DESCRIPTION
This trait provides native delegation methods for hash references.
=head1 PROVIDED METHODS
=over 4
=item B<get($key, $key2, $key3...)>
Returns values from the hash.
In list context it returns a list of values in the hash for the given keys. In
scalar context it returns the value for the last key specified.
This method requires at least one argument.
=item B<set($key =E<gt> $value, $key2 =E<gt> $value2...)>
Sets the elements in the hash to the given values. It returns the new values
set for each key, in the same order as the keys passed to the method.
This method requires at least two arguments, and expects an even number of
arguments.
=item B<delete($key, $key2, $key3...)>
Removes the elements with the given keys.
In list context it returns a list of values in the hash for the deleted
keys. In scalar context it returns the value for the last key specified.
=item B<keys>
Returns the list of keys in the hash.
This method does not accept any arguments.
=item B<exists($key)>
Returns true if the given key is present in the hash.
This method requires a single argument.
=item B<defined($key)>
Returns true if the value of a given key is defined.
This method requires a single argument.
=item B<values>
Returns the list of values in the hash.
This method does not accept any arguments.
=item B<kv>
Returns the key/value pairs in the hash as an array of array references.
for my $pair ( $object->option_pairs ) {
print "$pair->[0] = $pair->[1]\n";
}
This method does not accept any arguments.
=item B<elements>
Returns the key/value pairs in the hash as a flattened list..
This method does not accept any arguments.
=item B<clear>
Resets the hash to an empty value, like C<%hash = ()>.
This method does not accept any arguments.
=item B<count>
Returns the number of elements in the hash. Also useful for not empty:
C<< has_options => 'count' >>.
This method does not accept any arguments.
=item B<is_empty>
If the hash is populated, returns false. Otherwise, returns true.
This method does not accept any arguments.
=item B<accessor($key)>
=item B<accessor($key, $value)>
If passed one argument, returns the value of the specified key. If passed two
arguments, sets the value of the specified key.
When called as a setter, this method returns the value that was set.
=item B<shallow_clone>
This method returns a shallow clone of the hash reference. The return value
is a reference to a new hash with the same keys and values. It is I<shallow>
because any values that were references in the original will be the I<same>
references in the clone.
=back
Note that C<each> is deliberately omitted, due to its stateful interaction
with the hash iterator. C<keys> or C<kv> are much safer.
=head1 METHODS
=over 4
=item B<meta>
=back
=head1 BUGS
See L<Moose/BUGS> for details on reporting bugs.
=head1 AUTHOR
Moose is maintained by the Moose Cabal, along with the help of many contributors. See L<Moose/CABAL> and L<Moose/CONTRIBUTORS> for details.
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2012 by Infinity Interactive, Inc..
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
__END__
| Dokaponteam/ITF_Project | xampp/perl/vendor/lib/Moose/Meta/Attribute/Native/Trait/Hash.pm | Perl | mit | 4,245 |
=head1 NAME
perlport - Writing portable Perl
=head1 DESCRIPTION
Perl runs on numerous operating systems. While most of them share
much in common, they also have their own unique features.
This document is meant to help you to find out what constitutes portable
Perl code. That way once you make a decision to write portably,
you know where the lines are drawn, and you can stay within them.
There is a tradeoff between taking full advantage of one particular
type of computer and taking advantage of a full range of them.
Naturally, as you broaden your range and become more diverse, the
common factors drop, and you are left with an increasingly smaller
area of common ground in which you can operate to accomplish a
particular task. Thus, when you begin attacking a problem, it is
important to consider under which part of the tradeoff curve you
want to operate. Specifically, you must decide whether it is
important that the task that you are coding have the full generality
of being portable, or whether to just get the job done right now.
This is the hardest choice to be made. The rest is easy, because
Perl provides many choices, whichever way you want to approach your
problem.
Looking at it another way, writing portable code is usually about
willfully limiting your available choices. Naturally, it takes
discipline and sacrifice to do that. The product of portability
and convenience may be a constant. You have been warned.
Be aware of two important points:
=over 4
=item Not all Perl programs have to be portable
There is no reason you should not use Perl as a language to glue Unix
tools together, or to prototype a Macintosh application, or to manage the
Windows registry. If it makes no sense to aim for portability for one
reason or another in a given program, then don't bother.
=item Nearly all of Perl already I<is> portable
Don't be fooled into thinking that it is hard to create portable Perl
code. It isn't. Perl tries its level-best to bridge the gaps between
what's available on different platforms, and all the means available to
use those features. Thus almost all Perl code runs on any machine
without modification. But there are some significant issues in
writing portable code, and this document is entirely about those issues.
=back
Here's the general rule: When you approach a task commonly done
using a whole range of platforms, think about writing portable
code. That way, you don't sacrifice much by way of the implementation
choices you can avail yourself of, and at the same time you can give
your users lots of platform choices. On the other hand, when you have to
take advantage of some unique feature of a particular platform, as is
often the case with systems programming (whether for Unix, Windows,
S<Mac OS>, VMS, etc.), consider writing platform-specific code.
When the code will run on only two or three operating systems, you
may need to consider only the differences of those particular systems.
The important thing is to decide where the code will run and to be
deliberate in your decision.
The material below is separated into three main sections: main issues of
portability (L<"ISSUES">), platform-specific issues (L<"PLATFORMS">), and
built-in perl functions that behave differently on various ports
(L<"FUNCTION IMPLEMENTATIONS">).
This information should not be considered complete; it includes possibly
transient information about idiosyncrasies of some of the ports, almost
all of which are in a state of constant evolution. Thus, this material
should be considered a perpetual work in progress
(C<< <IMG SRC="yellow_sign.gif" ALT="Under Construction"> >>).
=head1 ISSUES
=head2 Newlines
In most operating systems, lines in files are terminated by newlines.
Just what is used as a newline may vary from OS to OS. Unix
traditionally uses C<\012>, one type of DOSish I/O uses C<\015\012>,
and S<Mac OS> uses C<\015>.
Perl uses C<\n> to represent the "logical" newline, where what is
logical may depend on the platform in use. In MacPerl, C<\n> always
means C<\015>. In DOSish perls, C<\n> usually means C<\012>, but
when accessing a file in "text" mode, STDIO translates it to (or
from) C<\015\012>, depending on whether you're reading or writing.
Unix does the same thing on ttys in canonical mode. C<\015\012>
is commonly referred to as CRLF.
To trim trailing newlines from text lines use chomp(). With default
settings that function looks for a trailing C<\n> character and thus
trims in a portable way.
When dealing with binary files (or text files in binary mode) be sure
to explicitly set $/ to the appropriate value for your file format
before using chomp().
Because of the "text" mode translation, DOSish perls have limitations
in using C<seek> and C<tell> on a file accessed in "text" mode.
Stick to C<seek>-ing to locations you got from C<tell> (and no
others), and you are usually free to use C<seek> and C<tell> even
in "text" mode. Using C<seek> or C<tell> or other file operations
may be non-portable. If you use C<binmode> on a file, however, you
can usually C<seek> and C<tell> with arbitrary values in safety.
A common misconception in socket programming is that C<\n> eq C<\012>
everywhere. When using protocols such as common Internet protocols,
C<\012> and C<\015> are called for specifically, and the values of
the logical C<\n> and C<\r> (carriage return) are not reliable.
print SOCKET "Hi there, client!\r\n"; # WRONG
print SOCKET "Hi there, client!\015\012"; # RIGHT
However, using C<\015\012> (or C<\cM\cJ>, or C<\x0D\x0A>) can be tedious
and unsightly, as well as confusing to those maintaining the code. As
such, the Socket module supplies the Right Thing for those who want it.
use Socket qw(:DEFAULT :crlf);
print SOCKET "Hi there, client!$CRLF" # RIGHT
When reading from a socket, remember that the default input record
separator C<$/> is C<\n>, but robust socket code will recognize as
either C<\012> or C<\015\012> as end of line:
while (<SOCKET>) {
# ...
}
Because both CRLF and LF end in LF, the input record separator can
be set to LF and any CR stripped later. Better to write:
use Socket qw(:DEFAULT :crlf);
local($/) = LF; # not needed if $/ is already \012
while (<SOCKET>) {
s/$CR?$LF/\n/; # not sure if socket uses LF or CRLF, OK
# s/\015?\012/\n/; # same thing
}
This example is preferred over the previous one--even for Unix
platforms--because now any C<\015>'s (C<\cM>'s) are stripped out
(and there was much rejoicing).
Similarly, functions that return text data--such as a function that
fetches a web page--should sometimes translate newlines before
returning the data, if they've not yet been translated to the local
newline representation. A single line of code will often suffice:
$data =~ s/\015?\012/\n/g;
return $data;
Some of this may be confusing. Here's a handy reference to the ASCII CR
and LF characters. You can print it out and stick it in your wallet.
LF eq \012 eq \x0A eq \cJ eq chr(10) eq ASCII 10
CR eq \015 eq \x0D eq \cM eq chr(13) eq ASCII 13
| Unix | DOS | Mac |
---------------------------
\n | LF | LF | CR |
\r | CR | CR | LF |
\n * | LF | CRLF | CR |
\r * | CR | CR | LF |
---------------------------
* text-mode STDIO
The Unix column assumes that you are not accessing a serial line
(like a tty) in canonical mode. If you are, then CR on input becomes
"\n", and "\n" on output becomes CRLF.
These are just the most common definitions of C<\n> and C<\r> in Perl.
There may well be others. For example, on an EBCDIC implementation
such as z/OS (OS/390) or OS/400 (using the ILE, the PASE is ASCII-based)
the above material is similar to "Unix" but the code numbers change:
LF eq \025 eq \x15 eq \cU eq chr(21) eq CP-1047 21
LF eq \045 eq \x25 eq chr(37) eq CP-0037 37
CR eq \015 eq \x0D eq \cM eq chr(13) eq CP-1047 13
CR eq \015 eq \x0D eq \cM eq chr(13) eq CP-0037 13
| z/OS | OS/400 |
----------------------
\n | LF | LF |
\r | CR | CR |
\n * | LF | LF |
\r * | CR | CR |
----------------------
* text-mode STDIO
=head2 Numbers endianness and Width
Different CPUs store integers and floating point numbers in different
orders (called I<endianness>) and widths (32-bit and 64-bit being the
most common today). This affects your programs when they attempt to transfer
numbers in binary format from one CPU architecture to another,
usually either "live" via network connection, or by storing the
numbers to secondary storage such as a disk file or tape.
Conflicting storage orders make utter mess out of the numbers. If a
little-endian host (Intel, VAX) stores 0x12345678 (305419896 in
decimal), a big-endian host (Motorola, Sparc, PA) reads it as
0x78563412 (2018915346 in decimal). Alpha and MIPS can be either:
Digital/Compaq used/uses them in little-endian mode; SGI/Cray uses
them in big-endian mode. To avoid this problem in network (socket)
connections use the C<pack> and C<unpack> formats C<n> and C<N>, the
"network" orders. These are guaranteed to be portable.
As of perl 5.9.2, you can also use the C<E<gt>> and C<E<lt>> modifiers
to force big- or little-endian byte-order. This is useful if you want
to store signed integers or 64-bit integers, for example.
You can explore the endianness of your platform by unpacking a
data structure packed in native format such as:
print unpack("h*", pack("s2", 1, 2)), "\n";
# '10002000' on e.g. Intel x86 or Alpha 21064 in little-endian mode
# '00100020' on e.g. Motorola 68040
If you need to distinguish between endian architectures you could use
either of the variables set like so:
$is_big_endian = unpack("h*", pack("s", 1)) =~ /01/;
$is_little_endian = unpack("h*", pack("s", 1)) =~ /^1/;
Differing widths can cause truncation even between platforms of equal
endianness. The platform of shorter width loses the upper parts of the
number. There is no good solution for this problem except to avoid
transferring or storing raw binary numbers.
One can circumnavigate both these problems in two ways. Either
transfer and store numbers always in text format, instead of raw
binary, or else consider using modules like Data::Dumper (included in
the standard distribution as of Perl 5.005) and Storable (included as
of perl 5.8). Keeping all data as text significantly simplifies matters.
The v-strings are portable only up to v2147483647 (0x7FFFFFFF), that's
how far EBCDIC, or more precisely UTF-EBCDIC will go.
=head2 Files and Filesystems
Most platforms these days structure files in a hierarchical fashion.
So, it is reasonably safe to assume that all platforms support the
notion of a "path" to uniquely identify a file on the system. How
that path is really written, though, differs considerably.
Although similar, file path specifications differ between Unix,
Windows, S<Mac OS>, OS/2, VMS, VOS, S<RISC OS>, and probably others.
Unix, for example, is one of the few OSes that has the elegant idea
of a single root directory.
DOS, OS/2, VMS, VOS, and Windows can work similarly to Unix with C</>
as path separator, or in their own idiosyncratic ways (such as having
several root directories and various "unrooted" device files such NIL:
and LPT:).
S<Mac OS> uses C<:> as a path separator instead of C</>.
The filesystem may support neither hard links (C<link>) nor
symbolic links (C<symlink>, C<readlink>, C<lstat>).
The filesystem may support neither access timestamp nor change
timestamp (meaning that about the only portable timestamp is the
modification timestamp), or one second granularity of any timestamps
(e.g. the FAT filesystem limits the time granularity to two seconds).
The "inode change timestamp" (the C<-C> filetest) may really be the
"creation timestamp" (which it is not in UNIX).
VOS perl can emulate Unix filenames with C</> as path separator. The
native pathname characters greater-than, less-than, number-sign, and
percent-sign are always accepted.
S<RISC OS> perl can emulate Unix filenames with C</> as path
separator, or go native and use C<.> for path separator and C<:> to
signal filesystems and disk names.
Don't assume UNIX filesystem access semantics: that read, write,
and execute are all the permissions there are, and even if they exist,
that their semantics (for example what do r, w, and x mean on
a directory) are the UNIX ones. The various UNIX/POSIX compatibility
layers usually try to make interfaces like chmod() work, but sometimes
there simply is no good mapping.
If all this is intimidating, have no (well, maybe only a little)
fear. There are modules that can help. The File::Spec modules
provide methods to do the Right Thing on whatever platform happens
to be running the program.
use File::Spec::Functions;
chdir(updir()); # go up one directory
$file = catfile(curdir(), 'temp', 'file.txt');
# on Unix and Win32, './temp/file.txt'
# on Mac OS, ':temp:file.txt'
# on VMS, '[.temp]file.txt'
File::Spec is available in the standard distribution as of version
5.004_05. File::Spec::Functions is only in File::Spec 0.7 and later,
and some versions of perl come with version 0.6. If File::Spec
is not updated to 0.7 or later, you must use the object-oriented
interface from File::Spec (or upgrade File::Spec).
In general, production code should not have file paths hardcoded.
Making them user-supplied or read from a configuration file is
better, keeping in mind that file path syntax varies on different
machines.
This is especially noticeable in scripts like Makefiles and test suites,
which often assume C</> as a path separator for subdirectories.
Also of use is File::Basename from the standard distribution, which
splits a pathname into pieces (base filename, full path to directory,
and file suffix).
Even when on a single platform (if you can call Unix a single platform),
remember not to count on the existence or the contents of particular
system-specific files or directories, like F</etc/passwd>,
F</etc/sendmail.conf>, F</etc/resolv.conf>, or even F</tmp/>. For
example, F</etc/passwd> may exist but not contain the encrypted
passwords, because the system is using some form of enhanced security.
Or it may not contain all the accounts, because the system is using NIS.
If code does need to rely on such a file, include a description of the
file and its format in the code's documentation, then make it easy for
the user to override the default location of the file.
Don't assume a text file will end with a newline. They should,
but people forget.
Do not have two files or directories of the same name with different
case, like F<test.pl> and F<Test.pl>, as many platforms have
case-insensitive (or at least case-forgiving) filenames. Also, try
not to have non-word characters (except for C<.>) in the names, and
keep them to the 8.3 convention, for maximum portability, onerous a
burden though this may appear.
Likewise, when using the AutoSplit module, try to keep your functions to
8.3 naming and case-insensitive conventions; or, at the least,
make it so the resulting files have a unique (case-insensitively)
first 8 characters.
Whitespace in filenames is tolerated on most systems, but not all,
and even on systems where it might be tolerated, some utilities
might become confused by such whitespace.
Many systems (DOS, VMS ODS-2) cannot have more than one C<.> in their
filenames.
Don't assume C<< > >> won't be the first character of a filename.
Always use C<< < >> explicitly to open a file for reading, or even
better, use the three-arg version of open, unless you want the user to
be able to specify a pipe open.
open(FILE, '<', $existing_file) or die $!;
If filenames might use strange characters, it is safest to open it
with C<sysopen> instead of C<open>. C<open> is magic and can
translate characters like C<< > >>, C<< < >>, and C<|>, which may
be the wrong thing to do. (Sometimes, though, it's the right thing.)
Three-arg open can also help protect against this translation in cases
where it is undesirable.
Don't use C<:> as a part of a filename since many systems use that for
their own semantics (Mac OS Classic for separating pathname components,
many networking schemes and utilities for separating the nodename and
the pathname, and so on). For the same reasons, avoid C<@>, C<;> and
C<|>.
Don't assume that in pathnames you can collapse two leading slashes
C<//> into one: some networking and clustering filesystems have special
semantics for that. Let the operating system to sort it out.
The I<portable filename characters> as defined by ANSI C are
a b c d e f g h i j k l m n o p q r t u v w x y z
A B C D E F G H I J K L M N O P Q R T U V W X Y Z
0 1 2 3 4 5 6 7 8 9
. _ -
and the "-" shouldn't be the first character. If you want to be
hypercorrect, stay case-insensitive and within the 8.3 naming
convention (all the files and directories have to be unique within one
directory if their names are lowercased and truncated to eight
characters before the C<.>, if any, and to three characters after the
C<.>, if any). (And do not use C<.>s in directory names.)
=head2 System Interaction
Not all platforms provide a command line. These are usually platforms
that rely primarily on a Graphical User Interface (GUI) for user
interaction. A program requiring a command line interface might
not work everywhere. This is probably for the user of the program
to deal with, so don't stay up late worrying about it.
Some platforms can't delete or rename files held open by the system,
this limitation may also apply to changing filesystem metainformation
like file permissions or owners. Remember to C<close> files when you
are done with them. Don't C<unlink> or C<rename> an open file. Don't
C<tie> or C<open> a file already tied or opened; C<untie> or C<close>
it first.
Don't open the same file more than once at a time for writing, as some
operating systems put mandatory locks on such files.
Don't assume that write/modify permission on a directory gives the
right to add or delete files/directories in that directory. That is
filesystem specific: in some filesystems you need write/modify
permission also (or even just) in the file/directory itself. In some
filesystems (AFS, DFS) the permission to add/delete directory entries
is a completely separate permission.
Don't assume that a single C<unlink> completely gets rid of the file:
some filesystems (most notably the ones in VMS) have versioned
filesystems, and unlink() removes only the most recent one (it doesn't
remove all the versions because by default the native tools on those
platforms remove just the most recent version, too). The portable
idiom to remove all the versions of a file is
1 while unlink "file";
This will terminate if the file is undeleteable for some reason
(protected, not there, and so on).
Don't count on a specific environment variable existing in C<%ENV>.
Don't count on C<%ENV> entries being case-sensitive, or even
case-preserving. Don't try to clear %ENV by saying C<%ENV = ();>, or,
if you really have to, make it conditional on C<$^O ne 'VMS'> since in
VMS the C<%ENV> table is much more than a per-process key-value string
table.
On VMS, some entries in the %ENV hash are dynamically created when
their key is used on a read if they did not previously exist. The
values for C<$ENV{HOME}>, C<$ENV{TERM}>, C<$ENV{HOME}>, and C<$ENV{USER}>,
are known to be dynamically generated. The specific names that are
dynamically generated may vary with the version of the C library on VMS,
and more may exist than is documented.
On VMS by default, changes to the %ENV hash are persistent after the process
exits. This can cause unintended issues.
Don't count on signals or C<%SIG> for anything.
Don't count on filename globbing. Use C<opendir>, C<readdir>, and
C<closedir> instead.
Don't count on per-program environment variables, or per-program current
directories.
Don't count on specific values of C<$!>, neither numeric nor
especially the strings values-- users may switch their locales causing
error messages to be translated into their languages. If you can
trust a POSIXish environment, you can portably use the symbols defined
by the Errno module, like ENOENT. And don't trust on the values of C<$!>
at all except immediately after a failed system call.
=head2 Command names versus file pathnames
Don't assume that the name used to invoke a command or program with
C<system> or C<exec> can also be used to test for the existence of the
file that holds the executable code for that command or program.
First, many systems have "internal" commands that are built-in to the
shell or OS and while these commands can be invoked, there is no
corresponding file. Second, some operating systems (e.g., Cygwin,
DJGPP, OS/2, and VOS) have required suffixes for executable files;
these suffixes are generally permitted on the command name but are not
required. Thus, a command like "perl" might exist in a file named
"perl", "perl.exe", or "perl.pm", depending on the operating system.
The variable "_exe" in the Config module holds the executable suffix,
if any. Third, the VMS port carefully sets up $^X and
$Config{perlpath} so that no further processing is required. This is
just as well, because the matching regular expression used below would
then have to deal with a possible trailing version number in the VMS
file name.
To convert $^X to a file pathname, taking account of the requirements
of the various operating system possibilities, say:
use Config;
$thisperl = $^X;
if ($^O ne 'VMS')
{$thisperl .= $Config{_exe} unless $thisperl =~ m/$Config{_exe}$/i;}
To convert $Config{perlpath} to a file pathname, say:
use Config;
$thisperl = $Config{perlpath};
if ($^O ne 'VMS')
{$thisperl .= $Config{_exe} unless $thisperl =~ m/$Config{_exe}$/i;}
=head2 Networking
Don't assume that you can reach the public Internet.
Don't assume that there is only one way to get through firewalls
to the public Internet.
Don't assume that you can reach outside world through any other port
than 80, or some web proxy. ftp is blocked by many firewalls.
Don't assume that you can send email by connecting to the local SMTP port.
Don't assume that you can reach yourself or any node by the name
'localhost'. The same goes for '127.0.0.1'. You will have to try both.
Don't assume that the host has only one network card, or that it
can't bind to many virtual IP addresses.
Don't assume a particular network device name.
Don't assume a particular set of ioctl()s will work.
Don't assume that you can ping hosts and get replies.
Don't assume that any particular port (service) will respond.
Don't assume that Sys::Hostname (or any other API or command)
returns either a fully qualified hostname or a non-qualified hostname:
it all depends on how the system had been configured. Also remember
things like DHCP and NAT-- the hostname you get back might not be very
useful.
All the above "don't":s may look daunting, and they are -- but the key
is to degrade gracefully if one cannot reach the particular network
service one wants. Croaking or hanging do not look very professional.
=head2 Interprocess Communication (IPC)
In general, don't directly access the system in code meant to be
portable. That means, no C<system>, C<exec>, C<fork>, C<pipe>,
C<``>, C<qx//>, C<open> with a C<|>, nor any of the other things
that makes being a perl hacker worth being.
Commands that launch external processes are generally supported on
most platforms (though many of them do not support any type of
forking). The problem with using them arises from what you invoke
them on. External tools are often named differently on different
platforms, may not be available in the same location, might accept
different arguments, can behave differently, and often present their
results in a platform-dependent way. Thus, you should seldom depend
on them to produce consistent results. (Then again, if you're calling
I<netstat -a>, you probably don't expect it to run on both Unix and CP/M.)
One especially common bit of Perl code is opening a pipe to B<sendmail>:
open(MAIL, '|/usr/lib/sendmail -t')
or die "cannot fork sendmail: $!";
This is fine for systems programming when sendmail is known to be
available. But it is not fine for many non-Unix systems, and even
some Unix systems that may not have sendmail installed. If a portable
solution is needed, see the various distributions on CPAN that deal
with it. Mail::Mailer and Mail::Send in the MailTools distribution are
commonly used, and provide several mailing methods, including mail,
sendmail, and direct SMTP (via Net::SMTP) if a mail transfer agent is
not available. Mail::Sendmail is a standalone module that provides
simple, platform-independent mailing.
The Unix System V IPC (C<msg*(), sem*(), shm*()>) is not available
even on all Unix platforms.
Do not use either the bare result of C<pack("N", 10, 20, 30, 40)> or
bare v-strings (such as C<v10.20.30.40>) to represent IPv4 addresses:
both forms just pack the four bytes into network order. That this
would be equal to the C language C<in_addr> struct (which is what the
socket code internally uses) is not guaranteed. To be portable use
the routines of the Socket extension, such as C<inet_aton()>,
C<inet_ntoa()>, and C<sockaddr_in()>.
The rule of thumb for portable code is: Do it all in portable Perl, or
use a module (that may internally implement it with platform-specific
code, but expose a common interface).
=head2 External Subroutines (XS)
XS code can usually be made to work with any platform, but dependent
libraries, header files, etc., might not be readily available or
portable, or the XS code itself might be platform-specific, just as Perl
code might be. If the libraries and headers are portable, then it is
normally reasonable to make sure the XS code is portable, too.
A different type of portability issue arises when writing XS code:
availability of a C compiler on the end-user's system. C brings
with it its own portability issues, and writing XS code will expose
you to some of those. Writing purely in Perl is an easier way to
achieve portability.
=head2 Standard Modules
In general, the standard modules work across platforms. Notable
exceptions are the CPAN module (which currently makes connections to external
programs that may not be available), platform-specific modules (like
ExtUtils::MM_VMS), and DBM modules.
There is no one DBM module available on all platforms.
SDBM_File and the others are generally available on all Unix and DOSish
ports, but not in MacPerl, where only NBDM_File and DB_File are
available.
The good news is that at least some DBM module should be available, and
AnyDBM_File will use whichever module it can find. Of course, then
the code needs to be fairly strict, dropping to the greatest common
factor (e.g., not exceeding 1K for each record), so that it will
work with any DBM module. See L<AnyDBM_File> for more details.
=head2 Time and Date
The system's notion of time of day and calendar date is controlled in
widely different ways. Don't assume the timezone is stored in C<$ENV{TZ}>,
and even if it is, don't assume that you can control the timezone through
that variable. Don't assume anything about the three-letter timezone
abbreviations (for example that MST would be the Mountain Standard Time,
it's been known to stand for Moscow Standard Time). If you need to
use timezones, express them in some unambiguous format like the
exact number of minutes offset from UTC, or the POSIX timezone
format.
Don't assume that the epoch starts at 00:00:00, January 1, 1970,
because that is OS- and implementation-specific. It is better to
store a date in an unambiguous representation. The ISO 8601 standard
defines YYYY-MM-DD as the date format, or YYYY-MM-DDTHH-MM-SS
(that's a literal "T" separating the date from the time).
Please do use the ISO 8601 instead of making us to guess what
date 02/03/04 might be. ISO 8601 even sorts nicely as-is.
A text representation (like "1987-12-18") can be easily converted
into an OS-specific value using a module like Date::Parse.
An array of values, such as those returned by C<localtime>, can be
converted to an OS-specific representation using Time::Local.
When calculating specific times, such as for tests in time or date modules,
it may be appropriate to calculate an offset for the epoch.
require Time::Local;
$offset = Time::Local::timegm(0, 0, 0, 1, 0, 70);
The value for C<$offset> in Unix will be C<0>, but in Mac OS will be
some large number. C<$offset> can then be added to a Unix time value
to get what should be the proper value on any system.
On Windows (at least), you shouldn't pass a negative value to C<gmtime> or
C<localtime>.
=head2 Character sets and character encoding
Assume very little about character sets.
Assume nothing about numerical values (C<ord>, C<chr>) of characters.
Do not use explicit code point ranges (like \xHH-\xHH); use for
example symbolic character classes like C<[:print:]>.
Do not assume that the alphabetic characters are encoded contiguously
(in the numeric sense). There may be gaps.
Do not assume anything about the ordering of the characters.
The lowercase letters may come before or after the uppercase letters;
the lowercase and uppercase may be interlaced so that both "a" and "A"
come before "b"; the accented and other international characters may
be interlaced so that E<auml> comes before "b".
=head2 Internationalisation
If you may assume POSIX (a rather large assumption), you may read
more about the POSIX locale system from L<perllocale>. The locale
system at least attempts to make things a little bit more portable,
or at least more convenient and native-friendly for non-English
users. The system affects character sets and encoding, and date
and time formatting--amongst other things.
If you really want to be international, you should consider Unicode.
See L<perluniintro> and L<perlunicode> for more information.
If you want to use non-ASCII bytes (outside the bytes 0x00..0x7f) in
the "source code" of your code, to be portable you have to be explicit
about what bytes they are. Someone might for example be using your
code under a UTF-8 locale, in which case random native bytes might be
illegal ("Malformed UTF-8 ...") This means that for example embedding
ISO 8859-1 bytes beyond 0x7f into your strings might cause trouble
later. If the bytes are native 8-bit bytes, you can use the C<bytes>
pragma. If the bytes are in a string (regular expression being a
curious string), you can often also use the C<\xHH> notation instead
of embedding the bytes as-is. (If you want to write your code in UTF-8,
you can use the C<utf8>.) The C<bytes> and C<utf8> pragmata are
available since Perl 5.6.0.
=head2 System Resources
If your code is destined for systems with severely constrained (or
missing!) virtual memory systems then you want to be I<especially> mindful
of avoiding wasteful constructs such as:
# NOTE: this is no longer "bad" in perl5.005
for (0..10000000) {} # bad
for (my $x = 0; $x <= 10000000; ++$x) {} # good
@lines = <VERY_LARGE_FILE>; # bad
while (<FILE>) {$file .= $_} # sometimes bad
$file = join('', <FILE>); # better
The last two constructs may appear unintuitive to most people. The
first repeatedly grows a string, whereas the second allocates a
large chunk of memory in one go. On some systems, the second is
more efficient that the first.
=head2 Security
Most multi-user platforms provide basic levels of security, usually
implemented at the filesystem level. Some, however, do
not-- unfortunately. Thus the notion of user id, or "home" directory,
or even the state of being logged-in, may be unrecognizable on many
platforms. If you write programs that are security-conscious, it
is usually best to know what type of system you will be running
under so that you can write code explicitly for that platform (or
class of platforms).
Don't assume the UNIX filesystem access semantics: the operating
system or the filesystem may be using some ACL systems, which are
richer languages than the usual rwx. Even if the rwx exist,
their semantics might be different.
(From security viewpoint testing for permissions before attempting to
do something is silly anyway: if one tries this, there is potential
for race conditions-- someone or something might change the
permissions between the permissions check and the actual operation.
Just try the operation.)
Don't assume the UNIX user and group semantics: especially, don't
expect the C<< $< >> and C<< $> >> (or the C<$(> and C<$)>) to work
for switching identities (or memberships).
Don't assume set-uid and set-gid semantics. (And even if you do,
think twice: set-uid and set-gid are a known can of security worms.)
=head2 Style
For those times when it is necessary to have platform-specific code,
consider keeping the platform-specific code in one place, making porting
to other platforms easier. Use the Config module and the special
variable C<$^O> to differentiate platforms, as described in
L<"PLATFORMS">.
Be careful in the tests you supply with your module or programs.
Module code may be fully portable, but its tests might not be. This
often happens when tests spawn off other processes or call external
programs to aid in the testing, or when (as noted above) the tests
assume certain things about the filesystem and paths. Be careful not
to depend on a specific output style for errors, such as when checking
C<$!> after a failed system call. Using C<$!> for anything else than
displaying it as output is doubtful (though see the Errno module for
testing reasonably portably for error value). Some platforms expect
a certain output format, and Perl on those platforms may have been
adjusted accordingly. Most specifically, don't anchor a regex when
testing an error value.
=head1 CPAN Testers
Modules uploaded to CPAN are tested by a variety of volunteers on
different platforms. These CPAN testers are notified by mail of each
new upload, and reply to the list with PASS, FAIL, NA (not applicable to
this platform), or UNKNOWN (unknown), along with any relevant notations.
The purpose of the testing is twofold: one, to help developers fix any
problems in their code that crop up because of lack of testing on other
platforms; two, to provide users with information about whether
a given module works on a given platform.
Also see:
=over 4
=item *
Mailing list: cpan-testers@perl.org
=item *
Testing results: http://testers.cpan.org/
=back
=head1 PLATFORMS
As of version 5.002, Perl is built with a C<$^O> variable that
indicates the operating system it was built on. This was implemented
to help speed up code that would otherwise have to C<use Config>
and use the value of C<$Config{osname}>. Of course, to get more
detailed information about the system, looking into C<%Config> is
certainly recommended.
C<%Config> cannot always be trusted, however, because it was built
at compile time. If perl was built in one place, then transferred
elsewhere, some values may be wrong. The values may even have been
edited after the fact.
=head2 Unix
Perl works on a bewildering variety of Unix and Unix-like platforms (see
e.g. most of the files in the F<hints/> directory in the source code kit).
On most of these systems, the value of C<$^O> (hence C<$Config{'osname'}>,
too) is determined either by lowercasing and stripping punctuation from the
first field of the string returned by typing C<uname -a> (or a similar command)
at the shell prompt or by testing the file system for the presence of
uniquely named files such as a kernel or header file. Here, for example,
are a few of the more popular Unix flavors:
uname $^O $Config{'archname'}
--------------------------------------------
AIX aix aix
BSD/OS bsdos i386-bsdos
Darwin darwin darwin
dgux dgux AViiON-dgux
DYNIX/ptx dynixptx i386-dynixptx
FreeBSD freebsd freebsd-i386
Linux linux arm-linux
Linux linux i386-linux
Linux linux i586-linux
Linux linux ppc-linux
HP-UX hpux PA-RISC1.1
IRIX irix irix
Mac OS X darwin darwin
MachTen PPC machten powerpc-machten
NeXT 3 next next-fat
NeXT 4 next OPENSTEP-Mach
openbsd openbsd i386-openbsd
OSF1 dec_osf alpha-dec_osf
reliantunix-n svr4 RM400-svr4
SCO_SV sco_sv i386-sco_sv
SINIX-N svr4 RM400-svr4
sn4609 unicos CRAY_C90-unicos
sn6521 unicosmk t3e-unicosmk
sn9617 unicos CRAY_J90-unicos
SunOS solaris sun4-solaris
SunOS solaris i86pc-solaris
SunOS4 sunos sun4-sunos
Because the value of C<$Config{archname}> may depend on the
hardware architecture, it can vary more than the value of C<$^O>.
=head2 DOS and Derivatives
Perl has long been ported to Intel-style microcomputers running under
systems like PC-DOS, MS-DOS, OS/2, and most Windows platforms you can
bring yourself to mention (except for Windows CE, if you count that).
Users familiar with I<COMMAND.COM> or I<CMD.EXE> style shells should
be aware that each of these file specifications may have subtle
differences:
$filespec0 = "c:/foo/bar/file.txt";
$filespec1 = "c:\\foo\\bar\\file.txt";
$filespec2 = 'c:\foo\bar\file.txt';
$filespec3 = 'c:\\foo\\bar\\file.txt';
System calls accept either C</> or C<\> as the path separator.
However, many command-line utilities of DOS vintage treat C</> as
the option prefix, so may get confused by filenames containing C</>.
Aside from calling any external programs, C</> will work just fine,
and probably better, as it is more consistent with popular usage,
and avoids the problem of remembering what to backwhack and what
not to.
The DOS FAT filesystem can accommodate only "8.3" style filenames. Under
the "case-insensitive, but case-preserving" HPFS (OS/2) and NTFS (NT)
filesystems you may have to be careful about case returned with functions
like C<readdir> or used with functions like C<open> or C<opendir>.
DOS also treats several filenames as special, such as AUX, PRN,
NUL, CON, COM1, LPT1, LPT2, etc. Unfortunately, sometimes these
filenames won't even work if you include an explicit directory
prefix. It is best to avoid such filenames, if you want your code
to be portable to DOS and its derivatives. It's hard to know what
these all are, unfortunately.
Users of these operating systems may also wish to make use of
scripts such as I<pl2bat.bat> or I<pl2cmd> to
put wrappers around your scripts.
Newline (C<\n>) is translated as C<\015\012> by STDIO when reading from
and writing to files (see L<"Newlines">). C<binmode(FILEHANDLE)>
will keep C<\n> translated as C<\012> for that filehandle. Since it is a
no-op on other systems, C<binmode> should be used for cross-platform code
that deals with binary data. That's assuming you realize in advance
that your data is in binary. General-purpose programs should
often assume nothing about their data.
The C<$^O> variable and the C<$Config{archname}> values for various
DOSish perls are as follows:
OS $^O $Config{archname} ID Version
--------------------------------------------------------
MS-DOS dos ?
PC-DOS dos ?
OS/2 os2 ?
Windows 3.1 ? ? 0 3 01
Windows 95 MSWin32 MSWin32-x86 1 4 00
Windows 98 MSWin32 MSWin32-x86 1 4 10
Windows ME MSWin32 MSWin32-x86 1 ?
Windows NT MSWin32 MSWin32-x86 2 4 xx
Windows NT MSWin32 MSWin32-ALPHA 2 4 xx
Windows NT MSWin32 MSWin32-ppc 2 4 xx
Windows 2000 MSWin32 MSWin32-x86 2 5 00
Windows XP MSWin32 MSWin32-x86 2 5 01
Windows 2003 MSWin32 MSWin32-x86 2 5 02
Windows CE MSWin32 ? 3
Cygwin cygwin cygwin
The various MSWin32 Perl's can distinguish the OS they are running on
via the value of the fifth element of the list returned from
Win32::GetOSVersion(). For example:
if ($^O eq 'MSWin32') {
my @os_version_info = Win32::GetOSVersion();
print +('3.1','95','NT')[$os_version_info[4]],"\n";
}
There are also Win32::IsWinNT() and Win32::IsWin95(), try C<perldoc Win32>,
and as of libwin32 0.19 (not part of the core Perl distribution)
Win32::GetOSName(). The very portable POSIX::uname() will work too:
c:\> perl -MPOSIX -we "print join '|', uname"
Windows NT|moonru|5.0|Build 2195 (Service Pack 2)|x86
Also see:
=over 4
=item *
The djgpp environment for DOS, http://www.delorie.com/djgpp/
and L<perldos>.
=item *
The EMX environment for DOS, OS/2, etc. emx@iaehv.nl,
http://www.leo.org/pub/comp/os/os2/leo/gnu/emx+gcc/index.html or
ftp://hobbes.nmsu.edu/pub/os2/dev/emx/ Also L<perlos2>.
=item *
Build instructions for Win32 in L<perlwin32>, or under the Cygnus environment
in L<perlcygwin>.
=item *
The C<Win32::*> modules in L<Win32>.
=item *
The ActiveState Pages, http://www.activestate.com/
=item *
The Cygwin environment for Win32; F<README.cygwin> (installed
as L<perlcygwin>), http://www.cygwin.com/
=item *
The U/WIN environment for Win32,
http://www.research.att.com/sw/tools/uwin/
=item *
Build instructions for OS/2, L<perlos2>
=back
=head2 S<Mac OS>
Any module requiring XS compilation is right out for most people, because
MacPerl is built using non-free (and non-cheap!) compilers. Some XS
modules that can work with MacPerl are built and distributed in binary
form on CPAN.
Directories are specified as:
volume:folder:file for absolute pathnames
volume:folder: for absolute pathnames
:folder:file for relative pathnames
:folder: for relative pathnames
:file for relative pathnames
file for relative pathnames
Files are stored in the directory in alphabetical order. Filenames are
limited to 31 characters, and may include any character except for
null and C<:>, which is reserved as the path separator.
Instead of C<flock>, see C<FSpSetFLock> and C<FSpRstFLock> in the
Mac::Files module, or C<chmod(0444, ...)> and C<chmod(0666, ...)>.
In the MacPerl application, you can't run a program from the command line;
programs that expect C<@ARGV> to be populated can be edited with something
like the following, which brings up a dialog box asking for the command
line arguments.
if (!@ARGV) {
@ARGV = split /\s+/, MacPerl::Ask('Arguments?');
}
A MacPerl script saved as a "droplet" will populate C<@ARGV> with the full
pathnames of the files dropped onto the script.
Mac users can run programs under a type of command line interface
under MPW (Macintosh Programmer's Workshop, a free development
environment from Apple). MacPerl was first introduced as an MPW
tool, and MPW can be used like a shell:
perl myscript.plx some arguments
ToolServer is another app from Apple that provides access to MPW tools
from MPW and the MacPerl app, which allows MacPerl programs to use
C<system>, backticks, and piped C<open>.
"S<Mac OS>" is the proper name for the operating system, but the value
in C<$^O> is "MacOS". To determine architecture, version, or whether
the application or MPW tool version is running, check:
$is_app = $MacPerl::Version =~ /App/;
$is_tool = $MacPerl::Version =~ /MPW/;
($version) = $MacPerl::Version =~ /^(\S+)/;
$is_ppc = $MacPerl::Architecture eq 'MacPPC';
$is_68k = $MacPerl::Architecture eq 'Mac68K';
S<Mac OS X>, based on NeXT's OpenStep OS, runs MacPerl natively, under the
"Classic" environment. There is no "Carbon" version of MacPerl to run
under the primary Mac OS X environment. S<Mac OS X> and its Open Source
version, Darwin, both run Unix perl natively.
Also see:
=over 4
=item *
MacPerl Development, http://dev.macperl.org/ .
=item *
The MacPerl Pages, http://www.macperl.com/ .
=item *
The MacPerl mailing lists, http://lists.perl.org/ .
=item *
MPW, ftp://ftp.apple.com/developer/Tool_Chest/Core_Mac_OS_Tools/
=back
=head2 VMS
Perl on VMS is discussed in L<perlvms> in the perl distribution.
The official name of VMS as of this writing is OpenVMS.
Perl on VMS can accept either VMS- or Unix-style file
specifications as in either of the following:
$ perl -ne "print if /perl_setup/i" SYS$LOGIN:LOGIN.COM
$ perl -ne "print if /perl_setup/i" /sys$login/login.com
but not a mixture of both as in:
$ perl -ne "print if /perl_setup/i" sys$login:/login.com
Can't open sys$login:/login.com: file specification syntax error
Interacting with Perl from the Digital Command Language (DCL) shell
often requires a different set of quotation marks than Unix shells do.
For example:
$ perl -e "print ""Hello, world.\n"""
Hello, world.
There are several ways to wrap your perl scripts in DCL F<.COM> files, if
you are so inclined. For example:
$ write sys$output "Hello from DCL!"
$ if p1 .eqs. ""
$ then perl -x 'f$environment("PROCEDURE")
$ else perl -x - 'p1 'p2 'p3 'p4 'p5 'p6 'p7 'p8
$ deck/dollars="__END__"
#!/usr/bin/perl
print "Hello from Perl!\n";
__END__
$ endif
Do take care with C<$ ASSIGN/nolog/user SYS$COMMAND: SYS$INPUT> if your
perl-in-DCL script expects to do things like C<< $read = <STDIN>; >>.
The VMS operating system has two filesystems, known as ODS-2 and ODS-5.
For ODS-2, filenames are in the format "name.extension;version". The
maximum length for filenames is 39 characters, and the maximum length for
extensions is also 39 characters. Version is a number from 1 to
32767. Valid characters are C</[A-Z0-9$_-]/>.
The ODS-2 filesystem is case-insensitive and does not preserve case.
Perl simulates this by converting all filenames to lowercase internally.
For ODS-5, filenames may have almost any character in them and can include
Unicode characters. Characters that could be misinterpreted by the DCL
shell or file parsing utilities need to be prefixed with the C<^>
character, or replaced with hexadecimal characters prefixed with the
C<^> character. Such prefixing is only needed with the pathnames are
in VMS format in applications. Programs that can accept the UNIX format
of pathnames do not need the escape characters. The maximum length for
filenames is 255 characters. The ODS-5 file system can handle both
a case preserved and a case sensitive mode.
ODS-5 is only available on the OpenVMS for 64 bit platforms.
Support for the extended file specifications is being done as optional
settings to preserve backward compatibility with Perl scripts that
assume the previous VMS limitations.
In general routines on VMS that get a UNIX format file specification
should return it in a UNIX format, and when they get a VMS format
specification they should return a VMS format unless they are documented
to do a conversion.
For routines that generate return a file specification, VMS allows setting
if the C library which Perl is built on if it will be returned in VMS
format or in UNIX format.
With the ODS-2 file system, there is not much difference in syntax of
filenames without paths for VMS or UNIX. With the extended character
set available with ODS-5 there can be a significant difference.
Because of this, existing Perl scripts written for VMS were sometimes
treating VMS and UNIX filenames interchangeably. Without the extended
character set enabled, this behavior will mostly be maintained for
backwards compatibility.
When extended characters are enabled with ODS-5, the handling of
UNIX formatted file specifications is to that of a UNIX system.
VMS file specifications without extensions have a trailing dot. An
equivalent UNIX file specification should not show the trailing dot.
The result of all of this, is that for VMS, for portable scripts, you
can not depend on Perl to present the filenames in lowercase, to be
case sensitive, and that the filenames could be returned in either
UNIX or VMS format.
And if a routine returns a file specification, unless it is intended to
convert it, it should return it in the same format as it found it.
C<readdir> by default has traditionally returned lowercased filenames.
When the ODS-5 support is enabled, it will return the exact case of the
filename on the disk.
Files without extensions have a trailing period on them, so doing a
C<readdir> in the default mode with a file named F<A.;5> will
return F<a.> when VMS is (though that file could be opened with
C<open(FH, 'A')>).
With support for extended file specifications and if C<opendir> was
given a UNIX format directory, a file named F<A.;5> will return F<a>
and optionally in the exact case on the disk. When C<opendir> is given
a VMS format directory, then C<readdir> should return F<a.>, and
again with the optionally the exact case.
RMS had an eight level limit on directory depths from any rooted logical
(allowing 16 levels overall) prior to VMS 7.2, and even with versions of
VMS on VAX up through 7.3. Hence C<PERL_ROOT:[LIB.2.3.4.5.6.7.8]> is a
valid directory specification but C<PERL_ROOT:[LIB.2.3.4.5.6.7.8.9]> is
not. F<Makefile.PL> authors might have to take this into account, but at
least they can refer to the former as C</PERL_ROOT/lib/2/3/4/5/6/7/8/>.
Pumpkings and module integrators can easily see whether files with too many
directory levels have snuck into the core by running the following in the
top-level source directory:
$ perl -ne "$_=~s/\s+.*//; print if scalar(split /\//) > 8;" < MANIFEST
The VMS::Filespec module, which gets installed as part of the build
process on VMS, is a pure Perl module that can easily be installed on
non-VMS platforms and can be helpful for conversions to and from RMS
native formats. It is also now the only way that you should check to
see if VMS is in a case sensitive mode.
What C<\n> represents depends on the type of file opened. It usually
represents C<\012> but it could also be C<\015>, C<\012>, C<\015\012>,
C<\000>, C<\040>, or nothing depending on the file organization and
record format. The VMS::Stdio module provides access to the
special fopen() requirements of files with unusual attributes on VMS.
TCP/IP stacks are optional on VMS, so socket routines might not be
implemented. UDP sockets may not be supported.
The TCP/IP library support for all current versions of VMS is dynamically
loaded if present, so even if the routines are configured, they may
return a status indicating that they are not implemented.
The value of C<$^O> on OpenVMS is "VMS". To determine the architecture
that you are running on without resorting to loading all of C<%Config>
you can examine the content of the C<@INC> array like so:
if (grep(/VMS_AXP/, @INC)) {
print "I'm on Alpha!\n";
} elsif (grep(/VMS_VAX/, @INC)) {
print "I'm on VAX!\n";
} elsif (grep(/VMS_IA64/, @INC)) {
print "I'm on IA64!\n";
} else {
print "I'm not so sure about where $^O is...\n";
}
In general, the significant differences should only be if Perl is running
on VMS_VAX or one of the 64 bit OpenVMS platforms.
On VMS, perl determines the UTC offset from the C<SYS$TIMEZONE_DIFFERENTIAL>
logical name. Although the VMS epoch began at 17-NOV-1858 00:00:00.00,
calls to C<localtime> are adjusted to count offsets from
01-JAN-1970 00:00:00.00, just like Unix.
Also see:
=over 4
=item *
F<README.vms> (installed as L<README_vms>), L<perlvms>
=item *
vmsperl list, vmsperl-subscribe@perl.org
=item *
vmsperl on the web, http://www.sidhe.org/vmsperl/index.html
=back
=head2 VOS
Perl on VOS is discussed in F<README.vos> in the perl distribution
(installed as L<perlvos>). Perl on VOS can accept either VOS- or
Unix-style file specifications as in either of the following:
C<< $ perl -ne "print if /perl_setup/i" >system>notices >>
C<< $ perl -ne "print if /perl_setup/i" /system/notices >>
or even a mixture of both as in:
C<< $ perl -ne "print if /perl_setup/i" >system/notices >>
Even though VOS allows the slash character to appear in object
names, because the VOS port of Perl interprets it as a pathname
delimiting character, VOS files, directories, or links whose names
contain a slash character cannot be processed. Such files must be
renamed before they can be processed by Perl. Note that VOS limits
file names to 32 or fewer characters, file names cannot start with a
C<-> character, or contain any character matching C<< tr/ !%&'()*+;<>?// >>
The value of C<$^O> on VOS is "VOS". To determine the architecture that
you are running on without resorting to loading all of C<%Config> you
can examine the content of the @INC array like so:
if ($^O =~ /VOS/) {
print "I'm on a Stratus box!\n";
} else {
print "I'm not on a Stratus box!\n";
die;
}
Also see:
=over 4
=item *
F<README.vos> (installed as L<perlvos>)
=item *
The VOS mailing list.
There is no specific mailing list for Perl on VOS. You can post
comments to the comp.sys.stratus newsgroup, or subscribe to the general
Stratus mailing list. Send a letter with "subscribe Info-Stratus" in
the message body to majordomo@list.stratagy.com.
=item *
VOS Perl on the web at http://ftp.stratus.com/pub/vos/posix/posix.html
=back
=head2 EBCDIC Platforms
Recent versions of Perl have been ported to platforms such as OS/400 on
AS/400 minicomputers as well as OS/390, VM/ESA, and BS2000 for S/390
Mainframes. Such computers use EBCDIC character sets internally (usually
Character Code Set ID 0037 for OS/400 and either 1047 or POSIX-BC for S/390
systems). On the mainframe perl currently works under the "Unix system
services for OS/390" (formerly known as OpenEdition), VM/ESA OpenEdition, or
the BS200 POSIX-BC system (BS2000 is supported in perl 5.6 and greater).
See L<perlos390> for details. Note that for OS/400 there is also a port of
Perl 5.8.1/5.9.0 or later to the PASE which is ASCII-based (as opposed to
ILE which is EBCDIC-based), see L<perlos400>.
As of R2.5 of USS for OS/390 and Version 2.3 of VM/ESA these Unix
sub-systems do not support the C<#!> shebang trick for script invocation.
Hence, on OS/390 and VM/ESA perl scripts can be executed with a header
similar to the following simple script:
: # use perl
eval 'exec /usr/local/bin/perl -S $0 ${1+"$@"}'
if 0;
#!/usr/local/bin/perl # just a comment really
print "Hello from perl!\n";
OS/390 will support the C<#!> shebang trick in release 2.8 and beyond.
Calls to C<system> and backticks can use POSIX shell syntax on all
S/390 systems.
On the AS/400, if PERL5 is in your library list, you may need
to wrap your perl scripts in a CL procedure to invoke them like so:
BEGIN
CALL PGM(PERL5/PERL) PARM('/QOpenSys/hello.pl')
ENDPGM
This will invoke the perl script F<hello.pl> in the root of the
QOpenSys file system. On the AS/400 calls to C<system> or backticks
must use CL syntax.
On these platforms, bear in mind that the EBCDIC character set may have
an effect on what happens with some perl functions (such as C<chr>,
C<pack>, C<print>, C<printf>, C<ord>, C<sort>, C<sprintf>, C<unpack>), as
well as bit-fiddling with ASCII constants using operators like C<^>, C<&>
and C<|>, not to mention dealing with socket interfaces to ASCII computers
(see L<"Newlines">).
Fortunately, most web servers for the mainframe will correctly
translate the C<\n> in the following statement to its ASCII equivalent
(C<\r> is the same under both Unix and OS/390 & VM/ESA):
print "Content-type: text/html\r\n\r\n";
The values of C<$^O> on some of these platforms includes:
uname $^O $Config{'archname'}
--------------------------------------------
OS/390 os390 os390
OS400 os400 os400
POSIX-BC posix-bc BS2000-posix-bc
VM/ESA vmesa vmesa
Some simple tricks for determining if you are running on an EBCDIC
platform could include any of the following (perhaps all):
if ("\t" eq "\05") { print "EBCDIC may be spoken here!\n"; }
if (ord('A') == 193) { print "EBCDIC may be spoken here!\n"; }
if (chr(169) eq 'z') { print "EBCDIC may be spoken here!\n"; }
One thing you may not want to rely on is the EBCDIC encoding
of punctuation characters since these may differ from code page to code
page (and once your module or script is rumoured to work with EBCDIC,
folks will want it to work with all EBCDIC character sets).
Also see:
=over 4
=item *
L<perlos390>, F<README.os390>, F<perlbs2000>, F<README.vmesa>,
L<perlebcdic>.
=item *
The perl-mvs@perl.org list is for discussion of porting issues as well as
general usage issues for all EBCDIC Perls. Send a message body of
"subscribe perl-mvs" to majordomo@perl.org.
=item *
AS/400 Perl information at
http://as400.rochester.ibm.com/
as well as on CPAN in the F<ports/> directory.
=back
=head2 Acorn RISC OS
Because Acorns use ASCII with newlines (C<\n>) in text files as C<\012> like
Unix, and because Unix filename emulation is turned on by default,
most simple scripts will probably work "out of the box". The native
filesystem is modular, and individual filesystems are free to be
case-sensitive or insensitive, and are usually case-preserving. Some
native filesystems have name length limits, which file and directory
names are silently truncated to fit. Scripts should be aware that the
standard filesystem currently has a name length limit of B<10>
characters, with up to 77 items in a directory, but other filesystems
may not impose such limitations.
Native filenames are of the form
Filesystem#Special_Field::DiskName.$.Directory.Directory.File
where
Special_Field is not usually present, but may contain . and $ .
Filesystem =~ m|[A-Za-z0-9_]|
DsicName =~ m|[A-Za-z0-9_/]|
$ represents the root directory
. is the path separator
@ is the current directory (per filesystem but machine global)
^ is the parent directory
Directory and File =~ m|[^\0- "\.\$\%\&:\@\\^\|\177]+|
The default filename translation is roughly C<tr|/.|./|;>
Note that C<"ADFS::HardDisk.$.File" ne 'ADFS::HardDisk.$.File'> and that
the second stage of C<$> interpolation in regular expressions will fall
foul of the C<$.> if scripts are not careful.
Logical paths specified by system variables containing comma-separated
search lists are also allowed; hence C<System:Modules> is a valid
filename, and the filesystem will prefix C<Modules> with each section of
C<System$Path> until a name is made that points to an object on disk.
Writing to a new file C<System:Modules> would be allowed only if
C<System$Path> contains a single item list. The filesystem will also
expand system variables in filenames if enclosed in angle brackets, so
C<< <System$Dir>.Modules >> would look for the file
S<C<$ENV{'System$Dir'} . 'Modules'>>. The obvious implication of this is
that B<fully qualified filenames can start with C<< <> >>> and should
be protected when C<open> is used for input.
Because C<.> was in use as a directory separator and filenames could not
be assumed to be unique after 10 characters, Acorn implemented the C
compiler to strip the trailing C<.c> C<.h> C<.s> and C<.o> suffix from
filenames specified in source code and store the respective files in
subdirectories named after the suffix. Hence files are translated:
foo.h h.foo
C:foo.h C:h.foo (logical path variable)
sys/os.h sys.h.os (C compiler groks Unix-speak)
10charname.c c.10charname
10charname.o o.10charname
11charname_.c c.11charname (assuming filesystem truncates at 10)
The Unix emulation library's translation of filenames to native assumes
that this sort of translation is required, and it allows a user-defined list
of known suffixes that it will transpose in this fashion. This may
seem transparent, but consider that with these rules C<foo/bar/baz.h>
and C<foo/bar/h/baz> both map to C<foo.bar.h.baz>, and that C<readdir> and
C<glob> cannot and do not attempt to emulate the reverse mapping. Other
C<.>'s in filenames are translated to C</>.
As implied above, the environment accessed through C<%ENV> is global, and
the convention is that program specific environment variables are of the
form C<Program$Name>. Each filesystem maintains a current directory,
and the current filesystem's current directory is the B<global> current
directory. Consequently, sociable programs don't change the current
directory but rely on full pathnames, and programs (and Makefiles) cannot
assume that they can spawn a child process which can change the current
directory without affecting its parent (and everyone else for that
matter).
Because native operating system filehandles are global and are currently
allocated down from 255, with 0 being a reserved value, the Unix emulation
library emulates Unix filehandles. Consequently, you can't rely on
passing C<STDIN>, C<STDOUT>, or C<STDERR> to your children.
The desire of users to express filenames of the form
C<< <Foo$Dir>.Bar >> on the command line unquoted causes problems,
too: C<``> command output capture has to perform a guessing game. It
assumes that a string C<< <[^<>]+\$[^<>]> >> is a
reference to an environment variable, whereas anything else involving
C<< < >> or C<< > >> is redirection, and generally manages to be 99%
right. Of course, the problem remains that scripts cannot rely on any
Unix tools being available, or that any tools found have Unix-like command
line arguments.
Extensions and XS are, in theory, buildable by anyone using free
tools. In practice, many don't, as users of the Acorn platform are
used to binary distributions. MakeMaker does run, but no available
make currently copes with MakeMaker's makefiles; even if and when
this should be fixed, the lack of a Unix-like shell will cause
problems with makefile rules, especially lines of the form C<cd
sdbm && make all>, and anything using quoting.
"S<RISC OS>" is the proper name for the operating system, but the value
in C<$^O> is "riscos" (because we don't like shouting).
=head2 Other perls
Perl has been ported to many platforms that do not fit into any of
the categories listed above. Some, such as AmigaOS, Atari MiNT,
BeOS, HP MPE/iX, QNX, Plan 9, and VOS, have been well-integrated
into the standard Perl source code kit. You may need to see the
F<ports/> directory on CPAN for information, and possibly binaries,
for the likes of: aos, Atari ST, lynxos, riscos, Novell Netware,
Tandem Guardian, I<etc.> (Yes, we know that some of these OSes may
fall under the Unix category, but we are not a standards body.)
Some approximate operating system names and their C<$^O> values
in the "OTHER" category include:
OS $^O $Config{'archname'}
------------------------------------------
Amiga DOS amigaos m68k-amigos
BeOS beos
MPE/iX mpeix PA-RISC1.1
See also:
=over 4
=item *
Amiga, F<README.amiga> (installed as L<perlamiga>).
=item *
Atari, F<README.mint> and Guido Flohr's web page
http://stud.uni-sb.de/~gufl0000/
=item *
Be OS, F<README.beos>
=item *
HP 300 MPE/iX, F<README.mpeix> and Mark Bixby's web page
http://www.bixby.org/mark/perlix.html
=item *
A free perl5-based PERL.NLM for Novell Netware is available in
precompiled binary and source code form from http://www.novell.com/
as well as from CPAN.
=item *
S<Plan 9>, F<README.plan9>
=back
=head1 FUNCTION IMPLEMENTATIONS
Listed below are functions that are either completely unimplemented
or else have been implemented differently on various platforms.
Following each description will be, in parentheses, a list of
platforms that the description applies to.
The list may well be incomplete, or even wrong in some places. When
in doubt, consult the platform-specific README files in the Perl
source distribution, and any other documentation resources accompanying
a given port.
Be aware, moreover, that even among Unix-ish systems there are variations.
For many functions, you can also query C<%Config>, exported by
default from the Config module. For example, to check whether the
platform has the C<lstat> call, check C<$Config{d_lstat}>. See
L<Config> for a full description of available variables.
=head2 Alphabetical Listing of Perl Functions
=over 8
=item -X
C<-r>, C<-w>, and C<-x> have a limited meaning only; directories
and applications are executable, and there are no uid/gid
considerations. C<-o> is not supported. (S<Mac OS>)
C<-w> only inspects the read-only file attribute (FILE_ATTRIBUTE_READONLY),
which determines whether the directory can be deleted, not whether it can
be written to. Directories always have read and write access unless denied
by discretionary access control lists (DACLs). (S<Win32>)
C<-r>, C<-w>, C<-x>, and C<-o> tell whether the file is accessible,
which may not reflect UIC-based file protections. (VMS)
C<-s> returns the size of the data fork, not the total size of data fork
plus resource fork. (S<Mac OS>).
C<-s> by name on an open file will return the space reserved on disk,
rather than the current extent. C<-s> on an open filehandle returns the
current size. (S<RISC OS>)
C<-R>, C<-W>, C<-X>, C<-O> are indistinguishable from C<-r>, C<-w>,
C<-x>, C<-o>. (S<Mac OS>, Win32, VMS, S<RISC OS>)
C<-b>, C<-c>, C<-k>, C<-g>, C<-p>, C<-u>, C<-A> are not implemented.
(S<Mac OS>)
C<-g>, C<-k>, C<-l>, C<-p>, C<-u>, C<-A> are not particularly meaningful.
(Win32, VMS, S<RISC OS>)
C<-d> is true if passed a device spec without an explicit directory.
(VMS)
C<-T> and C<-B> are implemented, but might misclassify Mac text files
with foreign characters; this is the case will all platforms, but may
affect S<Mac OS> often. (S<Mac OS>)
C<-x> (or C<-X>) determine if a file ends in one of the executable
suffixes. C<-S> is meaningless. (Win32)
C<-x> (or C<-X>) determine if a file has an executable file type.
(S<RISC OS>)
=item atan2
Due to issues with various CPUs, math libraries, compilers, and standards,
results for C<atan2()> may vary depending on any combination of the above.
Perl attempts to conform to the Open Group/IEEE standards for the results
returned from C<atan2()>, but cannot force the issue if the system Perl is
run on does not allow it. (Tru64, HP-UX 10.20)
The current version of the standards for C<atan2()> is available at
L<http://www.opengroup.org/onlinepubs/009695399/functions/atan2.html>.
=item binmode
Meaningless. (S<Mac OS>, S<RISC OS>)
Reopens file and restores pointer; if function fails, underlying
filehandle may be closed, or pointer may be in a different position.
(VMS)
The value returned by C<tell> may be affected after the call, and
the filehandle may be flushed. (Win32)
=item chmod
Only limited meaning. Disabling/enabling write permission is mapped to
locking/unlocking the file. (S<Mac OS>)
Only good for changing "owner" read-write access, "group", and "other"
bits are meaningless. (Win32)
Only good for changing "owner" and "other" read-write access. (S<RISC OS>)
Access permissions are mapped onto VOS access-control list changes. (VOS)
The actual permissions set depend on the value of the C<CYGWIN>
in the SYSTEM environment settings. (Cygwin)
=item chown
Not implemented. (S<Mac OS>, Win32, S<Plan 9>, S<RISC OS>)
Does nothing, but won't fail. (Win32)
A little funky, because VOS's notion of ownership is a little funky (VOS).
=item chroot
Not implemented. (S<Mac OS>, Win32, VMS, S<Plan 9>, S<RISC OS>, VOS, VM/ESA)
=item crypt
May not be available if library or source was not provided when building
perl. (Win32)
=item dbmclose
Not implemented. (VMS, S<Plan 9>, VOS)
=item dbmopen
Not implemented. (VMS, S<Plan 9>, VOS)
=item dump
Not useful. (S<Mac OS>, S<RISC OS>)
Not supported. (Cygwin, Win32)
Invokes VMS debugger. (VMS)
=item exec
Not implemented. (S<Mac OS>)
Implemented via Spawn. (VM/ESA)
Does not automatically flush output handles on some platforms.
(SunOS, Solaris, HP-UX)
=item exit
Emulates UNIX exit() (which considers C<exit 1> to indicate an error) by
mapping the C<1> to SS$_ABORT (C<44>). This behavior may be overridden
with the pragma C<use vmsish 'exit'>. As with the CRTL's exit()
function, C<exit 0> is also mapped to an exit status of SS$_NORMAL
(C<1>); this mapping cannot be overridden. Any other argument to exit()
is used directly as Perl's exit status. On VMS, unless the future
POSIX_EXIT mode is enabled, the exit code should always be a valid
VMS exit code and not a generic number. When the POSIX_EXIT mode is
enabled, a generic number will be encoded in a method compatible with
the C library _POSIX_EXIT macro so that it can be decoded by other
programs, particularly ones written in C, like the GNV package. (VMS)
=item fcntl
Not implemented. (Win32)
Some functions available based on the version of VMS. (VMS)
=item flock
Not implemented (S<Mac OS>, VMS, S<RISC OS>, VOS).
Available only on Windows NT (not on Windows 95). (Win32)
=item fork
Not implemented. (S<Mac OS>, AmigaOS, S<RISC OS>, VM/ESA, VMS)
Emulated using multiple interpreters. See L<perlfork>. (Win32)
Does not automatically flush output handles on some platforms.
(SunOS, Solaris, HP-UX)
=item getlogin
Not implemented. (S<Mac OS>, S<RISC OS>)
=item getpgrp
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>)
=item getppid
Not implemented. (S<Mac OS>, Win32, S<RISC OS>)
=item getpriority
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>, VOS, VM/ESA)
=item getpwnam
Not implemented. (S<Mac OS>, Win32)
Not useful. (S<RISC OS>)
=item getgrnam
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>)
=item getnetbyname
Not implemented. (S<Mac OS>, Win32, S<Plan 9>)
=item getpwuid
Not implemented. (S<Mac OS>, Win32)
Not useful. (S<RISC OS>)
=item getgrgid
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>)
=item getnetbyaddr
Not implemented. (S<Mac OS>, Win32, S<Plan 9>)
=item getprotobynumber
Not implemented. (S<Mac OS>)
=item getservbyport
Not implemented. (S<Mac OS>)
=item getpwent
Not implemented. (S<Mac OS>, Win32, VM/ESA)
=item getgrent
Not implemented. (S<Mac OS>, Win32, VMS, VM/ESA)
=item gethostbyname
C<gethostbyname('localhost')> does not work everywhere: you may have
to use C<gethostbyname('127.0.0.1')>. (S<Mac OS>, S<Irix 5>)
=item gethostent
Not implemented. (S<Mac OS>, Win32)
=item getnetent
Not implemented. (S<Mac OS>, Win32, S<Plan 9>)
=item getprotoent
Not implemented. (S<Mac OS>, Win32, S<Plan 9>)
=item getservent
Not implemented. (Win32, S<Plan 9>)
=item sethostent
Not implemented. (S<Mac OS>, Win32, S<Plan 9>, S<RISC OS>)
=item setnetent
Not implemented. (S<Mac OS>, Win32, S<Plan 9>, S<RISC OS>)
=item setprotoent
Not implemented. (S<Mac OS>, Win32, S<Plan 9>, S<RISC OS>)
=item setservent
Not implemented. (S<Plan 9>, Win32, S<RISC OS>)
=item endpwent
Not implemented. (S<Mac OS>, MPE/iX, VM/ESA, Win32)
=item endgrent
Not implemented. (S<Mac OS>, MPE/iX, S<RISC OS>, VM/ESA, VMS, Win32)
=item endhostent
Not implemented. (S<Mac OS>, Win32)
=item endnetent
Not implemented. (S<Mac OS>, Win32, S<Plan 9>)
=item endprotoent
Not implemented. (S<Mac OS>, Win32, S<Plan 9>)
=item endservent
Not implemented. (S<Plan 9>, Win32)
=item getsockopt SOCKET,LEVEL,OPTNAME
Not implemented. (S<Plan 9>)
=item glob
This operator is implemented via the File::Glob extension on most
platforms. See L<File::Glob> for portability information.
=item gmtime
Same portability caveats as L<localtime>.
=item ioctl FILEHANDLE,FUNCTION,SCALAR
Not implemented. (VMS)
Available only for socket handles, and it does what the ioctlsocket() call
in the Winsock API does. (Win32)
Available only for socket handles. (S<RISC OS>)
=item kill
C<kill(0, LIST)> is implemented for the sake of taint checking;
use with other signals is unimplemented. (S<Mac OS>)
Not implemented, hence not useful for taint checking. (S<RISC OS>)
C<kill()> doesn't have the semantics of C<raise()>, i.e. it doesn't send
a signal to the identified process like it does on Unix platforms.
Instead C<kill($sig, $pid)> terminates the process identified by $pid,
and makes it exit immediately with exit status $sig. As in Unix, if
$sig is 0 and the specified process exists, it returns true without
actually terminating it. (Win32)
C<kill(-9, $pid)> will terminate the process specified by $pid and
recursively all child processes owned by it. This is different from
the Unix semantics, where the signal will be delivered to all
processes in the same process group as the process specified by
$pid. (Win32)
Is not supported for process identification number of 0 or negative
numbers. (VMS)
=item link
Not implemented. (S<Mac OS>, MPE/iX, S<RISC OS>)
Link count not updated because hard links are not quite that hard
(They are sort of half-way between hard and soft links). (AmigaOS)
Hard links are implemented on Win32 under NTFS only. They are
natively supported on Windows 2000 and later. On Windows NT they
are implemented using the Windows POSIX subsystem support and the
Perl process will need Administrator or Backup Operator privileges
to create hard links.
Available on 64 bit OpenVMS 8.2 and later. (VMS)
=item localtime
Because Perl currently relies on the native standard C localtime()
function, it is only safe to use times between 0 and (2**31)-1. Times
outside this range may result in unexpected behavior depending on your
operating system's implementation of localtime().
=item lstat
Not implemented. (S<RISC OS>)
Return values (especially for device and inode) may be bogus. (Win32)
=item msgctl
=item msgget
=item msgsnd
=item msgrcv
Not implemented. (S<Mac OS>, Win32, VMS, S<Plan 9>, S<RISC OS>, VOS)
=item open
The C<|> variants are supported only if ToolServer is installed.
(S<Mac OS>)
open to C<|-> and C<-|> are unsupported. (S<Mac OS>, Win32, S<RISC OS>)
Opening a process does not automatically flush output handles on some
platforms. (SunOS, Solaris, HP-UX)
=item pipe
Very limited functionality. (MiNT)
=item readlink
Not implemented. (Win32, VMS, S<RISC OS>)
=item rename
Can't move directories between directories on different logical volumes. (Win32)
=item select
Only implemented on sockets. (Win32, VMS)
Only reliable on sockets. (S<RISC OS>)
Note that the C<select FILEHANDLE> form is generally portable.
=item semctl
=item semget
=item semop
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>, VOS)
=item setgrent
Not implemented. (S<Mac OS>, MPE/iX, VMS, Win32, S<RISC OS>, VOS)
=item setpgrp
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>, VOS)
=item setpriority
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>, VOS)
=item setpwent
Not implemented. (S<Mac OS>, MPE/iX, Win32, S<RISC OS>, VOS)
=item setsockopt
Not implemented. (S<Plan 9>)
=item shmctl
=item shmget
=item shmread
=item shmwrite
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>, VOS)
=item sockatmark
A relatively recent addition to socket functions, may not
be implemented even in UNIX platforms.
=item socketpair
Not implemented. (S<RISC OS>, VOS, VM/ESA)
Available on 64 bit OpenVMS 8.2 and later. (VMS)
=item stat
Platforms that do not have rdev, blksize, or blocks will return these
as '', so numeric comparison or manipulation of these fields may cause
'not numeric' warnings.
mtime and atime are the same thing, and ctime is creation time instead of
inode change time. (S<Mac OS>).
ctime not supported on UFS (S<Mac OS X>).
ctime is creation time instead of inode change time (Win32).
device and inode are not meaningful. (Win32)
device and inode are not necessarily reliable. (VMS)
mtime, atime and ctime all return the last modification time. Device and
inode are not necessarily reliable. (S<RISC OS>)
dev, rdev, blksize, and blocks are not available. inode is not
meaningful and will differ between stat calls on the same file. (os2)
some versions of cygwin when doing a stat("foo") and if not finding it
may then attempt to stat("foo.exe") (Cygwin)
On Win32 stat() needs to open the file to determine the link count
and update attributes that may have been changed through hard links.
Setting ${^WIN32_SLOPPY_STAT} to a true value speeds up stat() by
not performing this operation. (Win32)
=item symlink
Not implemented. (Win32, S<RISC OS>)
Implemented on 64 bit VMS 8.3. VMS requires the symbolic link to be in Unix
syntax if it is intended to resolve to a valid path.
=item syscall
Not implemented. (S<Mac OS>, Win32, VMS, S<RISC OS>, VOS, VM/ESA)
=item sysopen
The traditional "0", "1", and "2" MODEs are implemented with different
numeric values on some systems. The flags exported by C<Fcntl>
(O_RDONLY, O_WRONLY, O_RDWR) should work everywhere though. (S<Mac
OS>, OS/390, VM/ESA)
=item system
Only implemented if ToolServer is installed. (S<Mac OS>)
As an optimization, may not call the command shell specified in
C<$ENV{PERL5SHELL}>. C<system(1, @args)> spawns an external
process and immediately returns its process designator, without
waiting for it to terminate. Return value may be used subsequently
in C<wait> or C<waitpid>. Failure to spawn() a subprocess is indicated
by setting $? to "255 << 8". C<$?> is set in a way compatible with
Unix (i.e. the exitstatus of the subprocess is obtained by "$? >> 8",
as described in the documentation). (Win32)
There is no shell to process metacharacters, and the native standard is
to pass a command line terminated by "\n" "\r" or "\0" to the spawned
program. Redirection such as C<< > foo >> is performed (if at all) by
the run time library of the spawned program. C<system> I<list> will call
the Unix emulation library's C<exec> emulation, which attempts to provide
emulation of the stdin, stdout, stderr in force in the parent, providing
the child program uses a compatible version of the emulation library.
I<scalar> will call the native command line direct and no such emulation
of a child Unix program will exists. Mileage B<will> vary. (S<RISC OS>)
Far from being POSIX compliant. Because there may be no underlying
/bin/sh tries to work around the problem by forking and execing the
first token in its argument string. Handles basic redirection
("<" or ">") on its own behalf. (MiNT)
Does not automatically flush output handles on some platforms.
(SunOS, Solaris, HP-UX)
The return value is POSIX-like (shifted up by 8 bits), which only allows
room for a made-up value derived from the severity bits of the native
32-bit condition code (unless overridden by C<use vmsish 'status'>).
If the native condition code is one that has a POSIX value encoded, the
POSIX value will be decoded to extract the expected exit value.
For more details see L<perlvms/$?>. (VMS)
=item times
Only the first entry returned is nonzero. (S<Mac OS>)
"cumulative" times will be bogus. On anything other than Windows NT
or Windows 2000, "system" time will be bogus, and "user" time is
actually the time returned by the clock() function in the C runtime
library. (Win32)
Not useful. (S<RISC OS>)
=item truncate
Not implemented. (Older versions of VMS)
Truncation to same-or-shorter lengths only. (VOS)
If a FILEHANDLE is supplied, it must be writable and opened in append
mode (i.e., use C<<< open(FH, '>>filename') >>>
or C<sysopen(FH,...,O_APPEND|O_RDWR)>. If a filename is supplied, it
should not be held open elsewhere. (Win32)
=item umask
Returns undef where unavailable, as of version 5.005.
C<umask> works but the correct permissions are set only when the file
is finally closed. (AmigaOS)
=item utime
Only the modification time is updated. (S<BeOS>, S<Mac OS>, VMS, S<RISC OS>)
May not behave as expected. Behavior depends on the C runtime
library's implementation of utime(), and the filesystem being
used. The FAT filesystem typically does not support an "access
time" field, and it may limit timestamps to a granularity of
two seconds. (Win32)
=item wait
=item waitpid
Not implemented. (S<Mac OS>)
Can only be applied to process handles returned for processes spawned
using C<system(1, ...)> or pseudo processes created with C<fork()>. (Win32)
Not useful. (S<RISC OS>)
=back
=head1 Supported Platforms
As of July 2002 (the Perl release 5.8.0), the following platforms are
able to build Perl from the standard source code distribution
available at http://www.cpan.org/src/index.html
AIX
BeOS
BSD/OS (BSDi)
Cygwin
DG/UX
DOS DJGPP 1)
DYNIX/ptx
EPOC R5
FreeBSD
HI-UXMPP (Hitachi) (5.8.0 worked but we didn't know it)
HP-UX
IRIX
Linux
Mac OS Classic
Mac OS X (Darwin)
MPE/iX
NetBSD
NetWare
NonStop-UX
ReliantUNIX (formerly SINIX)
OpenBSD
OpenVMS (formerly VMS)
Open UNIX (Unixware) (since Perl 5.8.1/5.9.0)
OS/2
OS/400 (using the PASE) (since Perl 5.8.1/5.9.0)
PowerUX
POSIX-BC (formerly BS2000)
QNX
Solaris
SunOS 4
SUPER-UX (NEC)
Tru64 UNIX (formerly DEC OSF/1, Digital UNIX)
UNICOS
UNICOS/mk
UTS
VOS
Win95/98/ME/2K/XP 2)
WinCE
z/OS (formerly OS/390)
VM/ESA
1) in DOS mode either the DOS or OS/2 ports can be used
2) compilers: Borland, MinGW (GCC), VC6
The following platforms worked with the previous releases (5.6 and
5.7), but we did not manage either to fix or to test these in time
for the 5.8.0 release. There is a very good chance that many of these
will work fine with the 5.8.0.
BSD/OS
DomainOS
Hurd
LynxOS
MachTen
PowerMAX
SCO SV
SVR4
Unixware
Windows 3.1
Known to be broken for 5.8.0 (but 5.6.1 and 5.7.2 can be used):
AmigaOS
The following platforms have been known to build Perl from source in
the past (5.005_03 and earlier), but we haven't been able to verify
their status for the current release, either because the
hardware/software platforms are rare or because we don't have an
active champion on these platforms--or both. They used to work,
though, so go ahead and try compiling them, and let perlbug@perl.org
of any trouble.
3b1
A/UX
ConvexOS
CX/UX
DC/OSx
DDE SMES
DOS EMX
Dynix
EP/IX
ESIX
FPS
GENIX
Greenhills
ISC
MachTen 68k
MiNT
MPC
NEWS-OS
NextSTEP
OpenSTEP
Opus
Plan 9
RISC/os
SCO ODT/OSR
Stellar
SVR2
TI1500
TitanOS
Ultrix
Unisys Dynix
The following platforms have their own source code distributions and
binaries available via http://www.cpan.org/ports/
Perl release
OS/400 (ILE) 5.005_02
Tandem Guardian 5.004
The following platforms have only binaries available via
http://www.cpan.org/ports/index.html :
Perl release
Acorn RISCOS 5.005_02
AOS 5.002
LynxOS 5.004_02
Although we do suggest that you always build your own Perl from
the source code, both for maximal configurability and for security,
in case you are in a hurry you can check
http://www.cpan.org/ports/index.html for binary distributions.
=head1 SEE ALSO
L<perlaix>, L<perlamiga>, L<perlapollo>, L<perlbeos>, L<perlbs2000>,
L<perlce>, L<perlcygwin>, L<perldgux>, L<perldos>, L<perlepoc>,
L<perlebcdic>, L<perlfreebsd>, L<perlhurd>, L<perlhpux>, L<perlirix>,
L<perlmachten>, L<perlmacos>, L<perlmacosx>, L<perlmint>, L<perlmpeix>,
L<perlnetware>, L<perlos2>, L<perlos390>, L<perlos400>,
L<perlplan9>, L<perlqnx>, L<perlsolaris>, L<perltru64>,
L<perlunicode>, L<perlvmesa>, L<perlvms>, L<perlvos>,
L<perlwin32>, and L<Win32>.
=head1 AUTHORS / CONTRIBUTORS
Abigail <abigail@foad.org>,
Charles Bailey <bailey@newman.upenn.edu>,
Graham Barr <gbarr@pobox.com>,
Tom Christiansen <tchrist@perl.com>,
Nicholas Clark <nick@ccl4.org>,
Thomas Dorner <Thomas.Dorner@start.de>,
Andy Dougherty <doughera@lafayette.edu>,
Dominic Dunlop <domo@computer.org>,
Neale Ferguson <neale@vma.tabnsw.com.au>,
David J. Fiander <davidf@mks.com>,
Paul Green <Paul.Green@stratus.com>,
M.J.T. Guy <mjtg@cam.ac.uk>,
Jarkko Hietaniemi <jhi@iki.fi>,
Luther Huffman <lutherh@stratcom.com>,
Nick Ing-Simmons <nick@ing-simmons.net>,
Andreas J. KE<ouml>nig <a.koenig@mind.de>,
Markus Laker <mlaker@contax.co.uk>,
Andrew M. Langmead <aml@world.std.com>,
Larry Moore <ljmoore@freespace.net>,
Paul Moore <Paul.Moore@uk.origin-it.com>,
Chris Nandor <pudge@pobox.com>,
Matthias Neeracher <neeracher@mac.com>,
Philip Newton <pne@cpan.org>,
Gary Ng <71564.1743@CompuServe.COM>,
Tom Phoenix <rootbeer@teleport.com>,
AndrE<eacute> Pirard <A.Pirard@ulg.ac.be>,
Peter Prymmer <pvhp@forte.com>,
Hugo van der Sanden <hv@crypt0.demon.co.uk>,
Gurusamy Sarathy <gsar@activestate.com>,
Paul J. Schinder <schinder@pobox.com>,
Michael G Schwern <schwern@pobox.com>,
Dan Sugalski <dan@sidhe.org>,
Nathan Torkington <gnat@frii.com>.
John Malmberg <wb8tyw@qsl.net>
| leighpauls/k2cro4 | third_party/cygwin/lib/perl5/5.10/pods/perlport.pod | Perl | bsd-3-clause | 86,283 |
package Kwiki::Users;
use Kwiki::Base -Base;
use mixin 'Kwiki::Installer';
const class_id => 'users';
const class_title => 'Kwiki Users';
const user_class => 'Kwiki::User';
sub init {
$self->hub->config->add_file('user.yaml');
}
sub all {
($self->current);
}
sub all_ids {
($self->current->id);
}
sub current {
return $self->{current} = shift if @_;
return $self->{current} if defined $self->{current};
my $user_id = $ENV{REMOTE_USER} || '';
$self->{current} = $self->new_user($user_id);
}
sub new_user {
$self->user_class->new(id => shift);
}
package Kwiki::User;
use base 'Kwiki::Base';
field 'id';
field 'name' => '';
sub new {
$self = super;
$self->set_user_name;
return $self;
}
sub set_user_name {
return unless $self->is_in_cgi;
my $name = '';
$name = $self->preferences->user_name->value
if $self->preferences->can('user_name');
$name ||= $self->hub->config->user_default_name;
$self->name($name);
}
sub preferences {
return $self->{preferences} = shift if @_;
return $self->{preferences} if defined $self->{preferences};
my $preferences = $self->hub->preferences;
$self->{preferences} =
$preferences->new_preferences($self->preference_values);
}
sub preference_values {
$self->hub->cookie->jar->{preferences} || {};
}
package Kwiki::Users;
__DATA__
=head1 NAME
Kwiki::Users - Kwiki Users Base Class
=head1 SYNOPSIS
=head1 DESCRIPTION
=head1 AUTHOR
Brian Ingerson <INGY@cpan.org>
=head1 COPYRIGHT
Copyright (c) 2004. Brian Ingerson. All rights reserved.
This program is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
See http://www.perl.com/perl/misc/Artistic.html
=cut
__config/user.yaml__
user_default_name: AnonymousGnome
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/Kwiki/Users.pm | Perl | mit | 1,827 |
#!/usr/bin/perl -s
#
# out put of find
$path = shift;
if($old){
$oldMeans = $old;
} else {
$oldMeans = 10;
}
if($dst){
$dstPath = $dst;
} else {
$dstPath = ".";
}
open(FP, "find $path -maxdepth 1 -type f |") || die "find <$path> failed";
while(<FP>){
s/[\r\n]+//;
if($verbose){
print $_, "\n";
}
next unless ( -e $_ );
next if ( -M $_ < $oldMeans);
if(/(20\d\d)(\d\d)/){
push(@cmd, "mv $_ $dstPath/$1_$2");
$mkdir{ "mkdir $dstPath/$1_$2" } = 1;
} elsif(/(\d\d)-(\d\d)-\d\d/){
push(@cmd, "mv $_ $dstPath/$1$2");
$mkdir{ "mkdir $dstPath/$1$2" } = 1;
} elsif(/\d\d\d\d/){
push(@cmd, "mv $_ $dstPath/$&");
$mkdir{ "mkdir $dstPath/$&" } = 1;
} elsif(/\d\d\-\d\d/){
push(@cmd, "mv $_ $dstPath/$&");
$mkdir{ "mkdir $dstPath/$&" } = 1;
} else {
print "Skip $_ \n";
}
}
close(FP);
print join("\n", map { s/mkdir/mkdir -p/; $_ } sort keys %mkdir),"\n";
print join("\n", @cmd),"\n";
| wittyfool/linux_amenities | seiri.pl | Perl | mit | 952 |
#!/usr/bin/env perl
#
# ====================================================================
# Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
#
# GHASH for ARMv8 Crypto Extension, 64-bit polynomial multiplication.
#
# June 2014
#
# Initial version was developed in tight cooperation with Ard
# Biesheuvel <ard.biesheuvel@linaro.org> from bits-n-pieces from
# other assembly modules. Just like aesv8-armx.pl this module
# supports both AArch32 and AArch64 execution modes.
#
# July 2014
#
# Implement 2x aggregated reduction [see ghash-x86.pl for background
# information].
#
# Current performance in cycles per processed byte:
#
# PMULL[2] 32-bit NEON(*)
# Apple A7 0.92 5.62
# Cortex-A53 1.01 8.39
# Cortex-A57 1.17 7.61
# Denver 0.71 6.02
#
# (*) presented for reference/comparison purposes;
$flavour = shift;
$output = shift;
$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
( $xlate="${dir}arm-xlate.pl" and -f $xlate ) or
( $xlate="${dir}../../perlasm/arm-xlate.pl" and -f $xlate) or
die "can't locate arm-xlate.pl";
open OUT,"| \"$^X\" $xlate $flavour $output";
*STDOUT=*OUT;
$Xi="x0"; # argument block
$Htbl="x1";
$inp="x2";
$len="x3";
$inc="x12";
{
my ($Xl,$Xm,$Xh,$IN)=map("q$_",(0..3));
my ($t0,$t1,$t2,$xC2,$H,$Hhl,$H2)=map("q$_",(8..14));
$code=<<___;
#include "arm_arch.h"
.text
___
$code.=".arch armv8-a+crypto\n" if ($flavour =~ /64/);
$code.=".fpu neon\n.code 32\n" if ($flavour !~ /64/);
################################################################################
# void gcm_init_v8(u128 Htable[16],const u64 H[2]);
#
# input: 128-bit H - secret parameter E(K,0^128)
# output: precomputed table filled with degrees of twisted H;
# H is twisted to handle reverse bitness of GHASH;
# only few of 16 slots of Htable[16] are used;
# data is opaque to outside world (which allows to
# optimize the code independently);
#
$code.=<<___;
.global gcm_init_v8
.type gcm_init_v8,%function
.align 4
gcm_init_v8:
vld1.64 {$t1},[x1] @ load input H
vmov.i8 $xC2,#0xe1
vshl.i64 $xC2,$xC2,#57 @ 0xc2.0
vext.8 $IN,$t1,$t1,#8
vshr.u64 $t2,$xC2,#63
vdup.32 $t1,${t1}[1]
vext.8 $t0,$t2,$xC2,#8 @ t0=0xc2....01
vshr.u64 $t2,$IN,#63
vshr.s32 $t1,$t1,#31 @ broadcast carry bit
vand $t2,$t2,$t0
vshl.i64 $IN,$IN,#1
vext.8 $t2,$t2,$t2,#8
vand $t0,$t0,$t1
vorr $IN,$IN,$t2 @ H<<<=1
veor $H,$IN,$t0 @ twisted H
vst1.64 {$H},[x0],#16 @ store Htable[0]
@ calculate H^2
vext.8 $t0,$H,$H,#8 @ Karatsuba pre-processing
vpmull.p64 $Xl,$H,$H
veor $t0,$t0,$H
vpmull2.p64 $Xh,$H,$H
vpmull.p64 $Xm,$t0,$t0
vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing
veor $t2,$Xl,$Xh
veor $Xm,$Xm,$t1
veor $Xm,$Xm,$t2
vpmull.p64 $t2,$Xl,$xC2 @ 1st phase
vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result
vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl
veor $Xl,$Xm,$t2
vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase
vpmull.p64 $Xl,$Xl,$xC2
veor $t2,$t2,$Xh
veor $H2,$Xl,$t2
vext.8 $t1,$H2,$H2,#8 @ Karatsuba pre-processing
veor $t1,$t1,$H2
vext.8 $Hhl,$t0,$t1,#8 @ pack Karatsuba pre-processed
vst1.64 {$Hhl-$H2},[x0] @ store Htable[1..2]
ret
.size gcm_init_v8,.-gcm_init_v8
___
################################################################################
# void gcm_gmult_v8(u64 Xi[2],const u128 Htable[16]);
#
# input: Xi - current hash value;
# Htable - table precomputed in gcm_init_v8;
# output: Xi - next hash value Xi;
#
$code.=<<___;
.global gcm_gmult_v8
.type gcm_gmult_v8,%function
.align 4
gcm_gmult_v8:
vld1.64 {$t1},[$Xi] @ load Xi
vmov.i8 $xC2,#0xe1
vld1.64 {$H-$Hhl},[$Htbl] @ load twisted H, ...
vshl.u64 $xC2,$xC2,#57
#ifndef __ARMEB__
vrev64.8 $t1,$t1
#endif
vext.8 $IN,$t1,$t1,#8
vpmull.p64 $Xl,$H,$IN @ H.lo·Xi.lo
veor $t1,$t1,$IN @ Karatsuba pre-processing
vpmull2.p64 $Xh,$H,$IN @ H.hi·Xi.hi
vpmull.p64 $Xm,$Hhl,$t1 @ (H.lo+H.hi)·(Xi.lo+Xi.hi)
vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing
veor $t2,$Xl,$Xh
veor $Xm,$Xm,$t1
veor $Xm,$Xm,$t2
vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction
vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result
vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl
veor $Xl,$Xm,$t2
vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction
vpmull.p64 $Xl,$Xl,$xC2
veor $t2,$t2,$Xh
veor $Xl,$Xl,$t2
#ifndef __ARMEB__
vrev64.8 $Xl,$Xl
#endif
vext.8 $Xl,$Xl,$Xl,#8
vst1.64 {$Xl},[$Xi] @ write out Xi
ret
.size gcm_gmult_v8,.-gcm_gmult_v8
___
################################################################################
# void gcm_ghash_v8(u64 Xi[2],const u128 Htable[16],const u8 *inp,size_t len);
#
# input: table precomputed in gcm_init_v8;
# current hash value Xi;
# pointer to input data;
# length of input data in bytes, but divisible by block size;
# output: next hash value Xi;
#
$code.=<<___;
.global gcm_ghash_v8
.type gcm_ghash_v8,%function
.align 4
gcm_ghash_v8:
___
$code.=<<___ if ($flavour !~ /64/);
vstmdb sp!,{d8-d15} @ 32-bit ABI says so
___
$code.=<<___;
vld1.64 {$Xl},[$Xi] @ load [rotated] Xi
@ "[rotated]" means that
@ loaded value would have
@ to be rotated in order to
@ make it appear as in
@ alorithm specification
subs $len,$len,#32 @ see if $len is 32 or larger
mov $inc,#16 @ $inc is used as post-
@ increment for input pointer;
@ as loop is modulo-scheduled
@ $inc is zeroed just in time
@ to preclude oversteping
@ inp[len], which means that
@ last block[s] are actually
@ loaded twice, but last
@ copy is not processed
vld1.64 {$H-$Hhl},[$Htbl],#32 @ load twisted H, ..., H^2
vmov.i8 $xC2,#0xe1
vld1.64 {$H2},[$Htbl]
cclr $inc,eq @ is it time to zero $inc?
vext.8 $Xl,$Xl,$Xl,#8 @ rotate Xi
vld1.64 {$t0},[$inp],#16 @ load [rotated] I[0]
vshl.u64 $xC2,$xC2,#57 @ compose 0xc2.0 constant
#ifndef __ARMEB__
vrev64.8 $t0,$t0
vrev64.8 $Xl,$Xl
#endif
vext.8 $IN,$t0,$t0,#8 @ rotate I[0]
b.lo .Lodd_tail_v8 @ $len was less than 32
___
{ my ($Xln,$Xmn,$Xhn,$In) = map("q$_",(4..7));
#######
# Xi+2 =[H*(Ii+1 + Xi+1)] mod P =
# [(H*Ii+1) + (H*Xi+1)] mod P =
# [(H*Ii+1) + H^2*(Ii+Xi)] mod P
#
$code.=<<___;
vld1.64 {$t1},[$inp],$inc @ load [rotated] I[1]
#ifndef __ARMEB__
vrev64.8 $t1,$t1
#endif
vext.8 $In,$t1,$t1,#8
veor $IN,$IN,$Xl @ I[i]^=Xi
vpmull.p64 $Xln,$H,$In @ H·Ii+1
veor $t1,$t1,$In @ Karatsuba pre-processing
vpmull2.p64 $Xhn,$H,$In
b .Loop_mod2x_v8
.align 4
.Loop_mod2x_v8:
vext.8 $t2,$IN,$IN,#8
subs $len,$len,#32 @ is there more data?
vpmull.p64 $Xl,$H2,$IN @ H^2.lo·Xi.lo
cclr $inc,lo @ is it time to zero $inc?
vpmull.p64 $Xmn,$Hhl,$t1
veor $t2,$t2,$IN @ Karatsuba pre-processing
vpmull2.p64 $Xh,$H2,$IN @ H^2.hi·Xi.hi
veor $Xl,$Xl,$Xln @ accumulate
vpmull2.p64 $Xm,$Hhl,$t2 @ (H^2.lo+H^2.hi)·(Xi.lo+Xi.hi)
vld1.64 {$t0},[$inp],$inc @ load [rotated] I[i+2]
veor $Xh,$Xh,$Xhn
cclr $inc,eq @ is it time to zero $inc?
veor $Xm,$Xm,$Xmn
vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing
veor $t2,$Xl,$Xh
veor $Xm,$Xm,$t1
vld1.64 {$t1},[$inp],$inc @ load [rotated] I[i+3]
#ifndef __ARMEB__
vrev64.8 $t0,$t0
#endif
veor $Xm,$Xm,$t2
vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction
#ifndef __ARMEB__
vrev64.8 $t1,$t1
#endif
vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result
vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl
vext.8 $In,$t1,$t1,#8
vext.8 $IN,$t0,$t0,#8
veor $Xl,$Xm,$t2
vpmull.p64 $Xln,$H,$In @ H·Ii+1
veor $IN,$IN,$Xh @ accumulate $IN early
vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction
vpmull.p64 $Xl,$Xl,$xC2
veor $IN,$IN,$t2
veor $t1,$t1,$In @ Karatsuba pre-processing
veor $IN,$IN,$Xl
vpmull2.p64 $Xhn,$H,$In
b.hs .Loop_mod2x_v8 @ there was at least 32 more bytes
veor $Xh,$Xh,$t2
vext.8 $IN,$t0,$t0,#8 @ re-construct $IN
adds $len,$len,#32 @ re-construct $len
veor $Xl,$Xl,$Xh @ re-construct $Xl
b.eq .Ldone_v8 @ is $len zero?
___
}
$code.=<<___;
.Lodd_tail_v8:
vext.8 $t2,$Xl,$Xl,#8
veor $IN,$IN,$Xl @ inp^=Xi
veor $t1,$t0,$t2 @ $t1 is rotated inp^Xi
vpmull.p64 $Xl,$H,$IN @ H.lo·Xi.lo
veor $t1,$t1,$IN @ Karatsuba pre-processing
vpmull2.p64 $Xh,$H,$IN @ H.hi·Xi.hi
vpmull.p64 $Xm,$Hhl,$t1 @ (H.lo+H.hi)·(Xi.lo+Xi.hi)
vext.8 $t1,$Xl,$Xh,#8 @ Karatsuba post-processing
veor $t2,$Xl,$Xh
veor $Xm,$Xm,$t1
veor $Xm,$Xm,$t2
vpmull.p64 $t2,$Xl,$xC2 @ 1st phase of reduction
vmov $Xh#lo,$Xm#hi @ Xh|Xm - 256-bit result
vmov $Xm#hi,$Xl#lo @ Xm is rotated Xl
veor $Xl,$Xm,$t2
vext.8 $t2,$Xl,$Xl,#8 @ 2nd phase of reduction
vpmull.p64 $Xl,$Xl,$xC2
veor $t2,$t2,$Xh
veor $Xl,$Xl,$t2
.Ldone_v8:
#ifndef __ARMEB__
vrev64.8 $Xl,$Xl
#endif
vext.8 $Xl,$Xl,$Xl,#8
vst1.64 {$Xl},[$Xi] @ write out Xi
___
$code.=<<___ if ($flavour !~ /64/);
vldmia sp!,{d8-d15} @ 32-bit ABI says so
___
$code.=<<___;
ret
.size gcm_ghash_v8,.-gcm_ghash_v8
___
}
$code.=<<___;
.asciz "GHASH for ARMv8, CRYPTOGAMS by <appro\@openssl.org>"
.align 2
___
if ($flavour =~ /64/) { ######## 64-bit code
sub unvmov {
my $arg=shift;
$arg =~ m/q([0-9]+)#(lo|hi),\s*q([0-9]+)#(lo|hi)/o &&
sprintf "ins v%d.d[%d],v%d.d[%d]",$1,($2 eq "lo")?0:1,$3,($4 eq "lo")?0:1;
}
foreach(split("\n",$code)) {
s/cclr\s+([wx])([^,]+),\s*([a-z]+)/csel $1$2,$1zr,$1$2,$3/o or
s/vmov\.i8/movi/o or # fix up legacy mnemonics
s/vmov\s+(.*)/unvmov($1)/geo or
s/vext\.8/ext/o or
s/vshr\.s/sshr\.s/o or
s/vshr/ushr/o or
s/^(\s+)v/$1/o or # strip off v prefix
s/\bbx\s+lr\b/ret/o;
s/\bq([0-9]+)\b/"v".($1<8?$1:$1+8).".16b"/geo; # old->new registers
s/@\s/\/\//o; # old->new style commentary
# fix up remainig legacy suffixes
s/\.[ui]?8(\s)/$1/o;
s/\.[uis]?32//o and s/\.16b/\.4s/go;
m/\.p64/o and s/\.16b/\.1q/o; # 1st pmull argument
m/l\.p64/o and s/\.16b/\.1d/go; # 2nd and 3rd pmull arguments
s/\.[uisp]?64//o and s/\.16b/\.2d/go;
s/\.[42]([sd])\[([0-3])\]/\.$1\[$2\]/o;
print $_,"\n";
}
} else { ######## 32-bit code
sub unvdup32 {
my $arg=shift;
$arg =~ m/q([0-9]+),\s*q([0-9]+)\[([0-3])\]/o &&
sprintf "vdup.32 q%d,d%d[%d]",$1,2*$2+($3>>1),$3&1;
}
sub unvpmullp64 {
my ($mnemonic,$arg)=@_;
if ($arg =~ m/q([0-9]+),\s*q([0-9]+),\s*q([0-9]+)/o) {
my $word = 0xf2a00e00|(($1&7)<<13)|(($1&8)<<19)
|(($2&7)<<17)|(($2&8)<<4)
|(($3&7)<<1) |(($3&8)<<2);
$word |= 0x00010001 if ($mnemonic =~ "2");
# since ARMv7 instructions are always encoded little-endian.
# correct solution is to use .inst directive, but older
# assemblers don't implement it:-(
sprintf ".byte\t0x%02x,0x%02x,0x%02x,0x%02x\t@ %s %s",
$word&0xff,($word>>8)&0xff,
($word>>16)&0xff,($word>>24)&0xff,
$mnemonic,$arg;
}
}
foreach(split("\n",$code)) {
s/\b[wx]([0-9]+)\b/r$1/go; # new->old registers
s/\bv([0-9])\.[12468]+[bsd]\b/q$1/go; # new->old registers
s/\/\/\s?/@ /o; # new->old style commentary
# fix up remainig new-style suffixes
s/\],#[0-9]+/]!/o;
s/cclr\s+([^,]+),\s*([a-z]+)/mov$2 $1,#0/o or
s/vdup\.32\s+(.*)/unvdup32($1)/geo or
s/v?(pmull2?)\.p64\s+(.*)/unvpmullp64($1,$2)/geo or
s/\bq([0-9]+)#(lo|hi)/sprintf "d%d",2*$1+($2 eq "hi")/geo or
s/^(\s+)b\./$1b/o or
s/^(\s+)ret/$1bx\tlr/o;
print $_,"\n";
}
}
close STDOUT; # enforce flush
| vbloodv/blood | extern/openssl.orig/crypto/modes/asm/ghashv8-armx.pl | Perl | mit | 11,481 |
package CXGN::List::Desynonymize;
use Moose;
use CXGN::Stock::StockLookup;
use Module::Pluggable require => 1;
my %stock_list_type_hash = (
'seedlots'=>'seedlot',
'plots'=>'plot',
'accessions'=>'accession',
'vector_constructs'=>'vector_construct',
'crosses'=>'cross',
'populations'=>'population',
'plants'=>'plant',
'family_names'=>'family_name'
);
sub desynonymize {
my $self = shift;
my $schema = shift; # dbschema
my $type = shift; # a stock type
my $list = shift; # an array ref to an array of stock names
#check if list is a stock list
my $match = 0;
my @stock_types = ('seedlots', 'plots', 'accessions', 'vector_constructs',
'crosses', 'populations', 'plants', 'family_names');
foreach my $stock_type (@stock_types) {
if( $stock_type eq $type ){
$match = 1;
last;
}
}
if ($match==0){
return {
success => "0",
error => "not a stock list"
};
}
else{
my $stocklookup = CXGN::Stock::StockLookup->new({ schema => $schema});
my $unique = $stocklookup->get_stock_synonyms('any_name',$stock_list_type_hash{$type},$list);
# my @already_unique = ();
# my @changed = ();
# my @missing = ();
# foreach my $old_name (@{$list}){
# if (defined $unique->{$old_name}){
# push @already_unique, $old_name;
# } else {
# UNFOUND: {
# while (my ($uniq_name, $synonyms) = each %{$unique}){
# foreach my $synonym (@{$synonyms}){
# if ($old_name eq $synonym){
# push @changed, [$old_name,$uniq_name];
# last UNFOUND;
# }
# }
# }
# push @missing, $old_name;
# }
# }
# }
my @unique_list = keys %{$unique};
return {
success => "1",
list => \@unique_list,
synonyms => $unique
# unchanged => \@already_unique,
# changed => \@changed,
# absent => \@missing
};
}
}
1;
| solgenomics/sgn | lib/CXGN/List/Desynonymize.pm | Perl | mit | 2,280 |
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
use Pod::Usage;
use Env qw(HOME);
use Cwd;
my $filename = 'liquibase.properties';
my $basePath = cwd();
my %opts=(
filename => \$filename,
driver => 'com.mysql.jdbc.Driver',
classpath => "${basePath}/mysql-connector-java-5.1.35-bin.jar",
url => 'jdbc:mysql://127.0.0.1/my_db',
username => 'root',
password => '',
changeLogFile => 'schema.xml',
help => 0
);
GetOptions(\%opts, 'filename=s', 'driver=s', 'classpath=s', 'url|server=s', 'username=s', 'password=s', 'changeLogFile=s', 'help|?')
or pod2usage(-existval => 1, -verbose => 99);
pod2usage(-exitval => 0, -verbose => 1) if $opts{help};
open(my $fh, '>:encoding(UTF-8)', $filename)
or die "Failed to open '$filename': $!\n";
for my $key (keys %opts) {
if ($key ne 'filename' && $key ne 'help') {
if ($key eq 'classpath') {
my $baseLen = length $basePath;
if (substr($opts{$key}, 0, $baseLen) ne $basePath) {
$opts{$key} = "$basePath/$opts{$key}";
}
}
print $fh "$key: $opts{$key}\n";
}
}
close $fh;
print "Check environment variable for LIQUIBASE_HOME\n";
if (!defined $ENV{LIQUIBASE_HOME}) {
#get pwd (of file)
my $basePath = cwd();
open(my $fh, '>>:encoding(UTF-8)', "$HOME/.bashrc")
or die "Failed to append to $HOME/.bashrc: $!\n";
print $fh "\nexport LIQUIBASE_HOME='$basePath'\n";
close $fh;
}
print "Done\n";
__END__
=head1 NAME
setup - Usage
=head1 SYNOPSIS
setup [options] - Generates generic liquibase properties file, with classpath, url, username, password and default changeLogFile set up
=head1 OPTIONS
Options:
--help : Display help message
--filename=liquibase.properties : The output file (default is liquibase.properties in current directory)
--driver=com.mysql.jdbc.Driver : The DB driver used by liquibase (class)
--classpath=./mysql-connector-java-5.1.35-bin.jar : The location of the DB driver jar
--url=jdbc:mysql://127.0.0.1/my_db : The DB to connect to
--username=root : user (DB credentials)
--password='' : password (DB credentials)
--changeLogFile=schema.xml : Default changelog file
=over 8
Enjoy
=back
=head1 DESCRIPTION
B<this program> will generate the liquibase.properties file with the params given. Default is to create it in the current directory under the liquibase.properties name
It's recommended you run this script in tandem with the get-liquibase.sh bash script, after which you can easily start using liquibase in your projects by simply running
the following command:
$ cp $LIQUIBASE_HOME/liquibase.properties ./
After which, commands like
$ liquibase generateChangeLog
will generate the changelog file, without those tedious flags
=cut
| EVODelavega/gp-scripts | liquibase/setup.pl | Perl | mit | 3,121 |
# Copyright (c) 2010 - Action Without Borders
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
package IF::ObjectContext;
use strict;
use IF::DB;
use IF::Log;
use IF::Entity;
use IF::Entity::Persistent;
use IF::Model;
use IF::FetchSpecification;
use IF::Qualifier;
use IF::Cache;
use IF::Array;
use Try::Tiny;
my $_objectContext;
# This allows only singletons:
sub new {
my $className = shift;
return $_objectContext if $_objectContext;
$_objectContext = {
_shouldTrackEntities => 0,
_saveChangesInProgress => 0,
_trackedEntities => undef,
_addedEntities => undef,
_forgottenEntities => undef,
_deletedEntities => undef,
_model => undef,
};
bless $_objectContext, $className;
$_objectContext->init();
$_objectContext->loadModel();
return $_objectContext;
}
sub init {
my ($self) = @_;
$self->initTrackingStore();
$self->enableTracking();
$self->{_saveChangesInProgress} = 0;
return $self;
}
sub initTrackingStore {
my ($self) = @_;
$self->{_trackedEntities} = IF::Dictionary->new();
$self->{_deletedEntities} = IF::Dictionary->new();
$self->{_addedEntities} = IF::Array->new();
$self->{_forgottenEntities} = IF::Array->new();
}
sub loadModel {
my $self = shift;
#$DB::single = 1;
$self->setModel(IF::Model->defaultModel());
}
sub model {
my ($self) = @_;
return $self->{_model};
}
sub setModel {
my ($self, $value) = @_;
$self->{_model} = $value;
}
# sub entityWithUniqueIdentifier {
# my ($self, $ui) = @_;
# return undef unless $ui;
# my $e = $ui->entityName();
# my $eid = $ui->externalId();
# return $self->entityWithExternalId($e, $eid);
# }
sub entityWithPrimaryKey {
my $self = shift;
my $entityName = shift;
my $id = shift;
unless ($id) {
#IF::Log::warning("Attempt to fetch $entityName with no key failed");
#IF::Log::stack(7);
return;
}
# // temporary hack - FIXME!
my $uid = IF::Entity::UniqueIdentifier->newFromString($entityName, $id);
my $tracked = $self->trackedInstanceOfEntityWithUniqueIdentifier($uid);
return $tracked if $tracked;
my $entityClassDescription = $self->model()->entityClassDescriptionForEntityNamed($entityName);
return unless $entityClassDescription;
my $keyQualifier = $entityClassDescription->_primaryKey()->qualifierForValue($id);
my $fetchSpecification = IF::FetchSpecification->new($entityName, $keyQualifier);
my $entities = $self->entitiesMatchingFetchSpecification($fetchSpecification);
if (scalar @$entities > 1) {
IF::Log::warning("Found more than one $entityName matching id $id");
return $entities->[0];
}
if (scalar @$entities == 0) {
IF::Log::warning("No $entityName matching id $id found");
return;
}
return $entities->[0];
}
sub entityWithExternalId {
my ($self, $entityName, $externalId) = @_;
return undef unless $externalId; # TODO: just have externalIdIsValid() check for this ?
return undef unless IF::Log::assert(
IF::Utility::externalIdIsValid($externalId),
"entityWithExternalId(): externalId='$externalId' .. is valid for class name $entityName",
);
return $self->entityWithPrimaryKey($entityName, IF::Utility::idFromExternalId($externalId));
}
sub newInstanceOfEntity {
my ($self, $entityName) = @_;
return $self->entityFromHash($entityName, {});
}
sub entityFromHash {
my ($self, $entityName, $hash) = @_;
return undef unless $entityName;
return undef unless $hash;
my $entityClass = $self->model()->entityNamespace()."::$entityName";
return $entityClass->new(%{$hash});
}
sub entityFromRawHash {
my ($self, $entityName, $hash) = @_;
return unless $entityName;
return unless $hash;
my $entityClass = $self->model()->entityNamespace()."::$entityName";
return $entityClass->newFromRawDictionary($hash);
}
sub entityArrayFromHashArray {
my ($self, $entityName, $hashArray) = @_;
return undef unless $entityName;
return undef unless $hashArray;
my $entityClass = $self->model()->entityNamespace()."::$entityName";
my $entityArray =[];
for my $e (@$hashArray) {
push (@$entityArray, $entityClass->new(%{$e}));
}
return $entityArray;
}
sub allEntities {
my $self = shift;
my $entityName = shift;
return [] unless $entityName;
my $fetchSpecification = IF::FetchSpecification->new($entityName);
$fetchSpecification->setFetchLimit(0);
return $self->entitiesMatchingFetchSpecification($fetchSpecification);
}
sub entitiesWithPrimaryKeys {
my ($self, $entityName, $entityIds) = @_;
my $entityClassDescription = $self->model()->entityClassDescriptionForEntityNamed($entityName);
return [] unless $entityClassDescription;
unless (IF::Log::assert(!$entityClassDescription->isAggregateEntity(), "Entity is not aggregate")) {
return;
}
my $results = [];
for (my $i=0; $i<=$#$entityIds; $i+=30) {
my $idList = [];
for (my $j=$i; $j<($i+30); $j++) {
last unless $entityIds->[$j];
push (@$idList, $entityIds->[$j]);
}
my $qualifier = IF::Qualifier->new("SQL",
$entityClassDescription->_primaryKey()->stringValue().
" IN (".join(",", @$idList).")"
);
my $entities = $self->entitiesMatchingQualifier($entityName, $qualifier);
push (@$results, @$entities);
}
return $results;
}
sub entityMatchingQualifier {
my ($self, $entityName, $qualifier) = @_;
my $entities = $self->entitiesMatchingQualifier($entityName, $qualifier);
if (scalar @$entities > 1) {
IF::Log::warning("More than one entity found for entityMatchingQualifier");
}
return $entities->[0];
}
sub entitiesMatchingQualifier {
my ($self, $entityName, $qualifier) = @_;
unless ($entityName) {
IF::Log::error("You must specify an entity type");
return;
}
return unless $qualifier;
my $fetchSpecification = IF::FetchSpecification->new($entityName, $qualifier);
return $self->entitiesMatchingFetchSpecification($fetchSpecification);
}
sub entityMatchingFetchSpecification {
my $self = shift;
my $fetchSpecification = shift;
my $entities = $self->entitiesMatchingFetchSpecification($fetchSpecification);
return $entities->[0];
}
sub entitiesMatchingFetchSpecification {
my $self = shift;
my $fetchSpecification = shift;
return IF::Array->new() unless $fetchSpecification;
my $results = IF::DB::rawRowsForSQLWithBindings($fetchSpecification->toSQLFromExpression());
$results = IF::Array->new() unless $results;
my $unpackedResults = $fetchSpecification->unpackResultsIntoEntitiesInObjectContext($results, $self);
IF::Log::database("Matched ".scalar @$results." rows, ".scalar @$unpackedResults." result(s).");
if ($self->trackingIsEnabled()) {
$self->trackEntities($unpackedResults);
}
return $unpackedResults;
}
sub countOfEntitiesMatchingFetchSpecification {
my $self = shift;
my $fetchSpecification = shift;
my $results = IF::DB::_driver()->countUsingSQL($fetchSpecification->toCountSQLFromExpression());
IF::Log::database("Counted ".$results->[0]->{COUNT}." results");
return $results->[0]->{COUNT};
}
sub resultsForSummarySpecification {
my ($self, $summarySpecification) = @_;
return [] unless $summarySpecification;
my $results = IF::DB::rawRowsForSQLWithBindings($summarySpecification->toSQLFromExpression());
my $unpackedResults = $summarySpecification->unpackResultsIntoDictionaries($results);
IF::Log::database("Summary contained ".scalar @$unpackedResults." results");
return [map { bless $_, "IF::Dictionary" } @$unpackedResults];
}
sub trackEntities {
my ($self) = shift;
my $entities;
if (IF::Array::isArray($_[0])) {
$entities = $_[0];
} else {
$entities = \@_;
}
foreach my $entity (@$entities) {
#print STDERR "Tracking entity $entity\n";
$self->trackEntity($entity);
}
}
sub trackEntity {
my ($self, $entity) = @_;
return if $entity->isTrackedByObjectContext();
if ($entity->hasNeverBeenCommitted()) {
push (@{$self->{_addedEntities}}, $entity);
$entity->awakeFromInsertionInObjectContext($self);
} else {
my $pkv = $entity->uniqueIdentifier()->description();
if ($self->{_trackedEntities}->{$pkv}) {
if ($self->{_trackedEntities}->{$pkv} == $entity) {
# this instance is already being tracked
} else {
my $trackedEntity = $self->{_trackedEntities}->{$pkv};
if ($trackedEntity->hasChanged()) {
# TODO what to do here?
IF::Log::error("Entity $pkv is already tracked by the ObjectContext but instances do not match");
}
}
} else {
$self->{_trackedEntities}->{$pkv} = $entity;
$entity->awakeFromFetchInObjectContext($self);
}
}
$self->{_forgottenEntities}->removeObject($entity);
#print STDERR "Setting tracking object context of $entity to $self\n";
$entity->setTrackingObjectContext($self);
# if the entity that was just added has related
# entities, we are going to track them too.
# TODO:kd - watch for cycles here.
my $relatedEntities = $entity->relatedEntities();
foreach my $e (@$relatedEntities) {
$self->trackEntity($e);
}
}
sub untrackEntity {
my ($self, $entity) = @_;
my $e = $self->trackedInstanceOfEntity($entity) || $entity;
unless ( $self->{_forgottenEntities}->containsObject($e) ) {
$self->{_forgottenEntities}->addObject($e);
}
$self->{_addedEntities}->removeObject($e);
unless ( $e->hasNeverBeenCommitted() ) {
my $pkv = $e->uniqueIdentifier()->description();
delete $self->{_trackedEntities}->{$pkv};
}
#print STDERR "Removing tracking object context of $e\n";
$e->setTrackingObjectContext(undef);
}
sub entityIsTracked {
my ($self, $entity) = @_;
my $e = $self->trackedInstanceOfEntity($entity);
return defined $e;
}
sub updateTrackedInstanceOfEntity {
my ($self, $entity) = @_;
return if $self->{_saveChangesInProgress};
$self->untrackEntity($entity);
$self->trackEntity($entity);
}
sub trackedInstanceOfEntity {
my ($self, $entity) = @_;
unless ($entity) {
IF::Log::error("Cannot retrieve tracked instance of nil");
return undef;
}
if ($entity->hasNeverBeenCommitted()) {
# we can't check for it by pk
if ($self->{_addedEntities}->containsObject($entity)) { return $entity }
return undef;
}
my $pkv = $entity->uniqueIdentifier()->description();
return $self->{_trackedEntities}->{$pkv} || $self->{_deletedEntities}->{$pkv};
}
sub trackedInstanceOfEntityWithUniqueIdentifier {
my ($self, $uid) = @_;
return $self->{_trackedEntities}->{$uid->description()};
}
# For now there's no real difference between
# inserting it into the ObjectContext and
# tracking stuff that comes from the DB - but
# maybe there will be so I'm adding this
# here.
sub insertEntity {
my ($self, $entity) = @_;
return unless $self->{_shouldTrackEntities};
$self->trackEntity($entity);
}
sub forgetEntity {
my ($self, $entity) = @_;
return unless $self->{_shouldTrackEntities};
$self->untrackEntity($entity);
}
sub deleteEntity {
my ($self, $entity) = @_;
return unless $self->{_shouldTrackEntities};
# TODO add notifications
return unless $entity->isTrackedByObjectContext();
unless ($entity->hasNeverBeenCommitted()) {
my $pkv = $entity->uniqueIdentifier->description();
if ($self->{_deletedEntities}->{$pkv}) {
if ($self->{_deletedEntities}->{$pkv} == $entity) {
# this instance is already deleted - ignore
} else {
IF::Log::error("Can't delete $entity - object with same PK value has already been deleted");
}
} else {
$self->{_deletedEntities}->{$pkv} = $entity;
}
}
}
# These are just here for testing; you generally won't want to use these.
sub forgottenEntities { return $_[0]->{_forgottenEntities} }
sub addedEntities { return $_[0]->{_addedEntities} }
sub deletedEntities { return $_[0]->{_deletedEntities} }
# we need to include _addedEntities here too; from the POV
# outside of the OC, added entities are "tracked" too.
sub trackedEntities {
my ($self) = @_;
return IF::Array->new()->initWithArrayRef([
values %{$self->{_trackedEntities}},
@{$self->{_addedEntities}},
values %{$self->{_deletedEntities}},
]);
}
sub changedEntities {
my ($self) = @_;
my $changed = IF::Array->new();
foreach my $e (values %{$self->{_trackedEntities}}) {
if ($e->hasChanged()) {
push @$changed, $e;
}
}
return $changed;
}
sub enableTracking {
my ($self) = @_;
$self->{_shouldTrackEntities} = 1;
}
sub disableTracking {
my ($self) = @_;
$self->{_shouldTrackEntities} = 0;
}
sub trackingIsEnabled {
my ($self) = @_;
return $self->{_shouldTrackEntities};
}
sub saveChanges {
my ($self) = @_;
unless ($self->{_shouldTrackEntities}) {
# TODO:kd - exceptions
IF::Log::error("Can't call saveChanges on an ObjectContext that is not tracking");
return;
}
# TODO Make transactions optional
#[startTransaction];
$self->{_saveChangesInProgress} = 1;
try {
# Process additions first.
my $aes = $self->{_addedEntities};
foreach my $ae (@{$self->{_addedEntities}}) {
$ae->save();
}
# then updates
my $updatedEntities = $self->{_trackedEntities}->allValues();
foreach my $ue (@$updatedEntities) {
$ue->save();
}
# then deletions
my $des = $self->{_deletedEntities}->allValues();
foreach my $de (@$des) {
$des->_deleteSelf();
}
} catch {
# [WMDB rollbackTransaction];
IF::Log::error("Transaction failed: $_");
return;
};
# I think we succeeded at this point, so
# move the added entities into the trackedEntities
# dictionary, clear the deletedEntities out,
# and do some other housekeeping
# NOTE: none of the exceptions thrown here are
# likely ever to occur; conceivably they could,
# and we need to check for them, but in general
# this code shouldn't throw.
try {
foreach my $entity (@{$self->{_addedEntities}}) {
if ($entity->hasNeverBeenCommitted()) {
# this shouldn't be possible
IF::Log::error("Failed to save new object $entity");
return; #?
}
my $pkv = $entity->uniqueIdentifier()->description();
if ($self->{_trackedEntities}->{$pkv}) {
# this instance is already being tracked
IF::Log::error("Newly saved object seems to be tracked already: $entity");
return;
} else {
$self->{_trackedEntities}->{$pkv} = $entity;
}
}
foreach my $entity (values %{$self->{_deletedEntities}}) {
unless ($entity->wasDeletedFromDataStore()) {
IF::Log::error("Object should have been deleted but wasn't: $entity");
return;
}
}
} catch {
# [WMDB rollbackTransaction];
IF::Log::error("Error during saveChanges: $_");
$self->{_saveChangesInProgress} = 0;
return;
};
$self->{_addedEntities} = IF::Array->new();
$self->{_deletedEntities} = IF::Dictionary->new();
# hmmmm, do we really want to flush this?
$self->{_forgottenEntities} = IF::Array->new();
# otherwise, commit the transaction
#[WMDB endTransaction];
$self->{_saveChangesInProgress} = 0;
#[WMLog debug:UTIL.object.repr(UTIL.keys(_trackedEntities))];
}
sub clearTrackedEntities {
my ($self) = @_;
my $all = $self->trackedEntities();
foreach my $e (@$all) {
$self->untrackEntity($e);
}
$self->initTrackingStore();
}
1;
| quile/if-framework | framework/lib/IF/ObjectContext.pm | Perl | mit | 17,487 |
package Nspamper;
use strict;
use warnings;
use Carp;
use Net::DNS;
use NetAddr::IP;
our $VERSION = 0.02;
# TODO: add / allow more verbose progress / error reporting
sub new {
my( $proto ) = @_;
bless {
resolver => Net::DNS::Resolver->new,
domain => {
# name => [ $nsresolver, ... ]
},
ns => {
# name => $resolver,
},
}, ref $proto || $proto;
}
sub ip_get {
my( $self, $name, $resolver ) = @_;
my @ip;
if( my $r = $resolver->query( $name, 'A' ) ){
foreach my $rr ( $r->answer ){
push @ip, $rr->address
if $rr->type eq 'A';
}
}
if( my $r = $resolver->query( $name, 'AAAA' ) ){
foreach my $rr ( $r->answer ){
push @ip, $rr->address
if $rr->type eq 'AAAA';
}
}
@ip or return;
return \@ip;
}
sub ns_get {
my( $self, $ns ) = @_;
my $ips = $self->ip_get( $ns, $self->{resolver} )
or return;
return Net::DNS::Resolver->new(
nameservers => $ips,
);
}
sub ns {
my( $self, $ns ) = @_;
$ns = lc $ns;
$self->{ns}{$ns}
||= $self->ns_get( $ns );
}
sub domain_get {
my( $self, $domain ) = @_;
my @resolver;
if( my $r = $self->{resolver}->query( $domain, 'SOA' ) ){
foreach my $rr ( $r->answer ){
$rr->type eq 'SOA'
or next;
my $ns = $self->ns( $rr->mname )
or next;
push @resolver, $ns;
}
# TODO: only lookup A/AAAA if they're not in $rr->additional
}
# TODO: secondary NS... if they don't get xfer from primary
# report failure if no resolver was found
@resolver or return;
return \@resolver;
}
sub domain {
my( $self, $domain ) = @_;
$domain = lc $domain;
$self->{domain}{$domain}
||= $self->domain_get( $domain );
}
sub compare_rr {
my( $self, $resolver, $domain, $host, $t, $want ) = @_;
my $na;
if( ! defined $want ){
# ok
} elsif( $t eq 'A' or $t eq 'AAAA' ){
$na = eval { NetAddr::IP->new($want) }
or return;
}
my $name = "$host.$domain";
my( $ok, $bad );
if( my $r = $resolver->query( $name, $t ) ){
foreach my $rr ( $r->answer ){
$rr->type eq $t
or next;
if( ! defined $want ){
++$bad;
} elsif( $t eq 'A' or $t eq 'AAAA' ){
my $wa = eval { NetAddr::IP->new( $rr->address ) };
if( ! $wa ){
++$bad;
} elsif( $na eq $wa ){
++$ok;
} else {
++$bad;
}
}
# TODO: other rrtypes
}
} else {
++$bad;
}
return if $ok && ! $bad;
my $update = Net::DNS::Update->new( $domain );
$update->push( "update", rr_del("$name $t"));
$update->push( "update", rr_add("$name 1 $t $want"))
if defined $want;
return {
resolver => $resolver,
update => $update,
name => $name,
type => $t,
want => $want,
};
}
sub compare {
my( $self, $domain, $host, $want ) = @_;
my $resolver = $self->domain( $domain )
or return;
my @changes;
foreach my $res ( @$resolver ){
foreach my $t ( keys %$want ){
if( my $c = $self->compare_rr( $res, $domain, $host, $t, $want->{$t} ) ){
push @changes, $c;
}
}
}
return \@changes;
}
sub update {
my( $self, $key, $changes ) = @_;
ref $changes eq 'ARRAY'
or croak "bad changes argument";
my $error;
foreach my $c ( @$changes ){
my $resolver = $c->{resolver};
$c->{update}->sign_tsig( $c->{name}, $key );
if( my $r = $resolver->send( $c->{update} ) ){
if( $r->header->rcode ne 'NOERROR' ){
$c->{error} = $r->header->rcode;
++$error;
}
} else {
$c->{error} = $resolver->errorstring;
++$error;
}
}
return !$error;
}
1;
| rclasen/nspamper | lib/Nspamper.pm | Perl | mit | 3,425 |
package JSON::Schema::Validator::State;
use strict;
use warnings;
use overload
'==' => \&num_comparision,
'""' => \&to_string,
bool => \&to_string;
sub new {
my ( $proto, %args ) = @_;
my $state = {};
$state->{path} = '$';
$state->{schema_root} = $args{schema_root};
$state->{errors} = {};
$state->{schemas_by_url} = {};
$state->{schemas_by_id} = {};
bless $state, $proto;
$state->id_lookup;
return $state;
}
sub to_string { not keys %{$_[0]->{errors}} }
sub num_comparision { shift->to_string == shift }
sub add_path {
my ( $state, $path ) = @_;
$state->{path} .= ".$path";
}
sub add_error {
my ( $state, $path, $msg ) = @_;
$state->{errors}->{$path} ||= [];
push @{ $state->{errors}->{$path} }, $msg;
}
sub id_lookup {
my ( $state, $schema, $seen ) = @_;
$schema ||= $state->{schema_root};
$seen ||= {};
return unless ref $schema eq 'HASH' || ref $schema eq 'ARRAY';
return if exists $seen->{$schema};
$seen->{$schema} = 1;
if ( ref $schema eq 'HASH' ) {
if ( exists $schema->{'$id'} ) {
$state->{schemas_by_id}{ $schema->{'$id'} } = $schema;
}
while ( my ( $k, $subschema ) = each %$schema ) {
$state->id_lookup( $subschema, $seen );
}
}
elsif ( ref $schema eq 'ARRAY' ) {
for ( @$schema ) {
$state->id_lookup( $_, $seen );
}
}
}
1;
| AnotherOneAckap/p5-json-schema-validator | lib/JSON/Schema/Validator/State.pm | Perl | mit | 1,327 |
/* Problem 1 */
odd_list(X, [], Y) :-
Y >= X.
odd_list(X, [Y|L], Y) :-
X > Y, Z is Y+2, odd_list(X, L, Z).
odd_list(X, L) :-
odd_list(X, L, 1).
/* Problem 2 */
nexttri(X, Y, Y, _) :-
X < Y.
nexttri(X, Y, A, B) :-
X >= A, P is A+B, Q is B+1, nexttri(X, Y, P, Q).
nexttri(X, Y) :-
nexttri(X, Y, 1, 2).
/* Problem 3 */
member(E, [E|_]).
member(E, [_|X]) :-
member(E, X).
list_diff([], _,[]).
list_diff([E|X], L, Y) :-
member(E, L), list_diff(X, L, Y).
list_diff([E|X], L, [E|Y]) :-
not(member(E, L)), list_diff(X, L, Y).
/* Problem 4 */
remove_duplicate([], []).
remove_duplicate(X, [E|Y]) :-
member(E, Y), remove_duplicate(X, Y).
remove_duplicate([E|X], [E|Y]) :-
not(member(E, Y)), remove_duplicate(X, Y).
list_merge(X, Y, Z) :-
append(X, Y, L), remove_duplicate(Z, L).
/* Problem 5 */
if_is_true(true).
if_is_true(X):-
X = true, !, fail.
if_is_true(and(X, Y)) :-
and(X, Y).
if_is_true(or(X, Y)) :-
or(X, Y).
and(X, Y) :-
if_is_true(X), if_is_true(Y).
or(X, _) :-
if_is_true(X).
or(_, X) :-
if_is_true(X).
| chpoon92/prolog-practice-assignment-prolog | src/Assignment3.pl | Perl | mit | 1,085 |
#!/usr/bin/perl
=head1 Static Index Generator
Generates a static index from Documenter index JSON
=cut
use strict;
use FindBin qw($Bin);
use lib "$Bin";
use JSON;
use File::Basename;
use File::Spec qw(catfile);
use XML::RSS;
use Scalar::Util qw(looks_like_number);
use DateTime;
use DateTime::Format::W3CDTF;
use DateTime::Format::Epoch;
use Template;
use Tools::Output;
use Tools::Output::HTML;
use sort 'stable';
if (!defined $ARGV[0]) {
die "Usage : staticindex.pl <indexfilename> <baseurl=http://localhost:4000/> <flat_type=html>";
}
my $baseurl = $ARGV[1] || "http://localhost:4000/";
my $flat_index_type = (lc $ARGV[2]) || 'html';
unless ($baseurl =~ m/\/$/) {
$baseurl .= '/';
}
my $js;
{ local $/ = undef; local *FILE;
open FILE, "<", $ARGV[0]; $js = <FILE>; close FILE }
my $f_base = basename($ARGV[0]), "\n";
my $f_dir = dirname($ARGV[0]), "\n";
my $indexdata = from_json($js);
our @linear_index = ();
recurse($indexdata);
=head2 Sorting comparator by index id
Used for sort, compares two index ids:
1.2.3 < 1.2.4
1.2 < 1.2.4
1.2.3 = 1.2.3
2.0 > 1.9.9
1.11 > 1.1
etc.
=cut
sub by_idx {
my $a = shift;
my $b = shift;
my $result = 0;
my @a_s = split /\./, $a->{linear_index_pos};
my @b_s = split /\./, $b->{linear_index_pos};
my $len = scalar @a_s;
if (scalar @b_s < $len) {
$len = scalar @b_s;
}
for (my $i = 0; $i < $len; $i++) {
if ($a_s[$i] ne $b_s[$i]) {
if (looks_like_number ($a_s[$i]) &&
looks_like_number ($b_s[$i]) ) {
return $a_s[$i] <=> $b_s[$i];
} else {
return $a_s[$i] cmp $b_s[$i];
}
}
}
# here, all elements in a_s and b_s were the same
# check which one of them is shorter
if (scalar @b_s < scalar @a_s) {
return -1;
}
if (scalar @a_s < scalar @b_s) {
return 1;
}
# equal elements, return;
return 0;
}
=head2 Recursively process the index tree
Parameters:
$node : the current node (hash with value and children elements)
$path : the current path (used in recursion)
$level : the current depth
$index_pos : the parent's index position
=cut
sub recurse {
my $node = shift;
my $path = shift || "Index";
my $level = shift || 1;
my $index_pos = shift || '1';
my $filename = $node->{value}->{link};
# remove hash tag
$filename =~ s/\#.*$//;
$filename =~ s/\.html$//;
$node->{value}->{path} = $path . "/" . $filename;
$node->{value}->{level} = $level;
$node->{value}->{linear_index_pos} = $index_pos;
$node->{value}->{linear_index_pos} =~ s/[^A-Za-z0-9\.\-\_]/\_/g;
push @linear_index, $node->{value}
if defined ($node->{value}->{link}) && $node->{value}->{link} ne "";
# default order is lexicographically by path,
# but we can prioritize items using index_path
# which is set using markup comments (see PerlParser.pm)
my @ordered_children = sort {
my $pa = $a->{value}->{index_path} || $a->{path};
my $pb = $b->{value}->{index_path} || $b->{path};
return $pa cmp $pb
} @{$node->{children}};
my $sub_index = 1;
foreach my $c (@ordered_children){
recurse($c, $node->{path}, $level + 1,
$index_pos . '.' . $sub_index);
$sub_index++;
}
# establish index order
@ordered_children = sort { by_idx($a->{value}, $b->{value}) } @ordered_children;
$node->{children} = \@ordered_children;
}
## write updated index
open OUT_INDEX, ">", $ARGV[0]
or die "Cannot update index with order information\n";
print OUT_INDEX to_json($indexdata, {pretty=>1});
close OUT_INDEX;
print "Number of items: ", scalar @linear_index, "\n";
# create an RSS 2.0 file
my $dt = DateTime->new( year => 1970, month => 1, day => 1 );
my $parser = DateTime::Format::Epoch->new(
epoch => $dt,
unit => 'seconds',
type => 'int', # or 'float', 'bigint'
skip_leap_seconds => 1,
start_at => 0,
local_epoch => undef,
);
my $formatter = DateTime::Format::W3CDTF->new;
my $rss = XML::RSS->new (version => '2.0');
$rss->channel(title => 'Source Index',
link => $baseurl,
language => 'en',
description => 'Source documentation',
pubDate => $formatter->format_datetime(DateTime->now),
lastBuildDate => $formatter->format_datetime(DateTime->now),
);
# index order sorting
sort {by_idx($a, $b)} @linear_index;
my $flat_output;
if ($flat_index_type eq 'html') {
$flat_output = Tools::Output::HTML->new;
} else {
$flat_output = Tools::Output->new;
}
foreach my $e (@linear_index) {
my $filename = $e->{link};
# remove hash tag
$filename =~ s/\#.*$//;
$filename = File::Spec->catfile($f_dir, $filename);
my $mod = $formatter->format_datetime(
$parser->parse_datetime( (stat "$filename")[9] )
);
my $vstr = $flat_output->l($flat_output->x($e->{title}), $e->{link});
if($e->{options} =~ m/show\_type/) {
$vstr = $e->{type} . ' ' . $vstr;
}
$flat_output->xt($e->{linear_index_pos});
$flat_output->t(
" " . $flat_output->b(
$vstr
)
);
$flat_output->t(
" (" . $flat_output->i(
$flat_output->x($e->{path})
)
. ")"
);
$flat_output->p();
$rss->add_item(title => $e->{title},
# creates a guid field with permaLink=true
permaLink => $baseurl . $e->{link},
description =>
$e->{type} . ":" .
$e->{level} . ":" .
$e->{linear_index_pos} . ":" .
$e->{path},
dc => {
date => $mod
},
);
}
$rss->save(File::Spec->catfile($f_dir, 'feed.rss'));
## make a static index file
## process template
my $template = Template->new({
INCLUDE_PATH => $Bin,
ABSOLUTE => 1,
EVAL_PERL => 1,
OUTPUT => File::Spec->catfile($f_dir, 'static_index.'.$flat_index_type),
ENCODING => 'utf8',
});
my $vars = {
doc => {
TITLE => "Documentation Index",
CONTENT => $flat_output->result,
}
};
my $templatefile = "template.$flat_index_type";
my $templatedir = File::Spec->catdir($Bin, 'templates', $flat_index_type);
$templatefile = File::Spec->catfile($templatedir, $templatefile);
$template->process (
$templatefile,
$vars,
File::Spec->catfile($f_dir, 'static_index.'.$flat_index_type),
{binmode=>'utf8'} )
|| die $template->error();
| pkrusche/documenter | staticindex.pl | Perl | mit | 6,358 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::hyperv::2012::local::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_simple);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '0.1';
%{$self->{modes}} = (
'list-node-vms' => 'apps::hyperv::2012::local::mode::listnodevms',
'node-integration-service' => 'apps::hyperv::2012::local::mode::nodeintegrationservice',
'node-replication' => 'apps::hyperv::2012::local::mode::nodereplication',
'node-snapshot' => 'apps::hyperv::2012::local::mode::nodesnapshot',
'node-vm-status' => 'apps::hyperv::2012::local::mode::nodevmstatus',
'scvmm-integration-service' => 'apps::hyperv::2012::local::mode::scvmmintegrationservice',
'scvmm-snapshot' => 'apps::hyperv::2012::local::mode::scvmmsnapshot',
'scvmm-vm-status' => 'apps::hyperv::2012::local::mode::scvmmvmstatus',
);
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Windows Hyper-V locally.
=cut
| wilfriedcomte/centreon-plugins | apps/hyperv/2012/local/plugin.pm | Perl | apache-2.0 | 2,087 |
#
# Copyright 2019 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package network::a10::ax::snmp::mode::vserverusage;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
sub custom_status_output {
my ($self, %options) = @_;
my $msg = 'status : ' . $self->{result_values}->{status};
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_axVirtualServerStatStatus'};
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'vserver', type => 1, cb_prefix_output => 'prefix_vserver_output', message_multiple => 'All virtual servers are ok' }
];
$self->{maps_counters}->{vserver} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'axVirtualServerStatStatus' }, { name => 'display' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
{ label => 'current-con', nlabel => 'virtualserver.connections.current.count', set => {
key_values => [ { name => 'axVirtualServerStatCurConns' }, { name => 'display' } ],
output_template => 'Current Connections : %s',
perfdatas => [
{ label => 'current_connections', value => 'axVirtualServerStatCurConns_absolute', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
{ label => 'total-con', nlabel => 'virtualserver.connections.total.count', set => {
key_values => [ { name => 'axVirtualServerStatTotConns', diff => 1 }, { name => 'display' } ],
output_template => 'Total Connections : %s',
perfdatas => [
{ label => 'total_connections', value => 'axVirtualServerStatTotConns_absolute', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
{ label => 'traffic-in', nlabel => 'virtualserver.traffic.in.bitspersecond', set => {
key_values => [ { name => 'axVirtualServerStatBytesIn', diff => 1 }, { name => 'display' } ],
per_second => 1, output_change_bytes => 2,
output_template => 'Traffic In : %s %s/s',
perfdatas => [
{ label => 'traffic_in', value => 'axVirtualServerStatBytesIn_per_second', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
{ label => 'traffic-out', nlabel => 'virtualserver.traffic.out.bitspersecond', set => {
key_values => [ { name => 'axVirtualServerStatBytesOut', diff => 1 }, { name => 'display' } ],
per_second => 1, output_change_bytes => 2,
output_template => 'Traffic Out : %s %s/s',
perfdatas => [
{ label => 'traffic_out', value => 'axVirtualServerStatBytesOut_per_second', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display_absolute' },
],
}
},
];
}
sub prefix_vserver_output {
my ($self, %options) = @_;
return "Virtual Server '" . $options{instance_value}->{display} . "' ";
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1);
bless $self, $class;
$options{options}->add_options(arguments =>
{
"filter-name:s" => { name => 'filter_name' },
"warning-status:s" => { name => 'warning_status', default => '' },
"critical-status:s" => { name => 'critical_status', default => '%{status} =~ /down/i' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$self->change_macros(macros => ['warning_status', 'critical_status']);
}
my %map_status = (
1 => 'up', 2 => 'down', 3 => 'disabled',
);
my $oid_axVirtualServerStatName = '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.2';
my $mapping = {
axVirtualServerStatBytesIn => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.4' },
axVirtualServerStatBytesOut => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.6' },
axVirtualServerStatTotConns => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.8' },
axVirtualServerStatCurConns => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.9' },
axVirtualServerStatStatus => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.10', map => \%map_status },
};
sub manage_selection {
my ($self, %options) = @_;
if ($options{snmp}->is_snmpv1()) {
$self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3.");
$self->{output}->option_exit();
}
my $snmp_result = $options{snmp}->get_table(oid => $oid_axVirtualServerStatName, nothing_quit => 1);
$self->{vserver} = {};
foreach my $oid (keys %{$snmp_result}) {
$oid =~ /^$oid_axVirtualServerStatName\.(.*)$/;
my $instance = $1;
$snmp_result->{$oid} =~ s/\\//g;
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$snmp_result->{$oid} !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "skipping virtual server '" . $snmp_result->{$oid} . "'.", debug => 1);
next;
}
$self->{vserver}->{$instance} = { display => $snmp_result->{$oid} };
}
$options{snmp}->load(oids => [$mapping->{axVirtualServerStatBytesIn}->{oid}, $mapping->{axVirtualServerStatBytesOut}->{oid},
$mapping->{axVirtualServerStatTotConns}->{oid}, $mapping->{axVirtualServerStatCurConns}->{oid},
$mapping->{axVirtualServerStatStatus}->{oid}
],
instances => [keys %{$self->{vserver}}], instance_regexp => '^(.*)$');
$snmp_result = $options{snmp}->get_leef(nothing_quit => 1);
foreach (keys %{$self->{vserver}}) {
my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $_);
foreach my $name (('axVirtualServerStatBytesIn', 'axVirtualServerStatBytesOut')) {
$result->{$name} *= 8;
}
foreach my $name (keys %$mapping) {
$self->{vserver}->{$_}->{$name} = $result->{$name};
}
}
if (scalar(keys %{$self->{vserver}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No virtual server found.");
$self->{output}->option_exit();
}
$self->{cache_name} = "a10_ax_" . $self->{mode} . '_' . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_name}) ? md5_hex($self->{option_results}->{filter_name}) : md5_hex('all'));
}
1;
__END__
=head1 MODE
Check virtual server usage.
=over 8
=item B<--warning-status>
Set warning threshold for status.
Can used special variables like: %{status}, %{display}
=item B<--critical-status>
Set critical threshold for status (Default: '%{status} =~ /down/i').
Can used special variables like: %{status}, %{display}
=item B<--warning-*>
Threshold warning.
Can be: 'current-con', 'total-con', 'traffic-in', 'traffic-out'.
=item B<--critical-*>
Threshold critical.
Can be: 'current-con', 'total-con', 'traffic-in', 'traffic-out'.
=item B<--filter-name>
Filter by virtual server name (can be a regexp).
=back
=cut
| Sims24/centreon-plugins | network/a10/ax/snmp/mode/vserverusage.pm | Perl | apache-2.0 | 9,167 |
#!/usr/bin/perl -w
use strict;
use lib ".";
use PAsm;
use Data::Dumper;
my $lowcovremoved = 0;
print STDERR "Removing nodes <= $MAX_LOW_COV_LEN bp with cov <= $MAX_LOW_COV_THRESH\n";
while (<>)
{
chomp;
my $node = {};
my @vals = split /\t/, $_;
my $nodeid = shift @vals;
my $msgtype = shift @vals; ## nodemsg
if ($msgtype eq $NODEMSG)
{
parse_node($node, \@vals);
}
else
{
die "Unknown msg: $_\n";
}
my $len = node_len($node);
my $cov = node_cov($node);
if (($len <= $MAX_LOW_COV_LEN) && ($cov <= $MAX_LOW_COV_THRESH))
{
#print STDERR "Deleting low coverage node $nodeid len=$len cov=$cov\n";
$lowcovremoved++;
foreach my $et (qw/ff fr rf rr/)
{
if (exists $node->{$et})
{
my $ret = flip_link($et);
foreach my $v (@{$node->{$et}})
{
print "$v\t$TRIMMSG\t$ret\t$nodeid\n";
}
}
}
}
else
{
print "$_\n";
}
}
hadoop_counter("lowcovremoved", $lowcovremoved);
| julianlau/contrail-emr | prototype/cliplowcoverage-map.pl | Perl | apache-2.0 | 999 |
#
# Copyright 2016 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package network::netasq::snmp::mode::vpnstatus;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use centreon::plugins::values;
use centreon::plugins::statefile;
use Digest::MD5 qw(md5_hex);
my $thresholds = {
vpn => [
['larval', 'WARNING'],
['mature', 'OK'],
['dying', 'CRITICAL'],
['dead', 'CRITICAL'],
],
};
my $instance_mode;
my $maps_counters = {
vpn => {
'000_status' => { set => {
key_values => [ { name => 'ntqVPNState' } ],
closure_custom_calc => \&custom_status_calc,
output_template => 'Status : %s', output_error_template => 'Status : %s',
output_use => 'ntqVPNState',
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&custom_threshold_output,
}
},
'001_traffic' => { set => {
key_values => [ { name => 'ntqVPNBytes', diff => 1 }, { name => 'num' } ],
per_second => 1, output_change_bytes => 2,
output_template => 'Traffic: %s %s/s',
perfdatas => [
{ label => 'traffic', value => 'ntqVPNBytes_per_second', template => '%s',
unit => 'b/s', min => 0, label_extra_instance => 1, cast_int => 1, instance_use => 'num_absolute' },
],
}
},
},
};
sub custom_threshold_output {
my ($self, %options) = @_;
return $instance_mode->get_severity(section => 'vpn', value => $self->{result_values}->{ntqVPNState});
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{ntqVPNState} = $options{new_datas}->{$self->{instance} . '_ntqVPNState'};
return 0;
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"filter-id:s" => { name => 'filter_id' },
"filter-src-ip:s" => { name => 'filter_src_ip' },
"filter-dst-ip:s" => { name => 'filter_dst_ip' },
"threshold-overload:s@" => { name => 'threshold_overload' },
});
$self->{statefile_value} = centreon::plugins::statefile->new(%options);
foreach my $key (('vpn')) {
foreach (keys %{$maps_counters->{$key}}) {
my ($id, $name) = split /_/;
if (!defined($maps_counters->{$key}->{$_}->{threshold}) || $maps_counters->{$key}->{$_}->{threshold} != 0) {
$options{options}->add_options(arguments => {
'warning-' . $name . ':s' => { name => 'warning-' . $name },
'critical-' . $name . ':s' => { name => 'critical-' . $name },
});
}
$maps_counters->{$key}->{$_}->{obj} = centreon::plugins::values->new(statefile => $self->{statefile_value},
output => $self->{output}, perfdata => $self->{perfdata},
label => $name);
$maps_counters->{$key}->{$_}->{obj}->set(%{$maps_counters->{$key}->{$_}->{set}});
}
}
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
foreach my $key (('vpn')) {
foreach (keys %{$maps_counters->{$key}}) {
$maps_counters->{$key}->{$_}->{obj}->init(option_results => $self->{option_results});
}
}
$instance_mode = $self;
$self->{statefile_value}->check_options(%options);
$self->{overload_th} = {};
foreach my $val (@{$self->{option_results}->{threshold_overload}}) {
if ($val !~ /^(.*?),(.*?),(.*)$/) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload option '" . $val . "'.");
$self->{output}->option_exit();
}
my ($section, $status, $filter) = ($1, $2, $3);
if ($self->{output}->is_litteral_status(status => $status) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload status '" . $val . "'.");
$self->{output}->option_exit();
}
$self->{overload_th}->{$section} = [] if (!defined($self->{overload_th}->{$section}));
push @{$self->{overload_th}->{$section}}, {filter => $filter, status => $status};
}
}
sub run {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
$self->{hostname} = $self->{snmp}->get_hostname();
$self->{snmp_port} = $self->{snmp}->get_port();
$self->manage_selection();
my $multiple = 1;
if (scalar(keys %{$self->{vpn}}) == 1) {
$multiple = 0;
}
if ($multiple == 1) {
$self->{output}->output_add(severity => 'OK',
short_msg => 'All VPN are ok');
}
my $matching = '';
foreach (('filter_id', 'filter_src_ip', 'filter_dst_ip')) {
$matching .= defined($self->{option_results}->{$_}) ? $self->{option_results}->{$_} : 'all';
}
$self->{new_datas} = {};
$self->{statefile_value}->read(statefile => "netasq_" . $self->{hostname} . '_' . $self->{snmp_port} . '_' . $self->{mode} . '_' . md5_hex($matching));
$self->{new_datas}->{last_timestamp} = time();
foreach my $id (sort keys %{$self->{vpn}}) {
my ($short_msg, $short_msg_append, $long_msg, $long_msg_append) = ('', '', '', '');
my @exits = ();
foreach (sort keys %{$maps_counters->{vpn}}) {
my $obj = $maps_counters->{vpn}->{$_}->{obj};
$obj->set(instance => $id);
my ($value_check) = $obj->execute(values => $self->{vpn}->{$id},
new_datas => $self->{new_datas});
if ($value_check != 0) {
$long_msg .= $long_msg_append . $obj->output_error();
$long_msg_append = ', ';
next;
}
my $exit2 = $obj->threshold_check();
push @exits, $exit2;
my $output = $obj->output();
$long_msg .= $long_msg_append . $output;
$long_msg_append = ', ';
if (!$self->{output}->is_status(litteral => 1, value => $exit2, compare => 'ok')) {
$short_msg .= $short_msg_append . $output;
$short_msg_append = ', ';
}
$maps_counters->{vpn}->{$_}->{obj}->perfdata(extra_instance => $multiple);
}
$self->{output}->output_add(long_msg => "VPN '$self->{vpn}->{$id}->{num}/$self->{vpn}->{$id}->{ntqVPNIPSrc}/$self->{vpn}->{$id}->{ntqVPNIPDst}' $long_msg");
my $exit = $self->{output}->get_most_critical(status => [ @exits ]);
if (!$self->{output}->is_status(litteral => 1, value => $exit, compare => 'ok')) {
$self->{output}->output_add(severity => $exit,
short_msg => "VPN '$self->{vpn}->{$id}->{num}/$self->{vpn}->{$id}->{ntqVPNIPSrc}/$self->{vpn}->{$id}->{ntqVPNIPDst}' $short_msg"
);
}
if ($multiple == 0) {
$self->{output}->output_add(short_msg => "VPN '$self->{vpn}->{$id}->{num}/$self->{vpn}->{$id}->{ntqVPNIPSrc}/$self->{vpn}->{$id}->{ntqVPNIPDst}' $long_msg");
}
}
$self->{statefile_value}->write(data => $self->{new_datas});
$self->{output}->display();
$self->{output}->exit();
}
sub get_severity {
my ($self, %options) = @_;
my $status = 'UNKNOWN'; # default
if (defined($self->{overload_th}->{$options{section}})) {
foreach (@{$self->{overload_th}->{$options{section}}}) {
if ($options{value} =~ /$_->{filter}/i) {
$status = $_->{status};
return $status;
}
}
}
foreach (@{$thresholds->{$options{section}}}) {
if ($options{value} =~ /$$_[0]/i) {
$status = $$_[1];
return $status;
}
}
return $status;
}
my %map_state = (
0 => 'larval',
1 => 'mature',
2 => 'dying',
3 => 'dead',
);
my $mapping = {
ntqVPNIPSrc => { oid => '.1.3.6.1.4.1.11256.1.1.1.1.2' },
};
my $mapping2 = {
ntqVPNIPDst => { oid => '.1.3.6.1.4.1.11256.1.1.1.1.3' },
};
my $mapping3 = {
ntqVPNState => { oid => '.1.3.6.1.4.1.11256.1.1.1.1.11', map => \%map_state },
};
my $mapping4 = {
ntqVPNBytes => { oid => '.1.3.6.1.4.1.11256.1.1.1.1.13' },
};
sub manage_selection {
my ($self, %options) = @_;
$self->{results} = $self->{snmp}->get_multiple_table(oids => [
{ oid => $mapping->{ntqVPNIPSrc}->{oid} },
{ oid => $mapping2->{ntqVPNIPDst}->{oid} },
{ oid => $mapping3->{ntqVPNState}->{oid} },
{ oid => $mapping4->{ntqVPNBytes}->{oid} },
],
, nothing_quit => 1);
$self->{vpn} = {};
foreach my $oid (keys %{$self->{results}->{$mapping3->{ntqVPNState}->{oid}}}) {
next if ($oid !~ /^$mapping3->{ntqVPNState}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$mapping->{ntqVPNIPSrc}->{oid}}, instance => $instance);
my $result2 = $self->{snmp}->map_instance(mapping => $mapping2, results => $self->{results}->{$mapping2->{ntqVPNIPDst}->{oid}}, instance => $instance);
my $result3 = $self->{snmp}->map_instance(mapping => $mapping3, results => $self->{results}->{$mapping3->{ntqVPNState}->{oid}}, instance => $instance);
my $result4 = $self->{snmp}->map_instance(mapping => $mapping4, results => $self->{results}->{$mapping4->{ntqVPNBytes}->{oid}}, instance => $instance);
if (defined($self->{option_results}->{filter_id}) && $self->{option_results}->{filter_id} ne '' &&
$instance !~ /$self->{option_results}->{filter_id}/) {
$self->{output}->output_add(long_msg => "Skipping '" . $instance . "': no matching filter id.");
next;
}
if (defined($self->{option_results}->{filter_src_ip}) && $self->{option_results}->{filter_src_ip} ne '' &&
$result->{ntqVPNIPSrc} !~ /$self->{option_results}->{filter_src_ip}/) {
$self->{output}->output_add(long_msg => "Skipping '" . $result->{ntqVPNIPSrc} . "': no matching filter src-ip.");
next;
}
if (defined($self->{option_results}->{filter_dst_ip}) && $self->{option_results}->{filter_dst_ip} ne '' &&
$result2->{ntqVPNIPDst} !~ /$self->{option_results}->{filter_dst_ip}/) {
$self->{output}->output_add(long_msg => "Skipping '" . $result2->{ntqVPNIPDst} . "': no matching filter dst-ip.");
next;
}
$self->{vpn}->{$instance} = { num => $instance, %$result, %$result2, %$result3, %$result4};
$self->{vpn}->{$instance}->{ntqVPNBytes} *= 8 if (defined($self->{vpn}->{$instance}->{ntqVPNBytes}));
}
if (scalar(keys %{$self->{vpn}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No entry found.");
$self->{output}->option_exit();
}
}
1;
__END__
=head1 MODE
Check VPN states.
=over 8
=item B<--warning-*>
Threshold warning.
Can be: 'traffic'.
=item B<--critical-*>
Threshold critical.
Can be: 'traffic'.
=item B<--filter-id>
Filter by id (regexp can be used).
=item B<--filter-src-ip>
Filter by src ip (regexp can be used).
=item B<--filter-dst-ip>
Filter by dst ip (regexp can be used).
=item B<--threshold-overload>
Set to overload default threshold values (syntax: section,status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='vpn,CRITICAL,^(?!(mature)$)'
=back
=cut
| bcournaud/centreon-plugins | network/netasq/snmp/mode/vpnstatus.pm | Perl | apache-2.0 | 13,345 |
false :-
main_verifier_error.
verifier_error(A,B,C) :-
A=0,
B=0,
C=0.
verifier_error(A,B,C) :-
A=0,
B=1,
C=1.
verifier_error(A,B,C) :-
A=1,
B=0,
C=1.
verifier_error(A,B,C) :-
A=1,
B=1,
C=1.
fibonacci(A,B,C,D,E) :-
A=1,
B=1,
C=1.
fibonacci(A,B,C,D,E) :-
A=0,
B=1,
C=1.
fibonacci(A,B,C,D,E) :-
A=0,
B=0,
C=0.
fibonacci__1(A) :-
true.
fibonacci___0(A,B) :-
fibonacci__1(B),
B<1,
A=0.
fibonacci__3(A) :-
fibonacci__1(A),
A>=1.
fibonacci___0(A,B) :-
fibonacci__3(B),
B=1,
A=1.
fibonacci__5(A) :-
fibonacci__3(A),
A<1.
fibonacci__5(A) :-
fibonacci__3(A),
A>1.
fibonacci___0(A,B) :-
fibonacci__5(B),
fibonacci(1,0,0,B+ -1,C),
fibonacci(1,0,0,B+ -2,D),
A=C+D.
fibonacci__split(A,B) :-
fibonacci___0(A,B).
fibonacci(A,B,C,D,E) :-
A=1,
B=0,
C=0,
fibonacci__split(E,D).
main_entry :-
true.
main__un :-
main_entry,
fibonacci(1,0,0,9,A),
A<34.
main__un :-
main_entry,
fibonacci(1,0,0,9,A),
A>34.
main_verifier_error :-
main__un.
| bishoksan/RAHFT | benchmarks_scp/SVCOMP15/svcomp15-clp/Fibonacci02_true-unreach-call_true-termination.c.pl | Perl | apache-2.0 | 1,073 |
#!/usr/bin/perl
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
use Digest::SHA qw(hmac_sha1 hmac_sha1_hex);
use Digest::HMAC_MD5 qw(hmac_md5 hmac_md5_hex);
use Getopt::Long;
use strict;
use warnings;
my $key = undef;
my $string = undef;
my $useparts = undef;
my $result = undef;
my $duration = undef;
my $keyindex = undef;
my $verbose = 0;
my $url = undef;
my $client = undef;
my $algorithm = 1;
$result = GetOptions(
"url=s" => \$url,
"useparts=s" => \$useparts,
"duration=i" => \$duration,
"key=s" => \$key,
"client=s" => \$client,
"algorithm=i" => \$algorithm,
"keyindex=i" => \$keyindex,
"verbose" => \$verbose
);
if ( !defined($key) || !defined($url) || !defined($duration) || !defined($keyindex) ) {
&help();
exit(1);
}
my $url_prefix = $url;
$url_prefix =~ s/^([^:]*:\/\/).*$/$1/;
$url =~ s/^[^:]+:\/\///;
my $i = 0;
my $part_active = 0;
my $j = 0;
my @inactive_parts = ();
foreach my $part ( split( /\//, $url ) ) {
if ( length($useparts) > $i ) {
$part_active = substr( $useparts, $i++, 1 );
}
if ($part_active) {
$string .= $part . "/";
}
else {
$inactive_parts[$j] = $part;
}
$j++;
}
my $urlHasParams = index($string,"?");
chop($string);
if ( defined($client) ) {
if ($urlHasParams > 0) {
$string .= "&C=" . $client . "&E=" . ( time() + $duration ) . "&A=" . $algorithm . "&K=" . $keyindex . "&P=" . $useparts . "&S=";
}
else {
$string .= "?C=" . $client . "&E=" . ( time() + $duration ) . "&A=" . $algorithm . "&K=" . $keyindex . "&P=" . $useparts . "&S=";
}
}
else {
if ($urlHasParams > 0) {
$string .= "&E=" . ( time() + $duration ) . "&A=" . $algorithm . "&K=" . $keyindex . "&P=" . $useparts . "&S=";
}
else {
$string .= "?E=" . ( time() + $duration ) . "&A=" . $algorithm . "&K=" . $keyindex . "&P=" . $useparts . "&S=";
}
}
$verbose && print "signed string = " . $string . "\n";
my $digest;
if ( $algorithm == 1 ) {
$digest = hmac_sha1_hex( $string, $key );
}
else {
$digest = hmac_md5_hex( $string, $key );
}
if ($urlHasParams == -1) {
my $qstring = ( split( /\?/, $string ) )[1];
print "curl -s -o /dev/null -v --max-redirs 0 '" . $url_prefix . $url . "?" . $qstring . $digest . "'\n";
}
else {
my $url_noparams = ( split( /\?/, $url ) )[0];
my $qstring = ( split( /\?/, $string ) )[1];
print "curl -s -o /dev/null -v --max-redirs 0 '" . $url_prefix . $url_noparams . "?" . $qstring . $digest . "'\n";
}
sub help {
print "sign.pl - Example signing utility in perl for signed URLs\n";
print "Usage: \n";
print " ./sign.pl --url <value> \\ \n";
print " --useparts <value> \\ \n";
print " --algorithm <value> \\ \n";
print " --duration <value> \\ \n";
print " --keyindex <value> \\ \n";
print " [--client <value>] \\ \n";
print " --key <value> \\ \n";
print " [--verbose] \n";
print "\n";
}
| PSUdaemon/trafficserver | plugins/experimental/url_sig/sign.pl | Perl | apache-2.0 | 3,707 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package database::cassandra::jmx::mode::clientrequestsusage;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'cr', type => 1, cb_prefix_output => 'prefix_cr_output', message_multiple => 'All client requests are ok', skipped_code => { -10 => 1 } },
];
$self->{maps_counters}->{cr} = [
{ label => 'total-latency', nlabel => 'client.request.latency.microsecond', set => {
key_values => [ { name => 'TotalLatency_Count', diff => 1 }, { name => 'display' } ],
output_template => 'Total Latency : %s us',
perfdatas => [
{ label => 'total_latency', value => 'TotalLatency_Count', template => '%s',
min => 0, unit => 'us', label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'timeouts', nlabel => 'client.request.timeout.count', set => {
key_values => [ { name => 'Timeouts_Count', diff => 1 }, { name => 'display' } ],
output_template => 'Timeouts : %s',
perfdatas => [
{ label => 'timeouts', value => 'Timeouts_Count', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'unavailables', nlabel => 'client.request.unavailable.count', set => {
key_values => [ { name => 'Unavailables_Count', diff => 1 }, { name => 'display' } ],
output_template => 'Unavailables : %s',
perfdatas => [
{ label => 'unavailbles', value => 'Unavailables_Count', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'failures', nlabel => 'client.request.failure.count', set => {
key_values => [ { name => 'Failures_Count', diff => 1 }, { name => 'display' } ],
output_template => 'Failures : %s',
perfdatas => [
{ label => 'failures', value => 'Failures_Count', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display' },
],
}
},
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
"filter-name:s" => { name => 'filter_name' },
});
return $self;
}
sub prefix_cr_output {
my ($self, %options) = @_;
return "Client Request '" . $options{instance_value}->{display} . "' ";
}
sub manage_selection {
my ($self, %options) = @_;
$self->{cr} = {};
$self->{request} = [
{ mbean => 'org.apache.cassandra.metrics:name=TotalLatency,scope=*,type=ClientRequest', attributes => [ { name => 'Count' } ] },
{ mbean => 'org.apache.cassandra.metrics:name=Timeouts,scope=*,type=ClientRequest', attributes => [ { name => 'Count' } ] },
{ mbean => 'org.apache.cassandra.metrics:name=Unavailables,scope=*,type=ClientRequest', attributes => [ { name => 'Count' } ] },
{ mbean => 'org.apache.cassandra.metrics:name=Failures,scope=*,type=ClientRequest', attributes => [ { name => 'Count' } ] },
];
my $result = $options{custom}->get_attributes(request => $self->{request}, nothing_quit => 1);
foreach my $mbean (keys %{$result}) {
$mbean =~ /scope=(.*?)(?:,|$)/;
my $scope = $1;
$mbean =~ /name=(.*?)(?:,|$)/;
my $name = $1;
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$scope !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "skipping '" . $scope . "': no matching filter.", debug => 1);
next;
}
$self->{cr}->{$scope} = { display => $scope } if (!defined($self->{cr}->{$scope}));
foreach (keys %{$result->{$mbean}}) {
$self->{cr}->{$scope}->{$name . '_' . $_} = $result->{$mbean}->{$_};
}
}
if (scalar(keys %{$self->{cr}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No client request found.");
$self->{output}->option_exit();
}
$self->{cache_name} = "cassandra_" . $self->{mode} . '_' . md5_hex($options{custom}->get_connection_info()) . '_' .
(defined($self->{option_results}->{filter_name}) ? md5_hex($self->{option_results}->{filter_name}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all'));
}
1;
__END__
=head1 MODE
Check client requests usage.
=over 8
=item B<--filter-counters>
Only display some counters (regexp can be used).
Example: --filter-counters='latency'
=item B<--filter-name>
Filter name (can be a regexp).
=item B<--warning-*> B<--critical-*>
Thresholds.
Can be: 'total-latency', 'timeouts', 'unavailables', 'failures'.
=back
=cut
| Tpo76/centreon-plugins | database/cassandra/jmx/mode/clientrequestsusage.pm | Perl | apache-2.0 | 6,116 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute
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.
=cut
package Bio::EnsEMBL::DBLoader::PipeConfig::LoadDBs_EG_conf;
use strict;
use warnings;
use base qw/Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf/;
use Bio::EnsEMBL::ApiVersion;
sub default_options {
my ($self) = @_;
my $parent_options = $self->SUPER::default_options();
my $options = {
%{$parent_options},
#FTP Settings
ftp_host => 'ftp.ensemblgenomes.org',
ftp_port => 21,
ftp_user => 'anonymous',
ftp_pass => '',
#rsync flag
rsync => 0,
#Location of the MySQL dump, filesystem or ftp url.
# E.g: /nfs/ensemblftp/PRIVATE
# E.g: rsync://ftp.ensembl.org/ensembl/pub
rsync_url => undef,
#Required DBs; leave blank for all DBs
databases => [],
#Mode; sets what we load. Defaults to all but ensembl & mart are available
mode => 'all',
#Set to the actual release or the current which
release => 'current',
#Only required when working with EnsemblGenomes servers
division => '',
#Work directory - location of the files where we can download to
#work_directory => '',
#Set to true if you have already downloaded all the required files via another mechanism
use_existing_files => 0,
#Run pipeline without the grant step. The databases will be loaded but users won't be able to see them.
prerelease => 0,
#Automatically set name
pipeline_name => 'mirror_eg_' .
$self->o('mode') . '_' . $self->o('division') . '_' . $self->o('release'),
#User email
email => $self->o( 'ENV', 'USER' ) . '@ebi.ac.uk',
#Target DB
target_db => { -host => $self->o('target_db_host'),
-port => $self->o('target_db_port'),
-user => $self->o('target_db_user'),
-pass => $self->o('target_db_pass') },
# Meadow type; useful for forcing jobs into a particular meadow
# by default this is LSF
meadow_type => 'LSF',
#Priority listing
priority => { species => [], group => [qw/core variation/], },
#grant users
grant_users => [], };
return $options;
} ## end sub default_options
#1 job - Figure out if we want all DBs or a subset
#5 jobs - Download all required databases & checksum
#Unlimited jobs - Prioritise into super, high & low
#2 jobs - Load DB SQL, Gunzip data & load tables
sub pipeline_analyses {
my ($self) = @_;
return [
{ -meadow_type => $self->o('meadow_type'),
-logic_name => 'find_dbs',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::DatabaseFactory',
-parameters => {databases => $self->o('databases'),
mode => $self->o('mode'),
column_names => ['database'],
fan_branch_code => 2,
randomize => 1,
rsync_url => $self->o('rsync_url'), },
-input_ids => [ {} ],
-flow_into => { '2->A' => [qw/download/],
'A->1' => ['Notify'] }, },
{ -meadow_type => $self->o('meadow_type'),
-logic_name => 'download',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::DownloadDatabase',
-flow_into => { 1 => [qw/prioritise/] },
-rc_name => 'himem',
-parameters => { rsync => $self->o('rsync'),
rsync_url => $self->o('rsync_url') },
-analysis_capacity => 5,
-failed_job_tolerance => 10, },
{
-logic_name => 'prioritise',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::Prioritise',
-parameters => { priority => $self->o('priority') },
-flow_into =>
{ 2 => ['load_files'], 3 => ['high_priority_load_files'], 4 => ['super_priority_load_files'],
5 => ['human_variation_load_files'] } },
{
-meadow_type=> $self->o('meadow_type'),
-logic_name => 'human_variation_load_files',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::LoadFiles',
-parameters => { target_db => $self->o('target_db') },
-failed_job_tolerance => 100,
-can_be_empty => 1,
-hive_capacity => 4,
-priority => 30,
-flow_into => { 1 => {'grant' => { database => '#database#'}} },
},
{
-meadow_type=> $self->o('meadow_type'),
-logic_name => 'super_priority_load_files',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::LoadFiles',
-parameters => { target_db => $self->o('target_db') },
-hive_capacity => 4,
-priority => 20,
-failed_job_tolerance => 100,
-can_be_empty => 1,
-flow_into => { 1 => {'grant' => { database => '#database#'}} },
},
{ -meadow_type => $self->o('meadow_type'),
-logic_name => 'high_priority_load_files',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::LoadFiles',
-parameters => { target_db => $self->o('target_db') },
-hive_capacity => 8,
-priority => 10,
-failed_job_tolerance => 100,
-can_be_empty => 1,
-flow_into =>
{ 1 => { 'grant' => { database => '#database#' } } }, },
{ -meadow_type => $self->o('meadow_type'),
-logic_name => 'load_files',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::LoadFiles',
-parameters => { target_db => $self->o('target_db') },
-hive_capacity => 4,
-max_retry_count => 1,
-failed_job_tolerance => 50,
-can_be_empty => 1,
-flow_into =>
{ 1 => { 'grant' => { database => '#database#' } } }, },
{
-logic_name => 'grant',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::Grant',
-parameters => {
target_db => $self->o('target_db'),
user_submitted_grant_users => $self->o('grant_users'),
},
-max_retry_count => 0,
-can_be_empty => 1, },
####### NOTIFICATION
{
-logic_name => 'Notify',
-module => 'Bio::EnsEMBL::DBLoader::RunnableDB::EmailSummary',
-parameters => {
email => $self->o('email'),
subject => $self->o('pipeline_name').' has finished',
},
},];
} ## end sub pipeline_analyses
sub pipeline_wide_parameters {
my ($self) = @_;
return { %{ $self->SUPER::pipeline_wide_parameters() },
release => $self->o('release'),
division => $self->o('division'),
ftp_host => $self->o('ftp_host'),
ftp_port => $self->o('ftp_port'),
ftp_user => $self->o('ftp_user'),
ftp_pass => $self->o('ftp_pass'),
work_directory => $self->o('work_directory'),
use_existing_files => $self->o('use_existing_files'),
prerelease => $self->o('prerelease'), };
}
sub resource_classes {
my ($self) = @_;
return {
default => { 'LSF' => '-q production-rh74' },
himem =>
{ 'LSF' => '-q production-rh74 -M 16000 -R "rusage[mem=16000]"' }
};
}
1;
| Ensembl/ensembl-database-loader | modules/Bio/EnsEMBL/DBLoader/PipeConfig/LoadDBs_EG_conf.pm | Perl | apache-2.0 | 7,661 |
package Venn::Controller::API::v1::Container;
=head1 NAME
Venn::Controller::API::v1::Container - Container CRUD
=head1 DESCRIPTION
RESTful interface for containers in Venn.
=head1 AUTHOR
Venn Engineering
Josh Arenberg, Norbert Csongradi, Ryan Kupfer, Hai-Long Nguyen
=head1 LICENSE
Copyright 2013,2014,2015 Morgan Stanley
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.
=cut
use v5.14;
use Moose;
use namespace::autoclean;
BEGIN {
extends qw( Venn::Controller::API::v1 );
with qw( Venn::ControllerRole::API::Results );
}
use TryCatch;
use Data::Dumper;
use Venn::Types qw(:all);
## no critic (RequireFinalReturn)
=head1 METHODS
=head2 container_base
Container base.
=cut
sub container_base :Chained('/') PathPart('api/v1/container') CaptureArgs(0) { }
=head2 container_type
Captures container type into the stash
Stashes:
container_type: the container type
source: the C_* class for the container
primary_field: the primary field of the table
display_name: display name for the container
container_rs: container resultset
=cut
sub container_type :Chained('container_base') PathPart('') CaptureArgs(1) {
my ($self, $c, $type) = @_;
my %map = %{Venn::Schema::container_mapping->{$type} || {}};
unless (%map) {
$self->simple_not_found($c, "Container type $type not found") unless %map;
$c->detach();
}
$c->stash->{container_type} = $type;
$c->stash->{source} = $map{source};
$c->stash->{primary_field} = $map{primary_field};
$c->stash->{display_name} = $map{display_name};
$c->stash->{container_rs} = $c->model('VennDB::' . $map{source});
}
=head2 container_known_pk
Captures the known container (its primary_field_value).
Stashes:
primary_field_value: primary field (e.g. the actual cluster_name, dzecl123)
=cut
sub container_known_pk :Chained('container_type') PathPart('') CaptureArgs(1) {
my ($self, $c, $pk) = @_;
$c->stash->{primary_field_value} = $pk;
}
=head2 get_all_types
REST GET /container
GET all containers
response 200 : (Array[Container]) list of types of containers
schema Container: {
"required": ["api_name", "columns", "primary_field", "class", "display_name"],
"properties": {
"api_name": { "type": "string", "description": "name of container", "example": "host" },
"columns": { "$ref": "#/definitions/ContainerColumn", "description": "data columns example" },
"primary_field": { "type": "string", "description": "primary key column", "example": "hostname" },
"class": { "type": "string", "description": "internal database table class", "example": "C_Host" },
"display_name": { "type": "string", "description": "display name for UI", "example": "Hosts" }
}
}
schema ContainerColumn: {
"properties": {
"hostname": { "$ref": "#/definitions/ContainerColumnHostname" },
"rack_name": { "$ref": "#/definitions/ContainerColumnRackname" }
}
}
schema ContainerColumnHostname: {
"properties": {
"data_type": { "type": "string", "description": "database data type", "example": "varchar" },
"is_foreign_key": { "type": "boolean", "description": "is it a foreign key", "example": "1" },
"is_nullable": { "type": "boolean", "description": "could it be null value", "example": "0" },
"display_name": { "type": "string", "description": "display name for UI", "example": "Host" },
"validate_error": { "type": "string", "description": "error message for failed validation", "example": "Host does not exist" },
"validate": { "type": "string", "description": "validator function reference", "example": "CODE" },
"size": { "type": "string", "description": "database data type size", "example": 64 }
}
}
schema ContainerColumnRackname: {
"properties": {
"data_type": { "type": "string", "description": "database data type", "example": "varchar" },
"is_foreign_key": { "type": "boolean", "description": "is it a foreign key", "example": "1" },
"is_nullable": { "type": "boolean", "description": "could it be null value", "example": "0" },
"display_name": { "type": "string", "description": "display name for UI", "example": "Rack" },
"validate_error": { "type": "string", "description": "error message for failed validation", "example": "Rack does not exist" },
"validate": { "type": "string", "description": "validator function reference", "example": "CODE" },
"size": { "type": "string", "description": "database data type size", "example": 64 }
}
}
=cut
sub get_all_types :GET Chained('container_base') PathPart('') Args(0) Does(Auth) AuthRole(ro-action) {
my ($self, $c) = @_;
try {
return $self->simple_ok_with_result($c, $self->serialize_types($c, 'C'));
}
catch (VennException $ex) {
return $self->simple_bad_request($c, $ex->as_string_no_trace);
}
catch ($err) {
return $self->simple_internal_server_error($c, $err);
}
}
=head2 get_all_of_type
REST GET /container/$type
GET all containers of a type
param $type : (Str) [required] type of container
response 200 : (Array[Container]) list of containers of type $type
=cut
sub get_all_of_type :GET Chained('container_type') PathPart('') Args(0) Does(Auth) AuthRole(ro-action) {
my ($self, $c) = @_;
try {
my @rows = $c->stash->{container_rs}->search()->as_hash->all;
return $self->simple_ok_with_result($c, \@rows);
}
catch (VennException $err) {
return $self->simple_internal_server_error($c, "Venn error getting container data: " . $err->as_string_no_trace);
}
catch (DBIxException $err) {
return $self->simple_bad_request($c, "Database Error: $err");
}
catch ($err) {
return $self->simple_internal_server_error($c, $err);
}
}
=head2 get_container
REST GET /container/$type/$name
GET an container of type $type and name $name
param $type : (Str) [required] type of container
param $name : (Str) [required] name of container
response 200 : (Array[Container]) container of type and name
=cut
sub get_container :GET Chained('container_known_pk') PathPart('') Args(0) Does(Auth) AuthRole(ro-action) {
my ($self, $c) = @_;
try {
my $row = $c->stash->{container_rs}->search({
$c->stash->{primary_field} => $c->stash->{primary_field_value},
})->as_hash->first;
if ($row) {
return $self->simple_ok_with_result($c, $row);
}
else {
return $self->simple_not_found($c, "Container %s/%s not found", $c->stash->{container_type},
$c->{stash}->{primary_field_value});
}
}
catch (VennException $err) {
return $self->simple_internal_server_error($c, "Venn error getting container data: " . $err->as_string_no_trace);
}
catch (DBIxException $err) {
return $self->simple_bad_request($c, "Database Error: $err");
}
catch ($err) {
return $self->simple_internal_server_error($c, $err);
}
}
=head2 put_container
REST PUT /container/$type/$name
Creates a new or updates an existing container.
param $type : (Str) [required] type of container
param $name : (Str) [required] name of container
body : (Container) [required] container definition
response 201 : (Container) container created/updated
=cut
sub put_container :PUT Chained('container_known_pk') PathPart('') Args(0) Does(Auth) AuthRole(dev-action) {
my ($self, $c) = @_;
$c->req->data->{$c->stash->{primary_field}} = $c->stash->{primary_field_value};
try {
my $container_row = $c->stash->{container_rs}->find($c->stash->{primary_field_value});
if ($container_row) {
# update
$c->log->info("Update operation");
$container_row->update($c->req->data) if %{$c->req->data};
} else {
# create
$c->log->info("Create operation");
$c->stash->{container_rs}->create($c->req->data);
}
my $final_result = $c->stash->{container_rs}->search($c->stash->{primary_field_value})->as_hash->first;
return $self->simple_created($c, $final_result);
}
catch (VennException $err) {
return $self->simple_internal_server_error($c, "Venn error creating/updating container: " . $err->as_string_no_trace);
}
catch (DBIxException $err) {
return $self->simple_bad_request($c, "Database Error: " . $err);
}
catch ($err) {
return $self->simple_internal_server_error($c, "Error creating/updating container: $err");
}
}
=head2 delete_container
REST DELETE /container/$container_type/$primary_field_value
Deletes an container.
param $container_type : (String) container type
param $primary_field_value : (String) container primary field
response 200 : Deleted
=cut
sub delete_container :DELETE Chained('container_known_pk') PathPart('') Args(0) Does(Auth) AuthRole(dev-action) {
my ($self, $c) = @_;
try {
my $container_row = $c->stash->{container_rs}->find($c->stash->{primary_field_value});
if ($container_row) {
$container_row->delete();
return $self->simple_ok_without_result($c, "%s deleted.", $c->stash->{primary_field_value});
}
else {
return $self->simple_not_found($c, "%s not found.", $c->stash->{primary_field_value});
}
}
catch (VennException $err) {
return $self->simple_internal_server_error($c, "Venn error deleting container: " . $err->as_string_no_trace);
}
catch (DBIxException $err) {
return $self->simple_bad_request($c, "Database Error: " . $err);
}
catch ($err) {
return $self->simple_internal_server_error($c, "Error deleting container: $err");
}
}
## use critic
__PACKAGE__->meta->make_immutable;
| Morgan-Stanley/venn-core | lib/Venn/Controller/API/v1/Container.pm | Perl | apache-2.0 | 10,514 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute
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.
=cut
package Bio::EnsEMBL::Compara::RunnableDB::Families::MafftAfamily;
use strict;
use warnings;
use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor;
use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');
sub param_defaults {
return {
# --anysymbol helps when Uniprot sequence contains 'U' or other funny aminoacid codes
# --thread 1 is supposed to prevent forking
'mafft_cmdline_args' => '--anysymbol --thread #mafft_threads#',
'mafft_exec' => '#mafft_root_dir#/bin/mafft',
'mafft_threads' => 1,
};
}
sub fetch_input {
my $self = shift @_;
my $family_id = $self->param_required('family_id');
my $family = $self->compara_dba()->get_FamilyAdaptor()->fetch_by_dbID($family_id)
|| die "family $family_id could not have been fetched by the adaptor";
$self->param('family', $family); # save it for the future
my $aln;
eval {$aln = $family->get_SimpleAlign};
unless ($@) {
if(defined(my $flush = $aln->is_flush)) { # looks like this family is already aligned
return;
}
}
# otherwise prepare the files and perform the actual mafft run:
my $worker_temp_directory = $self->worker_temp_directory;
my $pep_file = $worker_temp_directory . "family_${family_id}.fa";
my $mafft_file = $worker_temp_directory . "family_${family_id}.mafft";
my $pep_counter = $family->print_sequences_to_file( $pep_file, -format => 'fasta' );
if ($pep_counter == 0) {
unlink $pep_file;
die "family $family_id does not seem to contain any members";
} elsif ($pep_counter == 1) {
unlink $pep_file;
my $member = $family->get_all_Members()->[0];
my $cigar_line = length($member->sequence).'M';
eval {$member->cigar_line($cigar_line) };
if($@) {
die "could not set the cigar_line for singleton family $family_id, because: $@ ";
}
# by setting this parameter we will trigger the update in write_output()
$self->param('singleton_relation', $member);
return;
} elsif ($pep_counter>=20000) {
my $mafft_cmdline_args = $self->param('mafft_cmdline_args') || '';
$self->param('mafft_cmdline_args', $mafft_cmdline_args.' --parttree' );
}
# if these two parameters are set, run() will need to actually execute mafft
$self->param('pep_file', $pep_file);
$self->param('mafft_file', $mafft_file);
}
sub run {
my $self = shift @_;
my $family_id = $self->param('family_id');
my $mafft_root_dir = $self->param_required('mafft_root_dir');
my $mafft_executable = $self->param_required('mafft_exec');
my $mafft_cmdline_args = $self->param('mafft_cmdline_args') || '';
my $pep_file = $self->param('pep_file') or return; # if we have no more work to do just exit gracefully
my $mafft_file = $self->param('mafft_file');
my $cmd_line = "$mafft_executable $mafft_cmdline_args $pep_file > $mafft_file";
if($self->debug) {
warn "About to execute: $cmd_line\n";
}
$self->dbc->disconnect_if_idle();
if(system($cmd_line)) {
# Possibly an ongoing MEMLIMIT
# Let's wait a bit to let LSF kill the worker as it should
sleep(30);
#
die "running mafft on family $family_id failed, because: $! ";
} elsif(-z $mafft_file) {
die "running mafft on family $family_id produced zero-length output";
}
# the file(s) will be removed on success and should stay undeleted on failure
unless($self->debug) {
unlink $pep_file;
}
}
sub write_output {
my $self = shift @_;
if($self->param('singleton_relation')) {
$self->compara_dba()->get_FamilyAdaptor()->update($self->param('family'), 1);
} elsif(my $mafft_file = $self->param('mafft_file')) {
my $family = $self->param('family');
$family->load_cigars_from_file($mafft_file, -format => 'fasta', -CHECK_SEQ => 1);
$family->adaptor->update($family, 1);
unless($self->debug) {
unlink $mafft_file;
}
} # otherwise we had no work to do and no files to remove
}
1;
| danstaines/ensembl-compara | modules/Bio/EnsEMBL/Compara/RunnableDB/Families/MafftAfamily.pm | Perl | apache-2.0 | 4,983 |
package Google::Ads::AdWords::v201809::FunctionParsingError;
use strict;
use warnings;
__PACKAGE__->_set_element_form_qualified(1);
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' };
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use base qw(Google::Ads::AdWords::v201809::ApiError);
# Variety: sequence
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %fieldPath_of :ATTR(:get<fieldPath>);
my %fieldPathElements_of :ATTR(:get<fieldPathElements>);
my %trigger_of :ATTR(:get<trigger>);
my %errorString_of :ATTR(:get<errorString>);
my %ApiError__Type_of :ATTR(:get<ApiError__Type>);
my %reason_of :ATTR(:get<reason>);
my %offendingText_of :ATTR(:get<offendingText>);
my %offendingTextIndex_of :ATTR(:get<offendingTextIndex>);
__PACKAGE__->_factory(
[ qw( fieldPath
fieldPathElements
trigger
errorString
ApiError__Type
reason
offendingText
offendingTextIndex
) ],
{
'fieldPath' => \%fieldPath_of,
'fieldPathElements' => \%fieldPathElements_of,
'trigger' => \%trigger_of,
'errorString' => \%errorString_of,
'ApiError__Type' => \%ApiError__Type_of,
'reason' => \%reason_of,
'offendingText' => \%offendingText_of,
'offendingTextIndex' => \%offendingTextIndex_of,
},
{
'fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'fieldPathElements' => 'Google::Ads::AdWords::v201809::FieldPathElement',
'trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'ApiError__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'reason' => 'Google::Ads::AdWords::v201809::FunctionParsingError::Reason',
'offendingText' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
'offendingTextIndex' => 'SOAP::WSDL::XSD::Typelib::Builtin::int',
},
{
'fieldPath' => 'fieldPath',
'fieldPathElements' => 'fieldPathElements',
'trigger' => 'trigger',
'errorString' => 'errorString',
'ApiError__Type' => 'ApiError.Type',
'reason' => 'reason',
'offendingText' => 'offendingText',
'offendingTextIndex' => 'offendingTextIndex',
}
);
} # end BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201809::FunctionParsingError
=head1 DESCRIPTION
Perl data type class for the XML Schema defined complexType
FunctionParsingError from the namespace https://adwords.google.com/api/adwords/cm/v201809.
An error resulting from a failure to parse the textual representation of a function.
=head2 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=item * reason
=item * offendingText
=item * offendingTextIndex
=back
=head1 METHODS
=head2 new
Constructor. The following data structure may be passed to new():
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| googleads/googleads-perl-lib | lib/Google/Ads/AdWords/v201809/FunctionParsingError.pm | Perl | apache-2.0 | 3,138 |
package VMOMI::FileTooLarge;
use parent 'VMOMI::FileFault';
use strict;
use warnings;
our @class_ancestors = (
'FileFault',
'VimFault',
'MethodFault',
);
our @class_members = (
['datastore', undef, 0, ],
['fileSize', undef, 0, ],
['maxFileSize', undef, 0, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/FileTooLarge.pm | Perl | apache-2.0 | 509 |
%%---------------------------------------------------------------------
%%
%% SHAPE CLASS
%%
%%---------------------------------------------------------------------
:- module(shape_class_doc,[],[objects,assertions,isomodes,regtypes]).
:- use_module(library('tcltk_obj/canvas_class')).
:- comment(hide,'class$call'/3).
:- comment(hide,'class$used'/2).
%%---------------------------------------------------------------------
%% COLOR
%%---------------------------------------------------------------------
tcl_color(black). % default color.
:- export(set_bg_color/1).
%%---------------------------------------------------------------------
:- pred set_bg_color(+Color) :: atom
# "@var{Color} specifies the color to use for drawing the
shape's outline. This option defaults to
black. If color is not specified then no outline is drawn for the shape.".
%%---------------------------------------------------------------------
set_bg_color(Color) :-
atom(Color),
retract_fact(tcl_color(_)),
asserta_fact(tcl_color(Color)),
notify_changes.
:- export(get_color/1).
%%---------------------------------------------------------------------
:- pred get_color(-Background) :: atom
# "Gets the shape @var{Background Color}.".
%%---------------------------------------------------------------------
get_color(Background) :-
!,
tcl_color(Background).
%:- export(set_fg_color/1).
%set_fg_color(Color) :-
% atom(Color),
% retract_fact(tcl_color(_,BG)),
% asserta_fact(tcl_color(Color,BG)),
% notify_changes.
%%---------------------------------------------------------------------
%% BORDER WIDTH
%%---------------------------------------------------------------------
border(1).
:- export(set_border_width/1).
%%---------------------------------------------------------------------
:- pred set_border_width(+Width) :: num
# "Specifies the @var{Width} borderthat the canvas widget should request from its geometry manager.".
%%---------------------------------------------------------------------
set_border_width(Border) :-
number(Border),
Border > 0,
set_fact(border(Border)),
notify_changes.
:- export(get_border_width/1).
%%---------------------------------------------------------------------
:- pred get_border_width(-Width) :: num
# "Gets the @var{Width} border of the canvas widget.".
%%---------------------------------------------------------------------
get_border_width(Border) :-
border(Border).
%%---------------------------------------------------------------------
%% IMPLEMENTATION
%%---------------------------------------------------------------------
:- export([tcl_name/1,creation_options/1]).
:- comment(hide,'tcl_name'/1).
tcl_name(_) :- fail.
%%---------------------------------------------------------------------
:- pred creation_options(-OptionsList) :: list
# "Creates a list with the options supported by the shapes.".
%%---------------------------------------------------------------------
%creation_options([min(fill),BG,min(outline),FG,min(width),B]) :-
creation_options([min(fill),BG,min(width),B]) :-
tcl_color(BG),
border(B).
notify_changes:-
self(Shape),
owner(AnOwner),
AnOwner instance_of canvas_class,
AnOwner:shape_changed(Shape),
fail.
notify_changes.
:- export([add_owner/1,remove_owner/1]).
:- comment(hide,'add_owner'/1).
:- comment(hide,'remove_owner'/1).
add_owner(Owner) :-
\+ owner(Owner),
Owner instance_of canvas_class,
assertz_fact(owner(Owner)),
self(Shape),
Owner:add_shape(Shape),
!.
add_owner(_).
remove_owner(Owner) :-
retract_fact(owner(Owner)),
Owner instance_of canvas_class,
self(Shape),
Owner:remove_shape(Shape),
!.
remove_owner(_).
%%---------------------------------------------------------------------
%% CONSTRUCTOR/DESTRUCTOR
%%---------------------------------------------------------------------
:- set_prolog_flag(multi_arity_warnings,off).
%%------------------------------------------------------------------------
:- export(shape_class/0).
:- pred shape_class :: list
#" Creates a new shape object.".
:- export(shape_class/1).
:- pred shape_class(+ShapeList) :: list
# "Adds shapes of the list to the canvas object.".
%%------------------------------------------------------------------------
shape_class. % Not owned
shape_class([]) :- !.
shape_class([AnOwner|Next]) :-
add_owner(AnOwner),
!,
shape_class(Next).
shape_class(AnOwner) :-
!,
add_owner(AnOwner).
:- set_prolog_flag(multi_arity_warnings,on).
destructor :-
self(Shape),
retract_fact(owner(AnOwner)),
AnOwner instance_of canvas_class, % Owner is still alive
AnOwner:remove_shape(Shape),
fail.
| leuschel/ecce | www/CiaoDE/ciao/library/tcltk_obj/Back/shape_class_doc.pl | Perl | apache-2.0 | 4,984 |
package VMOMI::EntityBackupConfig;
use parent 'VMOMI::DynamicData';
use strict;
use warnings;
our @class_ancestors = (
'DynamicData',
);
our @class_members = (
['entityType', undef, 0, ],
['configBlob', undef, 0, ],
['key', undef, 0, 1],
['name', undef, 0, 1],
['container', 'ManagedObjectReference', 0, 1],
['configVersion', undef, 0, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/EntityBackupConfig.pm | Perl | apache-2.0 | 593 |
package PerlSys::Version;
use strict;
use warnings;
use autodie;
use Config;
use Exporter "import";
our @EXPORT_OK = qw/
format_apiver
current_apiver
/;
our %EXPORT_TAGS = (all => \@EXPORT_OK);
sub format_apiver {
my ($rev, $ver, $sub) = @_;
my $str = sprintf "v%d.%d", $rev, $ver;
$str .= ".$sub" if $ver % 2 != 0;
return $str;
}
sub current_apiver {
return format_apiver(@Config::Config{qw/
api_revision
api_version
api_subversion
/});
}
1;
| vickenty/perl-sys | build/lib/PerlSys/Version.pm | Perl | bsd-2-clause | 505 |
#!/bin/env perl
use Pessoa;
my $pessoa = Pessoa->new (
pre => "Albert", nome => "Einstein",
ocup => "Físico", pais => "Alemanha");
do {
my $outra = Pessoa->new ();
$outra->pre("José");
$outra->nome("Leite Lopes");
$outra->ocup("Físico");
$outra->pais("Brasil");
};
my $outra = Pessoa->new ();
$outra->pre("Cesar");
$outra->nome("Lattes");
$outra->ocup("Físico");
$outra->pais("Brasil");
print "Quantos: ", Pessoa->quantos, "\nQuais:\n";
foreach my $p (Pessoa->todos)
{
print "- ", $p->completo, "\n";
}
| vinnix/PerlLab | Day03/pessoa.pl | Perl | bsd-2-clause | 521 |
% ask_for_file(-File)
% File unifies with stdin
ask_for_file(File) :- print('Write file name containig sudoku: '), read_token(File).
% ask_for_method(-Method)
% Method unifies with stdin
ask_for_method(Method) :- print('Write solving method name (neighbours, relatives, adhoc): '), read_token(Method).
% getopt(-File, -Method)
% tries to read commandline arguments
% if none provided, asks user to specify file containing sudoku data
% if provided, first parameter is used
% this procedure outputs file name for sudoku data file
getopt(File, Method) :- argument_counter(1), ask_for_file(File), ask_for_method(Method).
getopt(File, Method) :- argument_counter(2), argument_value(1, File), ask_for_method(Method).
getopt(File, Method) :- argument_counter(3), argument_value(1, File), argument_value(2, Method).
% valid_method(+Method)
% used for checking of availability of user-chosen Method
valid_method(string(neighbours)).
valid_method(string(relatives)).
valid_method(string(adhoc)).
valid_method(Method) :-
string(RawMethod) = Method,
format('ERROR: invalid method name "%s"~n', [RawMethod]),
fail.
% open_file(+File)
% opens File and uses it as stdin
% TODO - save error to variable and make recovery procedure with pattern matching
open_file(File) :-
string(RawFile) = File,
catch(
open(RawFile, read, Stream),
_,
format('Error opening file %s', [File])
),
set_input(Stream).
% parse_numbers(+M, +N, ?Position, +List, -Result)
% reads stdin for terms
% for each term based on position computes its XY coordinates
% uses accumulator technique
parse_numbers(M, N, Position, List, Result) :-
read(Number),
(Number = end_of_file, Result = List ;
X is Position mod (M * N),
Y is Position div (M * N),
NewList = [ [X, Y, Number] | List ],
NextPosition is Position + 1,
parse_numbers(M, N, NextPosition, NewList, Result)).
% parse_dimension(-M, -N)
% reads two integers from stdin and returns both
parse_dimension(M, N) :-
read(M),
read(N).
% parse_sudoku(-Sudoku)
% utilizes previous procedures
% sudoku is stored in sudoku/3 predicate
% first two are dimensions of the sudoku
% third argument is list of lists, called fields
% a field is a list of length 3
% first element is X coordinate
% second element is Y coordinate
% third element is value of the field
parse_sudoku(Sudoku) :-
parse_dimension(M, N),
parse_numbers(M, N, 0, [], Numbers),
Sudoku = sudoku(M, N, Numbers), !.
| lovasko/NoveZamky | src/io.pl | Perl | bsd-2-clause | 2,433 |
require Process;
$EXEPREFIX = ".".$DIR_SEPARATOR;
$TARGETHOSTNAME = "localhost";
package ACE;
sub CheckForExeDir
{
for($i = 0; $i <= $#ARGV; $i++) {
if ($ARGV[$i] eq '-ExeSubDir') {
if (defined $ARGV[$i + 1]) {
$::EXEPREFIX = $ARGV[$i + 1].$::DIR_SEPARATOR;
}
else {
print STDERR "You must pass a directory with ExeSubDir\n";
exit(1);
}
splice(@ARGV, $i, 2);
}
}
}
### Check and remove, but don't actually use
sub CheckForConfig
{
for($i = 0; $i <= $#ARGV;) {
if ($ARGV[$i] eq '-Config') {
if (!defined $ARGV[$i + 1]) {
print STDERR "You must pass a configuration with Config\n";
exit(1);
}
splice(@ARGV, $i, 2);
} else {
$i++;
}
}
}
sub checkForTarget
{
my($cwd) = shift;
for($i = 0; $i <= $#ARGV; $i++) {
if ($ARGV[$i] eq '-chorus') {
if (defined $ARGV[$i + 1]) {
$::TARGETHOSTNAME = $ARGV[$i + 1];
$::EXEPREFIX = "rsh $::TARGETHOSTNAME arun $cwd$::DIR_SEPARATOR";
}
else {
print STDERR "The -chorus option requires " .
"the hostname of the target\n";
exit(1);
}
splice(@ARGV, $i, 2);
# Don't break from the loop just in case there
# is an accidental duplication of the -chorus option
}
}
}
# Returns a unique id, uid for unix, last digit of IP for NT
sub uniqueid
{
if ($^O eq "MSWin32")
{
my $uid = 1;
open (IPNUM, "ipconfig|") || die "Can't run ipconfig: $!\n";
while (<IPNUM>)
{
if (/Address/)
{
$uid = (split (/: (\d+)\.(\d+)\.(\d+)\.(\d+)/))[4];
}
}
close IPNUM;
return $uid;
}
else
{
return getpwnam (getlogin ());
}
}
# Waits until a file exists
sub waitforfile
{
local($file) = @_;
sleep 1 while (!(-e $file && -s $file));
}
sub waitforfile_timed
{
my $file = shift;
my $maxtime = shift;
while ($maxtime-- != 0) {
if (-e $file && -s $file) {
return 0;
}
sleep 1;
}
return -1;
}
$sleeptime = 5;
CheckForExeDir ();
CheckForConfig ();
1;
| wfnex/openbras | src/ace/ACE_wrappers/bin/ACEutils.pm | Perl | bsd-3-clause | 2,097 |
#ExStart:1
use lib 'lib';
use strict;
use warnings;
use utf8;
use File::Slurp; # From CPAN
use JSON;
use AsposeStorageCloud::StorageApi;
use AsposeStorageCloud::ApiClient;
use AsposeStorageCloud::Configuration;
use AsposeTasksCloud::TasksApi;
use AsposeTasksCloud::ApiClient;
use AsposeTasksCloud::Configuration;
use AsposeTasksCloud::Object::Calendar;
my $configFile = '../config/config.json';
my $configPropsText = read_file($configFile);
my $configProps = decode_json($configPropsText);
my $data_path = '../../../Data/';
my $out_path = $configProps->{'out_folder'};
$AsposeTasksCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeTasksCloud::Configuration::api_key = $configProps->{'api_key'};
$AsposeTasksCloud::Configuration::debug = 1;
$AsposeStorageCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeStorageCloud::Configuration::api_key = $configProps->{'api_key'};
# Instantiate Aspose.Storage and Aspose.Tasks API SDK
my $storageApi = AsposeStorageCloud::StorageApi->new();
my $tasksApi = AsposeTasksCloud::TasksApi->new();
# Set input file name
my $name = 'sample-project-2.mpp';
# Upload file to aspose cloud storage
my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name);
# Invoke Aspose.Tasks Cloud SDK API to recalculate project resource fields
$response = $tasksApi->PutRecalculateProjectResourceFields(name => $name);
if($response->{'Status'} eq 'OK'){
print "\n Recalculate project resource fields, Done!";
}
#ExEnd:1 | aspose-tasks/Aspose.Tasks-for-Cloud | Examples/Perl/Tasks/RecalculateProjectResourceFields.pl | Perl | mit | 1,542 |
###########################################################################
#
# This file is partially auto-generated by the DateTime::Locale generator
# tools (v0.10). This code generator comes with the DateTime::Locale
# distribution in the tools/ directory, and is called generate-modules.
#
# This file was generated from the CLDR JSON locale data. See the LICENSE.cldr
# file included in this distribution for license details.
#
# Do not edit this file directly unless you are sure the part you are editing
# is not created by the generator.
#
###########################################################################
=pod
=encoding UTF-8
=head1 NAME
DateTime::Locale::ps - Locale data examples for the ps locale.
=head1 DESCRIPTION
This pod file contains examples of the locale data available for the
Pashto locale.
=head2 Days
=head3 Wide (format)
دوشنبه
سهشنبه
چهارشنبه
پنجشنبه
جمعه
شنبه
یکشنبه
=head3 Abbreviated (format)
دوشنبه
سهشنبه
چهارشنبه
پنجشنبه
جمعه
شنبه
یکشنبه
=head3 Narrow (format)
M
T
W
T
F
S
S
=head3 Wide (stand-alone)
دوشنبه
سهشنبه
چهارشنبه
پنجشنبه
جمعه
شنبه
یکشنبه
=head3 Abbreviated (stand-alone)
دوشنبه
سهشنبه
چهارشنبه
پنجشنبه
جمعه
شنبه
یکشنبه
=head3 Narrow (stand-alone)
M
T
W
T
F
S
S
=head2 Months
=head3 Wide (format)
جنوري
فبروري
مارچ
اپریل
می
جون
جولای
اګست
سپتمبر
اکتوبر
نومبر
دسمبر
=head3 Abbreviated (format)
جنوري
فبروري
مارچ
اپریل
می
جون
جولای
اګست
سپتمبر
اکتوبر
نومبر
دسمبر
=head3 Narrow (format)
1
2
3
4
5
6
7
8
9
10
11
12
=head3 Wide (stand-alone)
جنوري
فبروري
مارچ
اپریل
می
جون
جولای
اګست
سپتمبر
اکتوبر
نومبر
دسمبر
=head3 Abbreviated (stand-alone)
جنوري
فبروري
مارچ
اپریل
می
جون
جولای
اګست
سپتمبر
اکتوبر
نومبر
دسمبر
=head3 Narrow (stand-alone)
1
2
3
4
5
6
7
8
9
10
11
12
=head2 Quarters
=head3 Wide (format)
Q1
Q2
Q3
Q4
=head3 Abbreviated (format)
Q1
Q2
Q3
Q4
=head3 Narrow (format)
1
2
3
4
=head3 Wide (stand-alone)
Q1
Q2
Q3
Q4
=head3 Abbreviated (stand-alone)
Q1
Q2
Q3
Q4
=head3 Narrow (stand-alone)
1
2
3
4
=head2 Eras
=head3 Wide (format)
ق.م.
م.
=head3 Abbreviated (format)
ق.م.
م.
=head3 Narrow (format)
ق.م.
م.
=head2 Date Formats
=head3 Full
2008-02-05T18:30:30 = سهشنبه د 2008 د فبروري 5
1995-12-22T09:05:02 = جمعه د 1995 د دسمبر 22
-0010-09-15T04:44:23 = شنبه د -10 د سپتمبر 15
=head3 Long
2008-02-05T18:30:30 = د 2008 د فبروري 5
1995-12-22T09:05:02 = د 1995 د دسمبر 22
-0010-09-15T04:44:23 = د -10 د سپتمبر 15
=head3 Medium
2008-02-05T18:30:30 = 5 فبروري 2008
1995-12-22T09:05:02 = 22 دسمبر 1995
-0010-09-15T04:44:23 = 15 سپتمبر -10
=head3 Short
2008-02-05T18:30:30 = 2008/2/5
1995-12-22T09:05:02 = 1995/12/22
-0010-09-15T04:44:23 = -10/9/15
=head2 Time Formats
=head3 Full
2008-02-05T18:30:30 = 18:30:30 (UTC)
1995-12-22T09:05:02 = 9:05:02 (UTC)
-0010-09-15T04:44:23 = 4:44:23 (UTC)
=head3 Long
2008-02-05T18:30:30 = 18:30:30 (UTC)
1995-12-22T09:05:02 = 9:05:02 (UTC)
-0010-09-15T04:44:23 = 4:44:23 (UTC)
=head3 Medium
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 9:05:02
-0010-09-15T04:44:23 = 4:44:23
=head3 Short
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 9:05
-0010-09-15T04:44:23 = 4:44
=head2 Datetime Formats
=head3 Full
2008-02-05T18:30:30 = سهشنبه د 2008 د فبروري 5 18:30:30 (UTC)
1995-12-22T09:05:02 = جمعه د 1995 د دسمبر 22 9:05:02 (UTC)
-0010-09-15T04:44:23 = شنبه د -10 د سپتمبر 15 4:44:23 (UTC)
=head3 Long
2008-02-05T18:30:30 = د 2008 د فبروري 5 18:30:30 (UTC)
1995-12-22T09:05:02 = د 1995 د دسمبر 22 9:05:02 (UTC)
-0010-09-15T04:44:23 = د -10 د سپتمبر 15 4:44:23 (UTC)
=head3 Medium
2008-02-05T18:30:30 = 5 فبروري 2008 18:30:30
1995-12-22T09:05:02 = 22 دسمبر 1995 9:05:02
-0010-09-15T04:44:23 = 15 سپتمبر -10 4:44:23
=head3 Short
2008-02-05T18:30:30 = 2008/2/5 18:30
1995-12-22T09:05:02 = 1995/12/22 9:05
-0010-09-15T04:44:23 = -10/9/15 4:44
=head2 Available Formats
=head3 E (ccc)
2008-02-05T18:30:30 = سهشنبه
1995-12-22T09:05:02 = جمعه
-0010-09-15T04:44:23 = شنبه
=head3 EHm (E HH:mm)
2008-02-05T18:30:30 = سهشنبه 18:30
1995-12-22T09:05:02 = جمعه 09:05
-0010-09-15T04:44:23 = شنبه 04:44
=head3 EHms (E HH:mm:ss)
2008-02-05T18:30:30 = سهشنبه 18:30:30
1995-12-22T09:05:02 = جمعه 09:05:02
-0010-09-15T04:44:23 = شنبه 04:44:23
=head3 Ed (d, E)
2008-02-05T18:30:30 = 5, سهشنبه
1995-12-22T09:05:02 = 22, جمعه
-0010-09-15T04:44:23 = 15, شنبه
=head3 Ehm (E h:mm a)
2008-02-05T18:30:30 = سهشنبه 6:30 PM
1995-12-22T09:05:02 = جمعه 9:05 AM
-0010-09-15T04:44:23 = شنبه 4:44 AM
=head3 Ehms (E h:mm:ss a)
2008-02-05T18:30:30 = سهشنبه 6:30:30 PM
1995-12-22T09:05:02 = جمعه 9:05:02 AM
-0010-09-15T04:44:23 = شنبه 4:44:23 AM
=head3 Gy (G y)
2008-02-05T18:30:30 = م. 2008
1995-12-22T09:05:02 = م. 1995
-0010-09-15T04:44:23 = ق.م. -10
=head3 GyMMM (G y MMM)
2008-02-05T18:30:30 = م. 2008 فبروري
1995-12-22T09:05:02 = م. 1995 دسمبر
-0010-09-15T04:44:23 = ق.م. -10 سپتمبر
=head3 GyMMMEd (G y MMM d, E)
2008-02-05T18:30:30 = م. 2008 فبروري 5, سهشنبه
1995-12-22T09:05:02 = م. 1995 دسمبر 22, جمعه
-0010-09-15T04:44:23 = ق.م. -10 سپتمبر 15, شنبه
=head3 GyMMMd (G y MMM d)
2008-02-05T18:30:30 = م. 2008 فبروري 5
1995-12-22T09:05:02 = م. 1995 دسمبر 22
-0010-09-15T04:44:23 = ق.م. -10 سپتمبر 15
=head3 H (H)
2008-02-05T18:30:30 = 18
1995-12-22T09:05:02 = 9
-0010-09-15T04:44:23 = 4
=head3 Hm (H:mm)
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 9:05
-0010-09-15T04:44:23 = 4:44
=head3 Hms (H:mm:ss)
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 9:05:02
-0010-09-15T04:44:23 = 4:44:23
=head3 Hmsv (HH:mm:ss v)
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Hmv (HH:mm v)
2008-02-05T18:30:30 = 18:30 UTC
1995-12-22T09:05:02 = 09:05 UTC
-0010-09-15T04:44:23 = 04:44 UTC
=head3 M (L)
2008-02-05T18:30:30 = 2
1995-12-22T09:05:02 = 12
-0010-09-15T04:44:23 = 9
=head3 MEd (MM-dd, E)
2008-02-05T18:30:30 = 02-05, سهشنبه
1995-12-22T09:05:02 = 12-22, جمعه
-0010-09-15T04:44:23 = 09-15, شنبه
=head3 MMM (LLL)
2008-02-05T18:30:30 = فبروري
1995-12-22T09:05:02 = دسمبر
-0010-09-15T04:44:23 = سپتمبر
=head3 MMMEd (MMM d, E)
2008-02-05T18:30:30 = فبروري 5, سهشنبه
1995-12-22T09:05:02 = دسمبر 22, جمعه
-0010-09-15T04:44:23 = سپتمبر 15, شنبه
=head3 MMMMd (MMMM d)
2008-02-05T18:30:30 = فبروري 5
1995-12-22T09:05:02 = دسمبر 22
-0010-09-15T04:44:23 = سپتمبر 15
=head3 MMMd (MMM d)
2008-02-05T18:30:30 = فبروري 5
1995-12-22T09:05:02 = دسمبر 22
-0010-09-15T04:44:23 = سپتمبر 15
=head3 Md (MM-dd)
2008-02-05T18:30:30 = 02-05
1995-12-22T09:05:02 = 12-22
-0010-09-15T04:44:23 = 09-15
=head3 d (d)
2008-02-05T18:30:30 = 5
1995-12-22T09:05:02 = 22
-0010-09-15T04:44:23 = 15
=head3 h (h a)
2008-02-05T18:30:30 = 6 PM
1995-12-22T09:05:02 = 9 AM
-0010-09-15T04:44:23 = 4 AM
=head3 hm (h:mm a)
2008-02-05T18:30:30 = 6:30 PM
1995-12-22T09:05:02 = 9:05 AM
-0010-09-15T04:44:23 = 4:44 AM
=head3 hms (h:mm:ss a)
2008-02-05T18:30:30 = 6:30:30 PM
1995-12-22T09:05:02 = 9:05:02 AM
-0010-09-15T04:44:23 = 4:44:23 AM
=head3 hmsv (h:mm:ss a v)
2008-02-05T18:30:30 = 6:30:30 PM UTC
1995-12-22T09:05:02 = 9:05:02 AM UTC
-0010-09-15T04:44:23 = 4:44:23 AM UTC
=head3 hmv (h:mm a v)
2008-02-05T18:30:30 = 6:30 PM UTC
1995-12-22T09:05:02 = 9:05 AM UTC
-0010-09-15T04:44:23 = 4:44 AM UTC
=head3 ms (mm:ss)
2008-02-05T18:30:30 = 30:30
1995-12-22T09:05:02 = 05:02
-0010-09-15T04:44:23 = 44:23
=head3 y (y)
2008-02-05T18:30:30 = 2008
1995-12-22T09:05:02 = 1995
-0010-09-15T04:44:23 = -10
=head3 yM (y-MM)
2008-02-05T18:30:30 = 2008-02
1995-12-22T09:05:02 = 1995-12
-0010-09-15T04:44:23 = -10-09
=head3 yMEd (y-MM-dd, E)
2008-02-05T18:30:30 = 2008-02-05, سهشنبه
1995-12-22T09:05:02 = 1995-12-22, جمعه
-0010-09-15T04:44:23 = -10-09-15, شنبه
=head3 yMMM (y MMM)
2008-02-05T18:30:30 = 2008 فبروري
1995-12-22T09:05:02 = 1995 دسمبر
-0010-09-15T04:44:23 = -10 سپتمبر
=head3 yMMMEd (y MMM d, E)
2008-02-05T18:30:30 = 2008 فبروري 5, سهشنبه
1995-12-22T09:05:02 = 1995 دسمبر 22, جمعه
-0010-09-15T04:44:23 = -10 سپتمبر 15, شنبه
=head3 yMMMM (y MMMM)
2008-02-05T18:30:30 = 2008 فبروري
1995-12-22T09:05:02 = 1995 دسمبر
-0010-09-15T04:44:23 = -10 سپتمبر
=head3 yMMMd (y MMM d)
2008-02-05T18:30:30 = 2008 فبروري 5
1995-12-22T09:05:02 = 1995 دسمبر 22
-0010-09-15T04:44:23 = -10 سپتمبر 15
=head3 yMd (y-MM-dd)
2008-02-05T18:30:30 = 2008-02-05
1995-12-22T09:05:02 = 1995-12-22
-0010-09-15T04:44:23 = -10-09-15
=head3 yQQQ (y QQQ)
2008-02-05T18:30:30 = 2008 Q1
1995-12-22T09:05:02 = 1995 Q4
-0010-09-15T04:44:23 = -10 Q3
=head3 yQQQQ (y QQQQ)
2008-02-05T18:30:30 = 2008 Q1
1995-12-22T09:05:02 = 1995 Q4
-0010-09-15T04:44:23 = -10 Q3
=head2 Miscellaneous
=head3 Prefers 24 hour time?
Yes
=head3 Local first day of the week
1 (دوشنبه)
=head1 SUPPORT
See L<DateTime::Locale>.
=cut
| jkb78/extrajnm | local/lib/perl5/DateTime/Locale/ps.pod | Perl | mit | 10,379 |
package Paws::CognitoIdp::AdminUpdateDeviceStatusResponse;
use Moose;
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::CognitoIdp::AdminUpdateDeviceStatusResponse
=head1 ATTRIBUTES
=head2 _request_id => Str
=cut
1; | ioanrogers/aws-sdk-perl | auto-lib/Paws/CognitoIdp/AdminUpdateDeviceStatusResponse.pm | Perl | apache-2.0 | 282 |
#!/usr/bin/perl
use strict;
use utf8;
#use open ':utf8';
binmode STDERR, ':utf8';
#binmode STDOUT, ':utf8';
#use Storable;
use XML::LibXML;
my $num_args = $#ARGV + 1;
if ($num_args > 1 ) {
print "\nUsage: perl xml2senttok.pl -simple/-full (provide XML on STDIN) \n";
print "\tonly relevant for Quechua: simple or full xml: with simple quechua token=morphemes\n";
exit;
}
my $mode = $ARGV[0];
my $dom = XML::LibXML->load_xml( IO => *STDIN );
## make xml for InterText
my $domnew = XML::LibXML->createDocument ('1.0', 'UTF-8');
my $book = $domnew->createElementNS( "", "book" );
$book->setAttribute('id', $dom->documentElement->getAttribute('id'));
$domnew->setDocumentElement( $book );
foreach my $s ($dom->getElementsByTagName('s') ){
my $sentence = XML::LibXML::Element->new( 's' );
$sentence->setAttribute('id', $s->getAttribute('Intertext_id'));
$book->appendChild($sentence);
if($mode eq '-full'){
foreach my $w ($s->findnodes('descendant::w')){
#print $w->textContent()." ";
$sentence->appendText($w->textContent()." ");
}
}
else{
foreach my $t ($s->findnodes('descendant::t')){
#print $t->textContent()." ";
$sentence->appendText($t->textContent()." ");
}
}
#print "\n";
}
my $docstring = $domnew->toString(3);
print STDOUT $docstring; | a-rios/squoia | bilingwis_stuff/xml2senttok.pl | Perl | apache-2.0 | 1,289 |
#!/usr/bin/perl
#
# $Id$
#
# Copyright (c) 2007 .SE (The Internet Infrastructure Foundation).
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
# IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
######################################################################
package DNSCheck::Locale;
require 5.010001;
use warnings;
use strict;
use utf8;
use overload bool => \&_to_boolean;
######################################################################
sub new {
my $proto = shift;
my $class = ref( $proto ) || $proto;
my $self = {};
my $config = shift;
$self->{name} = $config->{locale_name};
$self->{lang} = $config->{locale_id};
$self->{messages} = $config->{messages};
return bless $self, $class;
}
sub expand {
my ( $self, $tag, @args ) = @_;
my $format = $self->{messages}{$tag}{format};
if ( $format and @args != $self->{messages}{$tag}{args} ) {
warn "invalid number of arguments supplied for $tag";
}
if ( $format ) {
return sprintf( $format, @args );
}
else {
return sprintf( "[MISSING LOCALE] %s %s", $tag, join( ",", @args ) );
}
}
sub _to_boolean {
my $self = shift;
return !!$self->{lang};
}
1;
__END__
=head1 NAME
DNSCheck::Locale - Translation of message tags to human-readable strings
=head1 DESCRIPTION
Module to take internal message tags used by DNSCheck and convert them into
human-readable text messages in any of the supported languages.
=head1 METHODS
=head2 new()
For internal use only. To get an object, use L<DNSCheck::locale()>.
=head2 expand($tag, @args)
Convert the given tag using the given arguments. If the C<@args> list doesn't
have exactly the same number of elements as the translation for the tag
requires, a warning message will be issued on STDERR. If the tag can't be found
in the currently configured language environment, a fallback message will be
generated.
=head1 SEE ALSO
L<DNSCheck>
| dotse/dnscheck | engine/lib/DNSCheck/Locale.pm | Perl | bsd-2-clause | 3,142 |
#
# Copyright 2017 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package centreon::common::aruba::snmp::mode::components::psu;
use strict;
use warnings;
my %map_psu_status = (
1 => 'active',
2 => 'inactive',
);
# In MIB 'aruba-systemext'
my $mapping = {
sysExtPowerSupplyStatus => { oid => '.1.3.6.1.4.1.14823.2.2.1.2.1.18.1.2', map => \%map_psu_status },
};
my $oid_wlsxSysExtPowerSupplyEntry = '.1.3.6.1.4.1.14823.2.2.1.2.1.18.1.2';
sub load {
my ($self) = @_;
push @{$self->{request}}, { oid => $oid_wlsxSysExtPowerSupplyEntry };
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking power supplies");
$self->{components}->{psu} = {name => 'power supplies', total => 0, skip => 0};
return if ($self->check_filter(section => 'psu'));
foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_wlsxSysExtPowerSupplyEntry}})) {
next if ($oid !~ /^$mapping->{sysExtPowerSupplyStatus}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_wlsxSysExtPowerSupplyEntry}, instance => $instance);
next if ($self->check_filter(section => 'psu', instance => $instance));
$self->{components}->{psu}->{total}++;
$self->{output}->output_add(long_msg => sprintf("Power supply '%s' status is %s [instance: %s].",
$instance, $result->{sysExtPowerSupplyStatus},
$instance
));
my $exit = $self->get_severity(section => 'psu', value => $result->{sysExtPowerSupplyStatus});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Power supply '%s' status is %s",
$instance, $result->{sysExtPowerSupplyStatus}));
}
}
}
1; | nichols-356/centreon-plugins | centreon/common/aruba/snmp/mode/components/psu.pm | Perl | apache-2.0 | 2,770 |
# <@LICENSE>
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to you 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.
# </@LICENSE>
package Mail::SpamAssassin::BayesStore::SDBM;
use strict;
use warnings;
use bytes;
use re 'taint';
use Fcntl;
use Mail::SpamAssassin::BayesStore::DBM;
use Mail::SpamAssassin::Logger;
use vars qw{ @ISA @DBNAMES };
@ISA = qw( Mail::SpamAssassin::BayesStore::DBM );
sub HAS_DBM_MODULE {
my ($self) = @_;
if (exists($self->{has_dbm_module})) {
return $self->{has_dbm_module};
}
$self->{has_dbm_module} = eval { require SDBM_File; };
}
sub DBM_MODULE {
return "SDBM_File";
}
# Possible file extensions used by the kinds of database files SDBM_File
# might create. We need these so we can create a new file and rename
# it into place.
sub DB_EXTENSIONS {
return ('.pag', '.dir');
}
sub _unlink_file {
my ($self, $filename) = @_;
for my $ext ($self->DB_EXTENSIONS) {
unlink $filename . $ext;
}
}
sub _rename_file {
my ($self, $sourcefilename, $targetfilename) = @_;
for my $ext ($self->DB_EXTENSIONS) {
return 0 unless (rename($sourcefilename . $ext, $targetfilename . $ext));
}
return 1;
}
# this is called directly from sa-learn(1).
sub perform_upgrade {
return 1;
}
1;
| renormalist/Mail-SpamAssassin-3.3.2-PerlFormance | lib/Mail/SpamAssassin/BayesStore/SDBM.pm | Perl | apache-2.0 | 1,933 |
% ----------------------------------------------------------------------
% BEGIN LICENSE BLOCK
% Version: CMPL 1.1
%
% The contents of this file are subject to the Cisco-style Mozilla Public
% License Version 1.1 (the "License"); you may not use this file except
% in compliance with the License. You may obtain a copy of the License
% at www.eclipse-clp.org/license.
%
% Software distributed under the License is distributed on an "AS IS"
% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
% the License for the specific language governing rights and limitations
% under the License.
%
% The Original Code is The ECLiPSe Constraint Logic Programming System.
% The Initial Developer of the Original Code is Cisco Systems, Inc.
% Portions created by the Initial Developer are
% Copyright (C) 1994-2006 Cisco Systems, Inc. All Rights Reserved.
%
% Contributor(s): ECRC GmbH
% Contributor(s): IC-Parc, Imperal College London
%
% END LICENSE BLOCK
%
% System: ECLiPSe Constraint Logic Programming System
% Version: $Id: notinstance.pl,v 1.1 2008/06/30 17:43:48 jschimpf Exp $
% ----------------------------------------------------------------------
%
% ECLiPSe PROLOG LIBRARY MODULE
%
% IDENTIFICATION: notinstance.pl
%
% AUTHOR: Joachim Schimpf
%
% CONTENTS: X ~= Y (X not unifiable with Y)
% X ~=< Y (X not instance of Y)
%
% DESCRIPTION:
%
:- module(notinstance).
:- comment(summary, "Constraints for structural equality and subsumption").
:- comment(author, "Joachim Schimpf, ECRC Munich").
:- comment(copyright, "Cisco Systems, Inc").
:- comment(date, "$Date: 2008/06/30 17:43:48 $").
:- export op(700, xfx, (~=<)).
:- export (~=<)/2, (~=)/2.
:- use_module(library(fd)).
:- pragma(nodebug).
%-----------------------------------------------------------------
% Non-unifiability
% Fails if X and Y are non-unifiable, otherwise succeeds or delays.
% Only one delayed goal, explicit wavefront list.
% Failure is detected eagerly.
% Success may be detected late.
%-----------------------------------------------------------------
:- comment((~=)/2, [template:"X ~= Y",
summary:"Constraints X and Y to be different",
desc:html("Fails if X and Y are non-unifiable, otherwise succeeds
or delays. Unlike the implementation of the same predicate in the
kernel, this one maintains and explicit wavefront and has only one
delayed goal. Failure is detected eagerly. Success may be
detected late.")]).
X ~= Y :-
nu_wf([X~=Y]).
nu_wf([X~=Y|WF0]) :-
nu3(X, Y, WF1, WF2),
( WF2 == true ->
true
; WF1 == WF2 ->
nu_wf(WF0)
;
% delay on one undecidable pair (could be more precise)
WF1 = WF0,
WF2 = [First|_],
make_suspension(nu_wf(WF2), 2, Susp),
insert_suspension(First, Susp, bound of suspend, suspend)
).
nu3(X, Y, Xr0, Xr) :-
var(X), var(Y),
X == Y,
!,
Xr = Xr0. % continue
nu3(X, Y, Xr0, Xr) :-
(var(X) ; var(Y)),
!,
Xr = [X~=Y|Xr0]. % delay
nu3(X, Y, Xr0, Xr) :-
atomic(X), atomic(Y),
X = Y,
!,
Xr = Xr0.
nu3(X, Y, Xr0, Xr) :-
compound(X), compound(Y),
functor(X, F, A),
functor(Y, F, A),
!,
nu3_arg(X, Y, Xr0, Xr, A).
nu3(_X, _Y, _Xr0, true). % succeed
nu3_arg(_X, _Y, Xr0, Xr, 0) :- !, Xr0 = Xr.
nu3_arg(X, Y, Xr0, Xr, N) :-
arg(N, X, Xarg),
arg(N, Y, Yarg),
nu3(Xarg, Yarg, Xr0, Xr1),
( Xr1 == true ->
Xr = true
;
N1 is N-1,
nu3_arg(X, Y, Xr1, Xr, N1)
).
%-----------------------------------------------------------------
% X ~=< Y Constrain X not to be an instance of Y.
%
% We assume:
% - no shared variables between X and Y
% - X may get more instantiated, but not Y
% Failure is detected eagerly.
% Success may be detected late.
% The binding table is done very naively currently.
%-----------------------------------------------------------------
:- comment((~=<)/2, [template:"X ~=< Y",
summary:"Constrain X not to be an instance of Y",
desc:html("We assume:
<UL>
<LI> no shared variables between X and Y
<LI> X may get more instantiated, but not Y
</UL>
Failure is detected eagerly. Success may be detected late.")]).
X ~=< Y :-
ni_wf(X ~=< Y, [], _V).
ni_wf(X ~=< Y, WF0, V) :-
!,
ni(X, Y, V, WF1, WF2),
( WF2 == true ->
true % definitely not an instance
; WF1 == WF2 ->
WF0 = [First|WF3],
ni_wf(First, WF3, V) % continue along the wavefront
;
% delay on one undecidable pair
WF1 = WF0, % prepend
WF2 = [First|WF3],
make_suspension(ni_wf(First, WF3, V), 2, Susp),
( First = (Lhs ~=< _) ->
insert_suspension_into_constrained_lists(Lhs, Susp)
; % First = (_ ~= _)
insert_suspension(First, Susp, bound of suspend, suspend)
)
).
ni_wf(X ~= Y, WF0, V) :-
nu3(X, Y, WF1, WF2),
( WF2 == true ->
true
; WF1 == WF2 ->
WF0 = [First|WF3],
ni_wf(First, WF3, V)
;
% delay on one undecidable pair
WF1 = WF0,
WF2 = [First|WF3],
make_suspension(ni_wf(First, WF3, V), 2, Susp),
insert_suspension(First, Susp, bound of suspend, suspend)
).
ni(X, Y, _V, T0, T) :-
var(X), nonvar(Y),
!,
T = [X~=<Y|T0].
ni(X, Y, _V, T0, T) :- % nonvar(X);var(Y)
meta(Y),
\+ instance(X,Y),
!,
( atomic(X) -> T = true ; T = [X~=<Y|T0] ).
ni(X, Y, V, T0, T) :- % nonvar(X);var(Y)
var(Y), !, % free(Y);meta(Y)
lookup(Y, V, Map),
( var(Map) ->
Map = map(X), % remember the mapping Y=X
T0 = T % one step closer to failure ...
;
Map = map(Xold),
nu3(Xold, X, T0, T) % add inequality constraint
).
ni(X, Y, _V, T0, T) :-
atomic(X), % atomic(Y),
X = Y,
!,
T0 = T. % one step closer to failure ...
ni(X, Y, V, T0, T) :-
compound(X), compound(Y),
functor(X, F, A),
functor(Y, F, A),
!,
ni_args(X, Y, V, T0, T, A).
ni(_X, _Y, _V, _T0, true). % not instances: success
ni_args(_X, _Y, _V, T0, T, 0) :- !, T0 = T.
ni_args(X, Y, V, T0, T, N) :-
arg(N, X, Xarg),
arg(N, Y, Yarg),
ni(Xarg, Yarg, V, T0, T1),
( T1 == true ->
T = true
;
N1 is N-1,
ni_args(X, Y, V, T1, T, N1)
).
lookup(Key, List, Entry) :-
var(List), !,
List = [Key-Entry|_].
lookup(Key, [Key0-Entry0|Tail], Entry) :-
Key == Key0 ->
Entry = Entry0
;
lookup(Key, Tail, Entry).
%-----------------------------------------------------------------
% insert_suspension_into_constrained_lists
%-----------------------------------------------------------------
insert_suspension_into_constrained_lists(Term, Susp) :-
term_variables(Term, Vars),
insert_in_proper_lists(Vars, Susp).
insert_in_proper_lists([], _Susp).
insert_in_proper_lists([Var|Vars], Susp) :-
( is_domain(Var) ->
insert_suspension(Var, Susp, any of fd, fd)
;
true
),
insert_suspension(Var, Susp, constrained of suspend, suspend),
insert_in_proper_lists(Vars, Susp).
| daleooo/barrelfish | usr/skb/eclipse_kernel/lib/notinstance.pl | Perl | mit | 6,749 |
#! /usr/bin/env perl
##**************************************************************
##
## Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
## University of Wisconsin-Madison, WI.
##
## 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.
##
##**************************************************************
use strict;
use warnings;
use Cwd;
use File::Temp qw/ tempfile tempdir /;
# open( STDOUT, "> /tmp/x_advertise.log" ) or die "Can't open stdout";
# open( STDERR, "> &STDOUT" ) or die "Can't open stderr";
# print STDOUT getcwd() ."\n";
# print "$0 " . join( " ", @ARGV ) . "\n";;
sub usage( )
{
print
"usage: $0 [options] <update-command> <file>\n" .
" --period <sec> specify update period (default 60 seconds)\n".
" --max-run <sec> specify maximum run time (default: none)\n".
" --delay <sec> delay before first publish (default: 5 seconds)\n" .
" --dir <dir> specify directory to create temp ad files in\n" .
" -k|--keep Keep temp ad files (for debugging)\n" .
" -f run in foreground (ignored; $0 always does)\n" .
" -l|--log <file> specify file to log to\n" .
" -n|--no-exec no execute / test mode\n" .
" -v|--verbose increase verbose level\n" .
" -t|--test print to stdout / stderr\n" .
" --valgrind run test under valgrind\n" .
" -q|--quiet cancel debug & verbose\n" .
" -h|--help this help\n";
}
my %settings =
(
period => 60,
delay => 5,
keep => 0,
done => 0,
valgrind => 0,
verbose => 0,
execute => 1,
test => 0,
);
my $skip = 0;
foreach my $argno ( 0 .. $#ARGV ) {
if ( $skip ) {
$skip--;
next;
}
my $arg = $ARGV[$argno];
my $arg1 = ($argno+1 > $#ARGV) ? undef : $ARGV[$argno+1];
if ( not $arg =~ /^-/ ) {
if ( !exists $settings{command} ) {
$settings{command} = $arg;
}
elsif ( !exists $settings{infile} ) {
$settings{infile} = $arg;
}
else {
print STDERR "Unknown argument $arg\n";
usage( );
exit(1);
}
}
elsif ( $arg eq "-n" or $arg eq "--no-exec" ) {
$settings{execute} = 0;
}
elsif ( $arg eq "--valgrind" ) {
$settings{valgrind} = 1;
}
elsif ( $arg eq "--period" and defined($arg1) ) {
$settings{period} = int($arg1);
$skip = 1;
}
elsif ( $arg eq "--delay" and defined($arg1) ) {
$settings{delay} = int($arg1);
$skip = 1;
}
elsif ( $arg eq "--max-run" and defined($arg1) ) {
$settings{max_run} = int($arg1);
$skip = 1;
}
elsif ( $arg eq "--dir" and defined($arg1) ) {
$settings{dir} = $arg1;
$skip = 1;
}
elsif ( $arg eq "--log" and defined($arg1) ) {
$settings{log} = $arg1;
}
elsif ( $arg eq "-k" or $arg eq "--keep" ) {
$settings{keep} = 1;
}
elsif ( $arg eq "-v" or $arg eq "--verbose" ) {
$settings{verbose}++;
}
elsif ( $arg eq "-d" or $arg eq "--debug" ) {
$settings{debug} = 1;
}
elsif ( $arg eq "-q" or $arg eq "--quiet" ) {
$settings{verbose} = 0;
$settings{debug} = 0;
}
elsif ( $arg eq "-t" or $arg eq "--test" ) {
$settings{test} = 1;
}
elsif ( $arg eq "-h" or $arg eq "--help" ) {
usage( );
exit(0);
}
else {
print STDERR "Unknown argument $arg\n";
usage( );
exit(1);
}
}
if ( !exists $settings{command} ) {
print STDERR "No command specified\n";
usage( );
exit(1);
}
if ( !exists $settings{infile} ) {
print STDERR "No input file specified\n";
usage( );
exit(1);
}
# Set the directory to use
if ( !exists $settings{dir} ) {
my @all = split( /\//, $settings{infile} );
if ( $#all == 1 ) {
$settings{dir} = $all[0];
}
else {
pop(@all);
$settings{dir} = join( "/", @all );
}
print "Dir set to " . $settings{dir} . "\n";
}
# Setup logging
if ( !exists $settings{log} ) {
$settings{log} = `condor_config_val ADVERTISER_LOG`;
chomp $settings{log};
print "New log: '".$settings{log}."'\n";
}
if ( !$settings{test} ) {
my $log = $settings{log};
open( STDOUT, ">$log" );
open( STDERR, ">&STDOUT" );
}
my @valgrind = ( "valgrind", "--tool=memcheck", "--num-callers=24",
"-v", "-v", "--leak-check=full" );
# Read in the original ad
my %ad;
open( AD, $settings{infile} ) or
die "Can't read ad file '".$settings{infile}."'";
while( <AD> ) {
chomp;
if ( /(\w+) = (.*)/ ) {
$ad{$1} = $2;
}
else {
die "Can't parse ad line $.: '$_'";
}
}
close( AD );
# Some simple ad manipulations
if ( !exists $ad{DaemonStartTime} ) {
$ad{DaemonStartTime} = time();
}
my $sequence = 1;
if ( exists $ad{UpdateSequenceNumber} ) {
$sequence = int($ad{UpdateSequenceNumber});
}
# Set an alarm
sub handler()
{
print "Caught signal; shutting down\n";
$settings{done} = 1;
}
$SIG{TERM} = \&handler;
$SIG{INT} = \&handler;
$SIG{QUIT} = \&handler;
if ( exists $settings{max_run} ) {
$SIG{ALRM} = \&handler;
alarm( $settings{max_run} );
}
# Delay before first publish
if ( $settings{delay} ) {
sleep( $settings{delay} );
}
# Now, got into publishing mode
while( ! $settings{done} ) {
print "loop\n";
$ad{UpdateSequenceNumber} = $sequence++;
my ($fh, $filename) = tempfile( DIR => $settings{dir} );
foreach my $attr ( keys(%ad) ) {
my $value = $ad{$attr};
if ( 1 ) {
print $fh "$attr = $value\n";
}
elsif ( $value eq "TRUE" ) {
print $fh "$attr = TRUE\n";
}
elsif ( $value eq "FALSE" ) {
print $fh "$attr = FALSE\n";
}
elsif ( $value =~ /^\d+$/ ) {
print $fh "$attr = $value\n";
}
elsif ( $value =~ /^\d+\.\d+$/ ) {
print $fh "$attr = $value\n";
}
else {
print $fh "$attr = \"$value\"\n";
}
}
close( $fh );
if ( $settings{verbose} >= 1 ) {
print "Temp file: $filename\n";
if ( $settings{verbose} > 1 ) {
system( "cat $filename" );
}
}
my $cmd = "";
if ( $settings{valgrind} ) {
$cmd .= join(" ", @valgrind );
$cmd .= " --log-file=".$settings{dir}."/advertise.valgrind ";
}
$cmd .= "condor_advertise ".$settings{command}." ".$filename;
print "Running: $cmd\n";
if ( $settings{execute} ) {
system( $cmd );
}
if ( not $settings{keep} ) {
unlink( $filename );
}
sleep( $settings{period} );
}
### Local Variables: ***
### mode:perl ***
### tab-width: 4 ***
### End: ***
| zhangzhehust/htcondor | src/condor_tests/x_advertise.pl | Perl | apache-2.0 | 6,628 |
#!/usr/bin/env perl
# ====================================================================
# Written by Andy Polyakov <appro@fy.chalmers.se> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
# SHA256/512 block procedure for PA-RISC.
# June 2009.
#
# SHA256 performance is >75% better than gcc 3.2 generated code on
# PA-7100LC. Compared to code generated by vendor compiler this
# implementation is almost 70% faster in 64-bit build, but delivers
# virtually same performance in 32-bit build on PA-8600.
#
# SHA512 performance is >2.9x better than gcc 3.2 generated code on
# PA-7100LC, PA-RISC 1.1 processor. Then implementation detects if the
# code is executed on PA-RISC 2.0 processor and switches to 64-bit
# code path delivering adequate peformance even in "blended" 32-bit
# build. Though 64-bit code is not any faster than code generated by
# vendor compiler on PA-8600...
#
# Special thanks to polarhome.com for providing HP-UX account.
$flavour = shift;
$output = shift;
open STDOUT,">$output";
if ($flavour =~ /64/) {
$LEVEL ="2.0W";
$SIZE_T =8;
$FRAME_MARKER =80;
$SAVED_RP =16;
$PUSH ="std";
$PUSHMA ="std,ma";
$POP ="ldd";
$POPMB ="ldd,mb";
} else {
$LEVEL ="1.0";
$SIZE_T =4;
$FRAME_MARKER =48;
$SAVED_RP =20;
$PUSH ="stw";
$PUSHMA ="stwm";
$POP ="ldw";
$POPMB ="ldwm";
}
if ($output =~ /512/) {
$func="sha512_block_data_order";
$SZ=8;
@Sigma0=(28,34,39);
@Sigma1=(14,18,41);
@sigma0=(1, 8, 7);
@sigma1=(19,61, 6);
$rounds=80;
$LAST10BITS=0x017;
$LD="ldd";
$LDM="ldd,ma";
$ST="std";
} else {
$func="sha256_block_data_order";
$SZ=4;
@Sigma0=( 2,13,22);
@Sigma1=( 6,11,25);
@sigma0=( 7,18, 3);
@sigma1=(17,19,10);
$rounds=64;
$LAST10BITS=0x0f2;
$LD="ldw";
$LDM="ldwm";
$ST="stw";
}
$FRAME=16*$SIZE_T+$FRAME_MARKER;# 16 saved regs + frame marker
# [+ argument transfer]
$XOFF=16*$SZ+32; # local variables
$FRAME+=$XOFF;
$XOFF+=$FRAME_MARKER; # distance between %sp and local variables
$ctx="%r26"; # zapped by $a0
$inp="%r25"; # zapped by $a1
$num="%r24"; # zapped by $t0
$a0 ="%r26";
$a1 ="%r25";
$t0 ="%r24";
$t1 ="%r29";
$Tbl="%r31";
@V=($A,$B,$C,$D,$E,$F,$G,$H)=("%r17","%r18","%r19","%r20","%r21","%r22","%r23","%r28");
@X=("%r1", "%r2", "%r3", "%r4", "%r5", "%r6", "%r7", "%r8",
"%r9", "%r10","%r11","%r12","%r13","%r14","%r15","%r16",$inp);
sub ROUND_00_15 {
my ($i,$a,$b,$c,$d,$e,$f,$g,$h)=@_;
$code.=<<___;
_ror $e,$Sigma1[0],$a0
and $f,$e,$t0
_ror $e,$Sigma1[1],$a1
addl $t1,$h,$h
andcm $g,$e,$t1
xor $a1,$a0,$a0
_ror $a1,`$Sigma1[2]-$Sigma1[1]`,$a1
or $t0,$t1,$t1 ; Ch(e,f,g)
addl @X[$i%16],$h,$h
xor $a0,$a1,$a1 ; Sigma1(e)
addl $t1,$h,$h
_ror $a,$Sigma0[0],$a0
addl $a1,$h,$h
_ror $a,$Sigma0[1],$a1
and $a,$b,$t0
and $a,$c,$t1
xor $a1,$a0,$a0
_ror $a1,`$Sigma0[2]-$Sigma0[1]`,$a1
xor $t1,$t0,$t0
and $b,$c,$t1
xor $a0,$a1,$a1 ; Sigma0(a)
addl $h,$d,$d
xor $t1,$t0,$t0 ; Maj(a,b,c)
`"$LDM $SZ($Tbl),$t1" if ($i<15)`
addl $a1,$h,$h
addl $t0,$h,$h
___
}
sub ROUND_16_xx {
my ($i,$a,$b,$c,$d,$e,$f,$g,$h)=@_;
$i-=16;
$code.=<<___;
_ror @X[($i+1)%16],$sigma0[0],$a0
_ror @X[($i+1)%16],$sigma0[1],$a1
addl @X[($i+9)%16],@X[$i],@X[$i]
_ror @X[($i+14)%16],$sigma1[0],$t0
_ror @X[($i+14)%16],$sigma1[1],$t1
xor $a1,$a0,$a0
_shr @X[($i+1)%16],$sigma0[2],$a1
xor $t1,$t0,$t0
_shr @X[($i+14)%16],$sigma1[2],$t1
xor $a1,$a0,$a0 ; sigma0(X[(i+1)&0x0f])
xor $t1,$t0,$t0 ; sigma1(X[(i+14)&0x0f])
$LDM $SZ($Tbl),$t1
addl $a0,@X[$i],@X[$i]
addl $t0,@X[$i],@X[$i]
___
$code.=<<___ if ($i==15);
extru $t1,31,10,$a1
comiclr,<> $LAST10BITS,$a1,%r0
ldo 1($Tbl),$Tbl ; signal end of $Tbl
___
&ROUND_00_15($i+16,$a,$b,$c,$d,$e,$f,$g,$h);
}
$code=<<___;
.LEVEL $LEVEL
.SPACE \$TEXT\$
.SUBSPA \$CODE\$,QUAD=0,ALIGN=8,ACCESS=0x2C,CODE_ONLY
.ALIGN 64
L\$table
___
$code.=<<___ if ($SZ==8);
.WORD 0x428a2f98,0xd728ae22,0x71374491,0x23ef65cd
.WORD 0xb5c0fbcf,0xec4d3b2f,0xe9b5dba5,0x8189dbbc
.WORD 0x3956c25b,0xf348b538,0x59f111f1,0xb605d019
.WORD 0x923f82a4,0xaf194f9b,0xab1c5ed5,0xda6d8118
.WORD 0xd807aa98,0xa3030242,0x12835b01,0x45706fbe
.WORD 0x243185be,0x4ee4b28c,0x550c7dc3,0xd5ffb4e2
.WORD 0x72be5d74,0xf27b896f,0x80deb1fe,0x3b1696b1
.WORD 0x9bdc06a7,0x25c71235,0xc19bf174,0xcf692694
.WORD 0xe49b69c1,0x9ef14ad2,0xefbe4786,0x384f25e3
.WORD 0x0fc19dc6,0x8b8cd5b5,0x240ca1cc,0x77ac9c65
.WORD 0x2de92c6f,0x592b0275,0x4a7484aa,0x6ea6e483
.WORD 0x5cb0a9dc,0xbd41fbd4,0x76f988da,0x831153b5
.WORD 0x983e5152,0xee66dfab,0xa831c66d,0x2db43210
.WORD 0xb00327c8,0x98fb213f,0xbf597fc7,0xbeef0ee4
.WORD 0xc6e00bf3,0x3da88fc2,0xd5a79147,0x930aa725
.WORD 0x06ca6351,0xe003826f,0x14292967,0x0a0e6e70
.WORD 0x27b70a85,0x46d22ffc,0x2e1b2138,0x5c26c926
.WORD 0x4d2c6dfc,0x5ac42aed,0x53380d13,0x9d95b3df
.WORD 0x650a7354,0x8baf63de,0x766a0abb,0x3c77b2a8
.WORD 0x81c2c92e,0x47edaee6,0x92722c85,0x1482353b
.WORD 0xa2bfe8a1,0x4cf10364,0xa81a664b,0xbc423001
.WORD 0xc24b8b70,0xd0f89791,0xc76c51a3,0x0654be30
.WORD 0xd192e819,0xd6ef5218,0xd6990624,0x5565a910
.WORD 0xf40e3585,0x5771202a,0x106aa070,0x32bbd1b8
.WORD 0x19a4c116,0xb8d2d0c8,0x1e376c08,0x5141ab53
.WORD 0x2748774c,0xdf8eeb99,0x34b0bcb5,0xe19b48a8
.WORD 0x391c0cb3,0xc5c95a63,0x4ed8aa4a,0xe3418acb
.WORD 0x5b9cca4f,0x7763e373,0x682e6ff3,0xd6b2b8a3
.WORD 0x748f82ee,0x5defb2fc,0x78a5636f,0x43172f60
.WORD 0x84c87814,0xa1f0ab72,0x8cc70208,0x1a6439ec
.WORD 0x90befffa,0x23631e28,0xa4506ceb,0xde82bde9
.WORD 0xbef9a3f7,0xb2c67915,0xc67178f2,0xe372532b
.WORD 0xca273ece,0xea26619c,0xd186b8c7,0x21c0c207
.WORD 0xeada7dd6,0xcde0eb1e,0xf57d4f7f,0xee6ed178
.WORD 0x06f067aa,0x72176fba,0x0a637dc5,0xa2c898a6
.WORD 0x113f9804,0xbef90dae,0x1b710b35,0x131c471b
.WORD 0x28db77f5,0x23047d84,0x32caab7b,0x40c72493
.WORD 0x3c9ebe0a,0x15c9bebc,0x431d67c4,0x9c100d4c
.WORD 0x4cc5d4be,0xcb3e42b6,0x597f299c,0xfc657e2a
.WORD 0x5fcb6fab,0x3ad6faec,0x6c44198c,0x4a475817
___
$code.=<<___ if ($SZ==4);
.WORD 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
.WORD 0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
.WORD 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
.WORD 0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
.WORD 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
.WORD 0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
.WORD 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
.WORD 0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
.WORD 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
.WORD 0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
.WORD 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
.WORD 0xd192e819,0xd6990624,0xf40e3585,0x106aa070
.WORD 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
.WORD 0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
.WORD 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
.WORD 0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
___
$code.=<<___;
.EXPORT $func,ENTRY,ARGW0=GR,ARGW1=GR,ARGW2=GR
.ALIGN 64
$func
.PROC
.CALLINFO FRAME=`$FRAME-16*$SIZE_T`,NO_CALLS,SAVE_RP,ENTRY_GR=18
.ENTRY
$PUSH %r2,-$SAVED_RP(%sp) ; standard prologue
$PUSHMA %r3,$FRAME(%sp)
$PUSH %r4,`-$FRAME+1*$SIZE_T`(%sp)
$PUSH %r5,`-$FRAME+2*$SIZE_T`(%sp)
$PUSH %r6,`-$FRAME+3*$SIZE_T`(%sp)
$PUSH %r7,`-$FRAME+4*$SIZE_T`(%sp)
$PUSH %r8,`-$FRAME+5*$SIZE_T`(%sp)
$PUSH %r9,`-$FRAME+6*$SIZE_T`(%sp)
$PUSH %r10,`-$FRAME+7*$SIZE_T`(%sp)
$PUSH %r11,`-$FRAME+8*$SIZE_T`(%sp)
$PUSH %r12,`-$FRAME+9*$SIZE_T`(%sp)
$PUSH %r13,`-$FRAME+10*$SIZE_T`(%sp)
$PUSH %r14,`-$FRAME+11*$SIZE_T`(%sp)
$PUSH %r15,`-$FRAME+12*$SIZE_T`(%sp)
$PUSH %r16,`-$FRAME+13*$SIZE_T`(%sp)
$PUSH %r17,`-$FRAME+14*$SIZE_T`(%sp)
$PUSH %r18,`-$FRAME+15*$SIZE_T`(%sp)
_shl $num,`log(16*$SZ)/log(2)`,$num
addl $inp,$num,$num ; $num to point at the end of $inp
$PUSH $num,`-$FRAME_MARKER-4*$SIZE_T`(%sp) ; save arguments
$PUSH $inp,`-$FRAME_MARKER-3*$SIZE_T`(%sp)
$PUSH $ctx,`-$FRAME_MARKER-2*$SIZE_T`(%sp)
blr %r0,$Tbl
ldi 3,$t1
L\$pic
andcm $Tbl,$t1,$Tbl ; wipe privilege level
ldo L\$table-L\$pic($Tbl),$Tbl
___
$code.=<<___ if ($SZ==8 && $SIZE_T==4);
ldi 31,$t1
mtctl $t1,%cr11
extrd,u,*= $t1,%sar,1,$t1 ; executes on PA-RISC 1.0
b L\$parisc1
nop
___
$code.=<<___;
$LD `0*$SZ`($ctx),$A ; load context
$LD `1*$SZ`($ctx),$B
$LD `2*$SZ`($ctx),$C
$LD `3*$SZ`($ctx),$D
$LD `4*$SZ`($ctx),$E
$LD `5*$SZ`($ctx),$F
$LD `6*$SZ`($ctx),$G
$LD `7*$SZ`($ctx),$H
extru $inp,31,`log($SZ)/log(2)`,$t0
sh3addl $t0,%r0,$t0
subi `8*$SZ`,$t0,$t0
mtctl $t0,%cr11 ; load %sar with align factor
L\$oop
ldi `$SZ-1`,$t0
$LDM $SZ($Tbl),$t1
andcm $inp,$t0,$t0 ; align $inp
___
for ($i=0;$i<15;$i++) { # load input block
$code.="\t$LD `$SZ*$i`($t0),@X[$i]\n"; }
$code.=<<___;
cmpb,*= $inp,$t0,L\$aligned
$LD `$SZ*15`($t0),@X[15]
$LD `$SZ*16`($t0),@X[16]
___
for ($i=0;$i<16;$i++) { # align data
$code.="\t_align @X[$i],@X[$i+1],@X[$i]\n"; }
$code.=<<___;
L\$aligned
nop ; otherwise /usr/ccs/bin/as is confused by below .WORD
___
for($i=0;$i<16;$i++) { &ROUND_00_15($i,@V); unshift(@V,pop(@V)); }
$code.=<<___;
L\$rounds
nop ; otherwise /usr/ccs/bin/as is confused by below .WORD
___
for(;$i<32;$i++) { &ROUND_16_xx($i,@V); unshift(@V,pop(@V)); }
$code.=<<___;
bb,>= $Tbl,31,L\$rounds ; end of $Tbl signalled?
nop
$POP `-$FRAME_MARKER-2*$SIZE_T`(%sp),$ctx ; restore arguments
$POP `-$FRAME_MARKER-3*$SIZE_T`(%sp),$inp
$POP `-$FRAME_MARKER-4*$SIZE_T`(%sp),$num
ldo `-$rounds*$SZ-1`($Tbl),$Tbl ; rewind $Tbl
$LD `0*$SZ`($ctx),@X[0] ; load context
$LD `1*$SZ`($ctx),@X[1]
$LD `2*$SZ`($ctx),@X[2]
$LD `3*$SZ`($ctx),@X[3]
$LD `4*$SZ`($ctx),@X[4]
$LD `5*$SZ`($ctx),@X[5]
addl @X[0],$A,$A
$LD `6*$SZ`($ctx),@X[6]
addl @X[1],$B,$B
$LD `7*$SZ`($ctx),@X[7]
ldo `16*$SZ`($inp),$inp ; advance $inp
$ST $A,`0*$SZ`($ctx) ; save context
addl @X[2],$C,$C
$ST $B,`1*$SZ`($ctx)
addl @X[3],$D,$D
$ST $C,`2*$SZ`($ctx)
addl @X[4],$E,$E
$ST $D,`3*$SZ`($ctx)
addl @X[5],$F,$F
$ST $E,`4*$SZ`($ctx)
addl @X[6],$G,$G
$ST $F,`5*$SZ`($ctx)
addl @X[7],$H,$H
$ST $G,`6*$SZ`($ctx)
$ST $H,`7*$SZ`($ctx)
cmpb,*<>,n $inp,$num,L\$oop
$PUSH $inp,`-$FRAME_MARKER-3*$SIZE_T`(%sp) ; save $inp
___
if ($SZ==8 && $SIZE_T==4) # SHA512 for 32-bit PA-RISC 1.0
{{
$code.=<<___;
b L\$done
nop
.ALIGN 64
L\$parisc1
___
@V=( $Ahi, $Alo, $Bhi, $Blo, $Chi, $Clo, $Dhi, $Dlo,
$Ehi, $Elo, $Fhi, $Flo, $Ghi, $Glo, $Hhi, $Hlo) =
( "%r1", "%r2", "%r3", "%r4", "%r5", "%r6", "%r7", "%r8",
"%r9","%r10","%r11","%r12","%r13","%r14","%r15","%r16");
$a0 ="%r17";
$a1 ="%r18";
$a2 ="%r19";
$a3 ="%r20";
$t0 ="%r21";
$t1 ="%r22";
$t2 ="%r28";
$t3 ="%r29";
$Tbl="%r31";
@X=("%r23","%r24","%r25","%r26"); # zaps $num,$inp,$ctx
sub ROUND_00_15_pa1 {
my ($i,$ahi,$alo,$bhi,$blo,$chi,$clo,$dhi,$dlo,
$ehi,$elo,$fhi,$flo,$ghi,$glo,$hhi,$hlo,$flag)=@_;
my ($Xhi,$Xlo,$Xnhi,$Xnlo) = @X;
$code.=<<___ if (!$flag);
ldw `-$XOFF+8*(($i+1)%16)`(%sp),$Xnhi
ldw `-$XOFF+8*(($i+1)%16)+4`(%sp),$Xnlo ; load X[i+1]
___
$code.=<<___;
shd $ehi,$elo,$Sigma1[0],$t0
add $Xlo,$hlo,$hlo
shd $elo,$ehi,$Sigma1[0],$t1
addc $Xhi,$hhi,$hhi ; h += X[i]
shd $ehi,$elo,$Sigma1[1],$t2
ldwm 8($Tbl),$Xhi
shd $elo,$ehi,$Sigma1[1],$t3
ldw -4($Tbl),$Xlo ; load K[i]
xor $t2,$t0,$t0
xor $t3,$t1,$t1
and $flo,$elo,$a0
and $fhi,$ehi,$a1
shd $ehi,$elo,$Sigma1[2],$t2
andcm $glo,$elo,$a2
shd $elo,$ehi,$Sigma1[2],$t3
andcm $ghi,$ehi,$a3
xor $t2,$t0,$t0
xor $t3,$t1,$t1 ; Sigma1(e)
add $Xlo,$hlo,$hlo
xor $a2,$a0,$a0
addc $Xhi,$hhi,$hhi ; h += K[i]
xor $a3,$a1,$a1 ; Ch(e,f,g)
add $t0,$hlo,$hlo
shd $ahi,$alo,$Sigma0[0],$t0
addc $t1,$hhi,$hhi ; h += Sigma1(e)
shd $alo,$ahi,$Sigma0[0],$t1
add $a0,$hlo,$hlo
shd $ahi,$alo,$Sigma0[1],$t2
addc $a1,$hhi,$hhi ; h += Ch(e,f,g)
shd $alo,$ahi,$Sigma0[1],$t3
xor $t2,$t0,$t0
xor $t3,$t1,$t1
shd $ahi,$alo,$Sigma0[2],$t2
and $alo,$blo,$a0
shd $alo,$ahi,$Sigma0[2],$t3
and $ahi,$bhi,$a1
xor $t2,$t0,$t0
xor $t3,$t1,$t1 ; Sigma0(a)
and $alo,$clo,$a2
and $ahi,$chi,$a3
xor $a2,$a0,$a0
add $hlo,$dlo,$dlo
xor $a3,$a1,$a1
addc $hhi,$dhi,$dhi ; d += h
and $blo,$clo,$a2
add $t0,$hlo,$hlo
and $bhi,$chi,$a3
addc $t1,$hhi,$hhi ; h += Sigma0(a)
xor $a2,$a0,$a0
add $a0,$hlo,$hlo
xor $a3,$a1,$a1 ; Maj(a,b,c)
addc $a1,$hhi,$hhi ; h += Maj(a,b,c)
___
$code.=<<___ if ($i==15 && $flag);
extru $Xlo,31,10,$Xlo
comiclr,= $LAST10BITS,$Xlo,%r0
b L\$rounds_pa1
nop
___
push(@X,shift(@X)); push(@X,shift(@X));
}
sub ROUND_16_xx_pa1 {
my ($Xhi,$Xlo,$Xnhi,$Xnlo) = @X;
my ($i)=shift;
$i-=16;
$code.=<<___;
ldw `-$XOFF+8*(($i+1)%16)`(%sp),$Xnhi
ldw `-$XOFF+8*(($i+1)%16)+4`(%sp),$Xnlo ; load X[i+1]
ldw `-$XOFF+8*(($i+9)%16)`(%sp),$a1
ldw `-$XOFF+8*(($i+9)%16)+4`(%sp),$a0 ; load X[i+9]
ldw `-$XOFF+8*(($i+14)%16)`(%sp),$a3
ldw `-$XOFF+8*(($i+14)%16)+4`(%sp),$a2 ; load X[i+14]
shd $Xnhi,$Xnlo,$sigma0[0],$t0
shd $Xnlo,$Xnhi,$sigma0[0],$t1
add $a0,$Xlo,$Xlo
shd $Xnhi,$Xnlo,$sigma0[1],$t2
addc $a1,$Xhi,$Xhi
shd $Xnlo,$Xnhi,$sigma0[1],$t3
xor $t2,$t0,$t0
shd $Xnhi,$Xnlo,$sigma0[2],$t2
xor $t3,$t1,$t1
extru $Xnhi,`31-$sigma0[2]`,`32-$sigma0[2]`,$t3
xor $t2,$t0,$t0
shd $a3,$a2,$sigma1[0],$a0
xor $t3,$t1,$t1 ; sigma0(X[i+1)&0x0f])
shd $a2,$a3,$sigma1[0],$a1
add $t0,$Xlo,$Xlo
shd $a3,$a2,$sigma1[1],$t2
addc $t1,$Xhi,$Xhi
shd $a2,$a3,$sigma1[1],$t3
xor $t2,$a0,$a0
shd $a3,$a2,$sigma1[2],$t2
xor $t3,$a1,$a1
extru $a3,`31-$sigma1[2]`,`32-$sigma1[2]`,$t3
xor $t2,$a0,$a0
xor $t3,$a1,$a1 ; sigma0(X[i+14)&0x0f])
add $a0,$Xlo,$Xlo
addc $a1,$Xhi,$Xhi
stw $Xhi,`-$XOFF+8*($i%16)`(%sp)
stw $Xlo,`-$XOFF+8*($i%16)+4`(%sp)
___
&ROUND_00_15_pa1($i,@_,1);
}
$code.=<<___;
ldw `0*4`($ctx),$Ahi ; load context
ldw `1*4`($ctx),$Alo
ldw `2*4`($ctx),$Bhi
ldw `3*4`($ctx),$Blo
ldw `4*4`($ctx),$Chi
ldw `5*4`($ctx),$Clo
ldw `6*4`($ctx),$Dhi
ldw `7*4`($ctx),$Dlo
ldw `8*4`($ctx),$Ehi
ldw `9*4`($ctx),$Elo
ldw `10*4`($ctx),$Fhi
ldw `11*4`($ctx),$Flo
ldw `12*4`($ctx),$Ghi
ldw `13*4`($ctx),$Glo
ldw `14*4`($ctx),$Hhi
ldw `15*4`($ctx),$Hlo
extru $inp,31,2,$t0
sh3addl $t0,%r0,$t0
subi 32,$t0,$t0
mtctl $t0,%cr11 ; load %sar with align factor
L\$oop_pa1
extru $inp,31,2,$a3
comib,= 0,$a3,L\$aligned_pa1
sub $inp,$a3,$inp
ldw `0*4`($inp),$X[0]
ldw `1*4`($inp),$X[1]
ldw `2*4`($inp),$t2
ldw `3*4`($inp),$t3
ldw `4*4`($inp),$a0
ldw `5*4`($inp),$a1
ldw `6*4`($inp),$a2
ldw `7*4`($inp),$a3
vshd $X[0],$X[1],$X[0]
vshd $X[1],$t2,$X[1]
stw $X[0],`-$XOFF+0*4`(%sp)
ldw `8*4`($inp),$t0
vshd $t2,$t3,$t2
stw $X[1],`-$XOFF+1*4`(%sp)
ldw `9*4`($inp),$t1
vshd $t3,$a0,$t3
___
{
my @t=($t2,$t3,$a0,$a1,$a2,$a3,$t0,$t1);
for ($i=2;$i<=(128/4-8);$i++) {
$code.=<<___;
stw $t[0],`-$XOFF+$i*4`(%sp)
ldw `(8+$i)*4`($inp),$t[0]
vshd $t[1],$t[2],$t[1]
___
push(@t,shift(@t));
}
for (;$i<(128/4-1);$i++) {
$code.=<<___;
stw $t[0],`-$XOFF+$i*4`(%sp)
vshd $t[1],$t[2],$t[1]
___
push(@t,shift(@t));
}
$code.=<<___;
b L\$collected_pa1
stw $t[0],`-$XOFF+$i*4`(%sp)
___
}
$code.=<<___;
L\$aligned_pa1
ldw `0*4`($inp),$X[0]
ldw `1*4`($inp),$X[1]
ldw `2*4`($inp),$t2
ldw `3*4`($inp),$t3
ldw `4*4`($inp),$a0
ldw `5*4`($inp),$a1
ldw `6*4`($inp),$a2
ldw `7*4`($inp),$a3
stw $X[0],`-$XOFF+0*4`(%sp)
ldw `8*4`($inp),$t0
stw $X[1],`-$XOFF+1*4`(%sp)
ldw `9*4`($inp),$t1
___
{
my @t=($t2,$t3,$a0,$a1,$a2,$a3,$t0,$t1);
for ($i=2;$i<(128/4-8);$i++) {
$code.=<<___;
stw $t[0],`-$XOFF+$i*4`(%sp)
ldw `(8+$i)*4`($inp),$t[0]
___
push(@t,shift(@t));
}
for (;$i<128/4;$i++) {
$code.=<<___;
stw $t[0],`-$XOFF+$i*4`(%sp)
___
push(@t,shift(@t));
}
$code.="L\$collected_pa1\n";
}
for($i=0;$i<16;$i++) { &ROUND_00_15_pa1($i,@V); unshift(@V,pop(@V)); unshift(@V,pop(@V)); }
$code.="L\$rounds_pa1\n";
for(;$i<32;$i++) { &ROUND_16_xx_pa1($i,@V); unshift(@V,pop(@V)); unshift(@V,pop(@V)); }
$code.=<<___;
$POP `-$FRAME_MARKER-2*$SIZE_T`(%sp),$ctx ; restore arguments
$POP `-$FRAME_MARKER-3*$SIZE_T`(%sp),$inp
$POP `-$FRAME_MARKER-4*$SIZE_T`(%sp),$num
ldo `-$rounds*$SZ`($Tbl),$Tbl ; rewind $Tbl
ldw `0*4`($ctx),$t1 ; update context
ldw `1*4`($ctx),$t0
ldw `2*4`($ctx),$t3
ldw `3*4`($ctx),$t2
ldw `4*4`($ctx),$a1
ldw `5*4`($ctx),$a0
ldw `6*4`($ctx),$a3
add $t0,$Alo,$Alo
ldw `7*4`($ctx),$a2
addc $t1,$Ahi,$Ahi
ldw `8*4`($ctx),$t1
add $t2,$Blo,$Blo
ldw `9*4`($ctx),$t0
addc $t3,$Bhi,$Bhi
ldw `10*4`($ctx),$t3
add $a0,$Clo,$Clo
ldw `11*4`($ctx),$t2
addc $a1,$Chi,$Chi
ldw `12*4`($ctx),$a1
add $a2,$Dlo,$Dlo
ldw `13*4`($ctx),$a0
addc $a3,$Dhi,$Dhi
ldw `14*4`($ctx),$a3
add $t0,$Elo,$Elo
ldw `15*4`($ctx),$a2
addc $t1,$Ehi,$Ehi
stw $Ahi,`0*4`($ctx)
add $t2,$Flo,$Flo
stw $Alo,`1*4`($ctx)
addc $t3,$Fhi,$Fhi
stw $Bhi,`2*4`($ctx)
add $a0,$Glo,$Glo
stw $Blo,`3*4`($ctx)
addc $a1,$Ghi,$Ghi
stw $Chi,`4*4`($ctx)
add $a2,$Hlo,$Hlo
stw $Clo,`5*4`($ctx)
addc $a3,$Hhi,$Hhi
stw $Dhi,`6*4`($ctx)
ldo `16*$SZ`($inp),$inp ; advance $inp
stw $Dlo,`7*4`($ctx)
stw $Ehi,`8*4`($ctx)
stw $Elo,`9*4`($ctx)
stw $Fhi,`10*4`($ctx)
stw $Flo,`11*4`($ctx)
stw $Ghi,`12*4`($ctx)
stw $Glo,`13*4`($ctx)
stw $Hhi,`14*4`($ctx)
comb,= $inp,$num,L\$done
stw $Hlo,`15*4`($ctx)
b L\$oop_pa1
$PUSH $inp,`-$FRAME_MARKER-3*$SIZE_T`(%sp) ; save $inp
L\$done
___
}}
$code.=<<___;
$POP `-$FRAME-$SAVED_RP`(%sp),%r2 ; standard epilogue
$POP `-$FRAME+1*$SIZE_T`(%sp),%r4
$POP `-$FRAME+2*$SIZE_T`(%sp),%r5
$POP `-$FRAME+3*$SIZE_T`(%sp),%r6
$POP `-$FRAME+4*$SIZE_T`(%sp),%r7
$POP `-$FRAME+5*$SIZE_T`(%sp),%r8
$POP `-$FRAME+6*$SIZE_T`(%sp),%r9
$POP `-$FRAME+7*$SIZE_T`(%sp),%r10
$POP `-$FRAME+8*$SIZE_T`(%sp),%r11
$POP `-$FRAME+9*$SIZE_T`(%sp),%r12
$POP `-$FRAME+10*$SIZE_T`(%sp),%r13
$POP `-$FRAME+11*$SIZE_T`(%sp),%r14
$POP `-$FRAME+12*$SIZE_T`(%sp),%r15
$POP `-$FRAME+13*$SIZE_T`(%sp),%r16
$POP `-$FRAME+14*$SIZE_T`(%sp),%r17
$POP `-$FRAME+15*$SIZE_T`(%sp),%r18
bv (%r2)
.EXIT
$POPMB -$FRAME(%sp),%r3
.PROCEND
.STRINGZ "SHA`64*$SZ` block transform for PA-RISC, CRYPTOGAMS by <appro\@openssl.org>"
___
# Explicitly encode PA-RISC 2.0 instructions used in this module, so
# that it can be compiled with .LEVEL 1.0. It should be noted that I
# wouldn't have to do this, if GNU assembler understood .ALLOW 2.0
# directive...
my $ldd = sub {
my ($mod,$args) = @_;
my $orig = "ldd$mod\t$args";
if ($args =~ /(\-?[0-9]+)\(%r([0-9]+)\),%r([0-9]+)/) # format 3 suffices
{ my $opcode=(0x14<<26)|($2<<21)|($3<<16)|(($1&0x1FF8)<<1)|(($1>>13)&1);
$opcode|=(1<<3) if ($mod =~ /^,m/);
$opcode|=(1<<2) if ($mod =~ /^,mb/);
sprintf "\t.WORD\t0x%08x\t; %s",$opcode,$orig;
}
else { "\t".$orig; }
};
my $std = sub {
my ($mod,$args) = @_;
my $orig = "std$mod\t$args";
if ($args =~ /%r([0-9]+),(\-?[0-9]+)\(%r([0-9]+)\)/) # format 3 suffices
{ my $opcode=(0x1c<<26)|($3<<21)|($1<<16)|(($2&0x1FF8)<<1)|(($2>>13)&1);
sprintf "\t.WORD\t0x%08x\t; %s",$opcode,$orig;
}
else { "\t".$orig; }
};
my $extrd = sub {
my ($mod,$args) = @_;
my $orig = "extrd$mod\t$args";
# I only have ",u" completer, it's implicitly encoded...
if ($args =~ /%r([0-9]+),([0-9]+),([0-9]+),%r([0-9]+)/) # format 15
{ my $opcode=(0x36<<26)|($1<<21)|($4<<16);
my $len=32-$3;
$opcode |= (($2&0x20)<<6)|(($2&0x1f)<<5); # encode pos
$opcode |= (($len&0x20)<<7)|($len&0x1f); # encode len
sprintf "\t.WORD\t0x%08x\t; %s",$opcode,$orig;
}
elsif ($args =~ /%r([0-9]+),%sar,([0-9]+),%r([0-9]+)/) # format 12
{ my $opcode=(0x34<<26)|($1<<21)|($3<<16)|(2<<11)|(1<<9);
my $len=32-$2;
$opcode |= (($len&0x20)<<3)|($len&0x1f); # encode len
$opcode |= (1<<13) if ($mod =~ /,\**=/);
sprintf "\t.WORD\t0x%08x\t; %s",$opcode,$orig;
}
else { "\t".$orig; }
};
my $shrpd = sub {
my ($mod,$args) = @_;
my $orig = "shrpd$mod\t$args";
if ($args =~ /%r([0-9]+),%r([0-9]+),([0-9]+),%r([0-9]+)/) # format 14
{ my $opcode=(0x34<<26)|($2<<21)|($1<<16)|(1<<10)|$4;
my $cpos=63-$3;
$opcode |= (($cpos&0x20)<<6)|(($cpos&0x1f)<<5); # encode sa
sprintf "\t.WORD\t0x%08x\t; %s",$opcode,$orig;
}
elsif ($args =~ /%r([0-9]+),%r([0-9]+),%sar,%r([0-9]+)/) # format 11
{ sprintf "\t.WORD\t0x%08x\t; %s",
(0x34<<26)|($2<<21)|($1<<16)|(1<<9)|$3,$orig;
}
else { "\t".$orig; }
};
sub assemble {
my ($mnemonic,$mod,$args)=@_;
my $opcode = eval("\$$mnemonic");
ref($opcode) eq 'CODE' ? &$opcode($mod,$args) : "\t$mnemonic$mod\t$args";
}
foreach (split("\n",$code)) {
s/\`([^\`]*)\`/eval $1/ge;
s/shd\s+(%r[0-9]+),(%r[0-9]+),([0-9]+)/
$3>31 ? sprintf("shd\t%$2,%$1,%d",$3-32) # rotation for >=32
: sprintf("shd\t%$1,%$2,%d",$3)/e or
# translate made up instructons: _ror, _shr, _align, _shl
s/_ror(\s+)(%r[0-9]+),/
($SZ==4 ? "shd" : "shrpd")."$1$2,$2,"/e or
s/_shr(\s+%r[0-9]+),([0-9]+),/
$SZ==4 ? sprintf("extru%s,%d,%d,",$1,31-$2,32-$2)
: sprintf("extrd,u%s,%d,%d,",$1,63-$2,64-$2)/e or
s/_align(\s+%r[0-9]+,%r[0-9]+),/
($SZ==4 ? "vshd$1," : "shrpd$1,%sar,")/e or
s/_shl(\s+%r[0-9]+),([0-9]+),/
$SIZE_T==4 ? sprintf("zdep%s,%d,%d,",$1,31-$2,32-$2)
: sprintf("depd,z%s,%d,%d,",$1,63-$2,64-$2)/e;
s/^\s+([a-z]+)([\S]*)\s+([\S]*)/&assemble($1,$2,$3)/e if ($SIZE_T==4);
s/cmpb,\*/comb,/ if ($SIZE_T==4);
s/\bbv\b/bve/ if ($SIZE_T==8);
print $_,"\n";
}
close STDOUT;
| domenicosolazzo/philocademy | venv/src/node-v0.10.36/deps/openssl/openssl/crypto/sha/asm/sha512-parisc.pl | Perl | mit | 21,242 |
# **************************************************************************** #
# #
# ::: :::::::: #
# main.pl :+: :+: :+: #
# +:+ +:+ +:+ #
# By: htindon <htindon@student.42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2014/07/22 14:30:24 by htindon #+# #+# #
# Updated: 2014/07/22 15:06:05 by htindon ### ########.fr #
# #
# **************************************************************************** #
use strict;
use warnings;
require 'srcs/toolbox.pl';
print_data("test");
| htindon/GeneaProject | srcs/main.pl | Perl | mit | 967 |
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Std;
use Config::Tiny;
use Cwd;
use FindBin qw($Bin);
############## Begin variables ##############
my (%opt, $seqFile, $confFile, $species, $verbose, $method);
our (%stats, $conf, $outfile);
my $defaultConf = "$Bin/../include/default.conf";
getopts('f:o:c:s:a:vh', \%opt);
var_check();
#Initialize stats hash, stores summary statistics for the run
# hits = genome hits
# hit_reads = reads that have hits
# nohits = sequences without hits
# nohit_reads = reads without hits
$stats{'hits'} = 0;
$stats{'hit_reads'} = 0;
$stats{'nohits'} = 0;
$stats{'nohit_reads'} = 0;
# Get configuration settings
my $Conf = Config::Tiny->read($confFile);
$conf = $Conf->{$species};
############## End variables ##############
############## Begin main program ##############
# Parse method input to determine the subroutine to use to align the input file
if ($method eq 'bowtie') {
bowtie($seqFile);
} else {
print STDERR " Alignment method type $method is not currently supported.\n\n";
var_error();
}
# Print out the run statistics
while (my ($k, $v) = each(%stats)) {
print $k." => ".$v."\n";
}
exit;
############## End main program ##############
############## Begin subroutines ##############
sub bowtie {
my $file = shift;
my $db = $conf->{'bowtieDB'};
if (!$db) {
print STDERR " Bowtie database $db is not defined in $confFile.\n\n";
var_error();
}
open (OUT, ">$outfile") or die " Cannot open file $outfile: $!\n\n";
# Run bowtie, parse output
#open BOW, "$Conf->{'PIPELINE'}->{'bowtie'} -f -n 0 -a -S --best $db $file |";
# Options
# -f Input file is FASTA
# -v 0 Report ungapped alignments with zero mismatches
# -a Report all alignments, limited by -v 0
# -S Output alignments in SAM format
# -p 4 Use four CPUs
#open BOW, "$Conf->{'PIPELINE'}->{'bowtie'} -f -v 0 -a -S -p 4 $db $file |";
open BOW, "$Conf->{'PIPELINE'}->{'bowtie'} -f -v 0 -a -S -p 1 $db $file |";
while (my $row = <BOW>) {
if (substr($row,0,1) eq '@') {
print OUT $row;
} else {
my @fields = split /\t/, $row;
my ($id, $reads) = split /:/, $fields[0];
if ($fields[2] eq '*') {
$stats{'nohits'}++;
$stats{'nohit_reads'} += $reads;
} elsif ($fields[5] !~ /^\d+M$/) {
print $row;
exit;
} else {
$stats{'hits'}++;
$stats{'hit_reads'} += $reads;
print OUT $row;
}
}
}
close BOW;
close OUT;
}
# var_check parses command-line options
# Activates var_error if required options missing, sets defaults
sub var_check {
if ($opt{'h'}) {
var_error();
}
if ($opt{'f'}) {
$seqFile = $opt{'f'};
} else {
var_error();
}
if ($opt{'v'}) {
$verbose = 1;
} else {
# Verbose output is off by default
$verbose = 0;
}
if ($opt{'o'}) {
$outfile = $opt{'o'};
} else {
var_error();
}
if ($opt{'c'}) {
$confFile = $opt{'c'};
} else {
# Default conf file
$confFile = $defaultConf;
}
if ($opt{'s'}) {
$species = $opt{'s'};
} else {
var_error();
}
if ($opt{'a'}) {
$method = $opt{'a'};
} else {
$method = 'bowtie';
}
}
# var_error prints out command-line options, defaults, optional settings
sub var_error {
print STDERR "\n\n";
print STDERR " This script will align reads to a reference genome and process the hits.\n";
print STDERR " Usage: Align.pl -f <sequence file> -o\n\n";
print STDERR " -f Input sequence file\n\n";
print STDERR " -o Output file name.\n\n";
print STDERR " -s Species code. Example: A_THALIANA\n\n";
print STDERR " -c Configuration file. Default = $defaultConf\n\n";
print STDERR " -a Alignment method. Default = bowtie.\n";
print STDERR " Current methods: bowtie\n\n";
print STDERR " -v Verbose output. Prints program status to terminal. Default is quiet.\n\n";
print STDERR " -h Print this menu\n\n";
exit 1;
}
| nfahlgren/srtools | bin/Align.pl | Perl | mit | 3,993 |
use warnings;
use LangIDTable;
use HCParser;
use IO::Handle;
use Getopt::Long;
STDOUT->autoflush(1);
my $batch_size = 2;
my $showHelp = 0;
GetOptions('batch=i' => \$batch_size,
'predictor=s' => \$LangIDTable::predictor,
'help' => \$showHelp);
if ($showHelp)
{
print <<HERE;
perl $0 [options] LangID_model_dir Twitter_Manifest
Test the language ID models in specified dir against
the Twitter samples specified in the Twitter Manifest.
HERE
exit;
}
my ($model_dir, @hc_twitter_files) = @ARGV;
opendir $model_dh, $model_dir;
my @model_files = readdir $model_dh;
closedir $model_dh;
@model_files = grep /\.lid$/, @model_files;
my $lang_codes = {};
print "Loading models...\n";
foreach my $file (@model_files)
{
my $model = new LangIDTable('xx', 'xx');
$model->load("$model_dir/$file");
$lang_codes->{$model->{'code2'}} = $model->{'name'};
push @models, $model;
}
my $parser = new HCParser;
if (@hc_twitter_files == 1 and $hc_twitter_files[0] =~ /\.manifest$/)
{
open my $in, $hc_twitter_files[0];
@hc_twitter_files = map { s/[\r\n]+//; $_ } <$in>;
close $in;
}
foreach my $hc_file (@hc_twitter_files)
{
$hc_file =~ s/\/cygdrive\/(\w)/\u$1:/i;
unless ($hc_file =~ /(?:^|\\|\/)(\w{2,3})_twitter.txt$/i)
{
warn "$hc_file doesn't match expected pattern for twitter data\n";
next;
}
my $correct_lid = lc $1;
print "Processing $lang_codes->{$correct_lid} ($correct_lid) ...\n";
$parser->open($hc_file);
my $classified_as = { $correct_lid => 0 };
my $total = 0;
my $batch_index = 0;
my $text = '';
while (my $values = $parser->read())
{
if (++$batch_index < $batch_size)
{
$text .= "$values->{text}\n";
}
else
{
$text .= "$values->{text}\n";
# test each model against this file
my @scored_models = ();
foreach my $model (@models)
{
push @scored_models, [ $model, $model->score($text) ];
}
@scored_models = sort { $b->[1] <=> $a->[1] } @scored_models;
my $class_name = $scored_models[0]->[0]->{'code2'};
if ($scored_models[0]->[1] < 0.1 * LangIDTable::get_max_score())
{
$class_name = 'unknown';
}
$classified_as->{$class_name}++;
$total++;
throttled_print('accuracy', 2, sprintf("Precision for $correct_lid thus far: %.1f%% (%d/%d)\n", 100 * $classified_as->{$correct_lid} / $total, $classified_as->{$correct_lid}, $total));
$text = "";
$batch_index = 0;
last if ($total >= 10000 / $batch_size);
}
}
print "$correct_lid $total classifications:\n";
my @langs = sort { $classified_as->{$b} <=> $classified_as->{$a} } keys %$classified_as;
for (my $i = 0; $i < @langs and $i < 10; $i++)
{
printf "\t%s: %.1f%% (%d)\n", $langs[$i], 100 * $classified_as->{$langs[$i]} / $total, $classified_as->{$langs[$i]};
}
$parser->close($hc_file);
$overalls->{$correct_lid} = $classified_as;
}
print "\n";
my $total = 0;
my $correct = 0;
foreach my $lid (keys %$overalls)
{
my $total_lang = 0;
foreach my $class (keys %{$overalls->{$lid}})
{
if ($class eq $lid)
{
$correct += $overalls->{$lid}->{$class};
}
$total += $overalls->{$lid}->{$class};
$total_lang += $overalls->{$lid}->{$class};
}
printf "Accuracy for %s (%s): %.1f%%\n", $lang_codes->{$lid}, $lid, 100 * $overalls->{$lid}->{$lid} / $total_lang;
}
printf "\nOverall accuracy: %.1f%%\n", 100 * $correct / $total;
sub throttled_print
{
my ($id, $interval, $message) = @_;
if (not defined $throttled_print_tracker->{$id} or time() - $throttled_print_tracker->{$id} >= $interval)
{
print $message;
$throttled_print_tracker->{$id} = time();
}
} | ktrnka/droidling | training/perl/test_twitter.pl | Perl | mit | 3,601 |
:- expects_dialect(lps).
% Exemplify external events defined as (polled) Prolog predicates
% TODO: We need more control over this, to specify predicates and their calling patterns
maxTime(5).
prolog_events myEvent(2,_).
if myEvent(X,Y) from _ to _ then writeln(X-Y) from T2.
% no facts here please, otherwise they'll be taken as macro action clauses:
myEvent(1,hello) :- true.
myEvent(2,ola) :- true.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_lps/examples/forTesting/externalPrologEvents.pl | Perl | mit | 404 |
#!/usr/bin/perl
use strict;
use warnings;
### Example for combination of query() and cmd(): set name of ethernet interface by default-name
use MikroTik::API;
if ( not ( defined $ARGV[0] && defined $ARGV[1] ) ) {
die 'USAGE: $0 <default name> <new name>';
}
my $api = MikroTik::API->new({
host => 'mikrotik.example.org',
username => 'whoami',
password => 'SECRET',
use_ssl => 1,
});
my ( $ret_interface_print, @interfaces ) = $api->query('/interface/print', { '.proplist' => '.id,name' }, { type => 'ether', 'default-name' => $ARGV[0] } );
if( $interfaces[0]->{name} eq $ARGV[1] ) {
print "Name is already set to this value\n";
}
else {
my $ret_set_interface = $api->cmd( '/interface/ethernet/set', { '.id' => $interfaces[0]->{'.id'}, 'name' => $ARGV[1] } );
print "Name changed\n";
}
$api->logout();
| martin8883/MikroTik-API | eg/set_ethernet_name.pl | Perl | mit | 814 |
=pod
=head1 NAME
SSL_set_connect_state, SSL_set_accept_state - prepare SSL object to work in client or server mode
=head1 SYNOPSIS
#include <openssl/ssl.h>
void SSL_set_connect_state(SSL *ssl);
void SSL_set_accept_state(SSL *ssl);
=head1 DESCRIPTION
SSL_set_connect_state() sets B<ssl> to work in client mode.
SSL_set_accept_state() sets B<ssl> to work in server mode.
=head1 NOTES
When the SSL_CTX object was created with L<SSL_CTX_new(3)>,
it was either assigned a dedicated client method, a dedicated server
method, or a generic method, that can be used for both client and
server connections. (The method might have been changed with
L<SSL_CTX_set_ssl_version(3)> or
SSL_set_ssl_method().)
When beginning a new handshake, the SSL engine must know whether it must
call the connect (client) or accept (server) routines. Even though it may
be clear from the method chosen, whether client or server mode was
requested, the handshake routines must be explicitly set.
When using the L<SSL_connect(3)> or
L<SSL_accept(3)> routines, the correct handshake
routines are automatically set. When performing a transparent negotiation
using L<SSL_write(3)> or L<SSL_read(3)>, the
handshake routines must be explicitly set in advance using either
SSL_set_connect_state() or SSL_set_accept_state().
=head1 RETURN VALUES
SSL_set_connect_state() and SSL_set_accept_state() do not return diagnostic
information.
=head1 SEE ALSO
L<ssl(3)>, L<SSL_new(3)>, L<SSL_CTX_new(3)>,
LL<SSL_connect(3)>, L<SSL_accept(3)>,
L<SSL_write(3)>, L<SSL_read(3)>,
L<SSL_do_handshake(3)>,
L<SSL_CTX_set_ssl_version(3)>
=cut
| vbloodv/blood | extern/openssl.orig/doc/ssl/SSL_set_connect_state.pod | Perl | mit | 1,609 |
package Play::Route::Feeds;
use Dancer ':syntax';
prefix '/api';
use Play::DB qw(db);
get '/feed' => sub {
return db->feeds->feed({
limit => 30,
map { param($_) ? ( $_ => param($_) ): () } qw/ limit offset for realm tab /,
});
};
true;
| berekuk/questhub | app/lib/Play/Route/Feeds.pm | Perl | mit | 264 |
package App::perlbrew;
use strict;
use 5.8.0;
our $VERSION = "0.03";
my $ROOT = $ENV{PERLBREW_ROOT} || "$ENV{HOME}/perl5/perlbrew";
my $CURRENT_PERL = "$ROOT/perls/current";
sub run_command {
my ( undef, $opt, $x, @args ) = @_;
$opt->{log_file} = "$ROOT/build.log";
my $self = bless $opt, __PACKAGE__;
$x ||= "help";
my $s = $self->can("run_command_$x") or die "Unknow command: `$x`. Typo?";
$self->$s(@args);
}
sub run_command_help {
print <<HELP;
perlbrew - $VERSION
Usage:
# Read more help
perlbrew -h
perlbrew init
perlbrew install perl-5.11.5
perlbrew install perl-5.12.0-RC0
perlbrew installed
perlbrew switch perl-5.12.0-RC0
perlbrew switch /usr/bin/perl
perlbrew off
HELP
}
sub run_command_init {
require File::Path;
File::Path::make_path(
"$ROOT/perls", "$ROOT/dists", "$ROOT/build", "$ROOT/etc",
"$ROOT/bin"
);
system <<RC;
echo 'export PATH=$ROOT/bin:$ROOT/perls/current/bin:\${PATH}' > $ROOT/etc/bashrc
echo 'setenv PATH $ROOT/bin:$ROOT/perls/current/bin:\$PATH' > $ROOT/etc/cshrc
RC
my ( $shrc, $yourshrc );
if ( $ENV{SHELL} =~ /(t?csh)/ ) {
$shrc = 'cshrc';
$yourshrc = $1 . "rc";
}
else {
$shrc = $yourshrc = 'bashrc';
}
print <<INSTRUCTION;
Perlbrew environment initiated, required directories are created under
$ROOT
Well-done! Congratulations! Please add the following line to the end
of your ~/.${yourshrc}
source $ROOT/etc/${shrc}
After that, exit this shell, start a new one, and install some fresh
perls:
perlbrew install perl-5.12.0-RC0
perlbrew install perl-5.10.1
For further instructions, simply run:
perlbrew
The default help messages will popup an tell you what to do!
Enjoy perlbrew at \$HOME!!
INSTRUCTION
}
sub run_command_install {
my ( $self, $dist, $opts ) = @_;
unless ($dist) {
require File::Spec;
require File::Path;
require File::Copy;
my $executable = $0;
unless (File::Spec->file_name_is_absolute($executable)) {
$executable = File::Spec->rel2abs($executable);
}
my $target = File::Spec->catfile($ROOT, "bin", "perlbrew");
if ($executable eq $target) {
print "You are already running the installed perlbrew:\n\n $executable\n";
exit;
}
File::Path::make_path("$ROOT/bin");
File::Copy::copy($executable, $target);
chmod(0755, $target);
print <<HELP;
The perlbrew is installed as:
$target
You may trash the downloaded $executable from now on.
Next, if this is the first time you run perlbrew installation, run:
$target init
And follow the instruction on screen.
HELP
return;
}
my ($dist_name, $dist_version) = $dist =~ m/^(.*)-([\d.]+)(?:-RC\d+)?$/;
if ($dist_name eq 'perl') {
require HTTP::Lite;
my $http_get = sub {
my ($url, $cb) = @_;
my $ua = HTTP::Lite->new;
my $loc = $url;
my $status = $ua->request($loc) or die "Fail to get $loc";
my $redir_count = 0;
while ($status == 302 || $status == 301) {
last if $redir_count++ > 5;
for ($ua->headers_array) {
/Location: (\S+)/ and $loc = $1, last;
}
$loc or last;
$status = $ua->request($loc) or die "Fail to get $loc";
}
if ($cb) {
return $cb->($ua->body);
}
return $ua->body;
};
my $html = $http_get->("http://search.cpan.org/dist/$dist");
my ($dist_path, $dist_tarball) =
$html =~ m[<a href="(/CPAN/authors/id/.+/(${dist}.tar.(gz|bz2)))">Download</a>];
print "Fetching $dist as ${ROOT}/dists/${dist_tarball}\n";
$http_get->(
"http://search.cpan.org${dist_path}",
sub {
my ($body) = @_;
open my $BALL, "> ${ROOT}/dists/${dist_tarball}";
print $BALL $body;
close $BALL;
}
);
my $usedevel = $dist_version =~ /5\.11/ ? "-Dusedevel" : "";
my @d_options = @{ $self->{D} };
my $as = $self->{as} || $dist;
unshift @d_options, qq(prefix=$ROOT/perls/$as);
push @d_options, "usedevel" if $dist_version =~ /5\.11/;
print "Installing $dist...";
my $tarx = "tar " . ( $dist_tarball =~ /bz2/ ? "xjf" : "xzf" );
my $cmd = join ";",
(
"cd $ROOT/build",
"$tarx $ROOT/dists/${dist_tarball}",
"cd $dist",
"rm -f config.sh Policy.sh",
"sh Configure -de " . join( ' ', map { "-D$_" } @d_options ),
"make",
(
$self->{force}
? ( 'make test', 'make install' )
: "make test && make install"
)
);
$cmd = "($cmd) >> '$self->{log_file}' 2>&1 "
if ( $self->{quiet} && !$self->{verbose} );
system($cmd);
}
}
sub run_command_installed {
my $self = shift;
my $current = readlink("$ROOT/perls/current");
for (<$ROOT/perls/*>) {
next if m/current/;
my ($name) = $_ =~ m/\/([^\/]+$)/;
print $name, ( $name eq $current ? '(*)' : '' ), "\n";
}
my $current_perl_executable = readlink("$ROOT/bin/perl");
for ( grep { -x $_ } map { "$_/perl" } split(":", $ENV{PATH}) ) {
print $_, ($current_perl_executable eq $_ ? "(*)" : ""), "\n";
}
}
sub run_command_switch {
my ( $self, $dist ) = @_;
if (-x $dist) {
unlink "$ROOT/perls/current";
system "ln -fs $dist $ROOT/bin/perl";
print "Switched to $dist\n";
return;
}
die "${dist} is not installed\n" unless -d "$ROOT/perls/${dist}";
unlink "$ROOT/perls/current";
system "cd $ROOT/perls; ln -s $dist current";
for my $executable (<$ROOT/perls/current/bin/*>) {
my ($name) = $executable =~ m/bin\/(.+?)(5\.\d.*)?$/;
my $target = "$ROOT/bin/${name}";
next unless -l $target || !-e $target;
system("ln -fs $executable $target");
}
}
sub run_command_off {
local $_ = "$ROOT/perls/current";
unlink if -l;
for my $executable (<$ROOT/bin/*>) {
unlink($executable) if -l $executable;
}
}
1;
__END__
=head1 NAME
App::perlbrew - Manage perl installations in your $HOME
=head1 SYNOPSIS
# Initialize
perlbrew init
# Install some Perls
perlbrew install perl-5.8.1
perlbrew install perl-5.11.5
# See what were installed
perlbrew installed
# Switch perl in the $PATH
perlbrew switch perl-5.11.5
perl -v
# Switch to another version
perlbrew switch perl-5.8.1
perl -v
# Switch to a certain perl executable not managed by perlbrew.
perlbrew switch /usr/bin/perl
# Or turn it off completely. Useful when you messed up too deep.
perlbrew off
# Use 'switch' command to turn it back on.
perlbrew switch perl-5.11.5
=head1 DESCRIPTION
perlbrew is a program to automate the building and installation of
perl in the users HOME. At the moment, it installs everything to
C<~/perl5/perlbrew>, and requires you to tweak your PATH by including a
bashrc/cshrc file it provides. You then can benefit from not having
to run 'sudo' commands to install cpan modules because those are
installed inside your HOME too. It's almost like an isolated perl
environments.
=head1 INSTALLATION
The recommended way to install perlbrew is to run these statements in
your shell:
curl -LO http://xrl.us/perlbrew
chmod +x perlbrew
./perlbrew install
After that, C<perlbrew> installs itself to C<~/perl5/perlbrew/bin>,
and you should follow the instruction on screen to setup your
C<.bashrc> or C<.cshrc> to put it in your PATH.
The downloaded perlbrew is a self-contained standalone program that
embed all non-core modules it uses. It should be runnable with perl
5.8 or high versions of perls.
You may also install perlbrew from CPAN with cpan / cpanp / cpanm:
cpan App::perlbrew
This installs 'perlbrew' into your current PATH and it is always
executed with your current perl.
=head1 USAGE
Please read the program usage by running
perlbrew
(No arguments.) To read a more detail one:
perlbrew -h
Alternatively, this should also do:
perldoc perlbrew
If you messed up to much or get confused by having to many perls
installed, you can do:
perlbrew switch /usr/bin/perl
It will make sure that your current perl in the PATH is pointing
to C</usr/bin/perl>.
As a matter of fact the C<switch> command checks whether the given
argument is an executale or not, and create a symlink named 'perl' to
it if it is. If you really want to you are able to do:
perlbrew switch /usr/bin/perl6
But maybe not. After running this you might not be able to run
perlbrew anymore. So be careful not making mistakes there.
=head1 AUTHOR
Kang-min Liu C<< <gugod@gugod.org> >>
=head1 COPYRIGHT
Copyright (c) 2010, Kang-min Liu C<< <gugod@gugod.org> >>.
The standalone executable contains the following modules embedded.
=over 4
=item L<HTTP::Lite>
Copyright (c) 2000-2002 Roy Hopper, 2009 Adam Kennedy.
Licensed under the same term as Perl itself.
=back
=head1 LICENCE
The MIT License
=head1 CONTRIBUTORS
Patches and code improvements were contributed by:
Tatsuhiko Miyagawa, Chris Prather
=head1 DISCLAIMER OF WARRANTY
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR, OR CORRECTION.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
| yanick/App-perlbrew | lib/App/perlbrew.pm | Perl | mit | 10,788 |
#!/usr/bin/env perl
package Ref;
use Modern::Perl;
use Ref;
sub gff {
my ($self, $prefix, $genome) = @_;
my $id = "";
my ($idt, $ind, $chr, %index);
open GFF, "$prefix/reference/".$genome."_genes.gff" or die $!;
while(my $aa = <GFF>){
chomp $aa;
my @row = split /\t/, $aa;
next if($row[2] =~ /UTR/ || $row[2] =~ /c_transcript/ || $row[2] =~ /region/);
next if($row[2] eq "protein" || $row[2] eq "CDS" ||$row[2] =~ /[^i]RNA/);
if($row[2] =~ /gene/){
if($row[8] =~ /^ID=(\w+);/o){
$id = $1;
$ind = int($row[3]/100000);
$chr = $row[0];
$index{$chr}{$ind}{$id}{start} = $row[3];
$index{$chr}{$ind}{$id}{end} = $row[4];
$index{$chr}{$ind+1}{$id}{start} = $row[3];
$index{$chr}{$ind+1}{$id}{end} = $row[4];
$index{$chr}{$ind-1}{$id}{start} = $row[3];
$index{$chr}{$ind-1}{$id}{end} = $row[4];
}
}elsif($row[8] =~ /Parent=$id/){
$index{$chr}{$ind}{$id}{exon} .= $row[3]."\t".$row[4].";";
$index{$chr}{$ind+1}{$id}{exon} .= $row[3]."\t".$row[4].";";
$index{$chr}{$ind-1}{$id}{exon} .= $row[3]."\t".$row[4].";";
}
}
close GFF;
return %index;
}
sub exons {
my ($self, $prefix, $genome) = @_;
system ("gffread -w exons.fa -g ".$prefix."/reference/".$genome."_chr_all.fasta ".$prefix."/reference/".$genome."_genes.gff");
open EXON, "<exons.fa" or die $!;
my (%exon, $gene, $tran);
while(my $exo = <EXON>){
chomp $exo;
if($exo =~ />(\w+)\.(\d+)/){
$gene = $1;
$tran = $2;
}elsif($exo=~ />(\w+)/){
$gene = $1;
$tran = 0;
}else{
$exon{$gene}{$tran} .= $exo;
}
}
close EXON;
unlink "exons.fa";
return %exon;
}
sub fas {
my ($self, $prefix, $genome) = @_;
my (%fas, $nam);
open FAS, $prefix."/reference/".$genome."_chr_all.fasta" or die $!;
while (my $line = <FAS>){
chomp $line;
if($line =~ />(.+)/){
$nam = $1;
$fas{$nam} = "";
}else{
$fas{$nam} .= $line;
}
}
close FAS;
return %fas;
}
sub geneinfo {
my ($self, $prefix, $genome) = @_;
my %geneinfo;
open TRA, ">transcripts.fa" or die $!;
my %exon = &exons($self, $prefix, $genome);
foreach my $gene (sort keys %exon){
my $long = 0;
my ($longt, $longtr);
foreach my $tran (keys %{$exon{$gene}}){
if(length($exon{$gene}{$tran}) > $long){
$long = length $exon{$gene}{$tran};
$longt = $exon{$gene}{$tran};
$longtr = $tran;
}
}
$geneinfo{$gene} = $long;
if($longtr){
print TRA ">$gene\.$longtr\n$longt\n";
}else{
print TRA ">$gene\n$longt\n";
}
}
close TRA;
return %geneinfo;
}
sub mir {
my ($self, $prefix, $genome) = @_;
open GFF, "$prefix/reference/$genome\_miRNA_miRNA_star.gff" or die $!;
my %mir;
while (my $bb = <GFF>){
chomp $bb;
my @row = split /\t/, $bb;
if($row[6] eq "+"){
$mir{$row[0]}{$row[3]}{name} = $row[8];
$mir{$row[0]}{$row[3]}{strand} = 0;
$mir{$row[0]}{$row[3]}{length} = $row[4] - $row[3] + 1;
}else{
$mir{$row[0]}{$row[4]}{name} = $row[8];
$mir{$row[0]}{$row[4]}{strand} = 16;
$mir{$row[0]}{$row[4]}{length} = $row[4] - $row[3] + 1;
}
}
close GFF;
return %mir;
}
sub splitgff {
my ($self, $prefix, $genome) = @_;
open GENE, "$prefix/reference/$genome"."_genes.gff" or die $!;
open TE, "$prefix/reference/$genome"."_transposons.gff" or die $!;
open TMP1, ">gene.gff" or die $!;
open TMP2, ">promoter.gff" or die $!;
while(my $aa = <GENE>){
chomp $aa;
my @row = split /\t/, $aa;
if($row[2] =~ /gene/){
if($row[8] =~ /ID=(\w+);/o){
my $name = $1;
if($row[8] =~ /Note=transposable_element_gene;/){
$row[8] = $name."_TEG";
}else{
$row[8] = $name;
}
my $row = join "\t", @row;
print TMP1 "$row\n";
$row[8] .= "_promoter";
if($row[6] eq "+"){
$row[4] = $row[3] - 1;
if($row[3] > 1000){
$row[3] = $row[3] - 1000;
}else{
$row[3] = 1;
}
#$row[3] = $row[4] + 1;
#$row[4] = $row[3] + 1000;
}else{
$row[3] = $row[4] + 1;
$row[4] = $row[4] + 1000;
#$row[4] = $row[3] - 1;
#$row[3] = $row[4] - 1000;
}
$row = join "\t", @row;
print TMP2 "$row\n";
}
}
}
close GENE;
close TMP1;
close TMP2;
open TMP, ">te.gff" or die $!;
while(my $bb = <TE>){
chomp $bb;
my @row = split /\t/, $bb;
if($row[2] =~ /transposable_element/){
if($row[8] =~ /ID=(\w+);/o){
$row[8] = $1;
my $row = join "\t", @row;
print TMP "$row\n";
}
}
}
close TMP;
close TE;
}
sub ann {
my ($self, $prefix, $genome, $binsize) = @_;
my %ann;
if(-e $prefix."/reference/".$genome.".annotation"){
open ANN, $prefix."/reference/".$genome.".annotation" or die $!;
while (my $aa = <ANN>){
chomp $aa;
my @row = split /\t/, $aa;
my $id = shift @row;
$ann{$id} = join "\t", @row;
}
close ANN;
}else{
Ref->splitgff($prefix, $genome);
open GENE, "gene.gff" or die $!;
open TE, "te.gff" or die $!;
open PRO, "promoter.gff" or die $!;
open MIR, $prefix."/reference/".$genome."_miRNA_miRNA_star.gff" or die $!;
while (my $aa = <GENE>){
chomp $aa;
my @row = split /\t/, $aa;
my $start = int($row[3] / $binsize);
my $end = int($row[4] / $binsize);
for(my $i=$start;$i<=$end;$i++){
my $id = $row[0]."_".$i;
$ann{$id} .= "GENE:".$row[8].",";
}
}
while (my $bb = <TE>){
chomp $bb;
my @row = split /\t/, $bb;
my $start = int($row[3] / $binsize);
my $end = int($row[4] / $binsize);
for(my $i=$start;$i<=$end;$i++){
my $id = $row[0]."_".$i;
$ann{$id} .= "TE:".$row[8].",";
}
}
while (my $cc = <MIR>){
chomp $cc;
my @row = split /\t/, $cc;
my $start = int($row[3] / $binsize);
my $end = int($row[4] / $binsize);
for(my $i=$start;$i<=$end;$i++){
my $id = $row[0]."_".$i;
$ann{$id} .= $row[8].",";
}
}
while (my $dd = <PRO>){
chomp $dd;
my @row = split /\t/, $dd;
my $start = int($row[3] / $binsize);
my $end = int($row[4] / $binsize);
for(my $i=$start;$i<=$end;$i++){
my $id = $row[0]."_".$i;
$ann{$id} .= "PROMOTER:".$row[8].",";
}
}
close GENE;
close TE;
close MIR;
close PRO;
unlink ("gene.gff", "te.gff", "promoter.gff");
}
return %ann;
}
sub lengthofchrom {
my ($self, $prefix, $genome, $binsize) = @_;
my %length;
open FAI, "$prefix/reference/$genome"."_chr_all.fasta.fai" or die $!;
while (my $fai = <FAI>){
chomp $fai;
my @row = split /\t/, $fai;
$length{$row[0]} = int($row[1]/$binsize);
}
close FAI;
return %length;
}
1;
__END__
| grubbybio/RNASeqTools | Ref.pm | Perl | mit | 6,921 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.