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
package PYX; # Pragmas. use base qw(Exporter); use strict; use warnings; # Modules. use PYX::Utils qw(decode); use Readonly; # Constants. Readonly::Array our @EXPORT_OK => qw(attribute char comment end_element instruction start_element); # Version. our $VERSION = 0.06; # Encode attribute as PYX. sub attribute { my (@attr) = @_; my @ret = (); while (@attr) { my ($key, $val) = (shift @attr, shift @attr); push @ret, "A$key ".decode($val); } return @ret; } # Encode characters between elements as PYX. sub char { my $char = shift; return '-'.decode($char); } # Encode comment as PYX. sub comment { my $comment = shift; return '_'.decode($comment); } # Encode end of element as PYX. sub end_element { my $elem = shift; return ')'.$elem; } # Encode instruction as PYX. sub instruction { my ($target, $code) = @_; my $ret = '?'.decode($target); if ($code) { $ret .= ' '.decode($code); } return $ret; } # Encode begin of element as PYX. sub start_element { my ($elem, @attr) = @_; my @ret = (); push @ret, '('.$elem; if (@attr) { push @ret, attribute(@attr); } return @ret; } 1; __END__ =pod =encoding utf8 =head1 NAME PYX - A perl module for PYX handling. =head1 SYNOPSIS use PYX qw(attribute char comment end_element instruction start_element); my @data = attribute(@attr); my @data = char($char); my @data = comment($comment); my @data = end_element($elem); my @data = instruction($target, $code); my @data = start_element($elem, @attr); =head1 SUBROUTINES =over 8 =item C<attribute(@attr)> Encode attribute as PYX. Returns array of encoded lines. =item C<char($char)> Encode characters between elements as PYX. Returns array of encoded lines. =item C<comment($comment)> Encode comment as PYX. Returns array of encoded lines. =item C<end_element($elem)> Encode end of element as PYX. Returns array of encoded lines. =item C<instruction($target, $code)> Encode instruction as PYX. Returns array of encoded lines. =item C<start_element($elem, @attr)> Encode begin of element as PYX. Returns array of encoded lines. =back =head1 EXAMPLE # Pragmas. use strict; use warnings; # Modules. use PYX qw(attribute char comment end_element instruction start_element); # Example output. my @data = ( instruction('xml', 'foo'), start_element('element'), attribute('key', 'val'), comment('comment'), char('data'), end_element('element'), ); # Print out. map { print $_."\n" } @data; # Output: # ?xml foo # (element # Akey val # _comment # -data # )element =head1 DEPENDENCIES L<Exporter>, L<PYX::Utils>, L<Readonly>. =head1 SEE ALSO =over =item L<Task::PYX> Install the PYX modules. =back =head1 REPOSITORY L<https://github.com/tupinek/PYX> =head1 AUTHOR Michal Špaček L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT © 2005-2016 Michal Špaček BSD 2-Clause License =head1 VERSION 0.06 =cut
tupinek/PYX
PYX.pm
Perl
bsd-2-clause
2,980
#!/usr/bin/env perl # Pragmas. use strict; use warnings; # Modules. use Class::Utils qw(set_split_params); # Hash reference with default parameters. my $self = { 'foo' => undef, }; # Set bad params. my @other_params = set_split_params($self, 'foo', 'bar', 'bad', 'value', ); # Print out. print "Foo: $self->{'foo'}\n"; print join ': ', @other_params; print "\n"; # Output: # Foo: bar # bad: value
gitpan/Class-Utils
examples/ex4.pl
Perl
bsd-2-clause
409
#!/usr/bin/perl #***************************************************** # Author: # Lokesh Jindal # lokeshjindal15@cs.wisc.edu # May, 2015 #***************************************************** use File::Find; use File::Basename; # my $RATE_CALC_PERIOD = 0.0002; # 200us or 0.2ms if (@ARGV !=2) { print "ERROR! Provide a value for RATE_CALC_PERIOD for the rate calculator in seconds\n"; print "Usage: <script> <name of directory containing subdirectories with gem5sim.out files> <RATE_CALC_PERIOD>\n"; exit; } my $RATE_CALC_PERIOD = $ARGV[1]; my $DATA_DIR = ""; if ($ARGV[0]) { $DATA_DIR = $ARGV[0]; print "DATA_DIR being used is *$DATA_DIR*\n"; } else { print "Usage: <script> <name of directory containing subdirectories with gem5sim.out files> <RATE_CALC_PERIOD>\n"; print "Kindly enter a valid DATA_DIR to look for gem5sim.out files! Exiting ... \n"; exit; } my @out_file_list; sub wanted_files { my $file_name = $File::Find::name; #print "file_name is $file_name\n"; if (!(-d $file_name)) { # print "file_name is $file_name\n"; } if (!(-d $file_name) and ($_ =~ /gem5sim.out$/)and !($file_name =~ /switch/) and !($file_name =~ /tux4/))# ignore switch and tux4 gem5sim.out { push @out_file_list, $file_name; } } find(\&wanted_files, $DATA_DIR); $num_out_file = @out_file_list; print "number of gem5sim.out files found is $num_out_file\n"; my $l = 0; while ( $l < $num_out_file) { chomp($out_file_list[$l]); print "$out_file_list[$l]\n"; $l++; } my $OUT_FILE_I = 0; while ($OUT_FILE_I < $num_out_file) { $out_file = $out_file_list[$OUT_FILE_I]; $out_dir = dirname($out_file); $BENCHMARKS[$OUT_FILE_I] = basename ($out_dir); print "gem5sim.out file beng used is $out_file and outdir is $out_dir\n"; print "********DANGER******** Removing existing pdgem5int.csv: rm $out_dir/m5out/pdgem5int.csv\n"; `rm $out_dir/m5out/pdgem5int.csv`; if (-e "$out_dir/m5out/cum.allcores.csv") { } else { print "***** ERROR! Can't find file $out_dir/m5out/cum.allcores.csv Exiting ...\n"; exit; } if (-e "$out_dir/m5out/stats.txt") { } else { print "***** ERROR! Can't find file $out_dir/m5out/stats.txt Exiting ...\n"; exit; } # $NUMPOINTS = `cat $out_dir/m5out/cum.allcores.csv | wc -l`; # chomp($NUMPOINTS); # $NUMPOINTS = $NUMPOINTS - 1; # $ref_sim_sec = ...; # parse the cumsimseconds from the cum.all.cores.csv file $start_tick = `head -10 "$out_dir/m5out/stats.txt" | grep final_tick`; if ($start_tick =~ /.*final_tick\s+(\d{9})\d{4}/) # read only 9 digits out of 13 reported digits { $BEGIN_TICK = $1; } else { print "ERROR! Could not find final tick Exiting ...\n"; exit; } print "start_tick is $start_tick and BEGIN_TICK is $BEGIN_TICK\n"; $tail = `tail -1 "$out_dir/m5out/cum.allcores.csv"`; my @values = split(',', $tail); my $MAX_SEC = $values[0] ; # TODO FIXME get the max number of seconds from cum.allcores.csv print "TAIL is $tail and MAX_SEC is $MAX_SEC\n"; my $sec_iter = 0; @time_array = 0; $time_array[$sec_iter] = 0; while ($time_array[$sec_iter] < $MAX_SEC) { $sec_iter++; $time_array[$sec_iter] = $RATE_CALC_PERIOD + $time_array[$sec_iter - 1]; } $NUMPOINTS = $sec_iter - 1; my $MAXINTS = 0; $MAXINTS = `grep "SENDING PDGEM5INT @ TICK" $out_file | wc -l`; chomp($MAXINTS); print "Number of PDGEM5INTS in $out_file is $MAXINTS\n"; if($MAXINTS == 0) { print "***** WARNING ***** MAXINTS is $MAXINTS for file $out_file\n"; # exit; } else # generate pdgem5int.csv file since MAXINTS > 0 { open OUT_FILE, $out_file or die $!; my $line = ""; my @interrupt; my @dump_interrupt; my $int_num; $int_num = 0; while ($line = <OUT_FILE>) { if ($line =~ /.*SENDING PDGEM5INT @ TICK :(\d{9})\d{4}:/) { $interrupt[$int_num] = $1; $interrupt[$int_num] = ($1 - $BEGIN_TICK) / 100000000; # reading only 9 digits out of 13 so divide by 10^8 instead of 10^12 $int_num = $int_num + 1; # print "int_num = $int_num and interrupt is $interrupt[$int_num]\n"; } # else # { # print "ERROR! tick match failed for line $line for file $out_file\n"; # print "Exiting ...\n"; # exit; # } } close OUT_FILE; if ($int_num != $MAXINTS) { print "***** ERROR! int_num = $int_num NOT EQUAL TO MAXINTS = $MAXINTS for file $out_file Exiting ...\n"; exit; } # $int_num = 0; # my $iter = 0; # while ($iter < $NUMPOINTS) # { # if (($int_num < $MAXINTS) && ($interrupt[$int_num] < $ref_sim_sec[$iter])) # { # while (($interrupt[$int_num] < $ref_sim_sec[$iter])) # { # $dump_interrupt[$iter] = 100; # $int_num++; # $iter++; # } # } # else # { # $dump_interrupt[$iter] = 0; # $iter++; # } # } # if ($int_num != $MAXINTS) # { # print "ERROR! After populating dump_interrupt, int_num = $int_num DOES NO MATCH MAXINTS = $MAXINTS Exiting ..."; # exit; # } $int_num = 0; $iter = 0; while ($iter < $NUMPOINTS) { if (($interrupt[$int_num] < $time_array[$iter]) && ($int_num < $MAXINTS)) { $dump_interrupt[$iter] = 100; $iter++; $int_num++; } else { $dump_interrupt[$iter] = 0; $iter++; } } if ($int_num != $MAXINTS) { print "ERROR! After populating dump_interrupt, int_num = $int_num DOES NO MATCH MAXINTS = $MAXINTS Exiting ..."; exit; } print "Let's create the csv file $out_dir/m5out/pdgem5int.csv\n"; open F1, ">$out_dir/m5out/pdgem5int.csv" or die $!; print F1 "cumtime,intornot\n"; $iter = 0; while ($iter < $NUMPOINTS) { print F1 "$time_array[$iter], $dump_interrupt[$iter]\n"; $iter++; } close F1; # close $OUT_FILE; } # end of creating the pdgem5int.csv file print "########################################################################################################"; $OUT_FILE_I++; }
lokeshjindal15/pd-gem5
scripts/pd5_parse_interrupt.pl
Perl
bsd-3-clause
5,823
#!/usr/bin/perl use POSIX qw(strftime); my $date = strftime("%Y%m%d", localtime); my $user = "apache"; my $dbname = "dental"; #print $date; #`mysqldump -u apache -p --opt dental > dentpro.060423.sql my $command = "mysqldump -u $user -p --opt $dbname > dentpro.$date.sql"; #print $command; print qq/press any key to execute "$command"\n/; <STDIN>; `$command`;
mjpan/jdentpro
scripts/dbdump.pl
Perl
bsd-3-clause
369
#!/usr/bin/perl -w use strict; use Getopt::Std; use POSIX qw(strftime); our($opt_h, $opt_s, $opt_o, $opt_m, $opt_p, $opt_b, $opt_t, $opt_c); getopts('bcths:o:p:m:'); if ( $opt_h ) { print "Usage: $0 [-s number] [-m number] [-o number]\n"; print " -b check Battery Back Up status\n"; print " -c check cache settings\n"; print " -s is how many hotspares are attached to the controller\n"; print " -m is the number of media errors to ignore\n"; print " -p is the predictive error count to ignore\n"; print " -o is the number of other disk errors to ignore\n"; print " -t print timestamps\n"; exit; } my $megaclibin = '/opt/MegaRAID/MegaCli/MegaCli64'; # the full path to your MegaCli binary my $megacli = "$megaclibin"; # how we actually call MegaCli my $megapostopt = '-NoLog'; # additional options to call at the end of MegaCli arguments my ($adapters); my $hotspares = 0; my $pdbad = 0; my $pdcount = 0; my $mediaerrors = 0; my $mediaallow = 0; my $prederrors = 0; my $predallow = 0; my $othererrors = 0; my $otherallow = 0; my $result = ''; my $status = 'OK'; my $checkbbu = 0; sub max_state ($$) { my ($current, $compare) = @_; if (($compare eq 'CRITICAL') || ($current eq 'CRITICAL')) { return 'CRITICAL'; } elsif ($compare eq 'OK') { return $current; } elsif ($compare eq 'WARNING') { return 'WARNING'; } elsif (($compare eq 'UNKNOWN') && ($current eq 'OK')) { return 'UNKNOWN'; } else { return $current; } } sub exitreport ($$) { my ($status, $message) = @_; if( $opt_t ) { print strftime("%a, %d %b %Y %H:%M:%S %z ", localtime(time())); } if ( $pdcount == 0 ) { print "ERROR?: No drives found\n"; } print "SERVERSTATUS=$status\n$message\n"; if ( $status eq "OK" ) { exit 0; } else { exit 1; } } if ( $opt_s ) { $hotspares = $opt_s; } if ( $opt_m ) { $mediaallow = $opt_m; } if ( $opt_p ) { $predallow = $opt_p; } if ( $opt_o ) { $otherallow = $opt_o; } if ( $opt_b ) { $checkbbu = $opt_b; } # Some sanity checks that you actually have something where you think MegaCli is (-e $megaclibin) || exitreport('UNKNOWN',"error: $megaclibin does not exist"); # Get the number of RAID controllers we have open (ADPCOUNT, "$megacli -adpCount $megapostopt |") || exitreport('UNKNOWN',"error: Could not execute $megacli -adpCount $megapostopt"); while (<ADPCOUNT>) { if ( m/Controller Count:\s*(\d+)/ ) { $adapters = $1; last; } } close ADPCOUNT; ADAPTER: for ( my $adp = 0; $adp < $adapters; $adp++ ) { my $hotsparecount = 0; # Get the Battery Back Up state for this adapter my ($bbustate); if ($checkbbu) { open (BBUGETSTATUS, "$megacli -AdpBbuCmd -GetBbuStatus -a$adp $megapostopt |") || exitreport('UNKNOWN', "error: Could not execute $megacli -AdpBbuCmd -GetBbuStatus -a$adp $megapostopt"); my ($bbucharging, $bbufullycharged, $bburelativecharge, $bbuexitcode); while (<BBUGETSTATUS>) { # Charging Status if ( m/Charging Status\s*:\s*(\w+)/i ) { $bbucharging = $1; } elsif ( m/Fully Charged\s*:\s*(\w+)/i ) { $bbufullycharged = $1; } elsif ( m/Relative State of Charge\s*:\s*(\w+)/i ) { $bburelativecharge = $1; } elsif ( m/Exit Code\s*:\s*(\w+)/i ) { $bbuexitcode = $1; } } close BBUGETSTATUS; # Determine the BBU state if ( $bbuexitcode ne '0x00' ) { $bbustate = 'NOT FOUND'; $status = 'CRITICAL'; } elsif ( $bbucharging ne 'None' ) { $bbustate = 'Charging(' . $bburelativecharge . '%)'; $status = 'WARNING'; } elsif ( $bbufullycharged ne 'Yes' ) { $bbustate = 'NotCharging(' . $bburelativecharge . '%)'; $status = 'WARNING'; } else { $bbustate = 'Charged(' . $bburelativecharge . '%)'; } } # Get the number of logical drives on this adapter open (LDGETNUM, "$megacli -LdGetNum -a$adp $megapostopt |") || exitreport('UNKNOWN', "error: Could not execute $megacli -LdGetNum -a$adp $megapostopt"); my ($ldnum); while (<LDGETNUM>) { if ( m/Number of Virtual drives configured on adapter \d:\s*(\d+)/i ) { $ldnum = $1; last; } } close LDGETNUM; LDISK: for ( my $ld = 0; $ld < $ldnum; $ld++ ) { # Get info on this particular logical drive open (LDINFO, "$megacli -LdInfo -L$ld -a$adp $megapostopt |") || exitreport('UNKNOWN', "error: Could not execute $megacli -LdInfo -L$ld -a$adp $megapostopt "); my $consistency_output = ''; my ($size, $unit, $raidlevel, $ldpdcount, $state, $spandepth, $consistency_percent, $consistency_minutes, $ccache_policy, $dcache_policy); while (<LDINFO>) { if ( m/^Size\s*:\s*((\d+\.?\d*)\s*(MB|GB|TB))/ ) { $size = $2; $unit = $3; # Adjust MB to GB if that's what we got if ( $unit eq 'MB' ) { $size = sprintf( "%.0f", ($size / 1024) ); $unit= 'GB'; } } elsif ( m/State\s*:\s*(\w+)/ ) { $state = $1; if ( $state ne 'Optimal' ) { $status = 'CRITICAL'; } } elsif ( m/Number Of Drives\s*(per span\s*)?:\s*(\d+)/ ) { $ldpdcount = $2; } elsif ( m/Span Depth\s*:\s*(\d+)/ ) { $spandepth = $1; } elsif ( m/RAID Level\s*: Primary-(\d)/ ) { $raidlevel = $1; } elsif ( m/\s+Check Consistency\s+:\s+Completed\s+(\d+)%,\s+Taken\s+(\d+)\s+min/ ) { $consistency_percent = $1; $consistency_minutes = $2; } elsif ( m/Current Cache Policy\s*:\s*([\w \,]+)/ ) { $ccache_policy = $1; if ( $ccache_policy ne 'WriteBack, ReadAdaptive, Cached, No Write Cache if Bad BBU' ) { if ( $opt_c ) { $status = 'WARNING-CACHE-POLICY'; } } } elsif ( m/Disk Cache Policy\s*:\s*([\w \,\']+)/ ) { $dcache_policy = $1; if ( $dcache_policy ne 'Disabled' ) { if ( $opt_c ) { $status = 'WARNING-CACHE-POLICY'; } } } } close LDINFO; # Report correct RAID-level and number of drives in case of Span configurations if ($ldpdcount && $spandepth > 1) { $ldpdcount = $ldpdcount * $spandepth; if ($raidlevel < 10) { $raidlevel = $raidlevel . "0"; } } if ($consistency_percent) { $status = 'WARNING\n'; $consistency_output = "CC ${consistency_percent}% ${consistency_minutes}m"; } $result .= "Adp=$adp Ld=$ld RAID=RAID$raidlevel drives=$ldpdcount size=$size$unit state=$consistency_output$state\n"; if ( $opt_c ) { $result .= "Adp=$adp Ld=$ld ControllerCache=\"$ccache_policy\" DiskCache=\"$dcache_policy\"\n"; } } #LDISK close LDINFO; # Get info on physical disks for this adapter open (PDLIST, "$megacli -PdList -a$adp $megapostopt |") || exitreport('UNKNOWN', "error: Could not execute $megacli -PdList -a$adp $megapostopt "); my ($slotnumber,$fwstate); PDISKS: while (<PDLIST>) { if ( m/Slot Number\s*:\s*(\d+)/ ) { $slotnumber = $1; $pdcount++; } elsif ( m/(\w+) Error Count\s*:\s*(\d+)/ ) { if ( $1 eq 'Media') { $mediaerrors += $2; } else { $othererrors += $2; } } elsif ( m/Predictive Failure Count\s*:\s*(\d+)/ ) { $prederrors += $1; } elsif ( m/Firmware state\s*:\s*(\w+)/ ) { $fwstate = $1; if ( $fwstate eq 'Hotspare' ) { $hotsparecount++; } elsif ( $fwstate eq 'Online' ) { # Do nothing } elsif ( $fwstate eq 'Unconfigured' ) { # A drive not in anything, or a non drive device $pdcount--; } elsif ( $slotnumber != 255 ) { $pdbad++; $status = 'CRITICAL'; } } } #PDISKS close PDLIST; $result .= "Adp=$adp hotspare=$hotsparecount\n"; $result .= "Adp=$adp BBU=$bbustate\n" if ($checkbbu); } $result .= "TotalDrives=$pdcount "; # Any bad disks? $result .= "BadDrives=$pdbad "; my $errorcount = $mediaerrors + $prederrors + $othererrors; # Were there any errors? $result .= "errors=$errorcount "; if ( $errorcount ) { if ( ( $mediaerrors > $mediaallow ) || ( $prederrors > $predallow ) || ( $othererrors > $otherallow ) ) { $status = max_state($status, 'WARNING'); } } exitreport($status, $result);
hpc/clusterscripts
check_megaraid.pl
Perl
bsd-3-clause
7,893
#------------------------------------------------------------------------------ # File: Shift.pl # # Description: ExifTool time shifting routines # # Revisions: 10/28/2005 - P. Harvey Created #------------------------------------------------------------------------------ package Image::ExifTool; use strict; sub ShiftTime($$;$$); #------------------------------------------------------------------------------ # apply shift to value in new value hash # Inputs: 0) ExifTool ref, 1) shift type, 2) shift string, 3) raw date/time value, # 4) new value hash ref # Returns: error string or undef on success and updates value in new value hash sub ApplyShift($$$$;$) { my ($self, $func, $shift, $val, $nvHash) = @_; # get shift direction from first character in shift string my $pre = ($shift =~ s/^(\+|-)//) ? $1 : '+'; my $dir = ($pre eq '+') ? 1 : -1; my $tagInfo = $$nvHash{TagInfo}; my $tag = $$tagInfo{Name}; my $shiftOffset; if ($$nvHash{ShiftOffset}) { $shiftOffset = $$nvHash{ShiftOffset}; } else { $shiftOffset = $$nvHash{ShiftOffset} = { }; } # initialize handler for eval warnings local $SIG{'__WARN__'} = \&SetWarning; SetWarning(undef); # shift is applied to ValueConv value, so we must ValueConv-Shift-ValueConvInv my ($type, $err); foreach $type ('ValueConv','Shift','ValueConvInv') { if ($type eq 'Shift') { #### eval ShiftXxx function $err = eval "Shift$func(\$val, \$shift, \$dir, \$shiftOffset)"; } elsif ($$tagInfo{$type}) { my $conv = $$tagInfo{$type}; if (ref $conv eq 'CODE') { $val = &$conv($val, $self); } else { return "Can't handle $type for $tag in ApplyShift()" if ref $$tagInfo{$type}; #### eval ValueConv/ValueConvInv ($val, $self) $val = eval $$tagInfo{$type}; } } else { next; } # handle errors $err and return $err; $@ and SetWarning($@); GetWarning() and return CleanWarning(); } # update value in new value hash $nvHash->{Value} = [ $val ]; return undef; # success } #------------------------------------------------------------------------------ # Check date/time shift # Inputs: 0) shift type, 1) shift string (without sign) # Returns: updated shift string, or undef on error (and may update shift) sub CheckShift($$) { my ($type, $shift) = @_; my $err; if ($type eq 'Time') { return "No shift direction" unless $shift =~ s/^(\+|-)//; # do a test shift to validate the shift string my $testTime = '2005:11:02 09:00:13.25-04:00'; $err = ShiftTime($testTime, $shift, $1 eq '+' ? 1 : -1); } else { $err = "Unknown shift type ($type)"; } return $err; } #------------------------------------------------------------------------------ # return the number of days in a month # Inputs: 0) month number (Jan=1, may be outside range), 1) year # Returns: number of days in month sub DaysInMonth($$) { my ($mon, $year) = @_; my @days = (31,28,31,30,31,30,31,31,30,31,30,31); # adjust to the range [0,11] while ($mon < 1) { $mon += 12; --$year; } while ($mon > 12) { $mon -= 12; ++$year; } # return standard number of days unless february on a leap year return $days[$mon-1] unless $mon == 2 and not $year % 4; # leap years don't occur on even centuries except every 400 years return 29 if $year % 100 or not $year % 400; return 28; } #------------------------------------------------------------------------------ # split times into corresponding components: YYYY mm dd HH MM SS tzh tzm # Inputs: 0) date/time or shift string 1) reference to list for returned components # 2) optional reference to list of time components (if shift string) # Returns: true on success # Returned components are 0-Y, 1-M, 2-D, 3-hr, 4-min, 5-sec, 6-tzhr, 7-tzmin sub SplitTime($$;$) { my ($val, $vals, $time) = @_; # insert zeros if missing in shift string if ($time) { $val =~ s/(^|[-+:\s]):/${1}0:/g; $val =~ s/:([:\s]|$)/:0$1/g; } # change dashes to colons in date (for XMP dates) if ($val =~ s/^(\d{4})-(\d{2})-(\d{2})/$1:$2:$3/) { $val =~ tr/T/ /; # change 'T' separator to ' ' } # add space before timezone to split it into a separate word $val =~ s/(\+|-)/ $1/; my @words = split ' ', $val; my $err = 1; my @v; for (;;) { my $word = shift @words; last unless defined $word; # split word into separate numbers (allow decimal points but no signs) my @vals = $word =~ /(?=\d|\.\d)\d*(?:\.\d*)?/g or last; if ($word =~ /^(\+|-)/) { # this is the timezone (defined $v[6] or @vals > 2) and $err = 1, last; my $sign = ($1 ne '-') ? 1 : -1; # apply sign to both minutes and seconds $v[6] = $sign * shift(@vals); $v[7] = $sign * (shift(@vals) || 0); } elsif ((@words and $words[0] =~ /^\d+/) or # there is a time word to follow (not $time and $vals[0] =~ /^\d{3}/) or # first value is year (3 or more digits) ($time and not defined $$time[3] and not defined $v[0])) # we don't have a time { # this is a date (must come first) (@v or @vals > 3) and $err = 1, last; not $time and @vals != 3 and $err = 1, last; $v[2] = pop(@vals); # take day first if only one specified $v[1] = pop(@vals) || 0; $v[0] = pop(@vals) || 0; } else { # this is a time (can't come after timezone) (defined $v[3] or defined $v[6] or @vals > 3) and $err = 1, last; not $time and @vals != 3 and @vals != 2 and $err = 1, last; $v[3] = shift(@vals); # take hour first if only one specified $v[4] = shift(@vals) || 0; $v[5] = shift(@vals) || 0; } $err = 0; } return 0 if $err or not @v; if ($time) { # zero any required shift entries which aren't yet defined $v[0] = $v[1] = $v[2] = 0 if defined $$time[0] and not defined $v[0]; $v[3] = $v[4] = $v[5] = 0 if defined $$time[3] and not defined $v[3]; $v[6] = $v[7] = 0 if defined $$time[6] and not defined $v[6]; } @$vals = @v; # return split time components return 1; } #------------------------------------------------------------------------------ # shift date/time by components # Inputs: 0) split date/time list ref, 1) split shift list ref, # 2) shift direction, 3) reference to output list of shifted components # 4) number of decimal points in seconds # 5) reference to return time difference due to rounding # Returns: error string or undef on success sub ShiftComponents($$$$$;$) { my ($time, $shift, $dir, $toTime, $dec, $rndPt) = @_; # min/max for Y, M, D, h, m, s my @min = ( 0, 1, 1, 0, 0, 0); my @max = (10000,12,28,24,60,60); my $i; # # apply the shift # my $c = 0; for ($i=0; $i<@$time; ++$i) { my $v = ($$time[$i] || 0) + $dir * ($$shift[$i] || 0) + $c; # handle fractional values by propagating remainders downwards if ($v != int($v) and $i < 5) { my $iv = int($v); $c = ($v - $iv) * $max[$i+1]; $v = $iv; } else { $c = 0; } $$toTime[$i] = $v; } # round off seconds to the required number of decimal points my $sec = $$toTime[5]; if (defined $sec and $sec != int($sec)) { my $mult = 10 ** $dec; my $rndSec = int($sec * $mult + 0.5 * ($sec <=> 0)) / $mult; $rndPt and $$rndPt = $sec - $rndSec; $$toTime[5] = $rndSec; } # # handle overflows, starting with least significant number first (seconds) # $c = 0; for ($i=5; $i>=0; $i--) { defined $$time[$i] or $c = 0, next; # apply shift and adjust for previous overflow my $v = $$toTime[$i] + $c; $c = 0; # set carry to zero # adjust for over/underflow my ($min, $max) = ($min[$i], $max[$i]); if ($v < $min) { if ($i == 2) { # 2 = day of month do { # add number of days in previous month --$c; my $mon = $$toTime[$i-1] + $c; $v += DaysInMonth($mon, $$toTime[$i-2]); } while ($v < 1); } else { my $fc = ($v - $min) / $max; # carry ($c) must be largest integer equal to or less than $fc $c = int($fc); --$c if $c > $fc; $v -= $c * $max; } } elsif ($v >= $max + $min) { if ($i == 2) { for (;;) { # test against number of days in current month my $mon = $$toTime[$i-1] + $c; my $days = DaysInMonth($mon, $$toTime[$i-2]); last if $v <= $days; $v -= $days; ++$c; last if $v <= 28; } } else { my $fc = ($v - $max - $min) / $max; # carry ($c) must be smallest integer greater than $fc $c = int($fc); ++$c if $c <= $fc; $v -= $c * $max; } } $$toTime[$i] = $v; # save the new value } # handle overflows in timezone if (defined $$toTime[6]) { my $m = $$toTime[6] * 60 + $$toTime[7]; $m += 0.5 * ($m <=> 0); # avoid round-off errors $$toTime[6] = int($m / 60); $$toTime[7] = int($m - $$toTime[6] * 60); } return undef; # success } #------------------------------------------------------------------------------ # Shift an integer or floating-point number # Inputs: 0) date/time string, 1) shift string, 2) shift direction (+1 or -1) # 3) (unused) # Returns: undef and updates input value sub ShiftNumber($$$;$) { my ($val, $shift, $dir) = @_; $_[0] = $val + $shift * $dir; # return shifted value return undef; # success! } #------------------------------------------------------------------------------ # Shift date/time string # Inputs: 0) date/time string, 1) shift string, 2) shift direction (+1 or -1), # or 0 or undef to take shift direction from sign of shift, # 3) reference to ShiftOffset hash (with Date, DateTime, Time, Timezone keys) # Returns: error string or undef on success and date/time string is updated sub ShiftTime($$;$$) { local $_; my ($val, $shift, $dir, $shiftOffset) = @_; my (@time, @shift, @toTime, $mode, $needShiftOffset, $dec); $dir or $dir = ($shift =~ s/^(\+|-)// and $1 eq '-') ? -1 : 1; # # figure out what we are dealing with (time, date or date/time) # SplitTime($val, \@time) or return "Invalid time string ($val)"; if (defined $time[0]) { $mode = defined $time[3] ? 'DateTime' : 'Date'; } elsif (defined $time[3]) { $mode = 'Time'; } # get number of digits after the seconds decimal point if (defined $time[5] and $time[5] =~ /\.(\d+)/) { $dec = length($1); } else { $dec = 0; } if ($shiftOffset) { $needShiftOffset = 1 unless defined $$shiftOffset{$mode}; $needShiftOffset = 1 if defined $time[6] and not defined $$shiftOffset{Timezone}; } else { $needShiftOffset = 1; } if ($needShiftOffset) { # # apply date/time shift the hard way # SplitTime($shift, \@shift, \@time) or return "Invalid shift string ($shift)"; # change 'Z' timezone to '+00:00' only if necessary if (@shift > 6 and @time <= 6) { $time[6] = $time[7] = 0 if $val =~ s/Z$/\+00:00/; } my $rndDiff; my $err = ShiftComponents(\@time, \@shift, $dir, \@toTime, $dec, \$rndDiff); $err and return $err; # # calculate and save the shift offsets for next time # if ($shiftOffset) { if (defined $time[0] or defined $time[3]) { my @tm1 = (0, 0, 0, 1, 0, 2000); my @tm2 = (0, 0, 0, 1, 0, 2000); if (defined $time[0]) { @tm1[3..5] = reverse @time[0..2]; @tm2[3..5] = reverse @toTime[0..2]; --$tm1[4]; # month should start from 0 --$tm2[4]; } my $diff = 0; if (defined $time[3]) { @tm1[0..2] = reverse @time[3..5]; @tm2[0..2] = reverse @toTime[3..5]; # handle fractional seconds separately $diff = $tm2[0] - int($tm2[0]) - ($tm1[0] - int($tm1[0])); $diff += $rndDiff if defined $rndDiff; # un-do rounding $tm1[0] = int($tm1[0]); $tm2[0] = int($tm2[0]); } eval q{ require Time::Local; $diff += Time::Local::timegm(@tm2) - Time::Local::timegm(@tm1); }; # not a problem if we failed here since we'll just try again next time, # so don't return error message unless (@$) { my $mode; if (defined $time[0]) { $mode = defined $time[3] ? 'DateTime' : 'Date'; } else { $mode = 'Time'; } $$shiftOffset{$mode} = $diff; } } if (defined $time[6]) { $$shiftOffset{Timezone} = ($toTime[6] - $time[6]) * 60 + $toTime[7] - $time[7]; } } } else { # # apply shift from previously calculated offsets # if ($$shiftOffset{Timezone} and @time <= 6) { # change 'Z' timezone to '+00:00' only if necessary $time[6] = $time[7] = 0 if $val =~ s/Z$/\+00:00/; } # apply the previous date/time shift if necessary if ($mode) { my @tm = (0, 0, 0, 1, 0, 2000); if (defined $time[0]) { @tm[3..5] = reverse @time[0..2]; --$tm[4]; # month should start from 0 } @tm[0..2] = reverse @time[3..5] if defined $time[3]; # save fractional seconds my $frac = $tm[0] - int($tm[0]); $tm[0] = int($tm[0]); my $tm; eval q{ require Time::Local; $tm = Time::Local::timegm(@tm) + $frac; }; $@ and return CleanWarning($@); $tm += $$shiftOffset{$mode}; # apply the shift $tm < 0 and return 'Shift results in negative time'; # save fractional seconds in shifted time $frac = $tm - int($tm); if ($frac) { $tm = int($tm); # must account for any rounding that could occur $frac + 0.5 * 10 ** (-$dec) >= 1 and ++$tm, $frac = 0; } @tm = gmtime($tm); @toTime = reverse @tm[0..5]; $toTime[0] += 1900; ++$toTime[1]; $toTime[5] += $frac; # add the fractional seconds back in } # apply the previous timezone shift if necessary if (defined $time[6]) { my $m = $time[6] * 60 + $time[7]; $m += $$shiftOffset{Timezone}; $m += 0.5 * ($m <=> 0); # avoid round-off errors $toTime[6] = int($m / 60); $toTime[7] = int($m - $toTime[6] * 60); } } # # insert shifted time components back into original string # my ($i, $err); for ($i=0; $i<@toTime; ++$i) { next unless defined $time[$i] and defined $toTime[$i]; my ($v, $d, $s); if ($i != 6) { # not timezone hours last unless $val =~ /((?=\d|\.\d)\d*(\.\d*)?)/g; next if $toTime[$i] == $time[$i]; $v = $1; # value $d = $2; # decimal part of value $s = ''; # no sign } else { last if $time[$i] == $toTime[$i] and $time[$i+1] == $toTime[$i+1]; last unless $val =~ /((?:\+|-)(?=\d|\.\d)\d*(\.\d*)?)/g; $v = $1; $d = $2; if ($toTime[6] >= 0 and $toTime[7] >= 0) { $s = '+'; } else { $s = '-'; $toTime[6] = -$toTime[6]; $toTime[7] = -$toTime[7]; } } my $nv = $toTime[$i]; my $pos = pos $val; my $len = length $v; my $sig = $len - length $s; my $dec = $d ? length($d) - 1 : 0; my $newNum = sprintf($dec ? "$s%0$sig.${dec}f" : "$s%0${sig}d", $nv); length($newNum) != $len and $err = 1; substr($val, $pos - $len, $len) = $newNum; pos($val) = $pos; } $err and return "Error packing shifted time ($val)"; $_[0] = $val; # return shifted value return undef; # success! } 1; # end __END__ =head1 NAME Image::ExifTool::Shift.pl - ExifTool time shifting routines =head1 DESCRIPTION This module contains routines used by ExifTool to shift date and time values. =head1 DETAILS Time shifts are applied to standard EXIF-formatted date/time values (eg. C<2005:03:14 18:55:00>). Date-only and time-only values may also be shifted, and an optional timezone (eg. C<-05:00>) is also supported. Here are some general rules and examples to explain how shift strings are interpreted: Date-only values are shifted using the following formats: 'Y:M:D' - shift date by 'Y' years, 'M' months and 'D' days 'M:D' - shift months and days only 'D' - shift specified number of days Time-only values are shifted using the following formats: 'h:m:s' - shift time by 'h' hours, 'm' minutes and 's' seconds 'h:m' - shift hours and minutes only 'h' - shift specified number of hours Timezone shifts are specified in the following formats: '+h:m' - shift timezone by 'h' hours and 'm' minutes '-h:m' - negative shift of timezone hours and minutes '+h' - shift timezone hours only '-h' - negative shift of timezone hours only A valid shift value consists of one or two arguments, separated by a space. If only one is provided, it is assumed to be a time shift when applied to a time-only or a date/time value, or a date shift when applied to a date-only value. For example: '1' - shift by 1 hour if applied to a time or date/time value, or by one day if applied to a date value '2:0' - shift 2 hours (time, date/time), or 2 months (date) '5:0:0' - shift 5 hours (time, date/time), or 5 years (date) '0:0:1' - shift 1 s (time, date/time), or 1 day (date) If two arguments are given, the date shift is first, followed by the time shift: '3:0:0 0' - shift date by 3 years '0 15:30' - shift time by 15 hours and 30 minutes '1:0:0 0:0:0+5:0' - shift date by 1 year and timezone by 5 hours A date shift is simply ignored if applied to a time value or visa versa. Numbers specified in shift fields may contain a decimal point: '1.5' - 1 hour 30 minutes (time, date/time), or 1 day (date) '2.5 0' - 2 days 12 hours (date/time), 12 hours (time) or 2 days (date) And to save typing, a zero is assumed for any missing numbers: '1::' - shift by 1 hour (time, date/time) or 1 year (date) '26:: 0' - shift date by 26 years '+:30 - shift timezone by 30 minutes Below are some specific examples applied to real date and/or time values ('Dir' is the applied shift direction: '+' is positive, '-' is negative): Original Value Shift Dir Shifted Value --------------------- ------- --- --------------------- '20:30:00' '5' + '01:30:00' '2005:01:27' '5' + '2005:02:01' '2005:01:27 20:30:00' '5' + '2005:01:28 01:30:00' '11:54:00' '2.5 0' - '23:54:00' '2005:11:02' '2.5 0' - '2005:10:31' '2005:11:02 11:54:00' '2.5 0' - '2005:10:30 23:54:00' '2004:02:28 08:00:00' '1 1.3' + '2004:02:29 09:18:00' '07:00:00' '-5' + '07:00:00' '07:00:00+01:00' '-5' + '07:00:00-04:00' '07:00:00Z' '+2:30' - '07:00:00-02:30' '1970:01:01' '35::' + '2005:01:01' '2005:01:01' '400' + '2006:02:05' '10:00:00.00' '::1.33' - '09:59:58.67' =head1 NOTES The format of the original date/time value is not changed when the time shift is applied. This means that the length of the date/time string will not change, and only the numbers in the string will be modified. The only exception to this rule is that a 'Z' timezone is changed to '+00:00' notation if a timezone shift is applied. A timezone will not be added to the date/time string. =head1 TRICKY This module is perhaps more complicated than it needs to be because it is designed to be very flexible in the way time shifts are specified and applied... The ability to shift dates by Y years, M months, etc, conflicts with the design goal of maintaining a constant shift for all time values when applying a batch shift. This is because shifting by 1 month can be equivalent to anything from 28 to 31 days, and 1 year can be 365 or 366 days, depending on the starting date. The inconsistency is handled by shifting the first tag found with the actual specified shift, then calculating the equivalent time difference in seconds for this shift and applying this difference to subsequent tags in a batch conversion. So if it works as designed, the behaviour should be both intuitive and mathematically correct, and the user shouldn't have to worry about details such as this (in keeping with Perl's "do the right thing" philosophy). =head1 BUGS Due to the use of the standard time library functions, dates are typically limited to the range 1970 to 2038 on 32-bit systems. =head1 AUTHOR Copyright 2003-2014, 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 SEE ALSO L<Image::ExifTool(3pm)|Image::ExifTool> =cut
gitzain/SortPhotos
Image-ExifTool/lib/Image/ExifTool/Shift.pl
Perl
mit
22,635
=pod This is a valid pod file =cut
quattor/maven-tools
build-scripts/src/test/resources/okpod/localtest.pod
Perl
apache-2.0
37
=encoding utf-8 =head1 NAME ngx_http_sub_module - Module ngx_http_sub_module =head1 The C<ngx_http_sub_module> module is a filter that modifies a response by replacing one specified string by another. This module is not built by default, it should be enabled with the C<--with-http_sub_module> configuration parameter. =head1 Example Configuration location / { sub_filter '<a href="http://127.0.0.1:8080/' '<a href="https://$host/'; sub_filter '<img src="http://127.0.0.1:8080/' '<img src="https://$host/'; sub_filter_once on; } =head1 Directives =head2 sub_filter B<syntax:> sub_filter I<I<C<string>> I<C<replacement>>> B<context:> I<http> B<context:> I<server> B<context:> I<location> Sets a string to replace and a replacement string. The string to replace is matched ignoring the case. The string to replace (1.9.4) and replacement string can contain variables. Several C<sub_filter> directives can be specified on one configuration level (1.9.4). These directives are inherited from the previous level if and only if there are no C<sub_filter> directives defined on the current level. =head2 sub_filter_last_modified B<syntax:> sub_filter_last_modified I<C<on> E<verbar> C<off>> B<default:> I<off> B<context:> I<http> B<context:> I<server> B<context:> I<location> This directive appeared in version 1.5.1. Allows preserving the C<Last-Modified> header field from the original response during replacement to facilitate response caching. By default, the header field is removed as contents of the response are modified during processing. =head2 sub_filter_once B<syntax:> sub_filter_once I<C<on> E<verbar> C<off>> B<default:> I<on> B<context:> I<http> B<context:> I<server> B<context:> I<location> Indicates whether to look for each string to replace once or repeatedly. =head2 sub_filter_types B<syntax:> sub_filter_types I<I<C<mime-type>> ...> B<default:> I<textE<sol>html> B<context:> I<http> B<context:> I<server> B<context:> I<location> Enables string replacement in responses with the specified MIME types in addition to “C<textE<sol>html>”. The special value “C<*>” matches any MIME type (0.8.29).
LomoX-Offical/nginx-openresty-windows
src/pod/nginx/ngx_http_sub_module.pod
Perl
bsd-2-clause
2,278
package DDG::Spice::Equaldex; # ABSTRACT: LGBT rights by region use DDG::Spice; use Locale::Country; spice is_cached => 1; spice to => 'http://equaldex.com/api/region?format=json&region=$1&callback={{callback}}'; triggers startend => "lgbt", "lesbian", "gay", "bisexual", "transgender"; my $guardRe = qr/(rights?|laws?) (in)?\s?/; handle remainder => sub { if(m/$guardRe/) { my $country = $'; # Workaround for Locale::Country returning ISO 3166-1 alpha-2 code when using country2code("us(a)") $country = "united states" if $country =~ /\busa?\b/; # Return full country name if valid return $country if defined country2code($country); # Return country name from ISO 3166-1 alpha-2 code if(code2country($country, LOCALE_CODE_ALPHA_2)) { return lc code2country($country, LOCALE_CODE_ALPHA_2); } # Return country name from ISO 3166-1 alpha-3 code if(code2country($country, LOCALE_CODE_ALPHA_3)) { return lc code2country($country, LOCALE_CODE_ALPHA_3); } } return; }; 1;
mr-karan/zeroclickinfo-spice
lib/DDG/Spice/Equaldex.pm
Perl
apache-2.0
1,099
# -*- perl -*- # Text::Template.pm # # Fill in `templates' # # Copyright 2013 M. J. Dominus. # You may copy and distribute this program under the # same terms as Perl itself. # If in doubt, write to mjd-perl-template+@plover.com for a license. # package Text::Template; $Text::Template::VERSION = '1.56'; # ABSTRACT: Expand template text with embedded Perl use strict; use warnings; require 5.008; use base 'Exporter'; our @EXPORT_OK = qw(fill_in_file fill_in_string TTerror); our $ERROR; my %GLOBAL_PREPEND = ('Text::Template' => ''); sub Version { $Text::Template::VERSION; } sub _param { my ($k, %h) = @_; for my $kk ($k, "\u$k", "\U$k", "-$k", "-\u$k", "-\U$k") { return $h{$kk} if exists $h{$kk}; } return undef; } sub always_prepend { my $pack = shift; my $old = $GLOBAL_PREPEND{$pack}; $GLOBAL_PREPEND{$pack} = shift; $old; } { my %LEGAL_TYPE; BEGIN { %LEGAL_TYPE = map { $_ => 1 } qw(FILE FILEHANDLE STRING ARRAY); } sub new { my ($pack, %a) = @_; my $stype = uc(_param('type', %a) || "FILE"); my $source = _param('source', %a); my $untaint = _param('untaint', %a); my $prepend = _param('prepend', %a); my $alt_delim = _param('delimiters', %a); my $broken = _param('broken', %a); my $encoding = _param('encoding', %a); unless (defined $source) { require Carp; Carp::croak("Usage: $ {pack}::new(TYPE => ..., SOURCE => ...)"); } unless ($LEGAL_TYPE{$stype}) { require Carp; Carp::croak("Illegal value `$stype' for TYPE parameter"); } my $self = { TYPE => $stype, PREPEND => $prepend, UNTAINT => $untaint, BROKEN => $broken, ENCODING => $encoding, (defined $alt_delim ? (DELIM => $alt_delim) : ()) }; # Under 5.005_03, if any of $stype, $prepend, $untaint, or $broken # are tainted, all the others become tainted too as a result of # sharing the expression with them. We install $source separately # to prevent it from acquiring a spurious taint. $self->{SOURCE} = $source; bless $self => $pack; return unless $self->_acquire_data; $self; } } # Convert template objects of various types to type STRING, # in which the template data is embedded in the object itself. sub _acquire_data { my $self = shift; my $type = $self->{TYPE}; if ($type eq 'STRING') { # nothing necessary } elsif ($type eq 'FILE') { my $data = _load_text($self->{SOURCE}); unless (defined $data) { # _load_text already set $ERROR return undef; } if ($self->{UNTAINT} && _is_clean($self->{SOURCE})) { _unconditionally_untaint($data); } if (defined $self->{ENCODING}) { require Encode; $data = Encode::decode($self->{ENCODING}, $data, &Encode::FB_CROAK); } $self->{TYPE} = 'STRING'; $self->{FILENAME} = $self->{SOURCE}; $self->{SOURCE} = $data; } elsif ($type eq 'ARRAY') { $self->{TYPE} = 'STRING'; $self->{SOURCE} = join '', @{ $self->{SOURCE} }; } elsif ($type eq 'FILEHANDLE') { $self->{TYPE} = 'STRING'; local $/; my $fh = $self->{SOURCE}; my $data = <$fh>; # Extra assignment avoids bug in Solaris perl5.00[45]. if ($self->{UNTAINT}) { _unconditionally_untaint($data); } $self->{SOURCE} = $data; } else { # This should have been caught long ago, so it represents a # drastic `can't-happen' sort of failure my $pack = ref $self; die "Can only acquire data for $pack objects of subtype STRING, but this is $type; aborting"; } $self->{DATA_ACQUIRED} = 1; } sub source { my $self = shift; $self->_acquire_data unless $self->{DATA_ACQUIRED}; return $self->{SOURCE}; } sub set_source_data { my ($self, $newdata, $type) = @_; $self->{SOURCE} = $newdata; $self->{DATA_ACQUIRED} = 1; $self->{TYPE} = $type || 'STRING'; 1; } sub compile { my $self = shift; return 1 if $self->{TYPE} eq 'PREPARSED'; return undef unless $self->_acquire_data; unless ($self->{TYPE} eq 'STRING') { my $pack = ref $self; # This should have been caught long ago, so it represents a # drastic `can't-happen' sort of failure die "Can only compile $pack objects of subtype STRING, but this is $self->{TYPE}; aborting"; } my @tokens; my $delim_pats = shift() || $self->{DELIM}; my ($t_open, $t_close) = ('{', '}'); my $DELIM; # Regex matches a delimiter if $delim_pats if (defined $delim_pats) { ($t_open, $t_close) = @$delim_pats; $DELIM = "(?:(?:\Q$t_open\E)|(?:\Q$t_close\E))"; @tokens = split /($DELIM|\n)/, $self->{SOURCE}; } else { @tokens = split /(\\\\(?=\\*[{}])|\\[{}]|[{}\n])/, $self->{SOURCE}; } my $state = 'TEXT'; my $depth = 0; my $lineno = 1; my @content; my $cur_item = ''; my $prog_start; while (@tokens) { my $t = shift @tokens; next if $t eq ''; if ($t eq $t_open) { # Brace or other opening delimiter if ($depth == 0) { push @content, [ $state, $cur_item, $lineno ] if $cur_item ne ''; $cur_item = ''; $state = 'PROG'; $prog_start = $lineno; } else { $cur_item .= $t; } $depth++; } elsif ($t eq $t_close) { # Brace or other closing delimiter $depth--; if ($depth < 0) { $ERROR = "Unmatched close brace at line $lineno"; return undef; } elsif ($depth == 0) { push @content, [ $state, $cur_item, $prog_start ] if $cur_item ne ''; $state = 'TEXT'; $cur_item = ''; } else { $cur_item .= $t; } } elsif (!$delim_pats && $t eq '\\\\') { # precedes \\\..\\\{ or \\\..\\\} $cur_item .= '\\'; } elsif (!$delim_pats && $t =~ /^\\([{}])$/) { # Escaped (literal) brace? $cur_item .= $1; } elsif ($t eq "\n") { # Newline $lineno++; $cur_item .= $t; } else { # Anything else $cur_item .= $t; } } if ($state eq 'PROG') { $ERROR = "End of data inside program text that began at line $prog_start"; return undef; } elsif ($state eq 'TEXT') { push @content, [ $state, $cur_item, $lineno ] if $cur_item ne ''; } else { die "Can't happen error #1"; } $self->{TYPE} = 'PREPARSED'; $self->{SOURCE} = \@content; 1; } sub prepend_text { my $self = shift; my $t = $self->{PREPEND}; unless (defined $t) { $t = $GLOBAL_PREPEND{ ref $self }; unless (defined $t) { $t = $GLOBAL_PREPEND{'Text::Template'}; } } $self->{PREPEND} = $_[1] if $#_ >= 1; return $t; } sub fill_in { my ($fi_self, %fi_a) = @_; unless ($fi_self->{TYPE} eq 'PREPARSED') { my $delims = _param('delimiters', %fi_a); my @delim_arg = (defined $delims ? ($delims) : ()); $fi_self->compile(@delim_arg) or return undef; } my $fi_varhash = _param('hash', %fi_a); my $fi_package = _param('package', %fi_a); my $fi_broken = _param('broken', %fi_a) || $fi_self->{BROKEN} || \&_default_broken; my $fi_broken_arg = _param('broken_arg', %fi_a) || []; my $fi_safe = _param('safe', %fi_a); my $fi_ofh = _param('output', %fi_a); my $fi_filename = _param('filename', %fi_a) || $fi_self->{FILENAME} || 'template'; my $fi_strict = _param('strict', %fi_a); my $fi_prepend = _param('prepend', %fi_a); my $fi_eval_package; my $fi_scrub_package = 0; unless (defined $fi_prepend) { $fi_prepend = $fi_self->prepend_text; } if (defined $fi_safe) { $fi_eval_package = 'main'; } elsif (defined $fi_package) { $fi_eval_package = $fi_package; } elsif (defined $fi_varhash) { $fi_eval_package = _gensym(); $fi_scrub_package = 1; } else { $fi_eval_package = caller; } my @fi_varlist; my $fi_install_package; if (defined $fi_varhash) { if (defined $fi_package) { $fi_install_package = $fi_package; } elsif (defined $fi_safe) { $fi_install_package = $fi_safe->root; } else { $fi_install_package = $fi_eval_package; # The gensymmed one } @fi_varlist = _install_hash($fi_varhash => $fi_install_package); if ($fi_strict) { $fi_prepend = "use vars qw(@fi_varlist);$fi_prepend" if @fi_varlist; $fi_prepend = "use strict;$fi_prepend"; } } if (defined $fi_package && defined $fi_safe) { no strict 'refs'; # Big fat magic here: Fix it so that the user-specified package # is the default one available in the safe compartment. *{ $fi_safe->root . '::' } = \%{ $fi_package . '::' }; # LOD } my $fi_r = ''; my $fi_item; foreach $fi_item (@{ $fi_self->{SOURCE} }) { my ($fi_type, $fi_text, $fi_lineno) = @$fi_item; if ($fi_type eq 'TEXT') { $fi_self->append_text_to_output( text => $fi_text, handle => $fi_ofh, out => \$fi_r, type => $fi_type,); } elsif ($fi_type eq 'PROG') { no strict; my $fi_lcomment = "#line $fi_lineno $fi_filename"; my $fi_progtext = "package $fi_eval_package; $fi_prepend;\n$fi_lcomment\n$fi_text;\n;"; my $fi_res; my $fi_eval_err = ''; if ($fi_safe) { no strict; no warnings; $fi_safe->reval(q{undef $OUT}); $fi_res = $fi_safe->reval($fi_progtext); $fi_eval_err = $@; my $OUT = $fi_safe->reval('$OUT'); $fi_res = $OUT if defined $OUT; } else { no strict; no warnings; my $OUT; $fi_res = eval $fi_progtext; $fi_eval_err = $@; $fi_res = $OUT if defined $OUT; } # If the value of the filled-in text really was undef, # change it to an explicit empty string to avoid undefined # value warnings later. $fi_res = '' unless defined $fi_res; if ($fi_eval_err) { $fi_res = $fi_broken->( text => $fi_text, error => $fi_eval_err, lineno => $fi_lineno, arg => $fi_broken_arg,); if (defined $fi_res) { $fi_self->append_text_to_output( text => $fi_res, handle => $fi_ofh, out => \$fi_r, type => $fi_type,); } else { return $fi_r; # Undefined means abort processing } } else { $fi_self->append_text_to_output( text => $fi_res, handle => $fi_ofh, out => \$fi_r, type => $fi_type,); } } else { die "Can't happen error #2"; } } _scrubpkg($fi_eval_package) if $fi_scrub_package; defined $fi_ofh ? 1 : $fi_r; } sub append_text_to_output { my ($self, %arg) = @_; if (defined $arg{handle}) { print { $arg{handle} } $arg{text}; } else { ${ $arg{out} } .= $arg{text}; } return; } sub fill_this_in { my ($pack, $text) = splice @_, 0, 2; my $templ = $pack->new(TYPE => 'STRING', SOURCE => $text, @_) or return undef; $templ->compile or return undef; my $result = $templ->fill_in(@_); $result; } sub fill_in_string { my $string = shift; my $package = _param('package', @_); push @_, 'package' => scalar(caller) unless defined $package; Text::Template->fill_this_in($string, @_); } sub fill_in_file { my $fn = shift; my $templ = Text::Template->new(TYPE => 'FILE', SOURCE => $fn, @_) or return undef; $templ->compile or return undef; my $text = $templ->fill_in(@_); $text; } sub _default_broken { my %a = @_; my $prog_text = $a{text}; my $err = $a{error}; my $lineno = $a{lineno}; chomp $err; # $err =~ s/\s+at .*//s; "Program fragment delivered error ``$err''"; } sub _load_text { my $fn = shift; open my $fh, '<', $fn or do { $ERROR = "Couldn't open file $fn: $!"; return undef; }; local $/; <$fh>; } sub _is_clean { my $z; eval { ($z = join('', @_)), eval '#' . substr($z, 0, 0); 1 } # LOD } sub _unconditionally_untaint { for (@_) { ($_) = /(.*)/s; } } { my $seqno = 0; sub _gensym { __PACKAGE__ . '::GEN' . $seqno++; } sub _scrubpkg { my $s = shift; $s =~ s/^Text::Template:://; no strict 'refs'; my $hash = $Text::Template::{ $s . "::" }; foreach my $key (keys %$hash) { undef $hash->{$key}; } %$hash = (); delete $Text::Template::{ $s . "::" }; } } # Given a hashful of variables (or a list of such hashes) # install the variables into the specified package, # overwriting whatever variables were there before. sub _install_hash { my $hashlist = shift; my $dest = shift; if (UNIVERSAL::isa($hashlist, 'HASH')) { $hashlist = [$hashlist]; } my @varlist; for my $hash (@$hashlist) { for my $name (keys %$hash) { my $val = $hash->{$name}; no strict 'refs'; no warnings 'redefine'; local *SYM = *{"$ {dest}::$name"}; if (!defined $val) { delete ${"$ {dest}::"}{$name}; my $match = qr/^.\Q$name\E$/; @varlist = grep { $_ !~ $match } @varlist; } elsif (ref $val) { *SYM = $val; push @varlist, do { if (UNIVERSAL::isa($val, 'ARRAY')) { '@' } elsif (UNIVERSAL::isa($val, 'HASH')) { '%' } else { '$' } } . $name; } else { *SYM = \$val; push @varlist, '$' . $name; } } } @varlist; } sub TTerror { $ERROR } 1; __END__ =pod =encoding UTF-8 =head1 NAME Text::Template - Expand template text with embedded Perl =head1 VERSION version 1.56 =head1 SYNOPSIS use Text::Template; $template = Text::Template->new(TYPE => 'FILE', SOURCE => 'filename.tmpl'); $template = Text::Template->new(TYPE => 'ARRAY', SOURCE => [ ... ] ); $template = Text::Template->new(TYPE => 'FILEHANDLE', SOURCE => $fh ); $template = Text::Template->new(TYPE => 'STRING', SOURCE => '...' ); $template = Text::Template->new(PREPEND => q{use strict;}, ...); # Use a different template file syntax: $template = Text::Template->new(DELIMITERS => [$open, $close], ...); $recipient = 'King'; $text = $template->fill_in(); # Replaces `{$recipient}' with `King' print $text; $T::recipient = 'Josh'; $text = $template->fill_in(PACKAGE => T); # Pass many variables explicitly $hash = { recipient => 'Abed-Nego', friends => [ 'me', 'you' ], enemies => { loathsome => 'Saruman', fearsome => 'Sauron' }, }; $text = $template->fill_in(HASH => $hash, ...); # $recipient is Abed-Nego, # @friends is ( 'me', 'you' ), # %enemies is ( loathsome => ..., fearsome => ... ) # Call &callback in case of programming errors in template $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => $ref, ...); # Evaluate program fragments in Safe compartment with restricted permissions $text = $template->fill_in(SAFE => $compartment, ...); # Print result text instead of returning it $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...); # Parse template with different template file syntax: $text = $template->fill_in(DELIMITERS => [$open, $close], ...); # Note that this is *faster* than using the default delimiters # Prepend specified perl code to each fragment before evaluating: $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...); use Text::Template 'fill_in_string'; $text = fill_in_string( <<EOM, PACKAGE => 'T', ...); Dear {$recipient}, Pay me at once. Love, G.V. EOM use Text::Template 'fill_in_file'; $text = fill_in_file($filename, ...); # All templates will always have `use strict vars' attached to all fragments Text::Template->always_prepend(q{use strict 'vars';}); =head1 DESCRIPTION This is a library for generating form letters, building HTML pages, or filling in templates generally. A `template' is a piece of text that has little Perl programs embedded in it here and there. When you `fill in' a template, you evaluate the little programs and replace them with their values. You can store a template in a file outside your program. People can modify the template without modifying the program. You can separate the formatting details from the main code, and put the formatting parts of the program into the template. That prevents code bloat and encourages functional separation. =head2 Example Here's an example of a template, which we'll suppose is stored in the file C<formletter.tmpl>: Dear {$title} {$lastname}, It has come to our attention that you are delinquent in your {$monthname[$last_paid_month]} payment. Please remit ${sprintf("%.2f", $amount)} immediately, or your patellae may be needlessly endangered. Love, Mark "Vizopteryx" Dominus The result of filling in this template is a string, which might look something like this: Dear Mr. Smith, It has come to our attention that you are delinquent in your February payment. Please remit $392.12 immediately, or your patellae may be needlessly endangered. Love, Mark "Vizopteryx" Dominus Here is a complete program that transforms the example template into the example result, and prints it out: use Text::Template; my $template = Text::Template->new(SOURCE => 'formletter.tmpl') or die "Couldn't construct template: $Text::Template::ERROR"; my @monthname = qw(January February March April May June July August September October November December); my %vars = (title => 'Mr.', firstname => 'John', lastname => 'Smith', last_paid_month => 1, # February amount => 392.12, monthname => \@monthname); my $result = $template->fill_in(HASH => \%vars); if (defined $result) { print $result } else { die "Couldn't fill in template: $Text::Template::ERROR" } =head2 Philosophy When people make a template module like this one, they almost always start by inventing a special syntax for substitutions. For example, they build it so that a string like C<%%VAR%%> is replaced with the value of C<$VAR>. Then they realize the need extra formatting, so they put in some special syntax for formatting. Then they need a loop, so they invent a loop syntax. Pretty soon they have a new little template language. This approach has two problems: First, their little language is crippled. If you need to do something the author hasn't thought of, you lose. Second: Who wants to learn another language? You already know Perl, so why not use it? C<Text::Template> templates are programmed in I<Perl>. You embed Perl code in your template, with C<{> at the beginning and C<}> at the end. If you want a variable interpolated, you write it the way you would in Perl. If you need to make a loop, you can use any of the Perl loop constructions. All the Perl built-in functions are available. =head1 Details =head2 Template Parsing The C<Text::Template> module scans the template source. An open brace C<{> begins a program fragment, which continues until the matching close brace C<}>. When the template is filled in, the program fragments are evaluated, and each one is replaced with the resulting value to yield the text that is returned. A backslash C<\> in front of a brace (or another backslash that is in front of a brace) escapes its special meaning. The result of filling out this template: \{ The sum of 1 and 2 is {1+2} \} is { The sum of 1 and 2 is 3 } If you have an unmatched brace, C<Text::Template> will return a failure code and a warning about where the problem is. Backslashes that do not precede a brace are passed through unchanged. If you have a template like this: { "String that ends in a newline.\n" } The backslash inside the string is passed through to Perl unchanged, so the C<\n> really does turn into a newline. See the note at the end for details about the way backslashes work. Backslash processing is I<not> done when you specify alternative delimiters with the C<DELIMITERS> option. (See L<"Alternative Delimiters">, below.) Each program fragment should be a sequence of Perl statements, which are evaluated the usual way. The result of the last statement executed will be evaluated in scalar context; the result of this statement is a string, which is interpolated into the template in place of the program fragment itself. The fragments are evaluated in order, and side effects from earlier fragments will persist into later fragments: {$x = @things; ''}The Lord High Chamberlain has gotten {$x} things for me this year. { $diff = $x - 17; $more = 'more' if ($diff == 0) { $diff = 'no'; } elsif ($diff < 0) { $more = 'fewer'; } ''; } That is {$diff} {$more} than he gave me last year. The value of C<$x> set in the first line will persist into the next fragment that begins on the third line, and the values of C<$diff> and C<$more> set in the second fragment will persist and be interpolated into the last line. The output will look something like this: The Lord High Chamberlain has gotten 42 things for me this year. That is 25 more than he gave me last year. That is all the syntax there is. =head2 The C<$OUT> variable There is one special trick you can play in a template. Here is the motivation for it: Suppose you are going to pass an array, C<@items>, into the template, and you want the template to generate a bulleted list with a header, like this: Here is a list of the things I have got for you since 1907: * Ivory * Apes * Peacocks * ... One way to do it is with a template like this: Here is a list of the things I have got for you since 1907: { my $blist = ''; foreach $i (@items) { $blist .= qq{ * $i\n}; } $blist; } Here we construct the list in a variable called C<$blist>, which we return at the end. This is a little cumbersome. There is a shortcut. Inside of templates, there is a special variable called C<$OUT>. Anything you append to this variable will appear in the output of the template. Also, if you use C<$OUT> in a program fragment, the normal behavior, of replacing the fragment with its return value, is disabled; instead the fragment is replaced with the value of C<$OUT>. This means that you can write the template above like this: Here is a list of the things I have got for you since 1907: { foreach $i (@items) { $OUT .= " * $i\n"; } } C<$OUT> is reinitialized to the empty string at the start of each program fragment. It is private to C<Text::Template>, so you can't use a variable named C<$OUT> in your template without invoking the special behavior. =head2 General Remarks All C<Text::Template> functions return C<undef> on failure, and set the variable C<$Text::Template::ERROR> to contain an explanation of what went wrong. For example, if you try to create a template from a file that does not exist, C<$Text::Template::ERROR> will contain something like: Couldn't open file xyz.tmpl: No such file or directory =head2 C<new> $template = Text::Template->new( TYPE => ..., SOURCE => ... ); This creates and returns a new template object. C<new> returns C<undef> and sets C<$Text::Template::ERROR> if it can't create the template object. C<SOURCE> says where the template source code will come from. C<TYPE> says what kind of object the source is. The most common type of source is a file: Text::Template->new( TYPE => 'FILE', SOURCE => $filename ); This reads the template from the specified file. The filename is opened with the Perl C<open> command, so it can be a pipe or anything else that makes sense with C<open>. The C<TYPE> can also be C<STRING>, in which case the C<SOURCE> should be a string: Text::Template->new( TYPE => 'STRING', SOURCE => "This is the actual template!" ); The C<TYPE> can be C<ARRAY>, in which case the source should be a reference to an array of strings. The concatenation of these strings is the template: Text::Template->new( TYPE => 'ARRAY', SOURCE => [ "This is ", "the actual", " template!", ] ); The C<TYPE> can be FILEHANDLE, in which case the source should be an open filehandle (such as you got from the C<FileHandle> or C<IO::*> packages, or a glob, or a reference to a glob). In this case C<Text::Template> will read the text from the filehandle up to end-of-file, and that text is the template: # Read template source code from STDIN: Text::Template->new ( TYPE => 'FILEHANDLE', SOURCE => \*STDIN ); If you omit the C<TYPE> attribute, it's taken to be C<FILE>. C<SOURCE> is required. If you omit it, the program will abort. The words C<TYPE> and C<SOURCE> can be spelled any of the following ways: TYPE SOURCE Type Source type source -TYPE -SOURCE -Type -Source -type -source Pick a style you like and stick with it. =over 4 =item C<DELIMITERS> You may also add a C<DELIMITERS> option. If this option is present, its value should be a reference to an array of two strings. The first string is the string that signals the beginning of each program fragment, and the second string is the string that signals the end of each program fragment. See L<"Alternative Delimiters">, below. =item C<ENCODING> You may also add a C<ENCODING> option. If this option is present, and the C<SOURCE> is a C<FILE>, then the data will be decoded from the given encoding using the L<Encode> module. You can use any encoding that L<Encode> recognizes. E.g.: Text::Template->new( TYPE => 'FILE', ENCODING => 'UTF-8', SOURCE => 'xyz.tmpl'); =item C<UNTAINT> If your program is running in taint mode, you may have problems if your templates are stored in files. Data read from files is considered 'untrustworthy', and taint mode will not allow you to evaluate the Perl code in the file. (It is afraid that a malicious person might have tampered with the file.) In some environments, however, local files are trustworthy. You can tell C<Text::Template> that a certain file is trustworthy by supplying C<UNTAINT =E<gt> 1> in the call to C<new>. This will tell C<Text::Template> to disable taint checks on template code that has come from a file, as long as the filename itself is considered trustworthy. It will also disable taint checks on template code that comes from a filehandle. When used with C<TYPE =E<gt> 'string'> or C<TYPE =E<gt> 'array'>, it has no effect. See L<perlsec> for more complete information about tainting. Thanks to Steve Palincsar, Gerard Vreeswijk, and Dr. Christoph Baehr for help with this feature. =item C<PREPEND> This option is passed along to the C<fill_in> call unless it is overridden in the arguments to C<fill_in>. See L<C<PREPEND> feature and using C<strict> in templates> below. =item C<BROKEN> This option is passed along to the C<fill_in> call unless it is overridden in the arguments to C<fill_in>. See L<C<BROKEN>> below. =back =head2 C<compile> $template->compile() Loads all the template text from the template's source, parses and compiles it. If successful, returns true; otherwise returns false and sets C<$Text::Template::ERROR>. If the template is already compiled, it returns true and does nothing. You don't usually need to invoke this function, because C<fill_in> (see below) compiles the template if it isn't compiled already. If there is an argument to this function, it must be a reference to an array containing alternative delimiter strings. See C<"Alternative Delimiters">, below. =head2 C<fill_in> $template->fill_in(OPTIONS); Fills in a template. Returns the resulting text if successful. Otherwise, returns C<undef> and sets C<$Text::Template::ERROR>. The I<OPTIONS> are a hash, or a list of key-value pairs. You can write the key names in any of the six usual styles as above; this means that where this manual says C<PACKAGE> (for example) you can actually use any of PACKAGE Package package -PACKAGE -Package -package Pick a style you like and stick with it. The all-lowercase versions may yield spurious warnings about Ambiguous use of package => resolved to "package" so you might like to avoid them and use the capitalized versions. At present, there are eight legal options: C<PACKAGE>, C<BROKEN>, C<BROKEN_ARG>, C<FILENAME>, C<SAFE>, C<HASH>, C<OUTPUT>, and C<DELIMITERS>. =over 4 =item C<PACKAGE> C<PACKAGE> specifies the name of a package in which the program fragments should be evaluated. The default is to use the package from which C<fill_in> was called. For example, consider this template: The value of the variable x is {$x}. If you use C<$template-E<gt>fill_in(PACKAGE =E<gt> 'R')> , then the C<$x> in the template is actually replaced with the value of C<$R::x>. If you omit the C<PACKAGE> option, C<$x> will be replaced with the value of the C<$x> variable in the package that actually called C<fill_in>. You should almost always use C<PACKAGE>. If you don't, and your template makes changes to variables, those changes will be propagated back into the main program. Evaluating the template in a private package helps prevent this. The template can still modify variables in your program if it wants to, but it will have to do so explicitly. See the section at the end on `Security'. Here's an example of using C<PACKAGE>: Your Royal Highness, Enclosed please find a list of things I have gotten for you since 1907: { foreach $item (@items) { $item_no++; $OUT .= " $item_no. \u$item\n"; } } Signed, Lord High Chamberlain We want to pass in an array which will be assigned to the array C<@items>. Here's how to do that: @items = ('ivory', 'apes', 'peacocks', ); $template->fill_in(); This is not very safe. The reason this isn't as safe is that if you had a variable named C<$item_no> in scope in your program at the point you called C<fill_in>, its value would be clobbered by the act of filling out the template. The problem is the same as if you had written a subroutine that used those variables in the same way that the template does. (C<$OUT> is special in templates and is always safe.) One solution to this is to make the C<$item_no> variable private to the template by declaring it with C<my>. If the template does this, you are safe. But if you use the C<PACKAGE> option, you will probably be safe even if the template does I<not> declare its variables with C<my>: @Q::items = ('ivory', 'apes', 'peacocks', ); $template->fill_in(PACKAGE => 'Q'); In this case the template will clobber the variable C<$Q::item_no>, which is not related to the one your program was using. Templates cannot affect variables in the main program that are declared with C<my>, unless you give the template references to those variables. =item C<HASH> You may not want to put the template variables into a package. Packages can be hard to manage: You can't copy them, for example. C<HASH> provides an alternative. The value for C<HASH> should be a reference to a hash that maps variable names to values. For example, $template->fill_in( HASH => { recipient => "The King", items => ['gold', 'frankincense', 'myrrh'], object => \$self, } ); will fill out the template and use C<"The King"> as the value of C<$recipient> and the list of items as the value of C<@items>. Note that we pass an array reference, but inside the template it appears as an array. In general, anything other than a simple string or number should be passed by reference. We also want to pass an object, which is in C<$self>; note that we pass a reference to the object, C<\$self> instead. Since we've passed a reference to a scalar, inside the template the object appears as C<$object>. The full details of how it works are a little involved, so you might want to skip to the next section. Suppose the key in the hash is I<key> and the value is I<value>. =over 4 =item * If the I<value> is C<undef>, then any variables named C<$key>, C<@key>, C<%key>, etc., are undefined. =item * If the I<value> is a string or a number, then C<$key> is set to that value in the template. =item * For anything else, you must pass a reference. If the I<value> is a reference to an array, then C<@key> is set to that array. If the I<value> is a reference to a hash, then C<%key> is set to that hash. Similarly if I<value> is any other kind of reference. This means that var => "foo" and var => \"foo" have almost exactly the same effect. (The difference is that in the former case, the value is copied, and in the latter case it is aliased.) =item * In particular, if you want the template to get an object or any kind, you must pass a reference to it: $template->fill_in(HASH => { database_handle => \$dbh, ... }); If you do this, the template will have a variable C<$database_handle> which is the database handle object. If you leave out the C<\>, the template will have a hash C<%database_handle>, which exposes the internal structure of the database handle object; you don't want that. =back Normally, the way this works is by allocating a private package, loading all the variables into the package, and then filling out the template as if you had specified that package. A new package is allocated each time. However, if you I<also> use the C<PACKAGE> option, C<Text::Template> loads the variables into the package you specified, and they stay there after the call returns. Subsequent calls to C<fill_in> that use the same package will pick up the values you loaded in. If the argument of C<HASH> is a reference to an array instead of a reference to a hash, then the array should contain a list of hashes whose contents are loaded into the template package one after the other. You can use this feature if you want to combine several sets of variables. For example, one set of variables might be the defaults for a fill-in form, and the second set might be the user inputs, which override the defaults when they are present: $template->fill_in(HASH => [\%defaults, \%user_input]); You can also use this to set two variables with the same name: $template->fill_in( HASH => [ { v => "The King" }, { v => [1,2,3] } ] ); This sets C<$v> to C<"The King"> and C<@v> to C<(1,2,3)>. =item C<BROKEN> If any of the program fragments fails to compile or aborts for any reason, and you have set the C<BROKEN> option to a function reference, C<Text::Template> will invoke the function. This function is called the I<C<BROKEN> function>. The C<BROKEN> function will tell C<Text::Template> what to do next. If the C<BROKEN> function returns C<undef>, C<Text::Template> will immediately abort processing the template and return the text that it has accumulated so far. If your function does this, it should set a flag that you can examine after C<fill_in> returns so that you can tell whether there was a premature return or not. If the C<BROKEN> function returns any other value, that value will be interpolated into the template as if that value had been the return value of the program fragment to begin with. For example, if the C<BROKEN> function returns an error string, the error string will be interpolated into the output of the template in place of the program fragment that cased the error. If you don't specify a C<BROKEN> function, C<Text::Template> supplies a default one that returns something like Program fragment delivered error ``Illegal division by 0 at template line 37'' (Note that the format of this message has changed slightly since version 1.31.) The return value of the C<BROKEN> function is interpolated into the template at the place the error occurred, so that this template: (3+4)*5 = { 3+4)*5 } yields this result: (3+4)*5 = Program fragment delivered error ``syntax error at template line 1'' If you specify a value for the C<BROKEN> attribute, it should be a reference to a function that C<fill_in> can call instead of the default function. C<fill_in> will pass a hash to the C<broken> function. The hash will have at least these three members: =over 4 =item C<text> The source code of the program fragment that failed =item C<error> The text of the error message (C<$@>) generated by eval. The text has been modified to omit the trailing newline and to include the name of the template file (if there was one). The line number counts from the beginning of the template, not from the beginning of the failed program fragment. =item C<lineno> The line number of the template at which the program fragment began. =back There may also be an C<arg> member. See C<BROKEN_ARG>, below =item C<BROKEN_ARG> If you supply the C<BROKEN_ARG> option to C<fill_in>, the value of the option is passed to the C<BROKEN> function whenever it is called. The default C<BROKEN> function ignores the C<BROKEN_ARG>, but you can write a custom C<BROKEN> function that uses the C<BROKEN_ARG> to get more information about what went wrong. The C<BROKEN> function could also use the C<BROKEN_ARG> as a reference to store an error message or some other information that it wants to communicate back to the caller. For example: $error = ''; sub my_broken { my %args = @_; my $err_ref = $args{arg}; ... $$err_ref = "Some error message"; return undef; } $template->fill_in( BROKEN => \&my_broken, BROKEN_ARG => \$error ); if ($error) { die "It didn't work: $error"; } If one of the program fragments in the template fails, it will call the C<BROKEN> function, C<my_broken>, and pass it the C<BROKEN_ARG>, which is a reference to C<$error>. C<my_broken> can store an error message into C<$error> this way. Then the function that called C<fill_in> can see if C<my_broken> has left an error message for it to find, and proceed accordingly. =item C<FILENAME> If you give C<fill_in> a C<FILENAME> option, then this is the file name that you loaded the template source from. This only affects the error message that is given for template errors. If you loaded the template from C<foo.txt> for example, and pass C<foo.txt> as the C<FILENAME> parameter, errors will look like C<... at foo.txt line N> rather than C<... at template line N>. Note that this does NOT have anything to do with loading a template from the given filename. See C<fill_in_file()> for that. For example: my $template = Text::Template->new( TYPE => 'string', SOURCE => 'The value is {1/0}'); $template->fill_in(FILENAME => 'foo.txt') or die $Text::Template::ERROR; will die with an error that contains Illegal division by zero at at foo.txt line 1 =item C<SAFE> If you give C<fill_in> a C<SAFE> option, its value should be a safe compartment object from the C<Safe> package. All evaluation of program fragments will be performed in this compartment. See L<Safe> for full details about such compartments and how to restrict the operations that can be performed in them. If you use the C<PACKAGE> option with C<SAFE>, the package you specify will be placed into the safe compartment and evaluation will take place in that package as usual. If not, C<SAFE> operation is a little different from the default. Usually, if you don't specify a package, evaluation of program fragments occurs in the package from which the template was invoked. But in C<SAFE> mode the evaluation occurs inside the safe compartment and cannot affect the calling package. Normally, if you use C<HASH> without C<PACKAGE>, the hash variables are imported into a private, one-use-only package. But if you use C<HASH> and C<SAFE> together without C<PACKAGE>, the hash variables will just be loaded into the root namespace of the C<Safe> compartment. =item C<OUTPUT> If your template is going to generate a lot of text that you are just going to print out again anyway, you can save memory by having C<Text::Template> print out the text as it is generated instead of making it into a big string and returning the string. If you supply the C<OUTPUT> option to C<fill_in>, the value should be a filehandle. The generated text will be printed to this filehandle as it is constructed. For example: $template->fill_in(OUTPUT => \*STDOUT, ...); fills in the C<$template> as usual, but the results are immediately printed to STDOUT. This may result in the output appearing more quickly than it would have otherwise. If you use C<OUTPUT>, the return value from C<fill_in> is still true on success and false on failure, but the complete text is not returned to the caller. =item C<PREPEND> You can have some Perl code prepended automatically to the beginning of every program fragment. See L<C<PREPEND> feature and using C<strict> in templates> below. =item C<DELIMITERS> If this option is present, its value should be a reference to a list of two strings. The first string is the string that signals the beginning of each program fragment, and the second string is the string that signals the end of each program fragment. See L<"Alternative Delimiters">, below. If you specify C<DELIMITERS> in the call to C<fill_in>, they override any delimiters you set when you created the template object with C<new>. =back =head1 Convenience Functions =head2 C<fill_this_in> The basic way to fill in a template is to create a template object and then call C<fill_in> on it. This is useful if you want to fill in the same template more than once. In some programs, this can be cumbersome. C<fill_this_in> accepts a string, which contains the template, and a list of options, which are passed to C<fill_in> as above. It constructs the template object for you, fills it in as specified, and returns the results. It returns C<undef> and sets C<$Text::Template::ERROR> if it couldn't generate any results. An example: $Q::name = 'Donald'; $Q::amount = 141.61; $Q::part = 'hyoid bone'; $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q); Dear {$name}, You owe me \\${sprintf('%.2f', $amount)}. Pay or I will break your {$part}. Love, Grand Vizopteryx of Irkutsk. EOM Notice how we included the template in-line in the program by using a `here document' with the C<E<lt>E<lt>> notation. C<fill_this_in> is a deprecated feature. It is only here for backwards compatibility, and may be removed in some far-future version in C<Text::Template>. You should use C<fill_in_string> instead. It is described in the next section. =head2 C<fill_in_string> It is stupid that C<fill_this_in> is a class method. It should have been just an imported function, so that you could omit the C<Text::Template-E<gt>> in the example above. But I made the mistake four years ago and it is too late to change it. C<fill_in_string> is exactly like C<fill_this_in> except that it is not a method and you can omit the C<Text::Template-E<gt>> and just say print fill_in_string(<<'EOM', ...); Dear {$name}, ... EOM To use C<fill_in_string>, you need to say use Text::Template 'fill_in_string'; at the top of your program. You should probably use C<fill_in_string> instead of C<fill_this_in>. =head2 C<fill_in_file> If you import C<fill_in_file>, you can say $text = fill_in_file(filename, ...); The C<...> are passed to C<fill_in> as above. The filename is the name of the file that contains the template you want to fill in. It returns the result text. or C<undef>, as usual. If you are going to fill in the same file more than once in the same program you should use the longer C<new> / C<fill_in> sequence instead. It will be a lot faster because it only has to read and parse the file once. =head2 Including files into templates People always ask for this. ``Why don't you have an include function?'' they want to know. The short answer is this is Perl, and Perl already has an include function. If you want it, you can just put {qx{cat filename}} into your template. VoilE<agrave>. If you don't want to use C<cat>, you can write a little four-line function that opens a file and dumps out its contents, and call it from the template. I wrote one for you. In the template, you can say {Text::Template::_load_text(filename)} If that is too verbose, here is a trick. Suppose the template package that you are going to be mentioning in the C<fill_in> call is package C<Q>. Then in the main program, write *Q::include = \&Text::Template::_load_text; This imports the C<_load_text> function into package C<Q> with the name C<include>. From then on, any template that you fill in with package C<Q> can say {include(filename)} to insert the text from the named file at that point. If you are using the C<HASH> option instead, just put C<include =E<gt> \&Text::Template::_load_text> into the hash instead of importing it explicitly. Suppose you don't want to insert a plain text file, but rather you want to include one template within another? Just use C<fill_in_file> in the template itself: {Text::Template::fill_in_file(filename)} You can do the same importing trick if this is too much to type. =head1 Miscellaneous =head2 C<my> variables People are frequently surprised when this doesn't work: my $recipient = 'The King'; my $text = fill_in_file('formletter.tmpl'); The text C<The King> doesn't get into the form letter. Why not? Because C<$recipient> is a C<my> variable, and the whole point of C<my> variables is that they're private and inaccessible except in the scope in which they're declared. The template is not part of that scope, so the template can't see C<$recipient>. If that's not the behavior you want, don't use C<my>. C<my> means a private variable, and in this case you don't want the variable to be private. Put the variables into package variables in some other package, and use the C<PACKAGE> option to C<fill_in>: $Q::recipient = $recipient; my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q'); or pass the names and values in a hash with the C<HASH> option: my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient }); =head2 Security Matters All variables are evaluated in the package you specify with the C<PACKAGE> option of C<fill_in>. if you use this option, and if your templates don't do anything egregiously stupid, you won't have to worry that evaluation of the little programs will creep out into the rest of your program and wreck something. Nevertheless, there's really no way (except with C<Safe>) to protect against a template that says { $Important::Secret::Security::Enable = 0; # Disable security checks in this program } or { $/ = "ho ho ho"; # Sabotage future uses of <FH>. # $/ is always a global variable } or even { system("rm -rf /") } so B<don't> go filling in templates unless you're sure you know what's in them. If you're worried, or you can't trust the person who wrote the template, use the C<SAFE> option. A final warning: program fragments run a small risk of accidentally clobbering local variables in the C<fill_in> function itself. These variables all have names that begin with C<$fi_>, so if you stay away from those names you'll be safe. (Of course, if you're a real wizard you can tamper with them deliberately for exciting effects; this is actually how C<$OUT> works.) I can fix this, but it will make the package slower to do it, so I would prefer not to. If you are worried about this, send me mail and I will show you what to do about it. =head2 Alternative Delimiters Lorenzo Valdettaro pointed out that if you are using C<Text::Template> to generate TeX output, the choice of braces as the program fragment delimiters makes you suffer suffer suffer. Starting in version 1.20, you can change the choice of delimiters to something other than curly braces. In either the C<new()> call or the C<fill_in()> call, you can specify an alternative set of delimiters with the C<DELIMITERS> option. For example, if you would like code fragments to be delimited by C<[@--> and C<--@]> instead of C<{> and C<}>, use ... DELIMITERS => [ '[@--', '--@]' ], ... Note that these delimiters are I<literal strings>, not regexes. (I tried for regexes, but it complicates the lexical analysis too much.) Note also that C<DELIMITERS> disables the special meaning of the backslash, so if you want to include the delimiters in the literal text of your template file, you are out of luck---it is up to you to choose delimiters that do not conflict with what you are doing. The delimiter strings may still appear inside of program fragments as long as they nest properly. This means that if for some reason you absolutely must have a program fragment that mentions one of the delimiters, like this: [@-- print "Oh no, a delimiter: --@]\n" --@] you may be able to make it work by doing this instead: [@-- # Fake matching delimiter in a comment: [@-- print "Oh no, a delimiter: --@]\n" --@] It may be safer to choose delimiters that begin with a newline character. Because the parsing of templates is simplified by the absence of backslash escapes, using alternative C<DELIMITERS> may speed up the parsing process by 20-25%. This shows that my original choice of C<{> and C<}> was very bad. =head2 C<PREPEND> feature and using C<strict> in templates Suppose you would like to use C<strict> in your templates to detect undeclared variables and the like. But each code fragment is a separate lexical scope, so you have to turn on C<strict> at the top of each and every code fragment: { use strict; use vars '$foo'; $foo = 14; ... } ... { # we forgot to put `use strict' here my $result = $boo + 12; # $boo is misspelled and should be $foo # No error is raised on `$boo' } Because we didn't put C<use strict> at the top of the second fragment, it was only active in the first fragment, and we didn't get any C<strict> checking in the second fragment. Then we misspelled C<$foo> and the error wasn't caught. C<Text::Template> version 1.22 and higher has a new feature to make this easier. You can specify that any text at all be automatically added to the beginning of each program fragment. When you make a call to C<fill_in>, you can specify a PREPEND => 'some perl statements here' option; the statements will be prepended to each program fragment for that one call only. Suppose that the C<fill_in> call included a PREPEND => 'use strict;' option, and that the template looked like this: { use vars '$foo'; $foo = 14; ... } ... { my $result = $boo + 12; # $boo is misspelled and should be $foo ... } The code in the second fragment would fail, because C<$boo> has not been declared. C<use strict> was implied, even though you did not write it explicitly, because the C<PREPEND> option added it for you automatically. There are three other ways to do this. At the time you create the template object with C<new>, you can also supply a C<PREPEND> option, in which case the statements will be prepended each time you fill in that template. If the C<fill_in> call has its own C<PREPEND> option, this overrides the one specified at the time you created the template. Finally, you can make the class method call Text::Template->always_prepend('perl statements'); If you do this, then call calls to C<fill_in> for I<any> template will attach the perl statements to the beginning of each program fragment, except where overridden by C<PREPEND> options to C<new> or C<fill_in>. An alternative to adding "use strict;" to the PREPEND option, you can pass STRICT => 1 to fill_in when also passing the HASH option. Suppose that the C<fill_in> call included both HASH => {$foo => ''} and STRICT => 1 options, and that the template looked like this: { $foo = 14; ... } ... { my $result = $boo + 12; # $boo is misspelled and should be $foo ... } The code in the second fragment would fail, because C<$boo> has not been declared. C<use strict> was implied, even though you did not write it explicitly, because the C<STRICT> option added it for you automatically. Any variable referenced in the template that is not in the C<HASH> option will be an error. =head2 Prepending in Derived Classes This section is technical, and you should skip it on the first few readings. Normally there are three places that prepended text could come from. It could come from the C<PREPEND> option in the C<fill_in> call, from the C<PREPEND> option in the C<new> call that created the template object, or from the argument of the C<always_prepend> call. C<Text::Template> looks for these three things in order and takes the first one that it finds. In a subclass of C<Text::Template>, this last possibility is ambiguous. Suppose C<S> is a subclass of C<Text::Template>. Should Text::Template->always_prepend(...); affect objects in class C<Derived>? The answer is that you can have it either way. The C<always_prepend> value for C<Text::Template> is normally stored in a hash variable named C<%GLOBAL_PREPEND> under the key C<Text::Template>. When C<Text::Template> looks to see what text to prepend, it first looks in the template object itself, and if not, it looks in C<$GLOBAL_PREPEND{I<class>}> where I<class> is the class to which the template object belongs. If it doesn't find any value, it looks in C<$GLOBAL_PREPEND{'Text::Template'}>. This means that objects in class C<Derived> I<will> be affected by Text::Template->always_prepend(...); I<unless> there is also a call to Derived->always_prepend(...); So when you're designing your derived class, you can arrange to have your objects ignore C<Text::Template::always_prepend> calls by simply putting C<Derived-E<gt>always_prepend('')> at the top of your module. Of course, there is also a final escape hatch: Templates support a C<prepend_text> that is used to look up the appropriate text to be prepended at C<fill_in> time. Your derived class can override this method to get an arbitrary effect. =head2 JavaScript Jennifer D. St Clair asks: > Most of my pages contain JavaScript and Stylesheets. > How do I change the template identifier? Jennifer is worried about the braces in the JavaScript being taken as the delimiters of the Perl program fragments. Of course, disaster will ensue when perl tries to evaluate these as if they were Perl programs. The best choice is to find some unambiguous delimiter strings that you can use in your template instead of curly braces, and then use the C<DELIMITERS> option. However, if you can't do this for some reason, there are two easy workarounds: 1. You can put C<\> in front of C<{>, C<}>, or C<\> to remove its special meaning. So, for example, instead of if (br== "n3") { // etc. } you can put if (br== "n3") \{ // etc. \} and it'll come out of the template engine the way you want. But here is another method that is probably better. To see how it works, first consider what happens if you put this into a template: { 'foo' } Since it's in braces, it gets evaluated, and obviously, this is going to turn into foo So now here's the trick: In Perl, C<q{...}> is the same as C<'...'>. So if we wrote {q{foo}} it would turn into foo So for your JavaScript, just write {q{if (br== "n3") { // etc. }} } and it'll come out as if (br== "n3") { // etc. } which is what you want. head2 Shut Up! People sometimes try to put an initialization section at the top of their templates, like this: { ... $var = 17; } Then they complain because there is a C<17> at the top of the output that they didn't want to have there. Remember that a program fragment is replaced with its own return value, and that in Perl the return value of a code block is the value of the last expression that was evaluated, which in this case is 17. If it didn't do that, you wouldn't be able to write C<{$recipient}> and have the recipient filled in. To prevent the 17 from appearing in the output is very simple: { ... $var = 17; ''; } Now the last expression evaluated yields the empty string, which is invisible. If you don't like the way this looks, use { ... $var = 17; ($SILENTLY); } instead. Presumably, C<$SILENTLY> has no value, so nothing will be interpolated. This is what is known as a `trick'. =head2 Compatibility Every effort has been made to make this module compatible with older versions. The only known exceptions follow: The output format of the default C<BROKEN> subroutine has changed twice, most recently between versions 1.31 and 1.40. Starting in version 1.10, the C<$OUT> variable is arrogated for a special meaning. If you had templates before version 1.10 that happened to use a variable named C<$OUT>, you will have to change them to use some other variable or all sorts of strangeness will result. Between versions 0.1b and 1.00 the behavior of the \ metacharacter changed. In 0.1b, \\ was special everywhere, and the template processor always replaced it with a single backslash before passing the code to Perl for evaluation. The rule now is more complicated but probably more convenient. See the section on backslash processing, below, for a full discussion. =head2 Backslash Processing In C<Text::Template> beta versions, the backslash was special whenever it appeared before a brace or another backslash. That meant that while C<{"\n"}> did indeed generate a newline, C<{"\\"}> did not generate a backslash, because the code passed to Perl for evaluation was C<"\"> which is a syntax error. If you wanted a backslash, you would have had to write C<{"\\\\"}>. In C<Text::Template> versions 1.00 through 1.10, there was a bug: Backslash was special everywhere. In these versions, C<{"\n"}> generated the letter C<n>. The bug has been corrected in version 1.11, but I did not go back to exactly the old rule, because I did not like the idea of having to write C<{"\\\\"}> to get one backslash. The rule is now more complicated to remember, but probably easier to use. The rule is now: Backslashes are always passed to Perl unchanged I<unless> they occur as part of a sequence like C<\\\\\\{> or C<\\\\\\}>. In these contexts, they are special; C<\\> is replaced with C<\>, and C<\{> and C<\}> signal a literal brace. Examples: \{ foo \} is I<not> evaluated, because the C<\> before the braces signals that they should be taken literally. The result in the output looks like this: { foo } This is a syntax error: { "foo}" } because C<Text::Template> thinks that the code ends at the first C<}>, and then gets upset when it sees the second one. To make this work correctly, use { "foo\}" } This passes C<"foo}"> to Perl for evaluation. Note there's no C<\> in the evaluated code. If you really want a C<\> in the evaluated code, use { "foo\\\}" } This passes C<"foo\}"> to Perl for evaluation. Starting with C<Text::Template> version 1.20, backslash processing is disabled if you use the C<DELIMITERS> option to specify alternative delimiter strings. =head2 A short note about C<$Text::Template::ERROR> In the past some people have fretted about `violating the package boundary' by examining a variable inside the C<Text::Template> package. Don't feel this way. C<$Text::Template::ERROR> is part of the published, official interface to this package. It is perfectly OK to inspect this variable. The interface is not going to change. If it really, really bothers you, you can import a function called C<TTerror> that returns the current value of the C<$ERROR> variable. So you can say: use Text::Template 'TTerror'; my $template = Text::Template->new(SOURCE => $filename); unless ($template) { my $err = TTerror; die "Couldn't make template: $err; aborting"; } I don't see what benefit this has over just doing this: use Text::Template; my $template = Text::Template->new(SOURCE => $filename) or die "Couldn't make template: $Text::Template::ERROR; aborting"; But if it makes you happy to do it that way, go ahead. =head2 Sticky Widgets in Template Files The C<CGI> module provides functions for `sticky widgets', which are form input controls that retain their values from one page to the next. Sometimes people want to know how to include these widgets into their template output. It's totally straightforward. Just call the C<CGI> functions from inside the template: { $q->checkbox_group(NAME => 'toppings', LINEBREAK => true, COLUMNS => 3, VALUES => \@toppings, ); } =head2 Automatic preprocessing of program fragments It may be useful to preprocess the program fragments before they are evaluated. See C<Text::Template::Preprocess> for more details. =head2 Automatic postprocessing of template hunks It may be useful to process hunks of output before they are appended to the result text. For this, subclass and replace the C<append_text_to_result> method. It is passed a list of pairs with these entries: handle - a filehandle to which to print the desired output out - a ref to a string to which to append, to use if handle is not given text - the text that will be appended type - where the text came from: TEXT for literal text, PROG for code =head1 HISTORY Originally written by Mark Jason Dominus, Plover Systems (versions 0.01 - 1.46) Maintainership transferred to Michael Schout E<lt>mschout@cpan.orgE<gt> in version 1.47 =head1 THANKS Many thanks to the following people for offering support, encouragement, advice, bug reports, and all the other good stuff. =over 4 =item * Andrew G Wood =item * Andy Wardley =item * António Aragão =item * Archie Warnock =item * Bek Oberin =item * Bob Dougherty =item * Brian C. Shensky =item * Chris Nandor =item * Chris Wesley =item * Chris.Brezil =item * Daini Xie =item * Dan Franklin =item * Daniel LaLiberte =item * David H. Adler =item * David Marshall =item * Dennis Taylor =item * Donald L. Greer Jr. =item * Dr. Frank Bucolo =item * Fred Steinberg =item * Gene Damon =item * Hans Persson =item * Hans Stoop =item * Itamar Almeida de Carvalho =item * James H. Thompson =item * James Mastros =item * Jarko Hietaniemi =item * Jason Moore =item * Jennifer D. St Clair =item * Joel Appelbaum =item * Joel Meulenberg =item * Jonathan Roy =item * Joseph Cheek =item * Juan E. Camacho =item * Kevin Atteson =item * Kevin Madsen =item * Klaus Arnhold =item * Larry Virden =item * Lieven Tomme =item * Lorenzo Valdettaro =item * Marek Grac =item * Matt Womer =item * Matt X. Hunter =item * Michael G Schwern =item * Michael J. Suzio =item * Michaely Yeung =item * Michelangelo Grigni =item * Mike Brodhead =item * Niklas Skoglund =item * Randal L. Schwartz =item * Reuven M. Lerner =item * Robert M. Ioffe =item * Ron Pero =item * San Deng =item * Sean Roehnelt =item * Sergey Myasnikov =item * Shabbir J. Safdar =item * Shad Todd =item * Steve Palincsar =item * Tim Bunce =item * Todd A. Green =item * Tom Brown =item * Tom Henry =item * Tom Snee =item * Trip Lilley =item * Uwe Schneider =item * Val Luck =item * Yannis Livassof =item * Yonat Sharon =item * Zac Hansen =item * gary at dls.net =back Special thanks to: =over 2 =item Jonathan Roy for telling me how to do the C<Safe> support (I spent two years worrying about it, and then Jonathan pointed out that it was trivial.) =item Ranjit Bhatnagar for demanding less verbose fragments like they have in ASP, for helping me figure out the Right Thing, and, especially, for talking me out of adding any new syntax. These discussions resulted in the C<$OUT> feature. =back =head2 Bugs and Caveats C<my> variables in C<fill_in> are still susceptible to being clobbered by template evaluation. They all begin with C<fi_>, so avoid those names in your templates. The line number information will be wrong if the template's lines are not terminated by C<"\n">. You should let me know if this is a problem. If you do, I will fix it. The C<$OUT> variable has a special meaning in templates, so you cannot use it as if it were a regular variable. There are not quite enough tests in the test suite. =head1 SOURCE The development version is on github at L<https://https://github.com/mschout/perl-text-template> and may be cloned from L<git://https://github.com/mschout/perl-text-template.git> =head1 BUGS Please report any bugs or feature requests on the bugtracker website L<https://github.com/mschout/perl-text-template/issues> When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. =head1 AUTHOR Michael Schout <mschout@cpan.org> =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Mark Jason Dominus <mjd@cpan.org>. 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
jens-maus/amissl
openssl/external/perl/Text-Template-1.56/lib/Text/Template.pm
Perl
bsd-3-clause
67,996
=head1 This Week on perl5-porters (30 June / 6 July 2003) As the next maintenance release of perl is getting closer, the porters are still fixing bugs. Among the subjects that have been investigated this week, we can remember some hash-ordering-dependent bugs, process name problems, and more syntactic issues. =head2 Hashes that bite The hash seed randomization patch that was introduced last week (see our previous summary) uncovered some nasty bugs in perl and in its test suite. Craig Berry discovered a bug in the order of destruction of weak references. This was fixed by Dave Mitchell. Enache Adrian noticed that rebuilds were made quite more often. This was caused by some shuffling of the keys in the generated Config.pm. There were some hash-order dependent tests as well, sometimes the cause being deeply hidden in the harness, or in the internals of Test::Builder. Paul Johnson says that he expects I<some very impressive fireworks when this gets out into the wild>. And in fact Slaven Rezic obtains random failures with HTML::Mason (that would be caused by Exception::Class) and SOAP::Lite. =head2 Setting C<$0> Andreas Koenig and Jarkko Hietaniemi were (once again) working on the problem of setting the C<$0> variable and having it change the name by which the operating system knows the perl process. The problem is, of course, how to cope with the ideas the various platforms have about it. =head2 perl581delta Jarkko began to work (with the help of the porters) on the next incarnation of the F<perldelta> manpage, to be bundled with the upcoming perl 5.8.1. And he released a large number of maintperl snapshots. Release candidates are obviously getting closer. =head2 More syntax weirdness with indirect objects Dave Mitchell gives a snippet of code : sub f { f a; } f a; where the first C<f a> is an indirect method call, using the indirect object notation (it's equivalent to C<< a->f() >>), whereas the second C<f a> is equivalent to C<f(a)> (with C<a> being a bareword). I'd say this particular syntax oddity is sub-optimal, -- but the indirect object syntax is hairy. http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2003-07/msg00066.html =head2 Harness speed Abigail complained that Test::Harness prints a counter at each test, thus augmenting the amount of time needed to run large number of tests. This ended up in a patch. As says Andy Lester, Test::Harness' maintainer, I<now, when you run a test harnessed, the numbers don't fly by one at a time, one update per second.> (In the same thread, Gurusamy Sarathy recalls the HARNESS_NOTTY environment variable, that suppresses progress messages.) http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2003-07/msg00212.html =head2 Briefly Jarkko, after a suggestion by Robin Barker, added a new utility in perl's source distribution, F<Porting/Modules>, to list the official maintainers of the modules (this is mostly useful for the modules that have a dual life on CPAN). Michael Schwern pointed out that he was reinventing the Module::CoreList wheel ; and Jarkko removed this F<Modules>. Dan Kogai explained that FreeBSD comes with an implementation of malloc() that is optimized for paged memory, and safe from duplicate free() calls. But the downside is that realloc() is very slow. That's usually not a big deal, because most programs don't use realloc() very often -- but perl does. (The default configuration of perl on FreeBSD is to use perl's internal malloc, that hasn't this realloc limitation.) James Jurach provided a patch to use 32 bit integers instead of 16 bit integers for line numbers. As it didn't seem to increase the size of cops on several platforms, it went in. Steve Grazzini produced a patch for the C<my SLICE> syntax we discussed last week. Its implementation was criticized ; and it wasn't applied. As Randal L. Schwartz reported, the initial value of C<@INC> (and directory installation scheme) of perl on MacOS X has to be cleaned up, as it causes problems with C<make install UNINST=1> (a sub-optimally documented MakeMaker feature, used to uninstall previous versions found in C<@INC>). Vadim Konovalov provided more WinCE portability patches, with threads and fork emulation. Tels pre-released Math::BigInt v1.65, Math::BigRat v0.10, and bignum v0.14. Michael Schwern released MakeMaker 6.10_07. Perl 5 turned 20000 patches old. =head2 About this summary This week's summary was written by Rafael Garcia-Suarez. Weekly summaries are published on F<http://use.perl.org/> and on a mailing list, which subscription address is L<perl5-summary-subscribe@perl.org>. Comments, corrections, additions, and suggestions are (as always) welcome.
autarch/perlweb
docs/dev/perl5/list-summaries/2003/p5p-200307-1.pod
Perl
apache-2.0
4,693
#!/usr/bin/perl -w # # Rush # # Rush a JIRA issue to Done status. # # Author: Nathan Helenihi # package JiraLite::Command::Rush; use strict; use warnings; use base qw( CLI::Framework::Command ); use JiraLite::Config::Jira; use JiraLite::Lib::Credentials; use JIRA::Client::Automated; use Data::Dumper; # Rush a ticket to Done status sub run { # Validate and configure arguments my $num_args = $#ARGV + 1; if ($num_args != 1) { print usage_text(); exit; } my $issue_id = $ARGV[0]; # Instantiate JIRA client with credentials my $creds = new JiraLite::Lib::Credentials(); my ($user, $password) = $creds->getCredentials(); my $jira = JIRA::Client::Automated->new($JiraLite::Config::Jira::URL, $user, $password); # Transition issue my $result; eval { $result = $jira->transition_issue($issue_id, 'Done'); }; warn $@ if $@; print "\n"; if ($result) { print "Successfully rushed issue to 'Done'."; } else { print "Failed to rush issue to 'Done'."; } print "\n\n"; } sub usage_text { qq{ Usage: $0 <r|rush> <TID> $0 rush $JiraLite::Config::Jira::PROJECT-000 } } 1;
MyAllocator/jiralite
JiraLite/Command/Rush.pm
Perl
mit
1,198
/** This is an example that shows how to convert ACE sentences into OWL/SWRL. A simple Prolog commandline interface ('cli') is provided. @author Kaarel Kaljurand @version 2010-11-14 */ % We point to the directory where APE modules and the lexicons are located. :- assert(user:file_search_path(ape, '../prolog')). :- use_module(ape('parser/ace_to_drs'), [ acetext_to_drs/5 ]). :- use_module(ape('utils/drs_to_ascii'), [ drs_to_ascii/2 ]). :- use_module(ape('utils/owlswrl/drs_to_owlswrl'), [ drs_to_owlswrl/4 ]). % Import the lexicons :- style_check(-singleton). :- style_check(-discontiguous). :- use_module(ape('lexicon/clex')). :- use_module(ape('lexicon/ulex')). :- style_check(+discontiguous). :- style_check(+singleton). :- use_module(ape('logger/error_logger'), [ clear_messages/0, get_messages/1 ]). :- use_module(ape('utils/owlswrl/owlswrl_to_fss'), [ owlswrl_to_fss/1 ]). :- use_module(ape('utils/owlswrl/owlswrl_to_xml'), [ owlswrl_to_xml/2 ]). t(AceText, Owl) :- clear_messages, acetext_to_drs(AceText, _, _, Drs, _), drs_to_owlswrl(Drs, test, 'Ontology from an ACE text.', Owl). t(AceText) :- clear_messages, acetext_to_drs(AceText, _, _, Drs, _), drs_to_ascii(Drs, DrsAscii), format("~w~n", [DrsAscii]), drs_to_owlswrl(Drs, test, 'Ontology from an ACE text.', Owl), get_messages(Messages), format("Messages: ~w~n~n", [Messages]), owlswrl_to_fss(Owl), nl, owlswrl_to_xml(Owl, XML), xml_write(user, XML, [layout(true), indent(0), header(false), net(true)]), format("~n~n"), !. t(_) :- format("Something failed.~n~n"). % Commandline interface cli :- clear_messages, prompt(Old, 'ACE to OWL> '), read_text_from_commandline(AceText), prompt(_, Old), t(AceText), cli. read_text_from_commandline([C | R]) :- get0(C), line_continues(C), !, read_text_from_commandline(R). read_text_from_commandline([]). multiline(false). line_continues(C) :- C \== 10, C \== -1, !. line_continues(C) :- multiline(true), C \== -1.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/ape/examples/ace_to_owl.pl
Perl
mit
1,985
#!usr\bin\perl open(my $fh, "<", "pbf_tabs.txt") or die "can't open pbr_tabs.txt"; my $header = "<style> table { width : 100%; position : absolute; } tr:nth-child(odd) { background: #f8f8f8; } #sold { background: #787878; } #rightcolumn { position : fixed; top : 0; right : 0; height : 100%; width : 50%; } #leftcolumn { position : absolute; top : 0; left : 0; height : 100%; width : 50%; } </style>"; my $pageOUT = "$header<div id=\"leftcolumn\">\n<table>"; while( my $line = <$fh>) { my @row = split('\t',$line); #print @row[0]."\n"; my $link =""; my $imgLink = ""; #wont always be a link if(trim(@row[0]) ne "-") { @row[1] = trim(@row[1]); $link = "<a name=\"@row[1]\" href=\"@row[0]\" target=\"content\">@row[1]</a>"; my $comicNum = @row[0]; $comicNum =~ /.*\/([0-9]+)\/$/; $comicNum = $1; my $dashName = @row[1]; $dashName =~ s/\s/_/g; $imgURL = "http://pbfcomics.com/archive_b/PBF$comicNum-$dashName.png"; $imgLink = "<a name=\"@row[1]img\" href=\"$imgURL\" target=\"content\">IMAGE</a>"; #$imgLink = http://pbfcomics.com/archive_b/PBF253-The_Last_Unicorns.jpg } else { $link = "@row[1]"; $imgLink = "-"} if ($row[3] !~ m/[0-9]/) { $pageOUT.="\t<tr id=\"sold\">\n"; } else { $pageOUT.="\t<tr>\n"; } foreach ($link, @row[2..3]) { $pageOUT.="\t\t<td>$_</td>\n"; } $pageOUT.="\t</tr>\n"; } $pageOUT.="</div> <div id=\"rightcolumn\"> <iframe name=\"content\" src=\"http://pbfcomics.com\" width = \"100%\" height = \"100%\" frameborder=\"0\"> </div>"; open (FILEOUT, '>pbrTABLE.html'); print FILEOUT $pageOUT; close (FILEOUT) or die "can't write"; close $fh; sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
peltzel/peltzel.github.io
page_script.pl
Perl
mit
1,842
package Net::Braintree::Transaction; use Net::Braintree::Transaction::CreatedUsing; use Net::Braintree::Transaction::EscrowStatus; use Net::Braintree::Transaction::Source; use Net::Braintree::Transaction::Status; use Net::Braintree::Transaction::Type; use Moose; extends "Net::Braintree::ResultObject"; my $meta = __PACKAGE__->meta; sub BUILD { my ($self, $attributes) = @_; my $sub_objects = { 'disputes' => 'Net::Braintree::Dispute'}; $meta->add_attribute('subscription', is => 'rw'); $self->subscription(Net::Braintree::Subscription->new($attributes->{subscription})) if ref($attributes->{subscription}) eq 'HASH'; delete($attributes->{subscription}); $meta->add_attribute('disbursement_details', is => 'rw'); $self->disbursement_details(Net::Braintree::DisbursementDetails->new($attributes->{disbursement_details})) if ref($attributes->{disbursement_details}) eq 'HASH'; delete($attributes->{disbursement_details}); $meta->add_attribute('paypal_details', is => 'rw'); $self->paypal_details(Net::Braintree::PayPalDetails->new($attributes->{paypal})) if ref($attributes->{paypal}) eq 'HASH'; delete($attributes->{paypal}); $self->setup_sub_objects($self, $attributes, $sub_objects); $self->set_attributes_from_hash($self, $attributes); } sub sale { my ($class, $params) = @_; $class->create($params, 'sale'); } sub credit { my ($class, $params) = @_; $class->create($params, 'credit'); } sub submit_for_settlement { my ($class, $id) = @_; $class->gateway->transaction->submit_for_settlement($id); } sub void { my ($class, $id) = @_; $class->gateway->transaction->void($id); } sub refund { my ($class, $id, $amount) = @_; my $params = {}; $params->{'amount'} = $amount if $amount; $class->gateway->transaction->refund($id, $params); } sub create { my ($class, $params, $type) = @_; $params->{'type'} = $type; $class->gateway->transaction->create($params); } sub find { my ($class, $id) = @_; $class->gateway->transaction->find($id); } sub search { my ($class, $block) = @_; $class->gateway->transaction->search($block); } sub hold_in_escrow { my ($class, $id) = @_; $class->gateway->transaction->hold_in_escrow($id); } sub release_from_escrow { my ($class, $id) = @_; $class->gateway->transaction->release_from_escrow($id); } sub cancel_release { my ($class, $id) = @_; $class->gateway->transaction->cancel_release($id); } sub all { my $class = shift; $class->gateway->transaction->all; } sub clone_transaction { my ($class, $id, $params) = @_; $class->gateway->transaction->clone_transaction($id, $params); } sub gateway { Net::Braintree->configuration->gateway; } sub is_disbursed { my $self = shift; $self->disbursement_details->is_valid(); }; 1;
gitpan/Net-Braintree
lib/Net/Braintree/Transaction.pm
Perl
mit
2,761
package SGN::Controller::solGS::Heritability; use Moose; use namespace::autoclean; use File::Slurp qw /write_file read_file/; use JSON; use Math::Round::Var; use Statistics::Descriptive; BEGIN { extends 'Catalyst::Controller' } sub check_regression_data :Path('/heritability/check/data/') Args(0) { my ($self, $c) = @_; my $trait_id = $c->req->param('trait_id'); my $pop_id = $c->req->param('training_pop_id'); my $combo_pops_id = $c->req->param('combo_pops_id'); my $protocol_id = $c->req->param('genotyping_protocol_id'); $c->controller('solGS::genotypingProtocol')->stash_protocol_id($c, $protocol_id); $c->stash->{data_set_type} = 'combined populations' if $combo_pops_id; $c->stash->{combo_pops_id} = $combo_pops_id; $c->stash->{pop_id} = $pop_id; $c->stash->{training_pop_id} = $pop_id; $c->controller('solGS::solGS')->get_trait_details($c, $trait_id); $self->get_regression_data_files($c); my $ret->{exists} = undef; my $gebv_file = $c->stash->{regression_gebv_file}; my $pheno_file = $c->stash->{regression_pheno_file}; if(-s $gebv_file && -s $pheno_file) { $ret->{exists} = 'yes'; } $ret = to_json($ret); $c->res->content_type('application/json'); $c->res->body($ret); } sub get_regression_data_files { my ($self, $c) = @_; my $pop_id = $c->stash->{pop_id}; my $trait_abbr = $c->stash->{trait_abbr}; my $cache_dir = $c->stash->{solgs_cache_dir}; $c->controller('solGS::Files')->model_phenodata_file($c); my $phenotype_file = $c->stash->{model_phenodata_file}; $c->controller('solGS::Files')->rrblup_training_gebvs_file($c); my $gebv_file = $c->stash->{rrblup_training_gebvs_file}; $c->stash->{regression_gebv_file} = $gebv_file; $c->stash->{regression_pheno_file} = $phenotype_file; } sub get_heritability { my ($self, $c, $pop_id, $trait_id) = @_; $c->controller("solGS::solGS")->get_trait_details($c, $trait_id); $c->controller('solGS::Files')->variance_components_file($c); my $var_comp_file = $c->stash->{variance_components_file}; my ($txt, $value) = map { split(/\t/) } grep {/SNP heritability/} read_file($var_comp_file, {binmode => ':utf8'}); return $value; } sub get_additive_variance { my ($self, $c, $pop_id, $trait_id) = @_; $c->controller("solGS::solGS")->get_trait_details($c, $trait_id); $c->controller('solGS::Files')->variance_components_file($c); my $var_comp_file = $c->stash->{variance_components_file}; my ($txt, $value) = map { split(/\t/) } grep {/Additive genetic/} read_file($var_comp_file, {binmode => ':utf8'}); return $value; } sub heritability_regeression_data :Path('/heritability/regression/data/') Args(0) { my ($self, $c) = @_; my $trait_id = $c->req->param('trait_id'); my $pop_id = $c->req->param('training_pop_id'); my $combo_pops_id = $c->req->param('combo_pops_id'); my $protocol_id = $c->req->param('genotyping_protocol_id'); $c->controller('solGS::genotypingProtocol')->stash_protocol_id($c, $protocol_id); $c->stash->{pop_id} = $pop_id; $c->stash->{training_pop_id} = $pop_id; $c->stash->{data_set_type} = 'combined populations' if $combo_pops_id; $c->stash->{combo_pops_id} = $combo_pops_id; $c->controller('solGS::solGS')->get_trait_details($c, $trait_id); $self->get_regression_data_files($c); my $gebv_file = $c->stash->{regression_gebv_file}; my $pheno_file = $c->stash->{regression_pheno_file}; my @gebv_data = map { $_ =~ s/\n//; $_ } read_file($gebv_file, {binmode => ':utf8'}); my @pheno_data = map { $_ =~ s/\n//; $_ } read_file($pheno_file, {binmode => ':utf8'}); @gebv_data = map { [ split(/\t/) ] } @gebv_data; @pheno_data = map { [ split(/\t/) ] } @pheno_data; my @pheno_values = map { $_->[1] } @pheno_data; shift(@pheno_values); shift(@gebv_data); shift(@pheno_data); my $stat = Statistics::Descriptive::Full->new(); $stat->add_data(@pheno_values); my $pheno_mean = $stat->mean(); my $round = Math::Round::Var->new(0.01); my @pheno_deviations = map { [$_->[0], $round->round(( $_->[1] - $pheno_mean ))] } @pheno_data; my $heritability = $self->get_heritability($c, $pop_id, $trait_id); my $ret->{status} = 'failed'; if (@gebv_data && @pheno_data) { $ret->{status} = 'success'; $ret->{gebv_data} = \@gebv_data; $ret->{pheno_deviations} = \@pheno_deviations; $ret->{pheno_data} = \@pheno_data; $ret->{heritability} = $heritability; } $ret = to_json($ret); $c->res->content_type('application/json'); $c->res->body($ret); } sub begin : Private { my ($self, $c) = @_; $c->controller('solGS::Files')->get_solgs_dirs($c); } #### 1; ####
solgenomics/sgn
lib/SGN/Controller/solGS/Heritability.pm
Perl
mit
4,989
package t::lib::HTTP::NGHTTP2::Trap; use strict; use warnings; use overload '""' => sub { my $self = shift; $self->(); return "poison"; }; sub new { my ($class, $code) = @_; return bless($code, $class); } 1;
gonzus/http-nghttp2
t/lib/HTTP/NGHTTP2/Trap.pm
Perl
mit
231
use strict; # # This is a SAS Component # use Data::Dumper; use Carp; use SeedEnv; my $usage = "usage: CSA_layout WorkingDir PegTbl1 RnaTbl1 Functions1"; my($dir,$peg_tbl1,$rna_tbl1,$functions1); ( ($dir = shift @ARGV) && (-s "$dir/output.second.pass") && ($peg_tbl1 = shift @ARGV) && (-s $peg_tbl1) && ($rna_tbl1 = shift @ARGV) && (-s $rna_tbl1) && ($functions1 = shift @ARGV) && (-s $functions1) ) || die $usage; my %func_of = map { ($_ =~ /^(fig\S+)\t(\S.*\S)/) ? ($1 => $2) : () } `cat $functions1`; my %to_abbrev = map { $_ =~ /^(\S+)\t(\S+)/; ($2 => $1) } `cat $dir/index1`; my $n = 0; my @pins = map { chop; [split(/\t/,$_)] } `cat $dir/output.second.pass`; my @repeats = map { chop; [split(/\t/,$_)] } `cat $dir/repeats2`; my @points; @pins = sort { ($a->[0] cmp $b->[0]) || ($a->[1] <=> $b->[1]) } @pins; my $n = 1; foreach my $_ (@pins) { push(@points,[$_->[3],$_->[4],'start',$_->[6] . ":" . $n]); push(@points,[$_->[3],$_->[5],'start',$_->[6] . ":" . $n++]); } $n = 1; foreach my $_ (@repeats) { push(@points,[$_->[0],$_->[1],'start','repeat' . ":" . $n]); push(@points,[$_->[0],$_->[2],'end','repeat' . ":" . $n++]); } my $mapped = 0; my $not_mapped = 0; foreach $_ (`cat $peg_tbl1`,`cat $rna_tbl1`) { if ($_ =~ /^(fig\|\S+)\t(\S+)/) { my $peg = $1; my($contig,$left,$right,$strand) = &SeedUtils::boundaries_of($2); my($beg,$end) = ($strand eq "+") ? ($left,$right) : ($right,$left); my $f = $func_of{$peg} ? $func_of{$peg} : ''; my($ptB,$ptE); if ($ptB = &locate($to_abbrev{$contig},$beg,\@pins)) { push(@points,[@$ptB,'start',$peg,$f]); $mapped++; } else { $not_mapped++; } if (my $ptE = &locate($to_abbrev{$contig},$end,\@pins)) { push(@points,[@$ptE,'end',$peg,$f]); $mapped++; } else { $not_mapped++; } } } @points = sort { ($a->[0] cmp $b->[0]) or ($a->[1] <=> $b->[1]) } @points; print "mapped gene boundaries = $mapped\n"; print "unmapped gene boundaries = $not_mapped\n"; foreach my $pt (@points) { print join("\t",@$pt),"\n"; } sub locate { my($contig,$x,$pins) = @_; foreach $_ (@$pins) { my($c1,$b1,$e1,$c2,$b2,$e2) = @$_; if (($contig eq $c1) && ($x >= $b1) && ($x <= $e1)) { my $incr = $x - $b1; return [$c2,($b2 < $e2) ? ($b2 + $incr) : ($b2 - $incr)]; } } return undef; }
kbase/kb_seed
service-scripts/CSA_layout.pl
Perl
mit
2,369
package Proverb; use strict; use warnings; sub proverb { my ( $items, $qualifier ) = @_; return undef; } __PACKAGE__;
exercism/xperl5
exercises/practice/proverb/Proverb.pm
Perl
mit
128
use Win32::OLE::Const "^Microsoft CDO for Windows 2000 Library"; #use Win32::OLE::Const ".*CDO"; #volstaat om de bibliotheek te vinden print "\ncdoSendUsingPort : ",cdoSendUsingPort; #toont de waarde use Win32::OLE::Const "^Microsoft Excel"; #use Win32::OLE::Const ".*Excel"; #volstaat om de bibliotheek te vinden print "\nxlHorizontaal : ",xlHorizontal; print "\nniet bestaand : ",xlHorizontaal; #geeft de naam zelf terug
VDBBjorn/Besturingssystemen-III
Labo/reeks1/Reeks1_08.pl
Perl
mit
440
#!/usr/bin/env perl use strict; use File::Basename qw(basename); my @ORIG_ARGV=@ARGV; use Cwd qw(getcwd); my $SCRIPT_DIR; BEGIN { use Cwd qw/ abs_path /; use File::Basename; $SCRIPT_DIR = dirname(abs_path($0)); push @INC, $SCRIPT_DIR, "$SCRIPT_DIR/../../environment", "$SCRIPT_DIR/../utils"; } # Skip local config (used for distributing jobs) if we're running in local-only mode use LocalConfig; use Getopt::Long; use IPC::Open2; use POSIX ":sys_wait_h"; my $QSUB_CMD = qsub_args(mert_memory()); my $default_jobs = env_default_jobs(); my $UTILS_DIR="$SCRIPT_DIR/../utils"; require "$UTILS_DIR/libcall.pl"; # Default settings my $srcFile; my $refFiles; my $bin_dir = $SCRIPT_DIR; die "Bin directory $bin_dir missing/inaccessible" unless -d $bin_dir; my $FAST_SCORE="$bin_dir/../../mteval/fast_score"; die "Can't execute $FAST_SCORE" unless -x $FAST_SCORE; my $MAPINPUT = "$bin_dir/mr_pro_generate_mapper_input.pl"; my $MAPPER = "$bin_dir/mr_pro_map"; my $REDUCER = "$bin_dir/mr_pro_reduce"; my $parallelize = "$UTILS_DIR/parallelize.pl"; my $libcall = "$UTILS_DIR/libcall.pl"; my $sentserver = "$UTILS_DIR/sentserver"; my $sentclient = "$UTILS_DIR/sentclient"; my $LocalConfig = "$SCRIPT_DIR/../../environment/LocalConfig.pm"; my $SCORER = $FAST_SCORE; die "Can't find $MAPPER" unless -x $MAPPER; my $cdec = "$bin_dir/../../decoder/cdec"; die "Can't find decoder in $cdec" unless -x $cdec; die "Can't find $parallelize" unless -x $parallelize; die "Can't find $libcall" unless -e $libcall; my $decoder = $cdec; my $lines_per_mapper = 30; my $iteration = 1; my $best_weights; my $psi = 1; my $default_max_iter = 30; my $max_iterations = $default_max_iter; my $jobs = $default_jobs; # number of decode nodes my $pmem = "4g"; my $disable_clean = 0; my %seen_weights; my $help = 0; my $epsilon = 0.0001; my $dryrun = 0; my $last_score = -10000000; my $metric = "ibm_bleu"; my $dir; my $iniFile; my $weights; my $use_make = 1; # use make to parallelize my $useqsub = 0; my $initial_weights; my $pass_suffix = ''; my $devset; # regularization strength my $reg = 500; my $reg_previous = 5000; # Process command-line options if (GetOptions( "config=s" => \$iniFile, "weights=s" => \$initial_weights, "devset=s" => \$devset, "jobs=i" => \$jobs, "metric=s" => \$metric, "pass-suffix=s" => \$pass_suffix, "qsub" => \$useqsub, "help" => \$help, "reg=f" => \$reg, "reg-previous=f" => \$reg_previous, "output-dir=s" => \$dir, ) == 0 || @ARGV!=0 || $help) { print_help(); exit; } if ($useqsub) { $use_make = 0; die "LocalEnvironment.pm does not have qsub configuration for this host. Cannot run with --qsub!\n" unless has_qsub(); } my @missing_args = (); if (!defined $iniFile) { push @missing_args, "--config"; } if (!defined $devset) { push @missing_args, "--devset"; } if (!defined $initial_weights) { push @missing_args, "--weights"; } die "Please specify missing arguments: " . join (', ', @missing_args) . "\n" if (@missing_args); if ($metric =~ /^(combi|ter)$/i) { $lines_per_mapper = 5; } my $host =check_output("hostname"); chomp $host; my $bleu; my $interval_count = 0; my $logfile; my $projected_score; # used in sorting scores my $DIR_FLAG = '-r'; if ($metric =~ /^ter$|^aer$/i) { $DIR_FLAG = ''; } unless ($dir){ $dir = 'pro'; } unless ($dir =~ /^\//){ # convert relative path to absolute path my $basedir = check_output("pwd"); chomp $basedir; $dir = "$basedir/$dir"; } # Initializations and helper functions srand; my @childpids = (); my @cleanupcmds = (); sub cleanup { print STDERR "Cleanup...\n"; for my $pid (@childpids){ unchecked_call("kill $pid"); } for my $cmd (@cleanupcmds){ unchecked_call("$cmd"); } exit 1; }; # Always call cleanup, no matter how we exit *CORE::GLOBAL::exit = sub{ cleanup(); }; $SIG{INT} = "cleanup"; $SIG{TERM} = "cleanup"; $SIG{HUP} = "cleanup"; my $decoderBase = check_output("basename $decoder"); chomp $decoderBase; my $newIniFile = "$dir/$decoderBase.ini"; my $inputFileName = "$dir/input"; my $user = $ENV{"USER"}; # process ini file -e $iniFile || die "Error: could not open $iniFile for reading\n"; open(INI, $iniFile); if (-e $dir) { die "ERROR: working dir $dir already exists\n\n"; } else { mkdir "$dir" or die "Can't mkdir $dir: $!"; mkdir "$dir/hgs" or die; mkdir "$dir/scripts" or die; print STDERR <<EOT; DECODER: $decoder INI FILE: $iniFile WORKING DIR: $dir DEVSET: $devset EVAL METRIC: $metric MAX ITERATIONS: $max_iterations PARALLEL JOBS: $jobs HEAD NODE: $host PMEM (DECODING): $pmem INITIAL WEIGHTS: $initial_weights EOT } # Generate initial files and values check_call("cp $iniFile $newIniFile"); check_call("cp $initial_weights $dir/weights.0"); $iniFile = $newIniFile; my $refs = "$dir/dev.refs"; split_devset($devset, "$dir/dev.input.raw", $refs); my $newsrc = "$dir/dev.input"; enseg("$dir/dev.input.raw", $newsrc); $srcFile = $newsrc; my $devSize = 0; open F, "<$srcFile" or die "Can't read $srcFile: $!"; while(<F>) { $devSize++; } close F; unless($best_weights){ $best_weights = $weights; } unless($projected_score){ $projected_score = 0.0; } $seen_weights{$weights} = 1; my $random_seed = int(time / 1000); my $lastWeightsFile; my $lastPScore = 0; # main optimization loop my @allweights; while (1){ print STDERR "\n\nITERATION $iteration\n==========\n"; if ($iteration > $max_iterations){ print STDERR "\nREACHED STOPPING CRITERION: Maximum iterations\n"; last; } # iteration-specific files my $runFile="$dir/run.raw.$iteration"; my $onebestFile="$dir/1best.$iteration"; my $logdir="$dir/logs.$iteration"; my $decoderLog="$logdir/decoder.sentserver.log.$iteration"; my $scorerLog="$logdir/scorer.log.$iteration"; check_call("mkdir -p $logdir"); #decode print STDERR "RUNNING DECODER AT "; print STDERR unchecked_output("date"); my $im1 = $iteration - 1; my $weightsFile="$dir/weights.$im1"; push @allweights, "-w $dir/weights.$im1"; `rm -f $dir/hgs/*.gz`; my $decoder_cmd = "$decoder -c $iniFile --weights$pass_suffix $weightsFile -O $dir/hgs"; my $pcmd; if ($use_make) { $pcmd = "cat $srcFile | $parallelize --use-fork -p $pmem -e $logdir -j $jobs --"; } else { $pcmd = "cat $srcFile | $parallelize -p $pmem -e $logdir -j $jobs --"; } my $cmd = "$pcmd $decoder_cmd 2> $decoderLog 1> $runFile"; print STDERR "COMMAND:\n$cmd\n"; check_bash_call($cmd); my $num_hgs; my $num_topbest; my $retries = 0; while($retries < 5) { $num_hgs = check_output("ls $dir/hgs/*.gz | wc -l"); $num_topbest = check_output("wc -l < $runFile"); print STDERR "NUMBER OF HGs: $num_hgs\n"; print STDERR "NUMBER OF TOP-BEST HYPs: $num_topbest\n"; if($devSize == $num_hgs && $devSize == $num_topbest) { last; } else { print STDERR "Incorrect number of hypergraphs or topbest. Waiting for distributed filesystem and retrying...\n"; sleep(3); } $retries++; } die "Dev set contains $devSize sentences, but we don't have topbest and hypergraphs for all these! Decoder failure? Check $decoderLog\n" if ($devSize != $num_hgs || $devSize != $num_topbest); my $dec_score = check_output("cat $runFile | $SCORER -r $refs -m $metric"); chomp $dec_score; print STDERR "DECODER SCORE: $dec_score\n"; # save space check_call("gzip -f $runFile"); check_call("gzip -f $decoderLog"); # run optimizer print STDERR "RUNNING OPTIMIZER AT "; print STDERR unchecked_output("date"); print STDERR " - GENERATE TRAINING EXEMPLARS\n"; my $mergeLog="$logdir/prune-merge.log.$iteration"; my $score = 0; my $icc = 0; my $inweights="$dir/weights.$im1"; $cmd="$MAPINPUT $dir/hgs > $dir/agenda.$im1"; print STDERR "COMMAND:\n$cmd\n"; check_call($cmd); check_call("mkdir -p $dir/splag.$im1"); $cmd="split -a 3 -l $lines_per_mapper $dir/agenda.$im1 $dir/splag.$im1/mapinput."; print STDERR "COMMAND:\n$cmd\n"; check_call($cmd); opendir(DIR, "$dir/splag.$im1") or die "Can't open directory: $!"; my @shards = grep { /^mapinput\./ } readdir(DIR); closedir DIR; die "No shards!" unless scalar @shards > 0; my $joblist = ""; my $nmappers = 0; @cleanupcmds = (); my %o2i = (); my $first_shard = 1; my $mkfile; # only used with makefiles my $mkfilename; if ($use_make) { $mkfilename = "$dir/splag.$im1/domap.mk"; open $mkfile, ">$mkfilename" or die "Couldn't write $mkfilename: $!"; print $mkfile "all: $dir/splag.$im1/map.done\n\n"; } my @mkouts = (); # only used with makefiles my @mapoutputs = (); for my $shard (@shards) { my $mapoutput = $shard; my $client_name = $shard; $client_name =~ s/mapinput.//; $client_name = "pro.$client_name"; $mapoutput =~ s/mapinput/mapoutput/; push @mapoutputs, "$dir/splag.$im1/$mapoutput"; $o2i{"$dir/splag.$im1/$mapoutput"} = "$dir/splag.$im1/$shard"; my $script = "$MAPPER -s $srcFile -m $metric -r $refs -w $inweights -K $dir/kbest < $dir/splag.$im1/$shard > $dir/splag.$im1/$mapoutput"; if ($use_make) { my $script_file = "$dir/scripts/map.$shard"; open F, ">$script_file" or die "Can't write $script_file: $!"; print F "#!/bin/bash\n"; print F "$script\n"; close F; my $output = "$dir/splag.$im1/$mapoutput"; push @mkouts, $output; chmod(0755, $script_file) or die "Can't chmod $script_file: $!"; if ($first_shard) { print STDERR "$script\n"; $first_shard=0; } print $mkfile "$output: $dir/splag.$im1/$shard\n\t$script_file\n\n"; } else { my $script_file = "$dir/scripts/map.$shard"; open F, ">$script_file" or die "Can't write $script_file: $!"; print F "$script\n"; close F; if ($first_shard) { print STDERR "$script\n"; $first_shard=0; } $nmappers++; my $qcmd = "$QSUB_CMD -N $client_name -o /dev/null -e $logdir/$client_name.ER $script_file"; my $jobid = check_output("$qcmd"); chomp $jobid; $jobid =~ s/^(\d+)(.*?)$/\1/g; $jobid =~ s/^Your job (\d+) .*$/\1/; push(@cleanupcmds, "qdel $jobid 2> /dev/null"); print STDERR " $jobid"; if ($joblist == "") { $joblist = $jobid; } else {$joblist = $joblist . "\|" . $jobid; } } } my @dev_outs = (); my @devtest_outs = (); @dev_outs = @mapoutputs; if ($use_make) { print $mkfile "$dir/splag.$im1/map.done: @mkouts\n\ttouch $dir/splag.$im1/map.done\n\n"; close $mkfile; my $mcmd = "make -j $jobs -f $mkfilename"; print STDERR "\nExecuting: $mcmd\n"; check_call($mcmd); } else { print STDERR "\nLaunched $nmappers mappers.\n"; sleep 8; print STDERR "Waiting for mappers to complete...\n"; while ($nmappers > 0) { sleep 5; my @livejobs = grep(/$joblist/, split(/\n/, unchecked_output("qstat | grep -v ' C '"))); $nmappers = scalar @livejobs; } print STDERR "All mappers complete.\n"; } my $tol = 0; my $til = 0; my $dev_test_file = "$dir/splag.$im1/devtest.gz"; print STDERR "\nRUNNING CLASSIFIER (REDUCER)\n"; print STDERR unchecked_output("date"); $cmd="cat @dev_outs | $REDUCER -w $dir/weights.$im1 -C $reg -y $reg_previous --interpolate_with_weights $psi"; $cmd .= " > $dir/weights.$iteration"; print STDERR "COMMAND:\n$cmd\n"; check_bash_call($cmd); $lastWeightsFile = "$dir/weights.$iteration"; $lastPScore = $score; $iteration++; print STDERR "\n==========\n"; } check_call("cp $lastWeightsFile $dir/weights.final"); print STDERR "\nFINAL WEIGHTS: $dir/weights.final\n(Use -w <this file> with the decoder)\n\n"; print STDOUT "$dir/weights.final\n"; exit 0; sub read_weights_file { my ($file) = @_; open F, "<$file" or die "Couldn't read $file: $!"; my @r = (); my $pm = -1; while(<F>) { next if /^#/; next if /^\s*$/; chomp; if (/^(.+)\s+(.+)$/) { my $m = $1; my $w = $2; die "Weights out of order: $m <= $pm" unless $m > $pm; push @r, $w; } else { warn "Unexpected feature name in weight file: $_"; } } close F; return join ' ', @r; } sub enseg { my $src = shift; my $newsrc = shift; open(SRC, $src); open(NEWSRC, ">$newsrc"); my $i=0; while (my $line=<SRC>){ chomp $line; if ($line =~ /^\s*<seg/i) { if($line =~ /id="[0-9]+"/) { print NEWSRC "$line\n"; } else { die "When using segments with pre-generated <seg> tags, you must include a zero-based id attribute"; } } else { print NEWSRC "<seg id=\"$i\">$line</seg>\n"; } $i++; } close SRC; close NEWSRC; die "Empty dev set!" if ($i == 0); } sub print_help { my $executable = basename($0); chomp $executable; print << "Help"; Usage: $executable [options] $executable [options] Runs a complete PRO optimization using the ini file specified. Required: --config <cdec.ini> Decoder configuration file. --devset <files> Dev set source and reference data. --weights <file> Initial weights file (use empty file to start from 0) General options: --help Print this message and exit. --max-iterations <M> Maximum number of iterations to run. If not specified, defaults to $default_max_iter. --metric <method> Metric to optimize. Example values: IBM_BLEU, NIST_BLEU, Koehn_BLEU, TER, Combi --pass-suffix <S> If the decoder is doing multi-pass decoding, the pass suffix "2", "3", etc., is used to control what iteration of weights is set. --workdir <dir> Directory for intermediate and output files. If not specified, the name is derived from the ini filename. Assuming that the ini filename begins with the decoder name and ends with ini, the default name of the working directory is inferred from the middle part of the filename. E.g. an ini file named decoder.foo.ini would have a default working directory name foo. Regularization options: --reg <F> l2 regularization strength [default=500]. The greater this value, the closer to zero the weights will be. --reg-previous <F> l2 penalty for moving away from the weights from the previous iteration. [default=5000]. The greater this value, the closer to the previous iteration's weights the next iteration's weights will be. Job control options: --jobs <I> Number of decoder processes to run in parallel. [default=$default_jobs] --qsub Use qsub to run jobs in parallel (qsub must be configured in environment/LocalEnvironment.pm) --pmem <N> Amount of physical memory requested for parallel decoding jobs (used with qsub requests only) Deprecated options: --interpolate-with-weights <F> [deprecated] At each iteration the resulting weights are interpolated with the weights from the previous iteration, with this factor. [default=1.0, i.e., no effect] Help } sub convert { my ($str) = @_; my @ps = split /;/, $str; my %dict = (); for my $p (@ps) { my ($k, $v) = split /=/, $p; $dict{$k} = $v; } return %dict; } sub cmdline { return join ' ',($0,@ORIG_ARGV); } #buggy: last arg gets quoted sometimes? my $is_shell_special=qr{[ \t\n\\><|&;"'`~*?{}$!()]}; my $shell_escape_in_quote=qr{[\\"\$`!]}; sub escape_shell { my ($arg)=@_; return undef unless defined $arg; if ($arg =~ /$is_shell_special/) { $arg =~ s/($shell_escape_in_quote)/\\$1/g; return "\"$arg\""; } return $arg; } sub escaped_shell_args { return map {local $_=$_;chomp;escape_shell($_)} @_; } sub escaped_shell_args_str { return join ' ',&escaped_shell_args(@_); } sub escaped_cmdline { return "$0 ".&escaped_shell_args_str(@ORIG_ARGV); } sub split_devset { my ($infile, $outsrc, $outref) = @_; open F, "<$infile" or die "Can't read $infile: $!"; open S, ">$outsrc" or die "Can't write $outsrc: $!"; open R, ">$outref" or die "Can't write $outref: $!"; while(<F>) { chomp; my ($src, @refs) = split /\s*\|\|\|\s*/; die "Malformed devset line: $_\n" unless scalar @refs > 0; print S "$src\n"; print R join(' ||| ', @refs) . "\n"; } close R; close S; close F; }
kho/mr-cdec
training/pro/pro.pl
Perl
apache-2.0
15,825
package Paws::DynamoDB::KeySchemaElement; use Moose; has AttributeName => (is => 'ro', isa => 'Str', required => 1); has KeyType => (is => 'ro', isa => 'Str', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::DynamoDB::KeySchemaElement =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::DynamoDB::KeySchemaElement object: $service_obj->Method(Att1 => { AttributeName => $value, ..., KeyType => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::DynamoDB::KeySchemaElement object: $result = $service_obj->Method(...); $result->Att1->AttributeName =head1 DESCRIPTION Represents I<a single element> of a key schema. A key schema specifies the attributes that make up the primary key of a table, or the key attributes of an index. A C<KeySchemaElement> represents exactly one attribute of the primary key. For example, a simple primary key would be represented by one C<KeySchemaElement> (for the partition key). A composite primary key would require one C<KeySchemaElement> for the partition key, and another C<KeySchemaElement> for the sort key. A C<KeySchemaElement> must be a scalar, top-level attribute (not a nested attribute). The data type must be one of String, Number, or Binary. The attribute cannot be nested within a List or a Map. =head1 ATTRIBUTES =head2 B<REQUIRED> AttributeName => Str The name of a key attribute. =head2 B<REQUIRED> KeyType => Str The role that this key attribute will assume: =over =item * C<HASH> - partition key =item * C<RANGE> - sort key =back The partition key of an item is also known as its I<hash attribute>. The term "hash attribute" derives from DynamoDB' usage of an internal hash function to evenly distribute data items across partitions, based on their partition key values. The sort key of an item is also known as its I<range attribute>. The term "range attribute" derives from the way DynamoDB stores items with the same partition key physically close together, in sorted order by the sort key value. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::DynamoDB> =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/DynamoDB/KeySchemaElement.pm
Perl
apache-2.0
2,661
# # Copyright 2015 Electric Cloud, Inc. # # 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. # @files = ( #Configuration files ['//procedure[procedureName="CreateConfiguration"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ESXCreateConfigForm.xml'], ['//procedure[procedureName="DeleteConfiguration"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/deleteconfiguration.xml'], ['//property[propertyName="ui_forms"]/propertySheet/property[propertyName="ESXCreateConfigForm"]/value', 'ESXCreateConfigForm.xml'], ['//property[propertyName="ui_forms"]/propertySheet/property[propertyName="ESXEditConfigForm"]/value', 'ESXEditConfigForm.xml'], ['//procedure[procedureName="CreateConfiguration"]/step[stepName="CreateConfiguration"]/command', 'conf/createcfg.pl'], ['//procedure[procedureName="CreateConfiguration"]/step[stepName="CreateAndAttachCredential"]/command', 'conf/createAndAttachCredential.pl'], ['//procedure[procedureName="CreateConfiguration"]/step[stepName="AttemptConnection"]/command', 'conf/attemptConnection.pl'], ['//procedure[procedureName="DeleteConfiguration"]/step[stepName="DeleteConfiguration"]/command', 'conf/deletecfg.pl'], #Procedures ['//procedure[procedureName="Create"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/create.xml'], ['//step[stepName="Create"]/command', 'vm/create.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Clone"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/clone.xml'], ['//step[stepName="Clone"]/command', 'vm/clone.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Cleanup"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/cleanup.xml'], ['//step[stepName="Cleanup"]/command', 'vm/cleanup.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Relocate"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/relocate.xml'], ['//step[stepName="Relocate"]/command', 'vm/relocate.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Revert"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/revert.xml'], ['//step[stepName="Revert"]/command', 'vm/revert.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Snapshot"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/snapshot.xml'], ['//step[stepName="Snapshot"]/command', 'vm/snapshot.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="PowerOn"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/poweron.xml'], ['//step[stepName="PowerOn"]/command', 'vm/poweron.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="PowerOff"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/poweroff.xml'], ['//step[stepName="PowerOff"]/command', 'vm/poweroff.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Shutdown"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/shutdown.xml'], ['//step[stepName="Shutdown"]/command', 'vm/shutdown.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Suspend"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/suspend.xml'], ['//step[stepName="Suspend"]/command', 'vm/suspend.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="CreateResourceFromVM"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/createresourcefromvm.xml'], ['//step[stepName="CreateResourceFromVM"]/command', 'vm/createresourcefromvm.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="GetVMConfiguration"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/getvmconfiguration.xml'], ['//step[stepName="GetVMConfiguration"]/command', 'vm/getvmconfiguration.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Import"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/import.xml'], ['//step[stepName="Import"]/command', 'vm/import.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="Export"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/export.xml'], ['//step[stepName="Export"]/command', 'vm/export.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="RegisterVM"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/registervm.xml'], ['//step[stepName="RegisterVM"]/command', 'vm/registervm.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="CloudManagerGrow"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/cloudmanagergrow.xml'], ['//step[stepName="grow"]/command', 'vm/step.grow.pl'], ['//procedure[procedureName="CloudManagerShrink"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/cloudmanagershrink.xml'], ['//step[stepName="shrink"]/command', 'vm/step.shrink.pl'], ['//step[stepName="sync"]/command', 'vm/step.sync.pl'], ['//procedure[procedureName="ListEntity"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/listEntity.xml'], ['//step[stepName="ListEntity"]/command', 'vm/listEntity.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="CreateFolder"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/createFolder.xml'], ['//step[stepName="CreateFolder"]/command', 'vm/createFolder.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="DeleteEntity"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/deleteEntity.xml'], ['//step[stepName="DeleteEntity"]/command', 'vm/deleteEntity.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="RenameEntity"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/renameEntity.xml'], ['//step[stepName="RenameEntity"]/command', 'vm/renameEntity.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="MoveEntity"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/moveEntity.xml'], ['//step[stepName="MoveEntity"]/command', 'vm/moveEntity.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="DisplayESXSummary"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/displayESXSummary.xml'], ['//step[stepName="DisplayESXSummary"]/command', 'vm/displayESXSummary.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="CreateResourcepool"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/createResourcepool.xml'], ['//step[stepName="CreateResourcepool"]/command', 'vm/createResourcepool.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="EditResourcepool"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/editResourcepool.xml'], ['//step[stepName="EditResourcepool"]/command', 'vm/editResourcepool.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="ListSnapshot"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/listSnapshot.xml'], ['//step[stepName="ListSnapshot"]/command', 'vm/listSnapshot.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], '//procedure[procedureName="RemoveSnapshot"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/removeSnapshot.xml'], ['//step[stepName="RemoveSnapshot"]/command', 'vm/removeSnapshot.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="AddCdDvdDrive"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/addCdDvdDrive.xml'], ['//step[stepName="addCdDvdDrive"]/command', 'vm/addCdDvdDrive.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="EditCdDvdDrive"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/editCdDvdDrive.xml'], ['//step[stepName="editCdDvdDrive"]/command', 'vm/editCdDvdDrive.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="AddNetworkInterface"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/addNetworkInterface.xml'], ['//step[stepName="addNetworkInterface"]/command', 'vm/addNetworkInterface.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="ListDevice"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/listDevice.xml'], ['//step[stepName="listDevice"]/command', 'vm/listDevice.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="RemoveDevice"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/removeDevice.xml'], ['//step[stepName="removeDevice"]/command', 'vm/removeDevice.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="AddHardDisk"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/addHardDisk.xml'], ['//step[stepName="AddHardDisk"]/command', 'vm/addHardDisk.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="RevertToCurrentSnapshot"]/propertySheet/property[propertyName="ec_parameterForm"]/value', 'ui_forms/revertToCurrentSnapshot.xml'], ['//step[stepName="RevertToCurrentSnapshot"]/command', 'vm/revertToCurrentSnapshot.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], ['//procedure[procedureName="ChangeCpuMemAllocation"]/propertySheet/property[propertyName="ec_parameterForm"]/value','ui_forms/changeCpuMemAllocation.xml'], ['//step[stepName="changeCpuMemAllocation"]/command', 'vm/changeCpuMemAllocation.pl'], ['//step[stepName="SetTimelimit"]/command', 'setTimelimit.pl'], #Main files ['//property[propertyName="preamble"]/value', 'preamble.pl'], ['//property[propertyName="ESX"]/value', 'ESX.pm'], ['//property[propertyName="ec_setup"]/value', 'ec_setup.pl'], );
electric-cloud/EC-ESX
src/main/resources/project/manifest.pl
Perl
apache-2.0
17,076
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] 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::JSONServer::Tools::IDMapper; use strict; use warnings; use parent qw(EnsEMBL::Web::JSONServer::Tools); sub object_type { 'IDMapper' } 1;
muffato/public-plugins
tools/modules/EnsEMBL/Web/JSONServer/Tools/IDMapper.pm
Perl
apache-2.0
874
ctmc evolve const int QmaxL [1..10]; evolve const int QmaxH [1..10]; evolve distribution evTrans1 [2][0.0 .. 0.8]; evolve distribution evTrans2 [2][0.2 .. 0.6]; evolve distribution evTrans3 [2][0.2 .. 0.6]; evolve module PM p: [0..2]; [sleep2idle] p = 2 -> (p'=p); [idle2sleep] p = 2 -> (p'=p); [wait2sleep] (QL=0 & QH=0)|(QL=1 & QH=0) -> (p'=p); [wait2idle] (QL=0 & QH > 0)|(QL=1 & QH > 0)|QL > 1 -> (p'=p); [sleep2wait] (QL=0 & QH=2)|(QL > 0 & QH > 0) -> (p'=p); [requestH] QL=0 & QH=0 & sp=3 -> evTrans1 : (p'=0) + evTrans1 : (p'=1); [requestL] QL=3 & QH=0 & sp=3 -> evTrans2 : (p'=0) + evTrans2 : (p'=1); [sleep2wait] p = 1 -> (p'=0); [requestH]! (QL=0 & QH=0 & sp=3) -> (p'=p); [requestL]!(QL=3 & QH=0 & sp=3) -> (p'=p); endmodule evolve module PM p: [0..2]; [sleep2idle] false -> true; [idle2sleep] false -> true; [sleep2wait] false -> true; [wait2sleep] false -> true; [sleep2wait] false -> true; [wait2idle] (QL=0 & QH > 0)|(QL=1 & QH > 0)|QL > 1 -> (p'=p); [requestH] QL=0 & QH=0 & sp=3 -> evTrans2 : (p'=0) + evTrans2 : (p'=1); [requestL] QL=3 & QH=0 & sp=3 -> evTrans3 : (p'=0) + evTrans3 : (p'=1); [requestH]! (QL=0 & QH=0 & sp=3) -> (p'=p); [requestL]!(QL=3 & QH=0 & sp=3) -> (p'=p); endmodule const double service = 0.2; const double idle2wait = 1; const double idle2sleep = 0.5; const double wait2idle = 0.454; const double wait2sleep = 1.5; const double sleep2wait = 1.5; const double sleep2idle = 0.166; module SP sp:[0..3] init 0; //states: 0=busy, 1=idle, 2=wait, 3=sleep [sleep2wait] sp = 3 -> sleep2wait : (sp' = 2); [wait2sleep] sp = 2 -> wait2sleep : (sp' = 3); [wait2idle]sp=2 & QL=0 & QH=0 -> wait2idle: (sp' =1); [wait2idle]sp=2 & (QL>0|QH>0) -> wait2idle: (sp' =0); [idle2wait]sp=1&QL=0&QH=0 ->idle2wait: (sp' =2); [sleep2idle] sp = 3 & QL=0 & QH=0 ->sleep2idle: (sp' =1); [sleep2idle] sp = 3 & (QL > 0|QH > 0) -> sleep2idle : (sp' = 0); [idle2sleep]sp=1 & QL=0 & QH=0->idle2sleep:(sp' =3); [requestL] sp = 1 -> (sp' = 0); [requestH] sp = 1 -> (sp' = 0); [requestL] sp != 1 -> (sp' = sp); [requestH] sp != 1 -> (sp' = sp); [serveH] sp=0 & QH=1 & QL=0 -> service: (sp' =1); [serveL] sp=0 & QH=0 & QL=1 -> service:(sp' =1); [serveH]sp=0 & (QL+QH>1) -> service:(sp' =sp); [serveL]sp=0 & QH=0 & QL>1 -> service:(sp' =sp); endmodule const double reqL = 0.05; const double reqH = 0.15; module SRQL QL: [0..QmaxL]; [requestL] true -> reqL : (QL' = min(QL + 1, QmaxL)); [serveL] QL>0 & QH=0 -> (QL' = QL-1); endmodule module SRQH QH: [0..QmaxH]; [requestH] true -> reqH : (QH' = min(QH + 1, QmaxH)); [serveH] QH >0 -> (QH' =QH-1); endmodule rewards "QHLength" true : QH; endrewards rewards "QLLength" true : QL; endrewards rewards "TotalLength" true : QL+QH; endrewards rewards "TotalLost" [requestH] QH=QmaxH : 1; [requestL] QL=QmaxL : 1; endrewards rewards "power" sp=0 : 2.15; sp=1 : 0.95; sp=2 : 0.35; sp=3 : 0.13; endrewards
gerasimou/SBMS
RODES/models/DPM/dpm.pm
Perl
apache-2.0
2,908
package ReseqTrack::Hive::Process::ConvertRsemToReactome; use strict; use base ('ReseqTrack::Hive::Process::BaseProcess'); use ReseqTrack::DBSQL::DBAdaptor; use ReseqTrack::Tools::Exception qw(throw); use ReseqTrack::Tools::FileSystemUtils qw(check_file_exists delete_file); use ReseqTrack::Tools::GeneralUtils qw(get_open_file_handle execute_system_command); use Math::Trig; use Scalar::Util::Numeric qw(isint isnum); use PerlIO::gzip; use File::Slurp; use File::Copy; sub param_defaults { return { }; } sub run { my $self = shift @_; $self->param_required( 'file' ); my $annotation_file = $self->param_required( 'annotation_file' ); my $reactome_gene_file = $self->param_required( 'reactome_gene_file' ); my $transform_name = $self->param_required( 'transform_name' ); my $files = $self->param_as_array( 'file' ); foreach my $file ( @$files ) { check_file_exists( $file ); } throw('expecting single input file') if scalar @$files > 1; check_file_exists( $annotation_file ); check_file_exists( $reactome_gene_file ); throw( "couldn't identify transform_name: $transform_name" ) unless $transform_name eq 'asinh' or $transform_name eq 'log'; my $input = $$files[0]; my $out_file = $input; $out_file =~ s/\.results(?:\.gz)?$/\.reactome/; throw( "$out_file exists" ) if -e $out_file; my $tmp_file_name = $out_file . '.tmp'; my $output_name = $tmp_file_name; my $reactome_genes = _read_reactome_genes( $reactome_gene_file ); my $annotation = _read_annotation( $annotation_file ); my $input_fh = _opener( $input ); my $quants = _read_quant_file( $input_fh, $annotation ); close( $input_fh ); my $log; open my $output_fh, '>', $tmp_file_name; _write_reactome_quants( $output_fh, $reactome_genes, $quants, $log, $transform_name ); close( $output_fh ); move( $tmp_file_name, $out_file ); $self->output_param( 'reactome', $out_file ); } sub _read_reactome_genes { my ($reactome_genes_file) = @_; my @reactome_genes = sort { $a cmp $b } read_file( $reactome_genes_file, chomp => 1 ); return \@reactome_genes; } sub _read_annotation { my ( $annotation_file_name ) = @_; my $annotation_fh = _opener( $annotation_file_name ); my %annotation; LINE: while ( <$annotation_fh> ) { next unless $_ =~ m/^\S+\t\S+\tgene/ ; #huge performance improvement by checking type early chomp; my $feature = _parse_gff( $_ ); next LINE if $feature->{type} ne 'gene'; $annotation{ $feature->{attrib}{gene_id} } = $feature; } close( $annotation_fh ); return \%annotation; } sub _parse_gff { my ($line) = @_; my %f = ( attrib => {} ); my $attributes_text; ( $f{seq}, $f{src}, $f{type}, $f{start}, $f{end}, $f{score}, $f{strand}, $f{phase}, $attributes_text ) = split /\t/, $line; for my $a ( split /; */, $attributes_text ) { my ( $key, $value ) = split / /, $a; $value =~ s/"//g if $value; $f{attrib}{$key} = $value; } return \%f; } sub _opener { my ($file) = @_; my $fh; if ( $file =~ m/\.gz/ ) { open $fh, '<:gzip', $file; } else { open $fh, '<', $file; } return $fh; } sub _read_quant_file { my ( $input_fh, $annotation ) = @_; my %quants; LINE: while ( <$input_fh> ) { chomp; next if !$_ or m/^#/; next if /^(gene|transcript)/; my $feature = _parse_rsem( $_ ); throw( "No feature parsed from line: $_" ) unless $feature; my $tpm = $feature->{TPM}; throw( "No RPKM found in line: $_" ) unless defined $tpm; my $gene_id = $feature->{gene_id}; throw( "No gene id found in line: $_" ) unless $gene_id; my $annotation_feature = $annotation->{$gene_id}; throw( "No feature found for $gene_id" ) unless $annotation_feature; my $gene_name = $annotation_feature->{attrib}{gene_name}; throw( "No gene_name found for $gene_id" ) unless $gene_name; $quants{$gene_name} = $tpm; } return \%quants; } sub _parse_rsem { my ($line) = @_; my %f; my $attributes_text; ( $f{gene_id}, $f{transcript_id}, $f{length}, $f{effective_length}, $f{expected_count}, $f{TPM}, $f{FPKM}, $attributes_text, ) = split /\t/, $line; return \%f; } sub _write_reactome_quants { my ( $output_fh, $reactome_genes, $quants, $log , $transform_name ) = @_; my $scale = 'TPM'; $scale = 'log(TPM)' if ( $transform_name eq 'log' ); $scale = 'asinh(TPM)' if ( $transform_name eq 'asinh' ); print $output_fh "#Gene expression\t ${scale}$/"; for (@$reactome_genes) { my $q = $quants->{$_}; if ( $transform_name eq 'log' ){ if ($q) { $q = log10($q); } else{ $q = ''; } } if (defined $q && $transform_name eq 'asinh' ){ $q = asinh($q); } print $output_fh "$_\t$q$/" if ( defined $q ); } } 1;
EMBL-EBI-GCA/bp_project
lib/ReseqTrack/Hive/Process/ConvertRsemToReactome.pm
Perl
apache-2.0
4,933
istree(nil). istree(t(L,_,R)):-istree(L),istree(R). max(t(_,N,nil),N):-!. max(t(_,_,R),M):-max(R,M). min(t(nil,N,_),N):-!. min(t(L,_,_),M):-min(L,M). issorted(t(nil,_,nil)):-!. issorted(t(nil,N,R)):-issorted(R),!,min(R,X),X>N. issorted(t(L,N,nil)):-issorted(L),!,max(L,X),X=<N. issorted(t(L,N,R)):-issorted(L),issorted(R),max(L,X),min(R,Y),X=<N,Y>N. find(t(L,N,_),I,S):-I<N,!,find(L,I,S). find(t(_,N,R),I,S):-I>N,!,find(R,I,S). find(t(L,N,R),I,S):-!,I==N,S=t(L,N,R). insert(nil,I,t(nil,I,nil)):-!. insert(t(L,N,R),I,S):-I>=N,!,insert(R,I,Z),S=t(L,N,Z);I=<N,!,insert(L,I,Z),S=t(Z,N,R). delete(t(L,N,R),I,S):-I>N,!,delete(R,I,Z),S=t(L,N,Z);I<N,!,delete(L,I,Z),S=t(Z,N,R). delete(t(L,N,nil),I,S):-I==N,S=L,!. delete(t(L,N,R),I,S):-I==N,!,min(R,RN),delete(R,RN,Y),S=t(L,RN,Y). deleteall(T,I,S):-find(T,I,_),delete(T,I,Z),!,deleteall(Z,I,S). deleteall(T,_,T). listtree([],nil). listtree([L|LS],T):-listtree(LS,S),insert(S,L,T). treelist(nil,[]):-!. treelist(T,[X|M]):-min(T,X),delete(T,X,S),treelist(S,M). treelistunique(nil,[]):-!. treelistunique(T,[X|M]):-min(T,X),deleteall(T,X,S),treelistunique(S,M). treesort(L1,L2):-listtree(L1,T),treelist(T,L2). treesortunique(L1,L2):-listtree(L1,T),treelistunique(T,L2).
wouwouwou/2017_module_8
src/prolog/trees.pl
Perl
apache-2.0
1,219
# # 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 database::mysql::mode::databasessize; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold); sub custom_status_output { my ($self, %options) = @_; my $msg = '[connection state ' . $self->{result_values}->{connection_state} . '][power state ' . $self->{result_values}->{power_state} . ']'; return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{connection_state} = $options{new_datas}->{$self->{instance} . '_connection_state'}; $self->{result_values}->{power_state} = $options{new_datas}->{$self->{instance} . '_power_state'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, cb_prefix_output => 'prefix_global_output', }, { name => 'database', type => 3, cb_prefix_output => 'prefix_database_output', cb_long_output => 'database_long_output', indent_long_output => ' ', message_multiple => 'All databases are ok', group => [ { name => 'global_db', type => 0, skipped_code => { -10 => 1 } }, { name => 'table', display_long => 0, cb_prefix_output => 'prefix_table_output', message_multiple => 'All tables are ok', type => 1, skipped_code => { -10 => 1 } }, ] } ]; $self->{maps_counters}->{global} = [ { label => 'total-usage', nlabel => 'databases.space.usage.bytes', set => { key_values => [ { name => 'used' } ], output_template => 'used space %s %s', output_change_bytes => 1, perfdatas => [ { value => 'used_absolute', template => '%s', unit => 'B', min => 0 }, ], } }, { label => 'total-free', nlabel => 'databases.space.free.bytes', set => { key_values => [ { name => 'free' } ], output_template => 'free space %s %s', output_change_bytes => 1, perfdatas => [ { value => 'free_absolute', template => '%s', unit => 'B', min => 0 }, ], } }, ]; $self->{maps_counters}->{global_db} = [ { label => 'db-usage', nlabel => 'database.space.usage.bytes', set => { key_values => [ { name => 'used' } ], output_template => 'used %s %s', output_change_bytes => 1, perfdatas => [ { value => 'used_absolute', template => '%s', unit => 'B', min => 0, label_extra_instance => 1 }, ], } }, { label => 'db-free', nlabel => 'database.space.free.bytes', set => { key_values => [ { name => 'free' } ], output_template => 'free %s %s', output_change_bytes => 1, perfdatas => [ { value => 'free_absolute', template => '%s', unit => 'B', min => 0, label_extra_instance => 1 }, ], } }, ]; $self->{maps_counters}->{table} = [ { label => 'table-usage', nlabel => 'table.space.usage.bytes', set => { key_values => [ { name => 'used' }, { name => 'display' } ], output_template => 'used %s %s', output_change_bytes => 1, perfdatas => [ { value => 'used_absolute', template => '%s', unit => 'B', min => 0, label_extra_instance => 1 }, ], } }, { label => 'table-free', nlabel => 'table.space.free.bytes', set => { key_values => [ { name => 'free' }, { name => 'display' } ], output_template => 'free %s %s', output_change_bytes => 1, perfdatas => [ { value => 'free_absolute', template => '%s', unit => 'B', min => 0, label_extra_instance => 1 }, ], } }, { label => 'table-frag', nlabel => 'table.fragmentation.percentage', set => { key_values => [ { name => 'frag' }, { name => 'display' } ], output_template => 'fragmentation : %s %%', perfdatas => [ { value => 'frag_absolute', template => '%.2f', unit => '%', min => 0, max => 100, label_extra_instance => 1 }, ], } }, ]; } sub prefix_global_output { my ($self, %options) = @_; return "Total database "; } sub prefix_database_output { my ($self, %options) = @_; return "Database '" . $options{instance_value}->{display} . "' "; } sub database_long_output { my ($self, %options) = @_; return "checking database '" . $options{instance_value}->{display} . "'"; } sub prefix_table_output { my ($self, %options) = @_; return "table '" . $options{instance_value}->{display} . "' "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { 'filter-database:s' => { name => 'filter_database' }, }); return $self; } sub manage_selection { my ($self, %options) = @_; $options{sql}->connect(); if (!($options{sql}->is_version_minimum(version => '5'))) { $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported."); $self->{output}->option_exit(); } $options{sql}->query( query => q{show variables like 'innodb_file_per_table'} ); my ($name, $value) = $options{sql}->fetchrow_array(); my $innodb_per_table = 0; $innodb_per_table = 1 if ($value =~ /on/i); $options{sql}->query( query => q{SELECT table_schema, table_name, engine, data_free, data_length+index_length as data_used, (DATA_FREE / (DATA_LENGTH+INDEX_LENGTH)) as TAUX_FRAG FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND engine IN ('InnoDB', 'MyISAM')} ); my $result = $options{sql}->fetchall_arrayref(); my $innodb_ibdata_done = 0; $self->{global} = { free => 0, used => 0 }; $self->{database} = {}; foreach my $row (@$result) { next if (defined($self->{option_results}->{filter_database}) && $self->{option_results}->{filter_database} ne '' && $$row[0] !~ /$self->{option_results}->{filter_database}/); if (!defined($self->{database}->{$$row[0]})) { $self->{database}->{$$row[0]} = { display => $$row[0], global_db => { free => 0, used => 0 }, table => {} }; } if (($$row[2] =~ /innodb/i && ($innodb_per_table == 1 || $innodb_ibdata_done == 0))) { $self->{global}->{free} += $$row[3]; $self->{global}->{used} += $$row[4]; $innodb_ibdata_done = 1; } if ($$row[2] !~ /innodb/i || ($$row[2] =~ /innodb/i && $innodb_per_table == 1) ) { $self->{database}->{$$row[0]}->{global_db}->{free} += $$row[3]; $self->{database}->{$$row[0]}->{global_db}->{used} += $$row[4]; $self->{database}->{$$row[0]}->{table}->{$$row[1]} = { display => $$row[1], free => $$row[3], used => $$row[4], frag => $$row[5] }; } } } 1; __END__ =head1 MODE Check MySQL databases size. =over 8 =item B<--filter-database> Filter database to checks. =back =cut
Sims24/centreon-plugins
database/mysql/mode/databasessize.pm
Perl
apache-2.0
8,623
# 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::Enums::CampaignExperimentTypeEnum; use strict; use warnings; use Const::Exporter enums => [ UNSPECIFIED => "UNSPECIFIED", UNKNOWN => "UNKNOWN", BASE => "BASE", DRAFT => "DRAFT", EXPERIMENT => "EXPERIMENT" ]; 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Enums/CampaignExperimentTypeEnum.pm
Perl
apache-2.0
854
# At least ices_get_next must be defined. And, like all perl modules, it # must return 1 at the end. # Function called to initialize your python environment. # Should return 1 if ok, and 0 if something went wrong. sub cint { if ($_[0] >= int($_[0]) + 0.5) { $r = int($_[0]) + 1; } else { $r = int($_[0]); } } sub ices_init { print "Perl subsystem Initializing:\n"; @jingles = `/bin/ls -1 /home/sergey/jingles/*.mp3`; @new = `/bin/ls -1 /home/sergey/music/new/*.mp3`; @act = `/bin/ls -1 /home/sergey/music/act/*.mp3`; @pop = `/bin/ls -1 /home/sergey/music/pop/*.mp3`; @old = `/bin/ls -1 /home/sergey/music/old/*.mp3`; $sizej = scalar(@jingles); $sizen = scalar(@new); $sizea = scalar(@act); $sizep = scalar(@pop); $sizeo = scalar(@old); for ($i = 0; $i < $sizej; $i++){$arrayj[$i] = 0;} for ($i = 0; $i < $sizen; $i++){$arrayn[$i] = 0;} for ($i = 0; $i < $sizea; $i++){$arraya[$i] = 0;} for ($i = 0; $i < $sizep; $i++){$arrayp[$i] = 0;} for ($i = 0; $i < $sizeo; $i++){$arrayo[$i] = 0;} $finishj = undef*5; $finishn = undef*5; $finisha = undef*5; $finishp = undef*5; $finisho = undef*5; $replayj = undef*5; $replayn = undef*5; $replaya = undef*5; $replayp = undef*5; $replayo = undef*5; $numjin = undef*5; $numnew = undef*5; $numact = undef*5; $numpop = undef*5; $numold = undef*5; $numj = undef*5; $nums = undef*5; $nump = undef*5; $numberj = undef*5; $numbers = undef*5; $numberp = undef*5; $endhour = undef*5; return 1; } # Function called to shutdown your python enviroment. # Return 1 if ok, 0 if something went wrong. sub ices_shutdown { print "Perl subsystem shutting down:\n"; } sub get_song { # mass, array, size, finish, replay, num if ($_[4] == int(0.75*$_[2]) + 1) {$_[4] = 1;} else {$_[4]++;} if ($_[3] == int(0.75*$_[2]) + 1) { for ($g = 0; $g < $_[2]; $g++) {last if $_[1]->[$g] == $_[4];} $_[1]->[$g] = 0; } else {$_[5] = $_[2] - $_[3]; $_[3]++;} $play = cint(rand($_[5]-1)) + 1; $n = 0; for ($j = 0; $j < $_[2]; $j++) { if ($_[1]->[$j] == 0) { $n++; } last if $n == $play; } $_[1]->[$j] = $_[4]; chomp $_[0]->[$j]; open(F1, ">>/usr/local/etc/modules/out.dat"); print F1 $_[5], " ", $_[2], " ", $_[3], " ", $play, " ", $n, " ", $j, " | ", $_[4], " | ", $numj, " ", $numberj, " ", $nums, " " , $numbers, " | ", $_[1]->[$j], " ", $_[0]->[$j], "\n"; close(F1); return $_[0]->[$j]; } # Function called to get the next filename to stream. # Should return a string. sub ices_get_next { print "Perl subsystem quering for new track:\n"; open (TIMETABLE, "/usr/local/etc/modules/timetable.txt"); @table = <TIMETABLE>; close(TIMETABLE); open (LOG, ">>/home/sergey/ices-0.4/tmp/ices.log"); print LOG "[" . localtime() . "]"; close(LOG); my $hour = 10; my $t = time(); $hour = cint($t/3600); my $diff = $t - $hour*3600; if (($diff > -90 && $diff < 300) && ($endhour != $hour)) { $endhour = $hour; my $h = 20 - 10; $h = ($hour + 4) % 24; return "/home/sergey/jingles/time/" . $h . ".mp3"; } else { my $hours = int($t/3600); my $h = ($hours + 4) % 24; my $sec = $t - $hours*3600; for ($j = 0; $j < scalar(@table); $j++) { my $thour = substr(@table[$j],0,2) + 2 - 2; my $tsec = substr(@table[$j],3,2)*60; my $rdif = $sec - $tsec; if (($thour == $h) && ($rdif > -90 && $rdif < 300)) { open(F1, ">>/usr/local/etc/modules/out.dat"); print F1 "ïîðà! ",$thour, ":", $tsec, " ýòî ðàâíî ", $h, , ":", $sec, "\n"; close(F1); open(TT, ">/usr/local/etc/modules/timetable.txt"); for ($i = 0; $i < scalar(@table); $i++) { if ($i != $j) { print TT @table[$i]; } } close(TT); return substr(@table[$j],6,length(@table[$j]) - 7); } #else #{ # open(F1, ">>/usr/local/etc/modules/out1.dat"); # print F1 "ÍÅ ÏÎÐÀ! ",$thour, ":", $tsec, " ýòî ÍÅ ðàâíî ", $h, , ":", $sec, "\n"; # close(F1); #} } #if (($diff > 301 || $diff < -91) && ($endhour == 1)) {$endhour = 0;} if ($numberj == $numj) { $numj = cint(rand(2)) + 2; $numberj = 0; return get_song(\@jingles, \@arrayj, $sizej, $finishj, $replayj, $numjin); } else { $numberj++; if ($nump == $numberp) { $nump = cint(rand(2)) + 4; $numberp = 0; if (cint(rand(2)) == 0) { return get_song(\@old, \@arrayo, $sizeo, $finisho, $replayo, $numold); } else { return get_song(\@pop, \@arrayp, $sizep, $finishp, $replayp, $numpop); } } else { $numberp++; if ($nums == $numbers) { $nums = cint(rand(2)) + 2; $numbers = 0; return get_song(\@act, \@arraya, $sizea, $finisha, $replaya, $numact); } else { $numbers++; return get_song(\@new, \@arrayn, $sizen, $finishn, $replayn, $numnew); } } } } } # If defined, the return value is used for title streaming (metadata) #sub ices_get_metadata { # return "Artist - Title"; #} # Function used to put the current line number of # the playlist in the cue file. If you don't care # about cue files, just return any integer. #sub ices_get_lineno { # return 1; #} return 1;
HrundelB/radio-jam
perl/ices.pm
Perl
apache-2.0
5,276
## OpenXPKI::Crypto::Backend::OpenSSL::Command::pkcs7_get_chain ## Written 2005 by Michael Bell for the OpenXPKI project ## Rewritten 2006 by Julia Dubenskaya for the OpenXPKI project ## Refactoring by Oliver Welter 2013 for the OpenXPKI project ## (C) Copyright 2005-2013 by The OpenXPKI Project use strict; use warnings; package OpenXPKI::Crypto::Backend::OpenSSL::Command::pkcs7_get_chain; use OpenXPKI::Debug; use base qw(OpenXPKI::Crypto::Backend::OpenSSL::Command); use English; use Data::Dumper; use OpenXPKI::FileUtils; use OpenXPKI::DN; use OpenXPKI::Crypto::X509; use Encode; sub get_command { my $self = shift; $self->get_tmpfile ('PKCS7', 'OUT'); my $engine = ""; my $engine_usage = $self->{ENGINE}->get_engine_usage(); $engine = $self->{ENGINE}->get_engine() if ($self->{ENGINE}->get_engine() and ($engine_usage =~ m{ ALWAYS }xms)); ## check parameters if (not $self->{PKCS7}) { OpenXPKI::Exception->throw ( message => "I18N_OPENXPKI_CRYPTO_OPENSSL_COMMAND_PKCS7_GET_CHAIN_MISSING_PKCS7"); } ## prepare data $self->write_file (FILENAME => $self->{PKCS7FILE}, CONTENT => $self->{PKCS7}, FORCE => 1); ## build the command my $command = "pkcs7 -print_certs"; #$command .= " -text"; $command .= " -inform PEM"; $command .= " -in ".$self->{PKCS7FILE}; $command .= " -out ".$self->{OUTFILE}; return [ $command ]; } sub hide_output { return 0; } ## please notice that key_usage means usage of the engine's key sub key_usage { my $self = shift; return 0; } sub get_result { my $self = shift; my $fu = OpenXPKI::FileUtils->new(); my $pkcs7 = $fu->read_file ($self->{OUTFILE}); # We want to have the end entity certificate, which we autodetect by looking for # the certificate whoes subject is not an issuer in the found list ##! 16: 'pkcs7: ' . $pkcs7 ##! 2: "split certs" my %certsBySubject = (); my @issuers = (); my @parts = split /-----END CERTIFICATE-----\n\n/, $pkcs7; foreach my $cert (@parts) { $cert .= "-----END CERTIFICATE-----\n"; $cert =~ s/^.*\n-----BEGIN/-----BEGIN/s; my ($subject, $issuer); # Load the PEM into the x509 Object to parse it ##! 4: "determine the subject of the end entity cert" eval { my $x509 = $self->{XS}->get_object ({DATA => $cert, TYPE => "X509"}); $subject = $self->{XS}->get_object_function ({ OBJECT => $x509, FUNCTION => "subject"}); $issuer = $self->{XS}->get_object_function ({ OBJECT => $x509, FUNCTION => "issuer"}); $self->{XS}->free_object ($x509); }; ##! 8: 'Subject: ' . $subject ##! 8: 'Issuer: ' . $issuer if (exists $certsBySubject{$subject} && $certsBySubject{$subject}->{ISSUER} ne $issuer && $certsBySubject{$subject}->{CERT} ne $cert) { ##! 64: 'something funny is going on, the same certificate subject with different issuer or data is present' OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_CRYPTO_OPENSSL_COMMAND_PKCS7_GET_END_ENTITY_MULTIPLE_SAME_SUBJECTS_WITH_DIFFERENT_DATA', ); } $certsBySubject{$subject}->{ISSUER} = $issuer; $certsBySubject{$subject}->{CERT} = $cert; push @issuers, $issuer; } ##! 64: 'certs: ' . Dumper \%certsBySubject # Find subjects which are not issuers = entities my %entity = map { $_ => 1 } keys %certsBySubject; # Now unset all items where the subject is listes in @issuers foreach my $issuer (@issuers) { ##! 16: "Remove issuer " . $issuer delete( $entity{$issuer} ) if ($entity{$issuer}); } # Hopefully we have only one remaining now my @subjectsRemaining = keys %entity; if ( scalar @subjectsRemaining != 1 ) { ##! 2: "Too many remaining certs " . Dumper ( @subjectsRemaining ) OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_CRYPTO_OPENSSL_COMMAND_PKCS7_GET_END_ENTITY_UNABLE_TOO_DETECT_CORRECT_END_ENTITY_CERTIFICATE', ); } my $subject = shift @subjectsRemaining; # Requestor was just interessted in the entity if ($self->{NOCHAIN}) { ##! 8: 'entity only requested ' ##! 32: 'Entity pem ' . $certsBySubject{$subject}->{CERT} return $certsBySubject{$subject}->{CERT}; } # Start with the entity and build the chain ##! 16: 'entity subject: ' . $subject ##! 2: "create ordered cert list" my @chain; my $iterations = 0; my $MAX_CHAIN_LENGTH = 32; while (exists $certsBySubject{$subject} && $iterations < $MAX_CHAIN_LENGTH) { ##! 16: 'while for subject: ' . $subject push @chain, $certsBySubject{$subject}->{CERT}; last if ($subject eq $certsBySubject{$subject}->{ISSUER}); $subject = $certsBySubject{$subject}->{ISSUER}; $iterations++; } ##! 2: "end" ##! 32: 'Chain : ' . Dumper @chain if (! scalar @chain ) { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_CRYPTO_BACKEND_OPENSSL_COMMAND_PKCS7_GET_CHAIN_COULD_NOT_CREATE_CHAIN', ); } return \@chain; } sub __convert_subject { ##! 1: 'start' my $subject = shift; $subject =~ s/, /,/g; while ($subject =~ /\\x[0-9A-F]{2}/) { ##! 64: 'subject still contains \x-escaped character, replacing' use bytes; $subject =~ s/\\x([0-9A-F]{2})/chr(hex($1))/e; no bytes; ##! 64: 'subject after replacement: ' . $subject } my $dn = OpenXPKI::DN->new($subject); $subject = $dn->get_x500_dn(); ##! 1: 'end' return $subject; } 1; __END__ =head1 Name OpenXPKI::Crypto::Backend::OpenSSL::Command::pkcs7_get_chain =head1 Functions =head2 get_command =over =item * PKCS7 (a signature) =back =head2 hide_output returns false (chain verification is not a secret) =head2 key_usage returns false =head2 get_result Returns the PEM-encoded certificates in the correct order which are contained in the signature. The certificates are seperated by a blank line.
stefanomarty/openxpki
core/server/OpenXPKI/Crypto/Backend/OpenSSL/Command/pkcs7_get_chain.pm
Perl
apache-2.0
6,357
# 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::Resources::AccountLink; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { accountLinkId => $args->{accountLinkId}, dataPartner => $args->{dataPartner}, googleAds => $args->{googleAds}, resourceName => $args->{resourceName}, status => $args->{status}, thirdPartyAppAnalytics => $args->{thirdPartyAppAnalytics}, type => $args->{type}}; # 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/Resources/AccountLink.pm
Perl
apache-2.0
1,353
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2020] 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>. =head1 NAME Bio::EnsEMBL::Funcgen::RegulatoryFeature =head1 SYNOPSIS use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::Funcgen::DBSQL::DBAdaptor; Bio::EnsEMBL::Registry->load_registry_from_db( -host => 'ensembldb.ensembl.org', # alternatively 'useastdb.ensembl.org' -user => 'anonymous' ); my $regulatory_feature_adaptor = Bio::EnsEMBL::Registry->get_adaptor('homo_sapiens', 'funcgen', 'RegulatoryFeature'); my $regulatory_feature = $regulatory_feature_adaptor->fetch_by_stable_id('ENSR00000000011'); print 'Stable id: ' . $regulatory_feature->stable_id . "\n"; print 'Analysis: ' . $regulatory_feature->analysis->logic_name . "\n"; print 'Feature type: ' . $regulatory_feature->feature_type->name . "\n"; print 'Epigenome count: ' . $regulatory_feature->epigenome_count . "\n"; print 'Slice name: ' . $regulatory_feature->slice->name . "\n"; print 'Coordinates: ' . $regulatory_feature->start .' - '. $regulatory_feature->end . "\n"; print 'Regulatory build: ' . $regulatory_feature->get_regulatory_build->name . "\n"; =head1 DESCRIPTION A RegulatoryFeature object represents the output of the Ensembl RegulatoryBuild: http://www.ensembl.org/info/docs/funcgen/regulatory_build.html It may comprise many histone modification, transcription factor, polymerase and open chromatin features, which have been combined to provide a summary view and classification of the regulatory status at a given loci. =head1 SEE ALSO Bio::EnsEMBL:Funcgen::DBSQL::RegulatoryFeatureAdaptor =cut package Bio::EnsEMBL::Funcgen::RegulatoryFeature; use strict; use warnings; use Bio::EnsEMBL::Utils::Argument qw( rearrange ); use Bio::EnsEMBL::Utils::Exception qw( throw deprecate ); use base qw( Bio::EnsEMBL::Feature Bio::EnsEMBL::Funcgen::Storable ); =head2 new Arg [-SLICE] : Bio::EnsEMBL::Slice - The slice on which this feature is located. Arg [-START] : int - The start coordinate of this feature relative to the start of the slice it is sitting on. Coordinates start at 1 and are inclusive. Arg [-END] : int -The end coordinate of this feature relative to the start of the slice it is sitting on. Coordinates start at 1 and are inclusive. Arg [-FEATURE_SET] : Bio::EnsEMBL::Funcgen::FeatureSet - Regulatory Feature set Arg [-FEATURE_TYPE] : Bio::EnsEMBL::Funcgen::FeatureType - Regulatory Feature sub type Arg [-STABLE_ID] : (optional) string - Stable ID for this RegulatoryFeature e.g. ENSR00000000001 Arg [-DISPLAY_LABEL] : (optional) string - Display label for this feature Arg [-PROJECTED] : (optional) boolean - Flag to specify whether this feature has been projected or not Arg [-dbID] : (optional) int - Internal database ID. Arg [-ADAPTOR] : (optional) Bio::EnsEMBL::DBSQL::BaseAdaptor - Database adaptor. Example : my $feature = Bio::EnsEMBL::Funcgen::RegulatoryFeature->new( -SLICE => $chr_1_slice, -START => 1000000, -END => 1000024, -DISPLAY_LABEL => $text, -FEATURE_SET => $fset, -FEATURE_TYPE => $reg_ftype, ); Description: Constructor for RegulatoryFeature objects. Returntype : Bio::EnsEMBL::Funcgen::RegulatoryFeature Exceptions : None Caller : General Status : Stable =cut sub new { my $caller = shift; my $class = ref($caller) || $caller; my $self = $class->SUPER::new(@_); my ($stable_id, $attr_cache, $projected, $epigenome_count, $analysis) = rearrange(['STABLE_ID', 'PROJECTED', 'EPIGENOME_COUNT', 'ANALYSIS'], @_); #None of these are mandatory at creation #under different use cases $self->{stable_id} = $stable_id if defined $stable_id; $self->{projected} = $projected if defined $projected; $self->{epigenome_count} = $epigenome_count if defined $epigenome_count; $self->{analysis} = $analysis if defined $analysis; $self->{_regulatory_activity} = []; return $self; } sub analysis { return shift->get_Analysis; } sub _analysis_id { return shift->{_analysis_id}; } =head2 get_Analysis Arg : none Example : $analysis = $regulatory_feature->get_Analysis Description: Fetches the analysis used to generate this regulatory feature. This is the analysis of the regulatory build. Returntype : Bio::EnsEMBL::Analysis Exceptions : none Status : At Risk =cut sub get_Analysis { my $self = shift; if(! defined $self->{'_analysis'}) { $self->{'_analysis'} = $self ->adaptor ->db ->get_AnalysisAdaptor() ->fetch_by_dbID( $self->_analysis_id ); } return $self->{'_analysis'}; } sub regulatory_build_id { return shift->{regulatory_build_id}; } =head2 display_label Example : my $label = $feature->display_label; Description: Getter for the display label of this feature. Returntype : String Exceptions : None Caller : General Status : Stable =cut sub display_label { my $self = shift; if(! defined $self->{display_label}) { $self->{'display_label'} = $self->feature_type->name.' Regulatory Feature'; } return $self->{display_label}; } sub get_FeatureType { my $self = shift; return $self->{feature_type}; } sub feature_type { my $self = shift; my $value = shift; if(defined $value) { $self->{'feature_type'} = $value; } return $self->{feature_type}; } =head2 display_id Example : print $feature->display_id(); Description: This method returns a string that is considered to be the 'display' identifier. In this case it is the stable id of the regulatory feature. Returntype : String Exceptions : none Caller : web drawing code, Region Report tool Status : Stable =cut sub display_id { return shift->{stable_id}; } =head2 stable_id Example : my $stable_id = $feature->stable_id(); Description: Getter for the stable_id attribute for this feature. Returntype : string Exceptions : None Caller : General Status : At risk - setter functionality to be removed =cut sub stable_id { return shift->{stable_id}; } =head2 get_RegulatoryEvidence Arg [1] : String - Class of feature e.g. 'annotated' or 'motif' Arg [2] : Bio::EnsEMBL::Funcgen::Epigenome - The epigenome for which the evidence for its regulatory activity is requested. If no epigenome is provided, it will return a summary that can be used for the regulatory build track on the Ensembl website. Example : Description: Getter for the regulatory_evidence for this feature. Returntype : ARRAYREF Exceptions : Throws if feature class not valid Caller : General Status : At Risk =cut sub get_RegulatoryEvidence { my $self = shift; my $feature_class = shift; my $epigenome = shift; if(! defined $feature_class){ throw("Feature class string ('annotated' or 'motif') not defined!"); } if (! defined $epigenome) { # Hack, so we get a summary for the regulatory build track until the # current data issues have been fixed. $epigenome = $self->adaptor->db->get_EpigenomeAdaptor->fetch_by_dbID(1); } $self->_assert_epigenome_ok($epigenome); my $regulatory_activity = $self->regulatory_activity_for_epigenome($epigenome); # See https://github.com/Ensembl/ensembl-funcgen/pull/6 return [] unless $regulatory_activity; my $regulatory_evidence = $regulatory_activity->get_RegulatoryEvidence; return $regulatory_evidence; } sub _assert_epigenome_ok { my $self = shift; my $epigenome = shift; if (! defined $epigenome) { throw("Epigenome parameter was undefined!"); } if (ref $epigenome ne 'Bio::EnsEMBL::Funcgen::Epigenome') { throw("epigenome parameter must have type Bio::EnsEMBL::Funcgen::Epigenome!"); } } =head2 regulatory_activity_for_epigenome Arg [1] : Bio::EnsEMBL::Funcgen::Epigenome - The epigenome for which the evidence for it regulatory activity is requested. Example : Description: Getter for the regulatory_activity_for_epigenome for this feature. Returns undef, if no activity was predicted for the epigenome. Returntype : Bio::EnsEMBL::Funcgen::RegulatoryActivity Exceptions : none Caller : General Status : At Risk =cut sub regulatory_activity_for_epigenome { my $self = shift; my $epigenome = shift; if (! defined $epigenome) { throw("Epigenome parameter was undefined!"); } if (ref $epigenome ne 'Bio::EnsEMBL::Funcgen::Epigenome') { throw("Wrong parameter, expected an epigenome, but got a " . ref $epigenome); } my $epigenome_id = $epigenome->dbID; my @regulatory_activity = grep { $_->get_Epigenome->dbID == $epigenome_id } @{$self->regulatory_activity}; if (! @regulatory_activity) { return; } if (@regulatory_activity>1) { throw(); } return $regulatory_activity[0]; } =head2 get_all_MotifFeatures Example : my $overlapping_motif_features = $rf->get_all_MotifFeatures Description: Returns all MotifFeatures that overlap with a RegulatoryFeature Returntype : Arrayref of Bio::EnsEMBL::Funcgen::MotifFeature objects Exceptions : none Caller : General Status : At Risk =cut sub get_all_MotifFeatures { my $self = shift; my $motif_features = $self->adaptor()->_fetch_all_overlapping_MotifFeatures( $self ); return $motif_features; } =head2 get_all_experimentally_verified_MotifFeatures Example : my $motif_features = $rf->get_all_experimentally_verified_MotifFeatures; Description: Returns all experimentally verified MotifFeatures that overlap with a RegulatoryFeature Returntype : Arrayref of Bio::EnsEMBL::Funcgen::MotifFeature objects Exceptions : none Caller : General Status : At Risk =cut sub get_all_experimentally_verified_MotifFeatures { my $self = shift; my $motif_features = $self->adaptor() ->_fetch_all_overlapping_MotifFeatures_with_matching_Peak($self); return $motif_features; } sub _get_underlying_structure_motifs_by_epigenome { my $self = shift; my $epigenome = shift; my $regulatory_activity = $self->regulatory_activity_for_epigenome($epigenome); if (! defined $regulatory_activity) { die("No regulatory activity found for epigenome " . $epigenome->display_label . "."); } my $motif_evidence = $regulatory_activity->get_RegulatoryEvidence_by_type('motif'); return $motif_evidence; } sub _get_underlying_structure_motifs_by_epigenome_list { my $self = shift; my $epigenome_list = shift; my @all_motifs; foreach my $current_epigenome (@$epigenome_list) { my $motif_evidence = $self->_get_underlying_structure_motifs_by_epigenome($current_epigenome); push @all_motifs, @$motif_evidence; } my @unique_motifs; my %seen_motif_coordinates; MOTIF: foreach my $current_motif (@all_motifs) { my $unique_key = $current_motif->start . '_' . $current_motif->end; if (exists $seen_motif_coordinates{$unique_key}) { next MOTIF; } push @unique_motifs, $current_motif; $seen_motif_coordinates{$unique_key} = 1; } my @sorted_motifs = sort { $a->start <=> $b->start } @unique_motifs; return \@sorted_motifs; } =head2 get_underlying_structure Example : my @web_image_structure = @{$regulatory_feature->get_underlying_structure}; Description: Returns the underlying structure of the regulatory feature in a given epigenome. This structure is the bound start and end and the boundaries of all motifs linked to this regulatory feature for this epigenome. If no epigenome is provided, it will return a summary, which is the union of all underlying structures of all epigenomes in the regulatory build. Returntype : Arrayref of slice coordinates relative to the slice of the regulatory feature. Exceptions : None Caller : Webcode Status : At Risk =cut sub get_underlying_structure { my $self = shift; my $epigenome = shift; my $epigenome_specific_underlying_structure = []; my $motif_evidence; if ($epigenome) { $self->_assert_epigenome_ok($epigenome); $motif_evidence = $self->_get_underlying_structure_motifs_by_epigenome($epigenome); } else { my $regulatory_build = $self->get_regulatory_build; my $epigenome_list = $regulatory_build->get_all_Epigenomes; $motif_evidence = $self->_get_underlying_structure_motifs_by_epigenome_list($epigenome_list); } # This is used to make the coordinates relative to the start of the current # slice. The webcode expects it that way. # my $slice_start = $self->slice->start; foreach my $current_motif_evidence (@$motif_evidence) { push @$epigenome_specific_underlying_structure, ( 0 + $current_motif_evidence->start - $slice_start +1, 0 + $current_motif_evidence->end - $slice_start +1, ); } my $underlying_structure = [ 0 + $self->bound_start, 0 + $self->start, @$epigenome_specific_underlying_structure, 0 + $self->end, 0 + $self->bound_end ]; return $underlying_structure; } =head2 regulatory_activity Example : my $regulatory_activity = $regulatory_feature->regulatory_activity; Description: Fetches a list of regulatory activities associated to this regulatory feature. Returntype : ArrayRef[Bio::EnsEMBL::Funcgen::RegulatoryActivity] Exceptions : None Status : At Risk =cut sub regulatory_activity { my $self = shift; if(! defined $self->{'_regulatory_activity'}) { my $raa = $self->adaptor->db->{'_regulatory_activity_adaptor'} ||= $self ->adaptor ->db ->get_RegulatoryActivityAdaptor(); $self->{'_regulatory_activity'} = $raa->fetch_all_by_RegulatoryFeature($self); } return $self->{'_regulatory_activity'}; } =head2 get_regulatory_build Example : my $regulatory_build = $regulatory_feature->get_regulatory_build; Description: Fetches the regulatory build used to generate this regulatory feature. Returntype : Bio::EnsEMBL::Funcgen::RegulatoryBuild Exceptions : None Status : At Risk =cut sub get_regulatory_build { my $self = shift; if(! defined $self->{'_regulatory_build'}) { $self->{'_regulatory_build'} = $self ->adaptor ->db ->get_RegulatoryBuildAdaptor() ->fetch_by_dbID( $self->regulatory_build_id ); } return $self->{'_regulatory_build'}; } sub add_regulatory_activity { my $self = shift; my $regulatory_activity = shift; push @{$self->{_regulatory_activity}}, $regulatory_activity; } sub has_activity_in { my $self = shift; my $epigenome = shift; foreach my $current_regulatory_activity (@{$self->regulatory_activity}) { if ($current_regulatory_activity->epigenome_id() == $epigenome->dbID) { return 1; } } return; } sub has_epigenomes_with_activity { my $self = shift; my $activity = shift; foreach my $current_regulatory_activity (@{$self->regulatory_activity}) { if ($current_regulatory_activity->activity eq $activity) { return 1; } } return; } =head2 get_epigenomes_by_activity Example : my $regulatory_build = $regulatory_feature->get_epigenomes_by_activity($regulatory_activity); Description: Returns an array of epigenomes in which this regulatory feature has the regulatory activity given to this method as parameter. This can be used to get a list of epigenomes in which a regulatory feature is active. Returntype : ArrayRef[Bio::EnsEMBL::Funcgen::Epigenome] Exceptions : None Status : At Risk =cut sub get_epigenomes_by_activity { my $self = shift; my $activity = shift; if (!$self->adaptor->is_valid_activity($activity)) { throw( 'Please pass a valid activity to this method. Valid activities are: ' . $self->adaptor->valid_activities_as_string ); } my @epigenome_dbID_list = grep { $_ } map { $_->epigenome_id } grep { $_->activity eq $activity } @{$self->regulatory_activity}; my $epigenome_adaptor = $self->adaptor->db->get_EpigenomeAdaptor; return $epigenome_adaptor->fetch_all_by_dbID_list(\@epigenome_dbID_list); } =head2 epigenome_count Arg [1] : None Returntype : SCALAR Exceptions : None Description : Returns the amount of epigenomes in which this regulatory feature is active =cut sub epigenome_count { my $self = shift; return $self->{epigenome_count}; } =head2 bound_seq_region_start Example : my $bound_sr_start = $feature->bound_seq_region_start; Description: Getter for the seq_region bound_start attribute for this feature. Gives the 5' most start value of the underlying attribute features. Returntype : Integer Exceptions : None Caller : General Status : Stable =cut sub bound_seq_region_start { return $_[0]->seq_region_start - $_[0]->_bound_lengths->[0]; } =head2 bound_seq_region_end Example : my $bound_sr_end = $feature->bound_seq_region_end; Description: Getter for the seq_region bound_end attribute for this feature. Gives the 3' most end value of the underlying attribute features. Returntype : Integer Exceptions : None Caller : General Status : Stable =cut sub bound_seq_region_end { return $_[0]->seq_region_end + $_[0]->_bound_lengths->[1]; } sub _bound_lengths { my $self = shift; if(! defined $self->{_bound_lengths}){ my @af_attrs = @{$self->regulatory_evidence('annotated')}; if (! @af_attrs) { throw('Unable to set bound length, no AnnotatedFeature attributes available for RegulatoryFeature: ' .$self->dbID); } #Adding self here accounts for core region i.e. #features extending beyond the core may be absent on this cell type. my @start_ends; foreach my $feat (@af_attrs, $self) { push @start_ends, ($feat->seq_region_start, $feat->seq_region_end); } @start_ends = sort { $a <=> $b } @start_ends; $self->{_bound_lengths} = [ ($self->seq_region_start - $start_ends[0]), ($start_ends[$#start_ends] - $self->seq_region_end) ]; } return $self->{_bound_lengths}; } =head2 bound_start_length Example : my $bound_start_length = $reg_feat->bound_start_length; Description: Getter for the bound_start_length attribute for this feature, with respect to the host slice strand Returntype : Integer Exceptions : None Caller : General Status : Stable =cut sub bound_start_length { my $self = shift; return ($self->slice->strand == 1) ? $self->_bound_lengths->[0] : $self->_bound_lengths->[1]; } =head2 bound_end_length Example : my $bound_end_length = $reg_feat->bound_end_length; Description: Getter for the bound_end length attribute for this feature, with respect to the host slice strand. Returntype : Integer Exceptions : None Caller : General Status : Stable =cut sub bound_end_length { my $self = shift; return ($self->slice->strand == 1) ? $self->_bound_lengths->[1] : $self->_bound_lengths->[0]; } =head2 bound_start Example : my $bound_start = $feature->bound_start; Description: Getter for the bound_start attribute for this feature. Gives the 5' most start value of the underlying attribute features in local coordinates. Returntype : Integer Exceptions : None Caller : General Status : Stable =cut sub bound_start { return $_[0]->start - $_[0]->bound_start_length; } =head2 bound_end Example : my $bound_end = $feature->bound_start(); Description: Getter for the bound_end attribute for this feature. Gives the 3' most end value of the underlying attribute features in local coordinates. Returntype : Integer Exceptions : None Caller : General Status : Stable =cut sub bound_end { return $_[0]->end + $_[0]->bound_end_length; } =head2 feature_so_acc Example : print $feature->feature_so_acc; Description : Returns the sequence ontology accession for this type of regulatory feature. Returntype : String Status : At risk =cut sub feature_so_acc { my $self = shift; return $self->get_FeatureType->so_accession; } =head2 feature_so_term Example : print $feature->feature_so_term; Description : Returns the sequence ontology term for this type of regulatory feature. Returntype : String Status : At risk =cut sub feature_so_term { my $self = shift; return $self->get_FeatureType->so_term; } =head2 summary_as_hash Example : $regulatory_feature_summary = $regulatory_feature->summary_as_hash; Description : Retrieves a textual summary of this RegulatoryFeature. Returns : Hashref of descriptive strings Status : Intended for internal use (REST) =cut sub summary_as_hash { my $self = shift; my $feature_type = $self->feature_type; return { id => $self->stable_id, source => $self->analysis->logic_name, bound_start => $self->bound_seq_region_start, bound_end => $self->bound_seq_region_end, start => $self->seq_region_start, end => $self->seq_region_end, strand => $self->strand, seq_region_name => $self->seq_region_name, description => $self->feature_type->description, feature_type => $feature_type->name, }; } 1;
Ensembl/ensembl-funcgen
modules/Bio/EnsEMBL/Funcgen/RegulatoryFeature.pm
Perl
apache-2.0
23,192
package Paws::Pinpoint::GetSmsChannel; use Moose; has ApplicationId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'application-id', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'GetSmsChannel'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/v1/apps/{application-id}/channels/sms'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'GET'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Pinpoint::GetSmsChannelResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::Pinpoint::GetSmsChannel - Arguments for method GetSmsChannel on Paws::Pinpoint =head1 DESCRIPTION This class represents the parameters used for calling the method GetSmsChannel on the Amazon Pinpoint service. Use the attributes of this class as arguments to method GetSmsChannel. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to GetSmsChannel. As an example: $service_obj->GetSmsChannel(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 B<REQUIRED> ApplicationId => Str =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method GetSmsChannel in L<Paws::Pinpoint> =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/Pinpoint/GetSmsChannel.pm
Perl
apache-2.0
1,797
#!/usr/local/ensembl/bin/perl use strict; use warnings; use Getopt::Long; use FindBin qw( $Bin ); use Bio::EnsEMBL::Registry; use Data::Dumper; my ($species, $snpassay_file, $snpind_file,$population_name); # # bsub -q bigmem -W4:00 -R"select[mem>3500] rusage[mem=3500]" -M3500000 # GetOptions('species=s' => \$species, 'snpassay_file=s' => \$snpassay_file, 'snpind_file=s' => \$snpind_file, 'population_name=s' => \$population_name ); warn("Make sure you have a updated ensembl.registry file!\n"); my $registry_file ||= $Bin . "/ensembl.registry"; if ($population_name ne 'CELERA_STRAIN:SD' and $population_name ne 'ENSEMBL:STAR'){ die "Only allow STAR and CELERA data for the moment\n\n"; } #added default options $species ||= 'rat'; Bio::EnsEMBL::Registry->load_all( $registry_file ); my $dbVariation = Bio::EnsEMBL::Registry->get_DBAdaptor($species,'variation'); my $dbCore = Bio::EnsEMBL::Registry->get_DBAdaptor($species,'core'); open SNP, ">$snpassay_file" or die "could not open output file for snp assay info: $!\n"; #open IND, ">$snpind_file" or die "could not open output file for ind assay info: $!\n"; #first of all, write header for files print_snp_headers(); print_ind_headers(); #get data my $var_adaptor = $dbVariation->get_VariationAdaptor(); my $pop_adaptor = $dbVariation->get_PopulationAdaptor(); my $population = $pop_adaptor->fetch_by_name($population_name); my $variations = $var_adaptor->fetch_all_by_Population($population); my $vf_adaptor = $dbVariation->get_VariationFeatureAdaptor(); print_snp_data($variations,$vf_adaptor); close SNP or die "Could not close snp assay info file: $!\n"; #close IND or die "Could not close ind assay info file: $!\n"; #will print the snpassay file header sub print_snp_headers{ print_cont_section(SNP); #contacts print_pub_section(SNP); #publications print_method_section(IND); #methods print_pop_section(SNP); #print population section #snpassay print SNP "TYPE:\tSNPASSAY\n"; print SNP "HANDLE:\tENSEMBL\n"; print SNP "BATCH:\t2007\n"; #use year of submission for batch ?? print SNP "MOLTYPE:\tGenomic\n"; print SNP "METHOD:\tEnsembl-SSAHA\n"; print SNP "SAMPLESIZE:\t2\n"; #samplesize ?? print SNP "ORGANISM:\tRattus norvegicus\n"; print SNP "CITATION:\t\n"; print SNP "POPULATION:\t",$population_name,"\n"; print SNP "COMMENT:\t\n"; #any comment ?? print SNP "||\n"; } #for a list of variation objects, print the necessary information for dbSNP sub print_snp_data{ my $variations = shift; my $vf_adaptor = shift; foreach my $variation (@{$variations}){ my $vf = shift @{$vf_adaptor->fetch_all_by_Variation($variation)}; print SNP "SNP:\t",$variation->name,"\n"; print SNP "ACCESSION:\t",$vf->slice->accession_number,"\n"; #is this the info they want ?? print SNP "SAMPLESIZE:\t2\n"; #number of chromosomes ?? print SNP "LENGTH:\t", length($variation->five_prime_flanking_seq) + length($variation->three_prime_flanking_seq) + 1,"\n"; print SNP "5\'_FLANK:\t",$variation->five_prime_flanking_seq,"\n"; print SNP "OBSERVED:\t", $vf->allele_string,"\n"; print SNP "3\'_FLANK:\t",$variation->three_prime_flanking_seq,"\n"; print SNP "||\n"; } } #prints contacts section sub print_cont_section{ my $fh = shift; #contact details print $fh "TYPE:\tCONT\n"; print $fh "HANDLE:\tENSEMBL\n"; #should this be the source ?? print $fh "NAME:\tDaniel Rios\n"; #my name ?? print $fh "FAX:\t00441223494468\n"; print $fh "TEL:\t00441223494684\n"; print $fh "EMAIL:\tdani\@ebi.ac.uk\n"; print $fh "LAB:\tEnsembl project\n"; print $fh "INST:\tEuopearn Bioinformatics Institute\n"; print $fh "ADDR:\tEMBL-EBI,Wellcome Trust Genome Campus,Hinxton,CB10 1SD Cambridge, UK\n"; print $fh "||\n"; } #prints pub section sub print_pub_section{ my $fh = shift; #publications print $fh "TYPE:\tPUB:\n"; print $fh "||\n"; } #print population section sub print_pop_section{ my $fh = shift; #population print $fh "TYPE:\tPOPULATION\n"; print $fh "HANDLE:\tENSEMBL\n"; print $fh "ID:\t",$population_name,"\n"; print $fh "POP_CLASS:\tUNKNOWN\n"; print $fh "POPULATION:\t"; #add population description ?? print $fh "||\n"; } sub print_method_section{ my $fh = shift; #method print $fh "TYPE:\tMETHOD\n"; print $fh "HANDLE:\tENSEMBL\n"; print $fh "ID:\tEnsembl-SSAHA\n"; #which method ?? print $fh "METHOD_CLASS:\tComputation\n"; print $fh "SEQ_BOTH_STRANDS:\tNA\n"; #both strands ?? print $fh "TEMPLATE_TYPE:\tUNKNOWN\n"; print $fh "MULT_PCR_AMPLIFICATION:\tNA\n"; print $fh "MULT_CLONES_TESTED:\tNA\n"; print $fh "METHOD:\tComputationally discovered SNPs usng SSAHA\n"; #another comment ?? print $fh "||\n"; } #prints the headers for the snpinduse file sub print_ind_headers{ print_cont_section(IND); #contacts section print_pub_section(IND); #publications section print_pop_section(IND); #population section #print some individual specific section print_method_section(IND); #method section }
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-variation/scripts/import/dbSNP_submission.pl
Perl
apache-2.0
5,139
package VMOMI::VirtualMachineScsiPassthroughInfo; use parent 'VMOMI::VirtualMachineTargetInfo'; use strict; use warnings; our @class_ancestors = ( 'VirtualMachineTargetInfo', 'DynamicData', ); our @class_members = ( ['scsiClass', undef, 0, ], ['vendor', undef, 0, ], ['physicalUnitNumber', 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/VirtualMachineScsiPassthroughInfo.pm
Perl
apache-2.0
548
## no critic (RequireUseStrict) package Tapper::Producer::DummyProducer; BEGIN { $Tapper::Producer::DummyProducer::AUTHORITY = 'cpan:TAPPER'; } { $Tapper::Producer::DummyProducer::VERSION = '4.1.3'; } use Moose; sub produce { my ($self, $job, $precondition) = @_; die "Need a TestrunScheduling object in producer" unless ref($job) eq 'Tapper::Schema::TestrunDB::Result::TestrunScheduling'; my $type = $precondition->{options}{type} || 'no_option'; return { precondition_yaml => "---\nprecondition_type: $type\n---\nprecondition_type: second\n", topic => 'new_topic', }; } 1; __END__ =pod =encoding utf-8 =head1 NAME Tapper::Producer::DummyProducer =head2 produce Produce resulting precondition. =head1 AUTHOR AMD OSRC Tapper Team <tapper@amd64.org> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by Advanced Micro Devices, Inc.. This is free software, licensed under: The (two-clause) FreeBSD License =cut
gitpan/Tapper-Producer
lib/Tapper/Producer/DummyProducer.pm
Perl
bsd-2-clause
1,125
# # Copyright (c) 2014,2015 Apple Inc. All rights reserved. # # corecrypto Internal Use License Agreement # # IMPORTANT: This Apple corecrypto software is supplied to you by Apple Inc. ("Apple") # in consideration of your agreement to the following terms, and your download or use # of this Apple software constitutes acceptance of these terms. If you do not agree # with these terms, please do not download or use this Apple software. # # 1. As used in this Agreement, the term "Apple Software" collectively means and # includes all of the Apple corecrypto materials provided by Apple here, including # but not limited to the Apple corecrypto software, frameworks, libraries, documentation # and other Apple-created materials. In consideration of your agreement to abide by the # following terms, conditioned upon your compliance with these terms and subject to # these terms, Apple grants you, for a period of ninety (90) days from the date you # download the Apple Software, a limited, non-exclusive, non-sublicensable license # under Apple’s copyrights in the Apple Software to make a reasonable number of copies # of, compile, and run the Apple Software internally within your organization only on # devices and computers you own or control, for the sole purpose of verifying the # security characteristics and correct functioning of the Apple Software; provided # that you must retain this notice and the following text and disclaimers in all # copies of the Apple Software that you make. You may not, directly or indirectly, # redistribute the Apple Software or any portions thereof. The Apple Software is only # licensed and intended for use as expressly stated above and may not be used for other # purposes or in other contexts without Apple's prior written permission. Except as # expressly stated in this notice, no other rights or licenses, express or implied, are # granted by Apple herein. # # 2. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO # WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES # OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING # THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS, # SYSTEMS, OR SERVICES. APPLE DOES NOT WARRANT THAT THE APPLE SOFTWARE WILL MEET YOUR # REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR # ERROR-FREE, THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED, OR THAT THE APPLE # SOFTWARE WILL BE COMPATIBLE WITH FUTURE APPLE PRODUCTS, SOFTWARE OR SERVICES. NO ORAL # OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE # WILL CREATE A WARRANTY. # # 3. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL # OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING # IN ANY WAY OUT OF THE USE, REPRODUCTION, COMPILATION OR OPERATION OF THE APPLE # SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING # NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # 4. This Agreement is effective until terminated. Your rights under this Agreement will # terminate automatically without notice from Apple if you fail to comply with any term(s) # of this Agreement. Upon termination, you agree to cease all use of the Apple Software # and destroy all copies, full or partial, of the Apple Software. This Agreement will be # governed and construed in accordance with the laws of the State of California, without # regard to its choice of law rules. # # You may report security issues about Apple products to product-security@apple.com, # as described here:  https://www.apple.com/support/security/. Non-security bugs and # enhancement requests can be made via https://bugreport.apple.com as described # here: https://developer.apple.com/bug-reporting/ # # EA1350 # 10/5/15 # #!/usr/bin/perl -w sub stringit { my ($arg)=@_; $arg =~ s/(\w\w)/\\x$1/g; return "\"".$arg."\""; } sub readit { $_ = <STDIN>; s/\r//; s/\n//; return $_; } sub readstring { my ($k)=@_; $s = readit; $s =~ s/^${k} = (\w*).*/$1/; $l = length($s)/2; $s = stringit($s); return ($l, $s); } sub readvalue { my ($k)=@_; $s = readit; $s =~ s/^\[$k = (\w*)\].*/$1/; return $s; } sub read_vectors { while($_ !~ /^\[/) { readit; if($_ =~ /^COUNT = /) { $count = $_; $count =~ s/\r//; $count =~ s/\n//; ($el, $e) = readstring("EntropyInput"); ($nl, $n) = readstring("Nonce"); ($psl, $ps) = readstring("PersonalizationString"); readit; # skip ** INSTANTIATE: readit; # skip V = ... readit; # skip Key = ($erl, $er) = readstring("EntropyInputReseed"); ($arl, $ar) = readstring("AdditionalInputReseed"); readit; # skip ** RESEED: readit; # skip V = ... readit; # skip Key = ($a0l, $a0) = readstring("AdditionalInput"); readit; # skip ** GENERATE (FIRST CALL): readit; # skip V = ... readit; # skip Key = ($a1l, $a1) = readstring("AdditionalInput"); ($rl, $r) = readstring("ReturnedBits"); readit; # skip ** GENERATE (SECOND CALL): readit; # skip V = ... readit; # skip Key = print F "{ /* $count */\n"; print F "\t$el, $e,\n"; print F "\t$nl, $n,\n"; print F "\t$psl, $ps,\n"; print F "\t$a0l, $a0,\n"; print F "\t$erl, $er,\n"; print F "\t$arl, $ar,\n"; print F "\t$a1l, $a1,\n"; print F "\t$rl, $r\n"; print F "},\n"; } } } sub read_vectors_PR { while($_ !~ /^\[/) { readit; if($_ =~ /^COUNT = /) { $count = $_; $count =~ s/\r//; $count =~ s/\n//; ($el, $e) = readstring("EntropyInput"); ($nl, $n) = readstring("Nonce"); ($psl, $ps) = readstring("PersonalizationString"); ($a0l, $a0) = readstring("AdditionalInput"); ($e1l, $e1) = readstring("EntropyInputPR"); ($a1l, $a1) = readstring("AdditionalInput"); ($e2l, $e2) = readstring("EntropyInputPR"); ($rl, $r) = readstring("ReturnedBits"); print F "{ /* $count */\n"; print F "\t$el, $e,\n"; print F "\t$nl, $n,\n"; print F "\t$psl, $ps,\n"; print F "\t$a0l, $a0,\n"; print F "\t$e1l, $e1,\n"; print F "\t$a1l, $a1,\n"; print F "\t$e2l, $e2,\n"; print F "\t$rl, $r\n"; print F "},\n"; } } } while(<STDIN>) { if (/^\[(SHA-[^]]*)/) { $cipher = $1; $cipher =~ s|/|-|g; # Fix so that SHA-224/512 doesn't make a bad filename $PR = readvalue("PredictionResistance"); $EIL = readvalue("EntropyInputLen"); $NL = readvalue("NonceLen"); $PSL = readvalue("PersonalizationStringLen"); $AIL = readvalue("AdditionalInputLen"); $RBL = readvalue("ReturnedBitsLen"); readit; $filename="HMAC_DRBG-".$cipher; if($PR =~ /True/) { $filename=$filename."-PR"; } open(F, ">>$filename.inc"); print F "/* Cipher: $cipher "; print F " PR: $PR "; print F " EIL: $EIL "; print F " NL: $NL "; print F " PSL: $PSL "; print F " AIL: $AIL "; print F " RBL: $RBL */\n"; if($PR =~ /True/) { read_vectors_PR; } else { read_vectors; } print F "\n"; close(F); } }
GaloisInc/hacrypto
src/C/corecrypto/ccdrbg/xcunit/drbg-14.3.pl
Perl
bsd-3-clause
7,293
#!/usr/bin/perl # THIS IS A MODIFIED VERSION OF NMAP2SQLITE SCRIPT ORIGINALLY DEVELOPED BY ANTHONY G PERSAUD # BUT MODIFIED TO WORK WITH MYSQL DATABASES BY ROBIN BOWES. # nmap2db.pl # Description: # It takes in a nmap xml file and stores it into a SQLite database using DBI for # searching, storing and better reporting. This is just an example of how an # IP network database can be created using Nmap-Parser and automation. # # # 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. # use strict; use DBI; use Nmap::Parser 1.00; use vars qw(%S %G); use File::Spec::Functions; use Pod::Usage; use Carp; #Will use in the future use Getopt::Long; Getopt::Long::Configure('bundling'); GetOptions( 'help|h|?' => \$G{helpme}, 'nmap=s' => \$G{nmap}, 'xml' => \$G{file}, 'scan' => \$G{scan}, 'dbhost=s' => \$G{DBHOST}, 'db=s' => \$G{DBNAME}, 'dbtype=s' => \$G{DBTYPE}, 'table=s' => \$G{TABLE}, 'dbuser=s' => \$G{DBUSER}, 'dbpass=s' => \$G{DBPASS}, ) or ( pod2usage( -exitstatus => 0, -verbose => 2 ) ); unless ( $G{file} || $G{scan} ) { pod2usage( -exitstatus => 0, -verbose => 2 ); } print "\n$0 - ( http://nmapparser.wordpress.com )\n", ( '-' x 50 ), "\n\n"; if ( $G{scan} && $G{nmap} eq '' ) { $G{nmap} = find_exe(); } $G{DBNAME} ||= 'ip.db'; $G{TABLE} ||= 'hosts'; $G{DBTYPE} ||= 'SQLite'; if ( $G{DBTYPE} eq 'mysql' ) { $G{DBHOST} ||= 'localhost'; } print "Using DATABASE : $G{DBNAME}\n"; print "Database type : $G{DBTYPE}\n"; if ( $G{DBTYPE} eq 'mysql' ) { print "Using host : $G{DBHOST}\n"; print "Using user : $G{DBUSER}\n" if $G{DBUSER}; } print "Using TABLE : $G{TABLE}\n"; print "Using NMAP_EXE : $G{nmap}\n" if ( $G{scan} ); #Schema for table, simple for now $S{CREATE_TABLE} = qq{ CREATE TABLE } . $G{TABLE} . qq{ ( ip VARCHAR(15) PRIMARY KEY NOT NULL, mac VARCHAR(17), status VARCHAR(7) DEFAULT 'down', hostname TEXT, open_ports TEXT, filtered_ports TEXT, osname TEXT, osfamily TEXT, osgen TEXT, last_scanned TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE (ip)) }; $S{INSERT_HOST} = qq{REPLACE INTO } . $G{TABLE} . qq{ (ip, mac, status, hostname, open_ports, filtered_ports, osname, osfamily, osgen) VALUES (?,?,?,?,?,?,?,?,?)}; my $np = new Nmap::Parser; $np->callback( \&insert_host ); #not implemented in this script, will finish later... ;-) #$np->parsescan($PATH_TO_NMAP, $NMAP_ARGS, @IPS); # Set up the DB connection my $dsn = "DBI:$G{DBTYPE}"; $dsn .= ":host=$G{DBHOST}" if $G{DBTYPE} eq 'mysql'; $dsn .= ":$G{DBNAME}"; my $dbh = eval { DBI->connect( $dsn, $G{DBUSER}, $G{DBPASS} ) }; croak $@ if ($@); # Check if table exists... if ( !table_exists( $dbh, $G{DBNAME}, $G{TABLE} ) ) { print "\nGenerating table: $G{TABLE} ...\n"; eval { $dbh->do( $S{CREATE_TABLE} ) }; croak $@ if ($@); } #do stuff my $sth_ins = eval { $dbh->prepare_cached( $S{INSERT_HOST} ) }; croak $@ if ($@); #for every host scanned, insert or updated it in the table if ( $G{file} ) { for my $file (@ARGV) { print "\nProcessing file $file...\n"; $np->parsefile($file); } } elsif ( $G{scan} && $G{nmap} ) { print "\nProcessing scan: " . $G{nmap} . ' -sT -O -F ' . join( ' ', @ARGV ); $np->parsescan( $G{nmap}, '-sT -O -F', @ARGV ); } #Booyah! $sth_ins->finish; $dbh->disconnect(); #This function will insert the host, or update it if it already exists #Of course, we can always check the last_scanned entry in the database to #make sure the latest information is there, but this is just beta version. sub insert_host { my $host = shift; my $os = $host->os_sig(); #ip, mac, status, hostname, open_ports, filtered_ports, os_family, os_gen my @input_values = ( $host->addr, $host->mac_addr || undef, $host->status || undef, $host->hostname || undef, join( ',', $host->tcp_open_ports ) || undef, join( ',', $host->tcp_filtered_ports ) || undef, $os->name || undef, $os->osfamily || undef, $os->osgen || undef ); my $rv = $sth_ins->execute(@input_values) ? "ok" : "OOPS! - " . DBI->errstr; printf( "\t..> %-15s : (%4s) : %-s\n", $host->addr, $host->status, $rv ); } sub find_exe { my $exe_to_find = 'nmap'; $exe_to_find =~ s/\.exe//; local ($_); local (*DIR); for my $dir ( File::Spec->path() ) { opendir( DIR, $dir ) || next; my @files = ( readdir(DIR) ); closedir(DIR); my $path; for my $file (@files) { $file =~ s/\.exe$//; next unless ( $file eq $exe_to_find ); $path = File::Spec->catfile( $dir, $file ); next unless -r $path && ( -x _ || -l _ ); return $path; last DIR; } } warn "[Nmap2SQLite] No nmap in your PATH: use '--nmap nmap_path' option\n"; exit; } sub table_exists { my ( $dbh, $dbname, $tblname ) = @_; my @names = eval { $dbh->tables( '', $dbname, $tblname, "TABLE" ) }; croak $@ if ($@); my %names_h; @names_h{@names} = (); my $sql_quote_char = $dbh->get_info(29); return ( exists( $names_h{ $sql_quote_char . $tblname . $sql_quote_char } ) ); } __END__ =pod =head1 NAME nmap2db - store nmap scan data into entries in SQLite/MySQL database =head1 SYNOPSIS nmap2db.pl [options] --xml <XML_FILE> [<XML_FILE> ...] nmap2db.pl [options] --scan <IP_ADDR> [<IP_ADDR> ...] Examples connecting to a MySQL database (Robin Bowes): nmap2db.pl --dbtype mysql --dbname netdb --dbuser netuser --dbpass secret --xml 192.168.25.0.xml =head1 DESCRIPTION This script uses the nmap security scanner with the Nmap::Parser module in order to take an xml output scan file from nmap (-oX option), and place the information into a SQLite database (ip.db), into table (hosts). This is a modified version of the nmap2sqlite.pl script written originally by Anthony Persaud but modified by Robin Bowes to support MySQL databases. Here is the schema for the table stored in the SQLite database ip TEXT PRIMARY KEY NOT NULL, mac TEXT, status TEXT, hostname TEXT, open_ports TEXT, filtered_ports TEXT, osname TEXT, osfamily TEXT, osgen TEXT, last_scanned TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE (ip)) =head1 OPTIONS These options are passed as command line parameters. Please use EITHER --scan or --xml. NOT both. =over 4 =item B<--dbhost DBHOST> Connect to the DB on server DBHOST. Default: localhost. =item B<--db DBNAME> Sets the database name to DBNAME. Default: ip.db =item B<--dbtype DBTYPE> Sets the type of databases to use. Currently supported values are: mysql, SQLite Default: SQLite =item B<--table TABLE_NAME> Sets the table name to use in the database as TABLE_NAME. Default: hosts =item B<--dbuser DBUSER> Connect to the database as user DBUSER. Default: current user =item B<--dbpass DBPASS> Connect to the database with password DBPASS Default: no password =item B<-h,--help,-?> Shows this help information. =item B<--nmap> The path to the nmap executable. This should be used if nmap is not on your path. =item B<--scan> This will use parsescan() for the scan and take the arguments as IP addreses. =item B<--xml> This will use parsefile() for the input and take the arguments as nmap scan xml files. =back 4 =head1 TARGET SPECIFICATION This documentation was taken from the nmap man page. The IP address inputs to this scripts should be in the nmap target specification format. The simplest case is listing single hostnames or IP addresses onthe command line. If you want to scan a subnet of IP addresses, you can append '/mask' to the hostname or IP address. mask must be between 0 (scan the whole internet) and 32 (scan the single host specified). Use /24 to scan a class 'C' address and /16 for a class 'B'. You can use a more powerful notation which lets you specify an IP address using lists/ranges for each element. Thus you can scan the whole class 'B' network 128.210.*.* by specifying '128.210.*.*' or '128.210.0-255.0-255' or even use the mask notation: '128.210.0.0/16'. These are all equivalent. If you use asterisks ('*'), remember that most shells require you to escape them with back slashes or protect them with quotes. Another interesting thing to do is slice the Internet the other way. Examples: nmap2db.pl --scan 127.0.0.1 nmap2db.pl --scan target.example.com nmap2db.pl --scan target.example.com/24 nmap2db.pl --scan 10.210.*.1-127 nmap2db.pl --scan *.*.2.3-5 nmap2db.pl --scan 10.[10-15].10.[2-254] Examples connecting to a MySQL database: nmap2db.pl --dbtype mysql --dbname netdb --dbuser netuser --dbpass secret --xml 192.168.25.0.xml =head1 OUTPUT EXAMPLE See the SQLite database that is created. Default ip.db =head1 SUPPORT =head2 Discussion Forum If you have questions about how to use the module, or any of its features, you can post messages to the Nmap::Parser module forum on CPAN::Forum. L<http://www.cpanforum.com/dist/Nmap-Parser> =head2 Bug Reports Please submit any bugs to: L<https://github.com/apersaud/Nmap-Parser/issues> B<Please make sure that you submit the xml-output file of the scan which you are having trouble.> This can be done by running your scan with the I<-oX filename.xml> nmap switch. Please remove any important IP addresses for security reasons. =head2 Feature Requests Please submit any requests to: L<https://github.com/apersaud/Nmap-Parser/issues> =head1 SEE ALSO L<Nmap::Parser> The Nmap::Parser page can be found at: L<https://github.com/apersaud/Nmap-Parser>. It contains the latest developments on the module. The nmap security scanner homepage can be found at: L<http://www.insecure.org/nmap/>. =head1 AUTHOR Anthony Persaud <apersaud[at]gmail.com> L<http://modernistik.com> Additional features and improvements by: Robin Bowes <robin[at]robinbowes.com> L<http://robinbowes.com> Daniel Miller L<http://bonsaiviking.com/> =head1 COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. L<http://www.opensource.org/licenses/gpl-license.php> =cut
gitpan/Nmap-Parser
tools/nmap2db.pl
Perl
mit
11,802
package Google::Ads::AdWords::v201409::CampaignService::query; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409' } __PACKAGE__->__set_name('query'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::SOAP::Typelib::ComplexType ); our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %query_of :ATTR(:get<query>); __PACKAGE__->_factory( [ qw( query ) ], { 'query' => \%query_of, }, { 'query' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', }, { 'query' => 'query', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201409::CampaignService::query =head1 DESCRIPTION Perl data type class for the XML Schema defined element query from the namespace https://adwords.google.com/api/adwords/cm/v201409. Returns the list of campaigns that match the query. @param query The SQL-like AWQL query string. @return A list of campaigns. @throws ApiException if problems occur while parsing the query or fetching campaign information. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * query $element->set_query($data); $element->get_query(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201409::CampaignService::query->new($data); Constructor. The following data structure may be passed to new(): { query => $some_value, # string }, =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/CampaignService/query.pm
Perl
apache-2.0
1,916
# 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. package Lucy::Search::Matcher; use Lucy; our $VERSION = '0.005000'; $VERSION = eval $VERSION; 1; __END__
rectang/lucy
perl/lib/Lucy/Search/Matcher.pm
Perl
apache-2.0
891
package Paws::Pinpoint::SendMessagesResponse; use Moose; has MessageResponse => (is => 'ro', isa => 'Paws::Pinpoint::MessageResponse', required => 1); use MooseX::ClassAttribute; class_has _stream_param => (is => 'ro', default => 'MessageResponse'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::Pinpoint::SendMessagesResponse =head1 ATTRIBUTES =head2 B<REQUIRED> MessageResponse => L<Paws::Pinpoint::MessageResponse> =head2 _request_id => Str =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/Pinpoint/SendMessagesResponse.pm
Perl
apache-2.0
532
package # Date::Manip::TZ::asbagh00; # 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 10:41:41 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.org/tz use strict; use warnings; require 5.010000; our (%Dates,%LastRule); END { undef %Dates; undef %LastRule; } our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } %Dates = ( 1 => [ [ [1,1,2,0,0,0],[1,1,2,2,57,40],'+02:57:40',[2,57,40], 'LMT',0,[1889,12,31,21,2,19],[1889,12,31,23,59,59], '0001010200:00:00','0001010202:57:40','1889123121:02:19','1889123123:59:59' ], ], 1889 => [ [ [1889,12,31,21,2,20],[1889,12,31,23,59,56],'+02:57:36',[2,57,36], 'BMT',0,[1917,12,31,21,2,23],[1917,12,31,23,59,59], '1889123121:02:20','1889123123:59:56','1917123121:02:23','1917123123:59:59' ], ], 1917 => [ [ [1917,12,31,21,2,24],[1918,1,1,0,2,24],'+03:00:00',[3,0,0], 'AST',0,[1982,4,30,20,59,59],[1982,4,30,23,59,59], '1917123121:02:24','1918010100:02:24','1982043020:59:59','1982043023:59:59' ], ], 1982 => [ [ [1982,4,30,21,0,0],[1982,5,1,1,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1982,9,30,19,59,59],[1982,9,30,23,59,59], '1982043021:00:00','1982050101:00:00','1982093019:59:59','1982093023:59:59' ], [ [1982,9,30,20,0,0],[1982,9,30,23,0,0],'+03:00:00',[3,0,0], 'AST',0,[1983,3,30,20,59,59],[1983,3,30,23,59,59], '1982093020:00:00','1982093023:00:00','1983033020:59:59','1983033023:59:59' ], ], 1983 => [ [ [1983,3,30,21,0,0],[1983,3,31,1,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1983,9,30,19,59,59],[1983,9,30,23,59,59], '1983033021:00:00','1983033101:00:00','1983093019:59:59','1983093023:59:59' ], [ [1983,9,30,20,0,0],[1983,9,30,23,0,0],'+03:00:00',[3,0,0], 'AST',0,[1984,3,31,20,59,59],[1984,3,31,23,59,59], '1983093020:00:00','1983093023:00:00','1984033120:59:59','1984033123:59:59' ], ], 1984 => [ [ [1984,3,31,21,0,0],[1984,4,1,1,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1984,9,30,19,59,59],[1984,9,30,23,59,59], '1984033121:00:00','1984040101:00:00','1984093019:59:59','1984093023:59:59' ], [ [1984,9,30,20,0,0],[1984,9,30,23,0,0],'+03:00:00',[3,0,0], 'AST',0,[1985,3,31,20,59,59],[1985,3,31,23,59,59], '1984093020:00:00','1984093023:00:00','1985033120:59:59','1985033123:59:59' ], ], 1985 => [ [ [1985,3,31,21,0,0],[1985,4,1,1,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1985,9,28,21,59,59],[1985,9,29,1,59,59], '1985033121:00:00','1985040101:00:00','1985092821:59:59','1985092901:59:59' ], [ [1985,9,28,22,0,0],[1985,9,29,1,0,0],'+03:00:00',[3,0,0], 'AST',0,[1986,3,29,21,59,59],[1986,3,30,0,59,59], '1985092822:00:00','1985092901:00:00','1986032921:59:59','1986033000:59:59' ], ], 1986 => [ [ [1986,3,29,22,0,0],[1986,3,30,2,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1986,9,27,21,59,59],[1986,9,28,1,59,59], '1986032922:00:00','1986033002:00:00','1986092721:59:59','1986092801:59:59' ], [ [1986,9,27,22,0,0],[1986,9,28,1,0,0],'+03:00:00',[3,0,0], 'AST',0,[1987,3,28,21,59,59],[1987,3,29,0,59,59], '1986092722:00:00','1986092801:00:00','1987032821:59:59','1987032900:59:59' ], ], 1987 => [ [ [1987,3,28,22,0,0],[1987,3,29,2,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1987,9,26,21,59,59],[1987,9,27,1,59,59], '1987032822:00:00','1987032902:00:00','1987092621:59:59','1987092701:59:59' ], [ [1987,9,26,22,0,0],[1987,9,27,1,0,0],'+03:00:00',[3,0,0], 'AST',0,[1988,3,26,21,59,59],[1988,3,27,0,59,59], '1987092622:00:00','1987092701:00:00','1988032621:59:59','1988032700:59:59' ], ], 1988 => [ [ [1988,3,26,22,0,0],[1988,3,27,2,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1988,9,24,21,59,59],[1988,9,25,1,59,59], '1988032622:00:00','1988032702:00:00','1988092421:59:59','1988092501:59:59' ], [ [1988,9,24,22,0,0],[1988,9,25,1,0,0],'+03:00:00',[3,0,0], 'AST',0,[1989,3,25,21,59,59],[1989,3,26,0,59,59], '1988092422:00:00','1988092501:00:00','1989032521:59:59','1989032600:59:59' ], ], 1989 => [ [ [1989,3,25,22,0,0],[1989,3,26,2,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1989,9,23,21,59,59],[1989,9,24,1,59,59], '1989032522:00:00','1989032602:00:00','1989092321:59:59','1989092401:59:59' ], [ [1989,9,23,22,0,0],[1989,9,24,1,0,0],'+03:00:00',[3,0,0], 'AST',0,[1990,3,24,21,59,59],[1990,3,25,0,59,59], '1989092322:00:00','1989092401:00:00','1990032421:59:59','1990032500:59:59' ], ], 1990 => [ [ [1990,3,24,22,0,0],[1990,3,25,2,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1990,9,29,21,59,59],[1990,9,30,1,59,59], '1990032422:00:00','1990032502:00:00','1990092921:59:59','1990093001:59:59' ], [ [1990,9,29,22,0,0],[1990,9,30,1,0,0],'+03:00:00',[3,0,0], 'AST',0,[1991,3,31,23,59,59],[1991,4,1,2,59,59], '1990092922:00:00','1990093001:00:00','1991033123:59:59','1991040102:59:59' ], ], 1991 => [ [ [1991,4,1,0,0,0],[1991,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1991,9,30,23,59,59],[1991,10,1,3,59,59], '1991040100:00:00','1991040104:00:00','1991093023:59:59','1991100103:59:59' ], [ [1991,10,1,0,0,0],[1991,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1992,3,31,23,59,59],[1992,4,1,2,59,59], '1991100100:00:00','1991100103:00:00','1992033123:59:59','1992040102:59:59' ], ], 1992 => [ [ [1992,4,1,0,0,0],[1992,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1992,9,30,23,59,59],[1992,10,1,3,59,59], '1992040100:00:00','1992040104:00:00','1992093023:59:59','1992100103:59:59' ], [ [1992,10,1,0,0,0],[1992,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1993,3,31,23,59,59],[1993,4,1,2,59,59], '1992100100:00:00','1992100103:00:00','1993033123:59:59','1993040102:59:59' ], ], 1993 => [ [ [1993,4,1,0,0,0],[1993,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1993,9,30,23,59,59],[1993,10,1,3,59,59], '1993040100:00:00','1993040104:00:00','1993093023:59:59','1993100103:59:59' ], [ [1993,10,1,0,0,0],[1993,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1994,3,31,23,59,59],[1994,4,1,2,59,59], '1993100100:00:00','1993100103:00:00','1994033123:59:59','1994040102:59:59' ], ], 1994 => [ [ [1994,4,1,0,0,0],[1994,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1994,9,30,23,59,59],[1994,10,1,3,59,59], '1994040100:00:00','1994040104:00:00','1994093023:59:59','1994100103:59:59' ], [ [1994,10,1,0,0,0],[1994,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1995,3,31,23,59,59],[1995,4,1,2,59,59], '1994100100:00:00','1994100103:00:00','1995033123:59:59','1995040102:59:59' ], ], 1995 => [ [ [1995,4,1,0,0,0],[1995,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1995,9,30,23,59,59],[1995,10,1,3,59,59], '1995040100:00:00','1995040104:00:00','1995093023:59:59','1995100103:59:59' ], [ [1995,10,1,0,0,0],[1995,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1996,3,31,23,59,59],[1996,4,1,2,59,59], '1995100100:00:00','1995100103:00:00','1996033123:59:59','1996040102:59:59' ], ], 1996 => [ [ [1996,4,1,0,0,0],[1996,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1996,9,30,23,59,59],[1996,10,1,3,59,59], '1996040100:00:00','1996040104:00:00','1996093023:59:59','1996100103:59:59' ], [ [1996,10,1,0,0,0],[1996,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1997,3,31,23,59,59],[1997,4,1,2,59,59], '1996100100:00:00','1996100103:00:00','1997033123:59:59','1997040102:59:59' ], ], 1997 => [ [ [1997,4,1,0,0,0],[1997,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1997,9,30,23,59,59],[1997,10,1,3,59,59], '1997040100:00:00','1997040104:00:00','1997093023:59:59','1997100103:59:59' ], [ [1997,10,1,0,0,0],[1997,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1998,3,31,23,59,59],[1998,4,1,2,59,59], '1997100100:00:00','1997100103:00:00','1998033123:59:59','1998040102:59:59' ], ], 1998 => [ [ [1998,4,1,0,0,0],[1998,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1998,9,30,23,59,59],[1998,10,1,3,59,59], '1998040100:00:00','1998040104:00:00','1998093023:59:59','1998100103:59:59' ], [ [1998,10,1,0,0,0],[1998,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[1999,3,31,23,59,59],[1999,4,1,2,59,59], '1998100100:00:00','1998100103:00:00','1999033123:59:59','1999040102:59:59' ], ], 1999 => [ [ [1999,4,1,0,0,0],[1999,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[1999,9,30,23,59,59],[1999,10,1,3,59,59], '1999040100:00:00','1999040104:00:00','1999093023:59:59','1999100103:59:59' ], [ [1999,10,1,0,0,0],[1999,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2000,3,31,23,59,59],[2000,4,1,2,59,59], '1999100100:00:00','1999100103:00:00','2000033123:59:59','2000040102:59:59' ], ], 2000 => [ [ [2000,4,1,0,0,0],[2000,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2000,9,30,23,59,59],[2000,10,1,3,59,59], '2000040100:00:00','2000040104:00:00','2000093023:59:59','2000100103:59:59' ], [ [2000,10,1,0,0,0],[2000,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2001,3,31,23,59,59],[2001,4,1,2,59,59], '2000100100:00:00','2000100103:00:00','2001033123:59:59','2001040102:59:59' ], ], 2001 => [ [ [2001,4,1,0,0,0],[2001,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2001,9,30,23,59,59],[2001,10,1,3,59,59], '2001040100:00:00','2001040104:00:00','2001093023:59:59','2001100103:59:59' ], [ [2001,10,1,0,0,0],[2001,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2002,3,31,23,59,59],[2002,4,1,2,59,59], '2001100100:00:00','2001100103:00:00','2002033123:59:59','2002040102:59:59' ], ], 2002 => [ [ [2002,4,1,0,0,0],[2002,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2002,9,30,23,59,59],[2002,10,1,3,59,59], '2002040100:00:00','2002040104:00:00','2002093023:59:59','2002100103:59:59' ], [ [2002,10,1,0,0,0],[2002,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2003,3,31,23,59,59],[2003,4,1,2,59,59], '2002100100:00:00','2002100103:00:00','2003033123:59:59','2003040102:59:59' ], ], 2003 => [ [ [2003,4,1,0,0,0],[2003,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2003,9,30,23,59,59],[2003,10,1,3,59,59], '2003040100:00:00','2003040104:00:00','2003093023:59:59','2003100103:59:59' ], [ [2003,10,1,0,0,0],[2003,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2004,3,31,23,59,59],[2004,4,1,2,59,59], '2003100100:00:00','2003100103:00:00','2004033123:59:59','2004040102:59:59' ], ], 2004 => [ [ [2004,4,1,0,0,0],[2004,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2004,9,30,23,59,59],[2004,10,1,3,59,59], '2004040100:00:00','2004040104:00:00','2004093023:59:59','2004100103:59:59' ], [ [2004,10,1,0,0,0],[2004,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2005,3,31,23,59,59],[2005,4,1,2,59,59], '2004100100:00:00','2004100103:00:00','2005033123:59:59','2005040102:59:59' ], ], 2005 => [ [ [2005,4,1,0,0,0],[2005,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2005,9,30,23,59,59],[2005,10,1,3,59,59], '2005040100:00:00','2005040104:00:00','2005093023:59:59','2005100103:59:59' ], [ [2005,10,1,0,0,0],[2005,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2006,3,31,23,59,59],[2006,4,1,2,59,59], '2005100100:00:00','2005100103:00:00','2006033123:59:59','2006040102:59:59' ], ], 2006 => [ [ [2006,4,1,0,0,0],[2006,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2006,9,30,23,59,59],[2006,10,1,3,59,59], '2006040100:00:00','2006040104:00:00','2006093023:59:59','2006100103:59:59' ], [ [2006,10,1,0,0,0],[2006,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[2007,3,31,23,59,59],[2007,4,1,2,59,59], '2006100100:00:00','2006100103:00:00','2007033123:59:59','2007040102:59:59' ], ], 2007 => [ [ [2007,4,1,0,0,0],[2007,4,1,4,0,0],'+04:00:00',[4,0,0], 'ADT',1,[2007,9,30,23,59,59],[2007,10,1,3,59,59], '2007040100:00:00','2007040104:00:00','2007093023:59:59','2007100103:59:59' ], [ [2007,10,1,0,0,0],[2007,10,1,3,0,0],'+03:00:00',[3,0,0], 'AST',0,[9999,12,31,0,0,0],[9999,12,31,3,0,0], '2007100100:00:00','2007100103:00:00','9999123100:00:00','9999123103:00:00' ], ], ); %LastRule = ( ); 1;
nriley/Pester
Source/Manip/TZ/asbagh00.pm
Perl
bsd-2-clause
13,419
package Anysyncd::Action::CSync2; =head1 NAME Anysyncd::Action::CSync2 - csync2 based syncer for anysyncd =head1 SYNOPSIS [syncpair] handler = Anysyncd::Action::CSync2 prod_dir = /tmp/testdir csync_dir = /tmp/testdir2 watcher = /tmp/testdir remote_hosts = host1 host2 =head1 DESCRIPTION Anysyncd::Action::CSync2 is a syncer for anysyncd that uses csync2. It aims at being more robust by using csync2's ability to detect conflicts as well as other measures to ensure that only consistent states of the whole directory are used on any side. =head2 Configuration File For a general description of the configuration file, look at the anysynd documentation. =head3 CSync2 syncer options =over =item C<prod_dir> I<path> This is the source path for the whole process. This should be the path your applications use to store their files. =item C<csync_dir> I<path> This is the path for an intermediate copy of prod_dir used by csync2 for the sync to other nodes. This path must be included in the corresponding csync2 sync group. =item C<remote_hosts> I<host1 host2 host3> This list (seperated by whitespace) should include all other hosts in the csync2 cluster. This module requires SSH access to all of them. Either for the root user or a normal user that has sufficient rights, maybe granted by remote_prefix_command. =item C<remote_prefix_command> I<cmd> This allows to prefix all remote commands with I<cmd>. This can be used to employ sudo for example. =item C<retry_interval> I<seconds> This option defines the distance in time between two tries to sync a consistent directory state with no intermittent changes. Depending on typical workload on your prod_dir, this might be tuned to avoid many retries. =back =head2 csync2 Configuration File This module needs a working csync2 configuration that satisfies two conditions: =over =item * For each Anysyncd::Action::CSync2 syncer there is a csync2 sync group with an identical name =item * Each of these sync groups include the csync_dir from their corresponding Anysyncd::Action::CSync2 syncer. =back =head3 Example csync2 sync group This example of a csync2 sync group configuration would match the anysyncd configuration from the synopsis above. group syncpair { host host1; host host2; key /etc/csync2.key; include "/tmp/testdir2"; auto none; } =cut use Moose; use Net::OpenSSH; use AnyEvent::Util; use Carp qw(croak); use String::ShellQuote; use Anysyncd::Action::CSync2::Utils; extends 'Anysyncd::Action::Base'; has _retry_interval => ( is => 'rw', isa => 'Int', builder => '_build_retry_interval', lazy => 1, documentation => " when local sync fails, retry in this interval" ); sub _build_retry_interval { my $self = shift; return $self->config->{'retry_interval'} || 2; } sub BUILD { my $self = shift; # do some sanity checks if ( !$self->config->{'prod_dir'} or !$self->config->{'csync_dir'} or !$self->config->{'remote_hosts'} ) { croak( "BUILD(): At least one of 'prod_dir', 'csync_dir' and " . "'remote_hosts' is not configured." ); } # Do one full sync at startup unless ( $self->_noop() ) { $self->log->info("BUILD(): executing startup sync"); $self->process_files('full'); } } sub process_files { my ( $self, $full_sync ) = @_; $self->_lock(); $self->log->debug("process_files(): Processing files"); if ( !$full_sync and !scalar @{ $self->files() } ) { $self->log->debug("process_files(): No files to sync"); $self->_unlock(); return; } fork_call { my ( $err, $errstr, $start_ts ) = ( 0, "", undef ); # we try very hard to finish one local sync with no intermittent changes foreach my $i ( 1 .. 100 ) { $self->log->debug( "process_files(): local rsync run $i files: " . scalar( @{ $self->files } ) ); # clear list of files $self->files_clear; $start_ts = time(); $err = $self->_local_rsync(); $self->log->debug( "process_files(): local rsync finished " . "within " . ( time() - $start_ts ) . " seconds" ); if ( $err or scalar( @{ $self->files } ) ) { $self->log->debug( "process_files(): rsync was unsuccessfull " . "or new file changes arrived." ); my $diff_ts = time() - $start_ts; while ( $diff_ts < $self->_retry_interval ) { my $sleep = $self->_retry_interval - $diff_ts; $self->log->debug( "process_files(): delaying next run by " . "${sleep}s" ); sleep($sleep); $diff_ts = time() - $start_ts; } } else { $self->log->debug( "process_files(): No more file changes " . "left to sync" ); ( $err, $errstr ) = ( 0, "" ); last; } } if ($err) { $errstr = "process_files(): could not achieve a consistent local " . "sync state after 100 retries."; } # now follows everything involving the network ( $err, $errstr ) = $self->_check_stamps() if ( !$err ); ( $err, $errstr ) = $self->_csync2() if ( !$err ); ( $err, $errstr ) = $self->_commit_remote() if ( !$err ); return ( $err, $errstr, $start_ts ); } sub { my ( $err, $errstr, $start_ts ) = @_; if ($@) { $err = 1; $errstr = "process_files(): My child died: $@"; } if ($err) { $self->_report_error($errstr); } else { $self->_stamp_file( "success", $start_ts ); $self->log->info("process_files(): Synchronization succeeded."); } $self->_unlock(); }; } sub _commit_remote { my ($self) = @_; my $errstr = ""; my $err = 0; $self->log->debug("_commit_remote(): sub got called"); for my $host ( split( '\s+', $self->config->{'remote_hosts'} ) ) { my ( $l_err, $l_errstr ) = $self->_remote_cmd( $host, "anysyncd-csync2-remote-helper", "commit", $self->config->{name} ); if ($l_err) { $err++; $errstr .= "_commit_remote(): committing $host failed: " . $l_errstr . "\n\n"; } else { $self->log->debug("_commit_remote(): committing $host succeeded"); } } return ( $err, $errstr ); } sub _remote_cmd { my ( $self, $host, @cmd ) = @_; my ( $err, $errstr ) = ( 0, "" ); my $ssh = Net::OpenSSH->new($host); my $remote_prefix_cmd = $self->config->{'remote_prefix_command'} || undef; if ($remote_prefix_cmd) { unshift @cmd, $remote_prefix_cmd; } $self->log->debug( "_remote_cmd(): " . join( " ", @cmd ) ); my ( $out, $err_out ) = $ssh->capture2(@cmd); if ( $ssh->error or $err_out ) { $err++; $errstr = $ssh->error if $ssh->error; $errstr = ( $errstr ? "$errstr: $err_out" : $err_out ) if $err_out; } return ( $err, $errstr, $out ); } sub _csync2 { my ($self) = @_; my ( $err, $errstr ) = ( 0, "" ); $self->log->debug("_csync2(): sub got called"); my $cmd = "csync2 -x -G " . shell_quote( $self->config->{name} ) . " 2>&1"; my $csync_out = `$cmd`; $err = $?; if ($err) { $errstr = "_csync2(): csync2 failed with $err: $csync_out"; } return ( $err, $errstr ); } sub _local_rsync { my ($self) = @_; my $proddir = $self->config->{'prod_dir'}; my $csyncdir = $self->config->{'csync_dir'}; my $utils = Anysyncd::Action::CSync2::Utils->new( { name => $self->config->{name} } ); $self->log->debug("_local_rsync(): sub got called"); my ( $err, $errstr ) = $utils->rsync( $proddir, $csyncdir ); $self->log->info($errstr) if $err; return $err; } sub _check_stamps { my ($self) = @_; my $errstr = ""; my $err = 0; my $syncer = $self->config->{name}; $self->log->debug("_check_stamps(): sub got called"); for my $host ( split( '\s+', $self->config->{'remote_hosts'} ) ) { my ( $l_err, $l_errstr, $out ) = $self->_remote_cmd( $host, "anysyncd-csync2-remote-helper", "stamps", $syncer ); if ( not $l_err and $out =~ /^[0-9]{0,10}:[0-9]{0,10}$/ ) { my ( $succ, $lastchange ) = split( ':', $out ); if ( $succ and $lastchange and ( $lastchange > $succ ) ) { $err++; $errstr .= "_check_stamps(): remote host $host seems to have " . "unsynced changes. Syncing our changes to that host might be unsafe.\n\n"; } } if ($l_err) { $err++; $errstr .= "_check_stamps(): getting timestamps from $host failed: " . $l_errstr . "\n\n"; } if ( !$err ) { $self->log->debug("_check_stamps(): stamps on $host check out"); } } return ( $err, $errstr ); } 1; =pod =head1 LICENSE This is released under the MIT License. See the B<COPYRIGHT> file. =head1 AUTHOR Carsten Wolff <carsten.wolff@credativ.de>, Patrick Schoenfeld <patrick.schoenfeld@credativ.de> =cut # vim: syntax=perl sw=4 ts=4 et shiftround
credativ/pkg-anysyncd
lib/Anysyncd/Action/CSync2.pm
Perl
mit
9,709
=pod =head1 NAME OSSL_CMP_log_open, OSSL_CMP_log_close, OSSL_CMP_severity, OSSL_CMP_LOG_EMERG, OSSL_CMP_LOG_ALERT, OSSL_CMP_LOG_CRIT, OSSL_CMP_LOG_ERR, OSSL_CMP_LOG_WARNING, OSSL_CMP_LOG_NOTICE, OSSL_CMP_LOG_INFO, OSSL_CMP_LOG_DEBUG, OSSL_CMP_LOG_TRACE, OSSL_CMP_log_cb_t, OSSL_CMP_print_to_bio, OSSL_CMP_print_errors_cb - functions for logging and error reporting =head1 SYNOPSIS #include <openssl/cmp_util.h> int OSSL_CMP_log_open(void); void OSSL_CMP_log_close(void); /* severity level declarations resemble those from syslog.h */ typedef int OSSL_CMP_severity; #define OSSL_CMP_LOG_EMERG 0 #define OSSL_CMP_LOG_ALERT 1 #define OSSL_CMP_LOG_CRIT 2 #define OSSL_CMP_LOG_ERR 3 #define OSSL_CMP_LOG_WARNING 4 #define OSSL_CMP_LOG_NOTICE 5 #define OSSL_CMP_LOG_INFO 6 #define OSSL_CMP_LOG_DEBUG 7 #define OSSL_CMP_LOG_TRACE 8 typedef int (*OSSL_CMP_log_cb_t)(const char *component, const char *file, int line, OSSL_CMP_severity level, const char *msg); int OSSL_CMP_print_to_bio(BIO *bio, const char *component, const char *file, int line, OSSL_CMP_severity level, const char *msg); void OSSL_CMP_print_errors_cb(OSSL_CMP_log_cb_t log_fn); =head1 DESCRIPTION The logging and error reporting facility described here contains convenience functions for CMP-specific logging, including a string prefix mirroring the severity levels of syslog.h, and enhancements of the error queue mechanism needed for large diagnostic messages produced by the CMP library in case of certificate validation failures. When an interesting activity is performed or an error occurs, some detail should be provided for user information, debugging, and auditing purposes. A CMP application can obtain this information by providing a callback function with the following type: typedef int (*OSSL_CMP_log_cb_t)(const char *component, const char *file, int line, OSSL_CMP_severity level, const char *msg); The parameters may provide some component info (which may be a module name and/or function name) or NULL, a file pathname or NULL, a line number or 0 indicating the source code location, a severity level, and a message string describing the nature of the event, terminated by '\n'. Even when an activity is successful some warnings may be useful and some degree of auditing may be required. Therefore, the logging facility supports a severity level and the callback function has a I<level> parameter indicating such a level, such that error, warning, info, debug, etc. can be treated differently. The callback is activated only when the severity level is sufficient according to the current level of verbosity, which by default is B<OSSL_CMP_LOG_INFO>. The callback function may itself do non-trivial tasks like writing to a log file or remote stream, which in turn may fail. Therefore, the function should return 1 on success and 0 on failure. OSSL_CMP_log_open() initializes the CMP-specific logging facility to output everything to STDOUT. It fails if the integrated tracing is disabled or STDIO is not available. It may be called during application startup. Alternatively, L<OSSL_CMP_CTX_set_log_cb(3)> can be used for more flexibility. As long as neither if the two is used any logging output is ignored. OSSL_CMP_log_close() may be called when all activities are finished to flush any pending CMP-specific log output and deallocate related resources. It may be called multiple times. It does get called at OpenSSL stutdown. OSSL_CMP_print_to_bio() prints the given component info, filename, line number, severity level, and log message or error queue message to the given I<bio>. I<component> usually is a function or module name. If it is NULL, empty, or "(unknown function)" then "CMP" is used as fallback. OSSL_CMP_print_errors_cb() outputs any entries in the OpenSSL error queue. It is similar to L<ERR_print_errors_cb(3)> but uses the CMP log callback function I<log_fn> for uniformity with CMP logging if not NULL. Otherwise it prints to STDERR using L<OSSL_CMP_print_to_bio(3)> (unless B<OPENSSL_NO_STDIO> is defined). =head1 RETURN VALUES OSSL_CMP_log_close() and OSSL_CMP_print_errors_cb() do not return anything. All other functions return 1 on success, 0 on error. =head1 HISTORY The OpenSSL CMP support was added in OpenSSL 3.0. =head1 COPYRIGHT Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
jens-maus/amissl
openssl/doc/man3/OSSL_CMP_log_open.pod
Perl
bsd-3-clause
4,788
#!/usr/bin/perl #~ Copyright 2003, Rene Rivera. #~ Use, modification and distribution are subject to the Boost Software #~ License Version 1.0. (See accompanying file LICENSE_1_0.txt or #~ http://www.boost.org/LICENSE_1_0.txt) use FileHandle; use Time::Local; # Get the whle percent value # sub percent_value { my ($count,$total) = @_; my $percent = int (($count/$total)*100+0.5); if ($count > 0 && $percent == 0) { $percent = 1; } if ($count < $total && $percent == 100) { $percent = 99; } return $percent; } # Generate item html for the pass column. # sub result_info_pass { my ($color,$pass,$warn,$fail,$missing) = @_; my $percent = 100-percent_value($fail+$missing,$pass+$warn+$fail+$missing); return "<font color=\"$color\"><font size=\"+1\">$percent%</font><br>($warn&nbsp;warnings)</font>"; } # Generate item html for the fail column. # sub result_info_fail { my ($color,$pass,$warn,$fail,$missing) = @_; my $percent = percent_value($fail+$missing,$pass+$warn+$fail+$missing); return "<font color=\"$color\"><font size=\"+1\">$percent%</font><br>($fail)</font>"; } # Generate an age highlighted run date string. # Use as: data_info(run-date-html) # sub date_info { my %m = ('January',0,'February',1,'March',2,'April',3,'May',4,'June',5, 'July',6,'August',7,'September',8,'October',9,'November',10,'December',11); my @d = split(/ |:/,$_[0]); my ($hour,$min,$sec,$day,$month,$year) = ($d[0],$d[1],$d[2],$d[4],$m{$d[5]},$d[6]); #print "<!-- $hour.$min.$sec.$day.$month.$year -->\n"; my $test_t = timegm($sec,$min,$hour,$day,$month,$year); my $age = time-$test_t; my $age_days = $age/(60*60*24); #print "<!-- $age_days days old -->\n"; my $age_html = "<font>"; if ($age_days <= 2) { } elsif ($age_days <= 14) { $age_html = "<font color=\"#FF9900\">"; } else { $age_html = "<font color=\"#FF0000\">"; } return $age_html.$_[0]."</font>"; } # Generate an age string based on the run date. # Use as: age_info(run-date-html) # sub age_info { my %m = ('January',0,'February',1,'March',2,'April',3,'May',4,'June',5, 'July',6,'August',7,'September',8,'October',9,'November',10,'December',11); my @d = split(/ |:/,$_[0]); my ($hour,$min,$sec,$day,$month,$year) = ($d[0],$d[1],$d[2],$d[4],$m{$d[5]},$d[6]); #print "<!-- $hour.$min.$sec.$day.$month.$year -->\n"; my $test_t = timegm($sec,$min,$hour,$day,$month,$year); my $age = time-$test_t; my $age_days = $age/(60*60*24); #print "<!-- $age_days days old -->\n"; my $age_html = "<font>"; if ($age_days <= 2) { } elsif ($age_days <= 14) { $age_html = "<font color=\"#FF9900\">"; } else { $age_html = "<font color=\"#FF0000\">"; } if ($age_days <= 1) { $age_html = $age_html."today"; } elsif ($age_days <= 2) { $age_html = $age_html."yesterday"; } elsif ($age_days < 14) { my $days = int $age_days; $age_html = $age_html.$days." days"; } elsif ($age_days < 7*8) { my $weeks = int $age_days/7; $age_html = $age_html.$weeks." weeks"; } else { my $months = int $age_days/28; $age_html = $age_html.$months." months"; } return $age_html."</font>"; } #~ foreach my $k (sort keys %ENV) #~ { #~ print "<!-- $k = $ENV{$k} -->\n"; #~ } my $logdir = "$ENV{PWD}"; #~ my $logdir = "C:\\CVSROOTs\\Boost\\boost\\status"; opendir LOGS, "$logdir"; my @logs = grep /.*links[^.]*\.html$/, readdir LOGS; closedir LOGS; my @bgcolor = ( "bgcolor=\"#EEEEFF\"", "" ); my $row = 0; print "<table>\n"; print "<tr>\n", "<th align=\"left\" bgcolor=\"#DDDDDD\">Platform</th>\n", "<th align=\"left\" bgcolor=\"#DDDDDD\">Run Date</th>\n", "<th align=\"left\" bgcolor=\"#DDDDDD\">Age</th>\n", "<th align=\"left\" bgcolor=\"#DDDDDD\">Compilers</th>\n", "<th align=\"left\" bgcolor=\"#DDDDDD\">Pass</th>\n", "<th align=\"left\" bgcolor=\"#DDDDDD\">Fail</th>\n", "</tr>\n"; foreach $l (sort { lc($a) cmp lc($b) } @logs) { my $log = $l; $log =~ s/-links//s; my ($spec) = ($log =~ /cs-([^\.]+)/); my $fh = new FileHandle; if ($fh->open("<$logdir/$log")) { my $content = join('',$fh->getlines()); $fh->close; my ($status) = ($content =~ /(<h1>Compiler(.(?!<\/td>))+.)/si); my ($platform) = ($status =~ /Status: ([^<]+)/si); my ($run_date) = ($status =~ /Date:<\/b> ([^<]+)/si); $run_date =~ s/, /<br>/g; my ($compilers) = ($content =~ /Test Type<\/a><\/t[dh]>((.(?!<\/tr>))+.)/si); if ($compilers eq "") { next; } $compilers =~ s/-<br>//g; $compilers =~ s/<\/td>//g; my @compiler = ($compilers =~ /<td>(.*)$/gim); my $count = @compiler; my @results = ($content =~ /(>Pass<|>Warn<|>Fail<|>Missing<)/gi); my $test_count = (scalar @results)/$count; my @pass = map { 0 } (1..$count); my @warn = map { 0 } (1..$count); my @fail = map { 0 } (1..$count); my @missing = map { 0 } (1..$count); my @total = map { 0 } (1..$count); #~ print "<!-- ", #~ "pass = ",join(',',@pass)," ", #~ "warn = ",join(',',@warn)," ", #~ "fail = ",join(',',@fail)," ", #~ "missing = ",join(',',@missing)," ", #~ "total = ",join(',',@total)," ", #~ " -->\n"; for my $t (1..$test_count) { my $r0 = (($t-1)*$count); my $r1 = (($t-1)*$count+$count-1); my @r = @results[(($t-1)*$count)..(($t-1)*$count+$count-1)]; #~ print "<!-- ", #~ "result = ",join(',',@r)," ", #~ "range = ",$r0,"..",$r1," (",(scalar @results),")", #~ " -->\n"; for my $c (1..$count) { if ($r[$c-1] =~ /Pass/i) { ++$pass[$c-1]; } elsif ($r[$c-1] =~ /Warn/i) { ++$warn[$c-1]; } elsif ($r[$c-1] =~ /Fail/i) { ++$fail[$c-1]; } elsif ($r[$c-1] =~ /Missing/i) { ++$missing[$c-1]; } ++$total[$c-1]; } } #~ print "<!-- ", #~ "pass = ",join(',',@pass)," ", #~ "warn = ",join(',',@warn)," ", #~ "fail = ",join(',',@fail)," ", #~ "missing = ",join(',',@missing)," ", #~ "total = ",join(',',@total)," ", #~ " -->\n"; for my $comp (1..(scalar @compiler)) { my @lines = split(/<br>/,$compiler[$comp-1]); if (@lines > 2) { $compiler[$comp-1] = join(' ',@lines[0..(scalar @lines)-2])."<br>".$lines[(scalar @lines)-1]; } } print "<tr>\n", "<td rowspan=\"$count\" valign=\"top\"><font size=\"+1\">$platform</font><br>(<a href=\"./$log\">$spec</a>)</td>\n", "<td rowspan=\"$count\" valign=\"top\">",$run_date,"</td>\n", "<td rowspan=\"$count\" valign=\"top\">",age_info($run_date),"</td>\n", "<td valign=\"top\" ",$bgcolor[$row],">",$compiler[0],"</td>\n", "<td valign=\"top\" ",$bgcolor[$row],">",result_info_pass("#000000",$pass[0],$warn[0],$fail[0],$missing[0]),"</td>\n", "<td valign=\"top\" ",$bgcolor[$row],">",result_info_fail("#FF0000",$pass[0],$warn[0],$fail[0],$missing[0]),"</td>\n", "</tr>\n"; $row = ($row+1)%2; foreach my $c (1..($count-1)) { print "<tr>\n", "<td valign=\"top\" ",$bgcolor[$row],">",$compiler[$c],"</td>\n", "<td valign=\"top\" ",$bgcolor[$row],">",result_info_pass("#000000",$pass[$c],$warn[$c],$fail[$c],$missing[$c]),"</td>\n", "<td valign=\"top\" ",$bgcolor[$row],">",result_info_fail("#FF0000",$pass[$c],$warn[$c],$fail[$c],$missing[$c]),"</td>\n", "</tr>\n"; $row = ($row+1)%2; } print "<tr>\n", "<td colspan=\"7\"><hr size=\"1\" noshade></td>\n", "</tr>\n"; } } print "</table>\n";
flingone/frameworks_base_cmds_remoted
libs/boost/tools/regression/src/regression-logs.pl
Perl
apache-2.0
8,172
#!/usr/bin/perl # ******************************************************************** # * COPYRIGHT: # * Copyright (c) 2002-2008, International Business Machines Corporation and # * others. All Rights Reserved. # ******************************************************************** # Script to generate the icudata.jar and testdata.jar files. This file is # part of icu4j. It is checked into CVS. It is generated from # locale data in the icu4c project. See usage() notes (below) # for more information. # This script requires perl. For Win32, I recommend www.activestate.com. # Ram Viswanadha # copied heavily from genrbjar.pl # # 6/25/08 - Modified to better handle cygwin paths - Brian Rower # use File::Find; use File::Basename; use IO::File; use Cwd; use File::Copy; use Getopt::Long; use File::Path; use File::Copy; use Cwd; use Cwd 'abs_path'; main(); #------------------------------------------------------------------ sub main(){ GetOptions( "--icu-root=s" => \$icuRootDir, "--jar=s" => \$jarDir, "--icu4j-root=s" => \$icu4jDir, "--version=s" => \$version, "--verbose" => \$verbose, "--help" => \$help ); $cwd = abs_path(getcwd); if($help){ usage(); } unless (defined $icuRootDir){ $icuRootDir =abs_path($cwd."/../../.."); } unless (defined $icu4jDir){ $icu4jDir =abs_path($icuRootDir."/../icu4j"); } unless (defined $jarDir){ if(defined $ENV{'JAVA_HOME'}){ $jarDir=$ENV{'JAVA_HOME'}."/bin"; }else{ print("ERROR: JAVA_HOME enviroment variable undefined and --jar argument not specifed.\n"); usage(); } } $platform = getPlatform(); $icuBinDir = $icuRootDir; $path=$ENV{'PATH'}; if(($platform eq "cygwin") || ($platform eq "linux")){ $icuBinDir .= "/source/bin"; $icuLibDir = abs_path($icuBinDir."/../lib"); $path .=":$icuBinDir:$icuLibDir"; $libpath = $ENV{'LD_LIBRARY_PATH'}.":$icuLibDir"; $ENV{'LD_LIBRARY_PATH'} = $libpath; #print ("##### LD_LIBRARY_PATH = $ENV{'LD_LIBRARY_PATH'}\n"); }elsif($platform eq "aix"){ $icuBinDir .= "/source/bin"; $icuLibDir = abs_path($icuBinDir."/../lib"); $path .=":$icuBinDir:$icuLibDir"; $libpath = $ENV{'LIBPATH'}.":$icuLibDir"; $ENV{'LIBPATH'} = $libpath; #print ("##### LIBPATH = $ENV{'LIBPATH'}\n"); }elsif($platform eq "darwin"){ $icuBinDir .= "/source/bin"; $icuLibDir = abs_path($icuBinDir."/../lib"); $path .=":$icuBinDir:$icuLibDir"; $libpath = $ENV{'DYLD_LIBRARY_PATH'}.":$icuLibDir"; $ENV{'DYLD_LIBRARY_PATH'} = $libpath; }elsif($platform eq "MSWin32"){ $icuBinDir =$icuRootDir."/bin"; $path .=$icuBinDir; } $ENV{'PATH'} = $path; #print ("##### PATH = $ENV{'PATH'}\n"); # TODO add more platforms and test on Linux and Unix $icuBuildDir =$icuRootDir."/source/data/out/build"; $icuTestDataSrcDir =$icuRootDir."/source/test/testdata/"; $icuTestDataDir =$icuRootDir."/source/test/testdata/out/build/"; # now build ICU buildICU($platform, $icuRootDir, $icuTestDataDir, $verbose); #figure out the version and endianess unless (defined $version){ ($version, $endian) = getVersion(); #print "#################### $version, $endian ######\n"; } $icupkg = $icuBinDir."/icupkg -tb"; $tempDir = $cwd."/temp"; $version =~ s/\.//; $icu4jImpl = "com/ibm/icu/impl/data/"; $icu4jDataDir = $icu4jImpl."icudt".$version."b"; $icu4jDevDataDir = "com/ibm/icu/dev/data/"; $icu4jTestDataDir = "$icu4jDevDataDir/testdata"; $icuDataDir =$icuBuildDir."/icudt".$version.checkPlatformEndianess(); #remove the stale directories unlink($tempDir); convertData($icuDataDir, $icupkg, $tempDir, $icu4jDataDir, $verbose); #convertData($icuDataDir."/coll/", $icupkg, $tempDir, $icu4jDataDir."/coll"); createJar("\"$jarDir/jar\"", "icudata.jar", $tempDir, $icu4jDataDir, $verbose); convertTestData($icuTestDataDir, $icupkg, $tempDir, $icu4jTestDataDir, $verbose); createJar("\"$jarDir/jar\"", "testdata.jar", $tempDir, $icu4jTestDataDir, $verbose); copyData($icu4jDir, $icu4jImpl, $icu4jDevDataDir, $tempDir, $verbose); } #----------------------------------------------------------------------- sub buildICU{ local($platform, $icuRootDir, $icuTestDataDir, $verbose) = @_; $icuSrcDir = $icuRootDir."/source"; $icuSrcDataDir = $icuSrcDir."/data"; chdir($icuSrcDir); # clean the data directories unlink($icuBuildDir."../"); unlink($icuTestDataDir."../"); if(($platform eq "cygwin")||($platform eq "darwin")||($platform eq "linux")){ # make all in ICU cmd("make all", $verbose); chdir($icuSrcDataDir); cmd("make uni-core-data", $verbose); if(chdir($icuTestDataSrcDir)){ print("Invoking make in directory $icuTestDataSrcDir\n"); cmd("make JAVA_OUT_DIR=\"$icu4jDir/src/com/ibm/icu/dev/test/util/\" all java-output", $verbose); }else{ die "Could not cd to $icuTestDataSrcDir\n"; } }elsif($platform eq "aix"){ # make all in ICU cmd("gmake all", $verbose); chdir($icuSrcDataDir); cmd("gmake uni-core-data", $verbose); chdir($icuTestDataDir."../../"); cmd("gmake JAVA_OUT_DIR=\"$icu4jDir/src/com/ibm/icu/dev/test/util/\" all java-output", $verbose); }elsif($platform eq "MSWin32"){ #devenv.com $projectFileName \/build $configurationName > \"$cLogFile\" 2>&1 cmd("devenv.com allinone/allinone.sln /useenv /build Debug", $verbose); # build required data. this is required coz building icu will not build all the data chdir($icuSrcDataDir); cmd("NMAKE /f makedata.mak ICUMAKE=\"$icuSrcDataDir\" CFG=debug uni-core-data", $verbose); print "WARNING: Don't know how to build java-output on $platform. \n"; }else{ print "ERROR: Could not build ICU unknown platform $platform. \n"; exit(-1); } chdir($cwd); } #----------------------------------------------------------------------- sub getVersion{ my @list; opendir(DIR,$icuBuildDir); @list = readdir(DIR); closedir(DIR); if(scalar(@list)>3){ print("ERROR: More than 1 directory in build. Can't decide the version"); exit(-1); } foreach $item (@list){ next if($item eq "." || $item eq ".."); my ($ver, $end) =$item =~ m/icudt(.*)(l|b|e)$/; return $ver,$end; } } #----------------------------------------------------------------------- sub getPlatform{ $platform = $^O; return $platform; } #----------------------------------------------------------------------- sub createJar{ local($jar, $jarFile, $tempDir, $dirToJar, $verbose) = @_; chdir($tempDir); $command=""; print "INFO: Creating $jarFile\n"; if($platform eq "cygwin") { #make sure the given path is a cygwin path not a windows path $jar = `cygpath -au $jar`; chop($jar); #added by Brian Rower 6/25/08 #The following code deals with spaces in the path if(index($jar, "/ ") > 0) { $jar =~ s/[\/]\s/\\ /g; } elsif(index($jar, " ") > 0) { $jar =~ s/\s/\\ /g; } $tempDir = `cygpath -aw $tempDir`; chop($tempDir); $tempDir =~ s/\\/\\\\/g; } if(defined $verbose){ $command = "$jar cvf $jarFile -C $tempDir $dirToJar"; }else{ $command = "$jar cf $jarFile -C $tempDir $dirToJar"; } cmd($command, $verbose); } #----------------------------------------------------------------------- sub checkPlatformEndianess { my $is_big_endian = unpack("h*", pack("s", 1)) =~ /01/; if ($is_big_endian) { return "b"; }else{ return "l"; } } #----------------------------------------------------------------------- sub copyData{ local($icu4jDir, $icu4jImpl, $icu4jDevDataDir, $tempDir) =@_; print("INFO: Copying $tempDir/icudata.jar to $icu4jDir/src/$icu4jImpl\n"); mkpath("$icu4jDir/src/$icu4jImpl"); copy("$tempDir/icudata.jar", "$icu4jDir/src/$icu4jImpl"); print("INFO: Copying $tempDir/testdata.jar $icu4jDir/src/$icu4jDevDataDir\n"); mkpath("$icu4jDir/src/$icu4jDevDataDir"); copy("$tempDir/testdata.jar","$icu4jDir/src/$icu4jDevDataDir"); } #----------------------------------------------------------------------- sub convertData{ local($icuDataDir, $icupkg, $tempDir, $icu4jDataDir) =@_; my $dir = $tempDir."/".$icu4jDataDir; # create the temp directory mkpath($dir) ; # cd to the temp directory chdir($tempDir); my $endian = checkPlatformEndianess(); my @list; opendir(DIR,$icuDataDir); #print $icuDataDir; @list = readdir(DIR); closedir(DIR); my $op = $icupkg; #print "####### $endian ############\n"; if($endian eq "l"){ print "INFO: {Command: $op $icuDataDir/*.*}\n"; }else{ print "INFO: {Command: copy($icuDataDir/*.*, $tempDir/$icu4jDataDir/*)}\n"; } $i=0; # now convert foreach $item (@list){ next if($item eq "." || $item eq ".."); # next if($item =~ /^t_.*$\.res/ ||$item =~ /^translit_.*$\.res/ || # $item=~/$\.crs/ || $item=~ /$\.txt/ || # $item=~/icudata\.res/ || $item=~/$\.exp/ || $item=~/$\.lib/ || # $item=~/$\.obj/ || $item=~/$\.lst/); next if($item =~ /^t_.*$\.res/ ||$item =~ /^translit_.*$\.res/ || $item=~/$\.crs/ || $item=~ /$\.txt/ || $item=~/icudata\.res/ || $item=~/$\.exp/ || $item=~/$\.lib/ || $item=~/$\.obj/ || $item=~/$\.lst/); if(-d "$icuDataDir/$item"){ convertData("$icuDataDir/$item/", $icupkg, $tempDir, "$icu4jDataDir/$item/"); next; } if($endian eq "l"){ $command = $icupkg." $icuDataDir/$item $tempDir/$icu4jDataDir/$item"; cmd($command, $verbose); }else{ $rc = copy("$icuDataDir/$item", "$tempDir/$icu4jDataDir/$item"); if($rc==1){ #die "ERROR: Could not copy $icuDataDir/$item to $tempDir/$icu4jDataDir/$item, $!"; } } } chdir(".."); print "INFO: DONE\n"; } #----------------------------------------------------------------------- sub convertTestData{ local($icuDataDir, $icupkg, $tempDir, $icu4jDataDir) =@_; my $dir = $tempDir."/".$icu4jDataDir; # create the temp directory mkpath($dir); # cd to the temp directory chdir($tempDir); my $op = $icupkg; print "INFO: {Command: $op $icuDataDir/*.*}\n"; my @list; opendir(DIR,$icuDataDir) or die "ERROR: Could not open the $icuDataDir directory for reading $!"; #print $icuDataDir; @list = readdir(DIR); closedir(DIR); my $endian = checkPlatformEndianess(); $i=0; # now convert foreach $item (@list){ next if($item eq "." || $item eq ".."); next if( item=~/$\.crs/ || $item=~ /$\.txt/ || $item=~/$\.exp/ || $item=~/$\.lib/ || $item=~/$\.obj/ || $item=~/$\.mak/ || $item=~/test\.icu/ || $item=~/$\.lst/); $file = $item; $file =~ s/testdata_//g; if($endian eq "l"){ $command = "$icupkg $icuDataDir/$item $tempDir/$icu4jDataDir/$file"; cmd($command, $verbose); }else{ #print("Copying $icuDataDir/$item $tempDir/$icu4jDataDir/$file\n"); copy("$icuDataDir/$item", "$tempDir/$icu4jDataDir/$file"); } } chdir(".."); print "INFO: DONE\n"; } #------------------------------------------------------------------------------------------------ sub cmd { my $cmd = shift; my $verbose = shift; my $prompt = shift; $prompt = "Command: $cmd.." unless ($prompt); if(defined $verbose){ print $prompt."\n"; } system($cmd); my $exit_value = $? >> 8; #my $signal_num = $? & 127; #my $dumped_core = $? & 128; if ($exit_value == 0) { if(defined $verbose){ print "ok\n"; } } else { ++$errCount; print "ERROR: Execution of $prompt returned ($exit_value)\n"; exit(1); } } #----------------------------------------------------------------------- sub usage { print << "END"; Usage: gendtjar.pl Options: --icu-root=<directory where icu4c lives> --jar=<directory where jar.exe lives> --icu4j-root=<directory> --version=<ICU4C version> --verbose --help e.g: gendtjar.pl --icu-root=\\work\\icu --jar=\\jdk1.4.1\\bin --icu4j-root=\\work\\icu4j --version=3.0 END exit(0); }
ckelsel/chromium-4.0.210.0_p26329
third_party/icu/source/tools/genrb/gendtjar.pl
Perl
apache-2.0
12,986
=pod =head1 NAME EVP_SIGNATURE-ED25519, EVP_SIGNATURE-ED448, Ed25519, Ed448 - EVP_PKEY Ed25519 and Ed448 support =head1 DESCRIPTION The B<Ed25519> and B<Ed448> EVP_PKEY implementation supports key generation, one-shot digest sign and digest verify using PureEdDSA and B<Ed25519> or B<Ed448> (see RFC8032). It has associated private and public key formats compatible with RFC 8410. =head2 ED25519 and ED448 Signature Parameters No additional parameters can be set during one-shot signing or verification. In particular, because PureEdDSA is used, a digest must B<NOT> be specified when signing or verifying. See L<EVP_PKEY-X25519(7)> for information related to B<X25519> and B<X448> keys. The following signature parameters can be retrieved using EVP_PKEY_CTX_get_params(). =over 4 =item "algorithm-id" (B<OSSL_SIGNATURE_PARAM_ALGORITHM_ID>) <octet string> The parameters are described in L<provider-signature(7)>. =back =head1 NOTES The PureEdDSA algorithm does not support the streaming mechanism of other signature algorithms using, for example, EVP_DigestUpdate(). The message to sign or verify must be passed using the one-shot EVP_DigestSign() and EVP_DigestVerify() functions. When calling EVP_DigestSignInit() or EVP_DigestVerifyInit(), the digest I<type> parameter B<MUST> be set to NULL. Applications wishing to sign certificates (or other structures such as CRLs or certificate requests) using Ed25519 or Ed448 can either use X509_sign() or X509_sign_ctx() in the usual way. Ed25519 or Ed448 private keys can be set directly using L<EVP_PKEY_new_raw_private_key(3)> or loaded from a PKCS#8 private key file using L<PEM_read_bio_PrivateKey(3)> (or similar function). Completely new keys can also be generated (see the example below). Setting a private key also sets the associated public key. Ed25519 or Ed448 public keys can be set directly using L<EVP_PKEY_new_raw_public_key(3)> or loaded from a SubjectPublicKeyInfo structure in a PEM file using L<PEM_read_bio_PUBKEY(3)> (or similar function). Ed25519 and Ed448 can be tested with the L<openssl-speed(1)> application since version 1.1.1. Valid algorithm names are B<ed25519>, B<ed448> and B<eddsa>. If B<eddsa> is specified, then both Ed25519 and Ed448 are benchmarked. =head1 EXAMPLES To sign a message using a ED25519 or ED448 key: void do_sign(EVP_PKEY *ed_key, unsigned char *msg, size_t msg_len) { size_t sig_len; unsigned char *sig = NULL; EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); EVP_DigestSignInit(md_ctx, NULL, NULL, NULL, ed_key); /* Calculate the requires size for the signature by passing a NULL buffer */ EVP_DigestSign(md_ctx, NULL, &sig_len, msg, msg_len); sig = OPENSSL_zalloc(sig_len); EVP_DigestSign(md_ctx, sig, &sig_len, msg, msg_len); ... OPENSSL_free(sig); EVP_MD_CTX_free(md_ctx); } =head1 SEE ALSO L<EVP_PKEY-X25519(7)> L<provider-signature(7)>, L<EVP_DigestSignInit(3)>, L<EVP_DigestVerifyInit(3)>, =head1 COPYRIGHT Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
jens-maus/amissl
openssl/doc/man7/EVP_SIGNATURE-ED25519.pod
Perl
bsd-3-clause
3,352
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by 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'; 0180 024F END
liuyangning/WX_web
xampp/perl/lib/unicore/lib/Blk/LatinEx2.pl
Perl
mit
421
% ---------------------------------------------------------------------- % 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) 1989-2006 Cisco Systems, Inc. All Rights Reserved. % % Contributor(s): ECRC GmbH % % END LICENSE BLOCK % % System: ECLiPSe Constraint Logic Programming System % Version: $Id: paddy.pl,v 1.2 2008/08/04 10:28:36 jschimpf Exp $ % ---------------------------------------------------------------------- % The PADDY system. % PUT BINDING PROPAGATION IN POST-TRANSFORMATION! :- module(paddy). :- pragma(deprecated_warnings(off)). :- pragma(undeclared_warnings(off)). :- pragma(nowarnings). % lots of singleton variables in this file! :- local (help)/0. :- local variable(bounds), variable(index), variable(clause_id), variable(source_files), variable(progsize), variable(temp), variable(many_patterns), variable(name_count), variable(prune), variable(pattern_count), variable(pointer), variable(predicate_size), variable(pattern_number), variable(term_depth). :- import term_size/2, current_array_body/3, setval_body/3, getval_body/3, make_local_array_body/2, erase_array_body/2 from sepia_kernel. :- export pin/1, p/0, p/1, p/2, pout/1, pout/0, term_depth/1, pattern_number/1, bounds/1. :- dynamic temp_side/1, temp_prop/1, temp_head_pred/1, temp_delay_pred/1, temp_op/3, temp_dynamic_pred/1, temp_pd_predicate/1, temp_parallel_pred/1, deprolog_module/2, deprolog_file/1. array_size(F,N,T) :- functor(Old, F, 1), (current_array(Old,_) -> erase_array(F/1) ; true), X=..[F,N], make_local_array(X,T). bounds :- setval(progsize,0), getval(bounds,N), array_size(prune,N,byte), array_size(auxdef,N,byte), array_size(transformed,N,byte), array_size(recursive,N,byte), array_size(side,N,byte), array_size(prop,N,byte), array_size(clau,N,prolog), array_size(prog,N,prolog), array_size(proc,N,prolog). :- set_flag(print_depth,100), set_stream(divert,output), set_stream(log_output,null), ensure_loaded(library(lists)), set_stream(log_output,output), setval(term_depth,5), setval(pattern_number,100), setval(predicate_size,2000), setval(bounds,2000), bounds. pattern_number(N) :- getval(pattern_number,N1), setval(pattern_number,N), write(" pattern_number changed from "), write(N1), write(" to "), writeln(N). term_depth(N) :- getval(term_depth,N1), setval(term_depth,N), write(" term_depth changed from "), write(N1), write(" to "), writeln(N). pin(In) :- deprolog(In), static_analysis. p :- partial_deduction. pout :- write_relevant_clauses. pout(Out) :- write_relevant_clauses(Out). p(In) :- pin(In), partial_deduction, write_relevant_clauses. p(In,Out) :- pin(In), partial_deduction, write_relevant_clauses(Out). write_relevant_clauses(Out) :- divert(Out), writeclause(divert,(?-((current_predicate(get_cut/1) -> true ; import get_cut/1 from sepia_kernel)))), writeclause(divert,(?-((current_predicate(cut_to/1) -> true ; import cut_to/1 from sepia_kernel)))), getval(source_files,SF), pathnames(SF,SF1), writeclause(divert,(?-SF1)), write_relevant_clauses, undivert. pathnames([],[]). pathnames([F|L],[F1|L1]) :- name_string(F,Fc), (substring(Fc,"/",1) -> F1=F, pathnames(L,L1) ; get_flag(cwd,X), append_strings(X,Fc,F1), pathnames(L,L1)). name_string(A,B) :- atom(A) -> atom_string(A,B) ; B=A. write_relevant_clauses :- not (relevant_pred(F,A,L), nl(divert), rmember(I,L), getval(clau(I),(H,T)), not writeclause(divert,(H:-T))). bounds(N) :- getval(bounds,N1), setval(bounds,N), bounds, write(" Bounds changed from "), write(N1), write(" to "), writeln(N). % Preprocessor (deprolog) for PADDY. deprolog(In) :- deprolog_initialise, compile_term(cut_pred('0','0')), start_compile_stream(cut), clear_table(cut_table), clear_table(head_table), read_pd_file(In), clear_table(head_table), clear_table(cut_table), end_compile_stream(cut), make_static(temp_dynamic_pred(P),dynamic_pred(P)), make_static(temp_delay_pred(P),delay_pred(P)), make_static(temp_parallel_pred(P),parallel_pred(P)), drop_ops, add_cut_args, make_static(temp_head_pred(X),head_pred(X)), store_prog. deprolog_initialise :- retract_all(temp_head_pred(_)), retract_all(deprolog_module(_,_)), retract_all(temp_dynamic_pred(_)), retract_all(temp_pd_predicate(_)), retract_all(temp_parallel_pred(_)), clear_table(index_table), setval(clause_id,0), setval(index,0), retract_all(temp_delay_pred(_)), retract_all(temp_op(_,_,_)), retract_all(deprolog_file(_)). read_pd_file(In) :- exists(In) -> open(In,read,S), read(S,X), ((X=(?-L); X=(:-L)) -> setval(source_files,L), read_prolog(L), read_pd_clauses(S), close(S), make_static(temp_pd_predicate(P),pd_predicate(P)) ; write(" PADDY ERROR: file "), write(In), writeln(" must begin with `:-[..]'"), abort) ; write(" PADDY ERROR: query file "), write(In), writeln(" does not exist"), abort. read_pd_clauses(S) :- read(S,X), (X==end_of_file -> true ;X=(H:-T), functor(H,F,A), concat_atom([F,'_',A],FA) -> (table_entry(FA,head_table) -> write(" PADDY ERROR: "), write(F/A), writeln(" already occurred in the program"), abort ; true), (temp_pd_predicate(H) -> write(" PADDY ERROR: "), write(F/A), writeln(" has more than one clause"), abort ; true), (pure_conjunction(T) -> true ; writeln(" PADDY ERROR: "), writeclause((H:-T)), writeln(" is not a valid query clause"), abort), incval(index), getval(index,Ind), check_bounds(Ind), setval(proc(Ind),[]), predicate_key(H,Hk), write_table(Hk,Ind,index_table), addclause(Ind,(H:-T)), functor(G,F,A), assert(temp_pd_predicate(G)), assert(temp_head_pred(G)), write_table(FA,'0',head_table), read_pd_clauses(S) ; writeln(" PADDY ERROR: "), writeclause(X), writeln(" is not a valid query clause"), abort). pure_conjunction((A,B)) :- !, pure_conjunction(A), pure_conjunction(B). pure_conjunction(A) :- A\=(_;_), A\=(not _), A\=once(_), A\=(_->_), A\==!. read_prolog([]) :- !. read_prolog([H|T]) :- !, read_prolog(H), read_prolog(T). read_prolog(F) :- exists(F), !, write(" Enter file "), writeln(F), asserta(deprolog_file(F)), open(F,read,S), read_prolog_clause(S), close(S), retract(deprolog_file(F)), write(" Exit file "), writeln(F). read_prolog(F) :- term_string(F,FS), append_strings(FS,".pl",FSPL), exists(FSPL), !, write(" Reading "), writeln(FSPL), asserta(deprolog_file(F)), open(FSPL,read,S), read_prolog_clause(S), close(S), retract(deprolog_file(F)), write(" Exit file "), writeln(F). read_prolog(F) :- write(" PADDY warning: could not find file "), writeln(F). read_prolog_clause(S) :- read(S,X), (X==end_of_file -> deprolog_file(F), (retract(deprolog_module(M,F)) -> write(" Skipped module "), writeln(M) ; true) ; prolog_clause_analyse(X), read_prolog_clause(S)). prolog_clause_analyse((:-X)) :- !, dec_process((?-X)). prolog_clause_analyse((?-X)) :- !, dec_process((?-X)). prolog_clause_analyse((delay P if C)) :- !, assert(temp_delay_pred(P)). % DUPS? prolog_clause_analyse(_) :- deprolog_module(_,_), !. prolog_clause_analyse((H:-T)) :- !, prolog_clause_process(H,T). prolog_clause_analyse(X) :- prolog_clause_process(X,true). dec_process((?-A,B)) :- not (varof(V,A), occurs(V,B)), !, dec_process((?-A)), dec_process((?-B)). dec_process((?-compile(F))) :- !, (nonvar(F), exists(F) -> read_prolog(F) ;nonvar(F), term_string(F,FS), append_strings(FS,".pl",FSPL), exists(FSPL) -> read_prolog(FSPL) ; write(" PADDY warning: could not find file "), writeln(F)). dec_process((?-[A,B|T])) :- !, dec_process((?-compile(A))), dec_process((?-[B|T])). dec_process((?-[A])) :- !, dec_process((?-compile(A))). dec_process((?-op(P,A,N))) :- !, assert(temp_op(P,A,N)), op(P,A,N). dec_process((?-local_op(P,A,N))) :- !, assert(temp_op(P,A,N)), op(P,A,N). dec_process((?-global_op(P,A,N))) :- !, assert(temp_op(P,A,N)), op(P,A,N). dec_process((?-dynamic Spec)) :- !, not (extract_atom(F/A,Spec), functor(P,F,A), not assert(temp_dynamic_pred(P))). dec_process((?-parallel Spec)) :- !, not (extract_atom(F/A,Spec), functor(P,F,A), not assert(temp_parallel_pred(P))). dec_process((?-module(M))) :- !, deprolog_file(F), (retract(deprolog_module(M1,F)) -> write(" Skipped module "), writeln(M1) ; true), asserta(deprolog_module(M,F)), write(" Skipping module "), writeln(M). dec_process((?-G)). prolog_clause_process(H,T) :- functor(H,HF,HA), concat_atom([HF,'_',HA],FA), (table_entry(FA,head_table) -> true ; functor(H1,HF,HA), assert(temp_head_pred(H1)), write_table(FA,'0',head_table)), prolog_body_process(HF/HA,T,T1), predicate_key(H,Hk), (read_table(Hk,Ind,index_table) -> addclause(Ind,(H:-T1)) ; incval(index), getval(index,Ind), check_bounds(Ind), setval(proc(Ind),[]), write_table(Hk,Ind,index_table), addclause(Ind,(H:-T1))). prolog_body_process(_,G,P) :- var(G), !, P=call(G). prolog_body_process(HF/HA,call(A),P) :- !, prolog_body_process(HF/HA,A,P). prolog_body_process(HF/HA,(A->B;C),P) :- !, cond_process(HF/HA,(A->B;C),K,D), prolog_body_process(HF/HA,(get_cut(K),D),P). prolog_body_process(HF/HA,(A->B),P) :- !, cond_process(HF/HA,(A->B),K,D), prolog_body_process(HF/HA,(get_cut(K),D),P). prolog_body_process(HF/HA,(A;B),(C;D)) :- !, prolog_body_process(HF/HA,A,C), prolog_body_process(HF/HA,B,D). prolog_body_process(HF/HA,(A,B),(C,D)) :- !, prolog_body_process(HF/HA,A,C), prolog_body_process(HF/HA,B,D). prolog_body_process(HF/HA,(not A),P) :- !, prolog_body_process(HF/HA,(get_cut(C),(A,cut_to(C),fail;true)),P). prolog_body_process(HF/HA,once(A),P) :- !, prolog_body_process(HF/HA,(get_cut(C),A,cut_to(C)),P). prolog_body_process(HF/HA,!,!) :- !, concat_atom([HF,'_',HA],FA), (table_entry(FA,cut_table) -> true ; write_table(FA,'0',cut_table), stream_compile_term(cut,cut_pred(HF,HA))). prolog_body_process(HF/HA,(if A then B else C),(if D then E else F)) :- !, prolog_body_process(HF/HA,A,D), prolog_body_process(HF/HA,B,E), prolog_body_process(HF/HA,C,F). prolog_body_process(_,G,G). cond_process(HF/HA,X,K,X) :- var(X), !. cond_process(HF/HA,(A->B;C),K,(A,cut_to(K),B;Z)) :- !, cond_process(HF/HA,C,K,Z). cond_process(HF/HA,(A->B),K,(A,cut_to(K),B)) :- !. cond_process(HF/HA,!,K,!) :- !, concat_atom([HF,'_',HA],FA), (table_entry(FA,cut_table) -> true ; write_table(FA,'0',cut_table), stream_compile_term(cut,cut_pred(HF,HA))). cond_process(HF/HA,X,K,X). drop_ops :- not (retract(temp_op(P,A,N)), current_op(P,A,N), not abolish_op(N,A)). add_cut_args :- not (cut_pred(F,A), F/A\=='0'/'0', functor(G,F,A), not delay_pred(G), not dynamic_pred(G), not parallel_pred(G), not (incval(index), getval(index,IndC), G=..[F|Z], append(Z,[C],ZC), concat_atom([F,'_',cut],FC), GC=..[FC|ZC], assert(temp_head_pred(GC)), predicate_key(G,Gk), read_table(Gk,Ind,index_table), predicate_key(GC,GCk), write_table(GCk,IndC,index_table), getval(proc(Ind),L), setval(proc(IndC),L), setval(proc(Ind),[]), addclause(Ind,(G:-get_cut(C),GC)), add_cut_tos(L,FC))). add_cut_tos([],HF1). add_cut_tos([I|L],HF1) :- getval(clau(I),(H,T)), H=..[_|X], append(X,[C],X1), H1=..[HF1|X1], add_cut_tos_body(C,T,T1), setval(clau(I),(H1,T1)), add_cut_tos(L,HF1). add_cut_tos_body(C,(A,B),(X,Y)) :- !, add_cut_tos_body(C,A,X), add_cut_tos_body(C,B,Y). add_cut_tos_body(C,(A;B),(X;Y)) :- !, add_cut_tos_body(C,A,X), add_cut_tos_body(C,B,Y). add_cut_tos_body(C,!,cut_to(C)) :- !. add_cut_tos_body(C,T,T). store_prog :- setval(progsize,0), not (head_pred(P), predicate_key(P,Pk), read_table(Pk,Ind,index_table), getval(proc(Ind),L), rmember(I,L), getval(clau(I),(H,T)), incval(progsize), getval(progsize,PS), not setval(prog(PS),(H,T))). % Static Analyser for PADDY static_analysis :- static_initialise, setup_callgraph, setup_symbols, setup_body_preds, setup_side_preds, setup_prop_preds, setup_rec_analysis, make_name_table. make_name_table :- clear_table(name_table), not ((head_pred(G); body_pred(G), not head_pred(G)), functor(G,F,_), not write_table(F,'0',name_table)). static_initialise :- retract_all(temp_side(_)), retract_all(temp_prop(_)). setup_callgraph :- compile_term(calls('0','0')), start_compile_stream(comp), clear_table(call_table), not (head_pred(H), calls_atom(H,G), head_pred(G), functor(G,X,Y), functor(H,F,A), concat_atom([F,/,A,/,X,/,Y],FAXY), not table_entry(FAXY,call_table), not (stream_compile_term(comp,calls(F/A,X/Y)), write_table(FAXY,'0',call_table))), clear_table(call_table), end_compile_stream(comp). setup_symbols :- start_compile_stream(comp), clear_table(symbol_table), stream_compile_term(comp,symbol(true)), stream_compile_term(comp,symbol(_=_)), write_table('true/0','0',symbol_table), write_table('=/2','0',symbol_table), not (head_pred(H), predicate_key(H,Hk), read_table(Hk,Ind,index_table), getval(proc(Ind),L), member(I,L), getval(clau(I),C), extract_atom(A,C), not symbols(A)), clear_table(symbol_table), end_compile_stream(comp). symbols(T) :- var(T) -> true ;number(T) -> true ;string(T) -> true ; functor(T,F,A), concat_atom([F,'_',A],FA), (table_entry(FA,symbol_table) -> true ; functor(T1,F,A), stream_compile_term(comp,symbol(T1)), write_table(FA,'0',symbol_table)), symbols(A,T). symbols(N,T) :- N==0 -> true ; arg(N,T,X), symbols(X), M is N-1, symbols(M,T). setup_side_preds :- clear_table(side_table), not (head_pred(G), once((calls_atom(G,X), side_atom(X))), not (predicate_key(G,Gk), write_table(Gk,'0',side_table), assert(temp_side(G)))), propagate_side, make_static(temp_side(S),side(S)), clear_table(side_table). setup_prop_preds :- clear_table(prop_table), not (head_pred(G), once((calls_atom(G,X), prop_atom(X))), not (predicate_key(G,Gk), write_table(Gk,'0',prop_table), assert(temp_prop(G)))), propagate_prop, make_static(temp_prop(S),prop(S)), clear_table(prop_table). propagate_side :- setval(temp,no), not (temp_side(G), functor(G,F,A), calls(F1/A1,F/A), functor(X,F1,A1), concat_atom([F1,'_',A1],FA1), not table_entry(FA1,side_table), not (setval(temp,yes), write_table(FA1,'0',side_table), assert(temp_side(X)))), getval(temp,yes), !, propagate_side. propagate_side. propagate_prop :- setval(temp,no), not (temp_prop(G), functor(G,F,A), calls(F1/A1,F/A), functor(X,F1,A1), concat_atom([F1,'_',A1],FA1), not table_entry(FA1,prop_table), not (setval(temp,yes), write_table(FA1,'0',prop_table), assert(temp_prop(X)))), getval(temp,yes), !, propagate_prop. propagate_prop. calls_atom(G,X) :- predicate_key(G,Gk), read_table(Gk,Ind,index_table), getval(proc(Ind),L), rmember(Id,L), getval(clau(Id),(_,T)), extract_atom(X,T). side_atom(G) :- var(G), !. side_atom(call(X)) :- !, side_atom(X). side_atom(G) :- not head_pred(G), not open_no_side(G). prop_atom(G) :- var(G), !. prop_atom(call(X)) :- !, prop_atom(X). prop_atom(G) :- not head_pred(G), not open_no_prop(G). setup_body_preds :- start_compile_stream(body), clear_table(body_table), not (head_pred(P), not setup_body_pred(P)), clear_table(body_table), end_compile_stream(body). setup_body_pred(P) :- predicate_key(P,Pk), read_table(Pk,Ind,index_table), getval(proc(Ind),L), not (member(Id,L), getval(clau(Id),(_,T)), extract_atom(A,T), predicate_key(A,Ak), not setup_body_atom(A,Ak)). setup_body_atom(A,Ak) :- table_entry(Ak,body_table) -> true ; write_table(Ak,'0',body_table), functor(A,X,Y), functor(A1,X,Y), stream_compile_term(body,body_pred(A1)). setup_rec_analysis :- compile_term(non_recursive('0')), clear_table(nonrec_table), start_compile_stream(nonrec), not (head_pred(H), functor(H,F,A), not (calls(F/A,X/Y), functor(Z,X,Y), head_pred(Z)), not (stream_compile_term(nonrec,non_recursive(H)), concat_atom([F,'_',A],FA), write_table(FA,'0',nonrec_table))), propagate_nonrec, end_compile_stream(nonrec), clear_table(nonrec_table). propagate_nonrec :- setval(temp,no), not (head_pred(H), functor(H,F,A), concat_atom([F,'_',A],FA), not table_entry(FA,nonrec_table), not (calls(F/A,X/Y), concat_atom([X,'_',Y],XY), not table_entry(XY,nonrec_table)), not (setval(temp,yes), write_table(FA,'0',nonrec_table), stream_compile_term(nonrec,non_recursive(H)))), getval(temp,yes), !, propagate_nonrec. propagate_nonrec. % Partial deduction phase partial_deduction :- pd_initialise, cputime(T1), main_transformation, post_transformation, cputime(T2), T is T2-T1, write(" Transformation took "), write(T), writeln(" seconds"). % Initialisation pd_initialise :- clear_table(index_table), clear_table(defn_table), clear_table(aux_table), setval(many_patterns,false), setval(clause_id,0), setval(name_count,0), setval(index,0), setval(prune,0), setval(pattern_count,0), getval(progsize,S), setval(pointer,0), check_program_exists(S), pd_readclauses(S). check_program_exists(S) :- S==0 -> writeln(" PADDY ERROR: empty program"), abort ; true. pd_readclauses(S) :- incval(pointer), getval(pointer,P), (P>S -> true ; getval(prog(P),(H,T)), once(pd_clause_process(H,T)), pd_readclauses(S)). pd_clause_process(H,T) :- pd_body_process(T,T1), predicate_key(H,Hk), (read_table(Hk,Ind,index_table) -> addclause(Ind,(H:-T1)) ; incval(index), getval(index,Ind), check_bounds(Ind), setval(proc(Ind),[]), write_table(Hk,Ind,index_table), addclause(Ind,(H:-T1))). pd_body_process((A,B),(C,D)) :- !, pd_body_process(A,C), pd_body_process(B,D). pd_body_process((A;B),(C;D)) :- !, pd_body_process(A,C), pd_body_process(B,D). pd_body_process(call(A),call(A)) :- var(A), !. pd_body_process(call(A),P) :- !, pd_body_process(A,P). pd_body_process(G,G). % Transformation main_transformation :- not (pd_predicate(I), functor(I,F,A), write(" Goal "), writeln(F/A), predicate_key(I,Ik), read_table(Ik,II,index_table), getval(proc(II),[Id]), setval(proc(II),[]), getval(clau(Id),(I,G)), not transform(II,i,I,G)). transform(II,IU,I,G) :- setval(transformed(II),0), first_rest(G,F,R), unfold(II,IU,(I:-F,R),no_prune), fail ;set_properties(I,II). set_properties(I,Ind) :- setval(transformed(Ind),1), functor(I,F,A), getval(proc(Ind),L), recursive_class(L,F,A,Ind), improve_side_class(L,F,A,Ind), improve_prop_class(L,F,A,Ind). recursive_class(L,F,A,Ind) :- risky_recursion(F,A,L) -> setval(recursive(Ind),2) ;direct_recursion(L,F,A) -> setval(recursive(Ind),1) ; setval(recursive(Ind),0). risky_recursion(F,A,L) :- member(Id,L), getval(clau(Id),(_,T)), extract_atom(G,T), not functor(G,F,A), predicate_key(G,Gk), read_table(Gk,Ind,index_table), (getval(transformed(Ind),0); getval(recursive(Ind),2)). direct_recursion(L,F,A) :- member(Id,L), getval(clau(Id),(_,T)), extract_atom(G,T), functor(G,F,A). improve_side_class(L,F,A,Ind) :- getval(side(Ind),1), not (rmember(Id,L), getval(clau(Id),(_,G)), extract_atom(X,G), not functor(X,F,A), may_be_side(X)) -> setval(side(Ind),0) ; true. improve_prop_class(L,F,A,Ind) :- getval(prop(Ind),1), not (rmember(Id,L), getval(clau(Id),(_,G)), extract_atom(X,G), not functor(X,F,A), may_be_prop(X)) -> setval(prop(Ind),0) ; true. unfold(II,IU,(I:-F,R),Prune) :- F==true, R==true -> addclause(II,(I:-true)) ;head_pred(F), not dynamic_pred(F), not parallel_pred(F), not delay_pred(F) -> (IU==u, not non_recursive(F) -> make_fold(F,Ff,Indf), may_reunfold_def(Indf,Ff,R,F1,R1), unfold(II,u,(I:-F1,R1),no_prune) ; predicate_key(F,Fk), read_table(Fk,Ind,index_table), step(F,Ind,R,RF,RR,NewPrune), unfold(II,u,(I:-RF,RR),NewPrune)) ;F=call(G), nonvar(G) -> unfold(II,IU,(I:-G,R),Prune) ;executable_open(F) -> execute_open(F), first_rest(R,RF,RR), unfold(II,u,(I:-RF,RR),Prune) ;F=(F1;F2) -> (first_rest1(F1,R,Fd,Rd); first_rest1(F2,R,Fd,Rd)), unfold(II,IU,(I:-Fd,Rd),Prune) ;nonrecursive_auxdef(F,Ind) -> step(F,Ind,R,RF,RR,NewPrune), unfold(II,u,(I:-RF,RR),NewPrune) ; may_prune(F,Prune,I), new_aux(I1,R,I,F,Ind1), may_reunfold_aux(II,Ind1,I,F,I1). nonrecursive_auxdef(F,Ind) :- not head_pred(F), predicate_key(F,Fk), read_table(Fk,Ind,index_table), getval(transformed(Ind),1), getval(recursive(Ind),0). make_fold(F,Ff,Ind1) :- pattern_key(F,Sk), (read_table(Sk,[Ff1,F1,Ind,N1],defn_table) -> (instance(F,F1) -> Ff=Ff1, F=F1, Ind1=Ind ;term_size(F,N), N<N1 -> choose_fold(Sk,F,F,Ff,Ind1) ; generalise(F,F1,G), choose_fold(Sk,G,F,Ff,Ind1)) ; choose_fold(Sk,F,F,Ff,Ind1)). choose_fold(Sk,Fg,F,Fold,Ind) :- new_def(Fg,Sk,Foldg,Indg), transform(Indg,i,Foldg,Fg), (getval(recursive(Indg),0) -> Fold=Foldg, F=Fg, Ind=Indg ;read_table(Sk,[Foldr,Fr,Indr,_],defn_table), instance(F,Fr) -> Fold=Foldr, F=Fr, Ind=Indr ; Fold=Foldg, F=Fg, Ind=Indg). new_aux(I1,R,I,F,Ind) :- aux_key(R,Rk), (read_table(Rk,[I1,R1,Ind],aux_table), getval(transformed(Ind),1), variant(R,R1), R=R1, internal_check(R,I1,I+F) -> true ; newpred(I1,R,I+F), incval(index), getval(index,Ind), check_bounds(Ind), predicate_key(I1,I1k), write_table(I1k,Ind,index_table), setval(proc(Ind),[]), setval(auxdef(Ind),0), tentative_side_class(Ind,R), tentative_prop_class(Ind,R), write_table(Rk,[I1,R,Ind],aux_table), transform(Ind,u,I1,R)). aux_key(A,B) :- getval(term_depth,N), aux_key(A,C,N), (term_size(C,CS), getval(predicate_size,PS), CS>PS -> B='0' ; term_string(C,D), atom_string(B,D)). aux_key(((A,B),C),D,N) :- !, aux_key((A,B,C),D,N). aux_key((A,B),(C,D),N) :- !, sk(N,A,C), aux_key(B,D,N). aux_key(((A;B);C),D,N) :- !, aux_key((A;B;C),D,N). aux_key((A;B),(C;D),N) :- !, sk(N,A,C), aux_key(B,D,N). aux_key(A,B,N) :- sk(N,A,B). may_reunfold_aux(II,Ind,I,F,I1) :- getval(proc(Ind),L), may_reunfold_aux(L,II,Ind,I,F,I1). may_reunfold_aux([],II,Ind,I,F,I1) :- !, may_be_side(F), cj(F,fail,F1), addclause(II,(I:-F1)). may_reunfold_aux([Id],II,Ind,I,F,I1) :- !, getval(clau(Id),(I1c,T)), (may_be_prop(F) -> unifier(I1,I1c,E), cj(E,T,ET), cj(F,ET,F1), addclause(II,(I:-F1)) ; I1=I1c, cj(F,T,FT), addclause(II,(I:-FT))). may_reunfold_aux(L,II,Ind,I,F,I1) :- cj(F,I1,F1), addclause(II,(I:-F1)). calls_cut_to(Id,K,I) :- getval(clau(Id),(I,T)), (first_rest(T,cut_to(_),T1) -> true ; T1=T), extract_atom(cut_to(V),T1), V==K. unifier(A,B,E) :- unifier(A,B,[],E1), list_to_tuple(E1,E). unifier(A,B,Ei,Eo) :- var(A) -> (member(X=Y,Ei), (X==A; Y==A) -> Eo=Ei ; Eo=[A=B|Ei]) ;var(B) -> (member(X=Y,Ei), (X==B; Y==B) -> Eo=Ei ; Eo=[B=A|Ei]) ; A=..[FA|LA], B=..[FB|LB], (FA==FB -> unifierl(LA,LB,Ei,Eo) ; Eo=[fail]). unifierl(LA,LB,Ei,Eo) :- LA==[] -> (LB==[] -> Eo=Ei ; Eo=[fail]) ;LB==[] -> Eo=[fail] ; LA=[A|RA], LB=[B|RB], unifier(A,B,Ei,Et), unifierl(RA,RB,Et,Eo). list_to_tuple(L,T) :- L=[] -> T=true ;L=[X|Y] -> list_to_tuple(Y,A), eqjoin(X,A,T). eqjoin(A,B,C) :- A==fail -> C=fail ;B==fail -> C=fail ; C=(A,B). internal_check(R1,I1,Rest) :- not (varof(V,R1), not occurs(V,I1), occurs(V,Rest)). new_def(G,Sk,Ff,Ind) :- newpred(Ff,G), incval(index), getval(index,Ind), check_bounds(Ind), predicate_key(Ff,Ffk), setval(auxdef(Ind),1), write_table(Ffk,Ind,index_table), setval(proc(Ind),[]), tentative_side_class(Ind,G), tentative_prop_class(Ind,G), term_size(G,N), write_table(Sk,[Ff,G,Ind,N],defn_table), check_pattern_number. check_pattern_number :- incval(pattern_count), getval(pattern_count,N), getval(pattern_number,M), getval(term_depth,D), (N==M, D>1 -> setval(many_patterns,true), nl, writeln(" PADDY warning: pattern number exceeded") ; true). step(F,Ind,R,RF,RR,NewPrune) :- getval(proc(Ind),L), setup_prune_point(L,NewPrune), select_clause(NewPrune,Id,L), getval(clau(Id),(F,U)), first_rest1(U,R,RF,RR). setup_prune_point([],no_prune). setup_prune_point([_],no_prune). setup_prune_point([_,_|_],NewPrune) :- incval(prune), getval(prune,NewPrune), check_bounds(NewPrune), setval(prune(NewPrune),0). may_prune(_,no_prune,_) :- !. may_prune(cut_to(_),Prune,I) :- most_general(I), !, setval(prune(Prune),1). may_prune(_,_,_). select_clause(Prune,Id,[_|L]) :- select_clause(Prune,Id,L). select_clause(no_prune,Id,[Id|_]) :- !. select_clause(Prune,Id,[Id|_]) :- getval(prune(Prune),0). may_reunfold_def(Ind,Ff,R,F1,R1) :- getval(transformed(Ind),1), getval(proc(Ind),[Id]) -> getval(clau(Id),(Ff,T)), first_rest1(T,R,F1,R1) ; F1=Ff, R1=R. % Post-transformation post_transformation :- find_relevant_code, expand_dets, find_relevant_code, drop_equals, cut_args, cut_delabelling, last_cut_deletion, setup_trim, cut_reductions, add_once. find_relevant_code :- compile_term(relevant_pred('0','0','0')), start_compile_stream(relevant), clear_table(relevant), not (pd_predicate(G), functor(G,F,A), concat_atom([F,'_',A],FA), not table_entry(FA,relevant), read_table(FA,Ind,index_table), not find_relevant(FA,F/A,Ind)), clear_table(relevant), end_compile_stream(relevant). find_relevant(FA,F/A,Ind) :- getval(proc(Ind),L), L\==[] -> write_table(FA,'0',relevant), stream_compile_term(relevant,relevant_pred(F,A,L)), relevant_list(L) ; true. relevant_list([]). relevant_list([I|L]) :- getval(clau(I),(_,T)), relevant_body(T), relevant_list(L). relevant_body(T) :- not (extract_atom(P,T), not body_pred(P), not head_pred(P), predicate_key(P,Pk), read_table(Pk,Ind,index_table), functor(P,F,A), concat_atom([F,'_',A],FA), not table_entry(FA,relevant), not find_relevant(FA,F/A,Ind)). expand_dets :- not (relevant_pred(F,A,L), member(Id,L), getval(clau(Id),(H,T)), not (expand_dets(H,T,T1), setval(clau(Id),(H,T1)))). expand_dets(H,((A,B),C),T) :- !, expand_dets(H,(A,B,C),T). expand_dets(H,(A,B),(E,TX)) :- predicate_key(A,Ak), read_table(Ak,Ind,index_table), getval(proc(Ind),[Id]), !, getval(clau(Id),(P,T)), expand_dets(H,B,X), cj(T,X,TX), unifier(A,P,E). expand_dets(H,(A,B),AT) :- !, expand_dets(H,B,T), cj(A,T,AT). expand_dets(H,A,(E,T)) :- predicate_key(A,Ak), read_table(Ak,Ind,index_table), getval(proc(Ind),[Id]), !, getval(clau(Id),(P,T)), unifier(A,P,E). expand_dets(H,A,A). add_once :- not (relevant_pred(F,A,L), member(Id,L), getval(clau(Id),(H,T)), split5(T,TL,get_cut(K),TM,cut_to(K1),TR), K==K1, not (cj(TL,once(TM),LM), cj(LM,TR,LMR), setval(clau(Id),(H,LMR)))). split5(T,A,B,C,D,E) :- split(T,A,T1), split(T1,B,T2), B\==true, split(T2,C,T3), C\==true, split(T3,D,E), D\==true. split(T,L,R) :- split2(T,L,R) ;L=T, R=true. split2(T,L,R) :- T=((A,B),C) -> split2((A,B,C),L,R) ; (L=true, R=T ;T=(H,S), split2(S,X,R), cj(H,X,L)). drop_equals :- not (relevant_pred(F,A,L), member(Id,L), getval(clau(Id),(H,T)), not drop_equals(Id,H,true,T,no)). drop_equals(Id,H,X,A,Z) :- A==true -> (Z==yes -> setval(clau(Id),(H,X)) ; true) ; first_rest(A,F,R), (F=(P=Q), safe_equals(P=Q,(H,X)) -> P=Q, drop_equals(Id,H,X,R,yes) ; cj(X,F,XF), drop_equals(Id,H,XF,R,Z)). % could further weaken safe_equals safe_equals(P=Q,T) :- not P\=Q, (not not (copy_term(T,T1), P=Q, variant(T,T1)) -> true ; not (extract_atom(A,T), may_be_prop(A))). cut_args :- compile_term([cut_arg('0','0','0'),no_cut_arg('0','0')]), start_compile_stream(cut_arg), start_compile_stream(no_cut_arg), clear_table(cut_arg), clear_table(no_cut_arg), not (relevant_pred(_,_,L), rmember(Id,L), getval(clau(Id),(_,T)), pair(T,A,B), functor(B,F,M), relevant_pred(F,M,_), concat_atom([F,'_',M],FM), not table_entry(FM,no_cut_arg), not new_cut_arg(A,B,F,M,FM)), clear_table(no_cut_arg), clear_table(cut_arg), end_compile_stream(no_cut_arg), end_compile_stream(cut_arg). new_cut_arg(A,B,F,M,FM) :- A=get_cut(K), interval(1,N,M), arg(N,B,V), V==K -> (read_table(FM,N1,cut_arg), N\==N1 -> write_table(FM,'0',no_cut_arg), stream_compile_term(no_cut_arg,no_cut_arg(F,M)) ;read_table(FM,N,cut_arg) -> true ; write_table(FM,N,cut_arg), stream_compile_term(cut_arg,cut_arg(F,M,N))) ; write_table(FM,'0',no_cut_arg), stream_compile_term(no_cut_arg,no_cut_arg(F,M)). cut_delabelling :- not (cut_arg(F,M,N), (F,M,N)\==('0','0','0'), not no_cut_arg(F,M), relevant_pred(F,M,L), rmember(Id,L), not (getval(clau(Id),(H,T)), arg(N,H,K), cut_delabel(T,K,T1), setval(clau(Id),(H,T1)))). cut_delabel((A;B),K,(X;Y)) :- !, cut_delabel(A,K,X), cut_delabel(B,K,Y). cut_delabel((A,B),K,(X,Y)) :- !, cut_delabel(A,K,X), cut_delabel(B,K,Y). cut_delabel(cut_to(V),K,!) :- V==K, !. cut_delabel(X,_,X). pair(A,X,Y) :- pairtail((true,A),X,R), pairhead(R,Y). pairtail(((A,B),C),X,R) :- !, pairtail((A,B,C),X,R). pairtail(((A;B),C),X,R) :- !, pairhead(C,F), (pairtail((A,F),X,R); pairtail((B,F),X,R); pairtail(C,X,R)). pairtail((A,B),X,Y) :- !, (X=A, Y=B; pairtail(B,X,Y)). pairtail((A;B),X,R) :- (pairtail(A,X,R); pairtail(B,X,R)). pairhead((A,B),F) :- !, pairhead(A,F). pairhead((A;B),F) :- !, (pairhead(A,F); pairhead(B,F)). pairhead(F,F). last_cut_deletion :- not (relevant_pred(F,A,[Id|L]), getval(clau(Id),(H,T)), first_rest(T,!,R), not setval(clau(Id),(H,R))). cut_reductions :- not (relevant_pred(F,A,L), rmember(Id,L), not (getval(clau(Id),(H,T)), trim_body((H,T),(Hd,Td)), tidy(Td,T1), setval(clau(Id),(Hd,T1)))). setup_trim :- clear_table(redarg_table), repeat, setval(temp,no), setup_trim_loop, getval(temp,no), !. setup_trim_loop :- not (relevant_pred(F,A,L), F\=='0', nlist(A,[],Ri), trim_intersect(L,Ri,Ro), Ro\==[], functor(P,F,A), concat_atom([F,'_',A],Pk), (read_table(Pk,Ro1,redarg_table) -> Ro1\==Ro ; true), setval(temp,yes), not write_table(Pk,Ro,redarg_table)). trim_intersect([],Ri,Ri) :- !. trim_intersect(_,[],[]) :- !. trim_intersect([I|L],Ri,Ro) :- getval(clau(I),(H,T)), redargs(Ri,H,T,Rt), trim_intersect(L,Rt,Ro). trim_body((A,B),(X,Y)) :- !, trim_body(A,X), trim_body(B,Y). trim_body((A;B),(X;Y)) :- !, trim_body(A,X), trim_body(B,Y). trim_body(G,G) :- pd_predicate(G), !. trim_body(G,D) :- predicate_key(G,Gk), read_table(Gk,L,redarg_table), L\==[], !, G=..[F|X], droplis(X,L,Y,1), D=..[F|Y]. trim_body(G,G). redargs([],_,_,[]). redargs([N|Ri],H,T,Ro) :- arg(N,H,V), var(V), functor(H,HF,HA), not will_occur(V,T,N,HF,HA), unique_in_head(V,H,N,HA) -> Ro=[N|R], redargs(Ri,H,T,R) ; redargs(Ri,H,T,Ro). will_occur(V,T,N,HF,HA) :- extract_atom(A,T), functor(A,AF,AA), (concat_atom([AF,'_',AA],Ak), read_table(Ak,L,redarg_table) -> true ; L=[]), (HF/HA=AF/AA -> interval(1,I,AA), not memberchk(I,[N|L]) ; interval(1,I,AA), not memberchk(I,L)), arg(I,A,X), occurs(V,X). unique_in_head(V,H,N,HN) :- not (interval(1,I,HN), I\==N, arg(I,H,A), occurs(V,A)). nlist(0,Li,Li) :- !. nlist(N,Li,Lo) :- M is N-1, nlist(M,[N|Li],Lo). droplis([],L,[],_) :- !. droplis(X,[],X,_) :- !. droplis([A|B],[N|L],Y,N) :- !, M is N+1, droplis(B,L,Y,M). droplis([A|B],L,[A|C],N) :- M is N+1, droplis(B,L,C,M). % General facilities make_static(D,S) :- not D, !, S=..[F|L], dummies(L,L1), S1=..[F|L1], compile_term(S1). make_static(D,S) :- start_compile_stream(comp), not (retract(D), not stream_compile_term(comp,S)), end_compile_stream(comp). dummies([],[]). dummies([_|L],['0'|D]) :- dummies(L,D). start_compile_stream(S) :- open(_,string,S). stream_compile_term(S,X) :- printf(S,"%q. ",X). end_compile_stream(S) :- seek(S,0), set_stream(log_output,null), compile_stream(S), set_stream(log_output,output), close(S). % Generalisation (due to Joachim Schimpf) generalise(A,B,G) :- map(A,B,G,[],Map), sort(0,=<,Map,SortedMap), unify_duplicates(SortedMap). map(A,B,G,Map,NewMap) :- (nonvar(A), nonvar(B), functor(A,Name,Arity), functor(B,Name,Arity) -> functor(G,Name,Arity), map_arg(Arity,A,B,G,Map,NewMap) ; NewMap=[subst(A,B,G)|Map]). map_arg(0,A,B,G,NewMap,NewMap) :- !. map_arg(N,A,B,G,Map0,NewMap) :- arg(N,A,An), arg(N,B,Bn), arg(N,G,Gn), map(An,Bn,Gn,Map0,Map1), N1 is N-1, map_arg(N1,A,B,G,Map1,NewMap). unify_duplicates(M) :- M=[subst(A1,B1,G1)|T], T=[subst(A2,B2,G2)|_] -> (A1==A2, B1==B2 -> G1=G2 ; true), unify_duplicates(T) ; true. % New predicate generation newpred(N,R) :- varset(R,S), newpred1(N,S,R). newpred(N,R,R1) :- varset_inter(R1,R,S), newpred1(N,S,R). newpred1(N,S,R) :- (R=(_,_) -> Z=aux ;R=(_;_) -> Z=aux ; functor(R,Z,_)), getval(name_count,NC), once((interval(NC,K,9999999), concat_atom([Z,'_',K],Name), not table_entry(Name,name_table))), K1 is K+1, setval(name_count,K1), write_table(Name,'0',name_table), N=..[Name|S]. % Pattern function pattern_key(A,S) :- getval(term_depth,N), (N>1, getval(many_patterns,true) -> M=1 ; M=N), sk(N,A,S1), term_string(S1,Ss), atom_string(S,Ss). :- export sk/3. sk(0,_,'0') :- !. sk(_,T,'0') :- var(T), !. sk(N,T,S) :- symbol(T), !, functor(T,F,A), functor(S,F,A), M is N-1, sk(A,M,T,S). sk(_,_,'0'). sk(0,_,_,_) :- !. sk(A,N,T,S) :- arg(A,T,X), sk(N,X,Y), arg(A,S,Y), B is A-1, sk(B,N,T,S). % Side effect and propagation sensitivity may_be_side(G) :- var(G), !. may_be_side(call(X)) :- !, may_be_side(X). may_be_side(G) :- head_pred(G), !, side(G). may_be_side(G) :- predicate_key(G,Gk), read_table(Gk,Ind,index_table), !, getval(side(Ind),1). may_be_side(G) :- not open_no_side(G). may_be_prop(G) :- var(G), !. may_be_prop(call(X)) :- !, may_be_prop(X). may_be_prop(G) :- head_pred(G), !, (prop(G) -> true ; side(G), nonground(G)). may_be_prop(G) :- predicate_key(G,Gk), read_table(Gk,Ind,index_table), !, (getval(side(Ind),1) -> true ; getval(prop(Ind),1), nonground(G)). may_be_prop(G) :- not open_no_prop(G). tentative_side_class(Ind,G) :- extract_atom(X,G), may_be_side(X) -> setval(side(Ind),1) ; setval(side(Ind),0). tentative_prop_class(Ind,G) :- extract_atom(X,G), may_be_prop(X) -> setval(prop(Ind),1) ; setval(prop(Ind),0). /* TABLES: write_table writes Term to Table given key Atom. read_table retrieves it via Sepia hashing. delete_entry deletes an entry with key Atom from Table. table_entry tests to see if Table has an entry with key Atom. clear_table empties Table if it exists and starts it off again empty. */ predicate_key(P,K) :- functor(P,F,A), concat_atom([F,'_',A],K). write_table(Atom,Term,Table) :- (current_array_body(Atom,_,Table) -> true ; make_local_array_body(Atom,Table)), setval_body(Atom,Term,Table). read_table(Atom,Term,Table) :- current_array_body(Atom,_,Table) -> getval_body(Atom,Term,Table). delete_entry(Atom,Table) :- erase_array_body(Atom,Table). table_entry(Atom,Table) :- current_array_body(Atom,_,Table). clear_table(Table) :- erase_module(Table), create_module(Table). % BUILT-IN SIDE EFFECTS % Logic & control open_no_side(call(G)) :- nonvar(G), open_no_side(G). open_no_side(fail). open_no_side(false). open_no_side(true). open_no_side(get_cut(_)). % Database open_no_side(clause(_)). open_no_side(clause(_,_)). open_no_side(current_built_in(_)). open_no_side(current_predicate(_)). open_no_side(get_flag(_,_,_)). open_no_side(is_dynamic(_)). % Internal Indexed database open_no_side(current_record(_)). open_no_side(is_record(_)). open_no_side(recorded(_,_)). open_no_side(recorded(_,_,_)). open_no_side(recorded_list(_,_)). open_no_side(referenced_record(_,_)). % Type testing open_no_side(atom(_)). open_no_side(atomic(_)). open_no_side(integer(_)). open_no_side(nonground(_)). open_no_side(nonvar(_)). open_no_side(number(_)). open_no_side(float(_)). open_no_side(string(_)). open_no_side(type_of(_,_)). open_no_side(var(_)). % Term comparison open_no_side(_==_). open_no_side(_\=_). open_no_side(_\==_). open_no_side(_@<_). open_no_side(_@=<_). open_no_side(_@>_). open_no_side(_@>=_). open_no_side(compare(_,_,_)). open_no_side(compare_instances(_,_,_)). open_no_side(instance(_,_)). open_no_side(occurs(_,_)). open_no_side(variant(_,_)). % Term manipulation open_no_side(_=.._). open_no_side(arg(_,_,_)). open_no_side(atom_string(_,_)). open_no_side(char_int(_,_)). open_no_side(copy_term(_,_)). open_no_side(functor(_,_,_)). open_no_side(integer_atom(_,_)). open_no_side(name(_,_)). open_no_side(string_list(_,_)). open_no_side(term_string(_,_)). % All solution % Arithmetic open_no_side(+(_,_,_)). open_no_side(*(_,_,_)). open_no_side(-(_,_)). open_no_side(-(_,_,_)). open_no_side(<<(_,_,_)). open_no_side(>>(_,_,_)). open_no_side(\(_,_)). open_no_side(\/(_,_,_)). open_no_side(+(_,_)). open_no_side(_<_). open_no_side(_=<_). open_no_side(_=\=_). open_no_side(_>_). open_no_side(_>=_). open_no_side(_=:=_). open_no_side(/\(_,_,_)). open_no_side(/(_,_,_)). open_no_side(//(_,_,_)). open_no_side(_ is _). open_no_side(abs(_,_)). open_no_side(acos(_,_)). open_no_side(asin(_,_)). open_no_side(atan(_,_)). open_no_side(cos(_,_)). open_no_side(exp(_,_)). open_no_side(fix(_,_)). open_no_side(float(_,_)). open_no_side(ln(_,_)). open_no_side(max(_,_,_)). open_no_side(min(_,_,_)). open_no_side(mod(_,_,_)). open_no_side(plus(_,_,_)). open_no_side(round(_,_)). open_no_side(sin(_,_)). open_no_side(sqrt(_,_)). open_no_side(tan(_,_)). open_no_side(times(_,_,_)). open_no_side(xor(_,_,_)). open_no_side(^(_,_,_)). % Strings & atoms open_no_side(atom_length(_,_)). open_no_side(concat_atom(_,_)). open_no_side(concat_atoms(_,_,_)). open_no_side(concat_string(_,_)). open_no_side(concat_strings(_,_,_)). open_no_side(string_length(_,_)). open_no_side(substring(_,_,_)). % Module handling open_no_side(current_module(_)). open_no_side(is_locked(_)). open_no_side(is_module(_)). open_no_side(is_protected(_)). open_no_side(tool_body(_,_,_)). % Stream I/O open_no_side(at(_,_)). open_no_side(at_eof(_)). open_no_side(current_stream(_,_,_)). open_no_side(get_stream(_,_)). open_no_side(stream_number(_)). % Character I/O % Term I/O % Event handling open_no_side(current_error(_)). open_no_side(current_interrupt(_,_)). open_no_side(error_id(_,_)). open_no_side(get_error_handler(_,_)). open_no_side(get_error_handler(_,_,_)). open_no_side(get_interrupt_flag(_,_)). open_no_side(get_interrupt_handler(_,_)). open_no_side(get_interrupt_handler(_,_,_)). open_no_side(list_error(_,_,_)). % Debugging open_no_side(get_leash(_,_)). % Arrays & global variables open_no_side(current_array(_,_,_)). open_no_side(current_array(_,_)). open_no_side(getval(_,_)). % Coroutining open_no_side(~X) :- open_no_side(X). open_no_side(_~=_). open_no_side(delayed_goals(_)). open_no_side(delayed_goals_number(_,_)). open_no_side(no_delayed_goals). % Constructive negation open_no_side(ineq(_,_,_)). % External Interface % Prolog environment open_no_side(current_atom(_)). open_no_side(current_functor(_)). open_no_side(current_op(_)). open_no_side(is_built_in(_)). open_no_side(is_predicate(_)). open_no_side(phrase(_,_)). open_no_side(phrase(_,_,_)). open_no_side(statistics(_,_)). % Operating system open_no_side(argc(_)). open_no_side(argv(_,_)). open_no_side(cputime(_)). open_no_side(date(_)). open_no_side(exists(_)). open_no_side(get_file_info(_)). open_no_side(getcwd(_)). open_no_side(getenv(_,_)). open_no_side(pathname(_,_)). open_no_side(pathname(_,_,_)). open_no_side(read_directory(_,_,_,_)). open_no_side(random(_)). open_no_side(suffix(_,_)). % Libraries % BUILT-IN BACKWARD PROPAGATION SENSITIVITY % Logic & control open_no_prop(call(G)) :- nonvar(G), open_no_prop(G). open_no_prop(fail). open_no_prop(false). open_no_prop(true). open_no_prop(get_cut(_)). % Database open_no_prop(clause(_)). open_no_prop(clause(_,_)). open_no_prop(current_built_in(_)). open_no_prop(current_predicate(_)). open_no_prop(get_flag(_,_,_)). open_no_prop(is_dynamic(_)). % Internal Indexed database open_no_prop(current_record(_)). open_no_prop(is_record(_)). open_no_prop(recorded(_,_)). open_no_prop(recorded(_,_,_)). open_no_prop(recorded_list(_,_)). open_no_prop(referenced_record(_,_)). % Type testing % Term manipulation open_no_prop(_=.._). open_no_prop(arg(_,_,_)). open_no_prop(atom_string(_,_)). open_no_prop(char_int(_,_)). open_no_prop(functor(_,_,_)). open_no_prop(integer_atom(_,_)). open_no_prop(name(_,_)). open_no_prop(string_list(_,_)). % All solution % Arithmetic open_no_prop(*(_,_,_)). open_no_prop(+(_,_,_)). open_no_prop(-(_,_)). open_no_prop(-(_,_,_)). open_no_prop(<<(_,_,_)). open_no_prop(>>(_,_,_)). open_no_prop(\(_,_)). open_no_prop(\/(_,_,_)). open_no_prop(+(_,_)). open_no_prop(_<_). open_no_prop(_=<_). open_no_prop(_=\=_). open_no_prop(_>_). open_no_prop(_>=_). open_no_prop(_=:=_). open_no_prop(/\(_,_,_)). open_no_prop(/(_,_,_)). open_no_prop(//(_,_,_)). open_no_prop(_ is _). open_no_prop(abs(_,_)). open_no_prop(acos(_,_)). open_no_prop(asin(_,_)). open_no_prop(atan(_,_)). open_no_prop(cos(_,_)). open_no_prop(exp(_,_)). open_no_prop(fix(_,_)). open_no_prop(float(_,_)). open_no_prop(ln(_,_)). open_no_prop(max(_,_,_)). open_no_prop(min(_,_,_)). open_no_prop(mod(_,_,_)). open_no_prop(plus(_,_,_)). open_no_prop(round(_,_)). open_no_prop(sin(_,_)). open_no_prop(sqrt(_,_)). open_no_prop(tan(_,_)). open_no_prop(times(_,_,_)). open_no_prop(xor(_,_,_)). open_no_prop(^(_,_,_)). % Strings & atoms open_no_prop(atom_length(_,_)). open_no_prop(concat_atom(_,_)). open_no_prop(concat_atoms(_,_,_)). open_no_prop(concat_string(_,_)). open_no_prop(concat_strings(_,_,_)). open_no_prop(string_length(_,_)). open_no_prop(substring(_,_,_)). % Module handling open_no_prop(current_module(_)). open_no_prop(is_locked(_)). open_no_prop(is_module(_)). open_no_prop(is_protected(_)). open_no_prop(tool_body(_,_,_)). % Stream I/O open_no_prop(at(_,_)). open_no_prop(at_eof(_)). open_no_prop(current_stream(_,_,_)). open_no_prop(get_stream(_,_)). open_no_prop(stream_number(_)). % Character I/O % Term I/O % Event handling open_no_prop(current_error(_)). open_no_prop(current_interrupt(_,_)). open_no_prop(error_id(_,_)). open_no_prop(get_error_handler(_,_)). open_no_prop(get_error_handler(_,_,_)). open_no_prop(get_interrupt_flag(_,_)). open_no_prop(get_interrupt_handler(_,_)). open_no_prop(get_interrupt_handler(_,_,_)). open_no_prop(list_error(_,_,_)). % Debugging open_no_prop(get_leash(_,_)). % Arrays & global variables open_no_prop(current_array(_,_,_)). open_no_prop(current_array(_,_)). open_no_prop(getval(_,_)). % Coroutining open_no_prop(_ ~= _). open_no_prop(no_delayed_goals). % Constructive negation open_no_prop(ineq(_,_,_)). % External Interface % Prolog environment open_no_prop(current_atom(_)). open_no_prop(current_functor(_)). open_no_prop(is_built_in(_)). open_no_prop(is_predicate(_)). open_no_prop(phrase(_,_)). open_no_prop(phrase(_,_,_)). open_no_prop(statistics(_,_)). % Operating system open_no_prop(argc(_)). open_no_prop(argv(_,_)). open_no_prop(cputime(_)). open_no_prop(date(_)). open_no_prop(exists(_)). open_no_prop(getcwd(_)). open_no_prop(getenv(_,_)). open_no_prop(pathname(_,_)). open_no_prop(pathname(_,_,_)). open_no_prop(random(_)). open_no_prop(read_directory(_,_,_,_)). open_no_prop(suffix(_,_)). % Libraries % BUILT-IN EXECUTABILITY % Logic & control executable_open(call(G)) :- nonvar(G), executable_open(G). executable_open(fail). executable_open(false). % Database executable_open(clause(X)) :- nonvar(X). executable_open(clause(X,_)) :- nonvar(X), (functor(X,F,A), current_built_in(F/A) ;head_pred(X), not dynamic_pred(X)). executable_open(current_built_in(X)) :- ground(X). % Internal Indexed database % Type testing executable_open(atom(A)) :- nonvar(A). executable_open(atomic(A)) :- nonvar(A). executable_open(compound(A)) :- atomic(A); compound(A). executable_open(integer(A)) :- nonvar(A). executable_open(nonground(A)) :- ground(A). executable_open(nonvar(A)) :- nonvar(A). executable_open(number(A)) :- nonvar(A). executable_open(float(A)) :- nonvar(A). executable_open(string(A)) :- nonvar(A). executable_open(type_of(A,B)) :- ground(A); compound(A). executable_open(var(V)) :- nonvar(V). % Term comparison executable_open(A==B) :- A==B; A\=B. executable_open(A\=B) :- A==B; A\=B. executable_open(A\==B) :- A==B; A\=B. executable_open(A=B). executable_open(A@<B) :- ground(A), ground(B). executable_open(A@=<B) :- ground(A), ground(B). executable_open(A@>B) :- ground(A), ground(B). executable_open(A@>=B) :- ground(A), ground(B). executable_open(compare(A,B,C)) :- ground(B), ground(C). %executable_open(compare_instances(A,B,C)) :- ? % ground(B), ground(C); B\=C. ? %executable_open(instance(A,B)) :- ? % ground(A), ground(B); A\=B. ? executable_open(occurs(A,B)) :- occurs(A,B). executable_open(variant(A,B)) :- A==B; A\=B. % Term manipulation executable_open(A=..B) :- nonvar(A); clist(B), B=[H|T], atom(H). executable_open(arg(A,B,C)) :- nonvar(A), compound(B). executable_open(atom_string(A,B)) :- ground(A); ground(B). executable_open(char_int(A,B)) :- ground(A); ground(B). executable_open(copy_term(A,B)) :- ground(A); ground(B); A\=B. executable_open(functor(A,B,C)) :- nonvar(A); ground(B), ground(C). executable_open(integer_atom(A,B)) :- ground(A); ground(B). executable_open(name(A,B)) :- ground(A); ground(B). executable_open(string_list(A,B)) :- ground(A); ground(B). executable_open(term_string(A,B)) :- ground(A); ground(B). % All solution % Arithmetic executable_open(*(A,B,C)) :- nonvar(A), nonvar(B). executable_open(+(A,B,C)) :- nonvar(A), nonvar(B). executable_open(-(A,B)) :- nonvar(A). executable_open(-(A,B,C)) :- nonvar(A), nonvar(B). executable_open(<<(A,B,C)) :- nonvar(A), nonvar(B). executable_open(>>(A,B,C)) :- nonvar(A), nonvar(B). executable_open(\(A,B)) :- nonvar(A). executable_open(\/(A,B,C)) :- nonvar(A), nonvar(B). executable_open(+(A,B)) :- nonvar(A). executable_open(A<B) :- ground(A), ground(B). executable_open(A=<B) :- ground(A), ground(B). executable_open(A=\=B) :- ground(A), ground(B). executable_open(A>B) :- ground(A), ground(B). executable_open(A>=B) :- ground(A), ground(B). executable_open(A=:=B) :- ground(A), ground(B). executable_open(/\(A,B,C)) :- nonvar(A), nonvar(B). executable_open(/(A,B,C)) :- nonvar(A), nonvar(B). executable_open(//(A,B,C)) :- nonvar(A), nonvar(B). executable_open(A is B) :- ground(B). executable_open(abs(A,B)) :- nonvar(A). executable_open(acos(A,B)) :- nonvar(A). executable_open(asin(A,B)) :- nonvar(A). executable_open(atan(A,B)) :- nonvar(A). executable_open(cos(A,B)) :- nonvar(A). executable_open(exp(A,B)) :- nonvar(A). executable_open(fix(A,B)) :- nonvar(A). executable_open(float(A,B)) :- nonvar(A). executable_open(ln(A,B)) :- nonvar(A). executable_open(max(A,B,C)) :- nonvar(A), nonvar(B). executable_open(min(A,B,C)) :- nonvar(A), nonvar(B). executable_open(mod(A,B,C)) :- nonvar(A), nonvar(B). executable_open(plus(A,B,C)) :- nonvar(A), (nonvar(B); nonvar(C)); nonvar(B), nonvar(C). executable_open(round(A,B)) :- nonvar(A). executable_open(sin(A,B)) :- nonvar(A). executable_open(sqrt(A,B)) :- nonvar(A). executable_open(tan(A,B)) :- nonvar(A). executable_open(times(A,B,C)) :- nonvar(A), (nonvar(B); nonvar(C)); nonvar(B), nonvar(C). executable_open(xor(A,B,C)) :- nonvar(A), nonvar(B). executable_open(^(A,B,C)) :- nonvar(A), nonvar(B). % Strings & atoms executable_open(atom_length(A,B)) :- nonvar(A). executable_open(concat_atom(A,B)) :- ground(A). executable_open(concat_atoms(A,B,C)) :- ground(A), ground(B). executable_open(concat_string(A,B)) :- ground(A). executable_open(concat_strings(A,B,C)) :- nonvar(A), nonvar(B). executable_open(string_length(A,B)) :- nonvar(A). executable_open(substring(A,B,C)) :- nonvar(A), nonvar(B). % Module handling % Stream I/O % Character I/O % Term I/O % Event handling % Debugging % Arrays & global variables % Coroutining executable_open(A~=B) :- A==B; A\=B. % Constructive negation executable_open(ineq(V,A,B)) :- ineq_expand(V,A,B). % External Interface % Prolog environment executable_open(is_built_in(A)) :- nonvar(A), A=(B/C), nonvar(B), nonvar(C). % Operating system % Libraries % EXECUTION OF BUILT-INS execute_open(clause((A:-B))) :- !, fail. execute_open(clause(A)) :- !, fail. execute_open(clause(A,B)) :- !, fail. execute_open(ineq(V,A,B)) :- !, A\=B. execute_open((A~=B)) :- !, A\=B. execute_open(G) :- G. ineq_expand(V,A,B) :- A==B. ineq_expand(V,A,B) :- copy_term(V,V1), not (A=B, variant(V,V1)). clist(L) :- nonvar(L), (L==[]; L=[_|T], clist(T)). addclause(Ind,(H:-T)) :- metacall_process(T,T1), tidy(T1,Tp), % for gc(A),ct(A),fail etc (Tp==fail -> true ; incval(clause_id), getval(clause_id,ID), check_bounds(ID), setval(clau(ID),(H,Tp)), getval(proc(Ind),L), setval(proc(Ind),[ID|L])). metacall_process(T,Tm) :- var(T) -> Tm=call(T) ;T=call(X), nonvar(X) -> metacall_process(X,Tm) ; Tm=T. check_bounds(Ind) :- getval(bounds,Ind) -> writeln(" PADDY ERROR: transformation halted, bounds exceeded."), writeln(" The bounds can be increased using `bounds'"), writeln(" (type `help' for details)."), abort ; true. extract_atom(G,(A,B)) :- !, (extract_atom(G,A); extract_atom(G,B)). extract_atom(G,(A;B)) :- !, (extract_atom(G,A); extract_atom(G,B)). extract_atom(T,T). rmember(X,[A|B]) :- rmember(X,B); X=A. % ASSUMES get_cut(K) => K NOT IN CLAUSE HEAD! TRUE FOR AUTO-GEN GC... tidy(A,B) :- norm(A,C), tidy1(C,B). norm(((A;B);C),X) :- !, norm((A;B;C),X). norm((A;B),(C;D)) :- !, norm(A,C), norm(B,D). norm(((A,B),C),X) :- !, norm((A,B,C),X). norm((A,B),(C,D)) :- !, norm(A,C), norm(B,D). norm(A,A). tidy1((A;B),C) :- !, tidy1(A,D), tidy1(B,E), dj(D,E,C). tidy1((get_cut(X),A),B) :- !, tidy1(A,C), shift_gc(X,C,B). tidy1(get_cut(_),true) :- !. tidy1((cut_to(X),cut_to(Y),A),B) :- !, tidy1((cut_to(Y),A),B). tidy1((cut_to(X),cut_to(Y)),cut_to(Y)) :- !. tidy1((cut_to(X),A),B) :- !, tidy1(A,C), shift_ct(X,C,B). tidy1((!,cut_to(X),A),B) :- !, tidy1((cut_to(X),A),B). tidy1((!,cut_to(X)),cut_to(X)) :- !. tidy1((call(A),B),C) :- nonvar(A), !, tidy1((A,B),C). tidy1(call(A),C) :- nonvar(A), !, tidy1(A,C). tidy1((A,B),C) :- !, tidy1(B,D), cj(A,D,C). tidy1(A,A). /* Could also have: tidy1((cut_to(X),(A;B)),D) :- !, tidy1((cut_to(X),A;cut_to(X),B),D). tidy1(((A;B),C),D) :- !, tidy1((A,C;B,C),D). */ shift_gc(X,(A;B),AXB) :- not occurs(X,A), !, shift_gc(X,B,XB), dj(A,XB,AXB). shift_gc(X,(A=B,C),D) :- A\==X, B\==X, !, shift_gc(X,C,E), cj(A=B,E,D). shift_gc(X,A,A) :- A\=(_;_), not occurs(X,A), !. shift_gc(X,(cut_to(Y),A),B) :- X==Y, !, shift_gc(X,A,B). shift_gc(X,cut_to(Y),true) :- X==Y, !. shift_gc(X,(get_cut(Y),A),(X=Y,B)) :- !, cj(get_cut(X),A,B). shift_gc(X,A,B) :- cj(get_cut(X),A,B). shift_ct(X,C,B) :- (C=(get_cut(Y),D) -> cj(Y=X,D,E), B=(cut_to(X),E) ; cj(cut_to(X),C,B)). cj(fail,_,fail) :- !. cj(abort,_,abort) :- !. cj(true,B,B) :- !. cj(A,true,A) :- !. cj(A,B,(A,B)). dj(fail,B,B) :- !. dj(abort,B,abort) :- !. dj(A,fail,A) :- !. dj(A,B,(A;B)). first_rest(((A,B),C),F,R) :- !, first_rest((A,B,C),F,R). first_rest((F,R),F1,R1) :- !, F=F1, R=R1. first_rest(T,T,true). first_rest1(fail,_,fail,fail) :- !. first_rest1(true,A,B,C) :- !, first_rest(A,B,C). first_rest1(A,true,B,C) :- !, first_rest(A,B,C). first_rest1(((A,B),C),D,X,Y) :- !, first_rest1((A,B,C),D,X,Y). first_rest1((A,fail),_,A,fail) :- !. first_rest1((A,true),C,A,C) :- !. first_rest1((A,B),C,A,(B,C)) :- !. first_rest1(A,B,A,B). natural(0). natural(I) :- natural(J), I is J+1. interval(A,A,B) :- A=<B. interval(A,B,C) :- A<C, D is A+1, interval(D,B,C). most_general(H) :- functor(H,_,N), copy_term(H,H1), most_general(N,H1). most_general(0,H) :- !. most_general(N,H) :- arg(N,H,A), var(A), A=N, M is N-1, most_general(M,H). varof(V,T) :- term_string(T,X), open(X,string,I), readvar(I,T,S1), close(I), member([_|V],S1). % A slight flaw in this varset: (A,B,A) -> [B,A], ie ordering changed % for repeated variables. But it's faster than explicitly coding it. % For varset_inter should have largest argument first, for speed. varset(T,S) :- term_string(T,X), open(X,string,I), readvar(I,T,S1), close(I), strip_names(S1,S). strip_names([],[]). strip_names([[_|A]|B],[A|C]) :- strip_names(B,C). varset_inter(A,B,S) :- varset(A,T), inter(T,B,S). inter([],_,[]). inter([A|B],C,D) :- (occurs(A,C) -> D=[A|E]; D=E), inter(B,C,E). divert(F) :- open(F,write,file), set_stream(divert,file). undivert :- set_stream(divert,output), close(file). help :- writeln("COMMANDS"), nl, writeln("p(Infile)"), writeln(" partially deduces Infile, result to screen"), writeln("p(Infile,Outfile)"), writeln(" partially deduces Infile, result to Outfile"), nl, writeln("pin(Infile)"), writeln(" reads in the query file Infile"), writeln("p"), writeln(" performs the partial deduction"), writeln("pout(Outfile)"), writeln(" writes the result to the file Outfile"), writeln("pout"), writeln(" writes the result to the screen"), nl, writeln("term_depth(N)"), writeln(" sets the term abstraction depth to N (default 5)"), writeln("pattern_number(N)"), writeln(" sets the threshold number of patterns to N (default 100)"), writeln("bounds(N)"), writeln(" sets the array sizes to N"). ?- writeln(" *-------------------------------------------------------*"), writeln(" | The PADDY partial deduction system |"), writeln(" | |"), writeln(" | S.D.Prestwich ECRC 1992 |"), writeln(" | |"), writeln(" | (type `help' for help) |"), writeln(" *-------------------------------------------------------*"). :- set_error_handler(231, (help)/0).
modeswitch/barrelfish
usr/skb/eclipse_kernel/lib/paddy.pl
Perl
mit
56,413
package Parse::Binary; $Parse::Binary::VERSION = '0.11'; use 5.005; use bytes; use strict; use integer; use Parse::Binary::FixedFormat; =head1 NAME Parse::Binary - Unpack binary data structures into object hierarchies =head1 VERSION This document describes version 0.11 of Parse::Binary, released January 25, 2009. =head1 SYNOPSIS # This class represents a Win32 F<.ico> file: package IconFile; use base 'Parse::Binary'; use constant FORMAT => ( Magic => 'a2', Type => 'v', Count => 'v', 'Icon' => [ 'a16', '{$Count}', 1 ], Data => 'a*', ); # An individual icon resource: package Icon; use base 'Parse::Binary'; use constant FORMAT => ( Width => 'C', Height => 'C', ColorCount => 'C', Reserved => 'C', Planes => 'v', BitCount => 'v', ImageSize => 'V', ImageOffset => 'v', ); sub Data { my ($self) = @_; return $self->parent->substr($self->ImageOffset, $self->ImageSize); } # Simple F<.ico> file dumper that uses them: use IconFile; my $icon_file = IconFile->new('input.ico'); foreach my $icon ($icon_file->members) { print "Dimension: ", $icon->Width, "x", $icon->Height, $/; print "Colors: ", 2 ** $icon->BitCount, $/; print "Image Size: ", $icon->ImageSize, " bytes", $/; print "Actual Size: ", length($icon->Data), " bytes", $/, $/; } $icon_file->write('output.ico'); # save as another .ico file =head1 DESCRIPTION This module makes parsing binary data structures much easier, by serving as a base class for classes that represents the binary data, which may contain objects of other classes to represent parts of itself. Documentation is unfortunately a bit lacking at this moment. Please read the tests and source code of L<Parse::AFP> and L<Win32::Exe> for examples of using this module. =cut use constant PROPERTIES => qw( %struct $filename $size $parent @siblings %children $output $lazy $iterator $iterated ); use constant ENCODED_FIELDS => ( 'Data' ); use constant FORMAT => ( Data => 'a*' ); use constant SUBFORMAT => (); use constant DEFAULT_ARGS => (); use constant DELEGATE_SUBS => (); use constant DISPATCH_TABLE => (); use constant DISPATCH_FIELD => undef; use constant BASE_CLASS => undef; use constant ENCODING => undef; use constant PADDING => undef; unless (eval { require Scalar::Util; 1 }) { *Scalar::Util::weaken = sub { 1 }; *Scalar::Util::blessed = sub { UNIVERSAL::can($_[0], 'can') }; } ### Constructors ### sub new { my ($self, $input, $attr) = @_; no strict 'refs'; my $class = $self->class; $class->init unless ${"$class\::init_done"}; $attr ||= {}; $attr->{filename} ||= $input unless ref $input; my $obj = $class->spawn; %$obj = (%$obj, %$attr); my $data = $obj->read_data($input); $obj->load($data, $attr); if ($obj->{lazy}) { $obj->{lazy} = $obj; } elsif (!$obj->{iterator}) { $obj->make_members; } return $obj; } sub dispatch_field { return undef; } use vars qw(%HasMembers %DefaultArgs); use vars qw(%Fields %MemberFields %MemberClass %Packer %Parser %FieldPackFormat); use vars qw(%DispatchField %DispatchTable); sub init { no strict 'refs'; return if ${"$_[0]\::init_done"}; my $class = shift; *{"$class\::class"} = sub { ref($_[0]) || $_[0] }; *{"$class\::is_type"} = \&is_type; foreach my $item ($class->PROPERTIES) { no strict 'refs'; my ($sigil, $name) = split(//, $item, 2); *{"$class\::$name"} = ($sigil eq '$') ? sub { $_[0]{$name} } : ($sigil eq '@') ? sub { wantarray ? @{$_[0]{$name}||=[]} : ($_[0]{$name}||=[]) } : ($sigil eq '%') ? sub { $_[0]{$name}||={} } : die "Unknown sigil: $sigil"; *{"$class\::set_$name"} = ($sigil eq '$') ? sub { $_[0]->{$name} = $_[1] } : ($sigil eq '@') ? sub { @{$_[0]->{$name}||=$_[1]||[]} = @{$_[1]||[]} } : ($sigil eq '%') ? sub { %{$_[0]->{$name}||=$_[1]||{}} = %{$_[1]||{}} } : die "Unknown sigil: $sigil"; } my @args = $class->default_args; *{"$class\::default_args"} = \@args; *{"$class\::default_args"} = sub { @args }; my $delegate_subs = $class->delegate_subs; if (defined(&{"$class\::DELEGATE_SUBS"})) { $delegate_subs = { $class->DELEGATE_SUBS }; } *{"$class\::delegate_subs"} = sub { $delegate_subs }; while (my ($subclass, $methods) = each %$delegate_subs) { $methods = [ $methods ] unless ref $methods; foreach my $method (grep length, @$methods) { *{"$class\::$method"} = sub { goto &{$_[0]->require_class($subclass)->can($method)}; }; } } my $dispatch_table = $class->dispatch_table; if (defined(&{"$class\::DISPATCH_TABLE"})) { $dispatch_table = { $class->DISPATCH_TABLE }; } $DispatchTable{$class} = $dispatch_table; *{"$class\::dispatch_table"} = sub { $dispatch_table }; my $dispatch_field = undef; if (defined(&{"$class\::DISPATCH_FIELD"})) { $dispatch_field = $class->DISPATCH_FIELD; } $DispatchField{$class} = $dispatch_field; *{"$class\::dispatch_field"} = sub { $dispatch_field }; my @format = $class->format_list; if (my @subformat = $class->subformat_list) { my @new_format; while (my ($field, $format) = splice(@format, 0, 2)) { if ($field eq 'Data') { push @new_format, @subformat; } else { push @new_format, ($field => $format); } } @format = @new_format; } my @format_list = @format; *{"$class\::format_list"} = sub { @format_list }; my (@fields, @formats, @pack_formats, $underscore_count); my (%field_format, %field_pack_format); my (%field_parser, %field_packer, %field_length); my (@member_fields, %member_class); while (my ($field, $format) = splice(@format, 0, 2)) { if ($field eq '_') { # "we don't care" fields $underscore_count++; $field = "_${underscore_count}_$class"; $field =~ s/:/_/g; } if (ref $format) { $member_class{$field} = $class->classname($field); $field =~ s/:/_/g; $member_class{$field} = $class->classname($field); $class->require($member_class{$field}); push @member_fields, $field; } else { $format = [ $format ]; } push @fields, $field; my $string = join(':', $field, @$format); $field_format{$field} = [ @$format ]; if (!grep /\{/, @$format) { $field_length{$field} = length(pack($format->[0], 0)); $field_parser{$field} = Parse::Binary::FixedFormat->new( [ $string ] ); } push @formats, $string; s/\s*X\s*//g for @$format; my $pack_string = join(':', $field, @$format); $field_pack_format{$field} = [ @$format ]; $field_packer{$field} = Parse::Binary::FixedFormat->new( [ $pack_string ] ); push @pack_formats, $pack_string; } my $parser = $class->make_formatter(@formats); my $packer = $class->make_formatter(@pack_formats); $Packer{$class} = $packer; $Parser{$class} = $parser; $Fields{$class} = \@fields; $HasMembers{$class} = @member_fields ? 1 : 0; $DefaultArgs{$class} = \@args; $MemberClass{$class} = \%member_class; $MemberFields{$class} = \@member_fields; $FieldPackFormat{$class} = { map { ref($_) ? $_->[0] : $_ } %field_pack_format }; *{"$class\::fields"} = \@fields; *{"$class\::member_fields"} = \@member_fields; *{"$class\::has_members"} = @member_fields ? sub { 1 } : sub { 0 }; *{"$class\::fields"} = sub { @fields }; *{"$class\::formats"} = sub { @formats }; *{"$class\::member_fields"} = sub { @member_fields }; *{"$class\::member_class"} = sub { $member_class{$_[1]} }; *{"$class\::pack_formats"} = sub { @pack_formats }; *{"$class\::field_format"} = sub { $field_format{$_[1]}[0] }; *{"$class\::field_pack_format"} = sub { $field_pack_format{$_[1]}[0] }; *{"$class\::field_length"} = sub { $field_length{$_[1]} }; *{"$class\::parser"} = sub { $parser }; *{"$class\::packer"} = sub { $packer }; *{"$class\::field_parser"} = sub { my ($self, $field) = @_; $field_parser{$field} || do { Parse::Binary::FixedFormat->new( [ $self->eval_format( $self->{struct}, join(':', $field, @{$field_format{$field}}), ), ] ); }; }; *{"$class\::field_packer"} = sub { $field_packer{$_[1]} }; *{"$class\::has_field"} = sub { $field_packer{$_[1]} }; my %enc_fields = map { ($_ => 1) } $class->ENCODED_FIELDS; foreach my $field (@fields) { next if defined &{"$class\::$field"}; if ($enc_fields{$field} and my $encoding = $class->ENCODING) { require Encode; *{"$class\::$field"} = sub { my ($self) = @_; return Encode::decode($encoding => $self->{struct}{$field}); }; *{"$class\::Set$field"} = sub { my ($self, $data) = @_; $self->{struct}{$field} = Encode::encode($encoding => $data); }; next; } *{"$class\::$field"} = sub { $_[0]->{struct}{$field} }; *{"$class\::Set$field"} = sub { $_[0]->{struct}{$field} = $_[1] }; } ${"$class\::init_done"} = 1; } sub initialize { return 1; } ### Miscellanous ### sub field { my ($self, $field) = @_; return $self->{struct}{$field}; } sub set_field { my ($self, $field, $data) = @_; $self->{struct}{$field} = $data; } sub classname { my ($self, $class) = @_; return undef unless $class; $class =~ s/__/::/g; my $base_class = $self->BASE_CLASS or return $class; return $base_class if $class eq '::BASE::'; return "$base_class\::$class"; } sub member_fields { return (); } sub dispatch_class { my ($self, $field) = @_; my $table = $DispatchTable{ref $self}; my $class = exists($table->{$field}) ? $table->{$field} : $table->{'*'}; $class = &$class($self, $field) if UNIVERSAL::isa($class, 'CODE'); defined $class or return; if (my $members = $self->{parent}{callback_members}) { return unless $members->{$class}; } my $subclass = $self->classname($class) or return; return if $subclass eq $class; return $subclass; } sub require { my ($class, $module) = @_; return unless defined $module; my $file = "$module.pm"; $file =~ s{::}{/}g; return $module if (eval { require $file; 1 }); die $@ unless $@ =~ /^Can't locate /; return; } sub require_class { my ($class, $subclass) = @_; return $class->require($class->classname($subclass)); } sub format_list { my ($self) = @_; return $self->FORMAT; } sub subformat_list { my ($self) = @_; $self->SUBFORMAT ? $self->SUBFORMAT : (); } sub default_args { my ($self) = @_; $self->DEFAULT_ARGS ? $self->DEFAULT_ARGS : (); } sub dispatch_table { my ($self) = @_; $self->DISPATCH_TABLE ? { $self->DISPATCH_TABLE } : {}; } sub delegate_subs { my ($self) = @_; $self->DELEGATE_SUBS ? { $self->DELEGATE_SUBS } : {}; } sub class { my ($self) = @_; return(ref($self) || $self); } sub make_formatter { my ($self, @formats) = @_; return Parse::Binary::FixedFormat->new( $self->make_format(@formats) ); } sub make_format { my ($self, @formats) = @_; return \@formats unless grep /\{/, @formats; my @prefix; foreach my $format (@formats) { last if $format =~ /\{/; push @prefix, $format; } return { Chooser => sub { $self->chooser(@_) }, Formats => [ \@prefix, \@formats ], }; } sub chooser { my ($self, $rec, $obj, $mode) = @_; my $idx = @{$obj->{Layouts}}; my @format = $self->eval_format($rec, @{$obj->{Formats}[1]}); $obj->{Layouts}[$idx] = $self->make_formatter(@format); return $idx; } sub eval_format { my ($self, $rec, @format) = @_; foreach my $key (sort keys %$rec) { s/\$$key\b/$rec->{$key}/ for @format; } !/\$/ and s/\{(.*?)\}/$1/eeg for @format; die $@ if $@; return @format; } sub padding { return ''; } sub load_struct { my ($self, $data) = @_; $self->{struct} = $Parser{ref $self}->unformat($$data . $self->padding, $self->{lazy}, $self); } sub load_size { my ($self, $data) = @_; $self->{size} = length($$data); return 1; } sub lazy_load { my ($self) = @_; ref(my $sub = $self->{lazy}) or return; $self->{lazy} = 1; $self->make_members unless $self->{iterator}; } my %DispatchClass; sub load { my ($self, $data, $attr) = @_; return $self unless defined $data; no strict 'refs'; my $class = ref($self) || $self; $class->init unless ${"$class\::init_done"}; $self->load_struct($data); $self->load_size($data); if (my $field = $DispatchField{$class}) { if ( my $subclass = $DispatchClass{$class}{ $self->{struct}{$field} } ||= $self->dispatch_class( $self->{struct}{$field}) ) { $self->require($subclass); bless($self, $subclass); $self->load($data, $attr); } } return $self; } my (%classname, %fill_cache); sub spawn { my ($self, %args) = @_; my $class = ref($self) || $self; no strict 'refs'; if (my $subclass = delete($args{Class})) { $class = $classname{$subclass} ||= do { my $name = $self->classname($subclass); $self->require($name); $name->init; $name; }; } bless({ struct => { %args, @{ $DefaultArgs{$class} }, %{ $fill_cache{$class} ||= $class->fill_in }, }, }, $class); } sub fill_in { my $class = shift; my $entries = {}; foreach my $super_class ($class->superclasses) { my $field = $DispatchField{$super_class} or next; my $table = $DispatchTable{$super_class} or next; foreach my $code (reverse sort keys %$table) { $class->is_type($table->{$code}) or next; $entries->{$field} = $code; last; } } return $entries; } sub spawn_sibling { my ($self, %args) = @_; my $parent = $self->{parent} or die "$self has no parent"; my $obj = $self->spawn(%args); @{$obj}{qw( lazy parent output siblings )} = @{$self}{qw( lazy parent output siblings )}; $obj->{size} = length($obj->dump); $obj->refresh_parent; $obj->initialize; return $obj; } sub sibling_index { my ($self, $obj) = @_; $obj ||= $self; my @siblings = @{$self->{siblings}}; foreach my $index (($obj->{index}||0) .. $#siblings) { return $index if $obj == $siblings[$index]; } return undef; } sub gone { my ($self, $obj) = @_; $self->{parent}{struct}{Data} .= ($obj || $self)->dump; } sub prepend_obj { my ($self, %args) = @_; if ($self->{lazy}) { my $obj = $self->spawn(%args); $self->gone($obj); return; } my $obj = $self->spawn_sibling(%args); my $siblings = $self->{siblings}; my $index = $self->{index} ? $self->{index}++ : $self->sibling_index; $obj->{index} = $index; splice(@$siblings, $index, 0, $obj); return $obj; } sub append_obj { my ($self, %args) = @_; my $obj = $self->spawn_sibling(%args); @{$self->{siblings}} = ( map { $_, (($_ == $self) ? $obj : ()) } @{$self->{siblings}} ); return $obj; } sub remove { my ($self, %args) = @_; my $siblings = $self->{siblings}; splice(@$siblings, $self->sibling_index, 1, undef); Scalar::Util::weaken($self->{parent}); Scalar::Util::weaken($self); } sub read_data { my ($self, $data) = @_; return undef unless defined $data; return \($data->dump) if UNIVERSAL::can($data, 'dump'); return $data if UNIVERSAL::isa($data, 'SCALAR'); return \($self->read_file($data)); } sub read_file { my ($self, $file) = @_; local *FH; local $/; open FH, "< $file" or die "Cannot open $file for reading: $!"; binmode(FH); return scalar <FH>; } sub make_members { my ($self) = @_; $HasMembers{ref $self} or return; %{$self->{children}} = (); foreach my $field (@{$MemberFields{ref $self}}) { my ($format) = $self->eval_format( $self->{struct}, $FieldPackFormat{ref $self}{$field}, ); my $members = [ map { $self->new_member( $field, \pack($format, @$_) ) } $self->validate_memberdata($field) ]; $self->set_field_children( $field, $members ); } } sub set_members { my ($self, $field, $members) = @_; $field =~ s/:/_/g; $self->set_field_children( $field, [ map { $self->new_member( $field, $_ ) } @$members ], ); } sub set_field_children { my ($self, $field, $data) = @_; my $children = $self->field_children($field); @$children = @$data; return $children; } sub field_children { my ($self, $field) = @_; my $children = ($self->{children}{$field} ||= []); # $_->lazy_load for @$children; return(wantarray ? @$children : $children); } sub validate_memberdata { my ($self, $field) = @_; return @{$self->{struct}{$field}||[]}; } sub first_member { my ($self, $type) = @_; $self->lazy_load; return undef unless $HasMembers{ref $self}; no strict 'refs'; foreach my $field (@{$MemberFields{ref $self}}) { foreach my $member ($self->field_children($field)) { return $member if $member->is_type($type); } } return undef; } sub next_member { my ($self, $type) = @_; return undef unless $HasMembers{ref $self}; if ($self->{lazy} and !$self->{iterated}) { if (ref($self->{lazy})) { %{$self->{children}} = (); $self->{iterator} = $self->make_next_member; $self->lazy_load; } while (my $member = &{$self->{iterator}}) { return $member if $member->is_type($type); } $self->{iterated} = 1; return; } $self->{_next_member}{$type} ||= $self->members($type); shift(@{$self->{_next_member}{$type}}) || undef($self->{_next_member}{$type}); } sub make_next_member { my $self = shift; my $class = ref($self); my ($field_idx, $item_idx, $format) = (0, 0, undef); my @fields = @{$MemberFields{$class}}; my $struct = $self->{struct}; my $formats = $FieldPackFormat{$class}; sub { LOOP: { my $field = $fields[$field_idx] or return; my $items = $struct->{$field}; if ($item_idx > $#$items) { $field_idx++; $item_idx = 0; undef $format; redo; } $format ||= ($self->eval_format( $struct, $formats->{$field} ))[0]; my $item = $items->[$item_idx++]; $item = $item->($self, $items) if UNIVERSAL::isa($item, 'CODE'); $self->valid_memberdata($item) or redo; my $member = $self->new_member( $field, \pack($format, @$item) ); $member->{index} = (push @{$self->{children}{$field}}, $member) - 1; return $member; } }; } sub members { my ($self, $type) = @_; $self->lazy_load; no strict 'refs'; my @members = map { grep { $type ? $_->is_type($type) : 1 } $self->field_children($_) } @{$MemberFields{ref $self}}; wantarray ? @members : \@members; } sub members_recursive { my ($self, $type) = @_; my @members = ( ( $self->is_type($type) ? $self : () ), map { $_->members_recursive($type) } $self->members ); wantarray ? @members : \@members; } sub new_member { my ($self, $field, $data) = @_; my $obj = $MemberClass{ref $self}{$field}->new( $data, { lazy => $self->{lazy}, parent => $self } ); $obj->{output} = $self->{output}; $obj->{siblings} = $self->{children}{$field}||=[]; $obj->initialize; return $obj; } sub valid_memberdata { length($_[-1][0]) } sub dump_members { my ($self) = @_; return $Packer{ref $self}->format($self->{struct}); } sub dump { my ($self) = @_; return $self->dump_members if $HasMembers{ref $self}; return $Packer{ref $self}->format($self->{struct}); } sub write { my ($self, $file) = @_; if (ref($file)) { $$file = $self->dump; } elsif (!defined($file) and my $fh = $self->{output}) { print $fh $self->dump; } else { $file = $self->{filename} unless defined $file; $self->write_file($file, $self->dump) if defined $file; } } sub write_file { my ($self, $file, $data) = @_; local *FH; open FH, "> $file" or die "Cannot open $file for writing: $!"; binmode(FH); print FH $data; }; sub superclasses { my ($self) = @_; my $class = $self->class; no strict 'refs'; return @{"$class\::ISA"}; } my %type_cache; sub is_type { my ($self, $type) = @_; return 1 unless defined $type; my $class = ref($self) || $self; if (exists $type_cache{$class}{$type}) { return $type_cache{$class}{$type}; } $type_cache{$class}{$type} = 1; $type =~ s/__/::/g; $type =~ s/[^\w:]//g; return 1 if ($class =~ /::$type$/); no strict 'refs'; foreach my $super_class ($class->superclasses) { return 1 if $super_class->is_type($type); }; $type_cache{$class}{$type} = 0; } sub refresh { my ($self) = @_; foreach my $field (@{$MemberFields{ref $self}}) { my $parser = $self->field_parser($field); my $padding = $self->padding; local $SIG{__WARN__} = sub {}; @{$self->{struct}{$field}} = map { $parser->unformat( $_->dump . $padding, 0, $self)->{$field}[0] } grep defined, @{$self->{children}{$field}||[]}; $self->validate_memberdata; } $self->refresh_parent; } sub refresh_parent { my ($self) = @_; my $parent = $self->{parent} or return; $parent->refresh unless !Scalar::Util::blessed($parent) or $parent->{lazy}; } sub first_parent { my ($self, $type) = @_; return $self if $self->is_type($type); my $parent = $self->{parent} or return; return $parent->first_parent($type); } sub substr { my $self = shift; my $data = $self->Data; my $offset = shift(@_) - ($self->{size} - length($data)); my $length = @_ ? shift(@_) : (length($data) - $offset); my $replace = shift; # XXX - Check for "substr outside string" return if $offset > length($data); # Fetch a range return substr($data, $offset, $length) if !defined $replace; # Substitute a range substr($data, $offset, $length, $replace); $self->{struct}{Data} = $data; } sub set_output_file { my ($self, $file) = @_; open my $fh, '>', $file or die $!; binmode($fh); $self->{output} = $fh; } my %callback_map; sub callback { my $self = shift; my $pkg = shift || caller; my $types = shift or return; my $map = $callback_map{"@$types"} ||= $self->callback_map($pkg, $types); my $sub = $map->{ref $self} || $map->{'*'} or return; unshift @_, $self; goto &$sub; } sub callback_map { my ($self, $pkg, $types) = @_; my %map; my $base = $self->BASE_CLASS; foreach my $type (map "$_", @$types) { no strict 'refs'; my $method = $type; $method =~ s/::/_/g; $method =~ s/\*/__/g; defined &{"$pkg\::$method"} or next; $type = "$base\::$type" unless $type eq '*'; $map{$type} = \&{"$pkg\::$method"}; } return \%map; } sub callback_members { my $self = shift; $self->{callback_members} = { map { ($_ => 1) } @{$_[0]} }; while (my $member = $self->next_member) { $member->callback(scalar caller, @_); } } sub done { my $self = shift; return unless $self->{lazy}; $self->write; $self->remove; } 1; __END__ =head1 AUTHORS Audrey Tang E<lt>cpan@audreyt.orgE<gt> =head1 COPYRIGHT Copyright 2004-2009 by Audrey Tang E<lt>cpan@audreyt.orgE<gt>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L<http://www.perl.com/perl/misc/Artistic.html> =cut
liuyangning/WX_web
xampp/perl/vendor/lib/Parse/Binary.pm
Perl
mit
23,243
# -*- Mode: Perl -*- # # BlankNode.pm - Redland Perl RDF Blank Node module # # $Id: BlankNode.pm 10593 2006-03-05 08:30:38Z dajobe $ # # Copyright (C) 2005 David Beckett - http://purl.org/net/dajobe/ # Copyright (C) 2005 University of Bristol - http://www.bristol.ac.uk/ # # This package is Free Software or Open Source available under the # following licenses (these are alternatives): # 1. GNU Lesser General Public License (LGPL) # 2. GNU General Public License (GPL) # 3. Mozilla Public License (MPL) # # See LICENSE.html or LICENSE.txt at the top of this package for the # full license terms. # # # package RDF::Redland::BlankNode; use strict; use vars qw(@ISA); @ISA='RDF::Redland::Node'; =pod =head1 NAME RDF::Redland::BlankNode - Redland RDF Blank Node Class =head1 SYNOPSIS use RDF::Redland; my $node1=new RDF::Redland::BlankNode("id"); =head1 DESCRIPTION This class represents a blank nodes in the RDF graph. See L<RDF::Redland::Node> for the methods on this object. =cut ###################################################################### =pod =head1 CONSTRUCTOR =over =item new IDENTIFIER Create a new blank node with identifier I<IDENTIFIER>. =cut # CONSTRUCTOR sub new ($$) { my($proto,$arg)=@_; my $class = ref($proto) || $proto; my $self = {}; return RDF::Redland::Node->new_from_blank_identifier($arg); } =back =head1 SEE ALSO L<RDF::Redland::Node> =head1 AUTHOR Dave Beckett - http://purl.org/net/dajobe/ =cut 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/RDF/Redland/BlankNode.pm
Perl
mit
1,487
package O2::Template::Node::O2EndTag; use strict; use base 'O2::Template::Node'; 1;
haakonsk/O2-Framework
lib/O2/Template/Node/O2EndTag.pm
Perl
mit
87
use strict; use Data::Dumper; use Carp; # # This is a SAS Component # =head1 NAME all_entities_ProteinSequence =head1 SYNOPSIS all_entities_ProteinSequence [-a] [--fields fieldlist] > entity-data =head1 DESCRIPTION Return all instances of the ProteinSequence entity. We use the concept of ProteinSequence as an amino acid string with an associated MD5 value. It is easy to access the set of Features that relate to a ProteinSequence. While function is still associated with Features (and may be for some time), publications are associated with ProteinSequences (and the inferred impact on Features is through the relationship connecting ProteinSequences to Features). Example: all_entities_ProteinSequence -a would retrieve all entities of type ProteinSequence and include all fields in the entities in the output. =head2 Related entities The ProteinSequence entity has the following relationship links: =over 4 =item HasAssertedFunctionFrom Source =item HasConservedDomainModel ConservedDomainModel =item IsATopicOf Publication =item IsAlignedProteinComponentOf AlignmentRow =item IsProteinFor Feature =item IsProteinMemberOf Family =back =head1 COMMAND-LINE OPTIONS Usage: all_entities_ProteinSequence [arguments] > entity.data --fields list Choose a set of fields to return. List is a comma-separated list of strings. -a Return all available fields. --show-fields List the available fields. The following fields are available: =over 4 =item sequence The sequence contains the letters corresponding to the protein's amino acids. =back =head1 AUTHORS L<The SEED Project|http://www.theseed.org> =cut use Bio::KBase::CDMI::CDMIClient; use Getopt::Long; #Default fields my @all_fields = ( 'sequence' ); my %all_fields = map { $_ => 1 } @all_fields; our $usage = <<'END'; Usage: all_entities_ProteinSequence [arguments] > entity.data --fields list Choose a set of fields to return. List is a comma-separated list of strings. -a Return all available fields. --show-fields List the available fields. The following fields are available: sequence The sequence contains the letters corresponding to the protein's amino acids. END my $a; my $f; my @fields; my $show_fields; my $help; my $geO = Bio::KBase::CDMI::CDMIClient->new_get_entity_for_script("a" => \$a, "show-fields" => \$show_fields, "h" => \$help, "fields=s" => \$f); if ($help) { print $usage; exit 0; } if ($show_fields) { print "Available fields:\n"; print "\t$_\n" foreach @all_fields; exit 0; } if (@ARGV != 0 || ($a && $f)) { print STDERR $usage, "\n"; exit 1; } if ($a) { @fields = @all_fields; } elsif ($f) { my @err; for my $field (split(",", $f)) { if (!$all_fields{$field}) { push(@err, $field); } else { push(@fields, $field); } } if (@err) { print STDERR "all_entities_ProteinSequence: unknown fields @err. Valid fields are: @all_fields\n"; exit 1; } } my $start = 0; my $count = 1_000_000; my $h = $geO->all_entities_ProteinSequence($start, $count, \@fields ); while (%$h) { while (my($k, $v) = each %$h) { print join("\t", $k, map { ref($_) eq 'ARRAY' ? join(",", @$_) : $_ } @$v{@fields}), "\n"; } $start += $count; $h = $geO->all_entities_ProteinSequence($start, $count, \@fields); }
kbase/kb_seed
scripts/all_entities_ProteinSequence.pl
Perl
mit
3,409
package fasta; use strict; use warnings; sub new { my $class = shift; my $self = bless {}, $class; print "INFILE ",$_[0],"\n"; $self->{inFile} = $_[0]; ($self->{cmap}, $self->{sta}) = &genChromos($_[0]); return $self; } sub readFasta { my $self = shift; my $inputFA = $self->{inFile}; my $chromosMap = $self->{cmap}; my $chromName = $_[0]; my @gene; my $desiredLine; $chromName =~ s/_bb$//; # print "READING FASTA $chromNum\n"; if ( $chromName =~ /[\w+]/) { if ( ! eval { $desiredLine = $chromosMap->{$chromName} } ) { die "CHROMOSSOME \"$chromName\" NOT FOUND IN FASTA"; } } die "NO POSITION FOUND FOR $chromName" if ( ! defined $desiredLine ); #$gene[0] = ""; open FILE, "<$inputFA" or die "COULD NOT OPEN $inputFA: $!"; my $current; my $chromoName; my $on = 0; my $pos = 0; my $line = 1; # print "DESIRE $desiredLine $chromName\n"; my $leng = 0; seek(FILE, $desiredLine-200, 0); while (<FILE>) { # if ($line >= $desiredLine) # { chomp; s/\015//; if (( /^>/) && ($on)) { $on = 0; $pos = 1; #print "LAST LINE :: \"$_\"\n"; last; } elsif ($on) { $leng += length $_; #print "LINE [$line] \"$_\" IS \"", length $_, "\" LONG ($leng) \n"; push(@gene,split("",$_)); } elsif (/^>$chromName/) { #print "FIRST LINE [$line]:: \"$_\"\n"; $on = 1; $pos = 1; } $line++; } close FILE; print "\t\t\tGENE $chromName HAS ", scalar @gene, " bp\n"; if ( ! @gene ) { die "NO GENE READ\n";}; return \@gene; # return \%XMLpos; } sub genChromos { my $inputFA = $_[0]; my $on = 0; my $chromo; my $total; open FILE, "<$inputFA" or die "COULD NOT OPEN $inputFA: $!"; my $pos = 0; my $line = 1; my $current; # my $tell = 0; my %chromos; my %stat; my %chromosMap; while (<FILE>) { chomp; s/\015//; if ( /^>/) { $on = 0; $pos = 1; } if ($on) { $stat{$chromo}{size} += length $_; } if (/^>(.*)/) { $on = 1; $pos = 1; $chromo = $1; $chromosMap{$chromo} = tell(FILE); $stat{$chromo}{pos} = tell(FILE); $stat{$chromo}{size} = 0; # $chromosMap{$chromo} = $line; } $line++; } undef $chromo; close FILE; &printChromStat(\%stat); return (\%chromosMap, \%stat); } sub printChromStat { my $stat = $_[0]; foreach my $chromName (sort keys %$stat) { printf "\tCHROM \"%s\"", $chromName; foreach my $key (sort keys %{$stat->{$chromName}}) { my $value = $stat->{$chromName}{$key}; printf " %4s => %9d", $key, $value; } print "\n"; } } 1;
sauloal/perlscripts
Bio/toCheck/loadfasta1.pm
Perl
mit
3,229
=pod =head1 NAME llvm-prof - print execution profile of LLVM program =head1 SYNOPSIS B<llvm-prof> [I<options>] [I<bitcode file>] [I<llvmprof.out>] =head1 DESCRIPTION The B<llvm-prof> tool reads in an F<llvmprof.out> file (which can optionally use a specific file with the third program argument), a bitcode file for the program, and produces a human readable report, suitable for determining where the program hotspots are. This program is often used in conjunction with the F<utils/profile.pl> script. This script automatically instruments a program, runs it with the JIT, then runs B<llvm-prof> to format a report. To get more information about F<utils/profile.pl>, execute it with the B<-help> option. =head1 OPTIONS =over =item B<--annotated-llvm> or B<-A> In addition to the normal report printed, print out the code for the program, annotated with execution frequency information. This can be particularly useful when trying to visualize how frequently basic blocks are executed. This is most useful with basic block profiling information or better. =item B<--print-all-code> Using this option enables the B<--annotated-llvm> option, but it prints the entire module, instead of just the most commonly executed functions. =item B<--time-passes> Record the amount of time needed for each pass and print it to standard error. =back =head1 EXIT STATUS B<llvm-prof> returns 1 if it cannot load the bitcode file or the profile information. Otherwise, it exits with zero. =head1 AUTHOR B<llvm-prof> is maintained by the LLVM Team (L<http://llvm.org/>). =cut
abduld/clreflect
extern/llvm/docs/CommandGuide/llvm-prof.pod
Perl
mit
1,638
/********************************************************************** name: presupDRT.pl (Volume 2, Chapter 4) version: May 5, 1998 description: Presupposition Projection authors: Patrick Blackburn & Johan Bos **********************************************************************/ :- module(presupDRT,[presupDRT/0, presupDRT/2, presupDRT/3, presupDRTTestSuite/0]). :- use_module(readLine,[readLine/1]). :- use_module(comsemPredicates,[compose/3, printRepresentations/1]). :- ensure_loaded(comsemOperators). :- use_module(drsPredicates,[mergeDrs/2,betaConvertDrs/2]). :- use_module(resolvePresup,[projectDrs/1,accommodate/2]). :- [englishGrammar]. :- [discourseGrammar]. :- use_module(discourseTestSuite,[discourse/1]). /*======================================================================== Driver Predicate ========================================================================*/ presupDRT:- readLine(Discourse), setof(DRS,d2(DRS,Discourse,[]),DRSs), printRepresentations(DRSs). presupDRT(Discourse,DRSs):- setof(DRS,d2(DRS,Discourse,[]),DRSs). presupDRT(Discourse,OldDrs,NewDrs):- d1(CurrentDrs,Discourse,[]), combine(d2:NewDrs,[d1:merge(OldDrs,CurrentDrs)]). /*======================================================================== Testsuite Predicates ========================================================================*/ :-export(presupDRTTestSuite/0). presupDRTTestSuite:- format('~n>>>>> PRESUP DRT ON DISCOURE TEST SUITE <<<<<~n',[]), discourse(Discourse), format('~nDiscourse: ~p',[Discourse]), presupDRT(Discourse,DRSs), printRepresentations(DRSs), fail. presupDRTTestSuite. /*======================================================================== Semantic Rules ========================================================================*/ combine(d2:D,[d1:A]):- betaConvertDrs(A,B), projectDrs([B,pre([])]-[C,pre(P)]), accommodate(P,C-D). combine(d1:A,[s2:A]). combine(d1:merge(A,B),[s2:A,conj,d1:B]). combine(d1:drs([],[A v B]),[s2:A,disj,d1:B]). combine(s2:A,[s1:A]). combine(s2:drs([],[A>B]),[s1:A,cond,s1:B]). combine(s1:(A@B),[np2:A,vp2:B]). combine(np2:A,[np1:A]). combine(np2:((B@A)@C),[np1:A,coord:B,np1:C]). combine(np1:(A@B),[det:A,n2:B]). combine(np1:A,[pn:A]). combine(np1:A,[pro:A]). combine(np1:A,[np:A]). combine(n2:A,[n1:A]). combine(n2:((B@A)@C),[n1:A,coord:B,n1:C]). combine(n1:(A@B),[adj:A,n1:B]). combine(n1:A,[noun:A]). combine(n1:(B@A),[noun:A,pp:B]). combine(n1:(B@A),[noun:A,rc:B]). combine(vp2:A,[vp1:A]). combine(vp2:((B@A)@C),[vp1:A,coord:B,vp1:C]). combine(vp1:A,[v2:A]). combine(vp1:(A@B),[mod:A,v2:B]). combine(v2:(A@B),[cop:A,np2:B]). combine(v2:(C@(A@B)),[cop:A,neg:C,np2:B]). combine(v2:A,[v1:A]). combine(v2:((B@A)@C),[v1:A,coord:B,v1:C]). combine(v1:A,[iv:A]). combine(v1:(A@B),[tv:A,np2:B]). combine(pp:(A@B),[prep:A,np2:B]). combine(rc:(A@B),[relpro:A,vp2:B]). /*======================================================================== Semantic Macros ========================================================================*/ detSem(uni,lambda(P,lambda(Q,drs([],[merge(drs([X],[]),P@X)>(Q@X)])))). detSem(indef,lambda(P,lambda(Q,merge(merge(drs([X],[]),P@X),Q@X)))). detSem(def,lambda(P,lambda(Q,alfa(X,def,merge(drs([X],[]),P@X),Q@X)))). detSem(wh,lambda(P,lambda(Q,drs([],[question(X,P@X,Q@X)])))). detSem(poss(Gender),lambda(P,lambda(Q, alfa(Y,def,alfa(X,nonrefl,drs([X],[Basic]), merge(drs([Y],[of(Y,X)]),P@Y)),Q@Y)))):- compose(Basic,Gender,[X]). nounSem(Sym,lambda(X,drs([],[Cond]))):- compose(Cond,Sym,[X]). pnSem(Sym,Gender,lambda(P,alfa(X,name,drs([X],[X=Sym,Cond]),P@X))):- compose(Cond,Gender,[X]). proSem(Gender,Type,lambda(P,alfa(X,Type,drs([X],[Cond]),P@X))):- compose(Cond,Gender,[X]). npSem(wh,Sym,lambda(Q,drs([],[question(X,drs([],[Cond]),Q@X)]))):- compose(Cond,Sym,[X]). ivSem(Sym,lambda(X,drs([],[Cond]))):- compose(Cond,Sym,[X]). tvSem(Sym,lambda(K,lambda(Y,K @ lambda(X,drs([],[Cond]))))):- compose(Cond,Sym,[Y,X]). relproSem(lambda(P1,lambda(P2,lambda(X,merge(P1@X,P2@X))))). prepSem(Sym,lambda(K,lambda(P,lambda(Y,Drs)))):- Drs=merge(K@lambda(X,drs([],[Cond])),P@Y), compose(Cond,Sym,[Y,X]). adjSem(Sym,lambda(P,lambda(X,merge(drs([],[Cond]),(P@X))))):- compose(Cond,Sym,[X]). modSem(neg,lambda(P,lambda(X,drs([],[~(P @ X)])))). coordSem(conj,lambda(X,lambda(Y,lambda(P,merge(X@P,Y@P))))). coordSem(disj,lambda(X,lambda(Y,lambda(P,drs([],[(X@P) v (Y@P)]))))).
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/CURT/bb0/presupDRT.pl
Perl
mit
4,587
### # Utility # @version 1.0 # @see # programmed by D.Kim ## package Overwhelm::Util; use strict; use warnings; use Overwhelm::Exception; use Overwhelm::Const; use POSIX qw(strftime); BEGIN { use Exporter; use vars qw(@ISA); @ISA = qw(Exporter); } ### # Constructor ## sub new { new Overwhelm::Exception("This is a Static Class.\n"); } ### # Use Multi-Thread or Not # @return true or false ## sub hasThread { return $Overwhelm::Const::USE_THREAD; } 1; __END__
edydkim/Simple-Framework
Overwhelm/Util.pm
Perl
mit
486
use utf8; package Schema::Result::Menu; # Created by DBIx::Class::Schema::Loader # DO NOT MODIFY THE FIRST PART OF THIS FILE =head1 NAME Schema::Result::Menu =cut use strict; use warnings; use base 'DBIx::Class::Core'; =head1 TABLE: C<menu> =cut __PACKAGE__->table("menu"); =head1 ACCESSORS =head2 id data_type: 'integer' is_auto_increment: 1 is_nullable: 0 sequence: 'menu_id_seq' =head2 menu_type_id data_type: 'integer' is_foreign_key: 1 is_nullable: 1 =head2 page_id data_type: 'integer' is_foreign_key: 1 is_nullable: 1 =head2 name data_type: 'varchar' is_nullable: 1 size: 100 =head2 position data_type: 'integer' is_nullable: 1 =cut __PACKAGE__->add_columns( "id", { data_type => "integer", is_auto_increment => 1, is_nullable => 0, sequence => "menu_id_seq", }, "menu_type_id", { data_type => "integer", is_foreign_key => 1, is_nullable => 1 }, "page_id", { data_type => "integer", is_foreign_key => 1, is_nullable => 1 }, "name", { data_type => "varchar", is_nullable => 1, size => 100 }, "position", { data_type => "integer", is_nullable => 1 }, ); =head1 PRIMARY KEY =over 4 =item * L</id> =back =cut __PACKAGE__->set_primary_key("id"); =head1 RELATIONS =head2 menu_type Type: belongs_to Related object: L<Schema::Result::MenuType> =cut __PACKAGE__->belongs_to( "menu_type", "Schema::Result::MenuType", { id => "menu_type_id" }, { is_deferrable => 0, join_type => "LEFT", on_delete => "NO ACTION", on_update => "NO ACTION", }, ); =head2 page Type: belongs_to Related object: L<Schema::Result::Page> =cut __PACKAGE__->belongs_to( "page", "Schema::Result::Page", { id => "page_id" }, { is_deferrable => 0, join_type => "LEFT", on_delete => "NO ACTION", on_update => "NO ACTION", }, ); # Created by DBIx::Class::Schema::Loader v0.07033 @ 2013-10-16 00:16:36 # DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:ddgNmWcg9Fpe0trj8U6PrA # You can replace this text with custom code or comments, and it will be preserved on regeneration 1;
Nikolo/Margarita
lib/Schema/Result/Menu.pm
Perl
mit
2,148
# 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/Q713JNUf8G/northamerica. Olson data version 2016a # # Do not edit this file directly. # package DateTime::TimeZone::America::Port_au_Prince; $DateTime::TimeZone::America::Port_au_Prince::VERSION = '1.95'; use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::Port_au_Prince::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 59611178960, # utc_end 1890-01-01 04:49:20 (Wed) DateTime::TimeZone::NEG_INFINITY, # local_start 59611161600, # local_end 1890-01-01 00:00:00 (Wed) -17360, 0, 'LMT', ], [ 59611178960, # utc_start 1890-01-01 04:49:20 (Wed) 60465199740, # utc_end 1917-01-24 16:49:00 (Wed) 59611161620, # local_start 1890-01-01 00:00:20 (Wed) 60465182400, # local_end 1917-01-24 12:00:00 (Wed) -17340, 0, 'PPMT', ], [ 60465199740, # utc_start 1917-01-24 16:49:00 (Wed) 62556901200, # utc_end 1983-05-08 05:00:00 (Sun) 60465181740, # local_start 1917-01-24 11:49:00 (Wed) 62556883200, # local_end 1983-05-08 00:00:00 (Sun) -18000, 0, 'EST', ], [ 62556901200, # utc_start 1983-05-08 05:00:00 (Sun) 62572017600, # utc_end 1983-10-30 04:00:00 (Sun) 62556886800, # local_start 1983-05-08 01:00:00 (Sun) 62572003200, # local_end 1983-10-30 00:00:00 (Sun) -14400, 1, 'EDT', ], [ 62572017600, # utc_start 1983-10-30 04:00:00 (Sun) 62587746000, # utc_end 1984-04-29 05:00:00 (Sun) 62571999600, # local_start 1983-10-29 23:00:00 (Sat) 62587728000, # local_end 1984-04-29 00:00:00 (Sun) -18000, 0, 'EST', ], [ 62587746000, # utc_start 1984-04-29 05:00:00 (Sun) 62603467200, # utc_end 1984-10-28 04:00:00 (Sun) 62587731600, # local_start 1984-04-29 01:00:00 (Sun) 62603452800, # local_end 1984-10-28 00:00:00 (Sun) -14400, 1, 'EDT', ], [ 62603467200, # utc_start 1984-10-28 04:00:00 (Sun) 62619195600, # utc_end 1985-04-28 05:00:00 (Sun) 62603449200, # local_start 1984-10-27 23:00:00 (Sat) 62619177600, # local_end 1985-04-28 00:00:00 (Sun) -18000, 0, 'EST', ], [ 62619195600, # utc_start 1985-04-28 05:00:00 (Sun) 62634916800, # utc_end 1985-10-27 04:00:00 (Sun) 62619181200, # local_start 1985-04-28 01:00:00 (Sun) 62634902400, # local_end 1985-10-27 00:00:00 (Sun) -14400, 1, 'EDT', ], [ 62634916800, # utc_start 1985-10-27 04:00:00 (Sun) 62650645200, # utc_end 1986-04-27 05:00:00 (Sun) 62634898800, # local_start 1985-10-26 23:00:00 (Sat) 62650627200, # local_end 1986-04-27 00:00:00 (Sun) -18000, 0, 'EST', ], [ 62650645200, # utc_start 1986-04-27 05:00:00 (Sun) 62666366400, # utc_end 1986-10-26 04:00:00 (Sun) 62650630800, # local_start 1986-04-27 01:00:00 (Sun) 62666352000, # local_end 1986-10-26 00:00:00 (Sun) -14400, 1, 'EDT', ], [ 62666366400, # utc_start 1986-10-26 04:00:00 (Sun) 62682094800, # utc_end 1987-04-26 05:00:00 (Sun) 62666348400, # local_start 1986-10-25 23:00:00 (Sat) 62682076800, # local_end 1987-04-26 00:00:00 (Sun) -18000, 0, 'EST', ], [ 62682094800, # utc_start 1987-04-26 05:00:00 (Sun) 62697816000, # utc_end 1987-10-25 04:00:00 (Sun) 62682080400, # local_start 1987-04-26 01:00:00 (Sun) 62697801600, # local_end 1987-10-25 00:00:00 (Sun) -14400, 1, 'EDT', ], [ 62697816000, # utc_start 1987-10-25 04:00:00 (Sun) 62711733600, # utc_end 1988-04-03 06:00:00 (Sun) 62697798000, # local_start 1987-10-24 23:00:00 (Sat) 62711715600, # local_end 1988-04-03 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62711733600, # utc_start 1988-04-03 06:00:00 (Sun) 62729877600, # utc_end 1988-10-30 06:00:00 (Sun) 62711719200, # local_start 1988-04-03 02:00:00 (Sun) 62729863200, # local_end 1988-10-30 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62729877600, # utc_start 1988-10-30 06:00:00 (Sun) 62743183200, # utc_end 1989-04-02 06:00:00 (Sun) 62729859600, # local_start 1988-10-30 01:00:00 (Sun) 62743165200, # local_end 1989-04-02 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62743183200, # utc_start 1989-04-02 06:00:00 (Sun) 62761327200, # utc_end 1989-10-29 06:00:00 (Sun) 62743168800, # local_start 1989-04-02 02:00:00 (Sun) 62761312800, # local_end 1989-10-29 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62761327200, # utc_start 1989-10-29 06:00:00 (Sun) 62774632800, # utc_end 1990-04-01 06:00:00 (Sun) 62761309200, # local_start 1989-10-29 01:00:00 (Sun) 62774614800, # local_end 1990-04-01 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62774632800, # utc_start 1990-04-01 06:00:00 (Sun) 62792776800, # utc_end 1990-10-28 06:00:00 (Sun) 62774618400, # local_start 1990-04-01 02:00:00 (Sun) 62792762400, # local_end 1990-10-28 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62792776800, # utc_start 1990-10-28 06:00:00 (Sun) 62806687200, # utc_end 1991-04-07 06:00:00 (Sun) 62792758800, # local_start 1990-10-28 01:00:00 (Sun) 62806669200, # local_end 1991-04-07 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62806687200, # utc_start 1991-04-07 06:00:00 (Sun) 62824226400, # utc_end 1991-10-27 06:00:00 (Sun) 62806672800, # local_start 1991-04-07 02:00:00 (Sun) 62824212000, # local_end 1991-10-27 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62824226400, # utc_start 1991-10-27 06:00:00 (Sun) 62838136800, # utc_end 1992-04-05 06:00:00 (Sun) 62824208400, # local_start 1991-10-27 01:00:00 (Sun) 62838118800, # local_end 1992-04-05 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62838136800, # utc_start 1992-04-05 06:00:00 (Sun) 62855676000, # utc_end 1992-10-25 06:00:00 (Sun) 62838122400, # local_start 1992-04-05 02:00:00 (Sun) 62855661600, # local_end 1992-10-25 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62855676000, # utc_start 1992-10-25 06:00:00 (Sun) 62869586400, # utc_end 1993-04-04 06:00:00 (Sun) 62855658000, # local_start 1992-10-25 01:00:00 (Sun) 62869568400, # local_end 1993-04-04 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62869586400, # utc_start 1993-04-04 06:00:00 (Sun) 62887730400, # utc_end 1993-10-31 06:00:00 (Sun) 62869572000, # local_start 1993-04-04 02:00:00 (Sun) 62887716000, # local_end 1993-10-31 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62887730400, # utc_start 1993-10-31 06:00:00 (Sun) 62901036000, # utc_end 1994-04-03 06:00:00 (Sun) 62887712400, # local_start 1993-10-31 01:00:00 (Sun) 62901018000, # local_end 1994-04-03 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62901036000, # utc_start 1994-04-03 06:00:00 (Sun) 62919180000, # utc_end 1994-10-30 06:00:00 (Sun) 62901021600, # local_start 1994-04-03 02:00:00 (Sun) 62919165600, # local_end 1994-10-30 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62919180000, # utc_start 1994-10-30 06:00:00 (Sun) 62932485600, # utc_end 1995-04-02 06:00:00 (Sun) 62919162000, # local_start 1994-10-30 01:00:00 (Sun) 62932467600, # local_end 1995-04-02 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62932485600, # utc_start 1995-04-02 06:00:00 (Sun) 62950629600, # utc_end 1995-10-29 06:00:00 (Sun) 62932471200, # local_start 1995-04-02 02:00:00 (Sun) 62950615200, # local_end 1995-10-29 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62950629600, # utc_start 1995-10-29 06:00:00 (Sun) 62964540000, # utc_end 1996-04-07 06:00:00 (Sun) 62950611600, # local_start 1995-10-29 01:00:00 (Sun) 62964522000, # local_end 1996-04-07 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62964540000, # utc_start 1996-04-07 06:00:00 (Sun) 62982079200, # utc_end 1996-10-27 06:00:00 (Sun) 62964525600, # local_start 1996-04-07 02:00:00 (Sun) 62982064800, # local_end 1996-10-27 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 62982079200, # utc_start 1996-10-27 06:00:00 (Sun) 62995989600, # utc_end 1997-04-06 06:00:00 (Sun) 62982061200, # local_start 1996-10-27 01:00:00 (Sun) 62995971600, # local_end 1997-04-06 01:00:00 (Sun) -18000, 0, 'EST', ], [ 62995989600, # utc_start 1997-04-06 06:00:00 (Sun) 63013528800, # utc_end 1997-10-26 06:00:00 (Sun) 62995975200, # local_start 1997-04-06 02:00:00 (Sun) 63013514400, # local_end 1997-10-26 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63013528800, # utc_start 1997-10-26 06:00:00 (Sun) 63248187600, # utc_end 2005-04-03 05:00:00 (Sun) 63013510800, # local_start 1997-10-26 01:00:00 (Sun) 63248169600, # local_end 2005-04-03 00:00:00 (Sun) -18000, 0, 'EST', ], [ 63248187600, # utc_start 2005-04-03 05:00:00 (Sun) 63266328000, # utc_end 2005-10-30 04:00:00 (Sun) 63248173200, # local_start 2005-04-03 01:00:00 (Sun) 63266313600, # local_end 2005-10-30 00:00:00 (Sun) -14400, 1, 'EDT', ], [ 63266328000, # utc_start 2005-10-30 04:00:00 (Sun) 63279637200, # utc_end 2006-04-02 05:00:00 (Sun) 63266310000, # local_start 2005-10-29 23:00:00 (Sat) 63279619200, # local_end 2006-04-02 00:00:00 (Sun) -18000, 0, 'EST', ], [ 63279637200, # utc_start 2006-04-02 05:00:00 (Sun) 63297777600, # utc_end 2006-10-29 04:00:00 (Sun) 63279622800, # local_start 2006-04-02 01:00:00 (Sun) 63297763200, # local_end 2006-10-29 00:00:00 (Sun) -14400, 1, 'EDT', ], [ 63297777600, # utc_start 2006-10-29 04:00:00 (Sun) 63467132400, # utc_end 2012-03-11 07:00:00 (Sun) 63297759600, # local_start 2006-10-28 23:00:00 (Sat) 63467114400, # local_end 2012-03-11 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63467132400, # utc_start 2012-03-11 07:00:00 (Sun) 63487692000, # utc_end 2012-11-04 06:00:00 (Sun) 63467118000, # local_start 2012-03-11 03:00:00 (Sun) 63487677600, # local_end 2012-11-04 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63487692000, # utc_start 2012-11-04 06:00:00 (Sun) 63498582000, # utc_end 2013-03-10 07:00:00 (Sun) 63487674000, # local_start 2012-11-04 01:00:00 (Sun) 63498564000, # local_end 2013-03-10 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63498582000, # utc_start 2013-03-10 07:00:00 (Sun) 63519141600, # utc_end 2013-11-03 06:00:00 (Sun) 63498567600, # local_start 2013-03-10 03:00:00 (Sun) 63519127200, # local_end 2013-11-03 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63519141600, # utc_start 2013-11-03 06:00:00 (Sun) 63530031600, # utc_end 2014-03-09 07:00:00 (Sun) 63519123600, # local_start 2013-11-03 01:00:00 (Sun) 63530013600, # local_end 2014-03-09 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63530031600, # utc_start 2014-03-09 07:00:00 (Sun) 63550591200, # utc_end 2014-11-02 06:00:00 (Sun) 63530017200, # local_start 2014-03-09 03:00:00 (Sun) 63550576800, # local_end 2014-11-02 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63550591200, # utc_start 2014-11-02 06:00:00 (Sun) 63561481200, # utc_end 2015-03-08 07:00:00 (Sun) 63550573200, # local_start 2014-11-02 01:00:00 (Sun) 63561463200, # local_end 2015-03-08 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63561481200, # utc_start 2015-03-08 07:00:00 (Sun) 63582040800, # utc_end 2015-11-01 06:00:00 (Sun) 63561466800, # local_start 2015-03-08 03:00:00 (Sun) 63582026400, # local_end 2015-11-01 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63582040800, # utc_start 2015-11-01 06:00:00 (Sun) 63593535600, # utc_end 2016-03-13 07:00:00 (Sun) 63582022800, # local_start 2015-11-01 01:00:00 (Sun) 63593517600, # local_end 2016-03-13 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63593535600, # utc_start 2016-03-13 07:00:00 (Sun) 63614095200, # utc_end 2016-11-06 06:00:00 (Sun) 63593521200, # local_start 2016-03-13 03:00:00 (Sun) 63614080800, # local_end 2016-11-06 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63614095200, # utc_start 2016-11-06 06:00:00 (Sun) 63624985200, # utc_end 2017-03-12 07:00:00 (Sun) 63614077200, # local_start 2016-11-06 01:00:00 (Sun) 63624967200, # local_end 2017-03-12 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63624985200, # utc_start 2017-03-12 07:00:00 (Sun) 63645544800, # utc_end 2017-11-05 06:00:00 (Sun) 63624970800, # local_start 2017-03-12 03:00:00 (Sun) 63645530400, # local_end 2017-11-05 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63645544800, # utc_start 2017-11-05 06:00:00 (Sun) 63656434800, # utc_end 2018-03-11 07:00:00 (Sun) 63645526800, # local_start 2017-11-05 01:00:00 (Sun) 63656416800, # local_end 2018-03-11 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63656434800, # utc_start 2018-03-11 07:00:00 (Sun) 63676994400, # utc_end 2018-11-04 06:00:00 (Sun) 63656420400, # local_start 2018-03-11 03:00:00 (Sun) 63676980000, # local_end 2018-11-04 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63676994400, # utc_start 2018-11-04 06:00:00 (Sun) 63687884400, # utc_end 2019-03-10 07:00:00 (Sun) 63676976400, # local_start 2018-11-04 01:00:00 (Sun) 63687866400, # local_end 2019-03-10 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63687884400, # utc_start 2019-03-10 07:00:00 (Sun) 63708444000, # utc_end 2019-11-03 06:00:00 (Sun) 63687870000, # local_start 2019-03-10 03:00:00 (Sun) 63708429600, # local_end 2019-11-03 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63708444000, # utc_start 2019-11-03 06:00:00 (Sun) 63719334000, # utc_end 2020-03-08 07:00:00 (Sun) 63708426000, # local_start 2019-11-03 01:00:00 (Sun) 63719316000, # local_end 2020-03-08 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63719334000, # utc_start 2020-03-08 07:00:00 (Sun) 63739893600, # utc_end 2020-11-01 06:00:00 (Sun) 63719319600, # local_start 2020-03-08 03:00:00 (Sun) 63739879200, # local_end 2020-11-01 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63739893600, # utc_start 2020-11-01 06:00:00 (Sun) 63751388400, # utc_end 2021-03-14 07:00:00 (Sun) 63739875600, # local_start 2020-11-01 01:00:00 (Sun) 63751370400, # local_end 2021-03-14 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63751388400, # utc_start 2021-03-14 07:00:00 (Sun) 63771948000, # utc_end 2021-11-07 06:00:00 (Sun) 63751374000, # local_start 2021-03-14 03:00:00 (Sun) 63771933600, # local_end 2021-11-07 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63771948000, # utc_start 2021-11-07 06:00:00 (Sun) 63782838000, # utc_end 2022-03-13 07:00:00 (Sun) 63771930000, # local_start 2021-11-07 01:00:00 (Sun) 63782820000, # local_end 2022-03-13 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63782838000, # utc_start 2022-03-13 07:00:00 (Sun) 63803397600, # utc_end 2022-11-06 06:00:00 (Sun) 63782823600, # local_start 2022-03-13 03:00:00 (Sun) 63803383200, # local_end 2022-11-06 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63803397600, # utc_start 2022-11-06 06:00:00 (Sun) 63814287600, # utc_end 2023-03-12 07:00:00 (Sun) 63803379600, # local_start 2022-11-06 01:00:00 (Sun) 63814269600, # local_end 2023-03-12 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63814287600, # utc_start 2023-03-12 07:00:00 (Sun) 63834847200, # utc_end 2023-11-05 06:00:00 (Sun) 63814273200, # local_start 2023-03-12 03:00:00 (Sun) 63834832800, # local_end 2023-11-05 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63834847200, # utc_start 2023-11-05 06:00:00 (Sun) 63845737200, # utc_end 2024-03-10 07:00:00 (Sun) 63834829200, # local_start 2023-11-05 01:00:00 (Sun) 63845719200, # local_end 2024-03-10 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63845737200, # utc_start 2024-03-10 07:00:00 (Sun) 63866296800, # utc_end 2024-11-03 06:00:00 (Sun) 63845722800, # local_start 2024-03-10 03:00:00 (Sun) 63866282400, # local_end 2024-11-03 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63866296800, # utc_start 2024-11-03 06:00:00 (Sun) 63877186800, # utc_end 2025-03-09 07:00:00 (Sun) 63866278800, # local_start 2024-11-03 01:00:00 (Sun) 63877168800, # local_end 2025-03-09 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63877186800, # utc_start 2025-03-09 07:00:00 (Sun) 63897746400, # utc_end 2025-11-02 06:00:00 (Sun) 63877172400, # local_start 2025-03-09 03:00:00 (Sun) 63897732000, # local_end 2025-11-02 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63897746400, # utc_start 2025-11-02 06:00:00 (Sun) 63908636400, # utc_end 2026-03-08 07:00:00 (Sun) 63897728400, # local_start 2025-11-02 01:00:00 (Sun) 63908618400, # local_end 2026-03-08 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63908636400, # utc_start 2026-03-08 07:00:00 (Sun) 63929196000, # utc_end 2026-11-01 06:00:00 (Sun) 63908622000, # local_start 2026-03-08 03:00:00 (Sun) 63929181600, # local_end 2026-11-01 02:00:00 (Sun) -14400, 1, 'EDT', ], [ 63929196000, # utc_start 2026-11-01 06:00:00 (Sun) 63940690800, # utc_end 2027-03-14 07:00:00 (Sun) 63929178000, # local_start 2026-11-01 01:00:00 (Sun) 63940672800, # local_end 2027-03-14 02:00:00 (Sun) -18000, 0, 'EST', ], [ 63940690800, # utc_start 2027-03-14 07:00:00 (Sun) 63961250400, # utc_end 2027-11-07 06:00:00 (Sun) 63940676400, # local_start 2027-03-14 03:00:00 (Sun) 63961236000, # local_end 2027-11-07 02:00:00 (Sun) -14400, 1, 'EDT', ], ]; sub olson_version {'2016a'} sub has_dst_changes {33} sub _max_year {2026} sub _new_instance { return shift->_init( @_, spans => $spans ); } sub _last_offset { -18000 } my $last_observance = bless( { 'format' => 'E%sT', 'gmtoff' => '-5:00', 'local_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 699828, 'local_rd_secs' => 42540, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 699828, 'utc_rd_secs' => 42540, 'utc_year' => 1918 }, 'DateTime' ), 'offset_from_std' => 0, 'offset_from_utc' => -18000, 'until' => [], 'utc_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 699828, 'local_rd_secs' => 60540, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 699828, 'utc_rd_secs' => 60540, 'utc_year' => 1918 }, 'DateTime' ) }, 'DateTime::TimeZone::OlsonDB::Observance' ) ; sub _last_observance { $last_observance } my $rules = [ bless( { 'at' => '2:00', 'from' => '2012', 'in' => 'Nov', 'letter' => 'S', 'name' => 'Haiti', 'offset_from_std' => 0, 'on' => 'Sun>=1', 'save' => '0', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ), bless( { 'at' => '2:00', 'from' => '2012', 'in' => 'Mar', 'letter' => 'D', 'name' => 'Haiti', 'offset_from_std' => 3600, 'on' => 'Sun>=8', 'save' => '1:00', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ) ] ; sub _rules { $rules } 1;
jkb78/extrajnm
local/lib/perl5/DateTime/TimeZone/America/Port_au_Prince.pm
Perl
mit
19,197
package BlueBox::Data::Box::Manager; use strict; use base qw(Rose::DB::Object::Manager); use BlueBox::Data::Box; sub object_class { 'BlueBox::Data::Box' } __PACKAGE__->make_manager_methods('boxes'); 1;
console0/rose-db-presentation
BlueBox/lib/BlueBox/Data/Box/Manager.pm
Perl
mit
209
#!/usr/bin/perl # # Common test library for camsigd package CamsigdTest; use strict; use Test::More; use FindBin; use LWP::UserAgent; use HTTP::Request; use Fcntl; our $BINARY = "$FindBin::Bin/../camsigd"; sub start { my ($port_rd, $port_wr, $exit_rd, $exit_wr); my $flags; pipe $port_rd, $port_wr; pipe $exit_rd, $exit_wr; $flags = fcntl($port_wr, F_GETFD, 0); fcntl($port_wr, F_SETFD, $flags & ~FD_CLOEXEC); $flags = fcntl($exit_rd, F_GETFD, 0); fcntl($exit_rd, F_SETFD, $flags & ~FD_CLOEXEC); $ENV{TESTING_PORT_WRITE_FD} = fileno($port_wr); $ENV{TESTING_CONTROL_READ_FD} = fileno($exit_rd); $ENV{CAMLI_PASSWORD} = "test"; die "Binary $BINARY doesn't exist\n" unless -x $BINARY; my $pid = fork; die "Failed to fork" unless defined($pid); if ($pid == 0) { # child exec $BINARY, "-listen=:0"; die "failed to exec: $!\n"; } close($exit_rd); # child owns this side close($port_wr); # child owns this side print "Waiting for server to start...\n"; my $line = <$port_rd>; close($port_rd); # Parse the port line out chomp $line; # print "Got port line: $line\n"; die "Failed to start, no port info." unless $line =~ /:(\d+)$/; my $port = $1; return CamsigdTest::Server->new($pid, $port, $exit_wr); } package CamsigdTest::Server; sub new { my ($class, $pid, $port, $pipe_writer) = @_; return bless { pid => $pid, port => $port, pipe_writer => $pipe_writer, }; } sub DESTROY { my $self = shift; my $pipe = $self->{pipe_writer}; syswrite($pipe, "EXIT\n", 5); } sub root { my $self = shift; return "http://localhost:$self->{port}"; } 1;
marsch/camlistore
server/go/sigserver/test/CamsigdTest.pm
Perl
apache-2.0
1,734
package Google::Ads::AdWords::v201809::LocationCriterionService::RequestHeader; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' } __PACKAGE__->__set_name('RequestHeader'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201809::SoapHeader ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201809::LocationCriterionService::RequestHeader =head1 DESCRIPTION Perl data type class for the XML Schema defined element RequestHeader from the namespace https://adwords.google.com/api/adwords/cm/v201809. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201809::LocationCriterionService::RequestHeader->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201809::SoapHeader =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/LocationCriterionService/RequestHeader.pm
Perl
apache-2.0
1,047
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] 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 XrefParser::OrphanetParser; use strict; use warnings; use Carp; use File::Basename; use XML::LibXML; use base qw( XrefParser::BaseParser ); sub run { my ($self, $ref_arg) = @_; my $source_id = $ref_arg->{source_id}; my $species_id = $ref_arg->{species_id}; my $files = $ref_arg->{files}; my $verbose = $ref_arg->{verbose}; if((!defined $source_id) or (!defined $species_id) or (!defined $files) ){ croak "Need to pass source_id, species_id and file as pairs"; } $verbose |=0; my $xml_file = @{$files}[0]; print STDERR "Orphanet file to parse, $xml_file\n" if($verbose); my %gene_disorders; my $term = undef; my $desc = undef; my $xml_parser = XML::LibXML->new(); my $orphanet_doc = $xml_parser->parse_file($xml_file); my ($jdbor_node) = $orphanet_doc->findnodes('JDBOR'); my $release = $jdbor_node->getAttribute('version'); # Set release $self->set_release( $source_id,$release ); my $gene_disorder_count = 0; my $disorder_count = 0; foreach my $disorder ($orphanet_doc->findnodes('JDBOR/DisorderList/Disorder')) { my ($orpha_number_node) = $disorder->findnodes('./OrphaNumber'); my $orpha_number = $orpha_number_node->to_literal; my ($name_node) = $disorder->findnodes('./Name'); my $name = $name_node->to_literal; my @genes = $disorder->findnodes('./DisorderGeneAssociationList/DisorderGeneAssociation/Gene'); if ( scalar(@genes) > 0) { $disorder_count++; } foreach my $gene (@genes) { my $ref; #get the HGNC xref foreach my $external_reference_node ($gene->findnodes('./ExternalReferenceList/ExternalReference')) { my ($source_node) = $external_reference_node->findnodes('./Source'); if ($source_node->to_literal =~ /HGNC/) { my ($ref_node) = $external_reference_node->findnodes('./Reference'); $ref = $ref_node->to_literal; } } if (defined($ref)) { $gene_disorders{$ref}{$orpha_number} = $name; $gene_disorder_count++; } } } print "Parsed $disorder_count disorders\n"; print "Found $gene_disorder_count genes associated with disorders\n"; #get the mapping that are already there so that we don't get lots of duplicates. # stored in the global hash xref_dependent_mapped. $self->get_dependent_mappings($source_id); my (%hgnc) = %{$self->get_valid_codes("HGNC", $species_id)}; print "got " . scalar(keys (%hgnc)) . " HGNC entries\n"; print "species_id, source_id: $species_id, $source_id\n"; my $added = 0; my %Orphanet_xrefs; foreach my $hgnc_acc (keys (%gene_disorders)) { # Get the master_xref_id if(!defined($hgnc{$hgnc_acc})){ print STDERR "failed to get the master_xref_if for HGNC, $hgnc_acc!\n"; } else{ foreach my $master_xref_id (@{$hgnc{$hgnc_acc}}){ foreach my $orpha_number (keys %{$gene_disorders{$hgnc_acc}}) { my $description = $gene_disorders{$hgnc_acc}{$orpha_number}; $self->add_dependent_xref({ master_xref_id => $master_xref_id, acc => $orpha_number, label => $description || $orpha_number, source_id => $source_id, species_id => $species_id, desc => $description }); $Orphanet_xrefs{$orpha_number}++; $added++; } } } } print "Added " . scalar(keys %Orphanet_xrefs) . " Orphanet xrefs and " . $added . " dependent xrefs\n"; if ($added > 0) { return 0; } else { return 1; } } 1;
muffato/ensembl
misc-scripts/xref_mapping/XrefParser/OrphanetParser.pm
Perl
apache-2.0
4,213
# # 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 database::mongodb::mode::connections; 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 => 'global', type => 0, cb_prefix_output => 'prefix_output' }, ]; $self->{maps_counters}->{global} = [ { label => 'active', nlabel => 'connections.active.count', set => { key_values => [ { name => 'active' } ], output_template => 'Active: %d', perfdatas => [ { value => 'active_absolute', template => '%d', min => 0, unit => 'conn' }, ], } }, { label => 'current', nlabel => 'connections.current.count', set => { key_values => [ { name => 'current' } ], output_template => 'Current: %d', perfdatas => [ { value => 'current_absolute', template => '%d', min => 0, unit => 'conn' }, ], } }, { label => 'usage', nlabel => 'connections.usage.percentage', set => { key_values => [ { name => 'usage' } ], output_template => 'Usage: %.2f %%', perfdatas => [ { value => 'usage_absolute', template => '%.2f', min => 0, max => 100, unit => '%' }, ], } }, { label => 'total-created', nlabel => 'connections.created.persecond', set => { key_values => [ { name => 'totalCreated', diff => 1 } ], output_template => 'Created: %.2f/s', per_second => 1, perfdatas => [ { value => 'totalCreated_per_second', template => '%.2f', min => 0, unit => 'conn/s' }, ], } }, ]; } sub prefix_output { my ($self, %options) = @_; return "Connections "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1, statefile => 1); bless $self, $class; $options{options}->add_options(arguments => {}); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); } sub manage_selection { my ($self, %options) = @_; $self->{custom} = $options{custom}; $self->{global} = {}; my $server_stats = $self->{custom}->run_command( database => 'admin', command => $self->{custom}->ordered_hash(serverStatus => 1), ); $self->{global}->{active} = $server_stats->{connections}->{active}; $self->{global}->{current} = $server_stats->{connections}->{current}; $self->{global}->{usage} = $server_stats->{connections}->{current} / ($server_stats->{connections}->{current} + $server_stats->{connections}->{available}); $self->{global}->{totalCreated} = $server_stats->{connections}->{totalCreated}; $self->{cache_name} = "mongodb_" . $self->{mode} . '_' . $self->{custom}->get_hostname() . '_' . $self->{custom}->get_port() . '_' . (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')); } 1; __END__ =head1 MODE Check connections statistics =over 8 =item B<--warning-connections-*-count> Threshold warning. Can be: 'active', 'current'. =item B<--critical-connections-*-count> Threshold critical. Can be: 'active', 'current'. =item B<--warning-connections-usage-percentage> Threshold warning for connections usage (current over available) =item B<--critical-connections-usage-percentage> Threshold critical for connections usage (current over available) =item B<--warning-connections-created-persecond> Threshold warning for connections created per second. =item B<--critical-connections-created-persecond> Threshold critical for connections created per second. =back =cut
Sims24/centreon-plugins
database/mongodb/mode/connections.pm
Perl
apache-2.0
4,740
# ################################################################ # findRelativePath ################################################################ sub findRelativePath { my ($dirName, $rootName) = @_; my $relDirName = substr($dirName, length($rootName) + 1); #print("AAA - relDirName = '$relDirName'\n"); return ($relDirName); } ################################################################ # findDirContent ################################################################ sub findDirContent { my ($dirName) = @_; my @contents = (); opendir DIR, $dirName or return; @contents = map "$dirName$_", sort grep !/^\.\.?$/, readdir DIR; closedir DIR; return (@contents); } ################################################################ # createDestinationFolder ################################################################ sub createDestinationFolder { my ($dirName) = @_; my $driveName; my $pathName; if( -e $dirName) { print("Destination folder '$dirName' exists\n"); return (0); } else { ## create the destination folder print("Creating the destination folder '$dirName'\n"); # We have to strip off the drive: portion before starting ($driveName, $pathName) = split( /:\\/, $dirName); $driveName = $driveName . ":\\"; createSubFolders($pathName, $driveName); return (1); } } ################################################################ # createSubFolders ################################################################ sub createSubFolders { my ($dirName, $rootFolder) = @_; my @paths; my $path = $rootFolder; my $tmpPath; my $lastDirName = ""; # If the dirName is the same as before, then don't waste time if ($dirName ne $lastDirName) { # Assume that the $dirName is a hierarchical name, so create each folder needed @paths = split( /\\/, $dirName); foreach $tmpPath (@paths) { $path = $path . "\\" . $tmpPath; #print("AAA - path is '$path'\n"); if(! -e $path) { ## create the destination folder print("\tCreating the folder '$path'\n"); mkdir($path); } } $lastDirName = $dirName; } } ################################################################ # createWantedNames # Syntax of the mapping file is: # # <Comment> # Name This translates to s/^Name*/Name/ # Name1:Name2 This translates to s/^Name1*/Name2/ # Note that Name2 can refer to a hierarchic path. (e.g. Name1:Name2\Name3) ################################################################ sub createWantedNames { my ($srcFolder, $wantedFoldersFileName, $wantedFolderName) = @_; %namesWanted; my $tmpFileName; my $dirNameWanted; my $tmpKey; my $searchString; my $name1; my $name2; ## open up the file that contains the dirNames wanted if( $wantedFolderName ne "none") { ($name1, $name2) = parseSearchString( $wantedFolderName ); $namesWanted{ $name2 } = $name1; } else { $tmpFileName = "$srcFolder\\$wantedFoldersFileName"; print("Reading the wanted Folders file '$tmpFileName'\n"); open(IN, "$tmpFileName") or die "Can't open '$tmpFileName' for read: $!"; while ($line = <IN>) { ($searchString) = split( / *$/, $line); #print("AAA - searchString = '$searchString'\n"); # Ignore comment lines and blank lines in the file if($searchString !~ /\s*#.*/ && $searchString !~ /^\n/) { # Here if not a comment ($name1, $name2) = parseSearchString( $searchString ); #Check to see if these names have already been entered into the file for $tmpKey (sort keys %namesWanted) { if( lc($namesWanted{ $tmpKey }) eq lc($name1) ) { print("\nERROR: Found duplicate search string (Name1) '$name1' in '$wantedFoldersFileName'\n"); exit 1; } elsif( lc($tmpKey) eq lc($name2) ) { print("\nERROR: Found duplicate entry for target dirName (Name2) '$name2' in '$wantedFoldersFileName'\n"); exit 1; } } # Check to see if name2 is supposed to be hierarchic. If yes, then escape any '\' found $name2 =~ s/\s*\\/\\\\/g; #print ("AAA - name2 = '$name2'\n"); $namesWanted{ $name2 } = $name1; } } close (IN ); } return (%namesWanted); } ################################################################ # parseSearchString ################################################################ sub parseSearchString { my ($searchString) = @_; my $name1 = ""; my $name2 = ""; # Is line of the form '<Name>:<Name>' ? if($searchString =~ m/^\s*(.+) *:\s*(.+)\s*$/) { # Here if yes. $name1 = $1; $name2 = $2; $name1 =~ s/\s*$//; # The prior search doesn't strip out white space before the '#' #print("TwoMatch - Name1 = '$name1', Name2 = '$name2'\n"); } #Is line of the form '<Name>:' (which is really a two name case that the above search doesn't catch) ? elsif ($searchString =~ m/^\s*(.+) *:\s*$/) { #Here if yes. $name1 = $1; $name2 = $1; #print("TwoMatch - Name1 = '$name1', Name2 = '$name2'\n"); } #Is line of the form '<Name>' ? elsif ($searchString =~ /^\s*(.+)\s*$/) { #Here if yes. $1 is the search string $name1 = $1; $name2 = $1; #print("OneMatch - Name1 = '$name1'\n"); } else { # Here if invalid syntax print("ERROR: parseSearchString - Invalid syntax in string 'parseSearchString'\n"); exit 1; } return($name1, $name2); } ################################################################ # oneDirMatch ################################################################ sub oneDirMatch { my ($srcDirName, $searchName, $targetName) = @_; my @pathParts; my $folderName; #Strip out the folder name from the srcDirName ("aaa\bbb\folderName") @pathParts = split(/\\/, $srcDirName); $folderName = pop( @pathParts); #print("oneDirMatch: folderName = '$folderName', searchName= '$searchName', targetName = '$targetName'\n"); if ($folderName =~ /^$searchName.*/i) { #print("Found Dir match for '$srcDirName'. Returning the name '$targetName'\n"); return ( $targetName ); } else { #print("'$srcDirName' didn't match the search pattern '$searchName'\n"); return ( "none" ); } } ################################################################ # trim ################################################################ sub trim { my ($string) = @_; $string =~ s/^\s+//; $string =~ s/\s+$//; return $string; } ################################################################ # parseCommandLine ################################################################ sub parseCommandLine { my (%SWITCHES) = @_; my $numCmdLineArgs = scalar(@ARGV); my %cmdLineArgs = @ARGV; my $switch; my $tmpSwitch; my %cmdLineVars; my $debug = 1; my $value; #initialize the global variables $cmdLineVars{"srcFolder"} = "C:\\Scanned_Pictures"; $cmdLineVars{"destFolder"} = ""; $cmdLineVars{"outputFolder"} = ""; $cmdLineVars{"wantedFolder"} = ""; $cmdLineVars{"finalFolder"} = ""; $cmdLineVars{"wantedFoldersFileName"} = "aberscanWantedFolderMappings.txt"; $cmdLineVars{"wantedFolderName"} = "none"; $cmdLineVars{"fileRootName"} = "photo"; $cmdLineVars{"fileStartNumber"} = 1; $cmdLineVars{"photoMappingFile"} = "aberscanPhotoMappings.txt"; $cmdLineVars{"includeSource"} = 0; $cmdLineVars{"useOrigFileName"} = 0; $cmdLineVars{"removeOrigFileName"} = 0; $cmdLineVars{"createOutputDir"} = 1; $cmdLineVars{"tagFileName"} = "aberscanAddresses.csv"; # add a default setting that isn't in the command line $cmdLineVars{"rootDestFolder"} = "C:\\AberscanInProgress"; usage(%SWITCHES) if (defined($cmdLineArgs{-help})); if ($numCmdLineArgs % 2 != 0) { print STDERR "\nERROR: One or more switches don't have associated values\n"; helpAndExit(); } # filter out invalid options for $switch (keys %cmdLineArgs) { if (! defined($SWITCHES{$switch})) { print STDERR "\nERROR: invalid switch '$switch'\n"; helpAndExit(); } } # verify that required options are all specified, for $switch (keys %SWITCHES) { if ($SWITCHES{$switch} eq 'required') { if (! defined $cmdLineArgs{$switch}) { print STDERR "\nERROR: missing required switch '$switch <value>'\n"; helpAndExit(); } } } # Now parse what was specified on the command line for $switch (keys %SWITCHES) { if (defined $cmdLineArgs{$switch}) { $tmpSwitch = $switch; $tmpSwitch =~ s/-//; $cmdLineVars{$tmpSwitch} = $cmdLineArgs{$switch}; if( $switch eq "-includeSource") { if ($cmdLineVars{"includeSource"} != 1 && $cmdLineVars{"includeSource"} != 0) { $value = $cmdLineVars{"includeSource"}; print STDERR "\nERROR: invalid value '$value' for the -includeSource switch\n"; helpAndExit(); } } if( $switch eq "-useOrigFileName") { if ($cmdLineVars{"useOrigFileName"} != 1 && $cmdLineVars{"useOrigFileName"} != 0 && $cmdLineVars{"useOrigFileName"} != 2) { $value = $cmdLineVars{"useOrigFileName"}; print STDERR "\nERROR: invalid value '$value' for the -useOrigFileName switch\n"; helpAndExit(); } } if( $switch eq "-removeOrigFileName") { if ($cmdLineVars{"removeOrigFileName"} != 1 && $cmdLineVars{"removeOrigFileName"} != 0) { $value = $cmdLineVars{"removeOrigFileName"}; print STDERR "\nERROR: invalid value '$value' for the -removeOrigFileName switch\n"; helpAndExit(); } } if( $switch eq "-createOutputDir") { if ($cmdLineVars{"createOutputDir"} != 1 && $cmdLineVars{"createOutputDir"} != 0) { $value = $cmdLineVars{"createOutputDir"}; print STDERR "\nERROR: invalid value '$value' for the -createOutputDir switch\n"; helpAndExit(); } } #fix up the disk name on paths if ($switch eq "-destFolder") { $cmdLineVars{"destFolder"} =~ s/c:/C:/; } if ($switch eq "-srcFolder" ) { $cmdLineVars{"srcFolder"} =~ s/c:/C:/; } if ($switch eq "-outputFolder") { $cmdLineVars{"outputFolder"} =~ s/c:/C:/; } if ($switch eq "-finalFolder") { $cmdLineVars{"finalFolder"} =~ s/c:/C:/; } } } if ($debug == 1) { print STDOUT "Command Line Summary:\n"; for $switch (sort keys %SWITCHES) { $tmpSwitch = $switch; $tmpSwitch =~ s/-//; if($tmpSwitch ne "help") { print STDOUT "\t$tmpSwitch = '$cmdLineVars{$tmpSwitch}'\n"; } } } return (%cmdLineVars); } ################################################################ # helpAndExit # # Desc: Print out the command Line Usage instructions ################################################################ sub helpAndExit { print STDERR "\tType '$0 -help yes' for a full description of command line options\n"; exit 1; } #helpAndExit ################################################################ # usage # # Desc: Print out the command Line Usage instructions ################################################################ sub usage { my (%SWITCHES) = @_; my $usageText = ""; my $switch; print STDERR "Options can contain the following:\n"; for $switch (sort keys %SWITCHES) { if( $switch eq "-srcFolder") { print STDERR "\n\n -srcFolder <folderNamer> \tThe top level source folder that you want to recurse. The folders to \tbe searched for are listed in the file specified using the \t'wantedFoldersFileName' \tDefault: C:/Scanned_Pictures"; } elsif( $switch eq "-destFolder") { print STDERR "\n\n -destFolder <folderName> \tThe name of the folder where you want the folder copy to go, with \trenumbered files"; } elsif( $switch eq "-outputFolder") { print STDERR "\n\n -outputFolder <folderName> \tThe name of the folder where you want the (flat) output to \tgo, along with the mapping file"; } elsif( $switch eq "-finalFolder") { print STDERR "\n\n -finalFolder <folderName> \tName of folder that you want subFolders created within"; } elsif( $switch eq "-fileRootName") { print STDERR "\n\n -fileRootName <rootName> \tThe new root name for each new file created in the output folder \tDefault: photo"; } elsif( $switch eq "-fileStartNumber") { print STDERR "\n\n -fileStartNumber <number> \tThe starting number to be appended to the first file. \tSubsequent files will increment this starting number \tDefault: 1"; } elsif( $switch eq "-photoMappingFile") { print STDERR "\n\n -photoMappingFile <fileName> \tThis is the name of the file in the output folder 'outputFolder' that \tcontains the mappings between the photo file name, and the name of \tthe folder where the photo is to ultimately reside once done with \tPhotoshop processing. The syntax of this photo mapping file is: \t\t<Name of Final Folder>,<Name of Photo File> \t\t<Name of Final Folder>,<Name of Photo File> \t\t... \tThe step of putting the photo files back into their correct folder is \tdone using the perl script 'createEpsonFinalFolders'"; } elsif( $switch eq "-wantedFoldersFileName") { print STDERR "\n\n -wantedFoldersFileName <fileName> \tThis is the name of the file in the source folder 'srcFolder' that \tcontains the search strings used to match subdirectories within the \tsource folder. If there is a match, then all the photos (jpg) \tfound recursively in that folder are copied to the output folder. \tThe syntax of this file is: \t\t<FolderSearchStringToBeMatched> \t\t<FolderSearchStringToBeMatched> \tDefault: aberscanWantedFolderMappings.txt"; } elsif( $switch eq "-wantedFolderName") { print STDERR "\n\n -wantedFolderName <folderName> \tAdd a single folder name. Use this rather than creating the \t'aberscanWantedFolderMappings.txt' with just one name"; } elsif( $switch eq "-includeSource") { print STDERR "\n\n -includeSource <1|0> \tSpecifies whether the source name shows up in destination \tfile name - no (0), yes (1)"; } elsif( $switch eq "-useOrigFileName") { print STDERR "\n\n -useOrigFileName <1|0> \tSpecifies whether to keep the original file name or generate a new name \tfile name - no (0), yes (1), use just the text part of the name (e.g. photo) (2)"; } elsif( $switch eq "-tagFileName") { print STDERR "\n\n -tagFileName <fileName> \tSpecifies the name of the input tag file"; } elsif( $switch eq "-help") { } else { print STDERR "\nERROR: usage - cmdLine variable not known\n"; } } exit 1; } 1;
georgebswan/PerlLibrary
library.pl
Perl
apache-2.0
15,204
package Paws::DeviceFarm::GetRemoteAccessSession; use Moose; has Arn => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'arn' , required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'GetRemoteAccessSession'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::DeviceFarm::GetRemoteAccessSessionResult'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::DeviceFarm::GetRemoteAccessSession - Arguments for method GetRemoteAccessSession on Paws::DeviceFarm =head1 DESCRIPTION This class represents the parameters used for calling the method GetRemoteAccessSession on the AWS Device Farm service. Use the attributes of this class as arguments to method GetRemoteAccessSession. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to GetRemoteAccessSession. As an example: $service_obj->GetRemoteAccessSession(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 B<REQUIRED> Arn => Str The Amazon Resource Name (ARN) of the remote access session about which you want to get session information. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method GetRemoteAccessSession in L<Paws::DeviceFarm> =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/DeviceFarm/GetRemoteAccessSession.pm
Perl
apache-2.0
1,800
# # 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::cisco::vcs::restapi::mode::zones; 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 = sprintf("Status is '%s' [Type: %s]", $self->{result_values}->{status}, $self->{result_values}->{type}); return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{name} = $options{new_datas}->{$self->{instance} . '_Name'}; $self->{result_values}->{type} = $options{new_datas}->{$self->{instance} . '_Type'}; $self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_Status'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0}, { name => 'searches', type => 0, cb_prefix_output => 'prefix_searches_output' }, { name => 'zones', type => 1, cb_prefix_output => 'prefix_zones_output', message_multiple => 'All zones are ok' }, ]; $self->{maps_counters}->{global} = [ { label => 'zones-count', set => { key_values => [ { name => 'count' } ], output_template => 'Number of zones: %d', perfdatas => [ { label => 'zones_count', value => 'count_absolute', template => '%d', min => 0 }, ], } }, ]; $self->{maps_counters}->{searches} = [ { label => 'searches-total', set => { key_values => [ { name => 'Total', diff => 1 } ], output_template => 'Total: %.2f/s', per_second => 1, perfdatas => [ { label => 'searches_total', value => 'Total_per_second', template => '%.2f', min => 0, unit => 'searches/s' }, ], } }, { label => 'searches-dropped', set => { key_values => [ { name => 'Dropped', diff => 1 } ], output_template => 'Dropped: %.2f/s', per_second => 1, perfdatas => [ { label => 'searches_dropped', value => 'Dropped_per_second', template => '%.2f', min => 0, unit => 'searches/s' }, ], } }, { label => 'searches-max-sub-search-exceeded', set => { key_values => [ { name => 'MaxSubSearchExceeded', diff => 1 } ], output_template => 'Max Sub Search Exceeded: %.2f/s', per_second => 1, perfdatas => [ { label => 'searches_max_sub_search_exceeded', value => 'MaxSubSearchExceeded_per_second', template => '%.2f', min => 0, unit => 'searches/s' }, ], } }, { label => 'searches-max-targets-exceeded', set => { key_values => [ { name => 'MaxTargetsExceeded', diff => 1 } ], output_template => 'Max Targets Exceeded: %.2f/s', per_second => 1, perfdatas => [ { label => 'searches_max_targets_exceeded', value => 'MaxTargetsExceeded_per_second', template => '%.2f', min => 0, unit => 'searches/s' }, ], } }, ]; $self->{maps_counters}->{zones} = [ { label => 'status', set => { key_values => [ { name => 'Status' }, { name => 'Type' }, { name => 'Name' } ], 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 => 'calls-count', set => { key_values => [ { name => 'Calls' }, { name => 'Name' } ], output_template => 'Number of Calls: %d', perfdatas => [ { label => 'calls_count', value => 'Calls_absolute', template => '%d', min => 0, label_extra_instance => 1, instance_use => 'Name_absolute' }, ], } }, ]; } sub prefix_searches_output { my ($self, %options) = @_; return "Searches "; } sub prefix_zones_output { my ($self, %options) = @_; return "Zone '" . $options{instance_value}->{Name} . "' "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1); bless $self, $class; $options{options}->add_options(arguments => { "filter-counters:s" => { name => 'filter_counters' }, "warning-status:s" => { name => 'warning_status' }, "critical-status:s" => { name => 'critical_status', default => '%{status} ne "Active"' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->change_macros(macros => ['warning_status', 'critical_status']); } sub manage_selection { my ($self, %options) = @_; my $results = $options{custom}->get_endpoint(method => '/Status/Zones'); $self->{global}->{count} = 0; $self->{searches} = {}; $self->{zones} = {}; $self->{searches}->{Total} = $results->{Zones}->{Searches}->{Total}->{content}; $self->{searches}->{Dropped} = $results->{Zones}->{Searches}->{Dropped}->{content}; $self->{searches}->{MaxSubSearchExceeded} = $results->{Zones}->{Searches}->{MaxSubSearchExceeded}->{content}; $self->{searches}->{MaxTargetsExceeded} = $results->{Zones}->{Searches}->{MaxTargetsExceeded}->{content}; foreach my $zone (@{$results->{Zones}->{Zone}}) { next if (!defined($zone->{Name})); $self->{zones}->{$zone->{Name}->{content}} = { Type => $zone->{Type}->{content}, Name => $zone->{Name}->{content}, Calls => (defined($zone->{Calls})) ? scalar(@{$zone->{Calls}->{Call}}) : 0, Status => $zone->{Status}->{content}, }; $self->{global}->{count}++; } $self->{cache_name} = "cisco_vcs_" . $options{custom}->get_hostname() . '_' . $options{custom}->get_port() . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')); } 1; __END__ =head1 MODE Check zones count and state. =over 8 =item B<--warning-*> Threshold warning. Can be: 'zones-count', 'calls-count', 'searches-total' (/s), 'searches-dropped' (/s), 'searches-max-sub-search-exceeded' (/s), 'searches-max-targets-exceeded' (/s). =item B<--critical-*> Threshold critical. Can be: 'zones-count', 'calls-count', 'searches-total' (/s), 'searches-dropped' (/s), 'searches-max-sub-search-exceeded' (/s), 'searches-max-targets-exceeded' (/s). =item B<--warning-status> Set warning threshold for status. (Default: ''). Can use special variables like: %{status}, %{type}, %{name}. =item B<--critical-status> Set critical threshold for status. (Default: '%{status} ne "Active"'). Can use special variables like: %{status}, %{type}, %{name}. =back =cut
Sims24/centreon-plugins
network/cisco/vcs/restapi/mode/zones.pm
Perl
apache-2.0
8,282
use strict; use File::Spec; use File::Path; use LWP::Simple; use Archive::Extract; my $libDir = File::Spec->catdir($0, "..", "..", "lib"); my $cacheDir = File::Spec->catdir($ENV{TEMP}, 'get-req-cache'); mkpath $libDir; downloadAndExtract("http://sidi-util.googlecode.com/files/Sidi.Util-0.0.zip"); sub download { my ($url, $downloadDir) = @_; print "$url\n"; my @p = split /\//, $url; my $filename = File::Spec->catdir($downloadDir, pop @p); mkpath $downloadDir; mirror($url, $filename); return $filename; } sub downloadAndExtract { my ($url, $dir, $prefix) = @_; $dir or $dir = $libDir; $prefix or $prefix = '.'; my $archive = download($url, $cacheDir); my $ae = Archive::Extract->new( archive => $archive ); $ae->extract( to => File::Spec->catdir($dir, $prefix) ); }
sidiandi/sammy
get-prerequisites.pl
Perl
apache-2.0
857
# # 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 network::nortel::standard::snmp::mode::components::card; use strict; use warnings; use network::nortel::standard::snmp::mode::components::resources qw($map_card_status); my $mapping = { rcCardSerialNumber => { oid => '.1.3.6.1.4.1.2272.1.4.9.1.1.3' }, rcCardOperStatus => { oid => '.1.3.6.1.4.1.2272.1.4.9.1.1.6', map => $map_card_status }, }; my $oid_rcCardEntry = '.1.3.6.1.4.1.2272.1.4.9.1.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_rcCardEntry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking cards"); $self->{components}->{card} = {name => 'cards', total => 0, skip => 0}; return if ($self->check_filter(section => 'card')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_rcCardEntry}})) { next if ($oid !~ /^$mapping->{rcCardOperStatus}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_rcCardEntry}, instance => $instance); next if ($self->check_filter(section => 'card', instance => $instance)); $self->{components}->{card}->{total}++; $self->{output}->output_add(long_msg => sprintf("card '%s' status is '%s' [instance: %s].", $result->{rcCardSerialNumber}, $result->{rcCardOperStatus}, $instance )); my $exit = $self->get_severity(section => 'card', instance => $instance, value => $result->{rcCardOperStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Card '%s' status is '%s'", $result->{rcCardSerialNumber}, $result->{rcCardOperStatus})); } } } 1;
wilfriedcomte/centreon-plugins
network/nortel/standard/snmp/mode/components/card.pm
Perl
apache-2.0
2,771
package Paws::IoT::GetTopicRule; use Moose; has RuleName => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'ruleName', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'GetTopicRule'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/rules/{ruleName}'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'GET'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::IoT::GetTopicRuleResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::IoT::GetTopicRule - Arguments for method GetTopicRule on Paws::IoT =head1 DESCRIPTION This class represents the parameters used for calling the method GetTopicRule on the AWS IoT service. Use the attributes of this class as arguments to method GetTopicRule. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to GetTopicRule. As an example: $service_obj->GetTopicRule(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 B<REQUIRED> RuleName => Str The name of the rule. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method GetTopicRule in L<Paws::IoT> =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/IoT/GetTopicRule.pm
Perl
apache-2.0
1,738
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. hanoi(A,B,C,D,E) :- A=1, B=1, C=1. hanoi(A,B,C,D,E) :- A=0, B=1, C=1. hanoi(A,B,C,D,E) :- A=0, B=0, C=0. hanoi__1(A) :- true. hanoi___0(A,B) :- hanoi__1(B), B=1, A=1. hanoi__3(A) :- hanoi__1(A), A<1. hanoi__3(A) :- hanoi__1(A), A>1. hanoi___0(A,B) :- hanoi__3(B), hanoi(1,0,0,B+ -1,C), A=C*2+1. hanoi__split(A,B) :- hanoi___0(A,B). hanoi(A,B,C,D,E) :- A=1, B=0, C=0, hanoi__split(E,D). main_entry :- true. main__un(A) :- main_entry, A+ -1=<30. main__un1 :- main__un(A), hanoi(1,0,0,A,B), B=< -1. main_verifier_error :- main__un1.
bishoksan/RAHFT
benchmarks_scp/SVCOMP15/svcomp15-clp/recHanoi02_true-unreach-call_true-termination.c.pl
Perl
apache-2.0
856
use SDL::App; # open a 640x480 window for your application our $app = SDL::App->new(-width => 640, -height => 480); # create a surface out of an image file specified on the command-line our $img = SDL::Surface->new( -name => $ARGV[0] ); # blit the surface onto the window of your application $img->blit( undef, $app, undef ); # flush all pending screen updates $app->flip(); # sleep for 3 seconds to let the user view the image sleep 3;
jmcveigh/komodo-tools
scripts/perl/interactive_graphical_apps/sdl_show_image.pl
Perl
bsd-2-clause
442
/* -------------------------------------------------------------------------- Importing other modules -------------------------------------------------------------------------- */ :- use_module(binarise,[binarise/3]). :- use_module(ccg,[ccg/2]). :- use_module(pp,[pp/2]). :- use_module(printTree,[printBin/2]). :- use_module(printTUT,[printTUT/2,lenTUT/2]). :- use_module(printCCG,[printTokCat/2,printCCG/2,writeCCG/4]). /* -------------------------------------------------------------------------- Dynamic Predicates -------------------------------------------------------------------------- */ :- dynamic switch/2. /* -------------------------------------------------------------------------- Switches (yes/no) -------------------------------------------------------------------------- */ switch(tut,no). % print TUT tree switch(bin,no). % print binary tree switch(ppp,no). % print CCG derivation (pre postprocessing) switch(ccg,no). % print CCG derivation (final derivation) switch(pro,no). % print CCG derivation (Prolog) switch(lex,no). % print lexical entry switch(err,no). % print errors switch(pab,yes). % abstract over punctuation categories switch(sort,no). /* -------------------------------------------------------------------------- Exceptions (do not try to process these yet) -------------------------------------------------------------------------- */ dont('ALB-100'). % wrong attachment dont('ALB-245'). % coordination problem dont('ALB-254'). % coordination of constituents of different type dont('CODICECIVILE-364'). % idem (UNK) dont('CODICECIVILE-56'). % coordination (?) problem, takes a long time, no analysis dont('A-56'). % problem with pro-drop/sentence coordination dont('V-304'). % problem with pro-drop/sentence coordination dont('ALB-101'). % problem with pro-drop/sentence coordination dont('CHIAM-8'). % problem with pro-drop/sentence coordination dont('EVALITA-NEWSPAPER-80'). % problem with pro-drop/sentence coordination dont('V-493'). % problem with gliel' (should be arg, not mod!) -> see mail Cristina (Oct 26, 2009) dont('V-437'). % something goes wrong here with punctuation... (UNK) dont('ALB-22'). % sequence of two empty nodes dont('ALB-128'). % sequence of two empty nodes dont('ALB-257'). % sequence of two empty nodes dont('A-37'). % sequence of two empty nodes dont('A-38'). % sequence of two empty nodes dont('A-46'). % sequence of two empty nodes dont('CHIAM-20'). % sequence of two empty nodes dont('CODICECIVILE-288'). % sequence of two empty nodes dont('CODICECIVILE-291'). % sequence of two empty nodes dont('CODICECIVILE-461'). % sequence of two empty nodes (sopra o sotto il ...) % CODICECIVILE-19 % relative clause problem % Name = 'CODICECIVILE-18', % coordination problem % Name = 'V-466', % ne ne % Name = 'V-529', % Sia % Name = 'ALB-98', % funny "ma" + multiple conjunction % Name = 'ALB-26', % relative clause % Name = 'ALB-172', % strange relative clause /* -------------------------------------------------------------------------- Process all TUT derivations -------------------------------------------------------------------------- */ alltut(Stream):- switch(sort,no), tut(_,_,Name,_,Type:TUT), % get a constituent tree % Name = 'V-437', % lenTUT(Type:TUT,Len), % Len = 3, processTree(Name,Type,TUT,Stream), fail. % take the next tree alltut(Stream):- switch(sort,no), !, stats(user_output), close(Stream). alltut(_):- switch(sort,yes). /* -------------------------------------------------------------------------- Process one TUT tree -------------------------------------------------------------------------- */ processTree(Name,Type,TUT,Stream):- increase(tree), % update counter ( switch(tut,yes), format(Stream,'%%%% ~p~n',[Name]), % print TUT format printTUT(Type:TUT,Stream) ; \+ switch(tut,yes) ), binarise(TUT,Name,Tree), % binarise the TUT tree increase(bin), % update counter ( switch(bin,yes), format(Stream,'%%%% ~p~n',[Name]), % print binary tree printBin(Type:Tree,Stream) ; \+ switch(bin,yes) ), \+ dont(Name), ccg(Type:Tree,CCGTemp), % convert it into a CCG derivation ( switch(ppp,yes), printCCG(CCGTemp,Stream) ; \+ switch(ppp,yes) ), % print pre-CCG derivation pp(CCGTemp,CCG), % apply post-processing increase(ccg), % update counter counter(ccg,CCGNo), ( switch(pro,yes), writeCCG(CCG,Name,CCGNo,Stream) ; \+ switch(pro,yes) ), % print CCG (prolog) ( switch(ccg,yes), format(Stream,'%%%% ~p~n',[Name]), printCCG(CCG,Stream) ; \+ switch(ccg,yes) ), % print CCG derivation ( switch(lex,yes), format(Stream,'%%%% ~p~n',[Name]), printTokCat(CCG,Stream) ; \+ switch(lex,yes) ). % print lexicon /* -------------------------------------------------------------------------- Sorted on sentence length (wrapper) -------------------------------------------------------------------------- */ sortbank(Stream):- switch(sort,yes), !, sortbank(1,Stream). sortbank(_). /* -------------------------------------------------------------------------- Sorted on sentence length -------------------------------------------------------------------------- */ sortbank(N,Stream):- tut(_,_,Name,_,Type:TUT), % get a constituent tree lenTUT(Type:TUT,N), processTree(Name,Type,TUT,Stream), fail. % take the next tree of length N % \+ dont(Name), % % binarise(TUT,Name,Tree), % binarise the TUT tree % ccg(Type:Tree,CCGTemp), % convert it into a CCG derivation % pp(CCGTemp,CCG), % apply post-processing % increase(ccg), % update counter % format(Stream,'%%%% ~p~n',[Name]), % printCCG(CCG,Stream), sortbank(N,Stream):- tut(_,_,_,_,Type:TUT), lenTUT(Type:TUT,M), M > N, !, I is N + 1, sortbank(I,Stream). sortbank(_,Stream):- close(Stream). /* -------------------------------------------------------------------------- Stats -------------------------------------------------------------------------- */ stats(Stream):- write(Stream,'Statistics'), nl(Stream), write(Stream,'=========='), nl(Stream), counter(tree,Tree), write(Stream,tut:Tree), nl(Stream), counter(bin,Bin), write(Stream,bin:Bin), nl(Stream), counter(ccg,CCG), write(Stream,ccg:CCG), nl(Stream), nl(Stream). /* -------------------------------------------------------------------------- File handling -------------------------------------------------------------------------- */ output(Command,user_output):- parseCommand(Command,[File]), !, consult(File). output(Command,Stream):- parseCommand(Command,[FileIn,FileOut]), !, consult(FileIn), open(FileOut,write,Stream). /* -------------------------------------------------------------------------- Main Predicate -------------------------------------------------------------------------- */ run:- prolog_flag(argv,Command), output(Command,Stream), alltut(Stream), sortbank(Stream), !. run. /* -------------------------------------------------------------------------- Parse Command -------------------------------------------------------------------------- */ parseCommand([_,'-c',_Comm|Options],Files):- parseOptions(Options,Files), !. parseCommand([_,_,'-c',_Comm|Options],Files):- parseOptions(Options,Files), !. /* -------------------------------------------------------------------------- Parse Options -------------------------------------------------------------------------- */ parseOptions([],[]). parseOptions(['--errors'|L1],L2):- !, retractall(switch(err,_)), assert(switch(err,yes)), parseOptions(L1,L2). parseOptions(['--tut'|L1],L2):- !, retractall(switch(tut,_)), assert(switch(tut,yes)), parseOptions(L1,L2). parseOptions(['--bin'|L1],L2):- !, retractall(switch(bin,_)), assert(switch(bin,yes)), parseOptions(L1,L2). parseOptions(['--ccg'|L1],L2):- !, retractall(switch(ccg,_)), assert(switch(ccg,yes)), parseOptions(L1,L2). parseOptions(['--pro'|L1],L2):- !, retractall(switch(pro,_)), assert(switch(pro,yes)), parseOptions(L1,L2). parseOptions(['--sort'|L1],L2):- !, retractall(switch(sort,_)), assert(switch(sort,yes)), parseOptions(L1,L2). parseOptions(['--lex'|L1],L2):- !, retractall(switch(lex,_)), assert(switch(lex,yes)), parseOptions(L1,L2). parseOptions([X|L1],[X|L2]):- parseOptions(L1,L2). /* -------------------------------------------------------------------------- Counting -------------------------------------------------------------------------- */ :- dynamic counter/2. increase(X):- \+ counter(X,_), !, assert(counter(X,1)). increase(X):- retract(counter(X,N)), M is N + 1, assert(counter(X,M)), !. /* -------------------------------------------------------------------------- Starting -------------------------------------------------------------------------- */ :- run, halt.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/candc/src/data/italian/prolog/tut2ccg.pl
Perl
mit
10,283
# 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. package Lucy::Plan::Architecture; use Lucy; our $VERSION = '0.006000'; $VERSION = eval $VERSION; 1; __END__
apache/lucy
perl/lib/Lucy/Plan/Architecture.pm
Perl
apache-2.0
894
# install_check.pl do 'mysql-lib.pl'; # is_installed(mode) # For mode 1, returns 2 if the server is installed and configured for use by # Webmin, 1 if installed but not configured, or 0 otherwise. # For mode 0, returns 1 if installed, 0 if not sub is_installed { return 0 if (!-x $config{'mysqladmin'} || !-x $config{'mysql'}); return 0 if (&get_mysql_version(\$dummy) <= 0); if ($_[0]) { # Check if can login return 2 if (&is_mysql_running() == 1); } return 1; }
HasClass0/webmin
mysql/install_check.pl
Perl
bsd-3-clause
470
# slapd-monitor.pl # Monitor the openldap server on this host # Check the PID file to see if slapd is running sub get_slapd_status { return { 'up' => -1 } if (!&foreign_check("ldap-server")); &foreign_require("ldap-server", "ldap-server-lib.pl"); if (&foreign_call("ldap-server", "is_ldap_server_running")) { local $pidfile = &foreign_call("ldap-server", "get_ldap_server_pidfile"); local @st = stat($pidfile); return { 'up' => 1, 'desc' => &text('up_since', scalar(localtime($st[9]))) }; } else { return { 'up' => 0 }; } } sub parse_slapd_dialog { &depends_check($_[0], "ldap-server"); } 1;
HasClass0/webmin
status/slapd-monitor.pl
Perl
bsd-3-clause
606
package Crypt::OpenPGP::UserID; use strict; use Crypt::OpenPGP::ErrorHandler; use base qw( Crypt::OpenPGP::ErrorHandler ); sub new { my $id = bless { }, shift; $id->init(@_); } sub init { my $id = shift; my %param = @_; if (my $ident = $param{Identity}) { $id->{id} = $ident; } $id; } sub id { $_[0]->{id} } sub parse { my $class = shift; my($buf) = @_; my $id = $class->new; $id->{id} = $buf->bytes; $id; } sub save { $_[0]->{id} } 1; __END__ =head1 NAME Crypt::OpenPGP::UserID - PGP User ID packet =head1 SYNOPSIS use Crypt::OpenPGP::UserID; my $uid = Crypt::OpenPGP::UserID->new( Identity => 'Foo' ); my $serialized = $uid->save; my $identity = $uid->id; =head1 DESCRIPTION I<Crypt::OpenPGP::UserID> is a PGP User ID packet. Such a packet is used to represent the name and email address of the key holder, and typically contains an RFC822 mail name like Foo Bar <foo@bar.com> =head1 USAGE =head2 Crypt::OpenPGP::UserID->new( [ Identity => $identity ] ) Creates a new User ID packet object and returns that object. If you do not supply an identity, the object is created empty; this is used, for example, in I<parse> (below), to create an empty packet which is then filled from the data in the buffer. If you wish to initialize a non-empty object, supply I<new> with the I<Identity> parameter along with a value I<$identity> which should generally be in RFC822 form (above). =head2 $uid->save Returns the text of the user ID packet; this is the string passed to I<new> (above) as I<$identity>, for example. =head2 Crypt::OpenPGP::UserID->parse($buffer) Given I<$buffer>, a I<Crypt::OpenPGP::Buffer> object holding (or with offset pointing to) a User ID packet, returns a new <Crypt::OpenPGP::UserID> object, initialized with the user ID data in the buffer. =head2 $uid->id Returns the user ID data (eg. the string passed as I<$identity> to I<new>, above). =head1 AUTHOR & COPYRIGHTS Please see the Crypt::OpenPGP manpage for author, copyright, and license information. =cut
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/Crypt/OpenPGP/UserID.pm
Perl
mit
2,079
#!/usr/bin/perl -w use strict; use warnings; use Getopt::Std; &blast2sam; sub blast2sam { my %opts = (); getopts('s', \%opts); die("Usage: blast2sam.pl <in.blastn>\n") if (-t STDIN && @ARGV == 0); my ($qlen, $slen, $q, $s, $qbeg, $qend, @sam, @cigar, @cmaux, $show_seq); $show_seq = defined($opts{s}); @sam = (); @sam[0,4,6..8,10] = ('', 255, '*', 0, 0, '*'); while (<>) { if (@cigar && (/^Query=/ || /Score =.*bits.*Expect/)) { # print &blast_print_sam(\@sam, \@cigar, \@cmaux, $qlen - $qend); @cigar = (); } if (/^Query= (\S+)/) { $sam[0] = $1; } elsif (/\((\S+)\s+letters\)/) { $qlen = $1; $qlen =~ s/,//g; } elsif (/^>(\S+)/) { $sam[2] = $1; } elsif (/Length = (\d+)/) { $slen = $1; } elsif (/Score =\s+(\S+) bits.+Expect(\(\d+\))? = (\S+)/) { # the start of an alignment block my ($as, $ev) = (int($1 + .499), $3); $ev = "1$ev" if ($ev =~ /^e/); @sam[1,3,9,11,12] = (0, 0, '', "AS:i:$as", "EV:Z:$ev"); @cigar = (); $qbeg = 0; @cmaux = (0, 0, 0, ''); } elsif (/Strand = (\S+) \/ (\S+)/) { $sam[1] |= 0x10 if ($2 eq 'Minus'); } elsif (/Query\:\s(\d+)\s*(\S+)\s(\d+)/) { $q = $2; unless ($qbeg) { $qbeg = $1; push(@cigar, ($1-1) . "H") if ($1 > 1); } $qend = $3; if ($show_seq) { my $x = $q; $x =~ s/-//g; $sam[9] .= $x; } } elsif (/Sbjct\:\s(\d+)\s*(\S+)\s(\d+)/) { $s = $2; if ($sam[1] & 0x10) { $sam[3] = $3; } else { $sam[3] = $1 unless ($sam[3]); } &aln2cm(\@cigar, \$q, \$s, \@cmaux); } } &blast_print_sam(\@sam, \@cigar, \@cmaux, $qlen - $qend); } sub blast_print_sam { my ($sam, $cigar, $cmaux, $qrest) = @_; push(@$cigar, $cmaux->[1] . substr("MDI", $cmaux->[0], 1)); push(@$cigar, $qrest . 'H') if ($qrest); if ($sam->[1] & 0x10) { @$cigar = reverse(@$cigar); $sam->[9] = reverse($sam->[9]); $sam->[9] =~ tr/atgcrymkswATGCRYMKSW/tacgyrkmswTACGYRKMSW/; } $sam->[9] = '*' if (!$sam->[9]); $sam->[5] = join('', @$cigar); print join("\t", @$sam), "\n"; } sub aln2cm { my ($cigar, $q, $s, $cmaux) = @_; my $l = length($$q); for (my $i = 0; $i < $l; ++$i) { my $op; # set $op if (substr($$q, $i, 1) eq '-') { $op = 2; } elsif (substr($$s, $i, 1) eq '-') { $op = 1; } else { $op = 0; } # for CIGAR if ($cmaux->[0] == $op) { ++$cmaux->[1]; } else { push(@$cigar, $cmaux->[1] . substr("MDI", $cmaux->[0], 1)); $cmaux->[0] = $op; $cmaux->[1] = 1; } } }
ding-lab/msisensor
vendor/samtools-0.1.19/misc/blast2sam.pl
Perl
mit
2,415
my %c; while (<>) { chomp; my $s = $_; if (/^(\S+\s[wb]):\s*(.*)$/) { my $fen = $1; my @moves = split(/,/, $2); if ($c{$fen}) { foreach my $it (@moves) { $it =~ s/(\w\d)(\w\d)/$1-$2/; my $f = 1; foreach my $x (@{$c{$fen}}) { if ($it eq $x) { $f = 0; } } if ($f) { push(@{$c{$fen}}, $it); } } } else { $c{$fen} = \@moves; } } } while (my ($fen, $it) = each(%c)) { print "$fen: "; my $f = 0; foreach my $x (@$it) { if ($f) { print ","; } print "$x"; $f = 1; } print "\n"; }
GlukKazan/Dagaz
utils/sgf/join.pl
Perl
mit
756
#!/usr/bin/perl # Copyright (c) 1991-2011 Kawahara Lab., Kyoto University # Copyright (c) 2000-2005 Shikano Lab., Nara Institute of Science and Technology # Copyright (c) 2005-2011 Julius project team, Nagoya Institute of Technology # All rights reserved # # Generated automatically from yomi2voca.pl.in by configure. # # ¤Ò¤é¤¬¤Ê -> Julius ɸ½à¥â¥Ç¥ëÍÑÊÑ´¹¥¹¥¯¥ê¥×¥È # Âè2¥Õ¥£¡¼¥ë¥É¤Î¤Ò¤é¤¬¤Ê¤òÊÑ´¹¤¹¤ë¡¥ # # .yomi -> .dict # # ½õ»ì¤Î¡Ö¤Ï¡×¡Ö¤Ø¡×¡Ö¤ò¡×¢ª¡Öw a¡×¡Öe¡×¡Öo¡×¤ÏÊÑ´¹¸å¤Ë¼êư¤Çľ¤¹¤³¤È¡¥ # # ver2: ¾®¤µ¤¤¡Ö¤¡¤£¤¥¤§¤©¡×¤ä¡Ö¤¦¡«¡×¤Ê¤É¤ËÂбþ # # $error = 0; $lineno = 0; while (<>) { # ʸˡÍѤˡ¤"%" ¤Ç»Ï¤Þ¤ë¹Ô¤Ï¤½¤Î¤Þ¤Þ½ÐÎϤ¹¤ë¡¥ if (/^%/){ print; next; } chomp; # ɽµ­¤È¤Ò¤é¤¬¤ÊÆÉ¤ß¤òʬΥ @a = split; $_ = $a[1]; # ¤Ò¤é¤¬¤Ê¡¤Ä¹²»°Ê³°¤Ï¤½¤Î¤Þ¤Þ # 3ʸ»ú°Ê¾å¤«¤é¤Ê¤ëÊÑ´¹µ¬Â§¡Êv a¡Ë s/¤¦¡«¤¡/ b a/g; s/¤¦¡«¤£/ b i/g; s/¤¦¡«¤§/ b e/g; s/¤¦¡«¤©/ b o/g; s/¤¦¡«¤å/ by u/g; # 2ʸ»ú¤«¤é¤Ê¤ëÊÑ´¹µ¬Â§ s/¤¥¡«/ b u/g; s/¤¢¤¡/ a a/g; s/¤¤¤£/ i i/g; s/¤¤¤§/ i e/g; s/¤¤¤ã/ y a/g; s/¤¦¤¥/ u:/g; s/¤¨¤§/ e e/g; s/¤ª¤©/ o:/g; s/¤«¤¡/ k a:/g; s/¤­¤£/ k i:/g; s/¤¯¤¥/ k u:/g; s/¤¯¤ã/ ky a/g; s/¤¯¤å/ ky u/g; s/¤¯¤ç/ ky o/g; s/¤±¤§/ k e:/g; s/¤³¤©/ k o:/g; s/¤¬¤¡/ g a:/g; s/¤®¤£/ g i:/g; s/¤°¤¥/ g u:/g; s/¤°¤ã/ gy a/g; s/¤°¤å/ gy u/g; s/¤°¤ç/ gy o/g; s/¤²¤§/ g e:/g; s/¤´¤©/ g o:/g; s/¤µ¤¡/ s a:/g; s/¤·¤£/ sh i:/g; s/¤¹¤¥/ s u:/g; s/¤¹¤ã/ sh a/g; s/¤¹¤å/ sh u/g; s/¤¹¤ç/ sh o/g; s/¤»¤§/ s e:/g; s/¤½¤©/ s o:/g; s/¤¶¤¡/ z a:/g; s/¤¸¤£/ j i:/g; s/¤º¤¥/ z u:/g; s/¤º¤ã/ zy a/g; s/¤º¤å/ zy u/g; s/¤º¤ç/ zy o/g; s/¤¼¤§/ z e:/g; s/¤¾¤©/ z o:/g; s/¤¿¤¡/ t a:/g; s/¤Á¤£/ ch i:/g; s/¤Ä¤¡/ ts a/g; s/¤Ä¤£/ ts i/g; s/¤Ä¤¥/ ts u:/g; s/¤Ä¤ã/ ch a/g; s/¤Ä¤å/ ch u/g; s/¤Ä¤ç/ ch o/g; s/¤Ä¤§/ ts e/g; s/¤Ä¤©/ ts o/g; s/¤Æ¤§/ t e:/g; s/¤È¤©/ t o:/g; s/¤À¤¡/ d a:/g; s/¤Â¤£/ j i:/g; s/¤Å¤¥/ d u:/g; s/¤Å¤ã/ zy a/g; s/¤Å¤å/ zy u/g; s/¤Å¤ç/ zy o/g; s/¤Ç¤§/ d e:/g; s/¤É¤©/ d o:/g; s/¤Ê¤¡/ n a:/g; s/¤Ë¤£/ n i:/g; s/¤Ì¤¥/ n u:/g; s/¤Ì¤ã/ ny a/g; s/¤Ì¤å/ ny u/g; s/¤Ì¤ç/ ny o/g; s/¤Í¤§/ n e:/g; s/¤Î¤©/ n o:/g; s/¤Ï¤¡/ h a:/g; s/¤Ò¤£/ h i:/g; s/¤Õ¤¥/ f u:/g; s/¤Õ¤ã/ hy a/g; s/¤Õ¤å/ hy u/g; s/¤Õ¤ç/ hy o/g; s/¤Ø¤§/ h e:/g; s/¤Û¤©/ h o:/g; s/¤Ð¤¡/ b a:/g; s/¤Ó¤£/ b i:/g; s/¤Ö¤¥/ b u:/g; s/¤Õ¤ã/ hy a/g; s/¤Ö¤å/ by u/g; s/¤Õ¤ç/ hy o/g; s/¤Ù¤§/ b e:/g; s/¤Ü¤©/ b o:/g; s/¤Ñ¤¡/ p a:/g; s/¤Ô¤£/ p i:/g; s/¤×¤¥/ p u:/g; s/¤×¤ã/ py a/g; s/¤×¤å/ py u/g; s/¤×¤ç/ py o/g; s/¤Ú¤§/ p e:/g; s/¤Ý¤©/ p o:/g; s/¤Þ¤¡/ m a:/g; s/¤ß¤£/ m i:/g; s/¤à¤¥/ m u:/g; s/¤à¤ã/ my a/g; s/¤à¤å/ my u/g; s/¤à¤ç/ my o/g; s/¤á¤§/ m e:/g; s/¤â¤©/ m o:/g; s/¤ä¤¡/ y a:/g; s/¤æ¤¥/ y u:/g; s/¤æ¤ã/ y a:/g; s/¤æ¤å/ y u:/g; s/¤æ¤ç/ y o:/g; s/¤è¤©/ y o:/g; s/¤é¤¡/ r a:/g; s/¤ê¤£/ r i:/g; s/¤ë¤¥/ r u:/g; s/¤ë¤ã/ ry a/g; s/¤ë¤å/ ry u/g; s/¤ë¤ç/ ry o/g; s/¤ì¤§/ r e:/g; s/¤í¤©/ r o:/g; s/¤ï¤¡/ w a:/g; s/¤ò¤©/ o:/g; s/¤¦¡«/ b u/g; s/¤Ç¤£/ d i/g; s/¤Ç¤§/ d e:/g; s/¤Ç¤ã/ dy a/g; s/¤Ç¤å/ dy u/g; s/¤Ç¤ç/ dy o/g; s/¤Æ¤£/ t i/g; s/¤Æ¤§/ t e:/g; s/¤Æ¤ã/ ty a/g; s/¤Æ¤å/ ty u/g; s/¤Æ¤ç/ ty o/g; s/¤¹¤£/ s i/g; s/¤º¤¡/ z u a/g; s/¤º¤£/ z i/g; s/¤º¤¥/ z u/g; s/¤º¤ã/ zy a/g; s/¤º¤å/ zy u/g; s/¤º¤ç/ zy o/g; s/¤º¤§/ z e/g; s/¤º¤©/ z o/g; s/¤­¤ã/ ky a/g; s/¤­¤å/ ky u/g; s/¤­¤ç/ ky o/g; s/¤·¤ã/ sh a/g; s/¤·¤å/ sh u/g; s/¤·¤§/ sh e/g; s/¤·¤ç/ sh o/g; s/¤Á¤ã/ ch a/g; s/¤Á¤å/ ch u/g; s/¤Á¤§/ ch e/g; s/¤Á¤ç/ ch o/g; s/¤È¤¥/ t u/g; s/¤È¤ã/ ty a/g; s/¤È¤å/ ty u/g; s/¤È¤ç/ ty o/g; s/¤É¤¡/ d o a/g; s/¤É¤¥/ d u/g; s/¤É¤ã/ dy a/g; s/¤É¤å/ dy u/g; s/¤É¤ç/ dy o/g; s/¤É¤©/ d o:/g; s/¤Ë¤ã/ ny a/g; s/¤Ë¤å/ ny u/g; s/¤Ë¤ç/ ny o/g; s/¤Ò¤ã/ hy a/g; s/¤Ò¤å/ hy u/g; s/¤Ò¤ç/ hy o/g; s/¤ß¤ã/ my a/g; s/¤ß¤å/ my u/g; s/¤ß¤ç/ my o/g; s/¤ê¤ã/ ry a/g; s/¤ê¤å/ ry u/g; s/¤ê¤ç/ ry o/g; s/¤®¤ã/ gy a/g; s/¤®¤å/ gy u/g; s/¤®¤ç/ gy o/g; s/¤Â¤§/ j e/g; s/¤Â¤ã/ j a/g; s/¤Â¤å/ j u/g; s/¤Â¤ç/ j o/g; s/¤¸¤§/ j e/g; s/¤¸¤ã/ j a/g; s/¤¸¤å/ j u/g; s/¤¸¤ç/ j o/g; s/¤Ó¤ã/ by a/g; s/¤Ó¤å/ by u/g; s/¤Ó¤ç/ by o/g; s/¤Ô¤ã/ py a/g; s/¤Ô¤å/ py u/g; s/¤Ô¤ç/ py o/g; s/¤¦¤¡/ u a/g; s/¤¦¤£/ w i/g; s/¤¦¤§/ w e/g; s/¤¦¤©/ w o/g; s/¤Õ¤¡/ f a/g; s/¤Õ¤£/ f i/g; s/¤Õ¤¥/ f u/g; s/¤Õ¤ã/ hy a/g; s/¤Õ¤å/ hy u/g; s/¤Õ¤ç/ hy o/g; s/¤Õ¤§/ f e/g; s/¤Õ¤©/ f o/g; # 1²»¤«¤é¤Ê¤ëÊÑ´¹µ¬Â§ s/¤¢/ a/g; s/¤¤/ i/g; s/¤¦/ u/g; s/¤¨/ e/g; s/¤ª/ o/g; s/¤«/ k a/g; s/¤­/ k i/g; s/¤¯/ k u/g; s/¤±/ k e/g; s/¤³/ k o/g; s/¤µ/ s a/g; s/¤·/ sh i/g; s/¤¹/ s u/g; s/¤»/ s e/g; s/¤½/ s o/g; s/¤¿/ t a/g; s/¤Á/ ch i/g; s/¤Ä/ ts u/g; s/¤Æ/ t e/g; s/¤È/ t o/g; s/¤Ê/ n a/g; s/¤Ë/ n i/g; s/¤Ì/ n u/g; s/¤Í/ n e/g; s/¤Î/ n o/g; s/¤Ï/ h a/g; s/¤Ò/ h i/g; s/¤Õ/ f u/g; s/¤Ø/ h e/g; s/¤Û/ h o/g; s/¤Þ/ m a/g; s/¤ß/ m i/g; s/¤à/ m u/g; s/¤á/ m e/g; s/¤â/ m o/g; s/¤é/ r a/g; s/¤ê/ r i/g; s/¤ë/ r u/g; s/¤ì/ r e/g; s/¤í/ r o/g; s/¤¬/ g a/g; s/¤®/ g i/g; s/¤°/ g u/g; s/¤²/ g e/g; s/¤´/ g o/g; s/¤¶/ z a/g; s/¤¸/ j i/g; s/¤º/ z u/g; s/¤¼/ z e/g; s/¤¾/ z o/g; s/¤À/ d a/g; s/¤Â/ j i/g; s/¤Å/ z u/g; s/¤Ç/ d e/g; s/¤É/ d o/g; s/¤Ð/ b a/g; s/¤Ó/ b i/g; s/¤Ö/ b u/g; s/¤Ù/ b e/g; s/¤Ü/ b o/g; s/¤Ñ/ p a/g; s/¤Ô/ p i/g; s/¤×/ p u/g; s/¤Ú/ p e/g; s/¤Ý/ p o/g; s/¤ä/ y a/g; s/¤æ/ y u/g; s/¤è/ y o/g; s/¤ï/ w a/g; s/¤ð/ i/g; s/¤ñ/ e/g; s/¤ó/ N/g; s/¤Ã/ q/g; s/¡¼/:/g; # ¤³¤³¤Þ¤Ç¤Ë½èÍý¤µ¤ì¤Æ¤Ê¤¤ ¤¡¤£¤¥¤§¤© ¤Ï¤½¤Î¤Þ¤ÞÂçʸ»ú°·¤¤ s/¤¡/ a/g; s/¤£/ i/g; s/¤¥/ u/g; s/¤§/ e/g; s/¤©/ o/g; s/¤î/ w a/g; s/¤©/ o/g; # ¤½¤Î¾ÆÃÊ̤ʥ롼¥ë s/¤ò/ o/g; # ºÇ½é¤Î¶õÇò¤òºï¤ë s/^ ([a-z])/$1/g; # ÊÑ´¹¤Î·ë²ÌĹ²»µ­¹æ¤¬Â³¤¯¤³¤È¤¬¤Þ¤ì¤Ë¤¢¤ë¤Î¤Ç°ì¤Ä¤Ë¤Þ¤È¤á¤ë s/:+/:/g; # ¥¢¥ë¥Õ¥¡¥Ù¥Ã¥ÈÎó¤Ë¤Ê¤Ã¤Æ¤¤¤Ê¤¤¾ì¹ç¡¤ÊÑ´¹¤Ë¼ºÇÔ¤·¤Æ¤¤¤ë¤Î¤Ç # ɸ½à¥¨¥é¡¼½ÐÎϤ˽ÐÎϤ¹¤ë¡¥ $lineno++; if (! /^[ a-zA-Z:]+$/) { if ($error == 0) { $error = 1; print STDERR "Error: (they were also printed to stdout)\n"; } print STDERR "line " , $lineno , ": " , @a[0], "\t", $_,"\n"; } print @a[0], "\t", $_,"\n"; }
julius-speech/grammar-kit
bin/win32/yomi2voca.pl
Perl
mit
6,813
#!/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/. # ==================================================================== # # February 2012 # # The module implements bn_GF2m_mul_2x2 polynomial multiplication # used in bn_gf2m.c. It's kind of low-hanging mechanical port from # C for the time being... The subroutine runs in 37 cycles, which is # 4.5x faster than compiler-generated code. Though comparison is # totally unfair, because this module utilizes Galois Field Multiply # instruction. while (($output=shift) && ($output!~/\w[\w\-]*\.\w+$/)) {} open STDOUT,">$output"; ($rp,$a1,$a0,$b1,$b0)=("A4","B4","A6","B6","A8"); # argument vector ($Alo,$Alox0,$Alox1,$Alox2,$Alox3)=map("A$_",(16..20)); ($Ahi,$Ahix0,$Ahix1,$Ahix2,$Ahix3)=map("B$_",(16..20)); ($B_0,$B_1,$B_2,$B_3)=("B5","A5","A7","B7"); ($A,$B)=($Alo,$B_1); $xFF="B1"; sub mul_1x1_upper { my ($A,$B)=@_; $code.=<<___; EXTU $B,8,24,$B_2 ; smash $B to 4 bytes || AND $B,$xFF,$B_0 || SHRU $B,24,$B_3 SHRU $A,16, $Ahi ; smash $A to two halfwords || EXTU $A,16,16,$Alo XORMPY $Alo,$B_2,$Alox2 ; 16x8 bits muliplication || XORMPY $Ahi,$B_2,$Ahix2 || EXTU $B,16,24,$B_1 XORMPY $Alo,$B_0,$Alox0 || XORMPY $Ahi,$B_0,$Ahix0 XORMPY $Alo,$B_3,$Alox3 || XORMPY $Ahi,$B_3,$Ahix3 XORMPY $Alo,$B_1,$Alox1 || XORMPY $Ahi,$B_1,$Ahix1 ___ } sub mul_1x1_merged { my ($OUTlo,$OUThi,$A,$B)=@_; $code.=<<___; EXTU $B,8,24,$B_2 ; smash $B to 4 bytes || AND $B,$xFF,$B_0 || SHRU $B,24,$B_3 SHRU $A,16, $Ahi ; smash $A to two halfwords || EXTU $A,16,16,$Alo XOR $Ahix0,$Alox2,$Ahix0 || MV $Ahix2,$OUThi || XORMPY $Alo,$B_2,$Alox2 XORMPY $Ahi,$B_2,$Ahix2 || EXTU $B,16,24,$B_1 || XORMPY $Alo,$B_0,A1 ; $Alox0 XOR $Ahix1,$Alox3,$Ahix1 || SHL $Ahix0,16,$OUTlo || SHRU $Ahix0,16,$Ahix0 XOR $Alox0,$OUTlo,$OUTlo || XOR $Ahix0,$OUThi,$OUThi || XORMPY $Ahi,$B_0,$Ahix0 || XORMPY $Alo,$B_3,$Alox3 || SHL $Alox1,8,$Alox1 || SHL $Ahix3,8,$Ahix3 XOR $Alox1,$OUTlo,$OUTlo || XOR $Ahix3,$OUThi,$OUThi || XORMPY $Ahi,$B_3,$Ahix3 || SHL $Ahix1,24,$Alox1 || SHRU $Ahix1,8, $Ahix1 XOR $Alox1,$OUTlo,$OUTlo || XOR $Ahix1,$OUThi,$OUThi || XORMPY $Alo,$B_1,$Alox1 || XORMPY $Ahi,$B_1,$Ahix1 || MV A1,$Alox0 ___ } sub mul_1x1_lower { my ($OUTlo,$OUThi)=@_; $code.=<<___; ;NOP XOR $Ahix0,$Alox2,$Ahix0 || MV $Ahix2,$OUThi NOP XOR $Ahix1,$Alox3,$Ahix1 || SHL $Ahix0,16,$OUTlo || SHRU $Ahix0,16,$Ahix0 XOR $Alox0,$OUTlo,$OUTlo || XOR $Ahix0,$OUThi,$OUThi || SHL $Alox1,8,$Alox1 || SHL $Ahix3,8,$Ahix3 XOR $Alox1,$OUTlo,$OUTlo || XOR $Ahix3,$OUThi,$OUThi || SHL $Ahix1,24,$Alox1 || SHRU $Ahix1,8, $Ahix1 XOR $Alox1,$OUTlo,$OUTlo || XOR $Ahix1,$OUThi,$OUThi ___ } $code.=<<___; .text .if .ASSEMBLER_VERSION<7000000 .asg 0,__TI_EABI__ .endif .if __TI_EABI__ .asg bn_GF2m_mul_2x2,_bn_GF2m_mul_2x2 .endif .global _bn_GF2m_mul_2x2 _bn_GF2m_mul_2x2: .asmfunc MVK 0xFF,$xFF ___ &mul_1x1_upper($a0,$b0); # a0·b0 $code.=<<___; || MV $b1,$B MV $a1,$A ___ &mul_1x1_merged("A28","B28",$A,$B); # a0·b0/a1·b1 $code.=<<___; || XOR $b0,$b1,$B XOR $a0,$a1,$A ___ &mul_1x1_merged("A31","B31",$A,$B); # a1·b1/(a0+a1)·(b0+b1) $code.=<<___; XOR A28,A31,A29 || XOR B28,B31,B29 ; a0·b0+a1·b1 ___ &mul_1x1_lower("A30","B30"); # (a0+a1)·(b0+b1) $code.=<<___; || BNOP B3 XOR A29,A30,A30 || XOR B29,B30,B30 ; (a0+a1)·(b0+b1)-a0·b0-a1·b1 XOR B28,A30,A30 || STW A28,*${rp}[0] XOR B30,A31,A31 || STW A30,*${rp}[1] STW A31,*${rp}[2] STW B31,*${rp}[3] .endasmfunc ___ print $code; close STDOUT;
sim9108/SDKS
LibOpenSSL/src/bn/asm/c64xplus-gf2m.pl
Perl
mit
3,758
package Pakket::Controller::Scaffold; # ABSTRACT: Scaffold package source and spec use v5.22; use Moose; use MooseX::Clone; use MooseX::StrictConstructor; use namespace::autoclean; # core use File::Spec; use List::Util qw(any); use experimental qw(declared_refs refaliasing signatures); # non core use JSON::MaybeXS qw(decode_json); use Module::Runtime qw(use_module); use Path::Tiny; # local use Pakket::Constants qw( PARCEL_FILES_DIR PARCEL_METADATA_FILE ); use Pakket::Controller::Install; use Pakket::Type::Package; use Pakket::Type::PackageQuery; use constant { 'BUILD_DIR_TEMPLATE' => 'pakket-build-%s-XXXXXX', 'DEFAULT_PREFIX' => $ENV{'PERL_LOCAL_LIB_ROOT'} || '~/perl5', }; has [qw(dry_run)] => ( 'is' => 'ro', 'isa' => 'Bool', 'default' => 0, ); has [qw(keep)] => ( 'is' => 'ro', 'isa' => 'Bool', 'default' => 0, ); has [qw(overwrite)] => ( 'is' => 'ro', 'isa' => 'Int', 'default' => 0, ); has [qw(prefix)] => ( 'is' => 'ro', 'isa' => 'Maybe[Str]', ); has [qw(cpan_02packages)] => ( 'is' => 'ro', 'isa' => 'Maybe[Str]', ); has '_scaffolders_cache' => ( 'is' => 'ro', 'isa' => 'HashRef', 'lazy' => 1, 'default' => sub {+{}}, ); has 'installer' => ( 'is' => 'ro', 'isa' => 'Maybe[Pakket::Controller::Install]', 'lazy' => 1, 'clearer' => '_clear_installer', 'default' => sub ($self) { return Pakket::Controller::Install->new( 'pakket_dir' => path(File::Spec->devnull), # installer is unable install by default 'parcel_repo' => $self->parcel_repo, 'phases' => $self->phases, $self->%{qw(config log log_depth)}, ); }, ); with qw( MooseX::Clone Pakket::Controller::Role::CanProcessQueries Pakket::Role::CanFilterRequirements Pakket::Role::HasConfig Pakket::Role::HasLog Pakket::Role::HasParcelRepo Pakket::Role::HasSourceRepo Pakket::Role::HasSpecRepo Pakket::Role::Perl::BootstrapModules Pakket::Role::Perl::HasCpan ); sub execute ($self, %params) { return $self->process_queries(%params); } sub process_query ($self, $query, %params) { my $id = $query->short_name; { ## check processed packages my (\@found, undef) = $self->filter_packages_in_cache({$id => $query}, $params{'processing'} // {}); @found and $self->log->info('Skipping as we already processed or scheduled processing:', $id) and return; } { ## check existing packages if ($self->overwrite <= $query->as_prereq) { # if overwrite < 2 do not rebuild prereqs my ($package) = $self->spec_repo->filter_queries([$query]); $package and $self->log->notice('Skipping as we already have spec:', $package->id) and return; } } if (!exists $params{'build_dir'}) { $params{'build_dir'} = Path::Tiny->tempdir(sprintf (BUILD_DIR_TEMPLATE(), $query->name), 'CLEANUP' => !$self->keep); } $params{'processing'} //= {}; $params{'prefix'} //= path($self->prefix || DEFAULT_PREFIX())->absolute; $params{'pkg_dir'} //= $params{'build_dir'}->child($params{'prefix'})->absolute; $self->log->noticef('Scaffolding package: %s=%s', $id, $query->requirement); $self->_do_scaffold_query($query, %params); return; } sub _do_scaffold_query ($self, $query, %params) { my $scaffolder = $self->_get_scaffolder($query->category); $self->_process_meta($query, %params); my $package = $scaffolder->execute($query, \%params); $params{'processing'}{$package->short_name}{$package->version}{$package->release} = 1; if (!$params{'no_prereqs'}) { $self->process_prereqs( $package, %params, 'phases' => $params{'phases'} // $self->phases, 'types' => $params{'types'} // $self->types, ); } if ($self->dry_run) { $self->log->notice('Dry run, not saving:', $package->id); } else { $self->log->notice('Saving spec for:', $package->id); $self->add_spec_for_package($package); $self->log->notice('Saving source for:', $package->id); $self->add_source_for_package($package, $params{'sources'}); } $self->succeeded->{$package->id}++; return; } sub _get_scaffolder ($self, $category) { exists $self->_scaffolders_cache->{$category} and return $self->_scaffolders_cache->{$category}; my @valid_categories = qw(native perl); any {$category eq $_} @valid_categories or $self->croak('I do not have a scaffolder for category:', $category); my $scaffolder = $self->_scaffolders_cache->{$category} = use_module(sprintf ('%s::%s', __PACKAGE__, ucfirst $category))->new($self->%{qw(config log log_depth)}); $self->_bootstrap_scaffolder($scaffolder); return $scaffolder; } sub _bootstrap_scaffolder ($self, $scaffolder) { my ($modules, $requirements) = $scaffolder->bootstrap_prepare_modules(); $modules && $modules->@* or return; my (\@found, \@not_found) = $self->spec_repo->filter_requirements({$requirements->%*}); if (@not_found) { ## if even one of bootstrap packages not found we shoud rebuild whole bootstrap environment $self->log->notice('Bootstrapping scaffolder started:', $scaffolder->type); $scaffolder->bootstrap($self, $modules, $requirements); $self->log->notice('Bootstrapping scaffolder finished:', $scaffolder->type); } return; } sub _process_meta ($self, $query, %params) { $self->process_prereqs( $query, %params, 'phases' => [qw(configure)], 'types' => [qw(requires)], 'handler' => sub ($self, $queries, %p) { my (undef, \@not_found) = $self->filter_packages_in_cache(as_requirements($queries), $params{'processing'}); if (my @parcels = $self->parcel_repo->filter_queries(\@not_found)) { foreach my $package (@parcels) { $self->log->notice('Installing package:', $package->id); $self->_do_install_package($package, %p); } } }, ); return; } sub _do_install_package ($self, $package, %params) { $params{'processing'}{$package->short_name}{$package->version}{$package->release} = 1; my $parcel_dir = $self->parcel_repo->retrieve_package_file($package); my $spec_file = $parcel_dir->child(PARCEL_FILES_DIR(), PARCEL_METADATA_FILE()); my $spec = decode_json($spec_file->slurp_utf8); # Generate a Package instance from the spec using the information we have on it $package = Pakket::Type::Package->new_from_specdata($spec, $package->%{qw(as_prereq)}); if (!$params{'no_prereqs'}) { $self->process_prereqs( $package, %params, 'phases' => $params{'phases'} // $self->phases, 'types' => $params{'types'} // $self->types, ); } $self->log->info('Processing parcel:', $package->id, ('(as prereq)') x !!$package->as_prereq); $self->installer->install_parcel($package, $parcel_dir, $params{'pkg_dir'}); return; } before [qw(_do_scaffold_query)] => sub ($self, @) { return $self->log_depth_change(+1); }; after [qw(_do_scaffold_query)] => sub ($self, @) { return $self->log_depth_change(-1); }; __PACKAGE__->meta->make_immutable; 1; __END__
xsawyerx/pakket
lib/Pakket/Controller/Scaffold.pm
Perl
mit
7,566
############################################################################### # # This file copyright (c) 2001-2008 Randy J. Ray, all rights reserved # # See "LICENSE" in the documentation for licensing and redistribution terms. # ############################################################################### # # $Id: Procedure.pm 343 2008-04-09 09:54:36Z rjray $ # # Description: This class abstracts out all the procedure-related # operations from the RPC::XML::Server class # # Functions: new # name \ # code \ # signature \ These are the accessor functions for the # help / data in the object, though it's visible. # version / # hidden / # clone # is_valid # add_signature # delete_signature # make_sig_table # match_signature # reload # load_XPL_file # # Libraries: XML::Parser (used only on demand in load_XPL_file) # File::Spec # # Global Consts: $VERSION # # Environment: None. # ############################################################################### package RPC::XML::Procedure; use 5.005; use strict; use vars qw($VERSION); use subs qw(new is_valid name code signature help version hidden add_signature delete_signature make_sig_table match_signature reload load_XPL_file); use AutoLoader 'AUTOLOAD'; require File::Spec; $VERSION = '1.15'; ############################################################################### # # Sub Name: new # # Description: Create a new object of this class, storing the info on # regular keys (no obfuscation used here). # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $class in scalar Class to bless into # @argz in variable Disposition is variable; see # below # # Returns: Success: object ref # Failure: error string # ############################################################################### sub new { my $class = shift; my @argz = @_; my $data; # This will be a hashref that eventually gets blessed $class = ref($class) || $class; # # There are three things that @argz could be: # if (ref $argz[0]) { # 1. A hashref containing all the relevant keys $data = {}; %$data = %{$argz[0]}; } elsif (@argz == 1) { # 2. Exactly one non-ref element, a file to load # And here is where I cheat in a way that makes even me uncomfortable. # # Loading code from an XPL file, it can actually be of a type other # than how this constructor was called. So what we are going to do is # this: If $class is undef, that can only mean that we were called # with the intent of letting the XPL file dictate the resulting object. # If $class is set, then we'll call load_XPL_file normally, as a # method, to allow for subclasses to tweak things. if (defined $class) { $data = $class->load_XPL_file($argz[0]); return $data unless ref $data; # load_XPL_path signalled an error } else { # Spoofing the "class" argument to load_XPL_file makes me feel # even dirtier... $data = load_XPL_file(\$class, $argz[0]); return $data unless ref $data; # load_XPL_path signalled an error $class = "RPC::XML::$class"; } } else { # 3. If there is more than one arg, it's a sort-of-hash. That is, the # key 'signature' is allowed to repeat. my ($key, $val); $data = {}; $data->{signature} = []; while (@argz) { ($key, $val) = splice(@argz, 0, 2); if ($key eq 'signature') { # Since there may be more than one signature, we allow it to # repeat. Of course, that's also why we can't just take @argz # directly as a hash. *shrug* push(@{$data->{signature}}, ref($val) ? join(' ', @$val) : $val); } elsif (exists $data->{$key}) { return "${class}::new: Key '$key' may not be repeated"; } else { $data->{$key} = $val; } } } return "${class}::new: Missing required data" unless (exists $data->{signature} and (ref($data->{signature}) eq 'ARRAY') and scalar(@{$data->{signature}}) and $data->{name} and $data->{code}); bless $data, $class; # This needs to happen post-bless in case of error (for error messages) $data->make_sig_table; } ############################################################################### # # Sub Name: make_sig_table # # Description: Create a hash table of the signatures that maps to the # corresponding return type for that particular invocation. # Makes looking up call patterns much easier. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # # Returns: Success: $self # Failure: error message # ############################################################################### sub make_sig_table { my $self = shift; my ($sig, $return, $rest); delete $self->{sig_table}; for $sig (@{$self->{signature}}) { ($return, $rest) = split(/ /, $sig, 2); $rest = '' unless $rest; # If the key $rest already exists, then this is a collision return ref($self) . '::make_sig_table: Cannot have two different ' . "return values for one set of params ($return vs. " . "$self->{sig_table}->{$rest})" if $self->{sig_table}->{$rest}; $self->{sig_table}->{$rest} = $return; } $self; } # # These are basic accessor/setting functions for the various attributes # sub name { $_[0]->{name}; } # "name" cannot be changed at this level sub help { $_[1] and $_[0]->{help} = $_[1]; $_[0]->{help}; } sub version { $_[1] and $_[0]->{version} = $_[1]; $_[0]->{version}; } sub hidden { $_[1] and $_[0]->{hidden} = $_[1]; $_[0]->{hidden}; } sub code { ref $_[1] eq 'CODE' and $_[0]->{code} = $_[1]; $_[0]->{code}; } sub signature { if ($_[1] and ref $_[1] eq 'ARRAY') { my $old = $_[0]->{signature}; $_[0]->{signature} = $_[1]; unless (ref($_[0]->make_sig_table)) { # If it failed to re-init the table, restore the old list (and old # table). We don't have to check this return, since it had worked $_[0]->{signature} = $old; $_[0]->make_sig_table; } } # Return a copy of the array, not the original [ @{$_[0]->{signature}} ]; } package RPC::XML::Method; use strict; @RPC::XML::Method::ISA = qw(RPC::XML::Procedure); package RPC::XML::Procedure; 1; =head1 NAME RPC::XML::Procedure - Object encapsulation of server-side RPC procedures =head1 SYNOPSIS require RPC::XML::Procedure; ... $method_1 = RPC::XML::Procedure->new({ name => 'system.identity', code => sub { ... }, signature => [ 'string' ] }); $method_2 = RPC::XML::Procedure->new('/path/to/status.xpl'); =head1 IMPORTANT NOTE This package is comprised of the code that was formerly B<RPC::XML::Method>. The package was renamed when the decision was made to support procedures and methods as functionally different entities. It is not necessary to include both this module and B<RPC::XML::Method> -- this module provides the latter as an empty subclass. In time, B<RPC::XML::Method> will be removed from the distribution entirely. =head1 DESCRIPTION The B<RPC::XML::Procedure> package is designed primarily for behind-the-scenes use by the B<RPC::XML::Server> class and any subclasses of it. It is documented here in case a project chooses to sub-class it for their purposes (which would require setting the C<method_class> attribute when creating server objects, see L<RPC::XML::Server>). This package grew out of the increasing need to abstract the operations that related to the methods a given server instance was providing. Previously, methods were passed around simply as hash references. It was a small step then to move them into a package and allow for operations directly on the objects themselves. In the spirit of the original hashes, all the key data is kept in clear, intuitive hash keys (rather than obfuscated as the other classes do). Thus it is important to be clear on the interface here before sub-classing this package. =head1 USAGE The following methods are provided by this class: =over 4 =item new(FILE|HASHREF|LIST) Creates a new object of the class, and returns a reference to it. The arguments to the constructor are variable in nature, depending on the type: =over 8 =item FILE If there is exactly on argument that is not a reference, it is assumed to be a filename from which the method is to be loaded. This is presumed to be in the B<XPL> format descibed below (see L</"XPL File Structure">). If the file cannot be opened, or if once opened cannot be parsed, an error is raised. =item HASHREF If there is exactly one argument that is a reference, it is assumed to be a hash with the relevant information on the same keys as the object itself uses. This is primarily to support backwards-compatibility to code written when methods were implemented simply as hash references. =item LIST If there is more than one argument in the list, then the list is assumed to be a sort of "ersatz" hash construct, in that one of the keys (C<signature>) is allowed to occur multiple times. Otherwise, each of the following is allowed, but may only occur once: =over 12 =item name The name of the method, as it will be presented to clients =item code A reference to a subroutine, or an anonymous subroutine, that will receive calls for the method =item signature (May appear more than once) Provides one calling-signature for the method, as either a space-separated string of types or a list-reference =item help The help-text for a method, which is generally used as a part of the introspection interface for a server =item version The version number/string for the method =item hidden A boolean (true or false) value indicating whether the method should be hidden from introspection and similar listings =back Note that all of these correspond to the values that can be changed via the accessor methods detailed later. =back If any error occurs during object creation, an error message is returned in lieu of the object reference. =item clone Create a copy of the calling object, and return the new reference. All elements are copied over cleanly, except for the code reference stored on the C<code> hash key. The clone will point to the same code reference as the original. Elements such as C<signature> are copied, so that changes to the clone will not impact the original. =item name Returns the name by which the server is advertising the method. Unlike the next few accessors, this cannot be changed on an object. In order to streamline the managment of methods within the server classes, this must persist. However, the other elements may be used in the creation of a new object, which may then be added to the server, if the name absolutely must change. =item code([NEW]) Returns or sets the code-reference that will receive calls as marshalled by the server. The existing value is lost, so if it must be preserved, then it should be retrieved prior to the new value being set. =item signature([NEW]) Return a list reference containing the signatures, or set it. Each element of the list is a string of space-separated types (the first of which is the return type the method produces in that calling context). If this is being used to set the signature, then an array reference must be passed that contains one or more strings of this nature. Nested list references are not allowed at this level. If the new signatures would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is silently restored. =item help([NEW]) Returns or sets the help-text for the method. As with B<code>, the previous value is lost. =item hidden([NEW]) Returns or sets the hidden status of the method. Setting it loses the previous value. =item version([NEW]) Returns or sets the version string for the method (overwriting as with the other accessors). =item is_valid Returns a true/false value as to whether the object currently has enough content to be a valid method for a server to publish. This entails having at the very least a name, one or more signatures, and a code-reference to route the calls to. A server created from the classes in this software suite will not accept a method that is not valid. =item add_signature(LIST) Add one or more signatures (which may be a list reference or a string) to the internal tables for this method. Duplicate signatures are ignored. If the new signature would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is restored and an error message is returned. =item delete_signature(LIST) Deletes the signature or signatures (list reference or string) from the internal tables. Quietly ignores any signature that does not exist. If the new signature would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is restored and an error message is returned. =item match_signature(SIGNATURE) Check that the passed-in signature is known to the method, and if so returns the type that the method should be returning as a result of the call. Returns a zero (0) otherwise. This differs from other signature operations in that the passed-in signature (which may be a list-reference or a string) B<I<does not include the return type>>. This method is provided so that servers may check a list of arguments against type when marshalling an incoming call. For example, a signature of C<'int int'> would be tested for by calling C<$M-E<gt>match_signature('int')> and expecting the return value to be C<int>. =item call(SERVER, PARAMLIST) Execute the code that this object encapsulates, using the list of parameters passed in PARAMLIST. The SERVER argument should be an object derived from the B<RPC::XML::Server> class. For some types of procedure objects, this becomes the first argument of the parameter list to simulate a method call as if it were on the server object itself. The return value should be a data object (possibly a B<RPC::XML::fault>), but may not always be pre-encoded. Errors trapped in C<$@> are converted to fault objects. This method is generally used in the C<dispatch> method of the server class, where the return value is subsequently wrapped within a B<RPC::XML::response> object. =item reload Instruct the object to reload itself from the file it originally was loaded from, assuming that it was loaded from a file to begin with. Returns an error if the method was not originally loaded from a file, or if an error occurs during the reloading operation. =back =head2 Additional Hash Data In addition to the attributes managed by the accessors documented earlier, the following hash keys are also available for use. These are also not strongly protected, and the same care should be taken before altering any of them: =over 4 =item file When the method was loaded from a file, this key contains the path to the file used. =item mtime When the method was loaded from a file, this key contains the modification-time of the file, as a UNIX-style C<time> value. This is used to check for changes to the file the code was originally read from. =item called When the method is being used by one of the server classes provided in this software suite, this key is incremented each time the server object dispatches a request to the method. This can later be checked to provide some indication of how frequently the method is being invoked. =back =head2 XPL File Structure This section focuses on the way in which methods are expressed in these files, referred to here as "XPL files" due to the C<*.xpl> filename extension (which stands for "XML Procedure Layout"). This mini-dialect, based on XML, is meant to provide a simple means of specifying method definitions separate from the code that comprises the application itself. Thus, methods may theoretically be added, removed, debugged or even changed entirely without requiring that the server application itself be rebuilt (or, possibly, without it even being restarted). =over 4 =item The XML-based file structure The B<XPL Procedure Layout> dialect is a very simple application of XML to the problem of expressing the method in such a way that it could be useful to other packages than this one, or useful in other contexts than this one. The lightweight DTD for the layout can be summarized as: <!ELEMENT proceduredef (name, version?, hidden?, signature+, help?, code)> <!ELEMENT methoddef (name, version?, hidden?, signature+, help?, code)> <!ELEMENT name (#PCDATA)> <!ELEMENT version (#PCDATA)> <!ELEMENT hidden EMPTY> <!ELEMENT signature (#PCDATA)> <!ELEMENT help (#PCDATA)> <!ELEMENT code (#PCDATA)> <!ATTLIST code language (#PCDATA)> The containing tag is always one of C<E<lt>methoddefE<gt>> or C<E<lt>proceduredefE<gt>>. The tags that specify name, signatures and the code itself must always be present. Some optional information may also be supplied. The "help" text, or what an introspection API would expect to use to document the method, is also marked as optional. Having some degree of documentation for all the methods a server provides is a good rule of thumb, however. The default methods that this package provides are turned into XPL files by the B<make_method> tool (see L<make_method>). The final forms of these may serve as direct examples of what the file should look like. =item Information used only for book-keeping Some of the information in the XPL file is only for book-keeping: the version stamp of a method is never involved in the invocation. The server also keeps track of the last-modified time of the file the method is read from, as well as the full directory path to that file. The C<E<lt>hidden /E<gt>> tag is used to identify those methods that should not be exposed to the outside world through any sort of introspection/documentation API. They are still available and callable, but the client must possess the interface information in order to do so. =item The information crucial to the method The name, signatures and code must be present for obvious reasons. The C<E<lt>nameE<gt>> tag tells the server what external name this procedure is known by. The C<E<lt>signatureE<gt>> tag, which may appear more than once, provides the definition of the interface to the function in terms of what types and quantity of arguments it will accept, and for a given set of arguments what the type of the returned value is. Lastly is the C<E<lt>codeE<gt>> tag, without which there is no procedure to remotely call. =item Why the <code> tag allows multiple languages Note that the C<E<lt>codeE<gt>> tag is the only one with an attribute, in this case "language". This is designed to allow for one XPL file to provide a given method in multiple languages. Why, one might ask, would there be a need for this? It is the hope behind this package that collections of RPC suites may one day be made available as separate entities from this specific software package. Given this hope, it is not unreasonable to suggest that such a suite of code might be implemented in more than one language (each of Perl, Python, Ruby and Tcl, for example). Languages which all support the means by which to take new code and add it to a running process on demand (usually through an "C<eval>" keyword or something similar). If the file F<A.xpl> is provided with implementations in all four of the above languages, the name, help text, signature and even hidden status would likely be identical. So, why not share the non-language-specific elements in the spirit of re-use? =item The "make_method" utility The utility script C<make_method> is provided as a part of this software suite. It allows for the automatic creation of XPL files from either command-line information or from template files. It has a wide variety of features and options, and is out of the scope of this particular manual page. The package F<Makefile.PL> features an example of engineering the automatic generation of XPL files and their delivery as a part of the normal Perl module build process. Using this tool is highly recommended over managing XPL files directly. For the full details, see L<make_method>. =back =head1 DIAGNOSTICS Unless otherwise noted in the individual documentation sections, all methods return the object reference on success, or a (non-reference) text string containing the error message upon failure. =head1 CAVEATS Moving the method management to a separate class adds a good deal of overhead to the general system. The trade-off in reduced complexity and added maintainability should offset this. =head1 LICENSE This module and the code within are released under the terms of the Artistic License 2.0 (http://www.opensource.org/licenses/artistic-license-2.0.php). This code may be redistributed under either the Artistic License or the GNU Lesser General Public License (LGPL) version 2.1 (http://www.opensource.org/licenses/lgpl-license.php). =head1 SEE ALSO L<RPC::XML::Server>, L<make_method> =head1 AUTHOR Randy J. Ray <rjray@blackperl.com> =cut __END__ ############################################################################### # # Sub Name: clone # # Description: Create a near-exact copy of the invoking object, save that # the listref in the "signature" key is a copy, not a ref # to the same list. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # # Returns: Success: $new_self # Failure: error message # ############################################################################### sub clone { my $self = shift; my $new_self = {}; for (keys %$self) { next if $_ eq 'signature'; $new_self->{$_} = $self->{$_}; } $new_self->{signature} = []; @{$new_self->{signature}} = @{$self->{signature}}; bless $new_self, ref($self); } ############################################################################### # # Sub Name: is_valid # # Description: Boolean test to tell if the calling object has sufficient # data to be used as a server method for RPC::XML::Server or # Apache::RPC::Server. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object to test # # Returns: Success: 1, valid/complete # Failure: 0, invalid/incomplete # ############################################################################### sub is_valid { my $self = shift; return ((ref($self->{code}) eq 'CODE') and $self->{name} and (ref($self->{signature}) && scalar(@{$self->{signature}}))); } ############################################################################### # # Sub Name: add_signature # delete_signature # # Description: This pair of functions may be used to add and remove # signatures from a method-object. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # @args in list One or more signatures # # Returns: Success: $self # Failure: error string # ############################################################################### sub add_signature { my $self = shift; my @args = @_; my (%sigs, $one_sig, $tmp, $old); # Preserve the original in case adding the new one causes a problem $old = $self->{signature}; %sigs = map { $_ => 1 } @{$self->{signature}}; for $one_sig (@args) { $tmp = (ref $one_sig) ? join(' ', @$one_sig) : $one_sig; $sigs{$tmp} = 1; } $self->{signature} = [ keys %sigs ]; unless (ref($tmp = $self->make_sig_table)) { # Because this failed, we have to restore the old table and return # an error $self->{signature} = $old; $self->make_sig_table; return ref($self) . '::add_signature: Error re-hashing table: ' . $tmp; } $self; } sub delete_signature { my $self = shift; my @args = @_; my (%sigs, $one_sig, $tmp, $old); # Preserve the original in case adding the new one causes a problem $old = $self->{signature}; %sigs = map { $_ => 1 } @{$self->{signature}}; for $one_sig (@args) { $tmp = (ref $one_sig) ? join(' ', @$one_sig) : $one_sig; delete $sigs{$tmp}; } $self->{signature} = [ keys %sigs ]; unless (ref($tmp = $self->make_sig_table)) { # Because this failed, we have to restore the old table and return # an error $self->{signature} = $old; $self->make_sig_table; return ref($self) . '::delete_signature: Error re-hashing table: ' . $tmp; } $self; } ############################################################################### # # Sub Name: match_signature # # Description: Determine if the passed-in signature string matches any # of this method's known signatures. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # $sig in scalar Signature to check for # # Returns: Success: return type as a string # Failure: 0 # ############################################################################### sub match_signature { my $self = shift; my $sig = shift; $sig = join(' ', @$sig) if ref $sig; return $self->{sig_table}->{$sig} || 0; } ############################################################################### # # Sub Name: reload # # Description: Reload the method's code and ancillary data from the file # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # # Returns: Success: $self # Failure: error message # ############################################################################### sub reload { my $self = shift; return ref($self) . '::reload: No file associated with method ' . $self->{name} unless $self->{file}; my $tmp = $self->load_XPL_file($self->{file}); if (ref $tmp) { # Update the information on this actual object $self->{$_} = $tmp->{$_} for (keys %$tmp); # Re-calculate the signature table, in case that changed as well return $self->make_sig_table; } return $tmp; } ############################################################################### # # Sub Name: load_XPL_file # # Description: Load a XML-encoded method description (generally denoted # by a *.xpl suffix) and return the relevant information. # # Note that this does not fill in $self if $self is a hash # or object reference. This routine is not a substitute for # calling new() (which is why it isn't part of the public # API). # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # $file in scalar File to load # # Returns: Success: hashref of values # Failure: error string # ############################################################################### sub load_XPL_file { my $self = shift; my $file = shift; require XML::Parser; my ($me, $pkg, $data, $signature, $code, $codetext, $accum, $P, %attr); local *F; if (ref($self) eq 'SCALAR') { $me = __PACKAGE__ . '::load_XPL_file'; } else { $me = (ref $self) || $self || __PACKAGE__; $me .= '::load_XPL_file'; } $data = {}; # So these don't end up undef, since they're optional elements $data->{hidden} = 0; $data->{version} = ''; $data->{help} = ''; $data->{called} = 0; open(F, "< $file") or return "$me: Error opening $file for reading: $!"; $P = XML::Parser ->new(Handlers => {Char => sub { $accum .= $_[1] }, Start => sub { %attr = splice(@_, 2) }, End => sub { my $elem = $_[1]; $accum =~ s/^[\s\n]+//; $accum =~ s/[\s\n]+$//; if ($elem eq 'signature') { $data->{signature} ||= []; push(@{$data->{signature}}, $accum); } elsif ($elem eq 'code') { $data->{$elem} = $accum unless ($attr{language} and $attr{language} ne 'perl'); } elsif (substr($elem, -3) eq 'def') { # Don't blindly store the container tag... # We may need it to tell the caller what # our type is $$self = ucfirst substr($elem, 0, -3) if (ref($self) eq 'SCALAR'); } else { $data->{$elem} = $accum; } %attr = (); $accum = ''; }}); return "$me: Error creating XML::Parser object" unless $P; # Trap any errors eval { $P->parse(*F) }; close(F); return "$me: Error parsing $file: $@" if $@; # Try to normalize $codetext before passing it to eval my $class = __PACKAGE__; # token won't expand in the s/// below ($codetext = $data->{code}) =~ s/sub[\s\n]+([\w:]+)?[\s\n]*\{/sub \{ package $class; /; $code = eval $codetext; return "$me: Error creating anonymous sub: $@" if $@; $data->{code} = $code; # Add the file's mtime for when we check for stat-based reloading $data->{mtime} = (stat $file)[9]; $data->{file} = $file; $data; } ############################################################################### # # Sub Name: call # # Description: Encapsulates the invocation of the code block that the # object is abstracting. Manages parameters, signature # checking, etc. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # $srv in ref An object derived from the # RPC::XML::Server class # @dafa in list The params for the call itself # # Globals: None. # # Environment: None. # # Returns: Success: value # Failure: dies with RPC::XML::Fault object as message # ############################################################################### sub call { my ($self, $srv, @data) = @_; my (@paramtypes, @params, $signature, $resptype, $response, $name, $noinc); $name = $self->name; # Create the param list. # The type for the response will be derived from the matching signature @paramtypes = map { $_->type } @data; @params = map { $_->value } @data; $signature = join(' ', @paramtypes); $resptype = $self->match_signature($signature); # Since there must be at least one signature with a return value (even # if the param list is empty), this tells us if the signature matches: return RPC::XML::fault->new(301, "method $name has no matching " . 'signature for the argument list: ' . "[$signature]") unless ($resptype); # Set these in case the server object is part of the param list local $srv->{signature} = [ $resptype, @paramtypes ]; local $srv->{method_name} = $name; # If the method being called is "system.status", check to see if we should # increment the server call-count. $noinc = (($name eq 'system.status') && @data && ($paramtypes[0] eq 'boolean') && $params[0]) ? 1 : 0; # For RPC::XML::Method (and derivatives), pass the server object unshift(@params, $srv) if ($self->isa('RPC::XML::Method')); # Now take a deep breath and call the method with the arguments eval { $response = $self->{code}->(@params); }; # On failure, propagate user-generated RPC::XML::fault exceptions, or # transform Perl-level error/failure into such an object if ($@) { return UNIVERSAL::isa($@, 'RPC::XML::fault') ? $@ : RPC::XML::fault->new(302, "Method $name returned error: $@"); } $self->{called}++ unless $noinc; # Create a suitable return value if ((! ref($response)) && UNIVERSAL::can("RPC::XML::$resptype", 'new')) { my $class = "RPC::XML::$resptype"; $response = $class->new($response); } $response; }
carlgao/lenga
images/lenny64-peon/usr/share/perl5/RPC/XML/Procedure.pm
Perl
mit
34,970
package App::Sqitch::Target; use 5.010; use Moo; use strict; use warnings; use App::Sqitch::Types qw(Maybe URIDB Str Dir Engine Sqitch File Plan Bool); use App::Sqitch::X qw(hurl); use Locale::TextDomain qw(App-Sqitch); use Path::Class qw(dir file); use URI::db; use namespace::autoclean; has name => ( is => 'ro', isa => Str, required => 1, ); sub target { shift->name } has uri => ( is => 'ro', isa => URIDB, required => 1, handles => { engine_key => 'canonical_engine', dsn => 'dbi_dsn', username => 'user', password => 'password', }, ); has sqitch => ( is => 'ro', isa => Sqitch, required => 1, ); has engine => ( is => 'ro', isa => Engine, lazy => 1, default => sub { my $self = shift; require App::Sqitch::Engine; App::Sqitch::Engine->load({ sqitch => $self->sqitch, target => $self, }); }, ); # TODO: core.$engine is deprecated. Remove this workaround and warning # when it is removed. our $WARNED = $ENV{HARNESS_ACTIVE}; sub _engine_var { my ($self, $config, $ekey, $akey) = @_; return unless $ekey; if (my $val = $config->get( key => "engine.$ekey.$akey" )) { return $val; } # Look for the deprecated config section. my $val = $config->get( key => "core.$ekey.$akey" ) or return; return $val if $WARNED; App::Sqitch->warn(__x( "The core.{engine} config has been deprecated in favor of engine.{engine}.\nRun '{sqitch} engine update-config' to update your configurations.", engine => $ekey, sqitch => $0, )); $WARNED = 1; return $val; } sub _fetch { my ($self, $key) = @_; my $sqitch = $self->sqitch; if (my $val = $sqitch->options->{$key}) { return $val; } my $config = $sqitch->config; return $config->get( key => "target." . $self->name . ".$key" ) || $self->_engine_var($config, scalar $self->engine_key, $key) || $config->get( key => "core.$key"); } has registry => ( is => 'ro', isa => Str, lazy => 1, default => sub { my $self = shift; $self->_fetch('registry') || $self->engine->default_registry; }, ); has client => ( is => 'ro', isa => Str, lazy => 1, default => sub { my $self = shift; $self->_fetch('client') || do { my $client = $self->engine->default_client; return $client if $^O ne 'MSWin32'; return $client if $client =~ /[.](?:exe|bat)$/; return $client . '.exe'; }; }, ); has plan_file => ( is => 'ro', isa => File, lazy => 1, default => sub { my $self = shift; if (my $f = $self->_fetch('plan_file') ) { return file $f; } return $self->top_dir->file('sqitch.plan')->cleanup; }, ); has plan => ( is => 'ro', isa => Plan, lazy => 1, default => sub { my $self = shift; App::Sqitch::Plan->new( sqitch => $self->sqitch, target => $self, ); }, ); has top_dir => ( is => 'ro', isa => Dir, lazy => 1, default => sub { dir shift->_fetch('top_dir') || (); }, ); has deploy_dir => ( is => 'ro', isa => Dir, lazy => 1, default => sub { my $self = shift; if ( my $dir = $self->_fetch('deploy_dir') ) { return dir $dir; } $self->top_dir->subdir('deploy')->cleanup; }, ); has revert_dir => ( is => 'ro', isa => Dir, lazy => 1, default => sub { my $self = shift; if ( my $dir = $self->_fetch('revert_dir') ) { return dir $dir; } $self->top_dir->subdir('revert')->cleanup; }, ); has verify_dir => ( is => 'ro', isa => Dir, lazy => 1, default => sub { my $self = shift; if ( my $dir = $self->_fetch('verify_dir') ) { return dir $dir; } $self->top_dir->subdir('verify')->cleanup; }, ); has extension => ( is => 'ro', isa => Str, lazy => 1, default => sub { shift->_fetch('extension') || 'sql'; }, ); sub BUILDARGS { my $class = shift; my $p = @_ == 1 && ref $_[0] ? { %{ +shift } } : { @_ }; # Fetch params. URI can come from passed name. my $sqitch = $p->{sqitch} or return $p; my $name = $p->{name} || ''; my $uri = $p->{uri} ||= do { if ($name =~ /:/) { my $u = URI::db->new($name); if ($u && $u->canonical_engine) { $name = ''; $u; } } }; # If we have a URI up-front, it's all good. if ($uri) { unless ($name) { # Set the URI as the name, sans password. if ($uri->password) { $uri = $uri->clone; $uri->password(undef); } $p->{name} = $uri->as_string; } return $p; } # XXX $merge for deprecated options and config. # Can also move $ekey just to block below when deprecated merge is removed. my ($ekey, $merge); my $config = $sqitch->config; # If no name, try to find one. if (!$name) { # There are a couple of places to look for a name. NAME: { # Look for an engine key. $ekey = $sqitch->options->{engine}; unless ($ekey) { # No --engine, look for core target. if ( $uri = $config->get( key => 'core.target' ) ) { # We got core.target. $p->{name} = $name = $uri; last NAME; } # No core target, look for an engine key. $ekey = $config->get( key => 'core.engine' ) or hurl target => __( 'No engine specified; use --engine or set core.engine' ); } # Find the name in the engine config, or fall back on a simple URI. $uri = $class->_engine_var($config, $ekey, 'target') || "db:$ekey:"; $p->{name} = $name = $uri; } } # Now we should have a name. What is it? if ($name =~ /:/) { # The name is a URI from core.target or core.engine.target. $uri = $name; $name = $p->{name} = undef; $merge = 2; # Merge all deprecated stuff. } else { # Well then, there had better be a config with a URI. $uri = $config->get( key => "target.$name.uri" ) or do { # Die on no section or no URI. hurl target => __x( 'Cannot find target "{target}"', target => $name ) unless %{ $config->get_section( section => "target.$name" ) }; hurl target => __x( 'No URI associated with target "{target}"', target => $name, ); }; $merge = 1; # Merge only options. } # Instantiate the URI. $uri = $p->{uri} = URI::db->new( $uri ); $ekey ||= $uri->canonical_engine or hurl target => __x( 'No engine specified by URI {uri}; URI must start with "db:$engine:"', uri => $uri->as_string, ); if ($merge) { # Override parts with deprecated command-line options and config. my $opts = $sqitch->options; my $econfig = $merge > 1 ? $sqitch->config->get_section(section => "core.$ekey") || {} : {}; if (%{ $econfig } && !%{ $sqitch->config->get_section(section => "engine.$ekey") || {} }) { App::Sqitch->warn(__x( "The core.{engine} config has been deprecated in favor of engine.{engine}.\nRun '{sqitch} engine update-config' to update your configurations.", engine => $ekey, sqitch => $0, )) unless $WARNED; $WARNED = 1; } my @deprecated; if (my $host = $opts->{db_host}) { push @deprecated => '--db-host'; $uri->host($host); } elsif ($host = $econfig->{host}) { $uri->host($host) if $merge > 1; } if (my $port = $opts->{db_port}) { push @deprecated => '--db-port'; $uri->port($port); } elsif ($port = $econfig->{port}) { $uri->port($port) if $merge > 1; } if (my $user = $opts->{db_username}) { push @deprecated => '--db-username'; $uri->user($user); } elsif ($user = $econfig->{username}) { $uri->user($user) if $merge > 1; } if (my $pass = $econfig->{password}) { $uri->password($pass) if $merge > 1; } if (my $db = $opts->{db_name}) { push @deprecated => '--db-name'; $uri->dbname($db); } elsif ($db = $econfig->{db_name}) { $uri->dbname($db) if $merge > 1; } if (@deprecated) { $sqitch->warn(__nx( 'Option {options} deprecated and will be removed in 1.0; use URI {uri} instead', 'Options {options} deprecated and will be removed in 1.0; use URI {uri} instead', scalar @deprecated, options => join(', ', @deprecated), uri => $uri->as_string, )); } } unless ($name) { # Set the name. if ($uri->password) { # Remove the password from the name. my $tmp = $uri->clone; $tmp->password(undef); $p->{name} = $tmp->as_string; } else { $p->{name} = $uri->as_string; } } return $p; } 1; __END__ =head1 Name App::Sqitch::Target - Sqitch deployment target =head1 Synopsis my $plan = App::Sqitch::Target->new( sqitch => $sqitch, name => 'development', ); $target->engine->deploy; =head1 Description App::Sqitch::Target provides collects, in one place, the L<engine|App::Sqitch::Engine>, L<plan|App::Sqitch::Engine>, and file locations required to carry out Sqitch commands. All commands should instantiate a target to work with the plan or database. =head1 Interface =head3 C<new> my $target = App::Sqitch::Target->new( sqitch => $sqitch ); Instantiates and returns an App::Sqitch::Target object. The most important parameters are C<sqitch>, C<name> and C<uri>. The constructor tries really hard to figure out the proper name and URI during construction. If the C<uri> parameter is passed, this is straight-forward: if no C<name> is passed, C<name> will be set to the stringified format of the URI (minus the password, if present). Otherwise, when no URI is passed, the name and URI are determined by taking the following steps: =over =item * If there is no name, get the engine key from from C<--engine> or the C<core.engine> configuration option. If no key can be determined, an exception will be thrown. =item * Use the key to look up the target name in the C<engine.$engine.target> configuration option. If none is found, use C<db:$key:>. =item * If the name contains a colon (C<:>), assume it is also the value for the URI. =item * Otherwise, it should be the name of a configured target, so look for a URI in the C<target.$name.uri> configuration option. =back As a general rule, then, pass either a target name or URI string in the C<name> parameter, and Sqitch will do its best to find all the relevant target information. And if there is no name or URI, it will try to construct a reasonable default from the command-line options or engine configuration. =head2 Accessors =head3 C<sqitch> my $sqitch = $target->sqitch; Returns the L<App::Sqitch> object that instantiated the target. =head3 C<name> =head3 C<target> my $name = $target->name; $name = $target->target; The name of the target. If there was no name specified, the URI will be used (minus the password, if there is one). =head3 C<uri> my $uri = $target->uri; The L<URI::db> object encapsulating the database connection information. =head3 C<engine> my $engine = $target->engine; A L<App::Sqitch::Engine> object to use for database interactions with the target. =head3 C<registry> my $registry = $target->registry; The name of the registry used by the database. The value comes from one of these options, searched in this order: =over =item * C<--registry> =item * C<target.$name.registry> =item * C<engine.$engine.registry> =item * C<core.registry> =item * Engine-specific default =back =head3 C<client> my $client = $target->client; Path to the engine command-line client. The value comes from one of these options, searched in this order: =over =item * C<--client> =item * C<target.$name.client> =item * C<engine.$engine.client> =item * C<core.client> =item * Engine-and-OS-specific default =back =head3 C<top_dir> my $top_dir = $target->top_dir; The path to the top directory of the project. This directory generally contains the plan file and subdirectories for deploy, revert, and verify scripts. The value comes from one of these options, searched in this order: =over =item * C<--top-dir> =item * C<target.$name.top_dir> =item * C<engine.$engine.top_dir> =item * C<core.top_dir> =item * F<.> =back =head3 C<plan_file> my $plan_file = $target->plan_file; The path to the plan file. The value comes from one of these options, searched in this order: =over =item * C<--plan-file> =item * C<target.$name.plan_file> =item * C<engine.$engine.plan_file> =item * C<core.plan_file> =item * F<C<$top_dir>/sqitch.plan> =back =head3 C<deploy_dir> my $deploy_dir = $target->deploy_dir; The path to the deploy directory of the project. This directory contains all of the deploy scripts referenced by changes in the C<plan_file>. The value comes from one of these options, searched in this order: =over =item * C<--deploy-dir> =item * C<target.$name.deploy_dir> =item * C<engine.$engine.deploy_dir> =item * C<core.deploy_dir> =item * F<C<$top_dir/deploy>> =back =head3 C<revert_dir> my $revert_dir = $target->revert_dir; The path to the revert directory of the project. This directory contains all of the revert scripts referenced by changes the C<plan_file>. The value comes from one of these options, searched in this order: =over =item * C<--revert-dir> =item * C<target.$name.revert_dir> =item * C<engine.$engine.revert_dir> =item * C<core.revert_dir> =item * F<C<$top_dir/revert>> =back =head3 C<verify_dir> my $verify_dir = $target->verify_dir; The path to the verify directory of the project. This directory contains all of the verify scripts referenced by changes in the C<plan_file>. The value comes from one of these options, searched in this order: =over =item * C<--verify-dir> =item * C<target.$name.verify_dir> =item * C<engine.$engine.verify_dir> =item * C<core.verify_dir> =item * F<C<$top_dir/verify>> =back =head3 C<extension> my $extension = $target->extension; The file name extension to append to change names to create script file names. The value comes from one of these options, searched in this order: =over =item * C<--extension> =item * C<target.$name.extension> =item * C<engine.$engine.extension> =item * C<core.extension> =item * C<"sql"> =back =head3 C<engine_key> my $key = $target->engine_key; The key defining which engine to use. This value defines the class loaded by C<engine>. Convenience method for C<< $target->uri->canonical_engine >>. =head3 C<dsn> my $dsn = $target->dsn; The DSN to use when connecting to the target via the DBI. Convenience method for C<< $target->uri->dbi_dsn >>. =head3 C<username> my $username = $target->username; The username to use when connecting to the target via the DBI. Convenience method for C<< $target->uri->user >>. =head3 C<password> my $password = $target->password; The password to use when connecting to the target via the DBI. Convenience method for C<< $target->uri->password >>. =head1 See Also =over =item L<sqitch> The Sqitch command-line client. =back =head1 Author David E. Wheeler <david@justatheory.com> =head1 License Copyright (c) 2012-2014 iovation Inc. 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. =cut
gitpan/App-Sqitch
lib/App/Sqitch/Target.pm
Perl
mit
17,473
:- expects_dialect(lps). maxTime(5). fluents emergencia. actions presione_el_botón. events alerte_al_conductor. observe emergencia from 1 to 2. if emergencia at T1 then alerte_al_conductor from T1 to T2. alerte_al_conductor from T1 to T2 if presione_el_botón from T1 to T2. /** <examples> ?- go(Timeline). */
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_ec/test/lps_user_examples/emergencia.pl
Perl
mit
327
=pod =head1 NAME PKCS5_PBKDF2_HMAC, PKCS5_PBKDF2_HMAC_SHA1 - password based derivation routines with salt and iteration count =head1 SYNOPSIS #include <openssl/evp.h> int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, const EVP_MD *digest, int keylen, unsigned char *out); int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, int keylen, unsigned char *out); =head1 DESCRIPTION PKCS5_PBKDF2_HMAC() derives a key from a password using a salt and iteration count as specified in RFC 2898. B<pass> is the password used in the derivation of length B<passlen>. B<pass> is an optional parameter and can be NULL. If B<passlen> is -1, then the function will calculate the length of B<pass> using strlen(). B<salt> is the salt used in the derivation of length B<saltlen>. If the B<salt> is NULL, then B<saltlen> must be 0. The function will not attempt to calculate the length of the B<salt> because it is not assumed to be NULL terminated. B<iter> is the iteration count and its value should be greater than or equal to 1. RFC 2898 suggests an iteration count of at least 1000. Any B<iter> less than 1 is treated as a single iteration. B<digest> is the message digest function used in the derivation. Values include any of the EVP_* message digests. PKCS5_PBKDF2_HMAC_SHA1() calls PKCS5_PBKDF2_HMAC() with EVP_sha1(). The derived key will be written to B<out>. The size of the B<out> buffer is specified via B<keylen>. =head1 NOTES A typical application of this function is to derive keying material for an encryption algorithm from a password in the B<pass>, a salt in B<salt>, and an iteration count. Increasing the B<iter> parameter slows down the algorithm which makes it harder for an attacker to perform a brute force attack using a large number of candidate passwords. =head1 RETURN VALUES PKCS5_PBKDF2_HMAC() and PBKCS5_PBKDF2_HMAC_SHA1() return 1 on success or 0 on error. =head1 SEE ALSO L<evp(3)>, L<rand(3)>, L<EVP_BytesToKey(3)> =head1 HISTORY =cut
vbloodv/blood
extern/openssl.orig/doc/crypto/PKCS5_PBKDF2_HMAC.pod
Perl
mit
2,167
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] 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 XrefParser::VBExternalDescriptionParser; use strict; use warnings; use Carp; use POSIX qw(strftime); use File::Basename; use base qw( XrefParser::BaseParser ); # Parse the external description file # # stable_id description # AAEL003237 low molecular weight protein-tyrosine-phosphatase # AAEL014602 conserved hypothetical protein # AAEL010223 phosphatidylserine decarboxylase # ... sub run { my ($self, $ref_arg) = @_; my $source_id = $ref_arg->{source_id}; my $species_id = $ref_arg->{species_id}; my $files = $ref_arg->{files}; my $verbose = $ref_arg->{verbose}; if((!defined $source_id) or (!defined $species_id) or (!defined $files) ){ croak "Need to pass source_id, species_id and files as pairs"; } $verbose |=0; my $file = @{$files}[0]; print "source_id = $source_id, species= $species_id, file = $file\n" if($verbose); my $added = 0; my $count = 0; my $file_io = $self->get_filehandle($file); if ( !defined $file_io ) { print STDERR "ERROR: Could not open file $file\n"; return 1; } while ( my $line = $file_io->getline() ) { chomp $line; my ($gene_id, $description) = split("\t",$line); #and use the gene_id as accession my $xref_id = $self->get_xref($gene_id,$source_id, $species_id); if(!defined($xref_id)){ $xref_id = $self->add_xref({ acc => $gene_id, label => $gene_id, desc => $description, source_id => $source_id, species_id => $species_id, info_type => "DIRECT"} ); $count++; } if(defined($gene_id) and $gene_id ne "-"){ $self->add_direct_xref($xref_id, $gene_id, "Gene", "") ; $added++; } } $file_io->close(); print "Added $count xrefs and $added Direct xrefs to genes for VBExternalDescription\n" if($verbose); return 0; } 1;
muffato/ensembl
misc-scripts/xref_mapping/XrefParser/VBExternalDescriptionParser.pm
Perl
apache-2.0
2,582
# # 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 hardware::server::hp::ilo::xmlapi::custom::api; use strict; use warnings; use IO::Socket::SSL; use XML::Simple; use centreon::plugins::http; sub new { my ($class, %options) = @_; my $self = {}; bless $self, $class; if (!defined($options{output})) { print "Class Custom: Need to specify 'output' argument.\n"; exit 3; } if (!defined($options{options})) { $options{output}->add_option_msg(short_msg => "Class Custom: Need to specify 'options' argument."); $options{output}->option_exit(); } if (!defined($options{noptions})) { $options{options}->add_options(arguments => { 'hostname:s' => { name => 'hostname' }, 'timeout:s' => { name => 'timeout', default => 30 }, 'port:s' => { name => 'port', default => 443 }, 'username:s' => { name => 'username' }, 'password:s' => { name => 'password' }, 'force-ilo3' => { name => 'force_ilo3' } }); } $options{options}->add_help(package => __PACKAGE__, sections => 'XML API OPTIONS', once => 1); $self->{output} = $options{output}; $self->{http} = centreon::plugins::http->new(%options); return $self; } sub set_options { my ($self, %options) = @_; $self->{option_results} = $options{option_results}; } sub set_defaults {} sub check_options { my ($self, %options) = @_; if (!defined($self->{option_results}->{hostname}) || $self->{option_results}->{hostname} eq '') { $self->{output}->add_option_msg(short_msg => "Need to set hostname option."); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{username}) || $self->{option_results}->{username} eq '') { $self->{output}->add_option_msg(short_msg => "Need to set username option."); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{password})) { $self->{output}->add_option_msg(short_msg => "Need to set password option."); $self->{output}->option_exit(); } $self->{ssl_opts} = ''; if (!defined($self->{option_results}->{ssl_opt})) { $self->{option_results}->{ssl_opt} = ['SSL_verify_mode => SSL_VERIFY_NONE']; $self->{ssl_opts} = 'SSL_verify_mode => SSL_VERIFY_NONE'; } else { foreach (@{$self->{option_results}->{ssl_opt}}) { $self->{ssl_opts} .= "$_, "; } } if (!defined($self->{option_results}->{curl_opt})) { $self->{option_results}->{curl_opt} = ['CURLOPT_SSL_VERIFYPEER => 0', 'CURLOPT_SSL_VERIFYHOST => 0']; } $self->{http}->set_options(%{$self->{option_results}}); return 0; } sub find_ilo_version { my ($self, %options) = @_; ($self->{ilo2}, $self->{ilo3}) = (0, 0); my $client = new IO::Socket::SSL->new(PeerAddr => $self->{option_results}->{hostname} . ':' . $self->{option_results}->{port}, eval $self->{ssl_opts}, Timeout => $self->{option_results}->{timeout}); if (!$client) { $self->{output}->add_option_msg(short_msg => "Failed to establish SSL connection: $!, ssl_error=$SSL_ERROR"); $self->{output}->option_exit(); } print $client 'POST /ribcl HTTP/1.1' . "\r\n"; print $client "HOST: me" . "\r\n"; # Mandatory for http 1.1 print $client "User-Agent: locfg-Perl-script/3.0\r\n"; print $client "Content-length: 30" . "\r\n"; # Mandatory for http 1.1 print $client 'Connection: Close' . "\r\n"; # Required print $client "\r\n"; # End of http header print $client "<RIBCL VERSION=\"2.0\"></RIBCL>\r\n"; # Used by Content-length my $ln = <$client>; if ($ln =~ m/HTTP.1.1 200 OK/) { $self->{ilo3} = 1; } else { $self->{ilo2} = 1; } close $client; } sub get_ilo2_data { my ($self, %options) = @_; my $client = new IO::Socket::SSL->new(PeerAddr => $self->{option_results}->{hostname} . ':' . $self->{option_results}->{port}, eval $self->{ssl_opts}, Timeout => $self->{option_results}->{timeout}); if (!$client) { $self->{output}->add_option_msg(short_msg => "Failed to establish SSL connection: $!, ssl_error=$SSL_ERROR"); $self->{output}->option_exit(); } print $client '<?xml version="1.0"?>' . "\r\n"; print $client '<RIBCL VERSION="2.21">' . "\r\n"; print $client '<LOGIN USER_LOGIN="' . $self->{option_results}->{username} . '" PASSWORD="' . $self->{option_results}->{password} . '">' . "\r\n"; print $client '<SERVER_INFO MODE="read">' . "\r\n"; print $client '<GET_EMBEDDED_HEALTH />' . "\r\n"; print $client '</SERVER_INFO>' . "\r\n"; print $client '</LOGIN>' . "\r\n"; print $client '</RIBCL>' . "\r\n"; while (my $line = <$client>) { $self->{content} .= $line; } close $client; } sub get_ilo3_data { my ($self, %options) = @_; my $xml_script = "<RIBCL VERSION=\"2.21\"> <LOGIN USER_LOGIN=\"$self->{option_results}->{username}\" PASSWORD=\"$self->{option_results}->{password}\"> <SERVER_INFO MODE=\"read\"> <GET_EMBEDDED_HEALTH /> </SERVER_INFO> </LOGIN> </RIBCL> "; $self->{http}->add_header(key => 'TE', value => 'chunked'); $self->{http}->add_header(key => 'Connection', value => 'Close'); $self->{http}->add_header(key => 'Content-Type', value => 'text/xml'); $self->{content} = $self->{http}->request( method => 'POST', proto => 'https', url_path => '/ribcl', query_form_post => $xml_script, ); } sub check_ilo_error { my ($self, %options) = @_; # Looking for: # <RESPONSE # STATUS="0x005F" # MESSAGE='Login credentials rejected.' # /> while ($self->{content} =~ /<response[^>]*?status="0x(.*?)"[^>]*?message='(.*?)'/msig) { my ($status_code, $message) = ($1, $2); if ($status_code !~ /^0+$/) { $self->{output}->add_option_msg(short_msg => "Cannot get data: $2"); $self->{output}->option_exit(); } } } sub change_shitty_xml { my ($self, %options) = @_; # Can be like that the root <RIBCL VERSION="2.22" /> ???!! $options{response} =~ s/<RIBCL VERSION="(.*?)"\s*\/>/<RIBCL VERSION="$1">/mg; # ILO2 can send: # <DRIVES> # <Backplane firmware version="Unknown", enclosure addr="224"/> # <Drive Bay: "1"; status: "Ok"; uid led: "Off"> # <Drive Bay: "2"; status: "Ok"; uid led: "Off"> # <Drive Bay: "3"; status: "Not Installed"; uid led: "Off"> # <Drive Bay: "4"; status: "Not Installed"; uid led: "Off"> # <Backplane firmware version="1.16own", enclosure addr="226"/> # <Drive Bay: "5"; status: "Not Installed"; uid led: "Off"> # <Drive Bay: "6"; status: "Not Installed"; uid led: "Off"> # <Drive Bay: "7"; status: "Not Installed"; uid led: "Off"> # <Drive Bay: "8"; status: "Not Installed"; uid led: "Off"> # </DRIVES> $options{response} =~ s/<Backplane firmware version="(.*?)", enclosure addr="(.*?)"/<BACKPLANE FIRMWARE_VERSION="$1" ENCLOSURE_ADDR="$2"/mg; $options{response} =~ s/<Drive Bay: "(.*?)"; status: "(.*?)"; uid led: "(.*?)">/<DRIVE_BAY NUM="$1" STATUS="$2" UID_LED="$3" \/>/mg; #Other shitty xml: # <BACKPLANE> #  <ENCLOSURE_ADDR VALUE="224"/> # <DRIVE_BAY VALUE = "1"/> #  <PRODUCT_ID VALUE = "EG0300FCVBF"/> #  <STATUS VALUE = "Ok"/> #  <UID_LED VALUE = "Off"/> # <DRIVE_BAY VALUE = "2"/> #  <PRODUCT_ID VALUE = "EH0146FARUB"/> #  <STATUS VALUE = "Ok"/> #  <UID_LED VALUE = "Off"/> # <DRIVE_BAY VALUE = "3"/> #  <PRODUCT_ID VALUE = "EH0146FBQDC"/> #  <STATUS VALUE = "Ok"/> #  <UID_LED VALUE = "Off"/> # <DRIVE_BAY VALUE = "4"/> #  <PRODUCT_ID VALUE = "N/A"/> #  <STATUS VALUE = "Not Installed"/> #  <UID_LED VALUE = "Off"/> # </BACKPLANE> $options{response} =~ s/<DRIVE_BAY\s+VALUE\s*=\s*"(.*?)".*?<STATUS\s+VALUE\s*=\s*"(.*?)".*?<UID_LED\s+VALUE\s*=\s*"(.*?)".*?\/>/<DRIVE_BAY NUM="$1" STATUS="$2" UID_LED="$3" \/>/msg; # 3rd variant, known as the ArnoMLT variant # <BACKPLANE> # <FIRMWARE VERSION="1.16"/> # <ENCLOSURE ADDR="224"/> # <DRIVE BAY="1"/> # <PRODUCT ID="EG0300FCVBF"/> # <DRIVE_STATUS VALUE="Ok"/> # <UID LED="Off"/> # <DRIVE BAY="2"/> # <PRODUCT ID="EH0146FARUB"/> # <DRIVE_STATUS VALUE="Ok"/> # <UID LED="Off"/> # <DRIVE BAY="3"/> # <PRODUCT ID="EH0146FBQDC"/> # <DRIVE_STATUS VALUE="Ok"/> # <UID LED="Off"/> # <DRIVE BAY="4"/> # <PRODUCT ID="N/A"/> # <DRIVE_STATUS VALUE="Not Installed"/> # <UID LED="Off"/> # </BACKPLANE> $options{response} =~ s/<FIRMWARE\s+VERSION\s*=\s*"(.*?)".*?<ENCLOSURE\s+ADDR\s*=\s*"(.*?)".*?\/>/<BACKPLANE FIRMWARE_VERSION="$1" ENCLOSURE_ADDR="$2"/mg; $options{response} =~ s/<DRIVE\s+BAY\s*=\s*"(.*?)".*?<DRIVE_STATUS\s+VALUE\s*=\s*"(.*?)".*?<UID\s+LED\s*=\s*"(.*?)".*?\/>/<DRIVE_BAY NUM="$1" STATUS="$2" UID_LED="$3" \/>/msg; return $options{response}; } sub get_ilo_response { my ($self, %options) = @_; # ilo result is so shitty. We get the good result from size... my ($length, $response) = (0, ''); foreach (split /<\?xml.*?\?>/, $self->{content}) { if (length($_) > $length) { $response = $_; $length = length($_); } } $response = $self->change_shitty_xml(response => $response); my $xml_result; eval { $xml_result = XMLin($response, ForceArray => ['FAN', 'TEMP', 'MODULE', 'SUPPLY', 'PROCESSOR', 'NIC', 'SMART_STORAGE_BATTERY', 'CONTROLLER', 'DRIVE_ENCLOSURE', 'LOGICAL_DRIVE', 'PHYSICAL_DRIVE', 'DRIVE_BAY', 'BACKPLANE']); }; if ($@) { $self->{output}->add_option_msg(short_msg => "Cannot decode xml response: $@"); $self->{output}->option_exit(); } return $xml_result; } sub get_ilo_data { my ($self, %options) = @_; $self->{content} = ''; if (!defined($self->{option_results}->{force_ilo3})) { $self->find_ilo_version(); } else { $self->{ilo3} = 1; } if ($self->{ilo3} == 1) { $self->get_ilo3_data(); } else { $self->get_ilo2_data(); } $self->{content} =~ s/\r//sg; $self->{output}->output_add(long_msg => $self->{content}, debug => 1); $self->check_ilo_error(); return $self->get_ilo_response(); } 1; __END__ =head1 NAME ILO API =head1 SYNOPSIS ilo api =head1 XML API OPTIONS =over 8 =item B<--hostname> Hostname to query. =item B<--username> ILO username. =item B<--password> ILO password. =item B<--port> ILO Port (Default: 443). =item B<--timeout> Set timeout (Default: 30). =item B<--force-ilo3> Don't try to find ILO version. =back =head1 DESCRIPTION B<custom>. =cut
Tpo76/centreon-plugins
hardware/server/hp/ilo/xmlapi/custom/api.pm
Perl
apache-2.0
11,958
package XrefParser::IlluminaWGParser; use strict; use base qw( XrefParser::BaseParser ); sub run { my $self = shift if (defined(caller(1))); my $source_id = shift; my $species_id = shift; my $files = shift; my $release_file = shift; my $verbose = shift; my $file = @{$files}[0]; my @xrefs; my $file_io = $self->get_filehandle($file); if ( !defined $file_io ) { print STDERR "Could not open $file\n"; return 1; } my $read = 0; my $name_index; my $seq_index; my $defin_index; while ( $_ = $file_io->getline() ) { chomp; my $xref; # strip ^M at end of line $_ =~ s/\015//g; if(/^\[/){ # print $_."\n"; if(/^\[Probes/){ my $header = $file_io->getline(); # print $header."\n"; $read =1; my @bits = split("\t", $header); my $index =0; foreach my $head (@bits){ if($head eq "Search_Key"){ $name_index = $index; } elsif($head eq "Probe_Sequence"){ $seq_index = $index; } elsif($head eq "Definition"){ $defin_index = $index; } $index++; } if(!defined($name_index) or !defined($seq_index) or !defined($defin_index)){ die "Could not find index for search_key->$name_index, seq->$seq_index, definition->$defin_index"; } next; } else{ $read = 0; } } if($read){ # print $_."\n"; my @bits = split("\t", $_); my $sequence = $bits[$seq_index]; my $description = $bits[$defin_index]; my $illumina_id = $bits[$name_index]; # build the xref object and store it $xref->{ACCESSION} = $illumina_id; $xref->{LABEL} = $illumina_id; $xref->{SEQUENCE} = $sequence; $xref->{SOURCE_ID} = $source_id; $xref->{SPECIES_ID} = $species_id; $xref->{DESCRIPTION} = $description; $xref->{SEQUENCE_TYPE} = 'dna'; $xref->{STATUS} = 'experimental'; push @xrefs, $xref; } } $file_io->close(); XrefParser::BaseParser->upload_xref_object_graphs(\@xrefs); print scalar(@xrefs) . " Illumina V2 xrefs succesfully parsed\n" if($verbose); return 0; } 1;
adamsardar/perl-libs-custom
EnsemblAPI/ensembl/misc-scripts/xref_mapping/XrefParser/IlluminaWGParser.pm
Perl
apache-2.0
2,141
package Paws::KMS::Tag; use Moose; has TagKey => (is => 'ro', isa => 'Str', required => 1); has TagValue => (is => 'ro', isa => 'Str', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::KMS::Tag =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::KMS::Tag object: $service_obj->Method(Att1 => { TagKey => $value, ..., TagValue => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::KMS::Tag object: $result = $service_obj->Method(...); $result->Att1->TagKey =head1 DESCRIPTION A key-value pair. A tag consists of a tag key and a tag value. Tag keys and tag values are both required, but tag values can be empty (null) strings. =head1 ATTRIBUTES =head2 B<REQUIRED> TagKey => Str The key of the tag. =head2 B<REQUIRED> TagValue => Str The value of the tag. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::KMS> =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/KMS/Tag.pm
Perl
apache-2.0
1,448
# 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::MutateAdResult; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { ad => $args->{ad}, resourceName => $args->{resourceName}}; # 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/AdService/MutateAdResult.pm
Perl
apache-2.0
1,077
multi_test "Getting push rules doesn't corrupt the cache SYN-390", requires => [ local_user_fixture() ], do => sub { my ( $user ) = @_; do_request_json_for( $user, method => "PUT", uri => "/v3/pushrules/global/sender/%40a_user%3Amatrix.org", content => { "actions" => ["dont_notify"] } )->SyTest::pass_on_done("Set push rules for user" ) ->then( sub { do_request_json_for( $user, method => "GET", uri => "/v3/pushrules/", )->SyTest::pass_on_done("Got push rules the first time" ) })->then( sub { do_request_json_for( $user, method => "GET", uri => "/v3/pushrules/", )->SyTest::pass_on_done("Got push rules the second time" ) })->then_done(1); }
matrix-org/sytest
tests/90jira/SYN-390.pl
Perl
apache-2.0
816
=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 Bio::EnsEMBL::Production::Pipeline::FtpChecker::CheckVariationFtp; use strict; use warnings; use base qw/Bio::EnsEMBL::Production::Pipeline::FtpChecker::CheckFtp/; use Bio::EnsEMBL::Utils::Exception qw(throw); use Bio::EnsEMBL::DBSQL::DBAdaptor; use Data::Dumper; use Log::Log4perl qw/:easy/; my $expected_files = { "vcf" => {"dir" => "{division}/vcf/{species_dir}/", "excepted" =>[ '{species}*.vcf.gz', '{species}_incl_consequences*.vcf.gz', '{species}*.vcf.gz.tbi', '{species}_incl_consequences*.vcf.gz.tbi', 'README*', 'CHECKSUMS*' ]}, "gvf" => {"dir" => "{division}/gvf/{species_dir}/", "excepted" =>[ '{species}*.gvf.gz', '{species}_failed*.gvf.gz', '{species}_incl_consequences*.gvf.gz', 'README*', 'CHECKSUMS*' ]} }; sub run { my ($self) = @_; my $species = $self->param('species'); if ( $species !~ /Ancestral sequences/ ) { Log::Log4perl->easy_init($DEBUG); $self->{logger} = get_logger(); my $base_path = $self->param('base_path'); $self->{logger}->info("Checking $species on $base_path"); my $vals = {}; $vals->{species} = $species; $vals->{species_uc} = ucfirst $species; my $dba = $self->core_dba(); if($dba->dbc()->dbname() =~ m/^(.*_collection)_core_.*/) { $vals->{species_dir} = $1.'/'.$species; $vals->{collection_dir} = $1.'/'; } else { $vals->{species_dir} = $species; $vals->{collection_dir} = ''; } my $division = $dba->get_MetaContainer()->get_division(); $dba->dbc()->disconnect_if_idle(); if(defined $division) { $division = lc ($division); $division =~ s/ensembl//i; } if ($division eq "vertebrates"){ $division = ""; } $vals->{division} = $division; $self->check_files($species, 'variation', $base_path, $expected_files, $vals); } return; } 1;
Ensembl/ensembl-production
modules/Bio/EnsEMBL/Production/Pipeline/FtpChecker/CheckVariationFtp.pm
Perl
apache-2.0
2,654
=head1 NAME LedgerSMB::Template::CSV - Template support module for LedgerSMB =head1 METHODS =over =item get_template ($name) Returns the appropriate template filename for this format. =item preprocess ($vars) Returns $vars. =item process ($parent, $cleanvars) Processes the template for text. =item escape ($var) Escapes the variable for CSV inclusion =item postprocess ($parent) Returns the output filename. =back =head1 Copyright (C) 2007, The LedgerSMB core team. This work contains copyrighted information from a number of sources all used with permission. It is released under the GNU General Public License Version 2 or, at your option, any later version. See COPYRIGHT file for details. For a full list including contact information of contributors, maintainers, and copyright holders, see the CONTRIBUTORS file. =cut package LedgerSMB::Template::CSV; use warnings; use strict; use Template; use LedgerSMB::Template::TTI18N; use LedgerSMB::Template::DB; my $binmode = ':utf8'; binmode STDOUT, $binmode; binmode STDERR, $binmode; sub get_template { my $name = shift; return "${name}.csv"; } sub preprocess { my $rawvars = shift; my $vars; { # pre-5.14 compatibility block local ($@); # pre-5.14, do not die() in this block if (eval {$rawvars->can('to_output')}){ $rawvars = $rawvars->to_output; } } my $type = ref $rawvars; #XXX fix escaping function return $rawvars if $type =~ /^LedgerSMB::Locale/; return unless defined $rawvars; if ( $type eq 'ARRAY' ) { for (@{$rawvars}) { push @{$vars}, preprocess( $_ ); } } elsif ( !$type or $type eq 'SCALAR' or $type eq 'Math::BigInt::GMP') { # Scalars or GMP objects (which are SCALAR refs) --CT if ($type eq 'SCALAR' or $type eq 'Math::BigInt::GMP') { $vars = $$rawvars; return unless defined $vars; } else { $vars = $rawvars; } $vars =~ s/(^ +| +$)//g; } elsif ( $type eq 'CODE' ) { # a code reference makes no sense return undef; } else { # hashes and objects for ( keys %{$rawvars} ) { $vars->{$_} = preprocess( $rawvars->{$_} ); } } return $vars; } sub process { my $parent = shift; my $cleanvars = shift; my $template; my $source; my $output; $parent->{binmode} = $binmode; if ($parent->{outputfile}) { if (ref $parent->{outputfile}){ $output = $parent->{outputfile}; } else { $output = "$parent->{outputfile}.csv"; } } else { $output = \$parent->{output}; } if ($parent->{include_path} eq 'DB'){ $source = LedgerSMB::Template::DB->get_template( $parent->{template}, undef, 'csv' ); } elsif (ref $parent->{template} eq 'SCALAR') { $source = $parent->{template}; } elsif (ref $parent->{template} eq 'ARRAY') { $source = join "\n", @{$parent->{template}}; } else { $source = get_template($parent->{template}); } $template = Template->new({ INCLUDE_PATH => [$parent->{include_path_lang}, $parent->{include_path}, 'UI/lib'], START_TAG => quotemeta('<?lsmb'), END_TAG => quotemeta('?>'), DELIMITER => ';', DEBUG => ($parent->{debug})? 'dirs': undef, DEBUG_FORMAT => '', }) || die Template->error(); if (not $template->process( $source, {%$cleanvars, %$LedgerSMB::Template::TTI18N::ttfuncs, 'escape' => \&preprocess}, $output, binmode => ':utf8')) { die $template->error(); } $parent->{mimetype} = 'text/csv'; } sub postprocess { my $parent = shift; $parent->{rendered} = "$parent->{outputfile}.csv" if $parent->{outputfile}; if (!$parent->{rendered}){ return "$parent->{template}.csv"; } return $parent->{rendered}; } sub escape { } 1;
tridentcodesolution/tridentcodesolution.github.io
projects/CRM/LedgerSMB-master/LedgerSMB/Template/CSV.pm
Perl
apache-2.0
4,026
# 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::CampaignFeedService::GetCampaignFeedRequest; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = {resourceName => $args->{resourceName}}; # 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/CampaignFeedService/GetCampaignFeedRequest.pm
Perl
apache-2.0
1,057
:- module(persdbtr, [persistent_tr/2,persistent_term_tr/3], []). persistent_tr((:- persistent(F/A,D)), [(:- data(F/A)), '$is_persistent'(F/A,'$persistent_module':D)]). persistent_tr(persistent_dir(D,Dir), [persistent_dir('$persistent_module':D,Dir,default,default)]). persistent_tr((persistent_dir(D,Dir) :- Body), [(persistent_dir('$persistent_module':D,Dir,default,default) :- Body)]). persistent_tr(persistent_dir(D,Dir,DirPerms,FilePerms), [persistent_dir('$persistent_module':D,Dir,DirPerms,FilePerms)]). persistent_tr((persistent_dir(D,Dir,DirPerms,FilePerms) :- Body), [(persistent_dir('$persistent_module':D,Dir,DirPerms,FilePerms) :- Body)]). % kludge to get the name of the module being compiled for persistent_tr/2. % This predicate replaces '$persistent_module' set by persistent_tr/2. persistent_term_tr('$persistent_module', Module, Module).
leuschel/ecce
www/CiaoDE/ciao/library/persdb/persdbtr.pl
Perl
apache-2.0
869
#!/bin/env perl use strict; my $inp = 'AAA * BBB CCC * * "2000 01 00 00 00" "2004 01 00 00 00"' ; my @r; while ($inp =~ /( [^"\s]+ | "[^"]+?" ) /gx) { my $a = $1; $a =~ s/(?:^"|"$)//g; push @r, $a; } print join "\n", @r, ''; # Trick / Challange # # * Use Text::CSV_XS # http://search.cpan.org/~hmbrand/Text-CSV_XS-1.24/CSV_XS.pm ## Inline # find emails: # perl -ple 's/^.*\b(\w+@\w*.\w+)\b.*$/$1/' source.txt > target_emails_only.txt # from emails to handlers/logins # perl -ple 's/^.*\b(\w+)@\w*.\w+\b.*$/$1/' target_emails_only.txt > target_logins_only.txt
vinnix/PerlLab
Extras/regex.pl
Perl
bsd-2-clause
675
#!/usr/bin/perl -w # MGEL # Surya Saha 12/24/08 # reading cmd line input merged f_itemsets file which is sorted on confidence # writing out number of rules with confidence above certain thresholds #fam1, Category, fam2, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Avg dist, Std Dev, fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen # R=501 u2 R=468 8 0.8 0 0 8 0.8 1000 406.45 R=501 10 166 R=468 262 149 # R=810 u3 R=394 8 0.72 0 0 8 0.72 3854 746.43 R=810 11 224 R=394 15 289 # R=748 u3 R=225 7 0.7 0 0 7 0.7 634 37.22 R=748 10 241 R=225 22 457 my $ver=1.0; use strict; use warnings; use POSIX; unless (@ARGV == 1){ print "USAGE: $0 <input merged.f_itemsets file>\n"; exit; } # Supporting functions sub round2{ my ($num); $num=$_[0]; $num=$num*100; $num=int($num); $num=$num/100; return $num; } my ($ifname,$rec,@temp,@m_f_itemsets_table,%rel_ctrs,$ctr,$flag,$i,$j,$k,$key,$value,$tot_recs ,$user_t,$system_t,$cuser_t,$csystem_t); $ifname=$ARGV[0]; chomp $ifname; unless(open(INFILEFITEMSETS,$ifname)){print "not able to open ".$ifname."\n\n";exit;} unless(open(OUTFILEDATA,">$ifname.fdr.tab")){print "not able to open $ifname.fdr.tab\n\n";exit;} #fam1, Category, fam2, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Avg dist, Std Dev, fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen # R=501 U R=468 8 0.8 0 0 8 0.8 1000 406.45 R=501 10 166 R=468 262 149 # R=810 D R=394 8 0.72 0 0 8 0.72 3854 746.43 R=810 11 224 R=394 15 289 # slurping in the whole freq itemsets file $ctr=0; while($rec=<INFILEFITEMSETS>){ if($rec =~ /^#/){next;} if(length ($rec) < 10){next;}#for avoiding last line push @m_f_itemsets_table,[split(' ',$rec)]; $ctr++; } close (INFILEFITEMSETS); # record tot recs $tot_recs = $ctr; # initialize counters for ($i=0.05;$i<=1.05;$i+=0.05){ $rel_ctrs{"$i"}=0; } #fam1, Category, fam2, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Avg dist, Std Dev, fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen # R=501 U R=468 8 0.8 0 0 8 0.8 1000 406.45 R=501 10 166 R=468 262 149 # R=810 D R=394 8 0.72 0 0 8 0.72 3854 746.43 R=810 11 224 R=394 15 289 # updating the counters foreach $i (@m_f_itemsets_table){ while(($key, $value)= each %rel_ctrs){ # if (($i->[12]<=50) && ($i->[15]<=50)){ for families with elements within a range if($i->[4] >= $key){ $rel_ctrs{$key}++;} #increment ctr if valid } } # print the connected components $i=localtime(); # calculating time taken ($user_t,$system_t,$cuser_t,$csystem_t) = times; print OUTFILEDATA "\# Version: $ver\n"; print OUTFILEDATA "\# Time: $i\n\n"; print OUTFILEDATA "\# Runtime details after preparing graphs and getting the conn components:\n"; print OUTFILEDATA "\# System time for process: $system_t\n"; print OUTFILEDATA "\# User time for process: $user_t\n\n"; print OUTFILEDATA "\n**********************************************************************\n\n"; print OUTFILEDATA "\# Merged fitemsets file used : $ifname\n"; # getting the ctrs in a sorted array print OUTFILEDATA "Confidence threshold\tNumber of rules\n"; foreach $key (sort keys %rel_ctrs){ print OUTFILEDATA $key,"\t",$rel_ctrs{$key},"\n"; } print OUTFILEDATA "\n\n**********************************************************************\n\n"; print OUTFILEDATA "\# Runtime details : \n"; print OUTFILEDATA "\# System time for process: $system_t\n"; print OUTFILEDATA "\# User time for process: $user_t\n"; close (OUTFILEDATA); # calculating time taken ($user_t,$system_t,$cuser_t,$csystem_t) = times; print "\# Runtime details : \n"; print "\# System time for process: $system_t\n"; print "\# User time for process: $user_t\n"; exit;
suryasaha/ProxMiner
scripts/miner.fdr.real.merged.stage1.v1.pl
Perl
bsd-2-clause
3,725
package Proxy::AccessControl; use strict; use warnings; use Attribute::Handlers; my %perms; sub UNIVERSAL::perms { my ($package, $symbol, $referent, $attr, $data) = @_; my $method = *{ $symbol }{NAME}; for my $permission (split(/\s+/, $data)) { push @{ $perms{ $package }{ $method } }, $permission; } } sub dispatch { my ($user, $class, $method, @args) = @_; return unless $perms{ $class }{ $method } and $class->can( $method ); for my $perm (@{ $perms{ $class }{ $method } }) { die "Need permission '$perm\n'" unless $user->has_permission( $perm ); } $class->$method( @args ); } 1;
jmcveigh/komodo-tools
scripts/perl/control_access_to_remote_objects/lib/Proxy/AccessControl.pm
Perl
bsd-2-clause
690