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
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package cloud::aws::mode::metrics::ec2instancecpucreditusage; use strict; use warnings; use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(&cloudwatchCheck); my @Param; $Param[0] = { 'NameSpace' => 'AWS/EC2', 'MetricName' => 'CPUCreditUsage', 'ObjectName' => 'InstanceId', 'Unit' => 'Count', 'Labels' => { 'ShortOutput' => "CPUCreditUsage is %.2f%%", 'LongOutput' => "CPUCreditUsage is %.2f%%", 'PerfData' => 'CPUCreditUsage', 'Unit' => 'Count', 'Value' => "%.2f", } }; sub cloudwatchCheck { my ($self) = @_; @{ $self->{metric} } = @Param; } 1;
nichols-356/centreon-plugins
cloud/aws/mode/metrics/ec2instancecpucreditusage.pm
Perl
apache-2.0
1,419
package DDG::Spice::BitcoinBalance; # ABSTRACT: Displays the balance of a Bitcoin address from the Chain.com API. use DDG::Spice; primary_example_queries "17x23dNjXJLzGMev6R63uyRhMWP1VHawKc", "1Gn2dRFqouUHvuWPVhriCDtP3qVQc59WHy", "3QJmV3qfvL9SuYo34YihAf3sRCW3qSinyC"; description "Display the balance of a Bitcoin address"; name "Bitcoin Address Balance"; source "http://chain.com"; code_url "https://github.com/duckduckgo/zeroclickinfo-spice/blob/master/lib/DDG/Spice/BitcoinBalance.pm"; topics "economy_and_finance"; category "finance"; icon_url "https://chain.com/chain32x32.ico"; attribution github => ['https://github.com/chain-engineering','chain.com'], email => ['hello@chain.com','chain.com'], twitter => ["chain", 'chain.com'], web => ['https://chain.com','chain.com']; triggers query_raw => qr/^[13][1-9A-HJ-NP-Za-km-z]{26,33}$/; # This regular expression identifies the unique properties of a Bitcoin Address. spice to => 'https://api.chain.com/v1/bitcoin/addresses/$1?key={{ENV{DDG_SPICE_BITCOIN_APIKEY}}}'; # The Chain API requires an API key. Chain has granted the spice a free account with unlimited access. We can provide this to DuckDuckGo before release. spice wrap_jsonp_callback => 1; spice proxy_cache_valid => "418 1d"; handle query_raw => sub { return $_; }; 1;
timeanddate/zeroclickinfo-spice
lib/DDG/Spice/BitcoinBalance.pm
Perl
apache-2.0
1,346
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package centreon::common::violin::snmp::mode::hardware; use base qw(centreon::plugins::templates::hardware); use strict; use warnings; my $thresholds = { }; sub set_system { my ($self, %options) = @_; $self->{regexp_threshold_overload_check_section_option} = '^(vimm|ca|psu|fan|gfc|lfc)$'; $self->{regexp_threshold_numeric_check_section_option} = '^(temperature)$'; $self->{cb_hook2} = 'snmp_execute'; $self->{thresholds} = { vimm => [ ['not failed', 'OK'], ['failed', 'CRITICAL'], ], ca => [ ['ON', 'CRITICAL'], ['OFF', 'OK'], ], psu => [ ['OFF', 'CRITICAL'], ['Absent', 'OK'], ['ON', 'OK'], ], fan => [ ['OFF', 'CRITICAL'], ['Absent', 'OK'], ['Low', 'OK'], ['Medium', 'OK'], ['High', 'WARNING'], ], gfc => [ ['Online', 'OK'], ['Unconfigured', 'OK'], ['Unknown', 'UNKNOWN'], ['Not\s*Supported', 'WARNING'], ['Dead', 'CRITICAL'], ['Lost', 'CRITICAL'], ['Failover\s*Failed', 'CRITICAL'], ['Failover', 'WARNING'], ], lfc => [ ['Online', 'OK'], ['Unconfigured', 'OK'], ['Unknown', 'UNKNOWN'], ['Not\s*Supported', 'WARNING'], ['Dead', 'CRITICAL'], ['Lost', 'CRITICAL'], ['Failover\s*Failed', 'CRITICAL'], ['Failover', 'WARNING'], ], }; $self->{components_path} = 'centreon::common::violin::snmp::mode::components'; $self->{components_module} = ['ca', 'psu', 'fan', 'vimm', 'temperature', 'gfc', 'lfc']; } sub snmp_execute { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->{results} = $self->{snmp}->get_multiple_table(oids => $self->{request}); } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { }); return $self; } sub convert_index { my ($self, %options) = @_; my @results = (); my $separator = 32; my $result = ''; foreach (split /\./, $options{value}) { if ($_ < $separator) { push @results, $result; $result = ''; } else { $result .= chr; } } push @results, $result; return @results; } 1; __END__ =head1 MODE Check components (Fans, Power Supplies, Temperatures, Chassis alarm, vimm, global fc, local fc). =over 8 =item B<--component> Which component to check (Default: '.*'). Can be: 'psu', 'fan', 'ca', 'vimm', 'lfc', 'gfc', 'temperature'. =item B<--filter> Exclude some parts (comma seperated list) (Example: --filter=fan --filter=psu) Can also exclude specific instance: --filter=fan,41239F00647-A =item B<--absent-problem> Return an error if an entity is not 'present' (default is skipping) (comma seperated list) Can be specific or global: --absent-problem=fan,41239F00647-fan02 =item B<--no-component> Return an error if no compenents are checked. If total (with skipped) is 0. (Default: 'critical' returns). =item B<--threshold-overload> Set to overload default threshold values (syntax: section,[instance,]status,regexp) It used before default thresholds (order stays). Example: --threshold-overload='gfc,CRITICAL,^(?!(Online)$)' =item B<--warning> Set warning threshold for temperatures (syntax: type,regexp,threshold) Example: --warning='temperature,41239F00647-vimm46,20' --warning='temperature,41239F00647-vimm5.*,30' =item B<--critical> Set critical threshold for temperatures (syntax: type,regexp,threshold) Example: --critical='temperature,.*,25' --warning='temperature,.*,35' =back =cut
Shini31/centreon-plugins
centreon/common/violin/snmp/mode/hardware.pm
Perl
apache-2.0
4,761
package OpenResty::Inlined; use strict; use warnings; use base 'OpenResty'; sub response { my $self = shift; if ($self->{_no_response}) { return undef; } #print "HTTP/1.1 200 OK\n"; #warn $s; if (my $bin_data = $self->{_bin_data}) { return "BINARY DATA"; } if (my $error = $self->{_error}) { return $self->emit_error($error); } if (my $data = $self->{_data}) { if ($self->{_warning}) { $data->{warning} = $self->{_warning}; } return $data; } return undef; } sub emit_data { my ($self, $data) = @_; #warn "$data"; return $data; } 1; __END__ =head1 NAME OpenResty::Inlined - OpenResty app class for inlined REST requrests
beni55/old-openresty
lib/OpenResty/Inlined.pm
Perl
bsd-3-clause
737
# !!!!!!! 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'; 1000 109F END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/lib/Blk/Myanmar.pl
Perl
mit
421
do 'pserver-lib.pl'; # acl_security_form(&options) # Output HTML for editing security options for the pserver module sub acl_security_form { local $i = 0; foreach $f (@features, 'setup', 'init') { print "<tr>\n" if ($i%2 == 0); print "<td><b>",$text{'acl_'.$f},"</b></td> <td>\n"; printf "<input type=radio name=%s value=1 %s> $text{'yes'}\n", $f, $_[0]->{$f} ? 'checked' : ''; printf "<input type=radio name=%s value=0 %s> $text{'no'}</td>\n", $f, $_[0]->{$f} ? '' : 'checked'; print "</tr>\n" if ($i++%2 == 1); } print "</tr>\n" if ($i%2 == 1); } # acl_security_save(&options) # Parse the form for security options for the acl module sub acl_security_save { foreach $f (@features, 'setup', 'init') { $_[0]->{$f} = $in{$f}; } }
HasClass0/webmin
pserver/acl_security.pl
Perl
bsd-3-clause
745
## ## Italian tables ## package Date::Language::Romanian; use Date::Language (); use vars qw(@ISA @DoW @DoWs @MoY @MoYs @AMPM @Dsuf %MoY %DoW $VERSION); @ISA = qw(Date::Language); $VERSION = "1.01"; @MoY = qw(ianuarie februarie martie aprilie mai iunie iulie august septembrie octombrie noembrie decembrie); @DoW = qw(duminica luni marti miercuri joi vineri sambata); @DoWs = map { substr($_,0,3) } @DoW; @MoYs = map { substr($_,0,3) } @MoY; @AMPM = qw(AM PM); @Dsuf = ('') x 31; @MoY{@MoY} = (0 .. scalar(@MoY)); @MoY{@MoYs} = (0 .. scalar(@MoYs)); @DoW{@DoW} = (0 .. scalar(@DoW)); @DoW{@DoWs} = (0 .. scalar(@DoWs)); # Formatting routines sub format_a { $DoWs[$_[0]->[6]] } sub format_A { $DoW[$_[0]->[6]] } sub format_b { $MoYs[$_[0]->[4]] } sub format_B { $MoY[$_[0]->[4]] } sub format_h { $MoYs[$_[0]->[4]] } sub format_p { $_[0]->[2] >= 12 ? $AMPM[1] : $AMPM[0] } 1;
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/Date/Language/Romanian.pm
Perl
mit
892
#!/usr/bin/perl # torrentCleanup.pl # Removes useless crap from downloaded TV / Movie file names. # Meant for use on a DNS 323 NAS (hence Perl, and not something more readable) # Tested on Perl v5.10.0 use strict; #use warnings; #use diagnostics; use File::Copy; use Cwd; exit(&main); sub main(){ my $logfile = $0 . ".log"; if (! open LOG, ">", $logfile){ die "Cannot create logfile.: $!"; } my $cwd = cwd(); my $dir; if(defined $ARGV[0]){ $dir = $ARGV[0]; printf LOG "using argument as dir: $dir\n"; } else { $dir = $cwd; printf LOG "no dir arg supplied. using cwd as dir: $cwd\n"; } ########### # Case-Sensitive Patterns: # Replace with "" ########### my @CaseSensitivePatterns = qw( \-SWOLLED x264\-2HD x264\-KILLERS x264\-LOL x264\-EXCELLENCE hdtv\-lol x264\-2hd \-mSD AAC AMIABLE AFG \-ASAP AsA ARROW Atilla82 BAJSKORV \-BATV \-BeLLBoY BoB BluRay \.BOKUTOX \.D\-Z0N3 CALLIXTUS DIMENSION DOWNLOAD DiAMOND DiVERSiTY \-DoNE \-EMBRACE \-EVOLVE \-FLEET \-EVO FREE IGUANA IMAGiNE \-IMMERSE \.INTERNAL iNK iTALiAN Kingdom\-Release \-lol LOL LMAO MiB NANO \.PilotTV \-P0W4 \.PROPER \.REPACK \.repack \.Royskatt RmD \-THC \-TLA \-tla TS VAMPS UNCUT UnKnOwN UsaBit\.com UNRATED TOPAZ W4F cOOt \.web\-strife \.web\-tbs \-w4f \-crooks \-SVA \-RARBG \-NTb \-BORDERLiNE \-POOP \-guTTer \-WEB\-DL \-ETRG \.5\.1 \.WEB\-DL \.DD5\.1 \.H\.264 \-repack \-sva \.web\-tbs VIFY \.VIFY \.YIFY \-5\.1 \.\_ \_Parabellum VPPV \-nezu \.Hon3yHD \.HC \.800MB \-GalaxyRG \-NoTV \.WS \-aAF \-0TV ); ########### # Case Insensitive patterns # May or may not be prefixed by anything # Can definitely be replaced blindly and safely. # Replace with "" ########### my @CaseInsensitivePatterns = qw( 320p 480p 720p 1080p AC3 BDRip BRRip HDRip C4TV DVDRip DVDSCR \[Eng\] ENGRip FQM FXG HDTV h264 HDTVRip IDN_CREW MAXSPEED MXMG NiTR0 \[NO-RAR\] PDTV SeedPeer SUPERSEEDS\.ORG T0XiC x264 XViD ViP3R (\.|\-)Webrip \-bluray \.bluray ); my @ExplicitPatterns = ("HDScene Release" ,"{1337x}\-Noir" ,"DutchReleaseTeam" ,"dutch subs nl" ,"NWS\[gogt\]" ,"DOWNLOAD AT SUPERSEEDS.ORG" ,"ExtraTorrentRG" ,"www.Torrenting.com" ,"www.Torrentday.com" ," COMPLETE DVD Rip by vladtepes3176" ,"www.scenetime.com" ,"Blu-Ray" ,"www.torentz.3xforum.ro" ); my $hDir; opendir $hDir, $dir or die "Cannot open $dir: $!"; my $changeCount = 0; foreach my $oldname (readdir $hDir) { printf LOG "\n $oldname\n"; if($oldname =~ m/^\./) { printf LOG "filename begins with dot. Not going to touch it. \n"; }else{ my $newname = $oldname; my $didmatch = 0; foreach my $pattern(@ExplicitPatterns){ if($newname =~ m/(\-|\.|\ )*$pattern/ig){ printf LOG " remove ExplicitPatterns $pattern\n"; $newname =~ s/(\-|\.|\ )*$pattern//ig; $didmatch = 1; } } foreach my $pattern(@CaseSensitivePatterns){ $_ = $newname; if(/(\-|\.|\ )*$pattern/g){ printf LOG " remove CaseSensitivePatterns $pattern\n"; $newname =~ s/(\-|\.|\ )*$pattern//g; $didmatch = 1; } } foreach my $pattern(@CaseInsensitivePatterns){ $_ = $newname; if(/(\-|\.|\ )*$pattern/gi){ printf LOG " remove CaseInsensitivePatterns $pattern\n"; $newname =~ s/(\-|\.|\ )*$pattern//gi; $didmatch = 1; } } $_ = $newname; if(/\[.*\]/g){ printf LOG " remove everything inside square brackets\n"; $newname =~ s/\[.*\]//g; $didmatch = 1; } $_ = $newname; if(/\(\)/g){ printf LOG " remove empty round brackets\n"; $newname =~ s/\(\)//g; $didmatch = 1; } $_ = $newname; if(/\{\}/g){ printf LOG " remove empty curly braces\n"; $newname =~ s/\{\}//g; $didmatch = 1; } $_ = $newname; if(/\(\)/g){ printf LOG " remove round brackets with a comma\n"; $newname =~ s/\(\,\)//g; $didmatch = 1; } $_ = $newname; if(m{^(\s|\-)+}g){ printf LOG " trim beginning whitespace\n"; $newname =~ s/^(\s|\-)+//g; $didmatch = 1; } $_ = $newname; if(m{(\s|\-|\.)+$}){ printf LOG " trim ending whitespace\n"; $newname =~ s/(\s|\-|\.)+$//g; $didmatch = 1; } # is this dangerous? $_ = $newname; if(m/\.{2,}/){ printf LOG " consolidate multi dots\n"; $newname =~ s/\.{2,}/./g; $didmatch = 1; } my $oldpath = $dir . "/" . $oldname; my $newpath = $dir . "/" . $newname; if($didmatch){ $changeCount++; printf LOG "oldpath: $oldpath\n"; printf LOG "newpath: $newpath\n"; printf STDERR "$oldname -> $newname\n"; if(-d $oldpath){ printf LOG "New dir: [$newname]\n"; move($oldpath, $newpath) or die "move failed $!"; } elsif (-f $oldpath) { printf LOG "New fil: [$newname]\n"; move($oldpath, $newpath) or die "move failed $!"; } else { printf LOG "New UNK? [$newname]\n"; } } else { printf LOG "No chng: $newname\n"; } } } if($changeCount > 0) { printf STDERR "Activity saved to $logfile\n"; } close LOG; return 0; }
dale-c-anderson/torrentCleanup-pl
torrentCleanup.pl
Perl
mit
6,060
sub name_of_subroutine { ## Function : ## Returns : ## Arguments: $arrays_ref => Array ref description {REF} ## : $hash_href => Hash ref description {REF} ## : $scalar => Scalar description my ($arg_href) = @_; ## Flatten argument(s) my $arrays_ref; my $hash_href; ## Default(s) my $scalar; my $tmpl = { arrays_ref => { default => [], defined => 1, required => 1, store => \$arrays_ref, strict_type => 1, }, hash_href => { default => {}, defined => 1, required => 1, store => \$hash_href, strict_type => 1, }, scalar => { allow => qr{ \A\d+\z }sxm, default => 1, store => \$scalar, strict_type => 1, }, }; check( $tmpl, $arg_href, 1 ) or croak q{Could not parse arguments!}; return; }
henrikstranneheim/MIP
templates/code/subroutine.pl
Perl
mit
1,022
% The problem asks to find all integer points that % are inside a circle (around (0,0)) or that are on % the circle's borders % Generates all numbers between A and B gen(A, _, A). gen(A, B, X) :- A < B, A1 is A + 1, gen(A1, B, X). % Checks if a given point(X, Y) in 2D space is % in a circle with radius R around the (0, 0) point isInCirc(X, Y, R) :- X2 is X * X, Y2 is Y * Y, R2 is R * R, X2 + Y2 =< R2. % Generates all the poins in format (X, Y) that are % in the circle with radius R around the (0, 0) point allPoints(X, Y, R) :- R2 is 0 - R, gen(R2, R, X), gen(R2, R, Y), isInCirc(X, Y, R).
dkalinkov/fmi-projects
prolog/points-in-circle.pl
Perl
mit
655
########################################################################### # # This file is auto-generated by the Perl DateTime Suite time locale # generator (0.04). This code generator comes with the # DateTime::Locale distribution in the tools/ directory, and is called # generate_from_cldr. # # This file as generated from the CLDR XML locale data. See the # LICENSE.cldr file included in this distribution for license details. # # This file was generated from the source file ak.xml. # The source file version number was 1.26, generated on # 2007/07/19 22:31:38. # # Do not edit this file directly. # ########################################################################### package DateTime::Locale::ak; use strict; BEGIN { if ( $] >= 5.006 ) { require utf8; utf8->import; } } use DateTime::Locale::root; @DateTime::Locale::ak::ISA = qw(DateTime::Locale::root); my @day_names = ( "Dwowda", "Benada", "Wukuda", "Yawda", "Fida", "Memeneda", "Kwesida", ); my @day_abbreviations = ( "Dwo", "Ben", "Wuk", "Yaw", "Fia", "Mem", "Kwe", ); my @day_narrows = ( "D", "B", "W", "Y", "F", "M", "K", ); my @month_names = ( "Sanda\-Ɔpɛpɔn", "Kwakwar\-Ɔgyefuo", "Ebɔw\-Ɔbenem", "Ebɔbira\-Oforisuo", "Esusow\ Aketseaba\-Kɔtɔnimba", "Obirade\-Ayɛwohomumu", "Ayɛwoho\-Kitawonsa", "Difuu\-Ɔsandaa", "Fankwa\-Ɛbɔ", "Ɔbɛsɛ\-Ahinime", "Ɔberɛfɛw\-Obubuo", "Mumu\-Ɔpɛnimba", ); my @month_abbreviations = ( "S\-Ɔ", "K\-Ɔ", "E\-Ɔ", "E\-O", "E\-K", "O\-A", "A\-K", "D\-Ɔ", "F\-Ɛ", "Ɔ\-A", "Ɔ\-O", "M\-Ɔ", ); my @month_narrows = ( "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", ); my @quarter_names = ( "Q1", "Q2", "Q3", "Q4", ); my @quarter_abbreviations = ( "Q1", "Q2", "Q3", "Q4", ); my @am_pms = ( "AN", "EW", ); my @era_names = ( "Ansa\ Kristo", "Kristo\ Ekyiri", ); my @era_abbreviations = ( "AK", "KE", ); my $date_before_time = "1"; my $date_parts_order = "ymd"; sub day_names { \@day_names } sub day_abbreviations { \@day_abbreviations } sub day_narrows { \@day_narrows } sub month_names { \@month_names } sub month_abbreviations { \@month_abbreviations } sub month_narrows { \@month_narrows } sub quarter_names { \@quarter_names } sub quarter_abbreviations { \@quarter_abbreviations } sub am_pms { \@am_pms } sub era_names { \@era_names } sub era_abbreviations { \@era_abbreviations } sub full_date_format { "\%A\,\ \%\{ce_year\}\ \%B\ \%d" } sub long_date_format { "\%\{ce_year\}\ \%B\ \%\{day\}" } sub medium_date_format { "\%\{ce_year\}\ \%b\ \%\{day\}" } sub short_date_format { "\%y\/\%m\/\%d" } sub full_time_format { "\%H\:\%M\:\%S\ v" } sub long_time_format { "\%H\:\%M\:\%S\ \%\{time_zone_long_name\}" } sub medium_time_format { "\%H\:\%M\:\%S" } sub short_time_format { "\%H\:\%M" } sub date_before_time { $date_before_time } sub date_parts_order { $date_parts_order } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/DateTime/Locale/ak.pm
Perl
mit
3,180
%query: mergesort(i,o). mergesort([],[]). mergesort([X],[X]). mergesort([X,Y|Xs],Ys) :- split([X,Y|Xs],X1s,X2s), mergesort(X1s,Y1s), mergesort(X2s,Y2s), merge(Y1s,Y2s,Ys). split([],[],[]). split([X|Xs],[X|Ys],Zs) :- split(Xs,Zs,Ys). merge([],Xs,Xs). merge(Xs,[],Xs). merge([X|Xs],[Y|Ys],[X|Zs]) :- X=Y, merge([X|Xs],Ys,Zs).
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Logic_Programming/lpexamples/mergesort.pl
Perl
mit
384
#!/usr/bin/perl -w use 5.010; use strict; use constant PI => 3.1415926; my $radius; &input_func; until( $radius =~ /^-?\d{1,}\.?\d{0,}$/ ){ say "wrong input.."; &input_func; } $radius = 0 if( $radius < 0 ); my $circ = 2 * PI * $radius; say "The circumference of a circle of a radius $radius is $circ"; sub input_func{ say "Please enter the radius of a circle: "; chomp( $radius = <STDIN> ); }
OldSix/Learning-Perl
chapter02/01.pl
Perl
mit
412
#!/usr/bin/perl -w #http://www.cimgf.com/2008/04/13/git-and-xcode-a-git-build-number-script/ # Xcode auto-versioning script for Subversion by Axel Andersson # Updated for git by Marcus S. Zarra and Matt Long use strict; # Get the current git commit hash and use it to set the CFBundleVersion value my $REV = `/opt/local/bin/git show --abbrev-commit | grep "^commit"`; my $INFO = "$ENV{BUILT_PRODUCTS_DIR}/$ENV{WRAPPER_NAME}/Contents/Info.plist"; my $version = $REV; if( $version =~ /^commit\s+([^.]+)\.\.\.$/ ) { $version = $1; } else { $version = undef; } die "$0: No Git revision found" unless $version; open(FH, "$INFO") or die "$0: $INFO: $!"; my $info = join("", <FH>); close(FH); $info =~ s/([\t ]+<key>CFBundleVersion<\/key>\n[\t ]+<string>).*?(<\/string>)/$1$version$2/; open(FH, ">$INFO") or die "$0: $INFO: $!"; print FH $info; close(FH);
sauloal/linuxscripts
git/serial.pl
Perl
mit
865
package VulnDB::RDBO::Message::Manager; use base qw(Rose::DB::Object::Manager); use VulnDB::RDBO::Message; sub object_class { 'VulnDB::RDBO::Message' } __PACKAGE__->make_manager_methods('message'); 1;
jonaustin/advisoryscan
vulntracker/perl/vulntracker/VulnDB/RDBO/Message/Manager.pm
Perl
mit
207
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.4 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. package ABAC; use base qw(Exporter); use base qw(DynaLoader); package ABACc; bootstrap ABAC; package ABAC; @EXPORT = qw(); # ---------- BASE METHODS ------------- package ABAC; sub TIEHASH { my ($classname,$obj) = @_; return bless $obj, $classname; } sub CLEAR { } sub FIRSTKEY { } sub NEXTKEY { } sub FETCH { my ($self,$field) = @_; my $member_func = "swig_${field}_get"; $self->$member_func(); } sub STORE { my ($self,$field,$newval) = @_; my $member_func = "swig_${field}_set"; $self->$member_func($newval); } sub this { my $ptr = shift; return tied(%$ptr); } # ------- FUNCTION WRAPPERS -------- package ABAC; *SSL_keyid = *ABACc::SSL_keyid; *abac_context_new = *ABACc::abac_context_new; *abac_context_dup = *ABACc::abac_context_dup; *abac_context_free = *ABACc::abac_context_free; *abac_context_load_id_file = *ABACc::abac_context_load_id_file; *abac_context_load_id_chunk = *ABACc::abac_context_load_id_chunk; *abac_context_load_attribute_file = *ABACc::abac_context_load_attribute_file; *abac_context_load_attribute_chunk = *ABACc::abac_context_load_attribute_chunk; *abac_context_load_directory = *ABACc::abac_context_load_directory; *abac_context_query = *ABACc::abac_context_query; *abac_context_credentials = *ABACc::abac_context_credentials; *abac_context_credentials_free = *ABACc::abac_context_credentials_free; *abac_credential_head = *ABACc::abac_credential_head; *abac_credential_tail = *ABACc::abac_credential_tail; *abac_credential_attribute_cert = *ABACc::abac_credential_attribute_cert; *abac_credential_issuer_cert = *ABACc::abac_credential_issuer_cert; *abac_credential_dup = *ABACc::abac_credential_dup; *abac_credential_free = *ABACc::abac_credential_free; *abac_role_principal_new = *ABACc::abac_role_principal_new; *abac_role_role_new = *ABACc::abac_role_role_new; *abac_role_linking_new = *ABACc::abac_role_linking_new; *abac_role_free = *ABACc::abac_role_free; *abac_role_from_string = *ABACc::abac_role_from_string; *abac_role_dup = *ABACc::abac_role_dup; *abac_role_is_principal = *ABACc::abac_role_is_principal; *abac_role_is_role = *ABACc::abac_role_is_role; *abac_role_is_linking = *ABACc::abac_role_is_linking; *abac_role_is_intersection = *ABACc::abac_role_is_intersection; *abac_role_string = *ABACc::abac_role_string; *abac_role_linked_role = *ABACc::abac_role_linked_role; *abac_role_role_name = *ABACc::abac_role_role_name; *abac_role_principal = *ABACc::abac_role_principal; *abac_role_attr_key = *ABACc::abac_role_attr_key; *abac_id_from_file = *ABACc::abac_id_from_file; *abac_id_from_chunk = *ABACc::abac_id_from_chunk; *abac_id_privkey_from_file = *ABACc::abac_id_privkey_from_file; *abac_id_privkey_from_chunk = *ABACc::abac_id_privkey_from_chunk; *abac_id_generate = *ABACc::abac_id_generate; *abac_id_generate_with_key = *ABACc::abac_id_generate_with_key; *abac_id_keyid = *ABACc::abac_id_keyid; *abac_id_issuer = *ABACc::abac_id_issuer; *abac_id_subject = *ABACc::abac_id_subject; *abac_id_still_valid = *ABACc::abac_id_still_valid; *abac_id_has_keyid = *ABACc::abac_id_has_keyid; *abac_id_has_privkey = *ABACc::abac_id_has_privkey; *abac_id_validity = *ABACc::abac_id_validity; *abac_id_cert_filename = *ABACc::abac_id_cert_filename; *abac_id_write_cert = *ABACc::abac_id_write_cert; *abac_id_privkey_filename = *ABACc::abac_id_privkey_filename; *abac_id_write_privkey = *ABACc::abac_id_write_privkey; *abac_id_cert_chunk = *ABACc::abac_id_cert_chunk; *abac_id_privkey_chunk = *ABACc::abac_id_privkey_chunk; *abac_id_dup = *ABACc::abac_id_dup; *abac_id_free = *ABACc::abac_id_free; *abac_attribute_create = *ABACc::abac_attribute_create; *abac_attribute_set_head = *ABACc::abac_attribute_set_head; *abac_attribute_get_head = *ABACc::abac_attribute_get_head; *abac_attribute_set_tail = *ABACc::abac_attribute_set_tail; *abac_attribute_get_tail = *ABACc::abac_attribute_get_tail; *abac_attribute_principal = *ABACc::abac_attribute_principal; *abac_attribute_role = *ABACc::abac_attribute_role; *abac_attribute_linking_role = *ABACc::abac_attribute_linking_role; *abac_attribute_bake = *ABACc::abac_attribute_bake; *abac_attribute_baked = *ABACc::abac_attribute_baked; *abac_attribute_write = *ABACc::abac_attribute_write; *abac_attribute_write_file = *ABACc::abac_attribute_write_file; *abac_attribute_cert_chunk = *ABACc::abac_attribute_cert_chunk; *abac_attribute_free = *ABACc::abac_attribute_free; *abac_attribute_certs_from_file = *ABACc::abac_attribute_certs_from_file; *abac_attribute_certs_from_chunk = *ABACc::abac_attribute_certs_from_chunk; *abac_attribute_role_string = *ABACc::abac_attribute_role_string; *abac_attribute_issuer_id = *ABACc::abac_attribute_issuer_id; *abac_attribute_validity = *ABACc::abac_attribute_validity; *abac_attribute_get_principal = *ABACc::abac_attribute_get_principal; *abac_attribute_still_valid = *ABACc::abac_attribute_still_valid; ############# Class : ABAC::CredentialVector ############## package ABAC::CredentialVector; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( ABAC ); %OWNER = (); %ITERATORS = (); sub new { my $pkg = shift; my $self = ABACc::new_CredentialVector(@_); bless $self, $pkg if defined($self); } *size = *ABACc::CredentialVector_size; *empty = *ABACc::CredentialVector_empty; *clear = *ABACc::CredentialVector_clear; *push = *ABACc::CredentialVector_push; *get = *ABACc::CredentialVector_get; *set = *ABACc::CredentialVector_set; sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); return unless defined $self; delete $ITERATORS{$self}; if (exists $OWNER{$self}) { ABACc::delete_CredentialVector($self); delete $OWNER{$self}; } } sub DISOWN { my $self = shift; my $ptr = tied(%$self); delete $OWNER{$ptr}; } sub ACQUIRE { my $self = shift; my $ptr = tied(%$self); $OWNER{$ptr} = 1; } ############# Class : ABAC::abac_chunk_t ############## package ABAC::abac_chunk_t; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( ABAC ); %OWNER = (); %ITERATORS = (); *swig_ptr_get = *ABACc::abac_chunk_t_ptr_get; *swig_ptr_set = *ABACc::abac_chunk_t_ptr_set; *swig_len_get = *ABACc::abac_chunk_t_len_get; *swig_len_set = *ABACc::abac_chunk_t_len_set; sub new { my $pkg = shift; my $self = ABACc::new_abac_chunk_t(@_); bless $self, $pkg if defined($self); } sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); return unless defined $self; delete $ITERATORS{$self}; if (exists $OWNER{$self}) { ABACc::delete_abac_chunk_t($self); delete $OWNER{$self}; } } sub DISOWN { my $self = shift; my $ptr = tied(%$self); delete $OWNER{$ptr}; } sub ACQUIRE { my $self = shift; my $ptr = tied(%$self); $OWNER{$ptr} = 1; } ############# Class : ABAC::Role ############## package ABAC::Role; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( ABAC ); %OWNER = (); %ITERATORS = (); sub new { my $pkg = shift; my $self = ABACc::new_Role(@_); bless $self, $pkg if defined($self); } sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); return unless defined $self; delete $ITERATORS{$self}; if (exists $OWNER{$self}) { ABACc::delete_Role($self); delete $OWNER{$self}; } } *is_principal = *ABACc::Role_is_principal; *is_role = *ABACc::Role_is_role; *is_linking = *ABACc::Role_is_linking; *string = *ABACc::Role_string; *linked_role = *ABACc::Role_linked_role; *role_name = *ABACc::Role_role_name; *principal = *ABACc::Role_principal; sub DISOWN { my $self = shift; my $ptr = tied(%$self); delete $OWNER{$ptr}; } sub ACQUIRE { my $self = shift; my $ptr = tied(%$self); $OWNER{$ptr} = 1; } ############# Class : ABAC::Credential ############## package ABAC::Credential; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( ABAC ); %OWNER = (); %ITERATORS = (); sub new { my $pkg = shift; my $self = ABACc::new_Credential(@_); bless $self, $pkg if defined($self); } sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); return unless defined $self; delete $ITERATORS{$self}; if (exists $OWNER{$self}) { ABACc::delete_Credential($self); delete $OWNER{$self}; } } *head = *ABACc::Credential_head; *tail = *ABACc::Credential_tail; *attribute_cert = *ABACc::Credential_attribute_cert; *issuer_cert = *ABACc::Credential_issuer_cert; sub DISOWN { my $self = shift; my $ptr = tied(%$self); delete $OWNER{$ptr}; } sub ACQUIRE { my $self = shift; my $ptr = tied(%$self); $OWNER{$ptr} = 1; } ############# Class : ABAC::Context ############## package ABAC::Context; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( ABAC ); %OWNER = (); %ITERATORS = (); sub new { my $pkg = shift; my $self = ABACc::new_Context(@_); bless $self, $pkg if defined($self); } sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); return unless defined $self; delete $ITERATORS{$self}; if (exists $OWNER{$self}) { ABACc::delete_Context($self); delete $OWNER{$self}; } } *load_id_file = *ABACc::Context_load_id_file; *load_id_chunk = *ABACc::Context_load_id_chunk; *load_attribute_file = *ABACc::Context_load_attribute_file; *load_attribute_chunk = *ABACc::Context_load_attribute_chunk; *load_directory = *ABACc::Context_load_directory; *query = *ABACc::Context_query; *credentials = *ABACc::Context_credentials; sub DISOWN { my $self = shift; my $ptr = tied(%$self); delete $OWNER{$ptr}; } sub ACQUIRE { my $self = shift; my $ptr = tied(%$self); $OWNER{$ptr} = 1; } ############# Class : ABAC::ID ############## package ABAC::ID; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( ABAC ); %OWNER = (); %ITERATORS = (); sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); return unless defined $self; delete $ITERATORS{$self}; if (exists $OWNER{$self}) { ABACc::delete_ID($self); delete $OWNER{$self}; } } sub new_ID_chunk { my $pkg = shift; my $self = ABACc::new_ID_chunk(@_); bless $self, $pkg if defined($self); } sub new { my $pkg = shift; my $self = ABACc::new_ID(@_); bless $self, $pkg if defined($self); } *load_privkey = *ABACc::ID_load_privkey; *load_privkey_chunk = *ABACc::ID_load_privkey_chunk; *has_privkey = *ABACc::ID_has_privkey; *keyid = *ABACc::ID_keyid; *cert_filename = *ABACc::ID_cert_filename; *write_cert = *ABACc::ID_write_cert; *write_cert_file = *ABACc::ID_write_cert_file; *write_cert_name = *ABACc::ID_write_cert_name; *privkey_filename = *ABACc::ID_privkey_filename; *write_privkey = *ABACc::ID_write_privkey; *write_privkey_file = *ABACc::ID_write_privkey_file; *write_privkey_name = *ABACc::ID_write_privkey_name; *cert_chunk = *ABACc::ID_cert_chunk; *privkey_chunk = *ABACc::ID_privkey_chunk; sub DISOWN { my $self = shift; my $ptr = tied(%$self); delete $OWNER{$ptr}; } sub ACQUIRE { my $self = shift; my $ptr = tied(%$self); $OWNER{$ptr} = 1; } ############# Class : ABAC::Attribute ############## package ABAC::Attribute; use vars qw(@ISA %OWNER %ITERATORS %BLESSEDMEMBERS); @ISA = qw( ABAC ); %OWNER = (); %ITERATORS = (); sub DESTROY { return unless $_[0]->isa('HASH'); my $self = tied(%{$_[0]}); return unless defined $self; delete $ITERATORS{$self}; if (exists $OWNER{$self}) { ABACc::delete_Attribute($self); delete $OWNER{$self}; } } sub new { my $pkg = shift; my $self = ABACc::new_Attribute(@_); bless $self, $pkg if defined($self); } *principal = *ABACc::Attribute_principal; *role = *ABACc::Attribute_role; *linking_role = *ABACc::Attribute_linking_role; *bake = *ABACc::Attribute_bake; *baked = *ABACc::Attribute_baked; *write = *ABACc::Attribute_write; *write_file = *ABACc::Attribute_write_file; *write_name = *ABACc::Attribute_write_name; *cert_chunk = *ABACc::Attribute_cert_chunk; sub DISOWN { my $self = shift; my $ptr = tied(%$self); delete $OWNER{$ptr}; } sub ACQUIRE { my $self = shift; my $ptr = tied(%$self); $OWNER{$ptr} = 1; } # ------- VARIABLE STUBS -------- package ABAC; *ABAC_RC_SUCCESS = *ABACc::ABAC_RC_SUCCESS; *ABAC_RC_FAILURE = *ABACc::ABAC_RC_FAILURE; *ABAC_CERT_SUCCESS = *ABACc::ABAC_CERT_SUCCESS; *ABAC_CERT_INVALID = *ABACc::ABAC_CERT_INVALID; *ABAC_CERT_BAD_SIG = *ABACc::ABAC_CERT_BAD_SIG; *ABAC_CERT_MISSING_ISSUER = *ABACc::ABAC_CERT_MISSING_ISSUER; *ABAC_CERT_BAD_PRINCIPAL = *ABACc::ABAC_CERT_BAD_PRINCIPAL; *ABAC_CERT_INVALID_ISSUER = *ABACc::ABAC_CERT_INVALID_ISSUER; *ABAC_CERT_SIGNER_NOKEY = *ABACc::ABAC_CERT_SIGNER_NOKEY; *ABAC_SUCCESS = *ABACc::ABAC_SUCCESS; *ABAC_FAILURE = *ABACc::ABAC_FAILURE; *ABAC_GENERATE_INVALID_CN = *ABACc::ABAC_GENERATE_INVALID_CN; *ABAC_GENERATE_INVALID_VALIDITY = *ABACc::ABAC_GENERATE_INVALID_VALIDITY; *ABAC_ATTRIBUTE_ISSUER_NOKEY = *ABACc::ABAC_ATTRIBUTE_ISSUER_NOKEY; *ABAC_ATTRIBUTE_INVALID_ROLE = *ABACc::ABAC_ATTRIBUTE_INVALID_ROLE; *ABAC_ATTRIBUTE_INVALID_VALIDITY = *ABACc::ABAC_ATTRIBUTE_INVALID_VALIDITY; *ABAC_ATTRIBUTE_INVALID_ISSUER = *ABACc::ABAC_ATTRIBUTE_INVALID_ISSUER; 1;
nbsdx/abac
swig/perl/ABAC.pm
Perl
mit
13,514
#!/usr/bin/perl # **************************************************************************** # Script to generate the JIRA gadget XML files for TestRail user activity # summary for a specific test plan # **************************************************************************** use Config::Properties; use MIME::Base64; use JSON; use REST::Client; use HTML::Entities; # **************************************************************************** # Main # **************************************************************************** open my $PROPERTIES, '<', "./generate-gadget-xml.properties" or die "Unable to open configuration file: $!"; $properties = Config::Properties->new(); $properties->load($PROPERTIES); close ($PROPERTIES); my $gadgetDir = $properties->getProperty("gadgetDir"); # Set the URL, credentials, and headers for the REST calls my $url = $properties->getProperty("url"); my $user = $properties->getProperty("username"); my $pass = $properties->getProperty("password"); my $headers = { Authorization => 'Basic '. encode_base64($user . ':' . $pass), 'Content-type' => 'application/json' }; my $rest = REST::Client->new({host => "$url"}); my $templateXML, $projectPlanListXML = ""; my $defaultList = "0|0"; my $dataType = "enum"; my @projectPlanList; my $arr_index = 0; open $INXML, '<', "./template-user-activity-summary.xml" or die "Cannot open: $!"; $templateXML = join('',<$INXML>); close($INXML); $rest->GET("/index.php?/api/v2/get_projects", $headers ); my $project_data = decode_json( $rest->responseContent() ); if ($rest->responseCode() != 200) { printf("\nAPI call returned %s\n Error message: %s\n", $rest->responseCode(), $project_data->{error}); exit(1); } # Loop through all of the projects for my $project_node ( @$project_data ) { # Ignore completed projects if ($project_node->{'is_completed'} == 0) { $rest->GET("/index.php?/api/v2/get_plans/" . $project_node->{'id'}, $headers ); my $plan_data = decode_json( $rest->responseContent() ); if ($rest->responseCode() != 200) { printf("\nAPI call returned %s\n Error message: %s\n", $rest->responseCode(), $plan_data->{error}); exit(1); } # Loop through all of the plans for my $plan_node ( @$plan_data ) { # Ignore completed plans if ($plan_node->{'is_completed'} == 0) { $projectPlanList[$arr_index][0] = $project_node->{'id'}; $projectPlanList[$arr_index][1] = encode_entities($project_node->{'name'}); $projectPlanList[$arr_index][2] = $plan_node->{'id'}; $projectPlanList[$arr_index][3] = encode_entities($plan_node->{'name'}); $arr_index++; } } } } # Sort by project name, plan name @projectPlanList = sort { lc($a->[1]) cmp lc($b->[1])||lc($a->[3]) cmp lc($b->[3]) } (@projectPlanList); # Loop through all of the projects and plans to generate the UserPref XML for (my $i = 0; $i < $arr_index; $i++) { $projectPlanListXML .= "\n <EnumValue value=\"$projectPlanList[$i][0]|$projectPlanList[$i][2]\" display_value=\"($projectPlanList[$i][1]) $projectPlanList[$i][3]\"/>"; if ($defaultList eq "0|0") { $defaultList = "$projectPlanList[$i][0]|$projectPlanList[$i][2]"; } } if ($defaultList eq "0|0") { $dataType = "hidden"; } $templateXML =~ s/<%DEFAULTLIST%>/$defaultList/g; $templateXML =~ s/<%PROJECTPLANLIST%>/$projectPlanListXML/g; $templateXML =~ s/<%DATATYPE%>/$dataType/g; open $OUTXML, '>', "$gadgetDir/testrail-user-activity-summary.xml" or die "Cannot open: $!"; print($OUTXML "$templateXML"); close($OUTXML);
zenoss/testrail-jira-gadgets
scripts/generate-user-activity-gadget-xml.pl
Perl
apache-2.0
3,624
package Google::Ads::AdWords::v201402::AdWordsConversionTracker::TextFormat; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType AdWordsConversionTracker.TextFormat from the namespace https://adwords.google.com/api/adwords/cm/v201402. Text format to display on the conversion page. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/AdWordsConversionTracker/TextFormat.pm
Perl
apache-2.0
1,156
=head1 LICENSE See the NOTICE file distributed with this work for additional information regarding copyright ownership. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 NAME Bio::EnsEMBL::Compara::RunnableDB::DumpGenomes::DumpMaskedGenomeSequence =head1 DESCRIPTION Module to dump the soft- and hard-masked genome sequences. The files are moved to a shared directory. Input parameters =over =item genome_db_id dbID of the GenomeDB to dump =item genome_dumps_dir Base directory in which to dump the genome =back =cut package Bio::EnsEMBL::Compara::RunnableDB::DumpGenomes::DumpMaskedGenomeSequence; use strict; use warnings; use base ('Bio::EnsEMBL::Compara::RunnableDB::DumpGenomes::BaseDumpGenomeSequence'); sub set_dump_paths { my $self = shift; # The Runnable dumps the soft-masked genome and then converts it to hard-masked $self->param('repeat_masked', 'soft'); my $genome_db = $self->param('genome_db'); # Where the files should be $self->param('soft_masked_file', $genome_db->_get_genome_dump_path($self->param('genome_dumps_dir'), 'soft', not $self->param('is_reference'))); $self->param('hard_masked_file', $genome_db->_get_genome_dump_path($self->param('genome_dumps_dir'), 'hard', not $self->param('is_reference'))); return [$self->param('soft_masked_file'), $self->param('hard_masked_file')]; } sub run { my $self = shift; # Get the filenames my $tmp_dump_file = $self->param('genome_dump_file'); my $soft_masked_file = $self->param('soft_masked_file'); my $hard_masked_file = $self->param('hard_masked_file'); $self->_install_dump($tmp_dump_file, $soft_masked_file); # Convert to hard-masked my $cmd = qq{bash -c "tr a-z N < '$tmp_dump_file' > '$hard_masked_file'"}; $self->run_command($cmd, { die_on_failure => 1 }); die "$hard_masked_file size mismatch" if -s $tmp_dump_file != -s $hard_masked_file; unlink $tmp_dump_file; } sub write_output { my ($self) = @_; $self->dataflow_output_id( {'mask' => 'soft', 'genome_dump_file' => $self->param('soft_masked_file')}, 2 ); $self->dataflow_output_id( {'mask' => 'hard', 'genome_dump_file' => $self->param('hard_masked_file')}, 2 ); } 1;
Ensembl/ensembl-compara
modules/Bio/EnsEMBL/Compara/RunnableDB/DumpGenomes/DumpMaskedGenomeSequence.pm
Perl
apache-2.0
2,709
# # (c) Ferenc Erki <erkiferenc@gmail.com> # # vim: set ts=2 sw=2 tw=0: # vim: set expandtab: package Rex::Cloud::OpenStack; use strict; use warnings; our $VERSION = '0.56.1'; # VERSION use Rex::Logger; use base 'Rex::Cloud::Base'; BEGIN { use Rex::Require; JSON::XS->use; HTTP::Request::Common->use(qw(:DEFAULT DELETE)); LWP::UserAgent->use; } use Data::Dumper; use Carp; use MIME::Base64 qw(decode_base64); use Digest::MD5 qw(md5_hex); use File::Basename; sub new { my $that = shift; my $proto = ref($that) || $that; my $self = {@_}; bless( $self, $proto ); $self->{_agent} = LWP::UserAgent->new; $self->{_agent}->env_proxy; return $self; } sub set_auth { my ( $self, %auth ) = @_; $self->{auth} = \%auth; } sub _request { my ( $self, $method, $url, %params ) = @_; my $response; Rex::Logger::debug("Sending request to $url"); Rex::Logger::debug(" $_ => $params{$_}") for keys %params; { no strict 'refs'; $response = $self->{_agent}->request( $method->( $url, %params ) ); } Rex::Logger::debug( Dumper($response) ); if ( $response->is_error ) { Rex::Logger::info( 'Response indicates an error', 'warn' ); Rex::Logger::debug( $response->content ); } return decode_json( $response->content ) if $response->content; } sub _authenticate { my $self = shift; my $auth_data = { auth => { tenantName => $self->{auth}{tenant_name} || '', passwordCredentials => { username => $self->{auth}{username}, password => $self->{auth}{password}, } } }; my $content = $self->_request( POST => $self->{__endpoint} . '/tokens', content_type => 'application/json', content => encode_json($auth_data), ); $self->{auth}{tokenId} = $content->{access}{token}{id}; $self->{_agent}->default_header( 'X-Auth-Token' => $self->{auth}{tokenId} ); $self->{_catalog} = $content->{access}{serviceCatalog}; } sub get_nova_url { my $self = shift; $self->_authenticate unless $self->{auth}{tokenId}; my @nova_services = grep { $_->{type} eq 'compute' } @{ $self->{_catalog} }; return $nova_services[0]{endpoints}[0]{publicURL}; } sub get_cinder_url { my $self = shift; $self->_authenticate unless $self->{auth}{tokenId}; my @cinder_services = grep { $_->{type} eq 'volume' } @{ $self->{_catalog} }; return $cinder_services[0]{endpoints}[0]{publicURL}; } sub run_instance { my ( $self, %data ) = @_; my $nova_url = $self->get_nova_url; Rex::Logger::debug('Trying to start a new instance with data:'); Rex::Logger::debug(" $_ => $data{$_}") for keys %data; my $request_data = { server => { flavorRef => $data{plan_id}, imageRef => $data{image_id}, name => $data{name}, key_name => $data{key}, } }; my $content = $self->_request( POST => $nova_url . '/servers', content_type => 'application/json', content => encode_json($request_data), ); my $id = $content->{server}{id}; my $info; until ( ($info) = grep { $_->{id} eq $id } $self->list_running_instances ) { Rex::Logger::debug('Waiting for instance to be created...'); sleep 1; } if ( exists $data{volume} ) { $self->attach_volume( instance_id => $id, volume_id => $data{volume}, ); } if ( exists $data{floating_ip} ) { $self->associate_floating_ip( instance_id => $id, floating_ip => $data{floating_ip}, ); ($info) = grep { $_->{id} eq $id } $self->list_running_instances; } return $info; } sub terminate_instance { my ( $self, %data ) = @_; my $nova_url = $self->get_nova_url; Rex::Logger::debug("Terminating instance $data{instance_id}"); $self->_request( DELETE => $nova_url . '/servers/' . $data{instance_id} ); until ( !grep { $_->{id} eq $data{instance_id} } $self->list_running_instances ) { Rex::Logger::debug('Waiting for instance to be deleted...'); sleep 1; } } sub list_instances { my $self = shift; my %options = @_; $options{private_network} ||= "private"; $options{public_network} ||= "public"; $options{public_ip_type} ||= "floating"; $options{private_ip_type} ||= "fixed"; my $nova_url = $self->get_nova_url; my @instances; my $content = $self->_request( GET => $nova_url . '/servers/detail' ); for my $instance ( @{ $content->{servers} } ) { my %networks; for my $net ( keys %{ $instance->{addresses} } ) { for my $ip_conf ( @{ $instance->{addresses}->{$net} } ) { push @{ $networks{$net} }, { mac => $ip_conf->{'OS-EXT-IPS-MAC:mac_addr'}, ip => $ip_conf->{addr}, type => $ip_conf->{'OS-EXT-IPS:type'}, }; } } push @instances, { ip => ( [ map { $_->{"OS-EXT-IPS:type"} eq $options{public_ip_type} ? $_->{'addr'} : () } @{ $instance->{addresses}{ $options{public_network} } } ]->[0] || undef ), id => $instance->{id}, architecture => undef, type => $instance->{flavor}{id}, dns_name => undef, state => ( $instance->{status} eq 'ACTIVE' ? 'running' : 'stopped' ), __state => $instance->{status}, launch_time => $instance->{'OS-SRV-USG:launched_at'}, name => $instance->{name}, private_ip => ( [ map { $_->{"OS-EXT-IPS:type"} eq $options{private_ip_type} ? $_->{'addr'} : () } @{ $instance->{addresses}{ $options{private_network} } } ]->[0] || undef ), security_groups => ( join ',', map { $_->{name} } @{ $instance->{security_groups} } ), networks => \%networks, }; } return @instances; } sub list_running_instances { my $self = shift; return grep { $_->{state} eq 'running' } $self->list_instances; } sub stop_instance { my ( $self, %data ) = @_; my $nova_url = $self->get_nova_url; Rex::Logger::debug("Suspending instance $data{instance_id}"); $self->_request( POST => $nova_url . '/servers/' . $data{instance_id} . '/action', content_type => 'application/json', content => encode_json( { suspend => 'null' } ), ); while ( grep { $_->{id} eq $data{instance_id} } $self->list_running_instances ) { Rex::Logger::debug('Waiting for instance to be stopped...'); sleep 5; } } sub start_instance { my ( $self, %data ) = @_; my $nova_url = $self->get_nova_url; Rex::Logger::debug("Resuming instance $data{instance_id}"); $self->_request( POST => $nova_url . '/servers/' . $data{instance_id} . '/action', content_type => 'application/json', content => encode_json( { resume => 'null' } ), ); until ( grep { $_->{id} eq $data{instance_id} } $self->list_running_instances ) { Rex::Logger::debug('Waiting for instance to be started...'); sleep 5; } } sub list_flavors { my $self = shift; my $nova_url = $self->get_nova_url; Rex::Logger::debug('Listing flavors'); my $flavors = $self->_request( GET => $nova_url . '/flavors' ); confess "Error getting cloud flavors." if ( !exists $flavors->{flavors} ); return @{ $flavors->{flavors} }; } sub list_plans { return shift->list_flavors; } sub list_images { my $self = shift; my $nova_url = $self->get_nova_url; Rex::Logger::debug('Listing images'); my $images = $self->_request( GET => $nova_url . '/images' ); confess "Error getting cloud images." if ( !exists $images->{images} ); return @{ $images->{images} }; } sub create_volume { my ( $self, %data ) = @_; my $cinder_url = $self->get_cinder_url; Rex::Logger::debug('Creating a new volume'); my $request_data = { volume => { size => $data{size} || 1, availability_zone => $data{zone}, } }; my $content = $self->_request( POST => $cinder_url . '/volumes', content_type => 'application/json', content => encode_json($request_data), ); my $id = $content->{volume}{id}; until ( grep { $_->{id} eq $id and $_->{status} eq 'available' } $self->list_volumes ) { Rex::Logger::debug('Waiting for volume to become available...'); sleep 1; } return $id; } sub delete_volume { my ( $self, %data ) = @_; my $cinder_url = $self->get_cinder_url; Rex::Logger::debug('Trying to delete a volume'); $self->_request( DELETE => $cinder_url . '/volumes/' . $data{volume_id} ); until ( !grep { $_->{id} eq $data{volume_id} } $self->list_volumes ) { Rex::Logger::debug('Waiting for volume to be deleted...'); sleep 1; } } sub list_volumes { my $self = shift; my $cinder_url = $self->get_cinder_url; my @volumes; my $content = $self->_request( GET => $cinder_url . '/volumes' ); for my $volume ( @{ $content->{volumes} } ) { push @volumes, { id => $volume->{id}, status => $volume->{status}, zone => $volume->{availability_zone}, size => $volume->{size}, attached_to => join ',', map { $_->{server_id} } @{ $volume->{attachments} }, }; } return @volumes; } sub attach_volume { my ( $self, %data ) = @_; my $nova_url = $self->get_nova_url; Rex::Logger::debug('Trying to attach a new volume'); my $request_data = { volumeAttachment => { volumeId => $data{volume_id}, name => $data{name}, } }; $self->_request( POST => $nova_url . '/servers/' . $data{instance_id} . '/os-volume_attachments', content_type => 'application/json', content => encode_json($request_data), ); } sub detach_volume { my ( $self, %data ) = @_; my $nova_url = $self->get_nova_url; Rex::Logger::debug('Trying to detach a volume'); $self->_request( DELETE => $nova_url . '/servers/' . $data{instance_id} . '/os-volume_attachments/' . $data{volume_id} ); } sub get_floating_ip { my $self = shift; my $nova_url = $self->get_nova_url; # look for available floating IP my $floating_ips = $self->_request( GET => $nova_url . '/os-floating-ips' ); for my $floating_ip ( @{ $floating_ips->{floating_ips} } ) { return $floating_ip->{ip} if ( !$floating_ip->{instance_id} ); } confess "No floating IP available."; } sub associate_floating_ip { my ( $self, %data ) = @_; my $nova_url = $self->get_nova_url; # associate available floating IP to instance id my $request_data = { addFloatingIp => { address => $data{floating_ip} } }; Rex::Logger::debug('Associating floating IP to instance'); my $content = $self->_request( POST => $nova_url . '/servers/' . $data{instance_id} . '/action', content_type => 'application/json', content => encode_json($request_data), ); } sub list_keys { my $self = shift; my $nova_url = $self->get_nova_url; my $content = $self->_request( GET => $nova_url . '/os-keypairs' ); # remove ':' from fingerprint string foreach ( @{ $content->{keypairs} } ) { $_->{keypair}->{fingerprint} =~ s/://g; } return @{ $content->{keypairs} }; } sub upload_key { my ($self) = shift; my $nova_url = $self->get_nova_url; my $public_key = glob( Rex::Config->get_public_key ); my ( $public_key_name, undef, undef ) = fileparse( $public_key, qr/\.[^.]*/ ); my ( $type, $key, $comment ); # read public key my $fh; unless ( open( $fh, glob($public_key) ) ) { Rex::Logger::debug("Cannot read $public_key"); return undef; } { local $/ = undef; ( $type, $key, $comment ) = split( /\s+/, <$fh> ); } close $fh; # calculate key fingerprint so we can compare them my $fingerprint = md5_hex( decode_base64($key) ); Rex::Logger::debug("Public key fingerprint is $fingerprint"); # upoad only new key my $online_key = pop @{ [ map { $_->{keypair}->{fingerprint} eq $fingerprint ? $_ : () } $self->list_keys() ] }; if ($online_key) { Rex::Logger::debug("Public key already uploaded"); return $online_key->{keypair}->{name}; } my $request_data = { keypair => { public_key => "$type $key", name => $public_key_name, } }; Rex::Logger::info('Uploading public key'); $self->_request( POST => $nova_url . '/os-keypairs', content_type => 'application/json', content => encode_json($request_data), ); return $public_key_name; } 1;
gitpan/Rex
lib/Rex/Cloud/OpenStack.pm
Perl
apache-2.0
12,555
=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::Factory::Attrib; ### NAME: EnsEMBL::Web::Factory::Attrib ### Very simple factory to produce EnsEMBL::Web::Object::Attrib objects ### STATUS: Stable use strict; use warnings; use parent qw(EnsEMBL::Web::Factory); sub createObjects { my $self = shift; $self->DataObjects($self->new_object('Attrib', undef, $self->__data)); } 1;
muffato/public-plugins
admin/modules/EnsEMBL/Web/Factory/Attrib.pm
Perl
apache-2.0
1,070
=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 # Check if the allele registry API site is up or down; if down display down message in component, if up show widget package EnsEMBL::Web::Tools::FailOver::AlleleRegistry; use strict; use warnings; use EnsEMBL::Web::File::Utils::URL qw(file_exists); use base qw(EnsEMBL::Web::Tools::FailOver); sub new { my ($proto,$hub) = @_; my $self = $proto->SUPER::new("alleleregistry"); $self->{'hub'} = $hub; $self->{'check_url'} = $hub->get_ExtURL('ALLELE_REGISTRY'); # http://reg.test.genome.network return $self; } sub endpoints { return ['direct']; } sub fail_for { return 120; } # seconds after a failure to try checking again sub failure_dir { return $_[0]->{'hub'}->species_defs->ENSEMBL_FAILUREDIR; } sub min_initial_dead { return 5; } sub successful { return $_[1]; } sub attempt { my ($self,$endpoint,$payload,$tryhard) = @_; my $check_url = $self->{'check_url'}; return 0 unless defined $check_url; return file_exists($check_url); } 1;
Ensembl/ensembl-webcode
modules/EnsEMBL/Web/Tools/FailOver/AlleleRegistry.pm
Perl
apache-2.0
1,716
package Paws::EC2::ElasticGpuAssociation; use Moose; has ElasticGpuAssociationId => (is => 'ro', isa => 'Str', request_name => 'elasticGpuAssociationId', traits => ['NameInRequest']); has ElasticGpuAssociationState => (is => 'ro', isa => 'Str', request_name => 'elasticGpuAssociationState', traits => ['NameInRequest']); has ElasticGpuAssociationTime => (is => 'ro', isa => 'Str', request_name => 'elasticGpuAssociationTime', traits => ['NameInRequest']); has ElasticGpuId => (is => 'ro', isa => 'Str', request_name => 'elasticGpuId', traits => ['NameInRequest']); 1; ### main pod documentation begin ### =head1 NAME Paws::EC2::ElasticGpuAssociation =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::EC2::ElasticGpuAssociation object: $service_obj->Method(Att1 => { ElasticGpuAssociationId => $value, ..., ElasticGpuId => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::EC2::ElasticGpuAssociation object: $result = $service_obj->Method(...); $result->Att1->ElasticGpuAssociationId =head1 DESCRIPTION This class has no description =head1 ATTRIBUTES =head2 ElasticGpuAssociationId => Str The ID of the association. =head2 ElasticGpuAssociationState => Str The state of the association between the instance and the Elastic GPU. =head2 ElasticGpuAssociationTime => Str The time the Elastic GPU was associated with the instance. =head2 ElasticGpuId => Str The ID of the Elastic GPU. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::EC2> =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/EC2/ElasticGpuAssociation.pm
Perl
apache-2.0
2,067
package VMOMI::ArrayOfDVSVmVnicNetworkResourcePool; use parent 'VMOMI::ComplexType'; use strict; use warnings; our @class_ancestors = ( ); our @class_members = ( ['DVSVmVnicNetworkResourcePool', 'DVSVmVnicNetworkResourcePool', 1, 1], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/ArrayOfDVSVmVnicNetworkResourcePool.pm
Perl
apache-2.0
462
# 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::Common::IpBlockInfo; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = {ipAddress => $args->{ipAddress}}; # 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/Common/IpBlockInfo.pm
Perl
apache-2.0
1,017
package Paws::CloudDirectory::Facet; use Moose; has Name => (is => 'ro', isa => 'Str'); has ObjectType => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::Facet =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::CloudDirectory::Facet object: $service_obj->Method(Att1 => { Name => $value, ..., ObjectType => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CloudDirectory::Facet object: $result = $service_obj->Method(...); $result->Att1->Name =head1 DESCRIPTION A structure that contains C<Name>, C<ARN>, C<Attributes>, Rules, and C<ObjectTypes>. =head1 ATTRIBUTES =head2 Name => Str The name of the Facet. =head2 ObjectType => Str The object type that is associated with the facet. See CreateFacetRequest$ObjectType for more details. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CloudDirectory> =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/CloudDirectory/Facet.pm
Perl
apache-2.0
1,474
# 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::V8::Services::CampaignBudgetService; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseService); sub get { my $self = shift; my $request_body = shift; my $http_method = 'GET'; my $request_path = 'v8/{+resourceName}'; my $response_type = 'Google::Ads::GoogleAds::V8::Resources::CampaignBudget'; return $self->SUPER::call($http_method, $request_path, $request_body, $response_type); } sub mutate { my $self = shift; my $request_body = shift; my $http_method = 'POST'; my $request_path = 'v8/customers/{+customerId}/campaignBudgets:mutate'; my $response_type = 'Google::Ads::GoogleAds::V8::Services::CampaignBudgetService::MutateCampaignBudgetsResponse'; return $self->SUPER::call($http_method, $request_path, $request_body, $response_type); } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V8/Services/CampaignBudgetService.pm
Perl
apache-2.0
1,428
package VMOMI::DatacenterEvent; use parent 'VMOMI::Event'; use strict; use warnings; our @class_ancestors = ( 'Event', 'DynamicData', ); our @class_members = ( ); 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/DatacenterEvent.pm
Perl
apache-2.0
392
# # Copyright 2015 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::dell::idrac::snmp::mode::components::temperature; use strict; use warnings; my %map_temp_status = ( 1 => 'other', 2 => 'unknown', 3 => 'ok', 4 => 'nonCriticalUpper', 5 => 'criticalUpper', 6 => 'nonRecoverableUpper', 7 => 'nonCriticalLower', 8 => 'criticalLower', 9 => 'nonRecoverableLower', 10 => 'failed', ); my %map_temp_state = ( 1 => 'unknown', 2 => 'enabled', 4 => 'notReady', 6 => 'enabledAndNotReady', ); my %map_temp_type = ( 1 => 'temperatureProbeTypeIsOther', 2 => 'temperatureProbeTypeIsUnknown', 3 => 'temperatureProbeTypeIsAmbientESM', 16 => 'temperatureProbeTypeIsDiscrete', ); my $mapping = { temperatureProbeStateSettings => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.4', map => \%map_temp_state }, temperatureProbeStatus => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.5', map => \%map_temp_status }, temperatureProbeReading => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.6' }, temperatureProbeType => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.7', map => \%map_temp_type }, temperatureProbeLocationName => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.8' }, temperatureProbeUpperCriticalThreshold => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.10' }, temperatureProbeUpperNonCriticalThreshold => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.10' }, temperatureProbeLowerNonCriticalThreshold => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.11' }, temperatureProbeLowerCriticalThreshold => { oid => '.1.3.6.1.4.1.674.10892.5.4.700.20.1.12' }, }; my $oid_temperatureProbeTableEntry = '.1.3.6.1.4.1.674.10892.5.4.700.20.1'; sub load { my (%options) = @_; push @{$options{request}}, { oid => $oid_temperatureProbeTableEntry, begin => $mapping->{temperatureProbeStateSettings}->{oid}, end => $mapping->{temperatureProbeLowerCriticalThreshold}->{oid} }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking temperatures"); $self->{components}->{temperature} = {name => 'temperatures', total => 0, skip => 0}; return if ($self->check_exclude(section => 'temperature')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_temperatureProbeTableEntry}})) { next if ($oid !~ /^$mapping->{temperatureProbeStatus}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_temperatureProbeTableEntry}, instance => $instance); next if ($self->check_exclude(section => 'temperature', instance => $instance)); $self->{components}->{temperature}->{total}++; $result->{temperatureProbeReading} = (defined($result->{temperatureProbeReading})) ? $result->{temperatureProbeReading} / 10 : 'unknown'; $self->{output}->output_add(long_msg => sprintf("Temperature '%s' status is '%s' [instance = %s] [state = %s] [value = %s]", $result->{temperatureProbeLocationName}, $result->{temperatureProbeStatus}, $instance, $result->{temperatureProbeStateSettings}, $result->{temperatureProbeReading})); my $exit = $self->get_severity(section => 'temperature-state', value => $result->{temperatureProbeStateSettings}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Temperature '%s' state is '%s'", $result->{temperatureProbeLocationName}, $result->{temperatureProbeStateSettings})); next; } $exit = $self->get_severity(section => 'temperature-status', value => $result->{temperatureProbeStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Temperature '%s' status is '%s'", $result->{temperatureProbeLocationName}, $result->{temperatureProbeStatus})); } if (defined($result->{temperatureProbeReading}) && $result->{temperatureProbeReading} =~ /[0-9]/) { my ($exit, $warn, $crit, $checked) = $self->get_severity_numeric(section => 'temperature', instance => $instance, value => $result->{temperatureProbeReading}); if ($checked == 0) { my $warn_th = $result->{temperatureProbeLowerNonCriticalThreshold} . ':' . $result->{temperatureProbeUpperCriticalThreshold}; my $crit_th = $result->{temperatureProbeLowerCriticalThreshold} . ':' . $result->{temperatureProbeUpperCriticalThreshold}; $self->{perfdata}->threshold_validate(label => 'warning-temperature-instance-' . $instance, value => $warn_th); $self->{perfdata}->threshold_validate(label => 'critical-temperature-instance-' . $instance, value => $crit_th); $exit = $self->{perfdata}->threshold_check(value => $result->{temperatureProbeReading}, threshold => [ { label => 'critical-temperature-instance-' . $instance, exit_litteral => 'critical' }, { label => 'warning-temperature-instance-' . $instance, exit_litteral => 'warning' } ]); $warn = $self->{perfdata}->get_perfdata_for_output(label => 'warning-temperature-instance-' . $instance); $crit = $self->{perfdata}->get_perfdata_for_output(label => 'critical-temperature-instance-' . $instance) } if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Temperature '%s' is %s degree centigrade", $result->{temperatureProbeLocationName}, $result->{temperatureProbeReading})); } $self->{output}->perfdata_add(label => 'temp_' . $instance, unit => 'C', value => $result->{temperatureProbeReading}, warning => $warn, critical => $crit, ); } } } 1;
s-duret/centreon-plugins
hardware/server/dell/idrac/snmp/mode/components/temperature.pm
Perl
apache-2.0
7,233
## OpenXPKI::Service::Default.pm ## ## Written 2005-2006 by Michael Bell and Martin Bartosch for the OpenXPKI project ## Polished to use a state-machine like interface 2007 by Alexander Klink ## for the OpenXPKI project ## (C) Copyright 2005-2007 by The OpenXPKI Project package OpenXPKI::Service::Default; use base qw( OpenXPKI::Service ); use strict; use warnings; use utf8; use English; use List::Util qw( first ); use Class::Std; use Sys::SigAction qw( sig_alarm set_sig_handler ); use Data::Dumper; ## used modules use OpenXPKI::i18n qw(set_language); use OpenXPKI::Debug; use OpenXPKI::Exception; use OpenXPKI::Server; use OpenXPKI::Server::Session; use OpenXPKI::Server::Context qw( CTX ); use OpenXPKI::Service::Default::CommandApi2; use Log::Log4perl::MDC; my %state_of :ATTR; # the current state of the service my %max_execution_time : ATTR( :set<max_execution_time> ); sub init { my $self = shift; my $ident = ident $self; my $args = shift; ##! 1: "start" # timeout idle clients my $timeout = CTX('config')->get("system.server.service.Default.idle_timeout") || 120; $self->set_timeout($timeout); my $max_execution_time = CTX('config')->get("system.server.service.Default.max_execution_time") || 0; $self->set_max_execution_time($max_execution_time); $state_of{$ident} = 'NEW'; # in case we reuse a child in PreFork mode make sure there is # no session left in context OpenXPKI::Server::Context::killsession(); # TODO - this should be handled by the run method after some cleanup # do session init, PKI realm selection and authentication while ($state_of{$ident} ne 'MAIN_LOOP') { my $msg = $self->collect(); my $is_valid = $self->__is_valid_message({ MESSAGE => $msg, }); if (! $is_valid) { $self->__send_error({ ERROR => "I18N_OPENXPKI_SERVICE_DEFAULT_RUN_UNRECOGNIZED_SERVICE_MESSAGE", }); } else { # valid message received my $result; eval { # try to handle it $result = $self->__handle_message({ MESSAGE => $msg }); # persist session unless it was killed (we assume someone saved it before) CTX('session')->persist if OpenXPKI::Server::Context::hascontext('session'); }; if (my $exc = OpenXPKI::Exception->caught()) { $self->__send_error({ EXCEPTION => $exc }); } elsif ($EVAL_ERROR) { $self->__send_error({ EXCEPTION => $EVAL_ERROR }); } else { # if everything was fine, send the result to the client $self->talk($result); } } } return 1; } sub __is_valid_message : PRIVATE { my $self = shift; my $ident = ident $self; my $arg_ref = shift; my $message = $arg_ref->{'MESSAGE'}; my $message_name = $message->{'SERVICE_MSG'}; ##! 32: 'message_name: ' . $message_name ##! 32: 'state: ' . $state_of{$ident} # this is a table of valid messages that may be received from the # client in the different states my $valid_messages = { 'NEW' => [ 'PING', 'CONTINUE_SESSION', 'NEW_SESSION', 'DETACH_SESSION', 'GET_ENDPOINT_CONFIG', ], 'SESSION_ID_SENT' => [ 'PING', 'SESSION_ID_ACCEPTED', 'CONTINUE_SESSION', 'DETACH_SESSION', ], 'SESSION_ID_SENT_FROM_CONTINUE' => [ 'PING', 'SESSION_ID_ACCEPTED', 'CONTINUE_SESSION', 'DETACH_SESSION', ], 'SESSION_ID_SENT_FROM_RESET' => [ 'PING', 'SESSION_ID_ACCEPTED', 'CONTINUE_SESSION', 'DETACH_SESSION', ], 'WAITING_FOR_PKI_REALM' => [ 'PING', 'LOGOUT', 'GET_PKI_REALM', 'NEW_SESSION', 'CONTINUE_SESSION', 'DETACH_SESSION', ], 'WAITING_FOR_AUTHENTICATION_STACK' => [ 'PING', 'LOGOUT', 'GET_AUTHENTICATION_STACK', 'NEW_SESSION', 'CONTINUE_SESSION', 'DETACH_SESSION', ], 'WAITING_FOR_LOGIN' => [ 'PING', 'LOGOUT', 'GET_PASSWD_LOGIN', 'GET_CLIENT_LOGIN', 'GET_X509_LOGIN', 'NEW_SESSION', 'CONTINUE_SESSION', 'DETACH_SESSION', ], 'MAIN_LOOP' => [ 'PING', 'LOGOUT', 'STATUS', 'COMMAND', 'NEW_SESSION', 'CONTINUE_SESSION', 'DETACH_SESSION', 'RESET_SESSIONID', ], }; my @valid_msgs_now = @{ $valid_messages->{$state_of{$ident}} }; if (defined first { $_ eq $message_name } @valid_msgs_now) { # TODO - once could possibly check the content of the message # here, too ##! 16: 'message is valid' return 1; } CTX('log')->system()->warn('Invalid message '.$message_name.' received in state ' . $state_of{$ident}); ##! 16: 'message is NOT valid' return; } sub __handle_message : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $arg_ref = shift; my $message = $arg_ref->{'MESSAGE'}; my $message_name = $message->{'SERVICE_MSG'}; ##! 64: 'message: ' . Dumper $message my $result; # get the result from a method specific to the message name eval { my $method = '__handle_' . $message_name; CTX('log')->system->trace("<< $message_name (message from client)"); $result = $self->$method($message); }; if (my $exc = OpenXPKI::Exception->caught()) { $exc->rethrow(); } elsif ($EVAL_ERROR) { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_HANDLE_MESSAGE_FAILED', params => { 'MESSAGE_NAME' => $message_name, 'EVAL_ERROR' => $EVAL_ERROR, }, ); } return $result; } sub __handle_NEW_SESSION : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $msg = shift; Log::Log4perl::MDC->put('sid', undef); ##! 4: "new session" my $session = OpenXPKI::Server::Session->new(load_config => 1)->create; if (exists $msg->{LANGUAGE}) { ##! 8: "set language" set_language($msg->{LANGUAGE}); $session->data->language($msg->{LANGUAGE}); } else { ##! 8: "no language specified" } OpenXPKI::Server::Context::setcontext({'session' => $session, force => 1}); Log::Log4perl::MDC->put('sid', substr($session->data->id,0,4)); CTX('log')->system->info('New session created'); $self->__change_state({ STATE => 'SESSION_ID_SENT', }); return { SESSION_ID => $session->data->id, }; } sub __handle_CONTINUE_SESSION { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $msg = shift; my $session; # for whatever reason prior to the Client rewrite continue_session # has the session id not in params my $sess_id = exists $msg->{SESSION_ID} ? $msg->{SESSION_ID} : $msg->{PARAMS}->{SESSION_ID}; ##! 4: "try to continue session " . $sess_id $session = OpenXPKI::Server::Session->new(load_config => 1); $session->resume($sess_id) or OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_HANDLE_CONTINUE_SESSION_SESSION_CONTINUE_FAILED', params => {ID => $sess_id} ); # There might be an exisiting session if the child did some work before # we therefore use force to overwrite exisiting entries OpenXPKI::Server::Context::setcontext({'session' => $session, force => 1}); Log::Log4perl::MDC->put('sid', substr($sess_id,0,4)); CTX('log')->system->debug('Session resumed'); # do not use __change_state here, as we want to have access # to the old session in __handle_SESSION_ID_ACCEPTED $state_of{$ident} = 'SESSION_ID_SENT_FROM_CONTINUE'; return { SESSION_ID => $session->data->id, }; } sub __handle_RESET_SESSIONID: PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $msg = shift; my $sess_id = CTX('session')->new_id; CTX('log')->system->debug("Changing session ID to ".substr($sess_id,0,4)); Log::Log4perl::MDC->put('sid', substr($sess_id,0,4)); ##! 4: 'new session id ' . $sess_id $self->__change_state({ STATE => 'SESSION_ID_SENT_FROM_RESET', }); return { SESSION_ID => $sess_id, }; } sub __handle_DETACH_SESSION: PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $msg = shift; my $sessid = CTX('session')->data->id; ##! 4: "detach session " . $sessid OpenXPKI::Server::Context::killsession(); # Cleanup ALL items from the MDC! Log::Log4perl::MDC->remove(); $self->__change_state({ STATE => 'NEW' }); return { 'SERVICE_MSG' => 'DETACH' }; } sub __handle_PING : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $message = shift; if ($state_of{$ident} eq 'MAIN_LOOP') { return { SERVICE_MSG => 'SERVICE_READY', }; } elsif ($state_of{$ident} eq 'WAITING_FOR_PKI_REALM') { my @realm_names = CTX('config')->get_keys("system.realms"); my %realms =(); foreach my $realm (sort @realm_names) { my $label = CTX('config')->get("system.realms.$realm.label"); $realms{$realm}->{NAME} = $realm; $realms{$realm}->{LABEL} = $label; $realms{$realm}->{DESCRIPTION} = CTX('config')->get("system.realms.$realm.description") || $label; } return { SERVICE_MSG => 'GET_PKI_REALM', PARAMS => { 'PKI_REALMS' => \%realms, }, }; } elsif ($state_of{$ident} eq 'WAITING_FOR_AUTHENTICATION_STACK') { return $self->__list_authentication_stacks(); } elsif ($state_of{$ident} eq 'WAITING_FOR_LOGIN') { ##! 16: 'we are in state WAITING_FOR_LOGIN' ##! 16: 'auth stack: ' . CTX('session')->data->authentication_stack ##! 16: 'pki realm: ' . CTX('session')->data->pki_realm return $self->__handle_login( $message ); } return { SERVICE_MSG => 'START_SESSION' }; } sub __handle_SESSION_ID_ACCEPTED : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $message = shift; if ($state_of{$ident} eq 'SESSION_ID_SENT_FROM_RESET') { ##! 4: 'existing session detected' my $session = CTX('session'); ##! 8: 'Session ' . Dumper $session $self->__change_state({ STATE => 'MAIN_LOOP', }); } if ($state_of{$ident} eq 'SESSION_ID_SENT_FROM_CONTINUE') { ##! 4: 'existing session detected' my $session = CTX('session'); ##! 8: 'Session ' . Dumper $session $self->__change_state({ STATE => CTX('session')->data->status, }); } ##! 16: 'state: ' . $state_of{$ident} my $pki_realm_choice = $self->__pki_realm_choice_available(); ##! 16: 'pki_realm_choice: ' . $pki_realm_choice # if there is more than one PKI realm, send an appropriate # message for the user and set the state to # 'WAITING_FOR_PKI_REALM' # we only do this if we are in a 'SESSION_ID_SENT.*' state if ($pki_realm_choice && $state_of{$ident} =~ m{\A SESSION_ID_SENT.* \z}xms) { ##! 2: "build hash with ID, name and description" my @realm_names = CTX('config')->get_keys("system.realms"); my %realms =(); foreach my $realm (sort @realm_names) { $realms{$realm}->{NAME} = $realm; $realms{$realm}->{DESCRIPTION} = CTX('config')->get("system.realms.$realm.label"); } $self->__change_state({ STATE => 'WAITING_FOR_PKI_REALM', }); return { SERVICE_MSG => 'GET_PKI_REALM', PARAMS => { 'PKI_REALMS' => \%realms, }, }; } # if we do not have an authentication stack in the session, # send all available stacks to the user and set the state to # 'WAITING_FOR_AUTHENTICATION_STACK' if ($state_of{$ident} =~ m{\A SESSION_ID_SENT.* \z}xms && (! defined CTX('session')->data->authentication_stack) ) { ##! 4: 'sending authentication stacks' $self->__change_state({ STATE => 'WAITING_FOR_AUTHENTICATION_STACK', }); return $self->__list_authentication_stacks(); } if ($state_of{$ident} eq 'WAITING_FOR_AUTHENTICATION_STACK') { return $self->__list_authentication_stacks(); } if ($state_of{$ident} eq 'WAITING_FOR_LOGIN') { ##! 16: 'we are in state WAITING_FOR_LOGIN' ##! 16: 'auth stack: ' . CTX('session')->data->authentication_stack ##! 16: 'pki realm: ' . CTX('session')->data->pki_realm return $self->__handle_login( $message ); } if ($state_of{$ident} eq 'MAIN_LOOP') { return { SERVICE_MSG => 'SERVICE_READY', }; } ##! 16: 'end' return; } sub __handle_GET_PKI_REALM : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $message = shift; my $requested_realm = $message->{PARAMS}->{'PKI_REALM'}; if ($self->__is_valid_pki_realm($requested_realm)) { ##! 2: "update session with PKI realm" CTX('session')->data->pki_realm($requested_realm); Log::Log4perl::MDC->put('pki_realm', $requested_realm); } else { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_GET_PKI_REALM_INVALID_PKI_REALM_REQUESTED', ); } if (! defined CTX('session')->data->authentication_stack ) { $self->__change_state({ STATE => 'WAITING_FOR_AUTHENTICATION_STACK', }); # proceed if stack is already set if (defined $message->{PARAMS}->{'AUTHENTICATION_STACK'}) { delete $message->{PARAMS}->{'PKI_REALM'}; return $self->__handle_GET_AUTHENTICATION_STACK($message); } return $self->__list_authentication_stacks(); } # check for next step, change state and prepare response return; } sub __handle_GET_AUTHENTICATION_STACK : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $message = shift; my $requested_stack = $message->{PARAMS}->{'AUTHENTICATION_STACK'}; if (! $self->__is_valid_auth_stack($requested_stack)) { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_GET_AUTHENTICATION_STACK_INVALID_AUTH_STACK_REQUESTED', ); } else { # valid authentication stack $self->__change_state({ STATE => 'WAITING_FOR_LOGIN', }); CTX('session')->data->authentication_stack($requested_stack); # set session and forward state on success, returns reply delete $message->{PARAMS}->{'AUTHENTICATION_STACK'}; return $self->__handle_login( $message ); } return; } sub __handle_GET_PASSWD_LOGIN : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; return $self->__handle_login( shift ); } sub __handle_GET_CLIENT_LOGIN : PRIVATE { ##! 1: 'start' my $self = shift; return $self->__handle_login( shift ); } sub __handle_GET_X509_LOGIN : PRIVATE { ##! 1: 'start' my $self = shift; return $self->__handle_login( shift ); } sub __handle_LOGOUT : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $message = shift; my $old_session = CTX('session'); ##! 8: "logout received - terminate session " . $old_session->id, CTX('log')->system->debug('Terminating session ' . $old_session->id); $self->__change_state({ STATE => 'NEW' }); OpenXPKI::Server::Context::killsession(); Log::Log4perl::MDC->remove(); if (!$old_session->delete()) { CTX('log')->system->warn('Error terminating session!'); } return { 'SERVICE_MSG' => 'LOGOUT' }; } sub __handle_STATUS : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $message = shift; # closure to access session parameters or return undef if CTX('session') is not defined my $session_param = sub { my $param = shift; return CTX('session')->data->$param if OpenXPKI::Server::Context::hascontext('session'); return undef; }; # SERVICE_MSG ? return { SESSION => { ROLE => $session_param->("role"), USER => $session_param->("user"), }, }; } sub __handle_GET_ENDPOINT_CONFIG : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $msg = shift; my $interface = $msg->{PARAMS}->{interface}; my $endpoint = $msg->{PARAMS}->{endpoint}; my $res; ##! 64: Dumper $msg->{PARAMS} if (!$interface) { # nothing given. list configured interfaces/services $res = { INTERFACE => [ CTX('config')->get_keys(['endpoint']) ] }; } elsif (!$endpoint) { # default config plus names of all endpoints for given interface $res = { CONFIG => CTX('config')->get_hash(['endpoint', $interface, 'default' ]), ENDPOINT => [ CTX('config')->get_keys(['endpoint', $interface ]) ], }; } else { # endpoint configuration $res = { CONFIG => CTX('config')->get_hash(['endpoint', $interface, $endpoint ]) } } ##! 128: $res return { PARAMS => $res }; } sub __handle_COMMAND : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $data = shift; OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_COMMAND_MISSING', ) unless exists $data->{PARAMS}->{COMMAND}; ##! 16: "executing access control before doing anything else" #eval { # FIXME - ACL #CTX('acl')->authorize ({ # ACTIVITY => "Service::".$data->{PARAMS}->{COMMAND}, # AFFECTED_ROLE => "", #}); #}; ##! 32: 'Callstack ' . Dumper $data if (0 || $EVAL_ERROR) { ##! 1: "Permission denied for Service::".$data->{PARAMS}->{COMMAND}."." if (my $exc = OpenXPKI::Exception->caught()) { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_PERMISSION_DENIED', params => { EXCEPTION => $exc, }, ); } else { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_PERMISSION_DENIED', params => { ERROR => $EVAL_ERROR, }, ); } return; } ##! 16: "access to command granted" my $command; my $api = $data->{PARAMS}->{API} || 2; if ($api !~ /^2$/) { OpenXPKI::Exception->throw ( message => "I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_UNKNWON_COMMAND_API_VERSION", params => $data->{PARAMS}, ); } eval { $command = OpenXPKI::Service::Default::CommandApi2->new( command => $data->{PARAMS}->{COMMAND}, params => $data->{PARAMS}->{PARAMS}, ); }; if (my $exc = OpenXPKI::Exception->caught()) { if ($exc->message() =~ m{ I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_INVALID_COMMAND }xms) { ##! 16: "Invalid command $data->{PARAMS}->{COMMAND}" # fall-through intended } else { $exc->rethrow(); } } elsif ($EVAL_ERROR) { OpenXPKI::Exception->throw ( message => "I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_COULD_NOT_INSTANTIATE_COMMAND", params => { EVAL_ERROR => $EVAL_ERROR }, ); } return unless defined $command; ##! 16: 'command class instantiated successfully' my $result; eval { CTX('log')->system->debug("Executing command ".$data->{PARAMS}->{COMMAND}); my $sh; if ($max_execution_time{$ident}) { $sh = set_sig_handler( 'ALRM' ,sub { CTX('log')->system->error("Service command ".$data->{PARAMS}->{COMMAND}." was aborted after " . $max_execution_time{$ident}); CTX('log')->system->trace("Call was " . Dumper $data->{PARAMS} ); OpenXPKI::Exception->throw( message => "Server took too long to respond to your request - aborted!", params => { COMMAND => $data->{PARAMS}->{COMMAND} } ); }); sig_alarm( $max_execution_time{$ident} ); } # enclose command with DBI transaction CTX('dbi')->start_txn(); $result = $command->execute(); CTX('dbi')->commit(); if ($sh) { sig_alarm(0); } }; if (my $error = $EVAL_ERROR) { # rollback DBI (should not matter as we throw exception anyway) CTX('dbi')->rollback(); # just rethrow if we have an exception if (my $exc = OpenXPKI::Exception->caught()) { ##! 16: 'exception caught during execute' $exc->rethrow(); } ##! 16: "Exception caught during command execution" OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_EXECUTION_ERROR', params => { ERROR => $error }, ); } ##! 16: 'command executed successfully' # sanity checks on command reply if (! defined $result || ref $result ne 'HASH') { OpenXPKI::Exception->throw( message => 'I18N_OPENXPKI_SERVICE_DEFAULT_COMMAND_ILLEGAL_COMMAND_RETURN_VALUE', ); return; } ##! 16: 'returning result' return $result; } sub __pki_realm_choice_available : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; ##! 2: "check if PKI realm is already known" my $realm = OpenXPKI::Server::Context::hascontext('session') ? CTX('session')->data->pki_realm : undef; return $realm if defined $realm; ##! 2: "check if there is more than one realm" my @list = CTX('config')->get_keys('system.realms'); if (scalar @list < 1) { ##! 4: "no PKI realm configured" OpenXPKI::Exception->throw( message => "I18N_OPENXPKI_SERVICE_DEFAULT_NO_PKI_REALM_CONFIGURED", ); } elsif (scalar @list == 1) { ##! 4: "update session with PKI realm" ##! 16: 'PKI realm: ' . $list[0] CTX('session')->data->pki_realm($list[0]); return 0; } else { # more than one PKI realm available return 1; } return 0; } sub __list_authentication_stacks : PRIVATE { my $self = shift; my $authentication = CTX('authentication'); return { SERVICE_MSG => 'GET_AUTHENTICATION_STACK', PARAMS => { 'AUTHENTICATION_STACKS' => $authentication->list_authentication_stacks(), }, }; } sub __is_valid_auth_stack : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $stack = shift; my $stacks = CTX('authentication')->list_authentication_stacks(); return exists $stacks->{$stack}; } sub __is_valid_pki_realm : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $realm = shift; return CTX('config')->exists("system.realms.$realm"); } sub __change_state : PRIVATE { ##! 1: 'start' my $self = shift; my $ident = ident $self; my $arg_ref = shift; my $new_state = $arg_ref->{STATE}; ##! 4: 'changing state from ' . $state_of{$ident} . ' to ' . $new_state CTX('log')->system()->debug('Changing session state from ' . $state_of{$ident} . ' to ' . $new_state); $state_of{$ident} = $new_state; # save the new state in the session if (OpenXPKI::Server::Context::hascontext('session')) { CTX('session')->data->status($new_state); } # Set the daemon name after enterin MAIN_LOOP if ($new_state eq "MAIN_LOOP") { OpenXPKI::Server::__set_process_name("worker: %s (%s)", CTX('session')->data->user, CTX('session')->data->role); } elsif ($new_state eq "NEW") { OpenXPKI::Server::__set_process_name("worker: connected"); } return 1; } sub __handle_login { my $self = shift; my $ident = ident $self; my $message = shift; my $auth_reply = CTX('authentication')->login_step({ STACK => CTX('session')->data->authentication_stack, MESSAGE => $message, }); # returns an instance of OpenXPKI::Server::Authentication::Handle # if the login was successful, auth failure throws an exception if (ref $auth_reply eq 'OpenXPKI::Server::Authentication::Handle') { ##! 4: 'login successful' ##! 16: 'user: ' . $auth_reply->userid ##! 16: 'role: ' . $auth_reply->role ##! 32: $auth_reply CTX('log')->system->debug("Successful login from user ". $auth_reply->userid .", role ". $auth_reply->role); # successful login, save it in the session and mark session as valid CTX('session')->data->user( $auth_reply->userid ); CTX('session')->data->role( $auth_reply->role ); if ($auth_reply->has_tenants) { CTX('session')->data->tenants( $auth_reply->tenants ); } else { CTX('session')->data->clear_tenants(); } CTX('session')->data->userinfo( $auth_reply->userinfo // {} ); CTX('session')->data->authinfo( $auth_reply->authinfo // {} ); CTX('session')->is_valid(1); Log::Log4perl::MDC->put('user', $auth_reply->userid ); Log::Log4perl::MDC->put('role', $auth_reply->role ); $self->__change_state({ STATE => 'MAIN_LOOP', }); return { SERVICE_MSG => 'SERVICE_READY' }; } # returns a hash with information for the login stack if # no or insufficient auth data was passed return { SERVICE_MSG => 'GET_'.uc($auth_reply->{type}).'_LOGIN', PARAMS => $auth_reply->{params}, ($auth_reply->{sign} ? (SIGN => $auth_reply->{sign}) : ()), }; } sub run { my $self = shift; my $ident = ident $self; my $args = shift; $SIG{'TERM'} = \&OpenXPKI::Server::sig_term; $SIG{'HUP'} = \&OpenXPKI::Server::sig_hup; MESSAGE: while (1) { my $msg; eval { $msg = $self->collect(); }; if (my $exc = OpenXPKI::Exception->caught()) { if ($exc->message() =~ m{I18N_OPENXPKI_TRANSPORT.*CLOSED_CONNECTION}xms) { # client closed socket last MESSAGE; } else { $exc->rethrow(); } } elsif ($EVAL_ERROR) { OpenXPKI::Exception->throw ( message => "I18N_OPENXPKI_SERVICE_DEFAULT_RUN_READ_EXCEPTION", params => { EVAL_ERROR => $EVAL_ERROR, }); } last MESSAGE unless defined $msg; my $is_valid = $self->__is_valid_message({ MESSAGE => $msg }); if (! $is_valid) { CTX('log')->system->debug("Invalid message received from client: ".($msg->{SERVICE_MSG} // "(empty)")); $self->__send_error({ ERROR => "I18N_OPENXPKI_SERVICE_DEFAULT_RUN_UNRECOGNIZED_SERVICE_MESSAGE", }); } else { # valid message received my $result; # we dont need a valid session when we are not in main loop state if ($state_of{$ident} eq 'MAIN_LOOP' && ! CTX('session')->is_valid) { # check whether we still have a valid session (someone # might have logged out on a different forked server) CTX('log')->system->debug("Can't process client message: session is not valid (login incomplete)"); $self->__send_error({ ERROR => 'I18N_OPENXPKI_SERVICE_DEFAULT_RUN_SESSION_INVALID', }); } else { # our session is just fine eval { # try to handle it $result = $self->__handle_message({ MESSAGE => $msg }); # persist session unless it was killed (we assume someone saved it before) CTX('session')->persist if OpenXPKI::Server::Context::hascontext('session'); }; if (my $exc = OpenXPKI::Exception->caught()) { $self->__send_error({ EXCEPTION => $exc, }); } elsif ($EVAL_ERROR) { $self->__send_error({ EXCEPTION => $EVAL_ERROR, }); } else { # if everything was fine, send the result to the client $self->talk($result); } } } } return 1; } ################################## ## begin error handling ## ################################## sub __send_error { my $self = shift; my $params = shift; ##! 1: 'handle error' ##! 64: $params my $error; if ($params->{ERROR}) { $error = { LABEL => $params->{ERROR} }; } elsif (ref $params->{EXCEPTION} eq '') { # got exception with already stringified error $error = { LABEL => $params->{EXCEPTION} }; } else { my $class = ref $params->{EXCEPTION}; # blessed exception object - there are some bubble ups where message # is an exception again => enforce stringification on message $error = { LABEL => "".$params->{EXCEPTION}->message(), }; # get all scalar/hash/array parameters from OXI::Exceptions # this is used to transport some extra infos for validators, etc if ($class->isa('OpenXPKI::Exception')) { $error->{CLASS} = $class; if (defined $params->{EXCEPTION}->params) { my $p = $params->{EXCEPTION}->params; map { my $key = $_; my $val = $p->{$_}; my $ref = ref $val; delete $p->{$_} unless(defined $val && $ref =~ /^(|HASH|ARRAY)$/); } keys %{$p}; if($p) { $error->{PARAMS} = $p; } } if ($class eq 'OpenXPKI::Exception::InputValidator') { $error->{ERRORS} = $params->{EXCEPTION}->{errors}; } } } CTX('log')->system->debug('Sending error ' . Dumper $error); return $self->talk({ SERVICE_MSG => "ERROR", ERROR => $error, }); } ################################ ## end error handling ## ################################ 1; __END__ =head1 Name OpenXPKI::Service::Default - basic service implementation =head1 Description This is the common Service implementation to be used by most interactive clients. It supports PKI realm selection, user authentication and session handling. =head1 Protocol Definition =head2 Connection startup You can send two messages at the beginning of a connection. You can ask to continue an old session or you start a new session. The answer is always the same - the session ID or an error message. =head3 Session init --> {SERVICE_MSG => "NEW_SESSION", LANGUAGE => $lang} <-- {SESSION_ID => $ID} --> {SERVICE_MSG => "SESSION_ID_ACCEPTED"} <-- {SERVICE_MSG => "GET_PKI_REALM", PARAMS => { PKI_REALM => { "0" => { NAME => "Root Realm", DESCRIPTION => "This is an example root realm." } } } } } --> {SERVICE_MSG => "GET_PKI_REALM", PARAMS => { PKI_REALM => $realm, } } <-- {SERVICE_MSG => "GET_AUTHENTICATION_STACK", PARAMS => { AUTHENTICATION_STACKS => { "0" => { NAME => "Basic Root Auth Stack", DESCRIPTION => "This is the basic root authentication stack." } } } } --> {SERVICE_MSG => "GET_AUTHENTICATION_STACK", PARAMS => { AUTHENTICATION_STACK => "0" } } Example 1: Anonymous Login <-- {SERVICE_MSG => "SERVICE_READY"} Answer is the first command. Example 2: Password Login <-- {SERVICE_MSG => "GET_PASSWD_LOGIN", PARAMS => { NAME => "XYZ", DESCRIPTION => "bla bla ..." } } --> {LOGIN => "John Doe", PASSWD => "12345678"} on success ... <-- {SERVICE_MSG => "SERVICE_READY"} on failure ... <-- {ERROR => "some already translated message"} =head3 Session continue --> {SERVICE_MSG => "CONTINUE_SESSION", SESSION_ID => $ID} <-- {SESSION_ID => $ID} --> {SERVICE_MSG => "SESSION_ID_ACCEPTED} <-- {SERVICE_MSG => "SERVICE_READY"} =head1 Functions The functions does nothing else than to support the test stuff with a working user interface dummy. =over =item * START =item * init Receives messages, checks them for validity in the given state and passes them of to __handle_message if they are valid. Runs until it reaches the state 'MAIN_LOOP', which means that session initialization, PKI realm selection and login are done. =item * run Receives messages, checks them for validity in the given state (MAIN_LOOP) and passes them to __handle_message if they are valid. Runs until a LOGOUT command is received. =item * __is_valid_message Checks whether a given message is a valid message in the current state. Currently, this checks the message name ('SERVICE_MSG') only, could be used to validate the input as well later. =item * __handle_message Handles a message by passing it off to a handler named using the service message name. =item * __handle_NEW_SESSION Handles the NEW_SESSION message by creating a new session, saving it in the context and sending back the session ID. Changes the state to 'SESSION_ID_ACCEPTED' =item * __handle_CONTINUE_SESSION Handles the CONTINUE_SESSION message. =item * __handle_PING Handles the PING message by sending back an empty response. =item * __handle_SESSION_ID_ACCEPTED Handles the 'SESSION_ID_ACCEPTED' message. It looks whether there are multiple PKI realms defined. If so, it sends back the list and changes to state 'WAITING_FOR_PKI_REALM'. If not, it looks whether an authentication stack is present. If not, it sends the list of possible stacks and changes the state to 'WAITING_FOR_AUTHENTICATION_STACK'. =item * __handle_GET_PKI_REALM Handles the GET_PKI_REALM message by checking whether the received realm is valid and setting it in the context if so. =item * __handle_GET_AUTHENTICATION_STACK Handles the GET_AUTHENTICATION_STACK message by checking whether the received stack is valid and setting the corresponding attribute if it is =item * __handle_GET_PASSWD_LOGIN Handles the GET_PASSWD_LOGIN message by passing on the credentials to the Authentication modules 'login_step' method. =item * __handle_DETACH Removes the current session from this worker but does not delete the session. The worker is now free to handle requests for other sessions. =item * __handle_LOGOUT Handles the LOGOUT message by deleting the session from the backend. =item * __handle_STATUS Handles the STATUS message by sending back role and user information. =item * __handle_COMMAND Handles the COMMAND message by calling the corresponding command if the user is authorized. =item * __pki_realm_choice_available Checks whether more than one PKI realm is configured. =item * __list_authentication_stacks Returns a list of configured authentication stacks. =item * __is_valid_auth_stack Checks whether a given stack is a valid one. =item * __is_valid_pki_realm Checks whether a given realm is a valid one. =item * __change_state Changes the internal state. =item * __send_error Sends an error message to the user. =back
openxpki/openxpki
core/server/OpenXPKI/Service/Default.pm
Perl
apache-2.0
36,613
/* Copyright (C)1990-2002 UPM-CLIP */ %---------------------------------------------------------------------------- % Support for misc CIAO functionality in std Prolog systems (e.g., SICStus). %---------------------------------------------------------------------------- %---------------------------------------------------------------------------- % Syntax support for CIAO's operators %---------------------------------------------------------------------------- :- op(1190,fx,[(typedef),(type)]). :- op(1180,xfx,[(::=)]). :- op(1150,fx,[(data)]). :- op(950,xfy,[(&)]). :- op(950,xfy,[(\&)]). :- op(950,xf,[(&)]). :- op(1000,xfy,[(&&)]). %---------------------------------------------------------------------------- % Needed locally. %---------------------------------------------------------------------------- local_append([],Ys,Ys). local_append([E|Xs],Ys,[E|Zs]):- local_append(Xs,Ys,Zs). ccomp(M,Args) :- local_append("[CIAO-SICSTUS compatibility: ",M,T1), local_append(T1,"]~n",F), format(user_error,F,Args). %---------------------------------------------------------------------------- % Set paths for sub-libraries %---------------------------------------------------------------------------- add_ciao_lib_dir(DS,SL) :- local_append(DS,SL,NDS), name(ND,NDS), asserta(user:library_directory(ND)). :- ciao_library_directory(D), % last in sicstus lib name(D,DS), add_ciao_lib_dir(DS,"/contrib"), add_ciao_lib_dir(DS,"/library"), add_ciao_lib_dir(DS,"/lib"), add_ciao_lib_dir(DS,""), % second in ciao libs compat_library_directory(DC), name(DC,DCS), add_ciao_lib_dir(DCS,""). % first look in compat :- multifile file_search_path/2. :- dynamic file_search_path/2. % file_search_path(engine,E) :- comp_engine_directory(E). file_search_path(engine,E) :- library_directory(E). %---------------------------------------------------------------------------- % Emulate CIAO's directives %---------------------------------------------------------------------------- :- dynamic term_expansion/2. term_expansion(( :- add_sentence_trans(F/2) ), ( :- Expansion=..[F,A,B], assertz( (term_expansion(A,B):-Expansion) ) )). term_expansion(( :- meta_predicate(error_protect(goal)) ), ( :- meta_predicate(error_protect(:)) )). term_expansion(( :- meta_predicate(ctrlc_clean(goal)) ), ( :- meta_predicate(ctrlc_clean(:)) )). term_expansion(( :- meta_predicate(trace(goal)) ), ( :- meta_predicate(trace(:)) )). /* Does not work term_expansion(( :- meta_predicate(Spec0) ), ( :- ( user:translate_meta_spec(Spec0,Spec1), meta_predicate(Spec1) ) )). */ term_expansion(( :- new_declaration(D,_) ), ( :- ( D=F/N, functor(Skel,F,N), %% user:ccomp("Asserting ~w",[Skel]), assert(Skel) ))). term_expansion(( :- new_declaration(D) ), ( :- ( D=F/N, functor(Skel,F,N), %% user:ccomp("Asserting ~w",[Skel]), assert(Skel) ))). translate_meta_spec((Spec0,Specs0),(Spec1,Specs1)):- !, translate_meta_spec(Spec0,Spec1), translate_meta_spec(Specs0,Specs1). translate_meta_spec(Spec0,Spec1):- Spec0=..[F|Args0], translate_meta_args(Args0,Args1), Spec1=..[F|Args1], ccomp("Translated meta-predicate: ~w",[Spec1]). translate_meta_args([Arg0|Args0],[Arg1|Args1]):- translate_meta_arg(Arg0,Arg1), translate_meta_args(Args0,Args1). translate_meta_args([],[]). translate_meta_arg(goal,(:)):- !. translate_meta_arg(A,A). %---------------------------------------------------------------------------- % Emulate CIAO's additional module/file primitives %---------------------------------------------------------------------------- term_expansion( ( :- module(M,E,S) ), ( [(:- module(M,E)), (:- user:add_builtin_library(M)), (:- user:load_syntax_modules(S,M)) ] )). term_expansion( ( :- module(M,E) ), ( [(:- module(M,E)), (:- user:add_builtin_library(M)) ] )). add_builtin_library(builtin):- !. add_builtin_library(M):- compile(M:library(builtin)). %% Adds library( ) wrapper load_syntax_modules([],_CM) :- !. load_syntax_modules([M|Ms],CM) :- !, load_syntax_module(M,CM), load_syntax_modules(Ms,CM). load_syntax_modules(M,CM) :- !, load_syntax_module(M,CM). load_syntax_module(M,CM) :- user:ccomp("Loading ciao syntax module ~w into ~w",[M,CM]), compile(CM:library(M)). term_expansion(( :- data(X) ), ( [(:- user:ccomp("Defining data as dynamic: ~w",[X])), (:- dynamic(X)) ] )). term_expansion(( :- syntax(M) ), ( :- user:load_syntax_modules(M,user) )). term_expansion(( :- include(X) ), ( :- ( user:ccomp("Loading included file(s) ~w",[X]), compile(X)) )). term_expansion(( :- load_compilation_module(File) ), ( :- translation:use_module(File) )). %---------------------------------------------------------------------------- % ISO compliance %---------------------------------------------------------------------------- term_expansion(( :- initialization(Goal) ), ( :- ( user:ccomp("Executing initialization goal ~q",[Goal]), Goal ) )). %---------------------------------------------------------------------------- % CIAO's peculiarities %---------------------------------------------------------------------------- % For some strange reason SICStus refuses to load write.pl into c_itf % but it does it for metaterms ????? % goal_expansion(write_term(T,L), c_itf, ciao_write_term(T,L)). goal_expansion(write_term(T,L), c_itf, metaterms:ciao_write_term(T,L)). goal_expansion(this_module(M), c_itf, M = c_itf). %---------------------------------------------------------------------------- % CIAO's 'make' %---------------------------------------------------------------------------- make_exec(List,System):- %% compile(List), consult(List), save(System), start_program. start_program :- main, halt. start_program :- format(user_error,"[Program ended with failure]~n",[]), halt. makeql(X):- fcompile(X). %---------------------------------------------------------------------------- % Finally, load the compatibility with the basic builtins %---------------------------------------------------------------------------- :- use_module(builtin).
leuschel/ecce
www/CiaoDE/ciao/compatibility/sicstus3/user.pl
Perl
apache-2.0
6,305
package Paws::ServiceCatalog::Tag; use Moose; has Key => (is => 'ro', isa => 'Str', required => 1); has Value => (is => 'ro', isa => 'Str', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::ServiceCatalog::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::ServiceCatalog::Tag object: $service_obj->Method(Att1 => { Key => $value, ..., Value => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::ServiceCatalog::Tag object: $result = $service_obj->Method(...); $result->Att1->Key =head1 DESCRIPTION Key-value pairs to associate with this provisioning. These tags are entirely discretionary and are propagated to the resources created in the provisioning. =head1 ATTRIBUTES =head2 B<REQUIRED> Key => Str The C<ProvisioningArtifactParameter.TagKey> parameter from DescribeProvisioningParameters. =head2 B<REQUIRED> Value => Str The desired value for this key. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::ServiceCatalog> =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/ServiceCatalog/Tag.pm
Perl
apache-2.0
1,569
package Paws::Greengrass::ListSubscriptionDefinitionVersions; use Moose; has MaxResults => (is => 'ro', isa => 'Str', traits => ['ParamInQuery'], query_name => 'MaxResults'); has NextToken => (is => 'ro', isa => 'Str', traits => ['ParamInQuery'], query_name => 'NextToken'); has SubscriptionDefinitionId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'SubscriptionDefinitionId', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListSubscriptionDefinitionVersions'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/greengrass/definition/subscriptions/{SubscriptionDefinitionId}/versions'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'GET'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::Greengrass::ListSubscriptionDefinitionVersionsResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::Greengrass::ListSubscriptionDefinitionVersions - Arguments for method ListSubscriptionDefinitionVersions on Paws::Greengrass =head1 DESCRIPTION This class represents the parameters used for calling the method ListSubscriptionDefinitionVersions on the AWS Greengrass service. Use the attributes of this class as arguments to method ListSubscriptionDefinitionVersions. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListSubscriptionDefinitionVersions. As an example: $service_obj->ListSubscriptionDefinitionVersions(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 MaxResults => Str Specifies the maximum number of list results to be returned in this page =head2 NextToken => Str Specifies the pagination token used when iterating through a paginated request =head2 B<REQUIRED> SubscriptionDefinitionId => Str subscription definition Id =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method ListSubscriptionDefinitionVersions in L<Paws::Greengrass> =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/Greengrass/ListSubscriptionDefinitionVersions.pm
Perl
apache-2.0
2,523
# Auto-generated file -- DO NOT EDIT!!!!! =head1 NAME KinoSearch::Search::Hits - Access search results. =head1 DEPRECATED The KinoSearch code base has been assimilated by the Apache L<Lucy> project. The "KinoSearch" namespace has been deprecated, but development continues under our new name at our new home: L<http://lucy.apache.org/> =head1 SYNOPSIS my $hits = $searcher->hits( query => $query, offset => 0, num_wanted => 10, ); while ( my $hit = $hits->next ) { print "<p>$hit->{title} <em>" . $hit->get_score . "</em></p>\n"; } =head1 DESCRIPTION Hits objects are iterators used to access the results of a search. =head1 METHODS =head2 next() Return the next hit, or undef when the iterator is exhausted. =head2 total_hits() Return the total number of documents which matched the Query used to produce the Hits object. Note that this is the total number of matches, not just the number of matches represented by the Hits iterator. =head1 INHERITANCE KinoSearch::Search::Hits isa L<KinoSearch::Object::Obj>. =head1 COPYRIGHT AND LICENSE Copyright 2005-2011 Marvin Humphrey This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
gitpan/KinoSearch
lib/KinoSearch/Search/Hits.pod
Perl
apache-2.0
1,278
package Venn::Role::Util; =head1 NAME Venn::Role::Util =head1 DESCRIPTION Utilities library =head1 AUTHOR Venn Engineering Josh Arenberg, Norbert Csongradi, Ryan Kupfer, Hai-Long Nguyen =head1 LICENSE Copyright 2013,2014,2015 Morgan Stanley Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut use v5.14; use Moose::Role; use Hash::Merge; use Scalar::Util 'reftype'; =head1 METHODS =head2 $self->hash_replace($hash, $this, $that) Replaces $this to $that by walking the hash return : (HashRef) Returns the modified hash =cut sub hash_replace { my ($self, $hash, $this, $that) = @_; if (ref $hash eq 'HASH') { for my $k (keys %$hash) { # substitution in value my $v = $hash->{$k}; if (ref $v && reftype($v) eq "HASH") { $self->hash_replace($v, $this, $that); } elsif (ref $v && reftype($v) eq 'ARRAY') { @$v = map {$self->hash_replace($_, $this, $that)} @$v; } elsif (! ref $v) { $v =~ s/$this/$that/og; } my $new_hash = {}; for my $k (keys %$hash) { # substitution in key (my $new_key = $k) =~ s/$this/$that/og; $new_hash->{$new_key} = $hash->{$k}; } %$hash = %$new_hash; # replace old keys with new keys } } elsif (ref $hash && reftype($hash) eq 'ARRAY') { @$hash = map {$self->hash_replace($_, $this, $that)} @$hash; } elsif (!ref $hash) { $hash =~ s/$this/$that/og; } else { Carp::confess "Unknown reference encountered: ".ref($hash); } return $hash; } =head2 $self->hash_merge($hash1, $hash2 [, $precedence]) Simply merges the hashes, recursively, with left precedence return : (HashRef) Returns the merged hash =cut sub hash_merge { my ($self, $hash1, $hash2, $precedence ) = @_; $precedence //= 'LEFT_PRECEDENT'; my $merger = Hash::Merge->new($precedence); return $merger->merge($hash1, $hash2); } 1;
Morgan-Stanley/venn-core
lib/Venn/Role/Util.pm
Perl
apache-2.0
2,529
use strict; use warnings qw(FATAL); use MMPLD; $#ARGV == 1 or die "usage: $0 <inputfile> <outputfile>"; my $outfile = $ARGV[1]; my $m = MMPLD->new({filename=>$outfile, numframes=>1}); $m->StartFrame({frametime=>1.23, numlists=>1}); my $temp = <>; $temp =~ /(\d+)/; my $numPoints = $1; $m->StartList({ vertextype=>$VERTEX_XYZ_FLOAT, colortype=>$COLOR_INTENSITY_FLOAT, globalradius=>1.0, minintensity=>0.0, maxintensity=>255, particlecount=>$numPoints }); my @xs; my @ys; my @zs; my @is; my $currPoint = 0; my $oldperc = 0; while (<>) { my @vals = split /\s/; if ($#vals != 6) { next; } #push @xs, $vals[0]; #push @ys, $vals[1]; #push @zs, $vals[2]; #push @is, $vals[3]; $m->AddParticle({ x=>$vals[0], y=>$vals[1], z=>$vals[2], i=>$vals[3] }); #if ($#xs == 1) { # last; #} $currPoint++; my $newperc = int(($currPoint * 100) / $numPoints); if ($newperc != $oldperc) { print "$newperc%\n"; $oldperc = $newperc; } } print "got $currPoint points, should be $numPoints: " . (($currPoint==$numPoints)?'Ok':'Problem') . ".\n";
UniStuttgart-VISUS/megamol
utils/MMPLD/PTS2MMPLD.pl
Perl
bsd-3-clause
1,178
package AsposeTasksCloud::Object::TaskType; require 5.6.0; use strict; use warnings; use utf8; use JSON qw(decode_json); use Data::Dumper; use Module::Runtime qw(use_module); use Log::Any qw($log); use Date::Parse; use DateTime; use base "AsposeTasksCloud::Object::BaseObject"; # # # #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # my $swagger_types = { }; my $attribute_map = { }; # new object sub new { my ($class, %args) = @_; my $self = { }; return bless $self, $class; } # get swagger type of the attribute sub get_swagger_types { return $swagger_types; } # get attribute mappping sub get_attribute_map { return $attribute_map; } 1;
aspose-tasks/Aspose.Tasks-for-Cloud
SDKs/Aspose.Tasks-Cloud-SDK-for-Perl/lib/AsposeTasksCloud/Object/TaskType.pm
Perl
mit
759
:- module(argutils, [ sumargs/2 , addargs/3 ]). sumargs(Term,Total) :- functor(Term,_,N), sumargs(N,Term,0,Total). sumargs(0,_,S,S) :- !. sumargs(N,Term,S1,S3) :- succ(M,N), arg(N,Term,X), S2 is S1+X, sumargs(M,Term,S2,S3). %% addargs( +Term, +Args, -NewTerm) is det. % % Add an extra argument to a term, eg % == % ?- addargs(spam(fish,cake),spoon,T). % T = spam(fish,cake,spoon). % true. % == addargs(Term,Args,NewTerm) :- var(NewTerm) -> (Term=..L, append(L,Args,LL), NewTerm=..LL) ; (NewTerm=..LL, append(L,Args,LL), Term=..L). % functor(S1,F,A), arg(N,S1,X1), % functor(S2,F,A), arg(N,S2,X2), % phrase(P,X1,X2), % foreach((arg(I,S1,X),I\=N), arg(I,S2,X)). % reinstatevars(Bindings,'$VAR'(Name),Var) :- member(Name=Var,Bindings), !. % reinstatevars(_,Atomic,Atomic) :- atomic(Atomic), !. % reinstatevars(Bindings,Term1,Term2) :- % Term1 =.. [F | Args1], % maplist(reinstatevars(Bindings),Args1,Args2), % Term2 =.. [F | Args2].
TeamSPoon/logicmoo_workspace
packs_lib/genutils/prolog/argutils.pl
Perl
mit
1,009
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::AltAlleleGroup =head1 SYNOPSIS use Bio::EnsEMBL::AltAlleleGroup; use Bio::EnsEMBL::DBSQL::AltAlleleGroupAdaptor; my $aag_adaptor = Bio::EnsEMBL::Registry->get_DBAdaptor("Human","core","AltAlleleGroup"); # For a known Gene, find the reference alternative allele my $aag = $aag_adaptor->fetch_Group_by_dbID($gene->dbID); my $reference_gene = $aag->get_representative_Gene; # Get a list of AltAlleleGroups my $list = $aag_adaptor->fetch_all_Groups_by_type('HAS_CODING_POTENTIAL'); $list = $aag_adaptor->fetch_all_Groups(); while ($aag = shift @$list) { $aag->get_all_Genes; # Do your important things ... } # Creating and editing an AltAlleleGroup my $type_flags = [qw(IS_MOST_COMMON_ALLELE AUTOMATICALLY_ASSIGNED)]; $aag = Bio::EnsEMBL::AltAlleleGroup->new( -MEMBERS => [ [$gene_id,$type_flags ] ], ); $aag->remove_all_members; $aag->add_member([$gene_id,$type_flags]); my $dbID = $aag_adaptor->store($aag); =head1 DESCRIPTION Alt allele groups keep track of which alleles are tied to a particular Gene They allow related genes to be located. This class allows fetching of both IDs and fully fledged Gene objects. AltAlleleGroup members are assigned types to differentiate them by their origin. These types are set as flags, allowing you to select the union of types as well as by individual ones. No flags set denotes a situation of no information. Valid flags are as follows: 'IS_REPRESENTATIVE', 'IS_MOST_COMMON_ALLELE', 'IN_CORRECTED_ASSEMBLY', 'HAS_CODING_POTENTIAL', 'IN_ARTIFICIALLY_DUPLICATED_ASSEMBLY', 'IN_SYNTENIC_REGION', 'HAS_SAME_UNDERLYING_DNA_SEQUENCE', 'IN_BROKEN_ASSEMBLY_REGION', 'IS_VALID_ALTERNATE', 'SAME_AS_REPRESENTATIVE', 'SAME_AS_ANOTHER_ALLELE', 'MANUALLY_ASSIGNED', 'AUTOMATICALLY_ASSIGNED' =cut package Bio::EnsEMBL::AltAlleleGroup; use strict; use warnings; #use constant { # IS_REPRESENTATIVE => 1, # IS_MOST_COMMON_ALLELE => 2, # IN_CORRECTED_ASSEMBLY => 3, # HAS_CODING_POTENTIAL => 4, # IN_ARTIFICIALLY_DUPLICATED_ASSEMBLY => 5, # IN_SYNTENIC_REGION => 6, # HAS_SAME_UNDERLYING_DNA_SEQUENCE => 7, # IN_BROKEN_ASSEMBLY_REGION => 8, # IS_VALID_ALTERNATE => 9, # SAME_AS_REPRESENTATIVE => 10, # SAME_AS_ANOTHER_ALLELE => 11, # MANUALLY_ASSIGNED => 12, # AUTOMATICALLY_ASSIGNED => 13, #}; use Bio::EnsEMBL::Utils::Argument qw(rearrange); use Bio::EnsEMBL::Utils::Exception qw(warning throw); use Bio::EnsEMBL::Utils::Scalar qw(check_ref assert_integer assert_ref); use base qw/Bio::EnsEMBL::Storable/; =head2 new Arg [-MEMBERS]: A list reference of [gene_id,type_flags] : gene_id is a dbID for Gene (consistent only within one release) : type_flags is a hash ref of attributes for this member Example : $aag = Bio::EnsEMBL::AltAlleleGroup->new( -MEMBERS => [ [1,{$type} ], [2,{$other_type}],[3,{$type}], ); Description: Creates a new alt-allele group object Returntype : Bio::EnsEMBL::AltAlleleGroup Exceptions : none Caller : general =cut sub new { my $caller = shift; my $class = ref($caller) || $caller; my $self = $class->SUPER::new(@_); my ( $list ) = rearrange( [ 'MEMBERS'], @_ ); $self->{'MEMBERS'} = $list || []; return $self; } =head2 add_member Arg [1] : Gene dbID Arg [2] : Type List, used for assigning type flags of this member, see Description above Description : Adds a record of one new member to the AltAlleleGroup. Once a change is made, this must be persisted to the database with AltAlleleGroupAdaptor->store or ->update Example : $aag->add_member(1040032,$types_hash); $aaga->update($aag); # updating the whole group is necessary. =cut sub add_member { my ($self, $gene_id,$type_hash) = @_; if(!$self->contains_member($gene_id)) { push(@{$self->{MEMBERS}}, [$gene_id, {}]); $self->set_attribs($gene_id, $type_hash); } return; } =head2 get_all_members_with_type Arg [1] : String The type to search members by Description : Loops through the internal members array returning all attributes of the same type as what has been specified Example : my $members = $aag->get_all_members_with_type('IS_VALID_ALTERNATE'); =cut sub get_all_members_with_type { my $self = shift; my $type = shift; my @filtered_members; my $members = $self->{'MEMBERS'}; foreach my $member (@$members) { if (exists($member->[1]->{$type})) { push @filtered_members,$member; } } return \@filtered_members; } =head2 attribs Arg [1] : Int gene id to record attributes against Description : Returns all known attributes of the given gene id. Attributes are returned as a HashRef but is a copy of the interally held attribute list Returntype : HashRef copy of all the given id's attributes Example : $aag->attribs(10, 'IS_VALID_ALTERNATE'); $aag->attribs(10, [ 'IS_VALID_ALTERNATE' ]); $aag->attribs(10, {IS_VALID_ALTERNATE => 1}); =cut sub attribs { my ($self, $gene_id) = @_; assert_integer($gene_id, 'gene_id'); foreach my $member (@{$self->{MEMBERS}}) { if($member->[0] == $gene_id) { my $attribs = $member->[1]; return { %{$attribs} }; # make a copy. never leak } } return {}; } =head2 set_attribs Arg [1] : Int gene id to set attributes against Arg [2] : ArrayRef/HashRef/Scalar The attribute you wish to record Description : Adds the given type to the specified gene id in this group. You can specify the type using an ArrayRef, HashRef or a single scalar Example : $aag->attribs(10, 'IS_VALID_ALTERNATE'); $aag->attribs(10, [ 'IS_VALID_ALTERNATE' ]); $aag->attribs(10, {IS_VALID_ALTERNATE => 1}); =cut sub set_attribs { my ($self, $gene_id, $attribs) = @_; assert_integer($gene_id, 'gene_id'); my $current_attribs = $self->attribs($gene_id); if(check_ref($attribs, 'ARRAY')) { #Loop & add $current_attribs->{uc($_)} = 1 for @{$attribs}; } elsif(check_ref($attribs, 'HASH')) { #loop through the keys adding them in foreach my $key (keys %{$attribs}) { $current_attribs->{uc($key)} = 1; } } #Simple scalar value so just add it in else { $current_attribs->{uc($attribs)} = 1; } foreach my $member (@{$self->{MEMBERS}}) { if($member->[0] == $gene_id) { $member->[1] = $current_attribs; } } return; } =head2 remove_attribs Arg [1] : Int gene id to retrieve attributes against Arg [2] : ArrayRef/HashRef/Scalar The attribute you wish to remove Description : Removes the given type from this group against the specified gene identifier Example : $aag->remove_attribs(10, 'IS_VALID_ALTERNATE'); $aag->remove_attribs(10, [ 'IS_VALID_ALTERNATE' ]); $aag->remove_attribs(10, {IS_VALID_ALTERNATE => 1}); =cut sub remove_attribs { my ($self, $gene_id, $attribs) = @_; assert_integer($gene_id, 'gene_id'); my @to_remove; if(check_ref($attribs, 'ARRAY')) { @to_remove = map { uc($_) } @{$attribs}; } elsif(check_ref($attribs, 'HASH')) { @to_remove = map { uc($_) } keys %{$attribs}; } #Simple scalar value so just add it in else { @to_remove = uc($attribs); } foreach my $member (@{$self->{MEMBERS}}) { if($member->[0] == $gene_id) { my $current_attribs = $member->[1]; delete $current_attribs->{$_} for @to_remove; } } return; } =head2 remove_member Arg [1] : Int gene id to retrieve attributes against Arg [2] : ArrayRef/HashRef/Scalar The attribute you wish to remove Description : Removes the given member from this group. Any changes must be persisted back to the database via update() or store() methods in Bio::EnsEMBL::DBSQL::AltAlleleGroupAdaptor. Example : $aag->remove_member(10); =cut sub remove_member { my ($self, $gene_id) = @_; assert_integer($gene_id, 'gene_id'); my $members = $self->{MEMBERS}; my $size = scalar(@{$members}); for(my $i = 0; $i < $size; $i++) { my $current_id = $members->[$i]->[0]; #If this was the ID then splice it out of the array and exit if($current_id == $gene_id) { splice(@{$members}, $i, 1); last; } } return; } =head2 contains_member Arg [1] : Int gene id to retrieve attributes against Description : Searches through the members list looking for the specified gene id. Returns true if it was found or false if not. Returntype : Boolean indicating if the given gene id is held in this group Example : $aag->contains_member(10); =cut sub contains_member { my ($self, $gene_id) = @_; assert_integer($gene_id, 'gene_id'); foreach my $member (@{$self->{MEMBERS}}) { if($member->[0] == $gene_id) { return 1; } } return 0; } =head2 remove_all_members Description : Remove members from this object, but NOT the database. See AltAlleleGroupAdaptor->remove() to remove the group from the database =cut sub remove_all_members { my $self = shift; $self->{'MEMBERS'} = []; return; } =head2 rep_Gene_id Arg[1] : Optional - set a new representative Gene id for the group Description : Reports or sets the representative Gene for this AltAlleleGroup If you wish to remove the representative status of all genes without setting a new one, see unset_rep_Gene_id Returntype : Integer or undef if none set =cut sub rep_Gene_id { my $self = shift; my $new_id = shift; my $list = $self->{'MEMBERS'}; my $change; foreach my $allele (@$list) { my ($gene_id,$type) = @$allele; if (exists($type->{IS_REPRESENTATIVE}) && !defined($new_id) ) { return $gene_id; } if ($new_id) { unless ($gene_id == $new_id) {delete($allele->[1]->{IS_REPRESENTATIVE})} else { $allele->[1]->{IS_REPRESENTATIVE} = 1; $change = $new_id; } } } if ($change) { $self->{'MEMBERS'} = $list; return $new_id; } elsif ($new_id && !$change) { my $db_id = $self->dbID() || 'unknown'; throw("Requested representative gene ID was not set because it is not in this AltAlleleGroup, ID $db_id"); } else { warning("No representative allele currently set for this AltAlleleGroup"); return; } } =head2 unset_rep_Gene_id Description : Removes the representative Gene flag from this AltAlleleGroup. This action is not possible through rep_Gene_id due to validation of inputs. =cut sub unset_rep_Gene_id { my $self = shift; my $list = $self->{'MEMBERS'}; foreach my $allele (@$list) { delete($allele->[1]->{IS_REPRESENTATIVE}); } $self->{'MEMBERS'} = $list; return; } =head2 get_all_Gene_ids Arg[1] : Boolean - Do not include representative gene in list of ids. Arg[2] : ArrayRef - Can contain dbIDs or Gene objects to exclude from the returned list Description : fetches all the Gene dbIDs within the allele group. It can also be used to list those ids that are not the representative Gene. Returntype : ArrayRef of gene dbIDs =cut sub get_all_Gene_ids { my $self = shift; my $all_but_rep = shift; my $excluded_genes = shift; my $list = $self->{'MEMBERS'}; my %gene_exclusions; if($excluded_genes) { assert_ref($excluded_genes, 'ARRAY', 'excluded genes'); foreach my $gene (@{$excluded_genes}) { my $gene_id = (ref($gene)) ? $gene->dbID() : $gene; $gene_exclusions{$gene_id} = $gene_id; } } my @gene_ids; foreach my $allele (@$list) { my ($gene_id,$type) = @$allele; if ($all_but_rep && $type->{IS_REPRESENTATIVE}) {next;} if(exists $gene_exclusions{$gene_id}) { next; } push @gene_ids,$gene_id; } return [sort {$a <=> $b} @gene_ids]; } =head2 get_representative_Gene Description : Used to fetch a Gene object which has been marked as the representative Gene for this alt allele group. Returntype : Bio::EnsEMBL::Gene object which is the representative gene =cut sub get_representative_Gene { my $self = shift; my $ga = $self->adaptor->db->get_GeneAdaptor; return $ga->fetch_by_dbID($self->rep_Gene_id); } =head2 get_all_Genes Arg[1] : Boolean - Do not include representative gene in list of ids. Arg[2] : ArrayRef - Can contain dbIDs or Gene objects to exclude from the returned list Description : Fetches all the Gene objects within the allele group. It can also be used to list those Genes that are not the representative Gene. Returntype : ArrayRef of Bio::EnsEMBL::Gene objects =cut sub get_all_Genes { my ($self, $all_but_rep, $excluded_genes) = @_; my $gene_ids = $self->get_all_Gene_ids($all_but_rep, $excluded_genes); return $self->adaptor()->db()->get_GeneAdaptor()->fetch_all_by_dbID_list($gene_ids); } =head2 get_all_Genes_types Arg[1] : Boolean - Do not include representative gene in list of ids. Arg[2] : ArrayRef - Can contain dbIDs or Gene objects to exclude from the returned list Description : Fetches all the Gene objects within the allele group and their associcated attributes. It can also be used to list those Genes that are not the representative Gene. Returntype : ArrayRef. 2 dimensional holding [Bio::EnsEMBL::Gene, {attribute_hash}] =cut sub get_all_Genes_types { my ($self, $all_but_rep, $excluded_genes) = @_; my $gene_ids = $self->get_all_Gene_ids($all_but_rep, $excluded_genes); my $ga = $self->adaptor()->db()->get_GeneAdaptor(); my @output; my $members = $self->{MEMBERS}; foreach my $allele (@{$members}) { my ($gene_id,$attribs) = @$allele; if ($all_but_rep && $attribs->{IS_REPRESENTATIVE}) {next;} my $gene = $ga->fetch_by_dbID($gene_id); my %attribs_copy = %{$attribs}; push(@output, [$gene, \%attribs_copy]) } return \@output; } =head2 size Description : Returns the current size of this group in members Returntype : Int the size of the current alt allele group =cut sub size { my $self = shift; my $list = $self->{'MEMBERS'}; return scalar(@$list); } =head2 get_all_members Description : Retrieves all of the information about all members. Be aware that this emits the interal data structure so direct modification should be done with caution. Returntype : ArrayRef of id and type list: [gene_id,type] Caller : AltAlleleGroupAdaptor->store =cut sub get_all_members { my $self = shift; my $members = $self->{'MEMBERS'}; return $members; } 1;
mjg17/ensembl
modules/Bio/EnsEMBL/AltAlleleGroup.pm
Perl
apache-2.0
16,106
package Perun::GroupsAgent; use strict; use warnings; use Perun::Common; my $manager = 'groupsManager'; use fields qw(_agent _manager); sub new { my $self = fields::new(shift); $self->{_agent} = shift; $self->{_manager} = $manager; return $self; } sub createGroup { return Perun::Common::callManagerMethod('createGroup', 'Group', @_); } sub deleteGroup { return Perun::Common::callManagerMethod('deleteGroup', 'null', @_); } sub updateGroup { return Perun::Common::callManagerMethod('updateGroup', 'Group', @_); } sub getGroupById { return Perun::Common::callManagerMethod('getGroupById', 'Group', @_); } sub getGroupByName { return Perun::Common::callManagerMethod('getGroupByName', 'Group', @_); } sub addMember { return Perun::Common::callManagerMethod('addMember', 'null', @_); } sub removeMember { return Perun::Common::callManagerMethod('removeMember', 'null', @_); } sub getGroupMembers { return Perun::Common::callManagerMethod('getGroupMembers', '[]Member', @_); } sub getGroupRichMembers { return Perun::Common::callManagerMethod('getGroupRichMembers', '[]RichMember', @_); } sub getGroupRichMembersWithAttributes { return Perun::Common::callManagerMethod('getGroupRichMembersWithAttributes', '[]RichMember', @_); } sub getGroupMembersCount { return Perun::Common::callManagerMethod('getGroupMembersCount', 'number', @_); } sub getAllGroups { return Perun::Common::callManagerMethod('getAllGroups', '[]Group', @_); } sub getParentGroups { return Perun::Common::callManagerMethod('getParentGroups', '[]Group', @_); } sub getSubGroups { return Perun::Common::callManagerMethod('getSubGroups', '[]Group', @_); } sub addAdmin { return Perun::Common::callManagerMethod('addAdmin', 'null', @_); } sub removeAdmin { return Perun::Common::callManagerMethod('removeAdmin', 'null', @_); } sub getAdmins { return Perun::Common::callManagerMethod('getAdmins', '[]User', @_); } sub getRichAdmins { return Perun::Common::callManagerMethod('getRichAdmins', '[]RichUser', @_); } sub getRichAdminsWithAttributes { return Perun::Common::callManagerMethod('getRichAdminsWithAttributes', '[]RichUser', @_); } sub getGroups { return Perun::Common::callManagerMethod('getGroups', '[]Group', @_); } sub getGroupsCount { return Perun::Common::callManagerMethod('getGroupsCount', 'number', @_); } sub getSubGroupsCount { return Perun::Common::callManagerMethod('getSubGroupsCount', 'number', @_); } sub deleteAllGroups { return Perun::Common::callManagerMethod('deleteAllGroups', '', @_); } sub forceGroupSynchronization { return Perun::Common::callManagerMethod('forceGroupSynchronization', 'null', @_); } 1;
Holdo/perun
perun-rpc/src/main/perl/Perun/GroupsAgent.pm
Perl
bsd-2-clause
2,654
#!/usr/bin/perl use strict; use Test::More; use FindBin qw($Bin); use lib "$Bin/lib"; use MemcachedTest; sleep 1; my $threads = 128; my $running = 0; # default engine start option : -m 512 # example) ./memcached -E .libs/default_engine.so -X .libs/ascii_scrub.so -m 512 while ($running < $threads) { # my $sock = IO::Socket::INET->new(PeerAddr => "$server->{host}:$server->{port}"); my $sock = IO::Socket::INET->new(PeerAddr => "localhost:11211"); my $cpid = fork(); if ($cpid) { $running++; print "Launched $cpid. Running $running threads.\n"; } else { data_load($sock); sleep(10); data_work($sock); exit 0; } } while ($running > 0) { wait(); print "stopped. Running $running threads.\n"; $running--; } sub data_load { my $sock = shift; my $i; my $expire; for ($i = 0; $i < 100000; $i++) { my $keyrand = int(rand(9000000)); my $valrand = 30 + int(rand(50)); my $key = "dash$keyrand"; my $val = "B" x $valrand; my $len = length($val); my $res; $expire = 86400; print $sock "set $key 0 $expire $len\r\n$val\r\n"; $res = scalar <$sock>; if ($res ne "STORED\r\n") { print "set $key $len: $res\r\n"; } } print "data_load end\n"; } sub data_work { my $sock = shift; my $i; my $expire; for ($i = 0; $i < 50000000; $i++) { my $keyrand = int(rand(900000000)); my $valrand = 120 + int(rand(20)); # my $valrand = 300 + int(rand(1000)); my $key = "dash$keyrand"; my $val = "B" x $valrand; my $len = length($val); my $res; my $meth = int(rand(10)); sleep(0.1); if (($meth ge 0) and ($meth le 7)) { $expire = 86400; print $sock "set $key 0 $expire $len\r\n$val\r\n"; $res = scalar <$sock>; if ($res ne "STORED\r\n") { print "set $key $len: $res\r\n"; } } else { print $sock "get $key\r\n"; $res = scalar <$sock>; if ($res =~ /^VALUE/) { $res .= scalar(<$sock>) . scalar(<$sock>); } } } print "data_work end\n"; } #undef $server;
ropik/arcus-memcached
t/too_many_eviction_issue.pl
Perl
bsd-3-clause
2,296
:- module(pp,[pp/2]). :- use_module(slashes). :- use_module(idioms). :- use_module(printError,[error/2,error/3]). :- use_module(library(lists),[append/3]). /* =================================================================== Post-processing: pro-drop (subject and object) =================================================================== */ pp(ba(X,NP,VP1),tc(X,X\np,VP2)):- NP = t(np,'PRO~PE',_,'*[]'), !, pp(VP1,VP2). pp(fa(X,VP1,NP),tc(X,X/np,VP2)):- NP = t(np,'PRO~PE',_,'*[]'), !, pp(VP1,VP2). pp(ba(X,Arg,Fun1),tc(X,X\Cat,Fun2)):- Arg = t(Cat,_,_,Lex), empty(Lex), !, pp(Fun1,Fun2). pp(ba(X,Arg1,Fun),tc(X,Cat,Arg2)):- Fun = t(_\Cat,_,_,Lex), empty(Lex), !, pp(Arg1,Arg2). pp(fa(X,Fun1,Arg),tc(X,X/Cat,Fun2)):- Arg = t(Cat,_,_,Lex), empty(Lex), !, pp(Fun1,Fun2). pp(fa(X,Fun,Arg1),tc(X,Cat,Arg2)):- Fun = t(_/Cat,_,_,Lex), empty(Lex), !, pp(Arg1,Arg2). /* =================================================================== Post-processing: clitics (separation) =================================================================== */ pp(fa(X,VP1,NP1),fa(X,VP2,NP2)):- VP1 = t(X/np,POSVP,IVP,Token), NP1 = t(np,POSNP,INP,Token), atom_chars(Token,TokenChars), clitic(Pro), atom_chars(Pro,ProChars), append(TempChars,ProChars,TokenChars), !, append(TempChars,['~'],VerbChars), atom_chars(Verb,VerbChars), atom_chars(Clitic,['~'|ProChars]), VP2 = t(X/np,POSVP,IVP,Verb), NP2 = t(np,POSNP,INP,Clitic). pp(ba(X,VP1,NP1),ba(X,VP2,NP2)):- VP1 = t(X,POSVP,IVP,Token), NP1 = t(X\X,POSNP,INP,Token), atom_chars(Token,TokenChars), clitic(Pro), atom_chars(Pro,ProChars), append(TempChars,ProChars,TokenChars), !, append(TempChars,['~'],VerbChars), atom_chars(Verb,VerbChars), atom_chars(Clitic,['~'|ProChars]), VP2 = t(X,POSVP,IVP,Verb), NP2 = t(X\X,POSNP,INP,Clitic). /* =================================================================== Post-processing: clitics (deletion) =================================================================== */ %pp(fa(X,VP,NP),t(X,POS,I,Sym)):- % VP = t(X/np,POS,I,Sym), % NP = t(np,_,_,Sym), !. %pp(ba(X,VP,NP),t(X,POS,I,Sym)):- % VP = t(X,POS,I,Sym), % NP = t(X\X,_,_,Sym), !. /* =================================================================== Post-processing: composed clitics =================================================================== */ pp(t(np,POS,I,'glieli'),t(np,POS,I,'~li')):- !. pp(t(s:X/s:X,POS,I,'glieli'),t(s:X/s:X,POS,I,'gli~')):- !. pp(t(np,POS,I,'glielo'),t(np,POS,I,'~lo')):- !. pp(t(s:X/s:X,POS,I,'glielo'),t(s:X/s:X,POS,I,'gli~')):- !. pp(t(np,POS,I,'averlo'),t(np,POS,I,'~lo')):- !. pp(t(s:inf/s:pap,POS,I,'averlo'),t(s:inf/s:pap,POS,I,'aver~')):- !. /* =================================================================== Post-processing: punctuation abstraction =================================================================== */ pp(t((X/p:F)/X,B,C,D),t(('X'/p:F)/'X',B,C,D)):- user:switch(pab,yes), !. pp(t(X\(X/p:F),B,C,D),t('X'\('X'/p:F),B,C,D)):- user:switch(pab,yes), !. /* =================================================================== Post-processing: idioms =================================================================== */ pp(t(A,B,C,D),Tree2):- idiom(t(A,B,C,D),Tree1), !, Tree2=Tree1. /* =================================================================== Post-processing: general =================================================================== */ pp(t(A,B,C,D),t(A,B,C,D)):- !. pp(bxc(Cat,L1,R1),bxc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(fxc(Cat,L1,R1),fxc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(ba(Cat,L1,R1),ba(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(fa(Cat,L1,R1),fa(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(bc(Cat,L1,R1),bc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(fc(Cat,L1,R1),fc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(gfc(Cat,L1,R1),gfc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(gbc(Cat,L1,R1),gbc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(conj(Cat1,Cat2,L1,R1),conj(Cat1,Cat2,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(tc(Cat1,Cat2,T1),tc(Cat1,Cat2,T2)):- !, pp(T1,T2). pp(gbxc(Cat,L1,R1),gbxc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(gfxc(Cat,L1,R1),gfxc(Cat,L2,R2)):- !, pp(L1,L2), pp(R1,R2). pp(CCG,CCG):- error('ERROR (pp/2): ~p~n',[CCG]). /* =================================================================== Empty Nodes =================================================================== */ empty('*[]'):- !. empty(Node):- atom_chars(Node,['*','['|_]). /* =================================================================== Clitics =================================================================== */ clitic(gli). clitic(lo). clitic(la). clitic(le). clitic(li). clitic(ci). clitic(ne). clitic(si). clitic(ti). clitic(vi). clitic(mi).
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/candc/src/data/italian/prolog/pp.pl
Perl
mit
4,876
#----------------------------------------------------------- # compname.pl # Plugin for Registry Ripper; Access System hive file to get the # computername # # Change history # 20090727 - added Hostname # # References # http://support.microsoft.com/kb/314053/ # # copyright 2009 H. Carvey #----------------------------------------------------------- package compname; use strict; my %config = (hive => "System", hasShortDescr => 1, hasDescr => 0, hasRefs => 0, osmask => 22, version => 20090727); sub getConfig{return %config} sub getShortDescr { return "Gets ComputerName and Hostname values from System hive"; } sub getDescr{} sub getRefs {} sub getHive {return $config{hive};} sub getVersion {return $config{version};} my $VERSION = getVersion(); sub pluginmain { my $class = shift; my $hive = shift; ::logMsg("Launching compname v.".$VERSION); ::rptMsg("compname v.".$VERSION); # banner ::rptMsg("(".$config{hive}.") ".getShortDescr()."\n"); # banner my $reg = Parse::Win32Registry->new($hive); my $root_key = $reg->get_root_key; # First thing to do is get the ControlSet00x marked current...this is # going to be used over and over again in plugins that access the system # file my ($current,$ccs); my $key_path = 'Select'; my $key; if ($key = $root_key->get_subkey($key_path)) { $current = $key->get_value("Current")->get_data(); $ccs = "ControlSet00".$current; my $cn_path = $ccs."\\Control\\ComputerName\\ComputerName"; my $cn; if ($cn = $root_key->get_subkey($cn_path)) { my $name = $cn->get_value("ComputerName")->get_data(); ::rptMsg("ComputerName = ".$name); } else { ::rptMsg($cn_path." not found."); ::logMsg($cn_path." not found."); } } else { ::rptMsg($key_path." not found."); ::logMsg($key_path." not found."); } my $hostname; eval { my $host_path = $ccs."\\Services\\Tcpip\\Parameters"; $hostname = $root_key->get_subkey($host_path)->get_value("Hostname")->get_data(); ::rptMsg("TCP/IP Hostname = ".$hostname); }; } 1;
kefir-/autopsy
RecentActivity/release/rr-full/plugins/compname.pl
Perl
apache-2.0
2,193
=pod =head1 NAME d2i_X509_AUX, i2d_X509_AUX, i2d_re_X509_tbs, i2d_re_X509_CRL_tbs, i2d_re_X509_REQ_tbs - X509 encode and decode functions =head1 SYNOPSIS #include <openssl/x509.h> X509 *d2i_X509_AUX(X509 **px, const unsigned char **in, long len); int i2d_X509_AUX(X509 *x, unsigned char **out); int i2d_re_X509_tbs(X509 *x, unsigned char **out); int i2d_re_X509_CRL_tbs(X509_CRL *crl, unsigned char **pp); int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp); =head1 DESCRIPTION The X509 encode and decode routines encode and parse an B<X509> structure, which represents an X509 certificate. d2i_X509_AUX() is similar to L<d2i_X509(3)> but the input is expected to consist of an X509 certificate followed by auxiliary trust information. This is used by the PEM routines to read "TRUSTED CERTIFICATE" objects. This function should not be called on untrusted input. i2d_X509_AUX() is similar to L<i2d_X509(3)>, but the encoded output contains both the certificate and any auxiliary trust information. This is used by the PEM routines to write "TRUSTED CERTIFICATE" objects. Note that this is a non-standard OpenSSL-specific data format. i2d_re_X509_tbs() is similar to L<i2d_X509(3)> except it encodes only the TBSCertificate portion of the certificate. i2d_re_X509_CRL_tbs() and i2d_re_X509_REQ_tbs() are analogous for CRL and certificate request, respectively. The "re" in B<i2d_re_X509_tbs> stands for "re-encode", and ensures that a fresh encoding is generated in case the object has been modified after creation (see the BUGS section). The encoding of the TBSCertificate portion of a certificate is cached in the B<X509> structure internally to improve encoding performance and to ensure certificate signatures are verified correctly in some certificates with broken (non-DER) encodings. If, after modification, the B<X509> object is re-signed with X509_sign(), the encoding is automatically renewed. Otherwise, the encoding of the TBSCertificate portion of the B<X509> can be manually renewed by calling i2d_re_X509_tbs(). =head1 RETURN VALUES d2i_X509_AUX() returns a valid B<X509> structure or NULL if an error occurred. i2d_X509_AUX() returns the length of encoded data or -1 on error. i2d_re_X509_tbs(), i2d_re_X509_CRL_tbs() and i2d_re_X509_REQ_tbs() return the length of encoded data or 0 on error. =head1 SEE ALSO L<ERR_get_error(3)> L<X509_CRL_get0_by_serial(3)>, L<X509_get0_signature(3)>, L<X509_get_ext_d2i(3)>, L<X509_get_extension_flags(3)>, L<X509_get_pubkey(3)>, L<X509_get_subject_name(3)>, L<X509_get_version(3)>, L<X509_NAME_add_entry_by_txt(3)>, L<X509_NAME_ENTRY_get_object(3)>, L<X509_NAME_get_index_by_NID(3)>, L<X509_NAME_print_ex(3)>, L<X509_new(3)>, L<X509_sign(3)>, L<X509V3_get_d2i(3)>, L<X509_verify_cert(3)> =head1 COPYRIGHT Copyright 2002-2018 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/i2d_re_X509_tbs.pod
Perl
bsd-3-clause
3,114
# ====================================================================== # # Copyright (C) 2000-2001 Paul Kulchenko (paulclinger@yahoo.com) # SOAP::Lite is free software; you can redistribute it # and/or modify it under the same terms as Perl itself. # # $Id: LOCAL.pm 386 2011-08-18 19:48:31Z kutterma $ # # ====================================================================== package SOAP::Transport::LOCAL; use strict; our $VERSION = 0.714; # ====================================================================== package SOAP::Transport::LOCAL::Client; use SOAP::Lite; use vars qw(@ISA); @ISA = qw(SOAP::Client SOAP::Server); sub new { my $class = shift; return $class if ref $class; my(@arg_from, @method_from); while (@_) { $class->can($_[0]) ? push(@method_from, shift() => shift) : push(@arg_from, shift) } my $self = $class->SUPER::new(@arg_from); $self->is_success(1); # it's difficult to fail in this module $self->dispatch_to(@INC); while (@method_from) { my($method, $param_ref) = splice(@method_from,0,2); $self->$method(ref $param_ref eq 'ARRAY' ? @$param_ref : $param_ref) } return $self; } sub send_receive { my($self, %parameters) = @_; my($envelope, $endpoint, $action) = @parameters{qw(envelope endpoint action)}; SOAP::Trace::debug($envelope); my $response = $self->SUPER::handle($envelope); SOAP::Trace::debug($response); return $response; } # ====================================================================== 1; __END__
leighpauls/k2cro4
third_party/perl/perl/vendor/lib/SOAP/Transport/LOCAL.pm
Perl
bsd-3-clause
1,617
########################################################################### # # This file is auto-generated by the Perl DateTime Suite locale # generator (0.05). This code generator comes with the # DateTime::Locale distribution in the tools/ directory, and is called # generate-from-cldr. # # This file as generated from the CLDR XML locale data. See the # LICENSE.cldr file included in this distribution for license details. # # This file was generated from the source file ha_NE.xml # The source file version number was 1.18, generated on # 2009/05/05 23:06:36. # # Do not edit this file directly. # ########################################################################### package DateTime::Locale::ha_NE; use strict; use warnings; use utf8; use base 'DateTime::Locale::ha_Latn_NE'; sub cldr_version { return "1\.7\.1" } { my $first_day_of_week = "1"; sub first_day_of_week { return $first_day_of_week } } 1; __END__ =pod =encoding utf8 =head1 NAME DateTime::Locale::ha_NE =head1 SYNOPSIS use DateTime; my $dt = DateTime->now( locale => 'ha_NE' ); print $dt->month_name(); =head1 DESCRIPTION This is the DateTime locale package for Hausa Niger. =head1 DATA This locale inherits from the L<DateTime::Locale::ha_Latn_NE> locale. It contains the following data. =head2 Days =head3 Wide (format) Litini Talata Laraba Alhamis Jumma'a Asabar Lahadi =head3 Abbreviated (format) Lit Tal Lar Alh Jum Asa Lah =head3 Narrow (format) L T L A J A L =head3 Wide (stand-alone) Litini Talata Laraba Alhamis Jumma'a Asabar Lahadi =head3 Abbreviated (stand-alone) Lit Tal Lar Alh Jum Asa Lah =head3 Narrow (stand-alone) L T L A J A L =head2 Months =head3 Wide (format) Janairu Fabrairu Maris Afrilu Mayu Yuni Yuli Augusta Satumba Oktoba Nuwamba Disamba =head3 Abbreviated (format) Jan Fab Mar Afr May Yun Yul Aug Sat Okt Nuw Dis =head3 Narrow (format) J F M A M Y Y A S O N D =head3 Wide (stand-alone) Janairu Fabrairu Maris Afrilu Mayu Yuni Yuli Augusta Satumba Oktoba Nuwamba Disamba =head3 Abbreviated (stand-alone) Jan Fab Mar Afr May Yun Yul Aug Sat Okt Nuw Dis =head3 Narrow (stand-alone) J F M A M Y Y A S O N D =head2 Quarters =head3 Wide (format) Q1 Q2 Q3 Q4 =head3 Abbreviated (format) Q1 Q2 Q3 Q4 =head3 Narrow (format) 1 2 3 4 =head3 Wide (stand-alone) Q1 Q2 Q3 Q4 =head3 Abbreviated (stand-alone) Q1 Q2 Q3 Q4 =head3 Narrow (stand-alone) 1 2 3 4 =head2 Eras =head3 Wide Gabanin Miladi Miladi =head3 Abbreviated GM M =head3 Narrow GM M =head2 Date Formats =head3 Full 2008-02-05T18:30:30 = Talata, 5 Fabrairu, 2008 1995-12-22T09:05:02 = Jumma'a, 22 Disamba, 1995 -0010-09-15T04:44:23 = Asabar, 15 Satumba, -10 =head3 Long 2008-02-05T18:30:30 = 5 Fabrairu, 2008 1995-12-22T09:05:02 = 22 Disamba, 1995 -0010-09-15T04:44:23 = 15 Satumba, -10 =head3 Medium 2008-02-05T18:30:30 = 5 Fab, 2008 1995-12-22T09:05:02 = 22 Dis, 1995 -0010-09-15T04:44:23 = 15 Sat, -10 =head3 Short 2008-02-05T18:30:30 = 5/2/08 1995-12-22T09:05:02 = 22/12/95 -0010-09-15T04:44:23 = 15/9/-10 =head3 Default 2008-02-05T18:30:30 = 5 Fab, 2008 1995-12-22T09:05:02 = 22 Dis, 1995 -0010-09-15T04:44:23 = 15 Sat, -10 =head2 Time Formats =head3 Full 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Short 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head3 Default 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head2 Datetime Formats =head3 Full 2008-02-05T18:30:30 = Talata, 5 Fabrairu, 2008 18:30:30 UTC 1995-12-22T09:05:02 = Jumma'a, 22 Disamba, 1995 09:05:02 UTC -0010-09-15T04:44:23 = Asabar, 15 Satumba, -10 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 5 Fabrairu, 2008 18:30:30 UTC 1995-12-22T09:05:02 = 22 Disamba, 1995 09:05:02 UTC -0010-09-15T04:44:23 = 15 Satumba, -10 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 5 Fab, 2008 18:30:30 1995-12-22T09:05:02 = 22 Dis, 1995 09:05:02 -0010-09-15T04:44:23 = 15 Sat, -10 04:44:23 =head3 Short 2008-02-05T18:30:30 = 5/2/08 18:30 1995-12-22T09:05:02 = 22/12/95 09:05 -0010-09-15T04:44:23 = 15/9/-10 04:44 =head3 Default 2008-02-05T18:30:30 = 5 Fab, 2008 18:30:30 1995-12-22T09:05:02 = 22 Dis, 1995 09:05:02 -0010-09-15T04:44:23 = 15 Sat, -10 04:44:23 =head2 Available Formats =head3 d (d) 2008-02-05T18:30:30 = 5 1995-12-22T09:05:02 = 22 -0010-09-15T04:44:23 = 15 =head3 EEEd (d EEE) 2008-02-05T18:30:30 = 5 Tal 1995-12-22T09:05:02 = 22 Jum -0010-09-15T04:44:23 = 15 Asa =head3 Hm (H:mm) 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 9:05 -0010-09-15T04:44:23 = 4:44 =head3 hm (h:mm a) 2008-02-05T18:30:30 = 6:30 PM 1995-12-22T09:05:02 = 9:05 AM -0010-09-15T04:44:23 = 4:44 AM =head3 Hms (H:mm:ss) 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 9:05:02 -0010-09-15T04:44:23 = 4:44:23 =head3 hms (h:mm:ss a) 2008-02-05T18:30:30 = 6:30:30 PM 1995-12-22T09:05:02 = 9:05:02 AM -0010-09-15T04:44:23 = 4:44:23 AM =head3 M (L) 2008-02-05T18:30:30 = 2 1995-12-22T09:05:02 = 12 -0010-09-15T04:44:23 = 9 =head3 Md (M-d) 2008-02-05T18:30:30 = 2-5 1995-12-22T09:05:02 = 12-22 -0010-09-15T04:44:23 = 9-15 =head3 MEd (E, d-M) 2008-02-05T18:30:30 = Tal, 5-2 1995-12-22T09:05:02 = Jum, 22-12 -0010-09-15T04:44:23 = Asa, 15-9 =head3 MMM (LLL) 2008-02-05T18:30:30 = Fab 1995-12-22T09:05:02 = Dis -0010-09-15T04:44:23 = Sat =head3 MMMd (d MMM) 2008-02-05T18:30:30 = 5 Fab 1995-12-22T09:05:02 = 22 Dis -0010-09-15T04:44:23 = 15 Sat =head3 MMMEd (E d MMM) 2008-02-05T18:30:30 = Tal 5 Fab 1995-12-22T09:05:02 = Jum 22 Dis -0010-09-15T04:44:23 = Asa 15 Sat =head3 MMMMd (d MMMM) 2008-02-05T18:30:30 = 5 Fabrairu 1995-12-22T09:05:02 = 22 Disamba -0010-09-15T04:44:23 = 15 Satumba =head3 MMMMEd (E d MMMM) 2008-02-05T18:30:30 = Tal 5 Fabrairu 1995-12-22T09:05:02 = Jum 22 Disamba -0010-09-15T04:44:23 = Asa 15 Satumba =head3 ms (mm:ss) 2008-02-05T18:30:30 = 30:30 1995-12-22T09:05:02 = 05:02 -0010-09-15T04:44:23 = 44:23 =head3 y (y) 2008-02-05T18:30:30 = 2008 1995-12-22T09:05:02 = 1995 -0010-09-15T04:44:23 = -10 =head3 yM (y-M) 2008-02-05T18:30:30 = 2008-2 1995-12-22T09:05:02 = 1995-12 -0010-09-15T04:44:23 = -10-9 =head3 yMEd (EEE, d/M/yyyy) 2008-02-05T18:30:30 = Tal, 5/2/2008 1995-12-22T09:05:02 = Jum, 22/12/1995 -0010-09-15T04:44:23 = Asa, 15/9/-010 =head3 yMMM (y MMM) 2008-02-05T18:30:30 = 2008 Fab 1995-12-22T09:05:02 = 1995 Dis -0010-09-15T04:44:23 = -10 Sat =head3 yMMMEd (EEE, d MMM y) 2008-02-05T18:30:30 = Tal, 5 Fab 2008 1995-12-22T09:05:02 = Jum, 22 Dis 1995 -0010-09-15T04:44:23 = Asa, 15 Sat -10 =head3 yMMMM (y MMMM) 2008-02-05T18:30:30 = 2008 Fabrairu 1995-12-22T09:05:02 = 1995 Disamba -0010-09-15T04:44:23 = -10 Satumba =head3 yQ (y Q) 2008-02-05T18:30:30 = 2008 1 1995-12-22T09:05:02 = 1995 4 -0010-09-15T04:44:23 = -10 3 =head3 yQQQ (y QQQ) 2008-02-05T18:30:30 = 2008 Q1 1995-12-22T09:05:02 = 1995 Q4 -0010-09-15T04:44:23 = -10 Q3 =head3 yyQ (Q yy) 2008-02-05T18:30:30 = 1 08 1995-12-22T09:05:02 = 4 95 -0010-09-15T04:44:23 = 3 -10 =head2 Miscellaneous =head3 Prefers 24 hour time? Yes =head3 Local first day of the week Litini =head1 SUPPORT See L<DateTime::Locale>. =head1 AUTHOR Dave Rolsky <autarch@urth.org> =head1 COPYRIGHT Copyright (c) 2008 David Rolsky. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. This module was generated from data provided by the CLDR project, see the LICENSE.cldr in this distribution for details on the CLDR data's license. =cut
liuyangning/WX_web
xampp/perl/vendor/lib/DateTime/Locale/ha_NE.pm
Perl
mit
8,435
package UI::Server; # # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # use UI::Utils; use UI::Status; use Mojo::Base 'Mojolicious::Controller'; use Data::Dumper; sub index { my $self = shift; &navbarpage($self); } sub view { my $self = shift; my $mode = $self->param('mode'); my $id = $self->param('id'); my $rs_server = $self->db->resultset('Server')->search( { id => $id } ); if ( $mode eq "view" ) { &stash_role($self); my $data = $rs_server->single; # don't send the passwds over the wire if the user doesn't have at least Ops privs. if ( $self->stash('priv_level') < 20 ) { $data->{_column_data}->{ilo_password} = "*********"; $data->{_column_data}->{xmpp_passwd} = "*********"; } # Get list of ds ids associated with server $self->stash( server_data => $data ); my %delivery_services; my $rs_data = $self->db->resultset('DeliveryserviceServer')->search( { server => $id }, { prefetch => [ 'deliveryservice' ]} ); while ( my $row = $rs_data->next ) { $delivery_services{$row->deliveryservice->id} = $row->deliveryservice->xml_id; } my $service_tag = $self->db->resultset('Hwinfo')->search( { -and => [ serverid => $id, description => 'ServiceTag' ] } )->get_column('val')->single(); $self->stash( service_tag => $service_tag ); $self->stash( delivery_services => \%delivery_services ); $self->stash( fbox_layout => 1 ); } } sub server_by_id { my $self = shift; my $serverid = $self->param('id'); my $server_row = $self->db->resultset("Server")->search( { id => $serverid } )->single; if ( defined($server_row) ) { my %data = ( "id" => $server_row->id, "host_name" => $server_row->host_name, "domain_name" => $server_row->domain_name, "guid" => $server_row->guid, "tcp_port" => $server_row->tcp_port, "https_port" => $server_row->https_port, "xmpp_id" => $server_row->xmpp_id, "xmpp_passwd" => $server_row->xmpp_passwd, "interface_name" => $server_row->interface_name, "ip_address" => $server_row->ip_address, "ip_netmask" => $server_row->ip_netmask, "ip_gateway" => $server_row->ip_gateway, "ip6_address" => $server_row->ip6_address, "ip6_gateway" => $server_row->ip6_gateway, "interface_mtu" => $server_row->interface_mtu, ); $self->render( json => \%data ); } else { $self->render( json => { Error => "Server '$serverid' not found}" } ); } } # Read sub index_response { my $self = shift; my $data = getserverdata($self); $self->render( json => $data ); } sub getserverdata { my $self = shift; my @data; my $orderby = "host_name"; $orderby = $self->param('orderby') if ( defined $self->param('orderby') ); my $dbh = $self->db->storage->dbh; $orderby = $dbh->quote_identifier($orderby); my $qry = 'SELECT cdn.name AS cdn_name, sv.id AS id, sv.host_name AS host_name, sv.domain_name AS domain_name, sv.tcp_port AS tcp_port, sv.https_port AS https_port, sv.xmpp_id AS xmpp_id, \'**********\' AS xmpp_passwd, sv.interface_name AS interface_name, sv.ip_address AS ip_address, sv.ip_netmask AS ip_netmask, sv.ip_gateway AS ip_gateway, sv.ip6_address AS ip6_address, sv.ip6_gateway AS ip6_gateway, sv.interface_mtu AS interface_mtu, cg.name AS cachegroup, pl.name AS phys_location, sv.guid AS guid, sv.rack AS rack, tp.name AS type, st.name AS status, sv.offline_reason AS offline_reason, pf.name AS profile, sv.mgmt_ip_address AS mgmt_ip_address, sv.mgmt_ip_netmask AS mgmt_ip_netmask, sv.mgmt_ip_gateway AS mgmt_ip_gateway, sv.ilo_ip_address AS ilo_ip_address, sv.ilo_ip_netmask AS ilo_ip_netmask, sv.ilo_ip_gateway AS ilo_ip_gateway, sv.ilo_username AS ilo_username, \'**********\' AS ilo_password, sv.router_host_name AS router_host_name, sv.router_port_name AS router_port_name, sv.last_updated AS last_updated FROM server sv LEFT JOIN cdn cdn ON cdn.id = sv.cdn_id LEFT JOIN type tp ON tp.id = sv.type LEFT JOIN status st ON st.id = sv.status LEFT JOIN cachegroup cg ON cg.id = sv.cachegroup LEFT JOIN profile pf ON pf.id = sv.profile LEFT JOIN phys_location pl ON pl.id = sv.phys_location ORDER BY sv.'.$orderby.';'; my $stmt = $dbh->prepare($qry); $stmt->execute(); while ( my $row = $stmt->fetchrow_hashref() ) { push( @data, $row ); } return ( \@data ); } sub serverdetail { my $self = shift; my @data; my $select = undef; $select = $self->param('select') if ( defined $self->param('select') ); my $rs_data = $self->db->resultset('Server')->search( undef, { prefetch => [ 'cdn', 'cachegroup', 'type', 'profile', 'status', 'phys_location' ], } ); while ( my $row = $rs_data->next ) { my $cdn_name = defined( $row->cdn_id ) ? $row->cdn->name : ""; my $fqdn = $row->host_name . "." . $row->domain_name; if ( defined($select) && $fqdn !~ /$select/ ) { next; } my $serv = { "id" => $row->id, "host_name" => $row->host_name, "domain_name" => $row->domain_name, "tcp_port" => $row->tcp_port, "https_port" => $row->https_port, "xmpp_id" => $row->xmpp_id, "xmpp_passwd" => $row->xmpp_passwd, "interface_name" => $row->interface_name, "ip_address" => $row->ip_address, "ip_netmask" => $row->ip_netmask, "ip_gateway" => $row->ip_gateway, "ip6_address" => $row->ip6_address, "ip6_gateway" => $row->ip6_gateway, "interface_mtu" => $row->interface_mtu, "cdn" => $cdn_name, "cachegroup" => $row->cachegroup->name, "phys_location" => $row->phys_location->name, "guid" => $row->guid, "rack" => $row->rack, "type" => $row->type->name, "status" => $row->status->name, "offline_reason" => $row->offline_reason, "profile" => $row->profile->name, "mgmt_ip_address" => $row->mgmt_ip_address, "mgmt_ip_netmask" => $row->mgmt_ip_netmask, "mgmt_ip_gateway" => $row->mgmt_ip_gateway, "ilo_ip_address" => $row->ilo_ip_address, "ilo_ip_netmask" => $row->ilo_ip_netmask, "ilo_ip_gateway" => $row->ilo_ip_gateway, "ilo_username" => $row->ilo_username, "ilo_password" => $row->ilo_password, "router_host_name" => $row->router_host_name, "router_port_name" => $row->router_port_name, }; my $id = $row->id; my $rs_hwinfo_data = $self->db->resultset('Hwinfo')->search( { 'serverid' => $id } ); while ( my $hwinfo_row = $rs_hwinfo_data->next ) { $serv->{ $hwinfo_row->description } = $hwinfo_row->val; } push( @data, $serv ); } $self->render( json => \@data ); } sub edge_ds_status { my $self = shift; my $ds_id = $self->param('dsid'); my $profile_id = $self->param('profileid'); my $cachegroup_id = $self->param('cachegroupid'); my @data; my %servers_in_cg = (); my %servers_in_ds = (); my @etypes = &type_ids( $self, 'EDGE%', 'server' ); my $rs_servers_cg = $self->db->resultset('Server')->search( { cachegroup => $cachegroup_id, profile => $profile_id, type => { -in => \@etypes } } ); while ( my $row = $rs_servers_cg->next ) { $servers_in_cg{ $row->host_name } = $row->id; } my $rs_servers_ds = $self->db->resultset('DeliveryserviceServer') ->search( { deliveryservice => $ds_id }, { prefetch => [ { deliveryservice => undef }, { server => undef } ] } ); while ( my $row = $rs_servers_ds->next ) { $servers_in_ds{ $row->server->host_name } = $row->id; } my $id = 0; foreach my $server ( sort keys(%servers_in_cg) ) { push( @data, { "id" => $id, "name" => $server, "active" => defined( $servers_in_ds{$server} ) ? 1 : 0, } ); $id++; } $self->render( json => \@data ); } # Delete sub delete { my $self = shift; my $id = $self->param('id'); if ( !&is_oper($self) ) { $self->flash( alertmsg => "No can do. Get more privs." ); } else { my $delete = $self->db->resultset('Server')->search( { id => $id } ); my $host_name = $delete->get_column('host_name')->single(); $delete->delete(); $delete = $self->db->resultset('Servercheck')->search( { server => $id } ); $delete->delete(); &log( $self, "Delete server with id:" . $id . " named " . $host_name, "UICHANGE" ); } return $self->redirect_to('/close_fancybox.html'); } sub check_server_input_cgi { my $self = shift; my $id = shift; my $paramHashRef = {}; my $err = undef; foreach my $requiredParam (qw/host_name domain_name ip_address interface_name ip_netmask ip_gateway interface_mtu cdn cachegroup type profile offline_reason/) { $paramHashRef->{$requiredParam} = $self->param($requiredParam); } foreach my $optionalParam ( qw/ilo_ip_address ilo_ip_netmask ilo_ip_gateway mgmt_ip_address mgmt_ip_netmask mgmt_ip_gateway ip6_address ip6_gateway tcp_port https_port/) { $paramHashRef->{$optionalParam} = $self->param($optionalParam); } $paramHashRef = &trim_whitespace($paramHashRef); $err = &check_server_input( $self, $paramHashRef, $id ); return $err; } sub check_server_input { my $self = shift; my $paramHashRef = shift; my $id = shift; my $sep = "__NEWLINE__"; # the line separator sub that with \n in the .ep javascript my $err = ''; my $errorCSVLineDelim = ''; # First, check permissions if ( !&is_oper($self) ) { $err .= "You do not have enough privileges to modify this." . $sep; if ( defined( $paramHashRef->{'csv_line_number'} ) ) { $err = '</li><li>' . $errorCSVLineDelim . '[LINE #:' . $paramHashRef->{'csv_line_number'} . ']: ' . $err . '\n'; } return $err; } # then, check the mandatory parameters for 'existence'. The error may be a bit cryptic to the user, but # I don't want to write too much code around it. foreach my $param (qw/host_name domain_name ip_address interface_name ip_netmask ip_gateway interface_mtu cdn cachegroup type profile offline_reason/) { #print "$param -> " . $paramHashRef->{$param} . "\n"; if ( !defined( $paramHashRef->{$param} ) || $paramHashRef->{$param} eq "" ) { $err .= $param . " is a required field."; if ( defined( $paramHashRef->{'csv_line_number'} ) ) { $err = '</li><li>' . $errorCSVLineDelim . '[LINE #:' . $paramHashRef->{'csv_line_number'} . ']: ' . $err . '\n'; } return $err; } } # in order of the form if ( !&is_hostname( $paramHashRef->{'host_name'} ) ) { $err .= $paramHashRef->{'host_name'} . " is not a valid hostname (rfc1123)" . $sep; } my $dname = $paramHashRef->{'domain_name'}; if ( !&is_hostname($dname) ) { $err .= $dname . " is not a valid domain name (rfc1123)" . $sep; } # IP address checks foreach my $ipstr ( $paramHashRef->{'ip_address'}, $paramHashRef->{'ip_netmask'}, $paramHashRef->{'ip_gateway'}, $paramHashRef->{'ilo_ip_address'}, $paramHashRef->{'ilo_ip_netmask'}, $paramHashRef->{'ilo_ip_gateway'}, $paramHashRef->{'mgmt_ip_address'}, $paramHashRef->{'mgmt_ip_netmask'}, $paramHashRef->{'mgmt_ip_gateway'} ) { if ( !defined($ipstr) || $ipstr eq "" ) { next; } # already checked for mandatory. if ( !&is_ipaddress($ipstr) ) { $err .= $ipstr . " is not a valid IPv4 address or netmask" . $sep; } } my $ip_used = $self->db->resultset('Server') ->search( { -and => [ 'me.ip_address' => $paramHashRef->{'ip_address'}, 'profile.name' => $paramHashRef->{'profile'}, 'me.id' => { '!=' => $id } ] }, { join => [ 'profile' ] })->single(); if ( $ip_used ) { $err .= $paramHashRef->{'ip_address'} . " is already being used by a server with the same profile" . $sep; } if ( defined( $paramHashRef->{'ip_netmask'} ) && $paramHashRef->{'ip_netmask'} ne "" && !&is_netmask( $paramHashRef->{'ip_netmask'} ) ) { $err .= $paramHashRef->{'ip_netmask'} . " is not a valid netmask (I think... ;-)" . $sep; } if ( $paramHashRef->{'ilo_ip_netmask'} ne "" && !&is_netmask( $paramHashRef->{'ilo_ip_netmask'} ) ) { $err .= $paramHashRef->{'ilo_ip_netmask'} . " is not a valid netmask (I think... ;-). $sep"; } if ( $paramHashRef->{'mgmt_ip_netmask'} ne "" && !&is_netmask( $paramHashRef->{'mgmt_ip_netmask'} ) ) { $err .= $paramHashRef->{'mgmt_ip_netmask'} . " is not a valid netmask (I think... ;-). $sep"; } my $ipstr1 = $paramHashRef->{'ip_address'} . "/" . $paramHashRef->{'ip_netmask'}; my $ipstr2 = $paramHashRef->{'ip_gateway'} . "/" . $paramHashRef->{'ip_netmask'}; if ( defined( $paramHashRef->{'ip_netmask'} ) && $paramHashRef->{'ip_netmask'} ne "" && !&in_same_net( $ipstr1, $ipstr2 ) ) { $err .= $paramHashRef->{'ip_address'} . " and " . $paramHashRef->{'ip_gateway'} . " are not in same network" . $sep; } if ( defined( $paramHashRef->{'ip6_address'} ) && $paramHashRef->{'ip6_address'} ne "" ) { my $ip6_used = $self->db->resultset('Server') ->search( { -and => [ 'me.ip6_address' => $paramHashRef->{'ip6_address'}, 'profile.name' => $paramHashRef->{'profile'}, 'me.id' => { '!=' => $id } ] }, { join => [ 'profile' ] })->single(); if ( $ip6_used ) { $err .= $paramHashRef->{'ip6_address'} . " is already being used by a server with the same profile" . $sep; } } if ( ( defined( $paramHashRef->{'ip6_address'} ) && $paramHashRef->{'ip6_address'} ne "" ) || ( defined( $paramHashRef->{'ip6_gateway'} ) && $paramHashRef->{'ip6_gateway'} ne "" ) ) { if ( !&is_ip6address( $paramHashRef->{'ip6_address'} ) ) { $err .= "Address " . $paramHashRef->{'ip6_address'} . " is not a valid IPv6 address " . $sep; } if ( !&is_ip6address( $paramHashRef->{'ip6_gateway'} ) ) { $err .= "Gateway " . $paramHashRef->{'ip6_gateway'} . " is not a valid IPv6 address " . $sep; } } $ipstr1 = $paramHashRef->{'ilo_ip_address'} . "/" . $paramHashRef->{'ilo_ip_netmask'}; $ipstr2 = $paramHashRef->{'ilo_ip_gateway'} . "/" . $paramHashRef->{'ilo_ip_netmask'}; if ( $paramHashRef->{'ilo_ip_gateway'} ne "" && !&in_same_net( $ipstr1, $ipstr2 ) ) { $err .= $paramHashRef->{'ilo_ip_address'} . " and " . $paramHashRef->{'ilo_ip_gateway'} . " are not in same network" . $sep; } if ( defined( $paramHashRef->{'mgmt_ip_address'} ) ) { $ipstr1 = $paramHashRef->{'mgmt_ip_address'} . "/" . $paramHashRef->{'mgmt_ip_netmask'}; $ipstr2 = $paramHashRef->{'mgmt_ip_gateway'} . "/" . $paramHashRef->{'mgmt_ip_netmask'}; if ( $paramHashRef->{'mgmt_ip_gateway'} ne "" && !&in_same_net( $ipstr1, $ipstr2 ) ) { $err .= $paramHashRef->{'mgmt_ip_address'} . " and " . $paramHashRef->{'mgmt_ip_gateway'} . " are not in same network" . $sep; } } if ( defined( $paramHashRef->{'tcp_port'} ) && $paramHashRef->{'tcp_port'} !~ /\d+/ ) { $err .= $paramHashRef->{'tcp_port'} . " is not a valid tcp port" . $sep; } if ( defined( $paramHashRef->{'https_port'} ) && $paramHashRef->{'https_port'} ne "" && $paramHashRef->{'https_port'} !~ /\d+/ ) { print("https_port: " . defined( $paramHashRef->{'https_port'} ) . "\n"); $err .= $paramHashRef->{'https_port'} . " is not a valid https port" . $sep; } # RFC5952 checks (lc) if ( defined( $paramHashRef->{'csv_line_number'} ) && length($err) > 0 ) { $err = '</li><li>' . $errorCSVLineDelim . '[LINE #:' . $paramHashRef->{'csv_line_number'} . ']: ' . $err . '\n'; } my $profile = $self->db->resultset('Profile')->search( { 'me.id' => $paramHashRef->{'profile'}}, { prefetch => ['cdn'] } )->single(); my $cdn = $self->db->resultset('Cdn')->search( { 'me.id' => $paramHashRef->{'cdn'} } )->single(); if ( !defined($profile->cdn) ) { $err .= "the " . $paramHashRef->{'profile'} . " profile is not in the " . $cdn->name . " CDN." . $sep; } elsif ( $profile->cdn->id != $cdn->id ) { $err .= "the " . $paramHashRef->{'profile'} . " profile is not in the " . $cdn->name . " CDN." . $sep; } return $err; } # Update sub update { my $self = shift; my $paramHashRef = shift; #=== # foreach my $f ($self->param) { # print $f . " => " . $self->param($f) . "\n"; # } #=== my $server_status; if ( $self->param('status') =~ /\d+/ ) { $server_status = $self->db->resultset('Status')->search( { id => $self->param('status') } )->get_column('name')->single(); } else { $server_status = $self->param('status'); } my $offline_reason = &cgi_params_to_param_hash_ref($self)->{'offline_reason'}; if ($server_status ne "OFFLINE" && $server_status ne "ADMIN_DOWN") { $self->param(offline_reason => "N/A"); # this will satisfy the UI's requirement of offline reason if not offline or admin_down } else { if (defined($offline_reason) && $offline_reason ne "") { my $user=$self->current_user()->{username}; if ($offline_reason !~ /^${user}: /) { $self->param(offline_reason => $user . ": " . $offline_reason); } } } if ( !defined( $paramHashRef->{'csv_line_number'} ) ) { $paramHashRef = &cgi_params_to_param_hash_ref($self); } my $id = $paramHashRef->{'id'}; $paramHashRef = &trim_whitespace($paramHashRef); my $err = &check_server_input_cgi($self, $id); if ( defined($err) && length($err) > 0 ) { $self->flash( alertmsg => "update(): " . $err ); } else { # get resultset for original and one to be updated. Use to examine diffs to propagate the effects of the change. my $org_server = $self->db->resultset('Server')->search( { 'me.id' => $id }, { prefetch => 'cdn' } )->single(); my $update = $self->db->resultset('Server')->search( { 'me.id' => $id }, { prefetch => 'cdn' } )->single(); $update->update( { host_name => $paramHashRef->{'host_name'}, domain_name => $paramHashRef->{'domain_name'}, tcp_port => $paramHashRef->{'tcp_port'}, https_port => $paramHashRef->{'https_port'}, interface_name => $paramHashRef->{'interface_name'}, ip_address => $paramHashRef->{'ip_address'}, ip_netmask => $paramHashRef->{'ip_netmask'}, ip_gateway => $paramHashRef->{'ip_gateway'}, ip6_address => $self->paramAsScalar( 'ip6_address', undef ), ip6_gateway => $paramHashRef->{'ip6_gateway'}, interface_mtu => $paramHashRef->{'interface_mtu'}, cdn_id => $paramHashRef->{'cdn'}, cachegroup => $paramHashRef->{'cachegroup'}, phys_location => $paramHashRef->{'phys_location'}, guid => $paramHashRef->{'guid'}, rack => $paramHashRef->{'rack'}, type => $paramHashRef->{'type'}, status => $paramHashRef->{'status'}, offline_reason => $paramHashRef->{'offline_reason'}, profile => $paramHashRef->{'profile'}, mgmt_ip_address => $paramHashRef->{'mgmt_ip_address'}, mgmt_ip_netmask => $paramHashRef->{'mgmt_ip_netmask'}, mgmt_ip_gateway => $paramHashRef->{'mgmt_ip_gateway'}, ilo_ip_address => $paramHashRef->{'ilo_ip_address'}, ilo_ip_netmask => $paramHashRef->{'ilo_ip_netmask'}, ilo_ip_gateway => $paramHashRef->{'ilo_ip_gateway'}, ilo_username => $paramHashRef->{'ilo_username'}, ilo_password => $paramHashRef->{'ilo_password'}, router_host_name => $paramHashRef->{'router_host_name'}, router_port_name => $paramHashRef->{'router_port_name'}, } ); $update->update(); if ( $org_server->profile->id != $update->profile->id ) { my $org_cdn_name = $org_server->cdn->name; my $upd_cdn_name = $update->cdn->name; if ( $upd_cdn_name ne $org_cdn_name ) { my $delete = $self->db->resultset('DeliveryserviceServer')->search( { server => $id } ); $delete->delete(); &log( $self, $self->param('host_name') . " profile change assigns server to new CDN - deleting all DS assignments", "UICHANGE" ); $self->flash( alertmsg => "update(): CDN change - all delivery service assignments have been deleted." ); } if ( $org_server->type->id != $update->type->id ) { my $delete = $self->db->resultset('DeliveryserviceServer')->search( { server => $id } ); $delete->delete(); &log( $self, $self->param('host_name') . " profile change changes cache type - deleting all DS assignments", "UICHANGE" ); $self->flash( alertmsg => "update(): Type change - all delivery service assignments have been deleted." ); } } if ( $org_server->type->id != $update->type->id ) { # server type changed: servercheck entry required for EDGE and MID, but not others. Add or remove servercheck entry accordingly my @types; push( @types, &type_ids( $self, 'EDGE%', 'server' ) ); push( @types, &type_ids( $self, 'MID%', 'server' ) ); my %need_servercheck = map { $_ => 1 } @types; my $newtype_id = $update->type->id; my $servercheck = $self->db->resultset('Servercheck')->search( { server => $id } ); if ( $servercheck != 0 && !$need_servercheck{$newtype_id} ) { # servercheck entry found but not needed -- delete it $servercheck->delete(); &log( $self, $self->param('host_name') . " cache type change - deleting servercheck", "UICHANGE" ); } elsif ( $servercheck == 0 && $need_servercheck{$newtype_id} ) { # servercheck entry not found but needed -- insert it $servercheck = $self->db->resultset('Servercheck')->create( { server => $id } ); $servercheck->insert(); &log( $self, $self->param('host_name') . " cache type changed - adding servercheck", "UICHANGE" ); } } # creates the change log entry string which includes the new values for server properties that have changed (i.e. host_name->foo-bar) my $lstring = "Update server " . $self->param('host_name') . " "; foreach my $col ( keys %{ $org_server->{_column_data} } ) { if ( defined( $self->param($col) ) && $self->param($col) ne ( $org_server->{_column_data}->{$col} // "" ) ) { if ( $col eq 'ilo_password' || $col eq 'xmpp_passwd' ) { $lstring .= $col . "-> ***********"; } else { $lstring .= $col . "->" . $self->param($col) . " "; } } } # if the update has failed, we don't even get here, we go to the exception page. &log( $self, $lstring, "UICHANGE" ); } # $self->flash( alertmsg => "Success!" ); my $referer = $self->req->headers->header('referer'); return $self->redirect_to($referer); } sub updatestatus { my $self = shift; my $id = $self->param('id'); my $status = $self->param('status'); my $offline_reason = $self->param('offlineReason'); my $statstring = undef; if ( $status !~ /^\d$/ ) { # if it is a string like "REPORTED", look up the id in the db. $statstring = $status; $status = $self->db->resultset('Status')->search( { name => $statstring } )->get_column('id')->single(); } else { $statstring = $self->db->resultset('Status')->search( { id => $status } )->get_column('name')->single(); } my $update = $self->set_serverstatus( $id, $status, $offline_reason ); my $fqdn = $update->host_name . "." . $update->domain_name; my $lstring = "Update server $fqdn new status = $statstring [" . qq/$offline_reason/ . "]"; &log( $self, qq/$lstring/, "UICHANGE" ); my $referer = $self->req->headers->header('referer'); return $self->redirect_to($referer); } sub set_serverstatus { my $self = shift; # instead of using $self->param, grab method arguments due to the fact that # we can't use :status as a placeholder in our rest call -jse my $id = shift; my $status = shift; my $offline_reason = shift; my $update = $self->db->resultset('Server')->find( { id => $id } ); $update->update( { status => $status, offline_reason => $offline_reason } ); return ($update); } sub cgi_params_to_param_hash_ref { my $self = shift; my $paramHashRef = {}; foreach my $requiredParam ( qw/host_name domain_name ip_address interface_name ip_netmask ip_gateway interface_mtu cdn cachegroup type profile phys_location offline_reason/) { $paramHashRef->{$requiredParam} = $self->param($requiredParam); } foreach my $optionalParam ( qw/ilo_ip_address ilo_ip_netmask ilo_ip_gateway mgmt_ip_address mgmt_ip_netmask mgmt_ip_gateway ip6_address ip6_gateway tcp_port https_port ilo_username ilo_password router_host_name router_port_name status rack guid id/ ) { $paramHashRef->{$optionalParam} = $self->param($optionalParam); } return $paramHashRef; } # Create sub create { my $self = shift; my $paramHashRef = shift; if ( !defined( $paramHashRef->{'csv_line_number'} ) ) { $paramHashRef = &cgi_params_to_param_hash_ref($self); } return $self->redirect_to("/modify_error") if !&is_oper($self); my $new_id = -1; my $err = ''; if ( !defined( $paramHashRef->{'csv_line_number'} ) ) { $err = &check_server_input_cgi($self); } $paramHashRef = &trim_whitespace($paramHashRef); my $xmpp_passwd = "BOOGER"; if ( defined($err) && length($err) > 0 ) { $self->flash( alertmsg => "create(): [" . length($err) . "] " . $err ); } else { my $insert; if ( defined( $paramHashRef->{'ip6_address'} ) && $paramHashRef->{'ip6_address'} ne "" ) { $insert = $self->db->resultset('Server')->create( { host_name => $paramHashRef->{'host_name'}, domain_name => $paramHashRef->{'domain_name'}, tcp_port => $paramHashRef->{'tcp_port'}, https_port => $paramHashRef->{'https_port'}, xmpp_id => $paramHashRef->{'host_name'}, # TODO JvD remove me later. xmpp_passwd => $xmpp_passwd, interface_name => $paramHashRef->{'interface_name'}, ip_address => $paramHashRef->{'ip_address'}, ip_netmask => $paramHashRef->{'ip_netmask'}, ip_gateway => $paramHashRef->{'ip_gateway'}, ip6_address => $paramHashRef->{'ip6_address'}, ip6_gateway => $paramHashRef->{'ip6_gateway'}, interface_mtu => $paramHashRef->{'interface_mtu'}, cdn_id => $paramHashRef->{'cdn'}, cachegroup => $paramHashRef->{'cachegroup'}, phys_location => $paramHashRef->{'phys_location'}, guid => $paramHashRef->{'guid'}, rack => $paramHashRef->{'rack'}, type => $paramHashRef->{'type'}, status => &admin_status_id( $self, "OFFLINE" ), offline_reason => "Newly created", profile => $paramHashRef->{'profile'}, mgmt_ip_address => $paramHashRef->{'mgmt_ip_address'}, mgmt_ip_netmask => $paramHashRef->{'mgmt_ip_netmask'}, mgmt_ip_gateway => $paramHashRef->{'mgmt_ip_gateway'}, ilo_ip_address => $paramHashRef->{'ilo_ip_address'}, ilo_ip_netmask => $paramHashRef->{'ilo_ip_netmask'}, ilo_ip_gateway => $paramHashRef->{'ilo_ip_gateway'}, ilo_username => $paramHashRef->{'ilo_username'}, ilo_password => $paramHashRef->{'ilo_password'}, router_host_name => $paramHashRef->{'router_host_name'}, router_port_name => $paramHashRef->{'router_port_name'}, } ); } else { $insert = $self->db->resultset('Server')->create( { host_name => $paramHashRef->{'host_name'}, domain_name => $paramHashRef->{'domain_name'}, tcp_port => $paramHashRef->{'tcp_port'}, https_port => $paramHashRef->{'https_port'}, xmpp_id => $paramHashRef->{'host_name'}, # TODO JvD remove me later. xmpp_passwd => $xmpp_passwd, interface_name => $paramHashRef->{'interface_name'}, ip_address => $paramHashRef->{'ip_address'}, ip_netmask => $paramHashRef->{'ip_netmask'}, ip_gateway => $paramHashRef->{'ip_gateway'}, interface_mtu => $paramHashRef->{'interface_mtu'}, cdn_id => $paramHashRef->{'cdn'}, cachegroup => $paramHashRef->{'cachegroup'}, phys_location => $paramHashRef->{'phys_location'}, guid => $paramHashRef->{'guid'}, rack => $paramHashRef->{'rack'}, type => $paramHashRef->{'type'}, status => &admin_status_id( $self, "OFFLINE" ), offline_reason => "Newly created", profile => $paramHashRef->{'profile'}, mgmt_ip_address => $paramHashRef->{'mgmt_ip_address'}, mgmt_ip_netmask => $paramHashRef->{'mgmt_ip_netmask'}, mgmt_ip_gateway => $paramHashRef->{'mgmt_ip_gateway'}, ilo_ip_address => $paramHashRef->{'ilo_ip_address'}, ilo_ip_netmask => $paramHashRef->{'ilo_ip_netmask'}, ilo_ip_gateway => $paramHashRef->{'ilo_ip_gateway'}, ilo_username => $paramHashRef->{'ilo_username'}, ilo_password => $paramHashRef->{'ilo_password'}, router_host_name => $paramHashRef->{'router_host_name'}, router_port_name => $paramHashRef->{'router_port_name'}, } ); } $insert->insert(); $new_id = $insert->id; if ( scalar( grep { $paramHashRef->{'type'} eq $_ } &type_ids( $self, 'EDGE%', 'server' ) ) || scalar( grep { $paramHashRef->{'type'} eq $_ } &type_ids( $self, 'MID%', 'server' ) ) ) { $insert = $self->db->resultset('Servercheck')->create( { server => $new_id, } ); $insert->insert(); } # if the insert has failed, we don't even get here, we go to the exception page. &log( $self, "Create server with hostname:" . $paramHashRef->{'host_name'}, "UICHANGE" ); } if ( !defined( $paramHashRef->{'csv_line_number'} ) ) { if ( $new_id == -1 ) { my $referer = $self->req->headers->header('referer'); my $qstring = "?"; my @params = $self->param; foreach my $field (@params) { #print ">". $self->param($field) . "<\n"; if ( $self->param($field) ne "" ) { $qstring .= "$field=" . $self->param($field) . "\&"; } } if ( defined($referer) ) { chop($qstring); my $stripped = ( split( /\?/, $referer ) )[0]; return $self->redirect_to( $stripped . $qstring ); } else { return $self->render( text => "ERR = " . $err, layout => undef ); # for testing - $referer is not defined there. } } else { $self->flash( alertmsg => "Success!" ); return $self->redirect_to("/server/$new_id/view"); } } } # for the add server view sub add { my $self = shift; my $default_port = 80; my $default_https_port = 443; $self->stash( fbox_layout => 1, default_tcp_port => $default_port, default_https_port => $default_https_port, ); my @params = $self->param; foreach my $field (@params) { $self->stash( $field => $self->param($field) ); } } sub rest_update_server_status { my $self = shift; my $response; my $host_name = $self->param("name"); my $status = $self->param("state"); $response->{result} = "FAILED"; if ( &is_admin($self) ) { if ( defined($host_name) && defined($status) ) { my $row = $self->db->resultset("Server")->search( { host_name => $host_name } )->single; if ( defined($row) && defined( $row->id ) ) { my $status_id = UI::Status::is_valid_status( $self, $status ); if ($status_id) { $self->set_serverstatus( $row->id, $status_id ); $response->{result} = "SUCCESS"; $response->{message} = "Successfully set status of $host_name to $status"; my $fqdn = $row->host_name . "." . $row->domain_name; my $lstring = "Update server $fqdn status=$status"; &log( $self, $lstring, "APICHANGE" ); } else { $response->{message} = "Status $status is invalid"; } } else { $response->{message} = "Unable to find server ID for $host_name"; } } else { if ( !defined($host_name) ) { $response->{message} = "Hostname is undefined"; } elsif ( !defined($status) ) { $response->{message} = "Status is undefined"; } else { $response->{message} = "Insufficient data to proceed"; } } } else { $response->{message} = "You must be an admin to perform this function"; } $self->render( json => $response ); } sub get_server_status { my $self = shift; my $host_name = $self->param("name"); my $response = {}; if ( &is_admin($self) && defined($host_name) ) { my $row = $self->db->resultset("Server")->search( { host_name => $host_name } )->single; if ( defined($row) && defined( $row->id ) ) { $response->{status} = $row->status->name; } } $self->render( json => $response ); } sub readupdate { my $self = shift; my @data; my $host_name = $self->param("host_name"); my $rs_servers; my %parent_pending = (); my %parent_reval_pending = (); if ( $host_name =~ m/^all$/ ) { $rs_servers = $self->db->resultset("Server")->search(undef, { prefetch => [ 'type', 'cachegroup' ] } ); } else { $rs_servers = $self->db->resultset("Server")->search( { host_name => $host_name }, { prefetch => [ 'type', 'cachegroup' ] } ); my $count = $rs_servers->count(); if ( $count > 0 ) { if ( $rs_servers->single->type->name =~ m/^EDGE/ ) { my $parent_cg = $self->db->resultset('Cachegroup')->search( { id => $rs_servers->single->cachegroup->id } )->get_column('parent_cachegroup_id')->single; my $rs_parents = $self->db->resultset('Server')->search( { -and => [ cachegroup => $parent_cg, cdn_id => $rs_servers->single->cdn_id ] }, { prefetch => [ 'status'] } ); while ( my $prow = $rs_parents->next ) { if ( $prow->upd_pending == 1 && $prow->status->name ne "OFFLINE" ) { $parent_pending{ $rs_servers->single->host_name } = 1; } if ( $prow->reval_pending == 1 && $prow->status->name ne "OFFLINE" ) { $parent_reval_pending{ $rs_servers->single->host_name } = 1; } } } } } my $use_reval_pending = $self->db->resultset('Parameter')->search( { -and => [ 'name' => 'use_reval_pending', 'config_file' => 'global' ] } )->get_column('value')->single; while ( my $row = $rs_servers->next ) { my $parent_pending_flag = $parent_pending{ $row->host_name } ? 1 : 0; my $parent_reval_pending_flag = $parent_reval_pending{ $row->host_name } ? 1 : 0; my $reval_pending_flag = ($use_reval_pending) && $use_reval_pending ne '0' ? \$row->reval_pending : undef; push( @data, { host_name => $row->host_name, upd_pending => \$row->upd_pending, reval_pending => $reval_pending_flag, host_id => $row->id, status => $row->status->name, parent_pending => \$parent_pending_flag, parent_reval_pending => \$parent_reval_pending_flag } ); } $self->render( json => \@data ); } sub postupdate { my $self = shift; my $updated = $self->param("updated"); my $reval_updated = $self->param("reval_updated"); my $host_name = $self->param("host_name"); &stash_role($self); # Intentionally <= 10 rather than < 20 to allow an ORT role with level 11 to post to this, but not other admin routes. if ( $self->stash('priv_level') <= 10 ) { $self->render( text => "Forbidden", status => 403, layout => undef ); return; } if ( !defined($updated) ) { $self->render( text => "Failed request. Must provide updated status", status => 400, layout => undef ); return; } # resolve server id my $serverid = $self->db->resultset("Server")->search( { host_name => $host_name } )->get_column('id')->single; if ( !defined $serverid ) { $self->render( text => "Failed request. Unknown server", status => 404, layout => undef ); return; } my $update_server = $self->db->resultset('Server')->search( { id => $serverid } ); my $use_reval_pending = $self->db->resultset('Parameter')->search( { -and => [ 'name' => 'use_reval_pending', 'config_file' => 'global' ] } )->get_column('value')->single; #Parameters don't have boolean options at this time, so we're going to compare against the default string value of 0. if ( defined($use_reval_pending) && $use_reval_pending ne '0' && defined($reval_updated) ) { $update_server->update( { reval_pending => $reval_updated, upd_pending => $updated } ); } else { $update_server->update( { upd_pending => $updated } ); } $self->render( text => "Success", layout=>undef); } sub postupdatequeue { my $self = shift; my $setqueue = $self->param("setqueue"); my $status = $self->param("status"); my $host = $self->param("id"); my $cdn = $self->param("cdn"); my $cachegroup = $self->param("cachegroup"); my $wording = ( $setqueue == 1 ) ? "Queue Updates" : "Unqueue Updates"; if ( !&is_admin($self) && !&is_oper($self) ) { $self->flash( alertmsg => "You must be an ADMIN to perform this operation!" ); return; } if ( defined($host) ) { my $update; my $message; if ( $host eq "all" ) { $update = $self->db->resultset('Server')->search(undef); $message = "all servers"; } elsif (defined($status)) { my $server = $self->db->resultset('Server')->search( { id => $host, } )->single(); my @edge_cache_groups = $self->db->resultset('Cachegroup')->search( { parent_cachegroup_id => $server->cachegroup->id } )->all(); my @cg_ids = map { $_->id } @edge_cache_groups; $update = $self->db->resultset('Server')->search( { cachegroup => { -in => \@cg_ids }, cdn_id => $server->cdn_id } ); $message = "children of " . $server->host_name . " in the following cachegroups: " . join( ", ", map { $_->name } @edge_cache_groups ); } else { $update = $self->db->resultset('Server')->search( { id => $host } ); $message = $host; } $update->update( { upd_pending => $setqueue } ); &log( $self, "Flip Update bit ($wording) for " . $message, "UICHANGE" ); } elsif ( defined($cdn) && defined($cachegroup) ) { my @profiles; if ( $cdn ne "all" ) { @profiles = $self->db->resultset('Server')->search( { 'cdn.name' => $cdn }, { prefetch => 'cdn', select => 'me.profile', distinct => 1 } )->get_column('profile')->all(); } else { @profiles = $self->db->resultset('Profile')->search(undef)->get_column('id')->all; } my @cachegroups; if ( $cachegroup ne "all" ) { @cachegroups = $self->db->resultset('Cachegroup')->search( { name => $cachegroup } )->get_column('id')->all; } else { @cachegroups = $self->db->resultset('Cachegroup')->search(undef)->get_column('id')->all; } my $update = $self->db->resultset('Server')->search( { -and => [ cachegroup => { -in => \@cachegroups }, profile => { -in => \@profiles } ] } ); if ( $update->count() > 0 ) { $update->update( { upd_pending => $setqueue } ); $self->app->log->debug("Flip Update bit ($wording) for servers in CDN: $cdn, Cachegroup: $cachegroup"); &log( $self, "Flip Update bit ($wording) for servers in CDN:" . $cdn . " cachegroup:" . $cachegroup, "UICHANGE" ); } else { $self->app->log->debug("No Queue Updates for servers in CDN: $cdn, Cachegroup: $cachegroup"); } } $self->redirect_to('/tools/queue_updates'); } 1;
rscrimojr/incubator-trafficcontrol
traffic_ops/app/lib/UI/Server.pm
Perl
apache-2.0
39,109
package DDG::Goodie::CalendarToday; # ABSTRACT: Print calendar of current / given month and highlight (to)day use strict; use DDG::Goodie; use DateTime; use Try::Tiny; use URI::Escape::XS qw(encodeURIComponent); use Text::Trim; with 'DDG::GoodieRole::Dates'; zci answer_type => 'calendar'; zci is_cached => 0; primary_example_queries "calendar"; secondary_example_queries "calendar november", "calendar next november", "calendar november 2015", "cal 29 nov 1980", "cal 29.11.1980", "cal 1980-11-29"; description "Print calendar of current / given month and highlight (to)day"; name "Calendar Today"; code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/CalendarToday.pm'; category "dates"; topics "everyday"; attribution email => ['webmaster@quovadit.org', 'webmaster@quovadit.org']; triggers startend => 'calendar', 'cal'; # define variables my @weekDays = ("S", "M", "T", "W", "T", "F", "S"); my $filler_words_regex = qr/(?:\b(?:on|of|for|the|a)\b)/; my $datestring_regex = datestring_regex(); my $formatted_datestring_regex = formatted_datestring_regex(); my $relative_dates_regex = relative_dates_regex(); handle remainder => sub { my $query = $_; my $date_object = DateTime->now; my ($currentDay, $currentMonth, $currentYear) = ($date_object->day(), $date_object->month(), $date_object->year()); my $highlightDay = 0; # Initialized, but won't match, by default. $query =~ s/$filler_words_regex//g; # Remove filler words. $query =~ s/\s{2,}/ /g; # Tighten up any extra spaces we may have left. $query =~ s/'s//g; # Remove 's for possessives. $query = trim $query; # Trim outside spaces. if ($query) { my ($date_string) = $query =~ qr#^($datestring_regex)$#i; # Extract any datestring from the query. $date_object = parse_datestring_to_date($date_string); return unless $date_object; # Decide if a specific day should be highlighted. If the query was not precise, eg "Nov 2009", # we can't hightlight. OTOH, if they specified a date, we highlight. Relative dates like "next # year", or "last week" exactly specify a date so they get highlighted also. $highlightDay = $date_object->day() if ($query =~ $formatted_datestring_regex || $query =~ $relative_dates_regex); } # Highlight today if it's this month and no other day was chosen. $highlightDay ||= $currentDay if (($date_object->year() eq $currentYear) && ($date_object->month() eq $currentMonth)); my $the_year = $date_object->year(); my $the_month = $date_object->month(); # return calendar my $start = parse_datestring_to_date($the_year . "-" . $the_month . "-1"); return format_result({ first_day => $start, first_day_num => $start->day_of_week() % 7, # 0=Sunday last_day => DateTime->last_day_of_month( year => $the_year, month => $the_month, )->day(), highlight => $highlightDay, }); }; # prepare text and html to be returned sub format_result { my $args = shift; my ($firstDay, $first_day_num, $lastDay, $highlightDay) = @{$args}{qw(first_day first_day_num last_day highlight)}; my $previous = $firstDay->clone->subtract(months => 1); my $next = $firstDay->clone->add(months => 1); # Print heading my $rText = "\n"; my $rHtml = '<table class="calendar"><tr><th colspan="7"><span class="circle t_left"><a href="/?q=' . encodeURIComponent('calendar ' . $previous->strftime("%B %Y")) . '"><span class="ddgsi ddgsi-arrow-left"></span></a></span><span class="calendar__header"><b>'; $rHtml .= $firstDay->strftime("%B %Y").'</b></span><span class="circle t_right"><a href="/?q=' . encodeURIComponent('calendar ' . $next->strftime("%B %Y")) . '"><span class="ddgsi ddgsi-arrow-right"></span></a></span></th>'; $rHtml .= '</tr><tr>'; for my $dayHeading (@weekDays) { $rText .= $dayHeading . ' '; $rHtml .= '<th>' . $dayHeading . '</th>'; } $rText .= " ".$firstDay->strftime("%B %Y")."\n"; $rHtml .= "</tr><tr>"; # Skip to the first day of the week $rText .= " " x $first_day_num; $rHtml .= "<td>&nbsp;</td>" x $first_day_num; my $weekDayNum = $first_day_num; # Printing the month for (my $dayNum = 1; $dayNum <= $lastDay; $dayNum++) { my $padded_date = sprintf('%2s', $dayNum); if ($dayNum == $highlightDay) { $rText .= '|' . $padded_date . '|'; $rHtml .= '<td><span class="calendar__today circle">' . $dayNum . '</span></td>'; } else { $rText .= ' ' . $padded_date . ' '; $rHtml .= "<td>$dayNum</td>"; } # next row after 7 cells $weekDayNum++; if ($weekDayNum == 7) { $weekDayNum = 0; $rText .= "\n"; $rHtml .= "</tr><tr>"; } } $rText .= "\n"; $rHtml .="</tr></table>"; return $rText, html => $rHtml; } 1;
Faiz7412/zeroclickinfo-goodies
lib/DDG/Goodie/CalendarToday.pm
Perl
apache-2.0
5,290
# 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 debian/tzdata/northamerica. Olson data version 2008c # # Do not edit this file directly. # package DateTime::TimeZone::America::Chicago; use strict; use Class::Singleton; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::Chicago::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, 59418036000, DateTime::TimeZone::NEG_INFINITY, 59418014964, -21036, 0, 'LMT' ], [ 59418036000, 60502406400, 59418014400, 60502384800, -21600, 0, 'CT' ], [ 60502406400, 60520546800, 60502388400, 60520528800, -18000, 1, 'CDT' ], [ 60520546800, 60533856000, 60520525200, 60533834400, -21600, 0, 'CST' ], [ 60533856000, 60551996400, 60533838000, 60551978400, -18000, 1, 'CDT' ], [ 60551996400, 60557781600, 60551974800, 60557760000, -21600, 0, 'CST' ], [ 60557781600, 60571958400, 60557760000, 60571936800, -21600, 0, 'CT' ], [ 60571958400, 60584050800, 60571940400, 60584032800, -18000, 1, 'CDT' ], [ 60584050800, 60596755200, 60584029200, 60596733600, -21600, 0, 'CST' ], [ 60596755200, 60615500400, 60596737200, 60615482400, -18000, 1, 'CDT' ], [ 60615500400, 60631228800, 60615478800, 60631207200, -21600, 0, 'CST' ], [ 60631228800, 60643926000, 60631210800, 60643908000, -18000, 1, 'CDT' ], [ 60643926000, 60662678400, 60643904400, 60662656800, -21600, 0, 'CST' ], [ 60662678400, 60675980400, 60662660400, 60675962400, -18000, 1, 'CDT' ], [ 60675980400, 60694128000, 60675958800, 60694106400, -21600, 0, 'CST' ], [ 60694128000, 60707430000, 60694110000, 60707412000, -18000, 1, 'CDT' ], [ 60707430000, 60725577600, 60707408400, 60725556000, -21600, 0, 'CST' ], [ 60725577600, 60738879600, 60725559600, 60738861600, -18000, 1, 'CDT' ], [ 60738879600, 60757027200, 60738858000, 60757005600, -21600, 0, 'CST' ], [ 60757027200, 60770329200, 60757009200, 60770311200, -18000, 1, 'CDT' ], [ 60770329200, 60788476800, 60770307600, 60788455200, -21600, 0, 'CST' ], [ 60788476800, 60801778800, 60788458800, 60801760800, -18000, 1, 'CDT' ], [ 60801778800, 60820531200, 60801757200, 60820509600, -21600, 0, 'CST' ], [ 60820531200, 60833833200, 60820513200, 60833815200, -18000, 1, 'CDT' ], [ 60833833200, 60851980800, 60833811600, 60851959200, -21600, 0, 'CST' ], [ 60851980800, 60865282800, 60851962800, 60865264800, -18000, 1, 'CDT' ], [ 60865282800, 60883430400, 60865261200, 60883408800, -21600, 0, 'CST' ], [ 60883430400, 60896732400, 60883412400, 60896714400, -18000, 1, 'CDT' ], [ 60896732400, 60914880000, 60896710800, 60914858400, -21600, 0, 'CST' ], [ 60914880000, 60928182000, 60914862000, 60928164000, -18000, 1, 'CDT' ], [ 60928182000, 60946329600, 60928160400, 60946308000, -21600, 0, 'CST' ], [ 60946329600, 60959631600, 60946311600, 60959613600, -18000, 1, 'CDT' ], [ 60959631600, 60978384000, 60959610000, 60978362400, -21600, 0, 'CST' ], [ 60978384000, 60991081200, 60978366000, 60991063200, -18000, 1, 'CDT' ], [ 60991081200, 61009833600, 60991059600, 61009812000, -21600, 0, 'CST' ], [ 61009833600, 61023135600, 61009815600, 61023117600, -18000, 1, 'CDT' ], [ 61023135600, 61041283200, 61023114000, 61041261600, -21600, 0, 'CST' ], [ 61041283200, 61054585200, 61041265200, 61054567200, -18000, 1, 'CDT' ], [ 61054585200, 61067894400, 61054563600, 61067872800, -21600, 0, 'CST' ], [ 61067894400, 61090268400, 61067876400, 61090250400, -18000, 0, 'EST' ], [ 61090268400, 61104182400, 61090246800, 61104160800, -21600, 0, 'CST' ], [ 61104182400, 61117484400, 61104164400, 61117466400, -18000, 1, 'CDT' ], [ 61117484400, 61135632000, 61117462800, 61135610400, -21600, 0, 'CST' ], [ 61135632000, 61148934000, 61135614000, 61148916000, -18000, 1, 'CDT' ], [ 61148934000, 61167686400, 61148912400, 61167664800, -21600, 0, 'CST' ], [ 61167686400, 61180383600, 61167668400, 61180365600, -18000, 1, 'CDT' ], [ 61180383600, 61199136000, 61180362000, 61199114400, -21600, 0, 'CST' ], [ 61199136000, 61212438000, 61199118000, 61212420000, -18000, 1, 'CDT' ], [ 61212438000, 61230585600, 61212416400, 61230564000, -21600, 0, 'CST' ], [ 61230585600, 61243887600, 61230567600, 61243869600, -18000, 1, 'CDT' ], [ 61243887600, 61252092000, 61243866000, 61252070400, -21600, 0, 'CST' ], [ 61252092000, 61255468800, 61252070400, 61255447200, -21600, 0, 'CST' ], [ 61255468800, 61366287600, 61255450800, 61366269600, -18000, 1, 'CWT' ], [ 61366287600, 61370290800, 61366269600, 61370272800, -18000, 1, 'CPT' ], [ 61370290800, 61378322400, 61370269200, 61378300800, -21600, 0, 'CST' ], [ 61378322400, 61388438400, 61378300800, 61388416800, -21600, 0, 'CST' ], [ 61388438400, 61401740400, 61388420400, 61401722400, -18000, 1, 'CDT' ], [ 61401740400, 61419888000, 61401718800, 61419866400, -21600, 0, 'CST' ], [ 61419888000, 61433190000, 61419870000, 61433172000, -18000, 1, 'CDT' ], [ 61433190000, 61451337600, 61433168400, 61451316000, -21600, 0, 'CST' ], [ 61451337600, 61464639600, 61451319600, 61464621600, -18000, 1, 'CDT' ], [ 61464639600, 61482787200, 61464618000, 61482765600, -21600, 0, 'CST' ], [ 61482787200, 61496089200, 61482769200, 61496071200, -18000, 1, 'CDT' ], [ 61496089200, 61514841600, 61496067600, 61514820000, -21600, 0, 'CST' ], [ 61514841600, 61527538800, 61514823600, 61527520800, -18000, 1, 'CDT' ], [ 61527538800, 61546291200, 61527517200, 61546269600, -21600, 0, 'CST' ], [ 61546291200, 61559593200, 61546273200, 61559575200, -18000, 1, 'CDT' ], [ 61559593200, 61577740800, 61559571600, 61577719200, -21600, 0, 'CST' ], [ 61577740800, 61591042800, 61577722800, 61591024800, -18000, 1, 'CDT' ], [ 61591042800, 61609190400, 61591021200, 61609168800, -21600, 0, 'CST' ], [ 61609190400, 61622492400, 61609172400, 61622474400, -18000, 1, 'CDT' ], [ 61622492400, 61640640000, 61622470800, 61640618400, -21600, 0, 'CST' ], [ 61640640000, 61653942000, 61640622000, 61653924000, -18000, 1, 'CDT' ], [ 61653942000, 61672089600, 61653920400, 61672068000, -21600, 0, 'CST' ], [ 61672089600, 61688415600, 61672071600, 61688397600, -18000, 1, 'CDT' ], [ 61688415600, 61704144000, 61688394000, 61704122400, -21600, 0, 'CST' ], [ 61704144000, 61719865200, 61704126000, 61719847200, -18000, 1, 'CDT' ], [ 61719865200, 61735593600, 61719843600, 61735572000, -21600, 0, 'CST' ], [ 61735593600, 61751314800, 61735575600, 61751296800, -18000, 1, 'CDT' ], [ 61751314800, 61767043200, 61751293200, 61767021600, -21600, 0, 'CST' ], [ 61767043200, 61782764400, 61767025200, 61782746400, -18000, 1, 'CDT' ], [ 61782764400, 61798492800, 61782742800, 61798471200, -21600, 0, 'CST' ], [ 61798492800, 61814214000, 61798474800, 61814196000, -18000, 1, 'CDT' ], [ 61814214000, 61829942400, 61814192400, 61829920800, -21600, 0, 'CST' ], [ 61829942400, 61846268400, 61829924400, 61846250400, -18000, 1, 'CDT' ], [ 61846268400, 61861996800, 61846246800, 61861975200, -21600, 0, 'CST' ], [ 61861996800, 61877718000, 61861978800, 61877700000, -18000, 1, 'CDT' ], [ 61877718000, 61893446400, 61877696400, 61893424800, -21600, 0, 'CST' ], [ 61893446400, 61909167600, 61893428400, 61909149600, -18000, 1, 'CDT' ], [ 61909167600, 61924896000, 61909146000, 61924874400, -21600, 0, 'CST' ], [ 61924896000, 61940617200, 61924878000, 61940599200, -18000, 1, 'CDT' ], [ 61940617200, 61956345600, 61940595600, 61956324000, -21600, 0, 'CST' ], [ 61956345600, 61972066800, 61956327600, 61972048800, -18000, 1, 'CDT' ], [ 61972066800, 61987795200, 61972045200, 61987773600, -21600, 0, 'CST' ], [ 61987795200, 62004121200, 61987777200, 62004103200, -18000, 1, 'CDT' ], [ 62004121200, 62019244800, 62004099600, 62019223200, -21600, 0, 'CST' ], [ 62019244800, 62035570800, 62019226800, 62035552800, -18000, 1, 'CDT' ], [ 62035570800, 62041010400, 62035549200, 62040988800, -21600, 0, 'CST' ], [ 62041010400, 62051299200, 62040988800, 62051277600, -21600, 0, 'CST' ], [ 62051299200, 62067020400, 62051281200, 62067002400, -18000, 1, 'CDT' ], [ 62067020400, 62082748800, 62066998800, 62082727200, -21600, 0, 'CST' ], [ 62082748800, 62098470000, 62082730800, 62098452000, -18000, 1, 'CDT' ], [ 62098470000, 62114198400, 62098448400, 62114176800, -21600, 0, 'CST' ], [ 62114198400, 62129919600, 62114180400, 62129901600, -18000, 1, 'CDT' ], [ 62129919600, 62145648000, 62129898000, 62145626400, -21600, 0, 'CST' ], [ 62145648000, 62161369200, 62145630000, 62161351200, -18000, 1, 'CDT' ], [ 62161369200, 62177097600, 62161347600, 62177076000, -21600, 0, 'CST' ], [ 62177097600, 62193423600, 62177079600, 62193405600, -18000, 1, 'CDT' ], [ 62193423600, 62209152000, 62193402000, 62209130400, -21600, 0, 'CST' ], [ 62209152000, 62224873200, 62209134000, 62224855200, -18000, 1, 'CDT' ], [ 62224873200, 62240601600, 62224851600, 62240580000, -21600, 0, 'CST' ], [ 62240601600, 62256322800, 62240583600, 62256304800, -18000, 1, 'CDT' ], [ 62256322800, 62262374400, 62256301200, 62262352800, -21600, 0, 'CST' ], [ 62262374400, 62287772400, 62262356400, 62287754400, -18000, 1, 'CDT' ], [ 62287772400, 62298057600, 62287750800, 62298036000, -21600, 0, 'CST' ], [ 62298057600, 62319222000, 62298039600, 62319204000, -18000, 1, 'CDT' ], [ 62319222000, 62334950400, 62319200400, 62334928800, -21600, 0, 'CST' ], [ 62334950400, 62351276400, 62334932400, 62351258400, -18000, 1, 'CDT' ], [ 62351276400, 62366400000, 62351254800, 62366378400, -21600, 0, 'CST' ], [ 62366400000, 62382726000, 62366382000, 62382708000, -18000, 1, 'CDT' ], [ 62382726000, 62398454400, 62382704400, 62398432800, -21600, 0, 'CST' ], [ 62398454400, 62414175600, 62398436400, 62414157600, -18000, 1, 'CDT' ], [ 62414175600, 62429904000, 62414154000, 62429882400, -21600, 0, 'CST' ], [ 62429904000, 62445625200, 62429886000, 62445607200, -18000, 1, 'CDT' ], [ 62445625200, 62461353600, 62445603600, 62461332000, -21600, 0, 'CST' ], [ 62461353600, 62477074800, 62461335600, 62477056800, -18000, 1, 'CDT' ], [ 62477074800, 62492803200, 62477053200, 62492781600, -21600, 0, 'CST' ], [ 62492803200, 62508524400, 62492785200, 62508506400, -18000, 1, 'CDT' ], [ 62508524400, 62524252800, 62508502800, 62524231200, -21600, 0, 'CST' ], [ 62524252800, 62540578800, 62524234800, 62540560800, -18000, 1, 'CDT' ], [ 62540578800, 62555702400, 62540557200, 62555680800, -21600, 0, 'CST' ], [ 62555702400, 62572028400, 62555684400, 62572010400, -18000, 1, 'CDT' ], [ 62572028400, 62587756800, 62572006800, 62587735200, -21600, 0, 'CST' ], [ 62587756800, 62603478000, 62587738800, 62603460000, -18000, 1, 'CDT' ], [ 62603478000, 62619206400, 62603456400, 62619184800, -21600, 0, 'CST' ], [ 62619206400, 62634927600, 62619188400, 62634909600, -18000, 1, 'CDT' ], [ 62634927600, 62650656000, 62634906000, 62650634400, -21600, 0, 'CST' ], [ 62650656000, 62666377200, 62650638000, 62666359200, -18000, 1, 'CDT' ], [ 62666377200, 62680291200, 62666355600, 62680269600, -21600, 0, 'CST' ], [ 62680291200, 62697826800, 62680273200, 62697808800, -18000, 1, 'CDT' ], [ 62697826800, 62711740800, 62697805200, 62711719200, -21600, 0, 'CST' ], [ 62711740800, 62729881200, 62711722800, 62729863200, -18000, 1, 'CDT' ], [ 62729881200, 62743190400, 62729859600, 62743168800, -21600, 0, 'CST' ], [ 62743190400, 62761330800, 62743172400, 62761312800, -18000, 1, 'CDT' ], [ 62761330800, 62774640000, 62761309200, 62774618400, -21600, 0, 'CST' ], [ 62774640000, 62792780400, 62774622000, 62792762400, -18000, 1, 'CDT' ], [ 62792780400, 62806694400, 62792758800, 62806672800, -21600, 0, 'CST' ], [ 62806694400, 62824230000, 62806676400, 62824212000, -18000, 1, 'CDT' ], [ 62824230000, 62838144000, 62824208400, 62838122400, -21600, 0, 'CST' ], [ 62838144000, 62855679600, 62838126000, 62855661600, -18000, 1, 'CDT' ], [ 62855679600, 62869593600, 62855658000, 62869572000, -21600, 0, 'CST' ], [ 62869593600, 62887734000, 62869575600, 62887716000, -18000, 1, 'CDT' ], [ 62887734000, 62901043200, 62887712400, 62901021600, -21600, 0, 'CST' ], [ 62901043200, 62919183600, 62901025200, 62919165600, -18000, 1, 'CDT' ], [ 62919183600, 62932492800, 62919162000, 62932471200, -21600, 0, 'CST' ], [ 62932492800, 62950633200, 62932474800, 62950615200, -18000, 1, 'CDT' ], [ 62950633200, 62964547200, 62950611600, 62964525600, -21600, 0, 'CST' ], [ 62964547200, 62982082800, 62964529200, 62982064800, -18000, 1, 'CDT' ], [ 62982082800, 62995996800, 62982061200, 62995975200, -21600, 0, 'CST' ], [ 62995996800, 63013532400, 62995978800, 63013514400, -18000, 1, 'CDT' ], [ 63013532400, 63027446400, 63013510800, 63027424800, -21600, 0, 'CST' ], [ 63027446400, 63044982000, 63027428400, 63044964000, -18000, 1, 'CDT' ], [ 63044982000, 63058896000, 63044960400, 63058874400, -21600, 0, 'CST' ], [ 63058896000, 63077036400, 63058878000, 63077018400, -18000, 1, 'CDT' ], [ 63077036400, 63090345600, 63077014800, 63090324000, -21600, 0, 'CST' ], [ 63090345600, 63108486000, 63090327600, 63108468000, -18000, 1, 'CDT' ], [ 63108486000, 63121795200, 63108464400, 63121773600, -21600, 0, 'CST' ], [ 63121795200, 63139935600, 63121777200, 63139917600, -18000, 1, 'CDT' ], [ 63139935600, 63153849600, 63139914000, 63153828000, -21600, 0, 'CST' ], [ 63153849600, 63171385200, 63153831600, 63171367200, -18000, 1, 'CDT' ], [ 63171385200, 63185299200, 63171363600, 63185277600, -21600, 0, 'CST' ], [ 63185299200, 63202834800, 63185281200, 63202816800, -18000, 1, 'CDT' ], [ 63202834800, 63216748800, 63202813200, 63216727200, -21600, 0, 'CST' ], [ 63216748800, 63234889200, 63216730800, 63234871200, -18000, 1, 'CDT' ], [ 63234889200, 63248198400, 63234867600, 63248176800, -21600, 0, 'CST' ], [ 63248198400, 63266338800, 63248180400, 63266320800, -18000, 1, 'CDT' ], [ 63266338800, 63279648000, 63266317200, 63279626400, -21600, 0, 'CST' ], [ 63279648000, 63297788400, 63279630000, 63297770400, -18000, 1, 'CDT' ], [ 63297788400, 63309283200, 63297766800, 63309261600, -21600, 0, 'CST' ], [ 63309283200, 63329842800, 63309265200, 63329824800, -18000, 1, 'CDT' ], [ 63329842800, 63340732800, 63329821200, 63340711200, -21600, 0, 'CST' ], [ 63340732800, 63361292400, 63340714800, 63361274400, -18000, 1, 'CDT' ], [ 63361292400, 63372182400, 63361270800, 63372160800, -21600, 0, 'CST' ], [ 63372182400, 63392742000, 63372164400, 63392724000, -18000, 1, 'CDT' ], [ 63392742000, 63404236800, 63392720400, 63404215200, -21600, 0, 'CST' ], [ 63404236800, 63424796400, 63404218800, 63424778400, -18000, 1, 'CDT' ], [ 63424796400, 63435686400, 63424774800, 63435664800, -21600, 0, 'CST' ], [ 63435686400, 63456246000, 63435668400, 63456228000, -18000, 1, 'CDT' ], [ 63456246000, 63467136000, 63456224400, 63467114400, -21600, 0, 'CST' ], [ 63467136000, 63487695600, 63467118000, 63487677600, -18000, 1, 'CDT' ], [ 63487695600, 63498585600, 63487674000, 63498564000, -21600, 0, 'CST' ], [ 63498585600, 63519145200, 63498567600, 63519127200, -18000, 1, 'CDT' ], [ 63519145200, 63530035200, 63519123600, 63530013600, -21600, 0, 'CST' ], [ 63530035200, 63550594800, 63530017200, 63550576800, -18000, 1, 'CDT' ], [ 63550594800, 63561484800, 63550573200, 63561463200, -21600, 0, 'CST' ], [ 63561484800, 63582044400, 63561466800, 63582026400, -18000, 1, 'CDT' ], [ 63582044400, 63593539200, 63582022800, 63593517600, -21600, 0, 'CST' ], [ 63593539200, 63614098800, 63593521200, 63614080800, -18000, 1, 'CDT' ], [ 63614098800, 63624988800, 63614077200, 63624967200, -21600, 0, 'CST' ], [ 63624988800, 63645548400, 63624970800, 63645530400, -18000, 1, 'CDT' ], [ 63645548400, 63656438400, 63645526800, 63656416800, -21600, 0, 'CST' ], [ 63656438400, 63676998000, 63656420400, 63676980000, -18000, 1, 'CDT' ], [ 63676998000, 63687888000, 63676976400, 63687866400, -21600, 0, 'CST' ], [ 63687888000, 63708447600, 63687870000, 63708429600, -18000, 1, 'CDT' ], ]; sub olson_version { '2008c' } sub has_dst_changes { 99 } sub _max_year { 2018 } sub _new_instance { return shift->_init( @_, spans => $spans ); } sub _last_offset { -21600 } my $last_observance = bless( { 'format' => 'C%sT', 'gmtoff' => '-6:00', 'local_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 718067, 'local_rd_secs' => 0, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 718067, 'utc_rd_secs' => 0, 'utc_year' => 1968 }, 'DateTime' ), 'offset_from_std' => 0, 'offset_from_utc' => -21600, 'until' => [], 'utc_start_datetime' => bless( { 'formatter' => undef, 'local_rd_days' => 718067, 'local_rd_secs' => 21600, 'offset_modifier' => 0, 'rd_nanosecs' => 0, 'tz' => bless( { 'name' => 'floating', 'offset' => 0 }, 'DateTime::TimeZone::Floating' ), 'utc_rd_days' => 718067, 'utc_rd_secs' => 21600, 'utc_year' => 1968 }, 'DateTime' ) }, 'DateTime::TimeZone::OlsonDB::Observance' ) ; sub _last_observance { $last_observance } my $rules = [ bless( { 'at' => '2:00', 'from' => '2007', 'in' => 'Mar', 'letter' => 'D', 'name' => 'US', 'offset_from_std' => 3600, 'on' => 'Sun>=8', 'save' => '1:00', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ), bless( { 'at' => '2:00', 'from' => '2007', 'in' => 'Nov', 'letter' => 'S', 'name' => 'US', 'offset_from_std' => 0, 'on' => 'Sun>=1', 'save' => '0', 'to' => 'max', 'type' => undef }, 'DateTime::TimeZone::OlsonDB::Rule' ) ] ; sub _rules { $rules } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/DateTime/TimeZone/America/Chicago.pm
Perl
mit
19,086
#! /usr/bin/perl # Copyright (c) 1994 James Clark, 2000 Matthias Clasen # Copyright (c) 2000 Peter Nilsson # See the file COPYING for copying permission. use POSIX; # Package and version. $package = 'openjade'; $version = '1.3.3-pre1'; $package = $package; $version = $version; # be quiet, -w $prog = $0; $prog =~ s@.*/@@; $gen_c = 0; undef $opt_l; undef $opt_p; undef $opt_t; do 'getopts.pl'; &Getopts('l:p:t:'); $module = $opt_l; $pot_file = $opt_p; if (defined($opt_t)) { # don't try to read translations for English $opt_t =~ /.*en.*/ || &read_po_translations($opt_t); } $num = 0; foreach $def_file (@ARGV) { @tag_used = (); open(DEF, $def_file) || die "can't open \`$def_file': $!\n"; while (<DEF>) { chop; if (/^!cxx$/) { $gen_c = 1; next; } if (/^=/) { if (!defined($opt_p)) { $n = substr($_, 1); &error("= directive must increase message num") if ($n < $num); $num = $n; } next; } if (/^-/) { # a deleted message $num++; next; } next if /^[ ]*#/; next if /^[ ]*$/; @field = split('\+', $_, 5); &error("too few fields") if $#field < 3; if ($#field == 4 && $field[4] =~ /^%J/) { $field[3] .= '+'; $field[3] .= substr($field[4], 2); $#field = 3; } if ($field[0] eq "") { $type[$num] = ""; $argc = 0; } else { $field[0] =~ /^[IWQXE][0-9]$/ || &error("invalid first field");; $type[$num] = substr($field[0], 0, 1); $argc = int(substr($field[0], 1, 1)); } $nargs[$num] = $argc; $field[1] =~ /^[a-zA-Z_][a-zA-Z0-9_]+$/ || &error("invalid tag"); $tag[$num] = $field[1]; &error("duplicate tag $field[1]") if (!defined($opt_p) && defined($tag_used{$field[1]})); $tag_used{$field[1]} = 1; $field[2] =~ /^((ISO(\/IEC)? [0-9]+:[0-9]+ )?(([A-Z]?[0-9]+(\.[0-9]+)*(p[0-9]+)?)|(\[[0-9]+(\.[0-9]*)?\]))( (ISO(\/IEC)? [0-9]+:[0-9]+ )?(([A-Z]?[0-9]+(\.[0-9]+)*(p[0-9]+)?)|(\[[0-9]+(\.[0-9]*)?\])))*)?$/ || &error("invalid clauses field"); # push @clauses, $field[2]; $clauses[$num] = $field[2]; if ($argc == 0) { if ($field[0] ne "") { $field[3] =~ /^([^%]|%%)*$/ || &error("invalid character after %"); } } else { $field[3] =~ /^([^%]|%[%1-$argc])*$/ || &error("invalid character after %"); } $auxloc[$num] = ($#field == 4 ? "L" : ""); $message[$num] = $field[3]; $num++; if ($#field == 4) { $message2[$num] = $field[4]; $num++; } } close(DEF); if (!defined($opt_p)) { $file_base = $ARGV[0]; $file_base =~ s/\.[^.]*$//; $class = $file_base; $class =~ s|.*[\\/]||; # this is needed on Windows NT chmod 0666, "$file_base.h"; unlink("$file_base.h"); open(OUT, ">$file_base.h"); chmod 0444, "$file_base.h"; select(OUT); print <<END; // This file was automatically generated from $def_file by $prog. END print <<END if $gen_c; #ifndef ${class}_INCLUDED #define ${class}_INCLUDED 1 #ifdef __GNUG__ #pragma interface #endif END print <<END; #include <OpenSP/Message.h> #ifdef SP_NAMESPACE namespace SP_NAMESPACE { #endif struct $class { END foreach $i (0 .. $#message) { if (defined($message[$i])) { print " // $i\n"; print " static const Message"; if ($type[$i] eq "") { print "Fragment"; } else { print "Type$nargs[$i]$auxloc[$i]"; } print " $tag[$i];\n"; } } print "};\n"; print <<END if $gen_c; #ifdef SP_NAMESPACE } #endif #endif /* not ${class}_INCLUDED */ END if ($gen_c) { close(OUT); # this is needed on Windows NT chmod 0666, "$file_base.cxx"; unlink("$file_base.cxx"); open(OUT, ">$file_base.cxx"); chmod 0444, "$file_base.cxx"; select(OUT); print <<END; // This file was automatically generated from $def_file by $prog. #ifdef __GNUG__ #pragma implementation #endif #include "stylelib.h" #include "$class.h" #ifdef SP_NAMESPACE namespace SP_NAMESPACE { #endif END } if (defined($opt_l)) { print "extern MessageModule $module;\n\n"; } foreach $i (0 .. $#message) { if (defined($message[$i])) { if ($type[$i] eq "") { print "const MessageFragment ${class}::$tag[$i](\n"; } else { print "const MessageType$nargs[$i]$auxloc[$i] ${class}::$tag[$i](\n"; print "MessageType::"; if ($type[$i] eq 'I') { print 'info'; } elsif ($type[$i] eq 'W') { print 'warning'; } elsif ($type[$i] eq 'Q') { print 'quantityError'; } elsif ($type[$i] eq 'X') { print 'idrefError'; } else { print 'error'; } print ",\n"; } if (defined($opt_l)) { print "&$module,\n"; } else { print "0,\n"; } print "$i\n"; print "#ifndef SP_NO_MESSAGE_TEXT\n"; $str = $message[$i]; $str =~ s|\\|\\\\|g; $str =~ s|"|\\"|g; printf ",\"%s\"", $str; if ($clauses[$i]) { $str = $clauses[$i]; $str =~ s|\\|\\\\|g; $str =~ s|"|\\"|g; printf "\n,\"%s\"", $str; } if ($auxloc[$i]) { if ($clauses[$i] eq "") { print "\n,0"; } $str = $message2[$i + 1]; $str =~ s|\\|\\\\|g; $str =~ s|"|\\"|g; printf "\n,\"%s\"", $str; } print "\n#endif\n"; print ");\n"; } } print <<END; #ifdef SP_NAMESPACE } #endif END close(OUT); # this is needed on Windows NT chmod 0666, "$file_base.rc"; unlink("$file_base.rc"); open(OUT, ">$file_base.rc"); chmod 0444, "$file_base.rc"; select(OUT); print "STRINGTABLE\nBEGIN\n"; foreach $i (0 .. $#message) { if (defined($message[$i])) { $str = $message[$i]; if ($translation{$str}) { $str = $translation{$str}; } $str =~ s/"/""/g; printf " %d, \"%s\"\n", $i, $str; } elsif (defined($message2[$i])) { $str = $message2[$i]; $str =~ s/"/""/g; printf " %d, \"%s\"\n", $i, $str; } } print "END\n"; close(OUT); } # !opt_p } # foreach def_file if (defined($opt_p)) { # this is needed for GNU gettext chmod 0666, "$pot_file"; unlink("$pot_file"); open(OUT, ">$pot_file"); chmod 0444, "$pot_file"; select(OUT); $crdate = POSIX::strftime "%Y-%m-%d %H:%M+0000", gmtime; print <<END; # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR HOLDER # FIRST AUTHOR <EMAIL\@ADDRESS>, YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\\n" "POT-Creation-Date: $crdate\\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n" "Last-Translator: FULL NAME <EMAIL\@ADDRESS>\\n" "Language-Team: LANGUAGE <LL\@li.org>\\n" "MIME-Version:: 1.0\\n" "Content-Type: text/plain; charset=CHARSET\\n" "Content-Transfer-Encoding: ENCODING\\n" END foreach $i (0 .. $#message) { if (defined($message[$i]) && !defined($written{$message[$i]})) { next if $message[$i] eq ""; $written{$message[$i]} = 1; $str = $message[$i]; $str =~ s/"/\\"/g; printf "msgid \"%s\"\nmsgstr \"\"\n\n", $str; } elsif (defined($message2[$i]) && ! defined($written{$message2[$i]})) { $written{$message2[$i]} = 1; $str = $message2[$i]; $str =~ s/"/\\"/g; printf "msgid \"%s\"\nmsgstr \"\"\n\n", $str; } } } close(OUT); sub error { die "$def_file:$.: $_[0]\n"; } # Read a PO file with message translations. # This doesn't accept every valid PO file, but it seems to work reasonably. sub read_po_translations { my $po_in = $_[0]; open(PO_IN, "<$po_in") || die "Can't open file $po_in."; my $id = ""; my $str = ""; my $catching_string = 0; while(<PO_IN>) { if (/^\s*msgid/) { if ($catching_string) { &po_flush($id, $str); $id = ""; $str = ""; } $_ = $'; $catching_string = 1; } elsif (/^\s*msgstr/) { die "No msgid." if !$catching_string or $id; $id = $str; $str = ""; $_ = $'; } if ($catching_string) { my $in_string = 0; s/\s*//; while ($_) { if (s/^\"//) { $in_string = !$in_string; } if ($in_string) { if (s/^[^\"\\]+//) { $str .= $&; } elsif (s/^\\([ntbrf\\\"])//) { $str .= "\n" if $1 eq "n"; $str .= "\t" if $1 eq "t"; $str .= "\b" if $1 eq "b"; $str .= "\r" if $1 eq "r"; $str .= "\f" if $1 eq "f"; $str .= "\\" if $1 eq "\\"; $str .= "\"" if $1 eq "\""; } elsif (s/\\([0-9]+)//) { $str .= chr(oct($1)); } elsif (s/\\[xX]([0-9a-fA-F]+)//) { $str .= chr(hex($1)); } else { die "Invalid control sequence." if /^\\/; } } else { s/\s*//; last if /^[^"]/; } } } } if ($catching_string) { &po_flush($id, $str); } } sub po_flush { my $id = $_[0]; my $str = $_[1]; # We use a translation only if $id is non-empty (we don't include the # PO file header) and if $str is non-empty (the message is translated). if ($id && $str) { $translation{$id} = $str; } $id = ""; $str = ""; }
OS2World/DEV-UTIL-OpenJade
msggen.pl
Perl
mit
8,680
package LOCK; ## ## copied from app6:/httpd/servers/inventory/LOCK.pm ## ## changed to our format, added strict use strict; my $LOCKPATH = "/tmp"; my $VERBOSE = 1; my $MAXAGE = 30 * 60; # 30 minutes ## ## This will return a non-zero if the lock succeeeds ## sub grab_lock { my ($lockid,$ttl) = @_; if (not defined $ttl) { $ttl = $MAXAGE; } my $file = $LOCKPATH."/".$lockid.".lock"; if (-f $file) { $VERBOSE && print STDERR "Lock file $file existed!!!\n"; my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($file); $VERBOSE && print STDERR "TIME: ".time()." ctime: $ctime TIME-ctime: ".(time()-$ctime)." ttl: $ttl\n"; if (time()-$ctime > $ttl) { $VERBOSE && print STDERR "Expiring dirty lock file.. ($$)\n"; } else { return 0; } } ## write to lock file open F, ">$file"; print F $$; close F; my $RESULT = 0; $/ = undef; open F, "<$file"; $RESULT = <F>; close F; $/ = "\n"; if ($RESULT != $$) { $RESULT = 0; } # double check, this will handle the # 1=open,2=open,1=write,2=write,1=read,2=read,1=close,2=close which *could* happen # in theory, this should be run 1+n, where is the maximum number of threads if (!&verify_lock($lockid)) { $RESULT = 0; } return($RESULT); } ## ## release lock will return 0 if the lock could be released. ## sub release_lock { my ($lockid) = @_; $VERBOSE && print STDERR "DEBUG STATEMENT - release lock id is currently [$lockid]\n"; my $file = $LOCKPATH."/".$lockid.".lock"; if (!-f $file) { print STDERR "release_lock: Lock file $file did not exist!!!\n"; return 1; } $/ = undef; open F, "<$file"; my $RESULT = <F>; close F; $/ = "\n"; if ($RESULT == $$) { unlink($file); } else { print STDERR "Cannot remove $file because we are not the owner! [$RESULT] != [$$]\n"; } print STDERR "Released lock for $lockid\n"; return(0); } ## ## verify that the current process still holds the lock ## sub verify_lock { my ($lockid) = @_; my $file = $LOCKPATH."/".$lockid.".lock"; if (!-f $file) { print STDERR "verify_lock Lock file $file did not exist!!!\n"; return 0; } my $RESULT = 0; $/ = undef; open F, "<$file"; $RESULT = <F>; close F; $/ = "\n"; if ($RESULT != $$) { print STDERR "CRITICAL!!!! verify_lock on $file failed we are not the owner!\n"; $RESULT = 0; } print "verify lock returned: pid is $RESULT\n"; return($RESULT); } 1;
CommerceRack/backend
lib/LOCK.pm
Perl
mit
2,433
#!/usr/bin/perl # SPDX-FileCopyrightText: 2021 Pragmatic Software <pragma78@gmail.com> # SPDX-License-Identifier: MIT use warnings; use strict; package c99; use parent '_c_base'; 1;
pragma-/pbot
applets/pbot-vm/guest/lib/Languages/c99.pm
Perl
mit
186
# Copyright (c) 2010 - Action Without Borders # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. my $pv = perlVersion(); #print STDERR "Using local framework libs for perl $pv\n"; use lib "$ENV{'FRAMEWORK_ROOT'}"; use lib "$ENV{'FRAMEWORK_ROOT'}/lib"; use lib "$ENV{'FRAMEWORK_ROOT'}/conf"; use lib "$ENV{'FRAMEWORK_ROOT'}/local/lib/perl5/$pv"; use lib "$ENV{'FRAMEWORK_ROOT'}/local/lib/perl5/site_perl/$pv"; #print STDERR "Using local app libs for perl $pv\n"; # TODO figure out how to make this not yack?! use lib "$ENV{'APP_ROOT'}"; use lib "$ENV{'APP_ROOT'}/lib"; use lib "$ENV{'APP_ROOT'}/conf"; use lib "$ENV{'APP_ROOT'}/local/lib/perl5/$pv"; use lib "$ENV{'APP_ROOT'}/local/lib/perl5/site_perl/$pv"; sub perlVersion { return sprintf("%vd", $^V); } 1;
quile/if-framework
framework/bin/AppControl/Perl5Lib.pl
Perl
mit
1,791
#!/usr/bin/perl # Aroon Chande # BIOL-7210 -- Comp Genomics 2016 # Genome Assembly pipeline, for use in webapp use strict; use Async; use File::Path qw(make_path remove_tree); use File::Temp; use Getopt::Long; my($inDir,$outDir,$i,$base,$out,$r1,$r2,@steps,$link,$quast,$contigs); $inDir = "/data/public/reads/"; $outDir = "/data/public/assemblies/"; $tmpDir = temp_filename(); $contigs = "$tmpDir/contigs"; my $kmer = '115'; GetOptions ('steps=s{1,}' => \@steps); if (grep(/,/, @steps)){@steps = split(/,/,join(',',@steps));} # Remove generalization and make assumptions about naming scheme my @infiles = glob ( "$inDir/*R1_001_val_1.fq.gz" ); system(`mkdir -p $tmpDir/contigs`); #SPAdes if (grep(/spades|meta/i, @steps)){ foreach (@infiles){ get_files($_); system(`mkdir -p $tmpDir/spades/$out`); system(`spades.py -1 $r1 -2 $r2 -o $tmpDir/spades/$out -k 99,113,127 --only-assembler &>$tmpDir/status.log`); $link = join(".","spades",$out,"fa"); system(`cp $tmpDir/spades/$out/contigs.fasta $tmpDir/contigs/$link`) if (grep(/meta/i, @steps)); system(`cp $tmpDir/spades/$out/contigs.fasta $outDir/$link`) if !(grep(/meta/i, @steps)); system(`rm -rf $tmpDir/spades/$out/corrected`); } } # Velvet if (grep(/velvet|meta/i, @steps)){ foreach (@infiles){ get_files($_); system(`mkdir -p $tmpDir/velvet/`); system(`VelvetOptimiser.pl -d $tmpDir/velvet/$out/ -s 97 -e 127 -x 10 -f '-fastq.gz -shortPaired -separate $r1 $r2' -t 6 --optFuncKmer 'n50' &>$tmpDir/status.log`); $link = join(".","velvet",$out,"fa"); system(`cp $tmpDir/velvet/$out/contigs.fa $tmpDir/contigs/$link`) if (grep(/meta/i, @steps)); system(`cp $tmpDir/velvet/$out/contigs.fa $outDir/$link`) if !(grep(/meta/i, @steps)); system(`rm -rf $tmpDir/velvet/$out/Sequences`); } } # ABySS if (grep(/abyss|meta/i, @steps)){ foreach (@infiles){ get_files($_); system(`mkdir -p $tmpDir/abyss/k$kmer`); system("abyss-pe -C $tmpDir/abyss/k$kmer k=$kmer name=$out in='$r1 $r2' j=6 &>$tmpDir/status.log "); $link = join(".","abyss",$out,"fa"); my $contig = join("-",$out,"contigs.fa"); system(`cp $tmpDir/abyss/k$kmer/$contig $tmpDir/contigs/$link`) if (grep(/meta/i, @steps)); system(`cp $tmpDir/abyss/k$kmer/$contig $ourDir/$link`) if !(grep(/meta/i, @steps)); } } if (grep(/meta/i, @steps)){ system(`mkdir -p $tmpDir/meta/ 2>$tmpDir/status.log`); foreach (@infiles){ my $confFile =join(".",$out,"config"); open OUT, ">$tmpDir/$out/$confFile" or die; my $spades = join('.',"spades",$out,"fa"); my $velvet = join('.',"velvet",$out,"fa"); my $abyss = join('.',"abyss","115",$out,"fa"); my $meta = join(".","meta",$out,"fa"); print OUT "[global]\nbowtie2_threads=12\nbowtie2_read1=$r1\nbowtie2_read2=$r2\nbowtie2_maxins=3000\nbowtie2_minins=1000\ngenomeLength=1825000\nmateAn_A=1300\nmateAn_B=2300\n[1]\nfasta=$contigs/$spades\nID=Spades\n[2]\nfasta=$contigs/$abyss\nID=Abyss\n[3]\nfasta=$contigs/$velvet\nID=Velvet\n"; close OUT; system("metassemble --conf $tmpDir/$out/$confFile --outd $tmpDir/$out 2>>$tmpDir/status.log"); system("sed -i s/QVelvet.Abyss.Spades/$out $tmpDir/meta/$out/Metassembly/QVelvet.Abyss.Spades/M1/QVelvet.Abyss.Spades.fasta" ); system("cp $tmpDir/meta/$out/Metassembly/QVelvet.Abyss.Spades/M1/QVelvet.Abyss.Spades.fasta $outDir/contigs/$meta"); } } if (grep(/velvet/i, @steps)){$quast = Async->new( sub {system(`quast -R $ref --threads=2 $tmpDir/contigs/velvet* -o $tmpDir/quast/velvet >/dev/null`)} or die);} if (grep(/spades/i, @steps)){$quast = Async->new( sub {system(`quast -R $ref --threads=2 $tmpDir/contigs/spades* -o $tmpDir/quast/spades >/dev/null`)} or die);} if (grep(/abyss/i, @steps)){$quast = Async->new( sub {system(`quast -R $ref --threads=2 $tmpDir/contigs/abyss* -o $tmpDir/quast/abyss &>/dev/null`)} or die);} if (grep(/meta/i, @steps)){$quast = Async->new( sub {system(`quast -R $ref --threads=2 $tmpDir/contigs/meta* -o $tmpDir/quast/meta >/dev/null`)} or die);} while (1){ if ($quast->ready){ #combine reports my $report=temp_filename(); open REPORT, ">$report" or die "Cannot open $report: $!"; print REPORT "Assembly\n# contigs (>= 0 bp)\n# contigs (>= 1000 bp)\n# contigs (>= 5000 bp)\n# contigs (>= 10000 bp)\n# contigs (>= 25000 bp)\n# contigs (>= 50000 bp)\nTotal length (>= 0 bp)\nTotal length (>= 1000 bp)\nTotal length (>= 5000 bp)\nTotal length (>= 10000 bp)\nTotal length (>= 25000 bp)\nTotal length (>= 50000 bp)\n# contigs\nLargest contig\nTotal length\nReference length\nGC (%)\nReference GC (%)\nN50\nNG50\nN75\nNG75\nL50\nLG50\nL75\nLG75\n# misassemblies\n# misassembled contigs\nMisassembled contigs length\n# local misassemblies\n# unaligned contigs\nUnaligned length\nGenome fraction (%)\nDuplication ratio\n# Ns per 100 kbp\n# mismatches per 100 kbp\n# indels per 100 kbp\nLargest alignment\nNA50\nNGA50\nNA75\nNGA75\nLA50\nLGA50\nLA75\nLGA75"; close REPORT; system(`paste $report $tmpDir/quast/*/report.tsv| cut -f 1,3,5,7,9,11,13,15,17 > $tmpDir/quast/final_report.tsv`); remove_tree ("$tmpDir/quast/spades","$tmpDir/quast/velvet","$tmpDir/quast/meta","$tmpDir/quast/abyss","$tmpDir/quast/meta"); unlink @infiles; exit 0; } sleep 1; } } exit 0; ####### sub get_files(){ $base = shift; $base =~ s/\_R1_001_val_1\.fq\.gz//g; ($out) = $base =~ m/(M\d*)/; $r1 = join('_',$base,"R1_001_val_1.fq.gz"); $r2 = join('_',$base,"R2_001_val_2.fq.gz"); } sub temp_filename{ my $file = File::Temp->new( TEMPLATE => 'tempXXXXX', DIR => '/data/public/tmp/', ); }
biol7210-genomes/pipeline_scripts
assembly_pipeline_webapp.pl
Perl
mit
5,485
#!C:\strawberr\perl\bin\perl.exe # Test setters and getters for Animal use strict; use warnings; use Horse; use Sheep; my $tv_horse = Horse->named('Mr. Ed'); $tv_horse->set_name('Mister Ed'); $tv_horse->set_color('grey'); print $tv_horse->name, ' is ', $tv_horse->color, "\n"; print Sheep->name, ' colored ', Sheep->color, ' goes ', Sheep->sound, "\n"; Sheep->set_name('Test');
bewuethr/ctci
alpaca_book/chapter13/Animal/scripts/chapter15_ex01.pl
Perl
mit
381
#!/usr/bin/perl -wW use strict; my $ip = shift; exit unless ($ip); my $nip; $nip = $ip; $nip =~ s/\s+//g; $nip =~ s/(..)(..)(..)(..)/$1;$2;$3;$4/; my @tmp = split( ';', $nip ); $tmp[0] = hex( $tmp[0] ); $tmp[1] = hex( $tmp[1] ); $tmp[2] = hex( $tmp[2] ); $tmp[3] = hex( $tmp[3] ); $nip = join( '.', @tmp ); print "$ip - $nip\n";
mmmonk/crap
home_stuff/hex2ip.pl
Perl
mit
336
# Copyright: 2001-2004 The Perl Foundation. All Rights Reserved. # $Id: pdd05_opfunc.pod,v 1.4 2004/02/28 09:16:37 mikescott Exp $ =head1 NAME docs/pdds/pdd05_opfunc.pod - Opcode Function specs =head1 ABSTRACT This PDD specifies how the opcode functions should behave and how they are called by the Parrot interpreter. =head1 DESCRIPTION The opcode functions are the workhorse of the Parrot engine. They control program flow and do most of the work in a program. (The rest being done by the variable vtable functions) Opcode functions have very few limitations or restrictions on them. In particular, opcode functions: =over 4 =item * Can assume a working interpreter =item * Must leave all interpreter registers the way they were found, unless the opcode signature indicates otherwise =back Each opcode has two separate functions. The first function takes two parameters, the current interpreter pointer and current interpreter PC, and returns the address of the next opcode to execute. The second function takes zero or more parameters as addresses, register numbers, integers, or floating point numbers and optionally returns either the address of the next opcode or the register number holding the address of the next opcode. These are referred to as the I<wrapping function> and the I<inner function>, respectively. The I<wrapping function> is required, as this is the code that the interpreter will call. Normally this is automatically generated. The I<inner function> is the code that gets directly executed when parrot gets TIL-ified. If there is no I<inner function> for some reason, then your opcode will likely run slower (as the interpreter would need to set up the registers and other stuff that would normally get stripped away for speed) =head2 The wrapping function This is the function that the interpreter actually executes. It has all the intimate knowledge of its parameters embedded in it, and is responsible for figuring out what register data it needs and from where. This function is generally created automatically by C<opcode_process.pl>, so the programmer doesn't have to create it. If, for some reason, you do need or want to write it (for example if you have no inner function) that's fine. =head2 The inner function The inner function is the code that actually does the work. This is generally a chunk of C code, though the interpreter will be able to call perl code soon. =head1 IMPLEMENTATION =head2 Prototype declaration of inner function RETURN function(INPUT[, INPUT[, INPUT...]]) The C<RETURN> type may be one of: =over 4 =item void Indicates the function returns nothing. The I<wrapping function> will automagically figure out what address to return based on the size of the current opcode. =item void * Indicates the function returns the address of the next opcode to execute. =item I Indicates the function returns the number of the C<PMC> register that holds address of the next opcode to be execute. =back The C<ITEM> may be one of: =over 4 =item IV Indicates the item is an integer =item IV * Indicates the item is a pointer to an integer =item NV Indicates the item is a float =item NV * Indicates the item is a pointer to a float =item STRING Indicates the item is a parrot string pointer =item PMC Indicates the item is a pointer to a PMC =item INT Indicates the item is a pointer to an bigint structure =item NUM Indicates the item is a pointer to a bignum structure =item Ix Indicates the item is an integer register number. =item Nx Indicates the item is a float register number. =item Sx Indicates the item is a string register number. =item Px Indicates the item is a PMC register number. =back The function starts with the first open brace, which should generally be on the first non-empty line. For example: void addI(Ix out, Ix in1, Ix in2) { INTREG(out) = INTREG(in1) + INTREG(in2); } is a simple opcode function that corresponds to the C<addI> opcode. =head1 TODO =over 4 =item write opcode_process.pl =back =head1 REFERENCES Oploop PDD, PDD 4 (Internal types) =head1 FOOTNOTES None. =head1 VERSION 1.0 =head2 CURRENT Maintainer: Dan Sugalski <dan@sidhe.org> Class: Internals PDD Number: 5 Version: 1.0 Status: Developing Last Modified: 16 Jul 2001 PDD Format: 1 Language: English =head2 HISTORY None. First version =head1 CHANGES None. First version
autarch/perlweb
docs/dev/perl6/pdd/pdd05_opfunc.pod
Perl
apache-2.0
4,447
#!/usr/bin/perl # HACK HACK HACK :-) use strict; use warnings; use Carp; use File::Basename qw(dirname basename); use JSON::XS; use Getopt::Long; my $TIME_BETWEEN_PAGE_REQUESTS = 3; # time, in s, between additional page loads my $QUIET_MODE = undef; my $SCRIPT_DIR = dirname($0); my $PROJECT_CACHE = $SCRIPT_DIR . q{/projects/}; my $BACKER_PAGE = q{/backers}; my $PROJECT_URL = q{https://www.kickstarter.com/projects/}; sub project_cache_name { my ($project_id, $cursor, $page_ct, undef) = @_; my $project_escaped = $project_id; if ($page_ct) { $project_escaped .= q{__} . $page_ct . q{__} . $cursor; } $project_escaped =~ s/backers//gixm; $project_escaped =~ s/\?/__/gixm; $project_escaped =~ s/page=//gixm; $project_escaped =~ s/\//\./gixm; return $PROJECT_CACHE . $project_escaped; } sub download_project { my ($project_id, $cursor, $page_ct, undef) = @_; my $cache_name = project_cache_name($project_id, $cursor, $page_ct); if (-e $cache_name) { if (!defined $QUIET_MODE) { print STDERR qq{$project_id: already have project }, qq{locally as $cache_name\n}; } return; } my $project_post = $BACKER_PAGE; if ($cursor) { $project_post .= qq{?cursor=$cursor}; } my @cmd = ( q{curl }, q{'}, $PROJECT_URL, $project_id, $project_post, q{'}, q{ -o }, $cache_name ); my $cmd_str = join(q{}, @cmd); #print $cmd_str, qq{\n}; if (!defined $QUIET_MODE) { print STDERR qq{$project_id: Downloading project...\n}; } system($cmd_str); sleep($TIME_BETWEEN_PAGE_REQUESTS); return; } sub read_project_backers { my ($profile_content, undef) = @_; my $cursor = q{unknown}; my $final_page = undef; my %backers = (); for (my $i = 0; $i < scalar @{$profile_content}; ++$i) { my $line = $profile_content->[$i]; if (!defined $final_page && # defined once per pageload $line =~ /data-last_page=\"/) { # is this the final set of records? $final_page = ($line =~ /data-last_page=\"true\"/); } if ($line !~ /NS\_backers\_\_backing\_row/) { next; } if ($line =~ /data-cursor="(\d+)"/) { # keep updating with last cursor seen $cursor = $1; } ++$i; $line = $profile_content->[$i]; if ($line =~ /\"\/profile\/(\w+)\"/ixm) { $backers{$1} = 1; } } return { backers => [ sort keys %backers ], final_page => $final_page, cursor => $cursor }; } sub read_project_meta { my ($profile_content, undef) = @_; my %rtn = (); my @meta = grep { /kickstarter:/ixm } grep { /\<meta/ixm } @{$profile_content}; push(@meta, grep { /twitter:text/ixm } @{$profile_content}); foreach my $m (@meta) { my ($key, $val); if ($m =~ /property=\"(.*?)\"/gixm) { my @a = split(q{:}, $1); $key = pop @a; } if ($m =~ /content=\"(.*?)\"/gixm) { $val = $1; } if ($key eq q{backers}) { $val =~ s/,//gixm; } if ($key eq q{pledged}) { $val =~ s/\D+//gixm; } $rtn{$key} = $val; } foreach my $main_content_div (grep { /id\=\"main\_content\"/ixm } @{$profile_content}) { if ($main_content_div =~ /class=\"(.+)\" /ixm) { foreach my $class (split(/\s+/ixm, $1)) { if ($class =~ /^Project-ended-(.*)/ixm) { $rtn{project_ended} = $1; } if ($class =~ /^Project-state-(.*)/ixm) { $rtn{project_state} = $1; } } } } return \%rtn; } # This Fn doesn't work because Kickstarter doesn't respect page numbers; # have to make each request by parsing the previous request result. sub extract_additional_pages { my ($profile_content, undef) = @_; my @additional_pages = (); my $max_page = 1; foreach my $profile_line (grep { /\"pagination\"/ixm } @{$profile_content}) { my @a_tags = split(q{<a }, $profile_line); foreach my $link (@a_tags) { if ($link =~ /\/backers\?page=(\d+)\"/ixm && ($1 > $max_page)) { $max_page = $1; } } } if (1 < $max_page) { for (my $i = 2; $i <= $max_page; ++$i) { push(@additional_pages, q{/backers?page=} . $i); } } return \@additional_pages; } sub read_project_content { my ($project_id, $cursor, $page_ct, undef) = @_; my $project_h; download_project($project_id, $cursor, $page_ct); my $cache_name = project_cache_name($project_id, $cursor, $page_ct); open($project_h, q{<}, $cache_name) or croak(qq{Unable to open project '$project_id' as '$cache_name'}); my @project = <$project_h>; close($project_h) or croak(qq{Unable to open project '$project_id'}); chomp(@project); return \@project; } sub repr_project_meta { my ($project_map, $meta, undef) = @_; $meta->{id} = $project_map->{p_id}; $meta->{user} = $project_map->{p_maker}; $meta->{title} = $project_map->{p_title}; $meta->{vennback} = q{project_meta}; return encode_json $meta; } sub repr_project_backers { my ($project_map, $backers, undef) = @_; my @s_list = (); foreach my $back (@{$backers}) { my $s = encode_json { id => $project_map->{p_id}, vennback => q{project_back}, backer => $back }; push(@s_list, $s); } return join(qq{\n}, @s_list); } sub read_project { my ($project_map, undef) = @_; my $project_content = read_project_content($project_map->{p_id}); my $meta = read_project_meta($project_content); print repr_project_meta($project_map, $meta), qq{\n}; my @backers = (); my $backer_result; my $ct = 1; do { $backer_result = read_project_backers($project_content); push(@backers, @{$backer_result->{backers}}); ++$ct; $project_content = read_project_content($project_map->{p_id}, $backer_result->{cursor}, $ct); } until ($backer_result->{final_page}); print repr_project_backers($project_map, \@backers), qq{\n}; return; } sub split_project { my ($project_id, undef) = @_; # strip beginning parts if it's a URL $project_id =~ s/^.*\/projects\///gixm; # strip ending parts if it's a URL $project_id =~ s/\?.*$//gixm; my ($project_maker, $project_title) = split(q{/}, $project_id); return { p_maker => $project_maker, p_title => $project_title, p_id => $project_id }; } sub main { # TODO: Argument processing GetOptions(q{quiet} => \$QUIET_MODE); if (!scalar @ARGV) { push(@ARGV, 'yonder/dino-pet-a-living-bioluminescent-night-light-pet'); } if (!-d $PROJECT_CACHE) { mkdir $PROJECT_CACHE; } foreach my $project_raw (@ARGV) { my $project_map = split_project($project_raw); if ($project_map && scalar keys $project_map) { read_project($project_map); } } return; } main();
danvogel/venn-kick-back
project_into_recs.pl
Perl
apache-2.0
6,770
#** @file FrameworkUtils.pm # # @brief Methods for assisting with UW framework # @author Dave Boulineau (db), dboulineau@continuousassurance.org # @date 04/30/2014 09:44:47 # @copy Copyright (c) 2014 Software Assurance Marketplace, Morgridge Institute for Research #* # package SWAMP::FrameworkUtils; use 5.014; use utf8; use strict; use warnings; use parent qw(Exporter); BEGIN { our $VERSION = '1.00'; } our (@EXPORT_OK); BEGIN { require Exporter; @EXPORT_OK = qw(ReadStatusOut savereport generatereport); } use English '-no_match_vars'; use File::Basename qw(basename dirname); use File::Spec qw(devnull catfile); use Carp qw(croak carp); use XML::LibXML; use XML::LibXSLT; use SWAMP::SWAMPUtils qw(getSWAMPDir); my $stdDivPrefix = q{ } x 2; my $stdDivChars = q{-} x 10; my $stdDiv = "$stdDivPrefix$stdDivChars"; # statusOutObj = ReadStatusOut(filename) # # ReadStatusOut returns a hash containing the parsed status.out file. # # A status.out file consists of task lines in the following format with the # names of these elements labeled # # PASS: the-task-name (the-short-message) 40.186911s # # | | | | | # | task shortMsg dur | # status durUnit # # Each task may also optional have a multi-line message (the msg element). # The number of spaces before the divider are removed from each line and the # line-feed is removed from the last line of the message # # PASS: the-task-name (the-short-message) 40.186911s # ---------- # line A # line A+1 # ---------- # The returned hash contains a hash for each task. The key is the name of the # task. If there are duplicate task names, duplicate keys are named using the # scheme <task-name>#<unique-number>. # # The hash for each task contains the following keys # # status - one of PASS, FAIL, SKIP, or NOTE # task - name of the task # shortMsg - shortMsg or undef if not present # msg - msg or undef if not present # dur - duration is durUnits or undef if not present # durUnit - durUnits: 's' is for seconds # linenum - line number where task started in file # name - key used in hash (usually the same as task) # text - unparsed text # # Besided a hash for each task, the hash function returned from ReadStatusOut # also contains the following additional hash elements: # # #order - reference to an array containing references to the task hashes # in the order they appeared in the status.out file # #errors - reference to an array of errors in the status.out file # #warnings - reference to an array of warnings in the status.out file # #filename - filename read # # If there are no errors or warnings (the arrays are 0 length), then exists can # be used to check for the existence of a task. The following would correctly # check if that run succeeded: # # my $s = ReadStatusOut($filename) # if (!@{$s->{'#errors'}} && !@{$s->{'#warnings'}}) { # if (exists $s->{all} && $s->{all}{status} eq 'PASS') { # print "success\n"; # } else { # print "no success\n"; # } # } else { # print "bad status.out file\n"; # } # # sub ReadStatusOut { my $statusFile = shift; my %status = ( '#order' => [], '#errors' => [], '#warnings' => [], '#filename' => $statusFile ); my $lineNum = 0; my $fh; if ( !open $fh, "<", $statusFile ) { push @{ $status{'#errors'} }, "open $statusFile failed: $OS_ERROR"; return \%status; } my ( $lookingFor, $name, $prefix, $divider ) = ( 'task', q{} ); while (<$fh>) { ++$lineNum; my $line = $_; chomp; if ( $lookingFor eq 'task' ) { if (/^( \s*)(-+)$/sxm) { ( $prefix, $divider ) = ( $1, $2 ); $lookingFor = 'endMsg'; if ( $name eq q{} ) { push @{ $status{'#errors'} }, "Message divider before any task at line $lineNum"; $status{$name}{'linenum'} = $lineNum; } if ( defined( $status{$name}{'text'} ) && ( $status{$name}{'text'} =~ tr/\n// ) > 1 ) { push @{ $status{'#errors'} }, "Message found after another message at line $lineNum"; $status{$name}{'msg'} .= "\n"; } if ( $_ ne $stdDiv ) { push @{ $status{'#errors'} }, "Non-standard message divider '$_' at line $lineNum"; } $status{$name}{'text'} .= $line; $status{$name}{'msg'} .= q{}; } else { s/\s*$//sxm; if (/^\s*$/sxm) { push @{ $status{'#warnings'} }, "Blank line at line $lineNum"; next; } if (/^(\s*)([a-zA-Z0-9_-]+):\s+([a-zA-Z0-9_-]+)\s*(.*)$/sxm) { my ( $pre, $status, $task, $remain ) = ( $1, $2, $3, $4 ); $name = $task; if ( exists $status{$name} ) { push @{ $status{"#warnings"} }, "Duplicate task name found at lines $status{$name}{'linenum'} and $lineNum"; my $i = 0; do { ++$i; $name = "$task#$i"; } until ( !exists $status{$name} ); ## no critic (ControlStructures) } my ( $shortMsg, $dur, $durUnit ); if ( $remain =~ /^\((.*?)\)\s*(.*)/sxm ) { ( $shortMsg, $remain ) = ( $1, $2 ); } if ( $remain =~ /^(\d+(?:\.\d+)?)([a-zA-Z]*)\s*(.*)$/sxm ) { ( $dur, $durUnit, $remain ) = ( $1, $2, $3 ); } if ( $pre ne q{} ) { push @{ $status{'#warnings'} }, "White space before status at line $lineNum"; } if ( $remain ne q{} ) { push @{ $status{'#errors'} }, "Bad status.out at line: $lineNum"; } if ( defined $dur ) { if ( $durUnit eq q{} ) { push @{ $status{'#errors'} }, "Missing duration unit at line $lineNum"; } elsif ( $durUnit ne 's' ) { push @{ $status{'#errors'} }, "Duration unit not 's' at line $lineNum"; } } if ( defined $shortMsg ) { if ( $shortMsg =~ /\(/sxm ) { push @{ $status{'#warnings'} }, "Short message contains '(' at line $lineNum"; } } if ( $status !~ /^(?:NOTE|SKIP|PASS|FAIL)$/isxm ) { push @{ $status{'#errors'} }, "Unknown status '$status' at line $lineNum"; } elsif ( $status !~ /^(?:NOTE|SKIP|PASS|FAIL)$/sxm ) { push @{ $status{'#warnings'} }, "Status '$status' should be uppercase at line $lineNum"; } $status{$name} = { 'status' => $status, 'task' => $task, 'shortMsg' => $shortMsg, 'msg' => undef, 'dur' => $dur, 'durUnit' => $durUnit, 'linenum' => $lineNum, 'name' => $name, 'text' => $line }; push @{ $status{'#order'} }, $status{$name}; } } } elsif ( $lookingFor eq 'endMsg' ) { $status{$name}{'text'} .= $line; if (/^$prefix$divider$/sm) { ## no critic (RegularExpressions::RequireExtendedFormatting) $lookingFor = 'task'; chomp $status{$name}{'msg'}; } else { $line =~ s/^$prefix//sxm; $status{$name}{'msg'} .= $line; } } else { croak "Unknown lookingFor value = $lookingFor"; } } if ( !close $fh ) { push @{ $status{'#errors'} }, "close $statusFile failed: $OS_ERROR"; } if ( $lookingFor eq 'endMsg' ) { my $ln = $status{$name}{'linenum'}; push @{ $status{'#errors'} }, "Message divider '$prefix$divider' not seen before end of file at line $ln"; if ( defined $status{$name}{'msg'} ) { chomp $status{$name}{'msg'}; } } return \%status; } ###my $s = ReadStatusOut($ARGV[0]); ###my $errCnt = scalar @{$s->{'#errors'}}; ###my $warnCnt = scalar @{$s->{'#warnings'}}; ###my $filename = $s->{'#filename'}; ### ###print "$filename (errors: $errCnt, warnings: $warnCnt)\n"; ###print "Errors:\n\t", join("\n\t", @{$s->{'#errors'}}), "\n" if $errCnt; ###print "Warnings:\n\t", join("\n\t", @{$s->{'#warnings'}}), "\n" if $warnCnt; ###foreach my $t (@{$s->{'#order'}}) { ### my $status = $t->{status}; ### my $taskName = $t->{task}; ### print "$status $taskName\n"; ###} ### ###use Data::Dumper; ### ###print "--------------------\n"; ###print Dumper($s); sub generatereport { my $tarball = shift; my $status = loadStatusOut($tarball); my %report; $report{'tarball'} = basename $tarball; if ($status) { $report{'error'} = addErrorNote( $status, $tarball ); my $string; my $nOut; my $nErr; $report{'no-build'} = addBuildfailures( $status, $tarball ); ($nOut, $string) = addStdout( $status, $tarball ); if ($nOut > 0) { $report{'stdout'} = $string; } ($nErr, $string) = addStderror( $status, $tarball ); if ($nErr > 0) { $report{'stderr'} = $string; } if (($nOut + $nErr) == 0) { $report{'error'} .= q{<p><b>Unable to find specific stdout/stderr, showing output from entire assessment:</b><p>}; $report{'error'} .= rawTar($tarball, q{out/run.out}); } $string = rawTar($tarball, q{out/versions.txt}); if ($string) { $report{'versions'} = $string; } } else { $report{'error'} = addGenericError( $tarball ); } return %report; } sub savereport { my ( $report, $filename, $url ) = @_; my $fh; my $uuid = dirname ($filename); $uuid =~ s/^.*\///sxm; if ( !open $fh, '>', $filename ) { return 0; } print $fh qq{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n}; print $fh "<HTML><HEAD><TITLE>Failed Assessment Report</TITLE></HEAD>\n"; print $fh "<BODY>\n"; print $fh "<H2>Failed Assessment Report</H2>"; if ( $report->{'no-build'} ) { print $fh "<li><a href=#nobuild>Error messages from no-build step</a></li>\n"; } if ( $report->{'error'} ) { print $fh "<li><a href=#error>Error messages from assessment</a></li>\n"; } if ( $report->{'stdout'} ) { print $fh "<li><a href=#stdout>Standard out</a></li>\n"; } if ( $report->{'stderr'} ) { print $fh "<li><a href=#stderr>Standard error</a></li>\n"; } if ( $report->{'versions'} ) { print $fh "<li><a href=#versions>Version information</a></li>\n"; } print $fh qq{<li><a href=${url}$uuid/$report->{'tarball'}>Download all failed results as a single file</a></li>}; print $fh "<p>"; if ($report->{'no-build'}) { print $fh "$report->{'no-build'}\n"; } if ( $report->{'error'} ) { print $fh "<h3><a id=\"error\">Error messages from assessment</a></h3>\n"; print $fh "<pre>$report->{'error'}</pre>\n"; } if ( $report->{'stdout'} ) { print $fh "<hr><h3><a id=\"stdout\">Standard out</a></h3>\n"; print $fh "<pre>$report->{'stdout'}</pre>\n"; } if ( $report->{'stderr'} ) { print $fh "<hr><h3><a id=\"stderr\">Standard error</a></h3>\n"; print $fh "<pre>$report->{'stderr'}</pre>\n"; } if ($report->{'versions'}) { print $fh "<hr><h3><a id=\"versions\">Version information</a></h3>\n"; my @versions =split(/\n/sxm, $report->{'versions'}); print $fh "<pre><TABLE><TR><TH align=left>Component</TH><TH align=left>Version</TH>\n"; foreach (@versions) { my ($component,$version)=split(/:/sxm); print $fh "<TR><TD>$component</TD><TD>$version</TD>\n"; } print $fh "</TABLE></pre>\n"; } print $fh "<h5><pre>Report generated: ",scalar localtime,"</pre></h5>\n"; print $fh "</BODY>\n"; print $fh "</HTML>\n"; if (!close $fh) { } return 1; } sub loadStatusOut { my $tarfile = shift; my $statusOut = rawTar($tarfile); if ($statusOut) { if (open( my $fh, '>', q{tmps.out} )) { print $fh $statusOut; if (!close($fh)) { } return ReadStatusOut(q{tmps.out}); } } return; } sub addErrorNote { my ( $s, $tarfile ) = @_; my $note; if ( !@{ $s->{'#errors'} } && !@{ $s->{'#warnings'} } ) { if ( exists $s->{'all'} && $s->{'all'}{'status'} eq 'PASS' ) { $note = "No errors detected"; } else { my $errCnt = scalar @{ $s->{'#errors'} }; my $warnCnt = scalar @{ $s->{'#warnings'} }; my $filename = $s->{'#filename'}; my $errorString; $note = "$filename (errors: $errCnt, warnings: $warnCnt)\n"; #print "Errors:\n\t", join( "\n\t", @{ $s->{'#errors'} } ), "\n" if $errCnt; #print "Warnings:\n\t", join( "\n\t", @{ $s->{'#warnings'} } ), "\n" if $warnCnt; $errorString .= '<TABLE><TR><TH align=left>Failing Step</TH><TH align=left>Error Message</TH></TR>'; foreach my $t ( @{ $s->{'#order'} } ) { my $status = $t->{'status'}; my $taskName = $t->{'task'}; if ( $taskName ne q{all} && $status eq q{FAIL} ) { $errorString .= "<TR><TD>$taskName</TD>"; if (defined($t->{'msg'})) { $errorString .= "<TD>$t->{msg}</TD></TR>"; } else { $errorString .= "<TD>No error message found</TD>"; } } } $errorString .= '</TABLE>'; $note = $errorString; } } else { # say Dumper($s); $note = q{Unable to parse status.out}; } return $note; } sub tarTarTOC { my $tarball = shift; my $subfile = shift; my ( $output, $status ) = ( $_ = qx {tar -O -xzf $tarball $subfile | tar tzvf - 2>/dev/null}, $CHILD_ERROR >> 8 ); if ($status) { return; } else { return split( /\n/sxm, $output ); } } sub tarCat{ my $tarball = shift; my $subfile = shift; my $file = shift; my ( $output, $status ) = ( $_ = qx {tar -O -xzf $tarball $subfile | tar -O -xzf - $file 2>/dev/null}, $CHILD_ERROR >> 8 ); if ($status) { return; } else { return $output; } } sub tarTOC { my $tarball = shift; my ( $output, $status ) = ( $_ = qx {tar -tzvf $tarball 2>/dev/null}, $CHILD_ERROR >> 8 ); if ($status) { return; } else { return split( /\n/sxm, $output ); } } sub addBuildfailures { my ( $status_out, $tarfile ) = @_; my @files = tarTOC($tarfile); foreach (@files) { if (/source-compiles.xml/xsm) { my $rawxml = rawTar($tarfile, q{out/source-compiles.xml}); my $xslt = XML::LibXSLT->new(); my $source; my $success = eval { $source = XML::LibXML->load_xml( 'string' => $rawxml ); }; my $xsltfile = File::Spec->catfile( getSWAMPDir(), 'etc', 'no-build.xslt' ); if ( defined($success) ) { my $style_doc = XML::LibXML->load_xml( 'location' => "$xsltfile", 'no_cdata' => 1 ); my $stylesheet = $xslt->parse_stylesheet($style_doc); my $result = $stylesheet->transform($source); return $result->toString(); } } } return; } sub addStdout { my ( $status_out, $tarfile ) = @_; return findFiles($tarfile, q{(build_stdout|configure_stdout|resultparser.log)}); } sub addStderror { my ( $status, $tarfile ) = @_; return findFiles($tarfile, q{(build_stderr|configure_stderr)}); } sub findFiles { my ($tarfile, $pattern) = @_; my $string; my @files=tarTOC($tarfile); my $nFound = 0; foreach (@files) { if (/.tar.gz$/sxm) { chomp; my @line=split(q{ }, $_); my $files = getFiles($tarfile, $pattern, $line[-1]); if ($files) { $string .= $files; $nFound++; } } } return ($nFound, $string); } sub getFiles { my ( $tarfile, $pattern, $subfile ) = @_; my @files = tarTarTOC( $tarfile, $subfile ); my $str; #say "Looking for $pattern in $subfile in $tarfile"; foreach (@files) { if (/$pattern/sxm) { if (/swa_tool/sxm) { next; } chomp; #say "file $_"; my @line = split( q{ }, $_ ); $str .= "<b>FILE: $line[-1] from $subfile</b>\n"; $str .= tarCat( $tarfile, $subfile, $line[-1] ); $str .= q{<p>}; } } return $str; } sub addGenericError { my ($tarfile ) = @_; return q{Unable to determine the final status of the assessment.}; } sub rawTar { my $tarball = shift; my $file = shift // q{out/status.out}; my ( $output, $status ) = ( $_ = qx {tar -O -xzf $tarball $file 2>/dev/null}, $CHILD_ERROR >> 8 ); if ($status) { return; } else { return $output; } } 1; __END__ =pod =encoding utf8 =head1 NAME =head1 SYNOPSIS Write the Manual page for this package =head1 DESCRIPTION =head1 OPTIONS =over 8 =item =back =head1 EXAMPLES =head1 SEE ALSO =cut
OWASP/open-swamp
dataserver/opt/swamp/perl5/SWAMP/FrameworkUtils.pm
Perl
apache-2.0
18,752
# # 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 network::alcatel::omniswitch::snmp::mode::components::stack; use strict; use warnings; use network::alcatel::omniswitch::snmp::mode::components::resources qw(%oids $mapping); sub load {} sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking stack"); $self->{components}->{stack} = {name => 'stacks', total => 0, skip => 0}; return if ($self->check_filter(section => 'stack')); my @instances = (); foreach my $key (keys %{$self->{results}->{$oids{common}->{entPhysicalClass}}}) { if ($self->{results}->{$oids{common}->{entPhysicalClass}}->{$key} == 11) { next if ($key !~ /^$oids{common}->{entPhysicalClass}\.(.*)$/); push @instances, $1; } } foreach my $instance (@instances) { next if (!defined($self->{results}->{entity}->{$oids{$self->{type}}{chasEntPhysAdminStatus} . '.' . $instance})); my $result = $self->{snmp}->map_instance(mapping => $mapping->{$self->{type}}, results => $self->{results}->{entity}, instance => $instance); next if ($self->check_filter(section => 'stack', instance => $instance)); $self->{components}->{stack}->{total}++; $self->{output}->output_add(long_msg => sprintf("stack '%s/%s' [instance: %s, admin status: %s] operationnal status is %s.", $result->{entPhysicalName}, $result->{entPhysicalDescr}, $instance, $result->{chasEntPhysAdminStatus}, $result->{chasEntPhysOperStatus}) ); if ($result->{chasEntPhysPower} > 0) { $self->{output}->perfdata_add( label => "power", unit => 'W', nlabel => 'hardware.stack.power.watt', instances => $instance, value => $result->{chasEntPhysPower}, min => 0 ); } my $exit = $self->get_severity(label => 'admin', section => 'stack.admin', value => $result->{chasEntPhysAdminStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("stack '%s/%s/%s' admin status is %s", $result->{entPhysicalName}, $result->{entPhysicalDescr}, $instance, $result->{chasEntPhysAdminStatus})); next; } $exit = $self->get_severity(label => 'oper', section => 'stack.oper', value => $result->{chasEntPhysOperStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("stack '%s/%s/%s' operational status is %s", $result->{entPhysicalName}, $result->{entPhysicalDescr}, $instance, $result->{chasEntPhysOperStatus})); } } } 1;
Tpo76/centreon-plugins
network/alcatel/omniswitch/snmp/mode/components/stack.pm
Perl
apache-2.0
4,005
package Paws::ApiGateway::GetUsagePlanKey; use Moose; has KeyId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'keyId', required => 1); has UsagePlanId => (is => 'ro', isa => 'Str', traits => ['ParamInURI'], uri_name => 'usagePlanId', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'GetUsagePlanKey'); class_has _api_uri => (isa => 'Str', is => 'ro', default => '/usageplans/{usageplanId}/keys/{keyId}'); class_has _api_method => (isa => 'Str', is => 'ro', default => 'GET'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::ApiGateway::UsagePlanKey'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::ApiGateway::GetUsagePlanKey - Arguments for method GetUsagePlanKey on Paws::ApiGateway =head1 DESCRIPTION This class represents the parameters used for calling the method GetUsagePlanKey on the Amazon API Gateway service. Use the attributes of this class as arguments to method GetUsagePlanKey. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to GetUsagePlanKey. As an example: $service_obj->GetUsagePlanKey(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> KeyId => Str The key Id of the to-be-retrieved UsagePlanKey resource representing a plan customer. =head2 B<REQUIRED> UsagePlanId => Str The Id of the UsagePlan resource representing the usage plan containing the to-be-retrieved UsagePlanKey resource representing a plan customer. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method GetUsagePlanKey in L<Paws::ApiGateway> =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/ApiGateway/GetUsagePlanKey.pm
Perl
apache-2.0
2,182
#! /usr/bin/env perl # Copyright 2015-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 # https://www.openssl.org/source/license.html use strict; use warnings; use File::Compare qw/compare_text/; use File::Copy; use OpenSSL::Test qw/:DEFAULT/; my %conversionforms = ( # Default conversion forms. Other series may be added with # specific test types as key. "*" => [ "d", "p" ], "msb" => [ "d", "p", "msblob" ], "pvk" => [ "d", "p", "pvk" ], ); sub tconversion { my %opts = @_; die "Missing option -type" unless $opts{-type}; die "Missing option -in" unless $opts{-in}; my $testtype = $opts{-type}; my $t = $opts{-in}; my $prefix = $opts{-prefix} // $testtype; my @conversionforms = defined($conversionforms{$testtype}) ? @{$conversionforms{$testtype}} : @{$conversionforms{"*"}}; my @openssl_args; if (defined $opts{-args}) { @openssl_args = @{$opts{-args}} if ref $opts{-args} eq 'ARRAY'; @openssl_args = ($opts{-args}) if ref $opts{-args} eq ''; } @openssl_args = ($testtype) unless @openssl_args; my $n = scalar @conversionforms; my $totaltests = 1 # for initializing + $n # initial conversions from p to all forms (A) + $n*$n # conversion from result of A to all forms (B) + 1 # comparing original test file to p form of A + $n*($n-1); # comparing first conversion to each form in A with B $totaltests-- if ($testtype eq "p7d"); # no comparison of original test file $totaltests -= $n if ($testtype eq "pvk"); # no comparisons of the pvk form plan tests => $totaltests; my @cmd = ("openssl", @openssl_args); my $init; if (scalar @openssl_args > 0 && $openssl_args[0] eq "pkey") { $init = ok(run(app([@cmd, "-in", $t, "-out", "$prefix-fff.p"])), 'initializing'); } else { $init = ok(copy($t, "$prefix-fff.p"), 'initializing'); } if (!$init) { diag("Trying to copy $t to $prefix-fff.p : $!"); } SKIP: { skip "Not initialized, skipping...", 22 unless $init; foreach my $to (@conversionforms) { ok(run(app([@cmd, "-in", "$prefix-fff.p", "-inform", "p", "-out", "$prefix-f.$to", "-outform", $to])), "p -> $to"); } foreach my $to (@conversionforms) { foreach my $from (@conversionforms) { ok(run(app([@cmd, "-in", "$prefix-f.$from", "-inform", $from, "-out", "$prefix-ff.$from$to", "-outform", $to])), "$from -> $to"); } } if ($testtype ne "p7d") { is(cmp_text("$prefix-fff.p", "$prefix-f.p"), 0, 'comparing orig to p'); } foreach my $to (@conversionforms) { next if $to eq "d" or $to eq "pvk"; foreach my $from (@conversionforms) { is(cmp_text("$prefix-f.$to", "$prefix-ff.$from$to"), 0, "comparing $to to $from$to"); } } } } sub cmp_text { return compare_text(@_, sub { $_[0] =~ s/\R//g; $_[1] =~ s/\R//g; return $_[0] ne $_[1]; }); } sub file_contains { $_ = shift @_; my $pattern = shift @_; open(DATA, $_) or return 0; $_= join('', <DATA>); close(DATA); s/\s+/ /g; # take multiple whitespace (including newline) as single space return m/$pattern/ ? 1 : 0; } sub cert_contains { my $cert = shift @_; my $pattern = shift @_; my $expected = shift @_; my $name = shift @_; my $out = "cert_contains.out"; run(app(["openssl", "x509", "-noout", "-text", "-in", $cert, "-out", $out])); is(file_contains($out, $pattern), $expected, ($name ? "$name: " : ""). "$cert should ".($expected ? "" : "not ")."contain: \"$pattern\""); # not unlinking $out } sub uniq (@) { my %seen = (); grep { not $seen{$_}++ } @_; } sub file_n_different_lines { my $filename = shift @_; open(DATA, $filename) or return 0; chomp(my @lines = <DATA>); close(DATA); return scalar(uniq @lines); } sub cert_ext_has_n_different_lines { my $cert = shift @_; my $expected = shift @_; my $exts = shift @_; my $name = shift @_; my $out = "cert_n_different_exts.out"; run(app(["openssl", "x509", "-noout", "-ext", $exts, "-in", $cert, "-out", $out])); is(file_n_different_lines($out), $expected, ($name ? "$name: " : ""). "$cert '$exts' output should contain $expected different lines"); # not unlinking $out } 1;
openssl/openssl
test/recipes/tconversion.pl
Perl
apache-2.0
4,606
# # 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 centreon::common::ingrian::snmp::mode::memory; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub custom_usage_perfdata { my ($self, %options) = @_; $self->{output}->perfdata_add(label => 'used', unit => 'B', value => $self->{result_values}->{used}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{label}, total => $self->{result_values}->{total}, cast_int => 1), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{label}, total => $self->{result_values}->{total}, cast_int => 1), min => 0, max => $self->{result_values}->{total}); } sub custom_usage_threshold { my ($self, %options) = @_; my $exit = $self->{perfdata}->threshold_check(value => $self->{result_values}->{prct_used}, threshold => [ { label => 'critical-' . $self->{label}, exit_litteral => 'critical' }, { label => 'warning-' . $self->{label}, exit_litteral => 'warning' } ]); return $exit; } sub custom_usage_output { my ($self, %options) = @_; my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{total}); my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{used}); my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{free}); my $msg = sprintf("Memory Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $total_size_value . " " . $total_size_unit, $total_used_value . " " . $total_used_unit, $self->{result_values}->{prct_used}, $total_free_value . " " . $total_free_unit, $self->{result_values}->{prct_free}); return $msg; } sub custom_usage_calc { my ($self, %options) = @_; $self->{result_values}->{total} = $options{new_datas}->{$self->{instance} . '_total'}; $self->{result_values}->{prct_used} = $options{new_datas}->{$self->{instance} . '_prct_used'}; $self->{result_values}->{prct_free} = 100 - $self->{result_values}->{prct_used}; $self->{result_values}->{used} = $self->{result_values}->{total} * $self->{result_values}->{prct_used} / 100; $self->{result_values}->{free} = $self->{result_values}->{total} - $self->{result_values}->{used}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'memory', type => 0 } ]; $self->{maps_counters}->{memory} = [ { label => 'usage', set => { key_values => [ { name => 'prct_used' }, { name => 'total' } ], closure_custom_calc => $self->can('custom_usage_calc'), closure_custom_output => $self->can('custom_usage_output'), closure_custom_perfdata => $self->can('custom_usage_perfdata'), closure_custom_threshold_check => $self->can('custom_usage_threshold'), } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } sub manage_selection { my ($self, %options) = @_; my $oid_naeSystemStatUsedMem = '.1.3.6.1.4.1.5595.3.2.5.0'; my $oid_naeSystemStatTotalMem = '.1.3.6.1.4.1.5595.3.2.6.0'; # in Bytes my $snmp_result = $options{snmp}->get_leef(oids => [$oid_naeSystemStatUsedMem, $oid_naeSystemStatTotalMem], nothing_quit => 1); $self->{memory} = { prct_used => $snmp_result->{$oid_naeSystemStatUsedMem}, total => $snmp_result->{$oid_naeSystemStatTotalMem} }; } 1; __END__ =head1 MODE Check memory usages. =over 8 =item B<--warning-usage> Threshold warning (in percent). =item B<--critical-usage> Threshold critical (in percent). =back =cut
Tpo76/centreon-plugins
centreon/common/ingrian/snmp/mode/memory.pm
Perl
apache-2.0
4,918
#!/usr/bin/env perl use 5.10.0; use strict; use warnings; use lib './lib'; use Getopt::Long; use Path::Tiny qw/path/; use Pod::Usage; use Utils::CaddToBed; use Utils::Fetch; use Utils::LiftOverCadd; use Utils::SortCadd; use Utils::RenameTrack; use Seq::Build; my ( $yaml_config, $wantedName, $sortCadd, $renameTrack, $help, $liftOverCadd, $liftOverCadd_path, $liftOverChainPath, $debug, $overwrite, $fetch, $caddToBed, $compress, $toBed, $renameTrackTo, $verbose, $dryRunInsertions, ); # usage GetOptions( 'c|config=s' => \$yaml_config, 'n|name=s' => \$wantedName, 'h|help' => \$help, 'd|debug=i' => \$debug, 'o|overwrite' => \$overwrite, 'fetch' => \$fetch, 'caddToBed' => \$caddToBed, 'sortCadd' => \$sortCadd, 'renameTrack' => \$renameTrack, 'liftOverCadd' => \$liftOverCadd, 'compress' => \$compress, 'liftOverPath=s' => \$liftOverCadd_path, 'liftOverChainPath=s' => \$liftOverChainPath, 'renameTo=s' => \$renameTrackTo, 'verbose=i' => \$verbose, 'dryRun' => \$dryRunInsertions, ); if ( (!$fetch && !$caddToBed && !$liftOverCadd && !$sortCadd && !$renameTrack) || $help) { Pod::Usage::pod2usage(1); exit; } unless ($yaml_config) { Pod::Usage::pod2usage(); } my %options = ( config => $yaml_config, name => $wantedName || undef, debug => $debug, overwrite => $overwrite || 0, overwrite => $overwrite || 0, liftOverPath => $liftOverCadd_path || '', liftOverChainPath => $liftOverChainPath || '', renameTo => $renameTrackTo, verbose => $verbose, dryRun => $dryRunInsertions, ); if($compress) { $options{compress} = $compress; } # If user wants to split their local files, needs to happen before we build # So that the YAML config file has a chance to update if($caddToBed) { my $caddToBedRunner = Utils::CaddToBed->new(\%options); $caddToBedRunner->go(); } if($fetch) { my $fetcher = Utils::Fetch->new(\%options); $fetcher->fetch(); } if($liftOverCadd) { my $liftOverCadd = Utils::LiftOverCadd->new(\%options); $liftOverCadd->liftOver(); } if($sortCadd) { my $sortCadder = Utils::SortCadd->new(\%options); $sortCadder->sort(); } if($renameTrack) { say "renaming"; my $renamer = Utils::RenameTrack->new(\%options); $renamer->go(); } #say "done: " . $wantedType || $wantedName . $wantedChr ? ' for $wantedChr' : ''; __END__ =head1 NAME run_utils - Runs items in lib/Utils =head1 SYNOPSIS run_utils --config <file> --compress --name [--debug] =head1 DESCRIPTION C<run_utils.pl> Lets you run utility functions in lib/Utils =head1 OPTIONS =over 8 =item B<-t>, B<--compress> Flag to compress output files =item B<-c>, B<--config> Config: A YAML genome assembly configuration file that specifies the various tracks and data associated with the assembly. This is the same file that is used by the Seq Package to annotate snpfiles. =item B<-w>, B<--name> name: The name of the track in the YAML config file =back =head1 AUTHOR Alex Kotlar =head1 SEE ALSO Seq Package =cut
wingolab-org/seq2-annotator
bin/run_utils.pl
Perl
apache-2.0
3,061
# -*- cperl; cperl-indent-level: 4 -*- package WWW::Wookie::Widget::Category v1.1.1; use strict; use warnings; use utf8; use 5.020000; use Moose qw/around has/; use namespace::autoclean '-except' => 'meta', '-also' => qr/^_/sxm; has '_name' => ( 'is' => 'ro', 'isa' => 'Str', 'reader' => 'getName', ); has '_widgets' => ( 'traits' => ['Hash'], 'is' => 'rw', 'isa' => 'HashRef[WWW::Wookie::Widget]', 'default' => sub { {} }, ); sub put { my ( $self, $widget ) = @_; $self->_widgets->{ $widget->getIdentifier } = $widget; return; } sub get { my $self = shift; return $self->_widgets; } around 'BUILDARGS' => sub { my $orig = shift; my $class = shift; if ( 1 == @_ && !ref $_[0] ) { my ($name) = @_; return $class->$orig( '_name' => $name, ); } return $class->$orig(@_); }; no Moose; __PACKAGE__->meta->make_immutable; 1; __END__ =encoding utf8 =for stopwords Ipenburg MERCHANTABILITY =head1 NAME WWW::Wookie::Widget::Category - client side representation of a widget service category =head1 VERSION This document describes WWW::Wookie::Widget::Category version v1.1.1 =head1 SYNOPSIS use WWW::Wookie::Widget::Category; $c = WWW::Wookie::Widget::Category->new($name); $c->getName; =head1 DESCRIPTION =head1 SUBROUTINES/METHODS =head2 C<new> Create a new service type. =over =item 1. Service name as string =back =head2 C<getName> Gets the name of the service. Returns the name of the service as string. =head2 C<get> Gets the widgets available for this service. Returns an array of L<WWW::Wookie::Widget|WWW::Wookie::Widget> objects. =head2 C<put> Adds a L<WWW::Wookie::Widget|WWW::Wookie::Widget> object to this service. =head1 CONFIGURATION AND ENVIRONMENT =head1 DEPENDENCIES =over 4 =item * L<Moose|Moose> =item * L<namespace::autoclean|namespace::autoclean> =back =head1 INCOMPATIBILITIES =head1 DIAGNOSTICS =head1 BUGS AND LIMITATIONS Please report any bugs or feature requests at L<RT for rt.cpan.org|https://rt.cpan.org/Dist/Display.html?Queue=WWW-Wookie>. =head1 AUTHOR Roland van Ipenburg, E<lt>ipenburg@xs4all.nlE<gt> =head1 LICENSE AND COPYRIGHT Copyright 2017 by Roland van Ipenburg This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.14.0 or, at your option, any later version of Perl 5 you may have available. =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENSE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =cut
ipenburg/WWW-Wookie
lib/WWW/Wookie/Widget/Category.pm
Perl
apache-2.0
3,732
# # Copyright 2022 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 cloud::azure::network::appgateway::mode::units; use base qw(cloud::azure::custom::mode); use strict; use warnings; sub get_metrics_mapping { my ($self, %options) = @_; my $metrics_mapping = { 'capacityunits' => { 'output' => 'Capacity Units consumed', 'label' => 'capacity-units', 'nlabel' => 'appgateway.capacity.units.count', 'unit' => '', 'min' => '0' }, 'computeunits' => { 'output' => 'Compute Units consumed', 'label' => 'compute-units', 'nlabel' => 'appgateway.compute.units.count', 'unit' => '', 'min' => '0' }, 'estimatedbilledcapacityunits' => { 'output' => 'Estimated Billed Capacity Units', 'label' => 'estimated-billed-units', 'nlabel' => 'appgateway.billed.units.estimated.count', 'unit' => '', 'min' => '0' }, 'fixedbillablecapacityunits' => { 'output' => 'Fixed Billable Capacity Units', 'label' => 'fixed-billable-units', 'nlabel' => 'appgateway.billable.units.fixed.count', 'unit' => '', 'min' => '0' } }; return $metrics_mapping; } 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-metric:s' => { name => 'filter_metric' }, 'resource:s' => { name => 'resource' }, 'resource-group:s' => { name => 'resource_group' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{resource}) || $self->{option_results}->{resource} eq '') { $self->{output}->add_option_msg(short_msg => 'Need to specify either --resource <name> with --resource-group option or --resource <id>.'); $self->{output}->option_exit(); } my $resource = $self->{option_results}->{resource}; my $resource_group = defined($self->{option_results}->{resource_group}) ? $self->{option_results}->{resource_group} : ''; if ($resource =~ /^\/subscriptions\/.*\/resourceGroups\/(.*)\/providers\/Microsoft\.Network\/applicationGateways\/(.*)$/) { $resource_group = $1; $resource = $2; } $self->{az_resource} = $resource; $self->{az_resource_group} = $resource_group; $self->{az_resource_type} = 'applicationGateways'; $self->{az_resource_namespace} = 'Microsoft.Network'; $self->{az_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 900; $self->{az_interval} = defined($self->{option_results}->{interval}) ? $self->{option_results}->{interval} : 'PT5M'; $self->{az_aggregations} = ['Average']; if (defined($self->{option_results}->{aggregation})) { $self->{az_aggregations} = []; foreach my $stat (@{$self->{option_results}->{aggregation}}) { if ($stat ne '') { push @{$self->{az_aggregations}}, ucfirst(lc($stat)); } } } foreach my $metric (keys %{$self->{metrics_mapping}}) { next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne '' && $metric !~ /$self->{option_results}->{filter_metric}/); push @{$self->{az_metrics}}, $metric; } } 1; __END__ =head1 MODE Check Azure Application Gateway units statistics. Example: Using resource name : perl centreon_plugins.pl --plugin=cloud::azure::network::appgateway::plugin --mode=units --custommode=api --resource=<appgateway_id> --resource-group=<resourcegroup_id> --aggregation='average' --warning-compute-units='1000' --critical-compute-units='2000' Using resource id : perl centreon_plugins.pl --plugin=cloud::azure::integration::servicebus::plugin --mode=units --custommode=api --resource='/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_id>/providers/Microsoft.Network/applicationGateways/<appgateway_id>' --aggregation='average' --warning-compute-units='1000' --critical-compute-units='2000' Default aggregation: 'average' / 'total', 'minimum' and 'maximum' are valid. =over 8 =item B<--resource> Set resource name or id (Required). =item B<--resource-group> Set resource group (Required if resource's name is used). =item B<--warning-*> Warning threshold where '*' can be: 'estimated-billed-units', 'fixed-billable-units', 'compute-units', 'capacity-units'. =item B<--critical-*> Critical threshold where '*' can be: 'estimated-billed-units', 'fixed-billable-units', 'compute-units', 'capacity-units'. =back =cut
centreon/centreon-plugins
cloud/azure/network/appgateway/mode/units.pm
Perl
apache-2.0
5,596
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::radware::alteon::snmp::mode::vserverstatus; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use Digest::MD5 qw(md5_hex); my $instance_mode; sub custom_status_threshold { my ($self, %options) = @_; my $status = 'ok'; my $message; eval { local $SIG{__WARN__} = sub { $message = $_[0]; }; local $SIG{__DIE__} = sub { $message = $_[0]; }; if (defined($instance_mode->{option_results}->{critical_status}) && $instance_mode->{option_results}->{critical_status} ne '' && eval "$instance_mode->{option_results}->{critical_status}") { $status = 'critical'; } elsif (defined($instance_mode->{option_results}->{warning_status}) && $instance_mode->{option_results}->{warning_status} ne '' && eval "$instance_mode->{option_results}->{warning_status}") { $status = 'warning'; } }; if (defined($message)) { $self->{output}->output_add(long_msg => 'filter status issue: ' . $message); } return $status; } sub custom_status_output { my ($self, %options) = @_; my $msg = 'state : ' . $self->{result_values}->{state}; return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_state'}; $self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'vservers', type => 1, cb_prefix_output => 'prefix_vservers_output', message_multiple => 'All Virtual Servers are ok' } ]; $self->{maps_counters}->{vservers} = [ { label => 'status', threshold => 0, set => { key_values => [ { name => 'state' }, { name => 'display' } ], closure_custom_calc => $self->can('custom_status_calc'), closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => $self->can('custom_status_threshold'), } }, { label => 'traffic', set => { key_values => [ { name => 'traffic', diff => 1 }, { name => 'display' } ], per_second => 1, output_change_bytes => 2, output_template => 'Traffic : %s %s/s', perfdatas => [ { label => 'traffic', value => 'traffic_per_second', template => '%.2f', min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'current-sessions', set => { key_values => [ { name => 'current_sessions' }, { name => 'display' } ], output_template => 'Current Sessions : %s', perfdatas => [ { label => 'current_sessions', value => 'current_sessions_absolute', template => '%s', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, { label => 'total-sessions', set => { key_values => [ { name => 'total_sessions', diff => 1 }, { name => 'display' } ], output_template => 'Total Sessions : %s', perfdatas => [ { label => 'total_sessions', value => 'total_sessions_absolute', template => '%s', min => 0, label_extra_instance => 1, instance_use => 'display_absolute' }, ], } }, ]; } sub prefix_vservers_output { my ($self, %options) = @_; return "Virtual Server '" . $options{instance_value}->{display} . "' "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "filter-name:s" => { name => 'filter_name' }, "warning-status:s" => { name => 'warning_status', default => '' }, "critical-status:s" => { name => 'critical_status', default => '' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $instance_mode = $self; $self->change_macros(); } sub change_macros { my ($self, %options) = @_; foreach (('warning_status', 'critical_status')) { if (defined($self->{option_results}->{$_})) { $self->{option_results}->{$_} =~ s/%\{(.*?)\}/\$self->{result_values}->{$1}/g; } } } my %map_state = ( 2 => 'enabled', 3 => 'disabled', ); my $mapping = { slbCurCfgVirtServerState => { oid => '.1.3.6.1.4.1.1872.2.5.4.1.1.4.2.1.4', map => \%map_state }, slbCurCfgVirtServerVname => { oid => '.1.3.6.1.4.1.1872.2.5.4.1.1.4.2.1.10' }, slbCurCfgVirtServerAvail => { oid => '.1.3.6.1.4.1.1872.2.5.4.1.1.4.2.1.8' }, # can't get mapping for that. If someones has it, i'm interested :) }; my $mapping2 = { slbStatVServerCurrSessions => { oid => '.1.3.6.1.4.1.1872.2.5.4.2.4.1.2' }, slbStatVServerTotalSessions => { oid => '.1.3.6.1.4.1.1872.2.5.4.2.4.1.3' }, slbStatVServerHCOctetsLow32 => { oid => '.1.3.6.1.4.1.1872.2.5.4.2.4.1.5' }, slbStatVServerHCOctetsHigh32 => { oid => '.1.3.6.1.4.1.1872.2.5.4.2.4.1.6' }, slbStatVServerHCOctets => { oid => '.1.3.6.1.4.1.1872.2.5.4.2.4.1.13' }, }; sub manage_selection { my ($self, %options) = @_; my $snmp_result = $options{snmp}->get_multiple_table(oids => [ { oid => $mapping->{slbCurCfgVirtServerState}->{oid} }, { oid => $mapping->{slbCurCfgVirtServerVname}->{oid} }, ], return_type => 1, nothing_quit => 1); $self->{vservers} = {}; foreach my $oid (keys %{$snmp_result}) { next if ($oid !~ /^$mapping->{slbCurCfgVirtServerVname}->{oid}\.(.*)$/); my $instance = $1; my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $instance); if (!defined($result->{slbCurCfgVirtServerVname}) || $result->{slbCurCfgVirtServerVname} eq '') { $self->{output}->output_add(long_msg => "skipping Virtual Server '$instance': cannot get a name. please set it.", debug => 1); next; } if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $result->{slbCurCfgVirtServerVname} !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping Virtual Server '" . $result->{slbCurCfgVirtServerVname} . "'.", debug => 1); next; } $self->{vservers}->{$instance} = { display => $result->{slbCurCfgVirtServerVname}, state => $result->{slbCurCfgVirtServerState} }; } $options{snmp}->load(oids => [$mapping2->{slbStatVServerCurrSessions}->{oid}, $mapping2->{slbStatVServerTotalSessions}->{oid}, $mapping2->{slbStatVServerHCOctetsLow32}->{oid}, $mapping2->{slbStatVServerHCOctetsHigh32}->{oid}, $mapping2->{slbStatVServerHCOctets}->{oid} ], instances => [keys %{$self->{vservers}}], instance_regexp => '^(.*)$'); $snmp_result = $options{snmp}->get_leef(nothing_quit => 1); foreach (keys %{$self->{vservers}}) { my $result = $options{snmp}->map_instance(mapping => $mapping2, results => $snmp_result, instance => $_); $self->{vservers}->{$_}->{traffic} = (defined($result->{slbStatVServerHCOctets}) ? $result->{slbStatVServerHCOctets} * 8 : (($result->{slbStatVServerHCOctetsHigh32} << 32) + $result->{slbStatVServerHCOctetsLow32})) * 8; $self->{vservers}->{$_}->{current_sessions} = $result->{slbStatVServerCurrSessions}; $self->{vservers}->{$_}->{total_sessions} = $result->{slbStatVServerTotalSessions}; } if (scalar(keys %{$self->{vservers}}) <= 0) { $self->{output}->add_option_msg(short_msg => "No virtual server found."); $self->{output}->option_exit(); } $self->{cache_name} = "alteon_" . $self->{mode} . '_' . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' . (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' . (defined($self->{option_results}->{filter_name}) ? md5_hex($self->{option_results}->{filter_name}) : md5_hex('all')); } 1; __END__ =head1 MODE Check vservers status. =over 8 =item B<--warning-*> Threshold warning. Can be: 'traffic', 'total-sessions', 'current-sessions'. =item B<--critical-*> Threshold critical. Can be: 'traffic', 'total-sessions', 'current-sessions'. =item B<--warning-status> Set warning threshold for status. Can used special variables like: %{state}, %{display} =item B<--critical-status> Set critical threshold for status. Can used special variables like: %{state}, %{display} =item B<--filter-name> Filter by virtual server name (can be a regexp). =back =cut
maksimatveev/centreon-plugins
network/radware/alteon/snmp/mode/vserverstatus.pm
Perl
apache-2.0
10,360
#!/usr/bin/perl -w my $file = $ARGV[0]; my @lines = <>; my $anchors = {}; my $i = 0; foreach $line (@lines) { $i++; if ($line =~ m/id="([^"]+)"/) { $anchors->{$1} = $i; } } $i = 0; foreach $line (@lines) { $i++; while ($line =~ m/href="#([^"]+)"/g) { if (! exists($anchors->{$1})) { print "$file:$i: $1 referenced\n"; } } }
jeltz/rust-debian-package
src/etc/check-links.pl
Perl
apache-2.0
392
# 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::Resources::CallReportingSetting; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { callConversionAction => $args->{callConversionAction}, callConversionReportingEnabled => $args->{callConversionReportingEnabled}, callReportingEnabled => $args->{callReportingEnabled}}; # 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/Resources/CallReportingSetting.pm
Perl
apache-2.0
1,214
package Google::Ads::AdWords::v201402::FeedService::query; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' } __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::v201402::FeedService::query =head1 DESCRIPTION Perl data type class for the XML Schema defined element query from the namespace https://adwords.google.com/api/adwords/cm/v201402. Returns the list of Feed that match the query. @param query The SQL-like AWQL query string. @returns A list of Feed. @throws ApiException if problems occur while parsing the query or fetching Feed. =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::v201402::FeedService::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/v201402/FeedService/query.pm
Perl
apache-2.0
1,879
=head1 LICENSE # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2022] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Analysis::Runnable::LowCoverageGenomeAlignment - =head1 SYNOPSIS my $runnable = new Bio::EnsEMBL::Analysis::Runnable::LowCoverageGenomeAlignment (-workdir => $workdir, -multi_fasta_file => "/path/to/mfa/file", -tree_string => $tree_string, -taxon_species_tree => "tree in Newick format" -parameters => $parameters, (optional), -options => $options); $runnable->run; my @output = @{$runnable->output}; =head1 DESCRIPTION This module creates a new tree for those alignments which contain a segmental duplication. The module will runs treeBest where there are more than 3 sequences in an alignment, otherwise it will run semphy. This module is still under development. =head1 METHODS =cut package Bio::EnsEMBL::Analysis::Runnable::LowCoverageGenomeAlignment; use strict; use warnings; use Bio::EnsEMBL::Utils::Exception; use Bio::EnsEMBL::Utils::Argument; use Bio::EnsEMBL::Compara::GenomicAlign; use Bio::EnsEMBL::Compara::GenomicAlignBlock; use Bio::EnsEMBL::Compara::GenomicAlignTree; use Bio::EnsEMBL::Compara::Graph::NewickParser; use Data::Dumper; use File::Basename; use Bio::EnsEMBL::Analysis::Runnable; our @ISA = qw(Bio::EnsEMBL::Analysis::Runnable); =head2 new Arg [1] : -workdir => "/path/to/working/directory" Arg [2] : -multi_fasta_file => "/path/to/mfa/file" Arg [3] : -tree_string => $tree_string (optional) Arg [4] : -taxon_species_tree => $taxon_species_tree Arg [5] : -parameters => $parameters (optional) Arg [6] : -options => $options (optional) Function : contruct a new Bio::EnsEMBL::Analysis::Runnable::LowCoverageGenomeAlignment runnable Returntype: Bio::EnsEMBL::Analysis::Runnable::LowCoverageGenomeAlignment Exceptions: none Example : =cut sub new { my ($class,@args) = @_; my $self = $class->SUPER::new(@args); my ($workdir, $multi_fasta_file, $tree_string, $taxon_species_tree, $semphy_exe, $treebest_exe, $parameters, $options) = rearrange(['WORKDIR', 'MULTI_FASTA_FILE', 'TREE_STRING', 'TAXON_SPECIES_TREE', 'SEMPHY_EXE', 'TREEBEST_EXE', 'PARAMETERS', 'OPTIONS'], @args); chdir $self->workdir; $self->multi_fasta_file($multi_fasta_file) if (defined $multi_fasta_file); $self->tree_string($tree_string) if (defined $tree_string); $self->taxon_species_tree($taxon_species_tree) if (defined $taxon_species_tree); $self->semphy_exe($semphy_exe) if (defined $semphy_exe); $self->treebest_exe($treebest_exe) if (defined $treebest_exe); $self->parameters($parameters) if (defined $parameters); $self->options($options) if (defined $options); return $self; } sub multi_fasta_file { my $self = shift; $self->{'_multi_fasta_file'} = shift if(@_); return $self->{'_multi_fasta_file'}; } sub tree_string { my $self = shift; $self->{'_tree_string'} = shift if(@_); return $self->{'_tree_string'}; } sub semphy_exe { my $self = shift; $self->{'_semphy_exe'} = shift if(@_); return $self->{'_semphy_exe'}; } sub treebest_exe { my $self = shift; $self->{'_treebest_exe'} = shift if(@_); return $self->{'_treebest_exe'}; } sub taxon_species_tree { my $self = shift; $self->{'_taxon_species_tree'} = shift if(@_); return $self->{'_taxon_species_tree'}; } sub parameters { my $self = shift; $self->{'_parameters'} = shift if(@_); return $self->{'_parameters'}; } sub options { my $self = shift; $self->{'_options'} = shift if(@_); return $self->{'_options'}; } =head2 run_analysis Arg [1] : Bio::EnsEMBL::Analysis::Runnable::LowCoverageGenomeAlignment Arg [2] : string, program name Description: run treebest if more than 3 sequences in the alignment else run semphy Returntype : none Exceptions : throws if the program in not executable or if the results file doesnt exist Example : Status : At risk =cut sub run_analysis { my ($self, $program) = @_; #find how many sequences are in the mfa file my $num_sequences = get_num_sequences($self->multi_fasta_file); #treebest phyml needs at least 4 sequences to run. If I have less than #4, then run semphy instead. if ($num_sequences < 4) { $self->run_semphy_2x; } else { $self->run_treebest_2x; } #move this to compara module instead because it is easier to keep track #of the 2x composite fragments. And also it removes the need to create #compara objects in analysis module. #$self->parse_results; return 1; } #Find how many sequences in mfa file sub get_num_sequences { my ($mfa) = @_; my $cnt = 0; open (MFA, "$mfa") || throw("Couldn't open $mfa"); while (<MFA>) { $cnt++ if (/^>/); } close(MFA); return $cnt; } =head2 run_treebest_2x Arg [1] : none Description: create and open a commandline for the program treebest Returntype : none Exceptions : throws if the program in not executable or if the results file doesnt exist Example : Status : At risk =cut sub run_treebest_2x { my ($self) = @_; #Check I don't already have a tree return if ($self->tree_string); chdir $self->workdir; my $tree_file = "output.$$.tree"; #write species tree (with taxon_ids) to file in workdir my $species_tree_file = "species_tree.$$.tree"; open(F, ">$species_tree_file") || throw("Couldn't open $species_tree_file for writing"); print (F $self->taxon_species_tree); close(F); #Run treebeset my $command = $self->treebest_exe ." phyml -Snf $species_tree_file " . $self->multi_fasta_file . " | " . $self->treebest_exe . " sdi -rs $species_tree_file - > $tree_file"; print "Running treebest $command\n"; #run treebest to create tree unless (system($command) == 0) { throw("treebest execution failed\n"); os_error_warning($command); } #read in new tree if (-e $tree_file) { ## Treebest estimated the tree. Overwrite the order of the fasta files and get the tree open(F, $tree_file) || throw("Could not open tree file <$tree_file>"); my $newick; while (<F>) { $newick .= $_; } close(F); $newick =~ s/[\r\n]+$//; rearrange_multi_fasta_file($newick, $self->multi_fasta_file); } } =head2 run_semphy_2x Arg [1] : none Description: create and open a commandline for the program semphy Returntype : none Exceptions : throws if the program in not executable or if the results file doesnt exist Example : Status : At risk =cut sub run_semphy_2x { my ($self) = @_; #Check I don't already have a tree return if ($self->tree_string); chdir $self->workdir; my $tree_file = "output.$$.tree"; #Run semphy directly my $command = $self->semphy_exe . " --treeoutputfile=" . $tree_file . " -a 4 --hky -J -H -S --ACGprob=0.300000,0.200000,0.200000 --sequence=" . $self->multi_fasta_file; print "Running semphy $command\n"; #run semphy to create tree unless (system($command) == 0) { throw("semphy execution failed\n"); os_error_warning($command); } #read in new tree if (-e $tree_file) { ## Semphy estimated the tree. Overwrite the order of the fasta files and get the tree open(F, $tree_file) || throw("Could not open tree file <$tree_file>"); my ($newick) = <F>; close(F); $newick =~ s/[\r\n]+$//; rearrange_multi_fasta_file($newick, $self->multi_fasta_file); } #print "FINAL tree string $tree_string\n"; } =head2 os_error_warning Arg [1] : string: The command line argument of an exec() or system() call. Example : (system($command) == 0) || os_error_warning($command); Description: Evaluates an eventual operating system error in $! ($OS_ERROR) or the 16 bit wait(2) status word in $? ($CHILD_ERROR) after an exec() or system() call. It generates a warning message in both cases. Returntype : bool: true on success. Exceptions : none Caller : general Status : At Risk =cut sub os_error_warning { my $command = shift; my $warning = ''; $warning .= 'Encountered '; if ($!) { $warning .= "OS_ERROR \'$!\'"; } else { $warning .= 'CHILD_ERROR '; $warning .= 'Exit code: '; $warning .= ($? >> 8); $warning .= ' '; $warning .= 'Signal: '; $warning .= ($? & 127); $warning .= ' '; if ($? & 128) { $warning .= ' '; $warning .= 'Core dump '; } } $warning .= " on following command:\n"; $warning .= $command; warning($warning); return 1; } sub rearrange_multi_fasta_file { my ($tree_string, $mfa_file) = @_; my (@ordered_leaves) = $tree_string =~ /(seq[^:]+)/g; my $ordered_names; for (my $i = 0; $i < @ordered_leaves; $i++) { my $item; $item->{name} = ">" . $ordered_leaves[$i]; $item->{leaf} = $ordered_leaves[$i]; push @$ordered_names, $item; } my %mfa_data; open(MFA, $mfa_file) || throw("Could not open mfa file <$mfa_file>"); my $name; my $seq; while (<MFA>) { next if (/^\s*$/); chomp; if (/^>/) { if ($name) { $mfa_data{$name} = $seq; $seq = ""; } $name = $_; } else { $seq .= $_; } } $mfa_data{$name} = $seq; close(MFA); #overwrite existing mfa file open MFA, ">$mfa_file" || throw("Couldn't open $mfa_file"); foreach my $ordered_name (@$ordered_names) { #for ancestral next if (!defined $mfa_data{$ordered_name->{name}}); print MFA ">".$ordered_name->{leaf} . "\n"; my $seq = $mfa_data{$ordered_name->{name}}; $seq =~ s/(.{80})/$1\n/g; chomp $seq; print MFA $seq,"\n"; } close MFA; } 1;
Ensembl/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/Runnable/LowCoverageGenomeAlignment.pm
Perl
apache-2.0
10,615
p(X,X). p(s(X),Y) :- p(X,s(Y)). t(X) :- p(s(s(X)),X), q(X). tz(X) :- p(s(s(X)),X), z(X). q(0). q(s(X)) :- q(X). z(0). tz(X,Y) :- p(s(s(X)),Y), z(X), z(Y).
leuschel/ecce
ecce_examples/Termination/termtest.pl
Perl
apache-2.0
170
use strict; use warnings; use File::Basename; use lib dirname($0); use P4PPortalAPI; sub getPIDMaps { my (@servers) = @_; my %result; foreach my $server (@servers) { my %pidmap = getPIDMap($server); # Remove PIDs without any prefixes my $numprefixes = 0; my $numpids = 0; for my $pid (keys(%pidmap)) { my @prefixes = @{$pidmap{$pid}}; if (@prefixes == 0) { print STDERR "Ignoring empty PID $pid from server $server\n"; delete $pidmap{$pid}; next; } $numprefixes = $numprefixes + @prefixes; ++$numpids; } # Ignore if it has no PIDs next if ($numpids == 0); print STDERR "Using Portal Server: $server with $numpids PIDs and $numprefixes prefixes\n"; $result{$server} = \%pidmap; } return %result; } sub getRandP4PClientIP { my (%pidmaps) = @_; # Choose an ISP at random my @isps = keys(%pidmaps); return undef if (@isps == 0); my $isp = $isps[int(rand(@isps))]; my %pidmap = %{$pidmaps{$isp}}; # Choose a PID at random my @pids = keys(%pidmap); my $pid = $pids[int(rand(@pids))]; # Choose a prefix at random my @prefixes = @{$pidmap{$pid}}; my $prefix = $prefixes[int(rand(@prefixes))]; # Determine low address for the range my ($addr, $length) = split(/\//, $prefix); # If no prefix length (e.g., 32-bit length), return address itself return $addr if (!defined($length) || $length < 0 || $length >= 32); # Generate random offset within subnet my $randOffset = int(2**rand(32 - $length)); # Convert address to integer my $addrInt = unpack('N', pack('C4', split('\.', $addr))); # Extract necessary part of base address $addrInt = $addrInt & ((2**32 - 1) << (32 - $length)); # Add random offset to base address $addrInt = $addrInt + $randOffset; return join('.', unpack('C4', pack('N', $addrInt))); } 1;
Yale-LANS/ALTO
example-apps/tracker/emulator/data/scripts/Generate.pm
Perl
bsd-3-clause
1,802
# 1 "liblats.c" # 1 "<built-in>" # 1 "<command-line>" # 1 "liblats.c" # 984 "liblats.c" =pod =head1 NAME liblats.gex - GrADS Extension Library for File Subsetting and Reformatting =head1 SYNOPSIS =head3 GrADS Commands: =over 4 =item run B<set_lats> I<PARAMETER> I<VALUE> - Set internal parameters =item run B<query_lats> - Print internal paramaters =item run B<lats_grid> I<EXPR> - Set horizontal grid =item run B<lats_data> I<EXPR> - Write data to file =back =head1 DESCRIPTION This library provides GrADS extensions (I<gex>) for interfacing to LATS (Library of AMIP II Transmission Standards), a collection of I/O functions for creating lon/lat gridded datasets in the GRIB, NetCDF-3, NetCDF-4/HDF-5 and HDF-4 formats. This is the low level LATS interface in GrADS. Usually, one uses the wrapper B<lats4d.gs> script (L<http://opengrads.org/doc/scripts/lats4d/>) for a more user friendly interface which has reasonable defaults for most internal parameters. The GrADS interface to LATS is implemented by means of 4 I<User Defined Commands> (UDCs). Most parameters defining the output file are set by means of the B<set_lats> command; the current LATS state can queried with command B<query_lats>. Command B<lats_grid> is used to define the horizontal longitude/lattude grid (vertical levels are set with the B<set_lats> command.) Command B<lats_data> is used to write a 2-dimensional (longitude x latitude) slice of a variable, for a given time and level. The following sub-section describes the main attributes of the LATS library which this extension interfaces to. It has been adapted from the original LATS manual page. =head2 Overview of the LATS Library LATS is a subroutine library developed by the Program for Climate Model Diagnosis and Intercomparison (PCMDI) to output lon/lat gridded data for the AMIP II (Atmospheric Model Intercomparison Project II) and other intercomparison projects. In addition to outputting data, LATS optionally performs basic quality control on the data written. LATS outputs data in the GRIB and/or netCDF formats and provides an interface to GrADS and VCS. The LATS library is no longer supported by the original developers at PCMDI but remains as a viable mechanism for producing GRID-1, NetCDF and HDF output from GrADS. The main features of LATS are: =over 4 =item 1 LATS is designed to output rectilinear, generally global, gridded, spatio-temporal data. The amount of data written with a single function call is a horizontal longitude-latitude slice of a variable. =item 2 Data may be output in the machine-independent formats GRIB and/or netCDF and are directly readable by GrADS. =item 3 Acceptable variable names are prescribed. The units, datatype, and basic structure (e.g., single-level or multi-level) are inferred from the variable name. This information is tabled in an external, ASCII I<parameter table>. If no parameter table is specified, a default list of AMIP II parameters is used. =item 4 More than one LATS file may be open simultaneously for output. In GrADS, one usually write one file at a time. =item 5 Data must be written in increasing time sequence. All variables in a file share a common time frequency (e.g., hourly, monthly, etc.). Originally LATS did not support minutes, but a patch has ben developed in version used by GrADS to allow minutes are a valid time sequence. =item 6 For a given timepoint, variables, and multiple levels for a variable, may be written in any order. =item 7 Although GrADS Version 2 uses doubles (64 bits) to store variable data, all data written to file by this interface are floating-point or integer. INTEGER*8), and C int data can be written. =item 8 Data written to GRIB files are packed to a predefined bit width or numerical precision depending on the variable. The precision and bit width is specified in the I<parameter table> file. Floating-point data written to netCDF files are saved as 32-bit IEEE floating-point values; integer data are written as 32-bit 2's complement integers. =back =head1 ANATOMY OF A LATS BASED GRADS SCRIPT The skeleton of a GrADS script using the LATS interface is as follows: =over 4 =item 1. Optionally, specify an external parameter file, with B<set_lats> I<parmtab>. =item 2. Define the horizontal grid with B<lats_grid>. Define all vertical dimensions (e.g., pressure level) with B<set_lats> I<vertdim>. If a default surface dimension is defined for a variable, it does not have to be redefined with B<set_lats> I<vertdim>. Grids and vertical dimensions are shared across variables. NOTE: At present, only one grid may be defined for a GrADS/GRIB file. =item 3. Create a LATS file, with B<set_lats> I<create>. =item 4. Optionally, set the basetime, with B<set_lats> I<basetime>. =item 5. For EACH AND EVERY variable to be written, declare the variable with B<set_lats> I<var>. The LATS requirement that ALL variables be declared up front (before writing) is necessitated by the netCDF interface. =item 6. For each time-point, in increasing time order and, for each horizontal level of each variable, write the data for this level, time-point, with B<set_lats> I<write> and B<lats_data>. =item 7. Close the file, with B<set_lats> I<close>. =back By default, all errors are reported. =head2 QUALITY CONTROL LATS performs some basic quality control on the data written. The intention is to provide a quick check of data validity. For each level written the following statistics are calculated: range (maximum-minimum) and area-weighted average. If a missing data flag is defined for the variable, any missing data are ignored in calculating the statistics. Quality control is not performed on integer-valued variables. A QC exception is generated if abs(average - observed_average) > (tolerance * observed_standard_deviation). Similarly, an exception is generated if range > (range_tolerance * observed_range). In either case, a warning is issued, and an entry is written to the QC log file. The values of observed_average, tolerance, observed_standard_deviation, range_tolerance, and observed_range are tabled in the QC section of the I<Parameter Table> file. If no entry in this section is found for the given (variable,level_type,level), then no quality control is performed for that level. Data are always written, regardless of whether a QC exception is generated. The default name of the log file is I<lats.log>. This name is superseded by the value of the environment variable LATS_LOG, if defined. =head1 COMMANDS PROVIDED =head2 B<set_lats> I<basetime YEAR MONTH DAY HOUR> Set the basetime for file with ID fileid. The basetime is the initial time in which the file can be referenced. The function returns 1 if successful, 0 if an error oc- curs. =head2 B<set_lats> I<close> Close the file. The function returns 1 if successful, 0 if an error occurs. =over 8 =item B<NOTE:> It is important to call B<set_lats close>, to ensure that any buffered output is written to the file. =back =head2 B<set_lats> I<create FILENAME> Create a LATS file with the given I<FILENAME>, a string of length <= 256. If I<FILENME> does not end in the proper extension ('.nc' for netCDF, '.grb' for GRIB), the extension will be appended to the path. =head2 B<set_lats> I<convention CONVENTION> Deprecated. Same as B<set_lats> I<format>. =head2 B<set_lats> I<format FORMAT> The parameter I<FORMAT> defines the data format to be written, and the metadata convention to be followed when writing the format. The options are: =over 8 =item I<grads_grib> WMO GRIB format, plus a GrADS control file and the ancillary GRIB map file. If this format is used the time step (see B<set_lats deltat>) must be non-zero, implying that timepoints are evenly-spaced. All variables in a file must share the same horizontal grid. This convention is readable with GrADS. The GRIB data may be processed by the utility B<wgrib> shipped with most GrADS distributions. =item I<grib> Similar to I<grads_grib> but without a GrADS control file and the ancillary GRIB map file. =item I<netcdf> NetCDF-3 format, observing the COARDS metadata standard. When this format is specified, the calendar must be I<STANDARD>. Climatologies are indicated by specifying I<year = 2> in B<set_lats write>. For the I<clim> and I<climleap> calendars, the year is automatically set to 2. Files wiritten with this format are readable with GrADS. =item I<netcdf4> Like the I<netcdf> format, except that the files are in the new NetCDF-4 (actually HDF-5) format. =item I<hdf4> Like the I<netcdf> format, except that the files are in the new HDF-4 format. Notice that in GrADS v2, NetCDF and HDF-4 files are produced with the same GrADS executables. =back =head2 B<set_lats> I<calendar CALENDAR> I<CALENDAR> is the calendar type, one of the following values: =over 4 =item I<STANDARD> Standard Gregorian calendar. This is the default. =item I<NOLEAP> 365days/year, no leap years =item I<CLIM> Climatological time (no associated year), 365 days =item I<CLIMLEAP> Climatological time, 366 days =back =head2 B<set_lats> I<center CENTER> I<CENTER> is the name of the modeling center or group creating the file, a string of <= 128 characters. For GRIB output, center must match one of the centers listed in the parameter file. =head2 B<set_lats> I<deltat DeltaT> I<DeltaT> is the number of time units in the time increment, where the units are specified by frequency. For example, data which are defined at multiples of 6 hours would be specified with ga-> set_lats frequency hourly ga-> set_lats deltat 6 Similarly, monthly average data would be indicated by ga-> set_lats frequency monthly ga-> set_lats deltat 1 Note that times may be skipped for formats other than I<GRADS_GRIB>; the only requirement imposed by the LATS interface is that timepoints, as specified via B<set_lats write>, be at a multiple of the time increment, relative to the base time (the first time written). =head2 B<set_lats> I<frequency FREQUENCY> I<FREQUENCY> is the time frequency of variables to be written to the file, and has one of the values: =over 4 =item I<YEARLY> Only the year component of time is significant. I<DeltaT> (see B<set_lats>) is expressed in years. =item I<MONTHLY> The year and month components of time are significant. I<DeltaT> (see B<set_lats>) is expressed in months. Floating-point data in the I<GRADS_GRIB> format are compressed to 16-bits. =item I<MONTHLY_TABLE_COMP> The year and month components of time are significant. I<DeltaT> (see B<set_lats>) is expressed in months. Floating-point data in the I<GRADS_GRIB> format are compressed according to the specification in the parameter table. =item I<WEEKLY> The year, month, and day component of time are significant. I<DeltaT> is expressed in weeks. =item I<DAILY> The year, month, and day component of time are significant. delta is expressed in days. =item I<HOURLY> The year, month, day, and hour component of time are significant. I<DeltaT> is expressed in hours. =item I<MINUTES> The year, month, day, hour, and minute component of time are significant. I<DeltaT> is expressed in minutes. =item I<FORECAST_HOURLY> The year, month, day, and hour component of time are significant. I<DeltaT> is expressed in hours. =item I<FORECAST_MINUTES> The year, month, day, hour, and minute component of time are significant. I<DeltaT> is expressed in minutes. =item I<FIXED> Data are not time-dependent, e.g., for surface type, orography, etc. I<DeltaT> is ignored and year is set to 1 by convention. =back =head2 B<set_lats> I<gridtype GRIDTYPE> Define the type of horizontal grid. I<GRIDTYPE> is GAUSSIAN for Gaussian grids, LINEAR for evenly spaced grids, or GENERIC otherwise. The actual horizontal grid definition is performed with command B<lats_grid>. =head2 B<set_lats> I<gzip COMPRESSION_LEVEL> When writing NetCDF-4 files, specifes the level of GZIP compression to be employed. The higher the level, the harder the library works doing compression, usually (but not always) producing smaller files. The default is -1, meaning no compression. Notice that only NetCDF-4 files can be compressed. When I<COMPRESION_LEVEL> > 0 is specified with NetCDF-3 files, the format is automatically changed to NetCDF-4. For improving the compression effectiveness see B<set_lats> I<shave>. =head2 B<set_lats> I<model MODEL> I<MODEL> is the name of the model version which created this data. comments is a string of length 256 or less , including any null- terminator. The command returns an integer file ID, or 0 if the file cannot be created. =head2 B<set_lats> I<parmtab TABLE_FILENAME> Specify an external parameter table file. I<TABLE_FILENAME> is the pathname of a file containing a list of variable descriptions, and is a string of length <= 256 characters. Use of an external parameter table is optional. The location of the parameter table is determined as follows: (1) if the command B<set_lats> I<parmtab> is issued, the value of I<TABLE_FILENAME> is used, otherwise (2) if the environment variable LATS_PARMS is defined, its value is used, else (3) an internally-defined table of AMIP parameters is used. The command returns 1 on success, 0 on failure. =head2 B<set_lats> I<shave NBITS> Shave I<NBITS> off the mantissa of float-point numbers. By definition, IEEE float numbers have 24 bits dedicated for the mantissa. This command set to zero the last I<NBITS> of the mantissa, this way reducing entropy and improving the effectiveness of GZIP compression (see B<set_lats> I<gzip>). I<NBITS> must be in the range [1,23]. When I<NBITS> > 0 is specified, it automatically sets GZIP compression on at level 2, unless the compression level has already been set. (Currently compression is implemented only for NetCDF04 output.) NOTE: The actual shaving algorithm, first scales the variable being written for each horizontal layer, and then shaves bits off the mantissa. See http://en.wikipedia.org/wiki/Ieee_float for additional information on IEEE float-point numbers. =head2 B<set_lats> I<var VARNAME TIMESTAT LEVEL_ID> Declare a variable to be written to a LATS file. fileid is the integer file ID returned from lats_create. The variable name I<VARNAME> must match a name in the parameter table, and is a string of length <= 128 characters. I<TIMESTAT> is a time statistic identifier, one of: =over 4 =item I<AVERAGE> An average over the delta time interval frequency defined by lats_create. =item I<INSTANT> The field is valid at the instan- taneous time set by the year, month, day, hour. =item I<ACCUM> Accumulation during delta time interval I<DeltatT> (see B<set_lats deltat>). =back I<LEVID> is the ID of the vertical dimension of the variable, as returned from B<set_lats> I<vertdim>. If the variable has a default surface defined in the parameter table, or has no associated vertical dimension, I<LEVID> should be 0. (Note: if levid is 0 and the variable has a default surface defined, the netCDF representation of the variable will not have an explicit vertical dimension, but will have a I<level_description> attribute). B<set_lats var> should be called exactly once for each variable to be written to a LATS file and must be called BEFORE B<set_lats> I<write>. The function returns the integer variable ID on success, or 0 on failure. =head2 B<set_lats> I<vertdim DIM_NAME LEV_TYPE LEV_1 ... LEV_N> I<DIM_NAME> is the name of the vertical dimension (e.g., "height", "depth", "level"), and it should not contain any whitespace characters. I<LEV_TYPE> is the vertical dimension type. It must match one of the level types defined in the vertical dimension types section of the parameterfile, e.g., I<plev, hybrid>, etc. I<LEV_1>, ..., I<LEV_N> is a strictly monotonic list of level values. Multi-level variables must have a vertical dimension defined. If a single-level (e.g., surface) variable has a default level type specified in the parameter table, it is not necessary to call B<set_lats> I<vertdim>, since the level type will be associated with the variable by default. Note that the level units are determined from the vertical dimension type table entry for name. This command returns an integer level ID on success, or 0 on failure. =head2 B<set_lats> I<write VAR_ID [LEVEL]> Specifies which variable in the file will be written next. I<VAR_ID> is the integer variable ID returned from B<set_lats> I<var>. I<LEVEL> is the level value, and must match one of the levels declared via lats_vert_dim. (Exception: if the variable was declared with levid=0, the value of I<LEVEL> is ignored.) year is the four-digit integer year, month is the month number (1-12), day is the day in month (1-31), and hour is the integer hour (0-23). =head2 B<lats_grid> I<EXPR> Define a horizontal, longitude-latitude grid, based on the dimension environment associated with the GrADS expression I<EXPR>. The grid type is specified with command B<set_lats> I<gridtype>. =head2 B<lats_data> I<EXPR> Write a horizontal longitude-latitude cross-section of a variable contained in the GrADS expression I<EXPR>. The actual variable on file being written to is specified with he B<set_lats> I<write> command. For monthly data, as specified by lats_create, day and hour are ignored. For daily and weekly data, the hour is ignored. For fixed data, the year, month, day, and hour are ignored. For surface variables, lev is ignored. This command returns 1 if successful, 0 on failure. =head2 B<query_lats> Prints out the value of all internal parameters. =head1 ENVIRONMENT VARIABLES =over 4 =item LATS_PARMS Parameter table file (supersedes internal table if defined) =item LATS_LOG Log file (default: lats.log) =back =head1 HISTORICAL NOTES LATS was first introduced in GrADS v1.7 in the late 1990's by Mike Fiorino as means of producing GRIB-1/NetCDF output from GrADS. With the introduction of GrADS v2.0 in 2008, COLA removed LATS from the GrADS code base. In 2009, the OpenGrADS Project reintroduced LATS in GrADS v2.0 as a User Defiend Extension, adding support for NetCDF-3, NetCDF-4/HDF-5 and HDF-4 all from the same executable. =head1 SEE ALSO =over 4 =item * L<http://opengrads.org/> - OpenGrADS Home Page =item * L<http://cookbooks.opengrads.org/index.php?title=Main_Page> - OpenGrADS Cookbooks =item * L<http://opengrads.org/wiki/index.php?title=User_Defined_Extensions> - OpenGrADS User Defined Extensions =item * L<http://www.iges.org/grads/> - Official GrADS Home Page =item * L<http://www-pcmdi.llnl.gov> - PCMDI =item * L<http://www-pcmdi.llnl.gov/software/lats> - LATS =item * L<http://www.unidata.ucar.edu/packages/netcdf> - NetCDF =item * L<ftp://ncardata.ucar.edu/docs/grib/guide.txt> - GRIB =item * L<http://ferret.wrc.noaa.gov/noaa_coop/coop_cdf_profile.html> - COARDS =item * L<http://wesley.wwb.noaa.gov/wgrib.html> - wgrib =item * L<http://opengrads.org/doc/scripts/lats4d/> - LATS4D =item * L<http://en.wikipedia.org/wiki/Ieee_float> - IEEE Float numbers =back =head1 AUTHORS Arlindo da Silva (dasilva@opengrads.org) wrote the GrADS UDXT interface and created this dcumentation from the LATS manual page. Mike Fiorino (mfiorino@gmail) wrote the actual LATS interface to GrADS. Robert Drach, Mike Fiorino and Peter Gleckler (PCMDI/LLNL) wrote the original LATS library. =head1 COPYRIGHT The code implementing the GrADS extension has been placed in the public domain. Portions (C) 1996, Regents of the University of California. See the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
bucricket/projectMASviirs
source/bin/Linux/Versions/2.0.2.oga.2/x86_64/liblats.pod
Perl
bsd-3-clause
19,632
# Functions for checking for updates to packages from YUM, APT or some other # update system. BEGIN { push(@INC, ".."); }; eval "use WebminCore;"; &init_config(); &foreign_require("software", "software-lib.pl"); &foreign_require("cron", "cron-lib.pl"); &foreign_require("webmin", "webmin-lib.pl"); $available_cache_file = &cache_file_path("available.cache"); $current_cache_file = &cache_file_path("current.cache"); $updates_cache_file = &cache_file_path("updates.cache"); $cron_cmd = "$module_config_directory/update.pl"; $yum_cache_file = &cache_file_path("yumcache"); $apt_cache_file = &cache_file_path("aptcache"); $yum_changelog_cache_dir = &cache_file_path("yumchangelog"); # cache_file_path(name) # Returns a path in the /var directory unless the file already exists under # /etc/webmin sub cache_file_path { my ($name) = @_; if (-e "$module_config_directory/$name") { return "$module_config_directory/$name"; } return "$module_var_directory/$name"; } # get_software_packages() # Fills in software::packages with list of installed packages (if missing), # returns count. sub get_software_packages { if (!$get_software_packages_cache) { %software::packages = ( ); $get_software_packages_cache = &software::list_packages(); } return $get_software_packages_cache; } # list_current(nocache) # Returns a list of packages and versions for installed software. Keys are : # name - The my package name (ie. CSWapache2) # update - Name used to refer to it by the updates system (ie. apache2) # version - Version number # epoch - Epoch part of the version # desc - Human-readable description sub list_current { my ($nocache) = @_; if ($nocache || &cache_expired($current_cache_file)) { my $n = &get_software_packages(); my @rv; for(my $i=0; $i<$n; $i++) { push(@rv, { 'name' => $software::packages{$i,'name'}, 'update' => $software::packages{$i,'name'}, 'version' => $software::packages{$i,'version'}, 'epoch' => $software::packages{$i,'epoch'}, 'desc' => $software::packages{$i,'desc'}, 'system' => $software::update_system, }); &fix_pkgadd_version($rv[$#rv]); } # Filter out dupes and sort by name @rv = &filter_duplicates(\@rv); &write_cache_file($current_cache_file, \@rv); return @rv; } else { return &read_cache_file($current_cache_file); } } # list_available(nocache) # Returns the names and versions of packages available from the update system sub list_available { my ($nocache) = @_; my $expired = &cache_expired($available_cache_file); if ($nocache || $expired == 2 || $expired == 1 && !&check_available_lock()) { # Get from update system my @rv; my @avail = &packages_available(); foreach my $avail (@avail) { $avail->{'update'} = $avail->{'name'}; $avail->{'name'} = &csw_to_pkgadd($avail->{'name'}); push(@rv, $avail); } # Filter out dupes and sort by name @rv = &filter_duplicates(\@rv); if (!@rv) { # Failed .. fall back to cache @rv = &read_cache_file($available_cache_file); } &write_cache_file($available_cache_file, \@rv); return @rv; } else { return &read_cache_file($available_cache_file); } } # check_available_lock() # Returns 1 if the package update system is currently locked sub check_available_lock { if ($software::update_system eq "yum") { return &check_pid_file("/var/run/yum.pid"); } return 0; } # filter_duplicates(&packages) # Given a list of package structures, orders them by name and version number, # and removes dupes with the same name sub filter_duplicates { my ($pkgs) = @_; my @rv = sort { $a->{'name'} cmp $b->{'name'} || &compare_versions($b, $a) } @$pkgs; my %done; return grep { !$done{$_->{'name'},$_->{'system'}}++ } @rv; } # cache_expired(file) # Checks if some cache has expired. Returns 0 if OK, 1 if expired, 2 if # totally missing. sub cache_expired { my ($file) = @_; my @st = stat($file); return 2 if (!@st); if (!$config{'cache_time'} || time()-$st[9] > $config{'cache_time'}*60*60) { return 1; } return 0; } sub write_cache_file { my ($file, $arr) = @_; eval "use Data::Dumper"; if (!$@) { &open_tempfile(FILE, ">$file"); &print_tempfile(FILE, Dumper($arr)); &close_tempfile(FILE); $read_cache_file_cache{$file} = $arr; } } # read_cache_file(file) # Returns the contents of some cache file, as an array ref sub read_cache_file { my ($file) = @_; if (defined($read_cache_file_cache{$file})) { return @{$read_cache_file_cache{$file}}; } if (-r $file) { do $file; $read_cache_file_cache{$file} = $VAR1; return @$VAR1; } return ( ); } # compare_versions(&pkg1, &pk2) # Returns -1 if the version of pkg1 is older than pkg2, 1 if newer, 0 if same. sub compare_versions { my ($pkg1, $pkg2) = @_; if ($pkg1->{'system'} eq 'webmin' && $pkg2->{'system'} eq 'webmin') { # Webmin module version compares are always numeric return $pkg1->{'version'} <=> $pkg2->{'version'}; } my $ec = $pkg1->{'epoch'} <=> $pkg2->{'epoch'}; if ($ec && ($pkg1->{'epoch'} eq '' || $pkg2->{'epoch'} eq '') && $pkg1->{'system'} eq 'apt') { # On some Debian systems, we don't have a my epoch $ec = undef; } return $ec || &software::compare_versions($pkg1->{'version'}, $pkg2->{'version'}); } sub find_cron_job { my @jobs = &cron::list_cron_jobs(); my ($job) = grep { $_->{'user'} eq 'root' && $_->{'command'} eq $cron_cmd } @jobs; return $job; } # packages_available() # Returns a list of all available packages, as hash references with name and # version keys. These come from the APT, YUM or CSW update system, if available. # If not, nothing is returned. sub packages_available { if (@packages_available_cache) { return @packages_available_cache; } if (defined(&software::update_system_available)) { # From a decent package system my @rv = software::update_system_available(); my %done; foreach my $p (@rv) { $p->{'system'} = $software::update_system; $p->{'version'} =~ s/,REV=.*//i; # For CSW if ($p->{'system'} eq 'apt' && !$p->{'source'}) { $p->{'source'} = $p->{'file'} =~ /virtualmin/i ? 'virtualmin' : $p->{'file'} =~ /debian/i ? 'debian' : $p->{'file'} =~ /ubuntu/i ? 'ubuntu' : undef; } $done{$p->{'name'}} = $p; } if ($software::update_system eq "yum" && &has_command("up2date")) { # YUM is the package system select, but up2date is installed # too (ie. RHEL). Fetch its packages too.. if (!$done_rhn_lib++) { do "../software/rhn-lib.pl"; } my @rhnrv = &update_system_available(); foreach my $p (@rhnrv) { $p->{'system'} = "rhn"; my $d = $done{$p->{'name'}}; if ($d) { # Seen already .. but is this better? if (&compare_versions($p, $d) > 0) { # Yes .. replace @rv = grep { $_ ne $d } @rv; push(@rv, $p); $done{$p->{'name'}} = $p; } } else { push(@rv, $p); $done{$p->{'name'}} = $p; } } } @packages_available_cache = @rv; return @rv; } return ( ); } sub supports_updates_available { return defined(&software::update_system_updates); } # updates_available(no-cache) # Returns an array of hash refs of package updates available, according to # the update system, with caching. sub updates_available { my ($nocache) = @_; if (!scalar(@updates_available_cache)) { if ($nocache || &cache_expired($updates_cache_file)) { # Get from original source @updates_available_cache = &software::update_system_updates(); foreach my $a (@updates_available_cache) { $a->{'update'} = $a->{'name'}; $a->{'system'} = $software::update_system; } &write_cache_file($updates_cache_file, \@updates_available_cache); } else { # Use on-disk cache @updates_available_cache = &read_cache_file($updates_cache_file); } } return @updates_available_cache; } # package_install(package-name, [system]) # Install some package, either from an update system or from Webmin. Returns # a list of updated package names. sub package_install { my ($name, $system) = @_; my @rv; my $pkg; # First get from list of updates ($pkg) = grep { $_->{'update'} eq $name && ($_->{'system'} eq $system || !$system) } sort { &compare_versions($b, $a) } &list_possible_updates(0); if (!$pkg) { # Then try list of all available packages ($pkg) = grep { $_->{'update'} eq $name && ($_->{'system'} eq $system || !$system) } sort { &compare_versions($b, $a) } &list_available(0); } if (!$pkg) { print &text('update_efindpkg', $name),"<p>\n"; return ( ); } if (defined(&software::update_system_install)) { # Using some update system, like YUM or APT &clean_environment(); if ($software::update_system eq $pkg->{'system'}) { # Can use the default system @rv = &software::update_system_install($name, undef, 1); } else { # Another update system exists!! Use it.. if (!$done_rhn_lib++) { do "../software/$pkg->{'system'}-lib.pl"; } if (!$done_rhn_text++) { %text = ( %text, %software::text ); } @rv = &update_system_install($name, undef, 1); } &reset_environment(); } else { &error("Don't know how to install package $pkg->{'name'} with type $pkg->{'type'}"); } # Flush installed cache unlink($current_cache_file); return @rv; } # package_install_multiple(&package-names, system) # Install multiple packages, either from an update system or from Webmin. # Returns a list of updated package names. sub package_install_multiple { my ($names, $system) = @_; my @rv; my $pkg; if (defined(&software::update_system_install)) { # Using some update system, like YUM or APT &clean_environment(); if ($software::update_system eq $system) { # Can use the default system @rv = &software::update_system_install( join(" ", @$names), undef, 1); } else { # Another update system exists!! Use it.. if (!$done_rhn_lib++) { do "../software/$pkg->{'system'}-lib.pl"; } if (!$done_rhn_text++) { %text = ( %text, %software::text ); } @rv = &update_system_install(join(" ", @$names), undef, 1); } &reset_environment(); } else { &error("Don't know how to install packages"); } # Flush installed cache unlink($current_cache_file); return @rv; } # list_package_operations(package|packages, system) # Given a package (or space-separate package list), returns a list of all # dependencies that will be installed sub list_package_operations { my ($name, $system) = @_; if (defined(&software::update_system_operations)) { my @rv = &software::update_system_operations($name); foreach my $p (@rv) { $p->{'system'} = $system; } return @rv; } return ( ); } # list_possible_updates([nocache]) # Returns a list of updates that are available. Each element in the array # is a hash ref containing a name, version, description and severity flag. # Intended for calling from themes. Nocache 0=cache everything, 1=flush all # caches, 2=flush only current sub list_possible_updates { my ($nocache) = @_; my @rv; my @current = &list_current($nocache); if (&supports_updates_available()) { # Software module supplies a function that can list just packages # that need updating my %currentmap; foreach my $c (@current) { $currentmap{$c->{'name'},$c->{'system'}} ||= $c; } foreach my $a (&updates_available($nocache == 1)) { my $c = $currentmap{$a->{'name'},$a->{'system'}}; next if (!$c); next if ($a->{'version'} eq $c->{'version'}); push(@rv, { 'name' => $a->{'name'}, 'update' => $a->{'update'}, 'system' => $a->{'system'}, 'version' => $a->{'version'}, 'oldversion' => $c->{'version'}, 'epoch' => $a->{'epoch'}, 'oldepoch' => $c->{'epoch'}, 'security' => $a->{'security'}, 'source' => $a->{'source'}, 'desc' => $c->{'desc'} || $a->{'desc'} }); } } else { # Compute from current and available list my @avail = &list_available($nocache == 1); my %availmap; foreach my $a (@avail) { my $oa = $availmap{$a->{'name'},$a->{'system'}}; if (!$oa || &compare_versions($a, $oa) > 0) { $availmap{$a->{'name'},$a->{'system'}} = $a; } } foreach my $c (sort { $a->{'name'} cmp $b->{'name'} } @current) { # Work out the status my $a = $availmap{$c->{'name'},$c->{'system'}}; if ($a->{'version'} && &compare_versions($a, $c) > 0) { # A regular update is available push(@rv, { 'name' => $a->{'name'}, 'update' => $a->{'update'}, 'system' => $a->{'system'}, 'version' => $a->{'version'}, 'oldversion' => $c->{'version'}, 'epoch' => $a->{'epoch'}, 'oldepoch' => $c->{'epoch'}, 'security' => $a->{'security'}, 'source' => $a->{'source'}, 'desc' => $c->{'desc'} || $a->{'desc'}, 'severity' => 0 }); } } } return @rv; } # list_possible_installs([nocache]) # Returns a list of packages that could be installed, but are not yet sub list_possible_installs { my ($nocache) = @_; my @rv; my @current = &list_current($nocache); my @avail = &list_available($nocache == 1); foreach my $a (sort { $a->{'name'} cmp $b->{'name'} } @avail) { ($c) = grep { $_->{'name'} eq $a->{'name'} && $_->{'system'} eq $a->{'system'} } @current; if (!$c && &installation_candiate($a)) { push(@rv, { 'name' => $a->{'name'}, 'update' => $a->{'update'}, 'system' => $a->{'system'}, 'version' => $a->{'version'}, 'epoch' => $a->{'epoch'}, 'desc' => $a->{'desc'}, 'severity' => 0 }); } } return @rv; } # csw_to_pkgadd(package) # On Solaris systems, convert a CSW package name like ap2_modphp5 to a # real package name like CSWap2modphp5 sub csw_to_pkgadd { my ($pn) = @_; if ($gconfig{'os_type'} eq 'solaris') { $pn =~ s/[_\-]//g; $pn = "CSW$pn"; } return $pn; } # fix_pkgadd_version(&package) # If this is Solaris and the package version is missing, we need to make # a separate pkginfo call to get it. sub fix_pkgadd_version { my ($pkg) = @_; if ($gconfig{'os_type'} eq 'solaris') { if (!$pkg->{'version'}) { # Make an extra call to get the version my @pinfo = &software::package_info($pkg->{'name'}); $pinfo[4] =~ s/,REV=.*//i; $pkg->{'version'} = $pinfo[4]; } else { # Trip off the REV= $pkg->{'version'} =~ s/,REV=.*//i; } } $pkg->{'desc'} =~ s/^\Q$pkg->{'update'}\E\s+\-\s+//; } # installation_candiate(&package) # Returns 1 if some package can be installed, even when it currently isn't. # Always true for now. sub installation_candiate { my ($p) = @_; return 1; } # clear_repository_cache() # Clear any YUM or APT caches sub clear_repository_cache { if ($software::update_system eq "yum") { &execute_command("yum clean all"); } elsif ($software::update_system eq "apt") { &execute_command("apt-get update"); } elsif ($software::update_system eq "ports") { &foreign_require("proc"); foreach my $cmd ("portsnap fetch", "portsnap update || portsnap extract") { my ($fh, $pid) = &proc::pty_process_exec($cmd); while(<$fh>) { } close($fh); } } } # split_epoch(version) # Splits a version formatted like 5:x.yy into an epoch and real version sub split_epoch { my ($ver) = @_; if ($ver =~ /^(\d+):(\S+)$/) { return ($1, $2); } return (undef, $ver); } # get_changelog(&pacakge) # If possible, returns information about what has changed in some update sub get_changelog { my ($pkg) = @_; if ($pkg->{'system'} eq 'yum') { # See if yum supports changelog if (!defined($supports_yum_changelog)) { my $out = &backquote_command("yum -h 2>&1 </dev/null"); $supports_yum_changelog = $out =~ /changelog/ ? 1 : 0; } return undef if (!$supports_yum_changelog); # Check if we have this info cached my $cfile = $yum_changelog_cache_dir."/". $pkg->{'name'}."-".$pkg->{'version'}; my $cl = &read_file_contents($cfile); if (!$cl) { # Run it for this package and version my $started = 0; &open_execute_command(YUMCL, "yum changelog all ". quotemeta($pkg->{'name'}), 1, 1); while(<YUMCL>) { s/\r|\n//g; if (/^\Q$pkg->{'name'}-$pkg->{'version'}\E/) { $started = 1; } elsif (/^==========/ || /^changelog stats/) { $started = 0; } elsif ($started) { $cl .= $_."\n"; } } close(YUMCL); # Save the cache if (!-d $yum_changelog_cache_dir) { &make_dir($yum_changelog_cache_dir, 0700); } &open_tempfile(CACHE, ">$cfile"); &print_tempfile(CACHE, $cl); &close_tempfile(CACHE); } return $cl; } return undef; } sub flush_package_caches { unlink($current_cache_file); unlink($updates_cache_file); unlink($available_cache_file); unlink($available_cache_file.'0'); unlink($available_cache_file.'1'); @packages_available_cache = ( ); %read_cache_file_cache = ( ); } # list_for_mode(mode, nocache) # If not is 'updates' or 'security', return just updates. Othewise, return # all available packages. sub list_for_mode { my ($mode, $nocache) = @_; return $mode eq 'updates' || $mode eq 'security' ? &list_possible_updates($nocache) : &list_available($nocache); } # check_reboot_required(after-flag) # Returns 1 if the package system thinks a reboot is needed sub check_reboot_required { if ($gconfig{'os_type'} eq 'debian-linux') { return -e "/var/run/reboot-required" ? 1 : 0; } return 0; } 1;
HasClass0/webmin
package-updates/package-updates-lib.pl
Perl
bsd-3-clause
17,163
# # Author: Makarius # # tools.pl - list Isabelle tools with description # use strict; use warnings; my @tools = (); for my $dir (split(":", $ENV{"ISABELLE_TOOLS"})) { if (-d $dir) { if (opendir DIR, $dir) { for my $name (readdir DIR) { my $file = "$dir/$name"; if (-f $file and -x $file and !($file =~ /~$/ or $file =~ /\.orig$/)) { if (open FILE, $file) { my $description; while (<FILE>) { if (!defined($description) and m/DESCRIPTION: *(.*)$/) { $description = $1; } } close FILE; if (defined($description)) { push(@tools, " $name - $description\n"); } } } } closedir DIR; } } } for (sort @tools) { print };
MerelyAPseudonym/isabelle
lib/scripts/tools.pl
Perl
bsd-3-clause
820
# /=====================================================================\ # # | NNexus Autolinker | # # | Indexing Plug-in, nCatLab.org domain | # # |=====================================================================| # # | Part of the Planetary project: http://trac.mathweb.org/planetary | # # | Research software, produced as part of work done by: | # # | the KWARC group at Jacobs University | # # | Copyright (c) 2012 | # # | Released under the MIT License (MIT) | # # |---------------------------------------------------------------------| # # | Adapted from the original NNexus code by | # # | James Gardner and Aaron Krowne | # # |---------------------------------------------------------------------| # # | Deyan Ginev <d.ginev@jacobs-university.de> #_# | # # | http://kwarc.info/people/dginev (o o) | # # \=========================================================ooo==U==ooo=/ # package NNexus::Index::Nlab; use warnings; use strict; use base qw(NNexus::Index::Template); use List::MoreUtils qw(uniq); use URI::Escape; # nLab has a pretty unfriendly organization of their pages, # so we just ask politely for them to give us all of them at once sub domain_root { "ncatlab.org/nlab/search?query="; } our $nlab_base = 'http://ncatlab.org'; sub candidate_links { my ($self)=@_; my $url = $self->current_url; if ($url =~ /search\?query=$/) { # First page, collect all categories: my $dom = $self->current_dom; my @anchors = $dom->find('ul')->[0]->find('a')->each; my @pages = uniq(map {$nlab_base . uri_unescape($_)} grep {defined} map {$_->{'href'}} @anchors); return \@pages; } else {return [];} # skip leaves } # Index a concept page, ignore category pages sub index_page { my ($self) = @_; my $url = uri_unescape($self->current_url); # Nothing to do in category pages return [] if ((! $self->leaf_test($url)) || ($url =~ /search\?query=$/)); my $dom = $self->current_dom; my $h1 = $dom->find('h1')->[0]; my $concept = $h1 && lc($h1->text); my @categories = map {$_->text} $dom->find('a.category_link')->each; push @categories, 'XX-XX' unless @categories; return [{ url => $url, concept => $concept, scheme => 'nlab', categories => \@categories, }]; } sub candidate_categories {} sub leaf_test { $_[1] =~ /^ncatlab\.org\/nlab\/show\/(?:.+)$/ } 1; __END__ =pod =head1 NAME C<NNexus::Index::Nlab> - Indexing plug-in for the L<nLab|http://ncatlab.org> domain. =head1 DESCRIPTION Indexing plug-in for the nLab domain. See L<NNexus::Index::Template> for detailed indexing documentation. =head1 SEE ALSO L<NNexus::Index::Template> =head1 AUTHOR Deyan Ginev <d.ginev@jacobs-university.de> =head1 COPYRIGHT Research software, produced as part of work done by the KWARC group at Jacobs University Bremen. Released under the MIT License (MIT) =cut
dginev/nnexus
lib/NNexus/Index/Nlab.pm
Perl
mit
3,157
#!/bin/perl use strict; my $score; my @scores = sort { $a <=> $b } map { `cat $_` =~ /^(F_\S+)\s+:\s(\S+)$/m; $score = $1 ; $2 } @ARGV; my $mean = 0; $mean += $_ foreach(@scores); $mean /= @scores; my $var = 0; $var += ($mean - $_)**2 foreach(@scores); $var /= @scores; my $sd = sqrt($var); printf("Mean $score : %.4f [%.4f, %.4f]\n", $mean, $scores[0], $scores[-1]); printf("Std. Dev. : %.4f\n", $sd);
grammatical/baselines-emnlp2016
train/scripts/stats.perl
Perl
mit
409
package Google::Ads::AdWords::v201409::DataService::queryAdGroupBidLandscapeResponse; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409' } __PACKAGE__->__set_name('queryAdGroupBidLandscapeResponse'); __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 %rval_of :ATTR(:get<rval>); __PACKAGE__->_factory( [ qw( rval ) ], { 'rval' => \%rval_of, }, { 'rval' => 'Google::Ads::AdWords::v201409::AdGroupBidLandscapePage', }, { 'rval' => 'rval', } ); } # end BLOCK } # end of BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201409::DataService::queryAdGroupBidLandscapeResponse =head1 DESCRIPTION Perl data type class for the XML Schema defined element queryAdGroupBidLandscapeResponse from the namespace https://adwords.google.com/api/adwords/cm/v201409. =head1 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * rval $element->set_rval($data); $element->get_rval(); =back =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201409::DataService::queryAdGroupBidLandscapeResponse->new($data); Constructor. The following data structure may be passed to new(): { rval => $a_reference_to, # see Google::Ads::AdWords::v201409::AdGroupBidLandscapePage }, =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/DataService/queryAdGroupBidLandscapeResponse.pm
Perl
apache-2.0
1,873
#------------------------------------------------------------------------------ # File: Shortcuts.pm # # Description: ExifTool shortcut tags # # Revisions: 02/07/2004 - PH Moved out of Exif.pm # 09/15/2004 - PH Added D70Boring from Greg Troxel # 01/11/2005 - PH Added Canon20D from Christian Koller # 03/03/2005 - PH Added user defined shortcuts # 03/26/2005 - PH Added Nikon from Tom Christiansen # 02/28/2007 - PH Removed model-dependent shortcuts # --> this is what UserDefined::Shortcuts is for # 02/25/2009 - PH Added Unsafe # 07/03/2010 - PH Added CommonIFD0 #------------------------------------------------------------------------------ package Image::ExifTool::Shortcuts; use strict; use vars qw($VERSION); $VERSION = '1.64'; # this is a special table used to define command-line shortcuts # (documentation Notes may be added for these via %shortcutNotes in BuildTagLookup.pm) %Image::ExifTool::Shortcuts::Main = ( # this shortcut allows the three common date/time tags to be shifted at once AllDates => [ 'DateTimeOriginal', 'CreateDate', 'ModifyDate', ], # This is a shortcut to some common information which is useful in most images Common => [ 'FileName', 'FileSize', 'Model', 'DateTimeOriginal', 'ImageSize', 'Quality', 'FocalLength', 'ShutterSpeed', 'Aperture', 'ISO', 'WhiteBalance', 'Flash', ], # This shortcut provides the same information as the Canon utilities Canon => [ 'FileName', 'Model', 'DateTimeOriginal', 'ShootingMode', 'ShutterSpeed', 'Aperture', 'MeteringMode', 'ExposureCompensation', 'ISO', 'Lens', 'FocalLength', 'ImageSize', 'Quality', 'Flash', 'FlashType', 'ConditionalFEC', 'RedEyeReduction', 'ShutterCurtainHack', 'WhiteBalance', 'FocusMode', 'Contrast', 'Sharpness', 'Saturation', 'ColorTone', 'ColorSpace', 'LongExposureNoiseReduction', 'FileSize', 'FileNumber', 'DriveMode', 'OwnerName', 'SerialNumber', ], Nikon => [ 'Model', 'SubSecDateTimeOriginal', 'ShutterCount', 'LensSpec', 'FocalLength', 'ImageSize', 'ShutterSpeed', 'Aperture', 'ISO', 'NoiseReduction', 'ExposureProgram', 'ExposureCompensation', 'WhiteBalance', 'WhiteBalanceFineTune', 'ShootingMode', 'Quality', 'MeteringMode', 'FocusMode', 'ImageOptimization', 'ToneComp', 'ColorHue', 'ColorSpace', 'HueAdjustment', 'Saturation', 'Sharpness', 'Flash', 'FlashMode', 'FlashExposureComp', ], # This shortcut may be useful when copying tags between files to either # copy the maker notes as a block or prevent it from being copied MakerNotes => [ 'MakerNotes', # (for RIFF MakerNotes) 'MakerNoteApple', 'MakerNoteCanon', 'MakerNoteCasio', 'MakerNoteCasio2', 'MakerNoteDJI', 'MakerNoteFLIR', 'MakerNoteFujiFilm', 'MakerNoteGE', 'MakerNoteGE2', 'MakerNoteHasselblad', 'MakerNoteHP', 'MakerNoteHP2', 'MakerNoteHP4', 'MakerNoteHP6', 'MakerNoteISL', 'MakerNoteJVC', 'MakerNoteJVCText', 'MakerNoteKodak1a', 'MakerNoteKodak1b', 'MakerNoteKodak2', 'MakerNoteKodak3', 'MakerNoteKodak4', 'MakerNoteKodak5', 'MakerNoteKodak6a', 'MakerNoteKodak6b', 'MakerNoteKodak7', 'MakerNoteKodak8a', 'MakerNoteKodak8b', 'MakerNoteKodak8c', 'MakerNoteKodak9', 'MakerNoteKodak10', 'MakerNoteKodak11', 'MakerNoteKodak12', 'MakerNoteKodakUnknown', 'MakerNoteKyocera', 'MakerNoteMinolta', 'MakerNoteMinolta2', 'MakerNoteMinolta3', 'MakerNoteMotorola', 'MakerNoteNikon', 'MakerNoteNikon2', 'MakerNoteNikon3', 'MakerNoteNintendo', 'MakerNoteOlympus', 'MakerNoteOlympus2', 'MakerNoteLeica', 'MakerNoteLeica2', 'MakerNoteLeica3', 'MakerNoteLeica4', 'MakerNoteLeica5', 'MakerNoteLeica6', 'MakerNoteLeica7', 'MakerNoteLeica8', 'MakerNoteLeica9', 'MakerNoteLeica10', 'MakerNotePanasonic', 'MakerNotePanasonic2', 'MakerNotePanasonic3', 'MakerNotePentax', 'MakerNotePentax2', 'MakerNotePentax3', 'MakerNotePentax4', 'MakerNotePentax5', 'MakerNotePentax6', 'MakerNotePhaseOne', 'MakerNoteReconyx', 'MakerNoteReconyx2', 'MakerNoteReconyx3', 'MakerNoteRicoh', 'MakerNoteRicoh2', 'MakerNoteRicohPentax', 'MakerNoteRicohText', 'MakerNoteSamsung1a', 'MakerNoteSamsung1b', 'MakerNoteSamsung2', 'MakerNoteSanyo', 'MakerNoteSanyoC4', 'MakerNoteSanyoPatch', 'MakerNoteSigma', 'MakerNoteSigma3', 'MakerNoteSony', 'MakerNoteSony2', 'MakerNoteSony3', 'MakerNoteSony4', 'MakerNoteSony5', 'MakerNoteSonyEricsson', 'MakerNoteSonySRF', 'MakerNoteUnknownText', 'MakerNoteUnknownBinary', 'MakerNoteUnknown', ], # "unsafe" tags we normally don't copy in JPEG images, defined # as a shortcut to use when rebuilding JPEG EXIF from scratch Unsafe => [ 'IFD0:YCbCrPositioning', 'IFD0:YCbCrCoefficients', 'IFD0:TransferFunction', 'ExifIFD:ComponentsConfiguration', 'ExifIFD:CompressedBitsPerPixel', 'InteropIFD:InteropIndex', 'InteropIFD:InteropVersion', 'InteropIFD:RelatedImageWidth', 'InteropIFD:RelatedImageHeight', ], # standard tags used to define the color space of an image # (useful to preserve color space when deleting all meta information) ColorSpaceTags => [ 'ExifIFD:ColorSpace', 'ExifIFD:Gamma', 'InteropIFD:InteropIndex', 'ICC_Profile', ], # common metadata tags found in IFD0 of TIFF images CommonIFD0 => [ # standard EXIF 'IFD0:ImageDescription', 'IFD0:Make', 'IFD0:Model', 'IFD0:Software', 'IFD0:ModifyDate', 'IFD0:Artist', 'IFD0:Copyright', # other TIFF tags 'IFD0:Rating', 'IFD0:RatingPercent', 'IFD0:DNGLensInfo', 'IFD0:PanasonicTitle', 'IFD0:PanasonicTitle2', 'IFD0:XPTitle', 'IFD0:XPComment', 'IFD0:XPAuthor', 'IFD0:XPKeywords', 'IFD0:XPSubject', ], # large binary data tags which won't be loaded if excluded when extracting LargeTags => [ 'CanonVRD', 'DLOData', 'EXIF', 'ICC_Profile', 'IDCPreviewImage', 'ImageData', 'IPTC', 'JpgFromRaw', 'OriginalRawImage', 'OtherImage', 'PreviewImage', 'ThumbnailImage', 'TIFFPreview', 'XML', 'XMP', 'ZoomedPreviewImage', ], ); #------------------------------------------------------------------------------ # load user-defined shortcuts if available # Inputs: reference to user-defined shortcut hash sub LoadShortcuts($) { my $shortcuts = shift; my $shortcut; foreach $shortcut (keys %$shortcuts) { my $val = $$shortcuts{$shortcut}; # also allow simple aliases $val = [ $val ] unless ref $val eq 'ARRAY'; # save the user-defined shortcut or alias $Image::ExifTool::Shortcuts::Main{$shortcut} = $val; } } # (for backward compatibility, renamed in ExifTool 7.75) if (%Image::ExifTool::Shortcuts::UserDefined) { LoadShortcuts(\%Image::ExifTool::Shortcuts::UserDefined); } if (%Image::ExifTool::UserDefined::Shortcuts) { LoadShortcuts(\%Image::ExifTool::UserDefined::Shortcuts); } 1; # end __END__ =head1 NAME Image::ExifTool::Shortcuts - ExifTool shortcut tags =head1 SYNOPSIS This module is required by Image::ExifTool. =head1 DESCRIPTION This module contains definitions for tag name shortcuts used by Image::ExifTool. You can customize this file to add your own shortcuts. Individual users may also add their own shortcuts to the .ExifTool_config file in their home directory (or the directory specified by the EXIFTOOL_HOME environment variable). The shortcuts are defined in a hash called %Image::ExifTool::UserDefined::Shortcuts. The keys of the hash are the shortcut names, and the elements are either tag names or references to lists of tag names. An example shortcut definition in .ExifTool_config: %Image::ExifTool::UserDefined::Shortcuts = ( MyShortcut => ['createdate','exif:exposuretime','aperture'], MyAlias => 'FocalLengthIn35mmFormat', ); In this example, MyShortcut is a shortcut for the CreateDate, EXIF:ExposureTime and Aperture tags, and MyAlias is a shortcut for FocalLengthIn35mmFormat. The target tag names may contain an optional group name prefix. A group name applied to the shortcut will be ignored for any target tag with a group name prefix. =head1 AUTHOR Copyright 2003-2019, 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
philmoz/Focus-Points
focuspoints.lrdevplugin/bin/exiftool/lib/Image/ExifTool/Shortcuts.pm
Perl
apache-2.0
9,887
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This file is part of VivoMind Prolog Unicode Resources % SPDX-License-Identifier: CC0-1.0 % % VivoMind Prolog Unicode Resources is free software distributed using the % Creative Commons CC0 1.0 Universal (CC0 1.0) - Public Domain Dedication % license % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Last modified: March 13, 2012 % EMPTY
LogtalkDotOrg/logtalk3
library/unicode_data/unicode_names/unicode_name_lc_letter_cased.pl
Perl
apache-2.0
462
package Paws::CodeCommit::BatchGetRepositoriesOutput; use Moose; has Repositories => (is => 'ro', isa => 'ArrayRef[Paws::CodeCommit::RepositoryMetadata]', traits => ['NameInRequest'], request_name => 'repositories' ); has RepositoriesNotFound => (is => 'ro', isa => 'ArrayRef[Str|Undef]', traits => ['NameInRequest'], request_name => 'repositoriesNotFound' ); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::CodeCommit::BatchGetRepositoriesOutput =head1 ATTRIBUTES =head2 Repositories => ArrayRef[L<Paws::CodeCommit::RepositoryMetadata>] A list of repositories returned by the batch get repositories operation. =head2 RepositoriesNotFound => ArrayRef[Str|Undef] Returns a list of repository names for which information could not be found. =head2 _request_id => Str =cut 1;
ioanrogers/aws-sdk-perl
auto-lib/Paws/CodeCommit/BatchGetRepositoriesOutput.pm
Perl
apache-2.0
851
package Paws::ELBv2::CreateTargetGroupOutput; use Moose; has TargetGroups => (is => 'ro', isa => 'ArrayRef[Paws::ELBv2::TargetGroup]'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::ELBv2::CreateTargetGroupOutput =head1 ATTRIBUTES =head2 TargetGroups => ArrayRef[L<Paws::ELBv2::TargetGroup>] Information about the target group. =head2 _request_id => Str =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/ELBv2/CreateTargetGroupOutput.pm
Perl
apache-2.0
438
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::External::ExternalFeatureAdaptor =head 1 SUMMARY Allows features created externally from Ensembl in a single coordinate system to be retrieved in several other (Ensembl-style) coordinate systems. This is intended to be a replacement for the old Bio::EnsEMBL::DB::ExternalFeatureFactoryI interface. =head1 SYNOPSIS $database_adaptor = new Bio::EnsEMBL::DBSQL::DBAdaptor( -host => 'kaka.sanger.ac.uk', -dbname => 'homo_sapiens_core_9_30', -pass => 'anonymous' ); $xf_adaptor = new ExternalFeatureAdaptorSubClass; # Connect the Ensembl core database: $xf_adaptor->db($database_adaptor); # get some features in vontig coords @feats = @{ $xf_adaptor->fetch_all_by_contig_name('AC000087.2.1.42071') }; # get some features in assembly coords @feats = @{ $xf_adaptor->fetch_all_by_chr_start_end( 'X', 100000, 200000 ) }; # get some features in clone coords @feats = @{ $xf_adaptor->fetch_all_by_clone_accession('AC000087') }; # Add the adaptor to the ensembl core dbadaptor (implicitly sets db # attribute) $database_adaptor->add_ExternalFeatureAdaptor($xf_adaptor); # get some features in Slice coords $slice_adaptor = $database_adaptor->get_SliceAdaptor; $slice = $slice_adaptor->fetch_all_by_chr_start_end( 1, 100000, 200000 ); @feats = @{ $xf_adaptor->fetch_all_by_Slice($slice) }; # now features can be retrieved directly from Slice @feats = @{ $slice->get_all_ExternalFeatures }; =head1 DESCRIPTION This class is intended to be used as a method of getting external features into EnsEMBL. To work, this class must be extended and must implement the the coordinate_systems method. As well, the subclass is required to implement a single fetch method so that the external features may be retrieved. By implementing a single fetch_method in a single coordinate system all of the other ExternalFeatureAdaptor fetch methods become available for retrieving the data in several different coordinate systems. The coordinate_systems method should return a list of strings indicating which coordinate system(s) have been implemented. If a given string is returned from the coordinate_systems method then the corresponding fetch method must be implemented. The reverse is also true: if a fetch method is implemented then coordinate_systems must return the appropriate string in its list of return values. The following are the valid coordinate system values and the corresponding fetch methods that must be implemented: COORD SYSTEM STRING FETCH_METHOD ------------------- ------------ 'ASSEMBLY' fetch_all_by_chr_start_end 'CLONE' fetch_all_by_clone_accession 'CONTIG' fetch_all_by_contig_name 'SUPERCONTIG' fetch_all_by_supercontig_name 'SLICE' fetch_all_by_Slice The objects returned by the fetch methods should be EnsEMBL or BioPerl style Feature objects. These objects MUST have start, end and strand methods. Before the non-overridden ExternalFeatureAdaptor fetch methods may be called an EnsEMBL core database adaptor must be attached to the ExternalFeatureAdaptor . This database adaptor is required to perform the remappings between various coordinate system. This may be done implicitly by adding the ExternalFeatureAdaptor to the database adaptor through a call to the DBAdaptor add_ExternalFeatureAdaptor method or explicitly by calling the ExternalFeatureAdaptor ensembl_db method. =head1 METHODS =cut package Bio::EnsEMBL::External::ExternalFeatureAdaptor; use strict; use Bio::EnsEMBL::Utils::Exception qw(warning throw); =head2 new Arg [1] : none Example : $xfa = new Bio::EnsEMBL::External::ExternalFeatureAdaptor; Description: Creates a new ExternalFeatureAdaptor object. You may wish to extend this constructor and provide your own set of paremeters. Returntype : Bio::EnsEMBL::External::ExternalFeatureAdaptor Exceptions : none Caller : general =cut sub new { my $class = shift; if(ref $class) { return bless {}, ref $class; } return bless {}, $class; } =head2 ensembl_db Arg [1] : (optional) Bio::EnsEMBL::DBSQL::DBAdaptor Example : $external_feature_adaptor->ensembl_db($new_val); Description: none Returntype : Bio::EnsEMBL::DBSQL::DBAdaptor Exceptions : none Caller : internal =cut sub ensembl_db { my ($self, $value) = @_; if($value) { $self->{'ensembl_db'} = $value; } return $self->{'ensembl_db'}; } =head2 coordinate_systems Arg [1] : none Example : @implemented_coord_systems = $ext_adaptor->coordinate_systems; Description: ABSTRACT method. Must be implemented by all ExternalFeatureAdaptor subclasses. This method returns a list of coordinate systems which are implemented by the subclass. A minimum of on valid coordinate system must be implemented. Valid coordinate systems are: 'SLICE', 'ASSEMBLY', 'CONTIG', and 'CLONE'. Returntype : list of strings Exceptions : none Caller : internal =cut sub coordinate_systems { my $self = shift; throw("abstract method coordinate_systems not implemented\n"); return ''; } =head2 track_name Arg [1] : none Example : $track_name = $xf_adaptor->track_name; Description: Currently this is not really used. In the future it may be possible to have ExternalFeatures automatically displayed by the EnsEMBL web code. By default this method returns 'External features' but you are encouraged to override this method and provide your own meaningful name for the features your adaptor provides. This also allows you to distinguish the type of features retrieved from Slices. See the PODs for Bio::EnsEMBL::Slice::get_all_ExternalFeatures and Bio::EnsEMBL::DBSQL::DBAdaptor::add_ExternalFeatureAdaptor methods. Returntype : string Exceptions : none Caller : Bio::EnsEMBL::DBSQL::DBAdaptor::add_ExternalFeatureAdaptor =cut sub track_name { my $self = shift; return 'External features'; } =head2 feature_type Arg [1] : none Example : $feature_type = $xf_adaptor->track_name Description: Currently this is not used. In the future it may be possible to have ExternalFeatures automatically displayed by the EnsEMBL web code. This method would then be used do determine the type of glyphs used to draw the features which are returned from this external adaptor. Returntype : string Exceptions : none Caller : none =cut sub feature_type { my $self = shift; return qw(SIMPLE); } =head2 fetch_all_by_Slice Arg [1] : Bio::EnsEMBL::Slice $slice Example : @features = @{$ext_adaptor->fetch_all_by_Slice($slice)}; Description: Retrieves all features which lie in the region defined by $slice in slice coordinates. If this method is overridden then the coordinate_systems method must return 'SLICE' as one of its values. This method will work as is (i.e. without overriding it) providing at least one of the other fetch methods is overridden. Returntype : reference to a list of Bio::SeqFeature objects in the Slice coordinate system Exceptions : Thrown on incorrect input arguments Caller : general, fetch_all_by_chr_start_end =cut sub fetch_all_by_Slice { my ($self, $slice) = @_; unless($slice && ref $slice && $slice->isa('Bio::EnsEMBL::Slice')) { throw("[$slice] is not a Bio::EnsEMBL::Slice"); } my $out = []; my $csa = $self->ensembl_db->get_CoordSystemAdaptor(); my $slice_start = $slice->start; my $slice_end = $slice->end; my $slice_strand = $slice->strand; my $slice_seq_region = $slice->seq_region_name; my $slice_seq_region_id = $slice->get_seq_region_id; my $coord_system = $slice->coord_system; if($self->_supported('SLICE')) { throw("ExternalFeatureAdaptor supports SLICE coordinate system" . " but fetch_all_by_Slice not implemented"); } my %features; my $from_coord_system; my $fetch_method; # # Get all of the features from whatever coord system they are computed in # if($self->_supported('CLONE')) { $fetch_method = sub { my $self = shift; my $name = shift; my ($acc, $ver) = split(/\./, $name); $self->fetch_all_by_clone_accession($acc,$ver,@_); }; $from_coord_system = $csa->fetch_by_name('clone'); } elsif($self->_supported('ASSEMBLY')) { $from_coord_system = $csa->fetch_by_name('chromosome'); $fetch_method = $self->can('fetch_all_by_chr_start_end'); } elsif($self->_supported('CONTIG')) { $from_coord_system = $csa->fetch_by_name('contig'); $fetch_method = $self->can('fetch_all_by_contig_name'); } elsif($self->_supported('SUPERCONTIG')) { $from_coord_system = $csa->fetch_by_name('supercontig'); $fetch_method = $self->can('fetch_all_by_supercontig_name'); } else { $self->_no_valid_coord_systems(); } if($from_coord_system->equals($coord_system)) { $features{$slice_seq_region} = &$fetch_method($self, $slice_seq_region, $slice_start,$slice_end); } else { foreach my $segment (@{$slice->project($from_coord_system->name, $from_coord_system->version)}) { my ($start,$end,$pslice) = @$segment; $features{$pslice->seq_region_name } ||= []; push @{$features{$pslice->seq_region_name }}, @{&$fetch_method($self, $pslice->seq_region_name, $pslice->start(), $pslice->end())}; } } my @out; if(!$coord_system->equals($from_coord_system)) { my $asma = $self->ensembl_db->get_AssemblyMapperAdaptor(); my $mapper = $asma->fetch_by_CoordSystems($from_coord_system, $coord_system); my %slice_cache; my $slice_adaptor = $self->ensembl_db->get_SliceAdaptor(); my $slice_setter; #convert the coordinates of each of the features retrieved foreach my $fseq_region (keys %features) { my $feats = $features{$fseq_region}; next if(!$feats); $slice_setter = _guess_slice_setter($feats) if(!$slice_setter); foreach my $f (@$feats) { my($sr_id, $start, $end, $strand) = $mapper->fastmap($fseq_region,$f->start,$f->end,$f->strand, $from_coord_system); #maps to gap next if(!defined($sr_id)); #maps to unexpected seq region, probably error in the externally if($sr_id ne $slice_seq_region_id) { warning("Externally created Feature mapped to [$sr_id] " . "which is not on requested seq_region_id [$slice_seq_region_id]"); next; } #update the coordinates of the feature &$slice_setter($f,$slice); $f->start($start); $f->end($end); $f->strand($strand); push @out, $f; } } } else { #we already know the seqregion the featues are on, we just have #to put them on the slice @out = @{$features{$slice_seq_region}}; my $slice_setter = _guess_slice_setter(\@out); foreach my $f (@out) { &$slice_setter($f,$slice); } } # convert from assembly coords to slice coords # handle the circular slice case my $seq_region_len = $slice->seq_region_length(); foreach my $f (@out) { my($f_start, $f_end, $f_strand); if ($slice->strand == 1) { # Positive strand $f_start = $f->start - $slice_start + 1; $f_end = $f->end - $slice_start + 1; $f_strand = $f->strand; if ($slice->is_circular()) { # Handle cicular chromosomes if ($f_start > $f_end) { # Looking at a feature overlapping the chromsome origin. if ($f_end > $slice_start) { # Looking at the region in the beginning of the chromosome. $f_start -= $seq_region_len; } if ($f_end < 0) { $f_end += $seq_region_len; } } else { if ($slice_start > $slice_end && $f_end < 0) { # Looking at the region overlapping the chromosome origin and # a feature which is at the beginning of the chromosome. $f_start += $seq_region_len; $f_end += $seq_region_len; } } } } else { # Negative strand my ($seq_region_start, $seq_region_end) = ($f->start, $f->end); $f_start = $slice_end - $seq_region_end + 1; $f_end = $slice_end - $seq_region_start + 1; $f_strand = $f->strand * -1; if ($slice->is_circular()) { if ($slice_start > $slice_end) { # slice spans origin or replication if ($seq_region_start >= $slice_start) { $f_end += $seq_region_len; $f_start += $seq_region_len if $seq_region_end > $slice_start; } elsif ($seq_region_start <= $slice_end) { # do nothing } elsif ($seq_region_end >= $slice_start) { $f_start += $seq_region_len; $f_end += $seq_region_len; } elsif ($seq_region_end <= $slice_end) { $f_end += $seq_region_len if $f_end < 0; } elsif ($seq_region_start > $seq_region_end) { $f_end += $seq_region_len; } else { } } else { if ($seq_region_start <= $slice_end and $seq_region_end >= $slice_start) { # do nothing } elsif ($seq_region_start > $seq_region_end) { if ($seq_region_start <= $slice_end) { $f_start -= $seq_region_len; } elsif ($seq_region_end >= $slice_start) { $f_end += $seq_region_len; } else { } } } } } $f->start($f_start); $f->end($f_end); $f->strand($f_strand); } return \@out; } sub _guess_slice_setter { my $features = shift; #we do not know what type of features these are. They might #be bioperl features or old ensembl features, hopefully they are new #style features. Try to come up with a setter method for the #slice. return undef if(!@$features); my ($f) = @$features; my $slice_setter; foreach my $method (qw(slice contig attach_seq)) { last if($slice_setter = $f->can($method)); } if(!$slice_setter) { if($f->can('seqname')) { $slice_setter = sub { $_[0]->seqname($_[1]->seq_region_name()); }; } else { $slice_setter = sub{} if(!$slice_setter); } } return $slice_setter; } =head2 fetch_all_by_contig_name Arg [1] : string $contig_name Arg [2] : int $start (optional) The start of the region on the contig to retrieve features on if not specified the whole of the contig is used. Arg [3] : int $end (optional) The end of the region on the contig to retrieve features on if not specified the whole of the contig is used. Example : @fs = @{$self->fetch_all_by_contig_name('AB00879.1.1.39436')}; Description: Retrieves features on the contig defined by the name $contig_name in contig coordinates. If this method is overridden then the coordinate_systems method must return 'CONTIG' as one of its values. This method will work as is (i.e. without being overridden) providing at least one other fetch method has been overridden. Returntype : reference to a list of Bio::SeqFeature objects in the contig coordinate system. Exceptions : thrown if the input argument is incorrect thrown if the coordinate_systems method returns the value 'CONTIG' and this method has not been overridden. Caller : general, fetch_all_by_Slice =cut sub fetch_all_by_contig_name { my ($self, $contig_name, $start, $end) = @_; unless($contig_name) { throw("contig_name argument not defined"); } if($self->_supported('CONTIG')) { throw("ExternalFeatureAdaptor supports CONTIG coordinate system" . " but fetch_all_by_contig_name is not implemented"); } unless($self->ensembl_db) { throw('DB attribute not set. This value must be set for the ' . 'ExternalFeatureAdaptor to function correctly'); } my $slice_adaptor = $self->ensembl_db->get_SliceAdaptor(); my $slice = $slice_adaptor->fetch_by_region('contig', $contig_name, $start, $end); return $self->fetch_all_by_Slice($slice); } =head2 fetch_all_by_supercontig_name Arg [1] : string $supercontig_name Arg [2] : int $start (optional) The start of the region on the contig to retrieve features on if not specified the whole of the contig is used. Arg [3] : int $end (optional) The end of the region on the contig to retrieve features on if not specified the whole of the contig is used. Example : @fs = @{$self->fetch_all_by_contig_name('NT_004321')}; Description: Retrieves features on the contig defined by the name $supercontigname in supercontig coordinates. If this method is overridden then the coordinate_systems method must return 'SUPERCONTIG' as one of its values. This method will work as is (i.e. without being overridden) providing at least one other fetch method has been overridden. Returntype : reference to a list of Bio::SeqFeature objects in the contig coordinate system. Exceptions : thrown if the input argument is incorrect thrown if the coordinate_systems method returns the value 'SUPERCONTIG' and this method has not been overridden. Caller : general, fetch_all_by_Slice =cut sub fetch_all_by_supercontig_name { my ($self, $supercontig_name, $start, $end) = @_; unless($supercontig_name) { throw("supercontig_name argument not defined"); } if($self->_supported('SUPERCONTIG')) { throw("ExternalFeatureAdaptor supports SUPERCONTIG coordinate system" . " but fetch_all_by_supercontig_name is not implemented"); } unless($self->ensembl_db) { throw('DB attribute not set. This value must be set for the ' . 'ExternalFeatureAdaptor to function correctly'); } my $slice_adaptor = $self->ensembl_db->get_SliceAdaptor(); my $slice = $slice_adaptor->fetch_by_region('supercontig', $supercontig_name, $start, $end); return $self->fetch_all_by_Slice($slice); } =head2 fetch_all_by_clone_accession Arg [1] : string $acc The EMBL accession number of the clone to fetch features from. Arg [2] : (optional) string $ver Arg [3] : (optional) int $start Arg [4] : (optional) int $end Example : @fs = @{$self->fetch_all_by_clone_accession('AC000093')}; Description: Retrieves features on the clone defined by the $acc arg in Clone coordinates. If this method is overridden then the coordinate_systems method must return 'CLONE' as one of its values. The arguments start, end, version are passed if this method is overridden and can optionally be used to reduce the scope of the query and improve performance. This method will work as is - providing at least one other fetch method has been overridden. Returntype : reference to a list of Bio::SeqFeature objects in the Clone coordinate system Exceptions : thrown if the input argument is incorrect thrown if the coordinate system method returns the value 'CLONE' and this method is not overridden. thrown if the coordinate systems method does not return any valid values. Caller : general, fetch_all_by_clone_accession =cut sub fetch_all_by_clone_accession { my ($self, $acc, $version, $start, $end) = @_; unless($acc) { throw("clone accession argument not defined"); } if($self->_supported('CLONE')) { throw('ExternalFeatureAdaptor supports CLONE coordinate system ' . 'but does not implement fetch_all_by_clone_accession'); } unless($self->ensembl_db) { throw('DB attribute not set. This value must be set for the ' . 'ExternalFeatureAdaptor to function correctly'); } if(defined($version)) { $acc = "$acc.$version"; } elsif(!$acc =~ /\./) { $acc = "$acc.1"; } my $slice_adaptor = $self->ensembl_db->get_SliceAdaptor; my $slice = $slice_adaptor->fetch_by_region('clone', $acc, $start, $end); return $self->fetch_all_by_Slice($slice); } =head2 fetch_all_by_chr_start_end Arg [1] : string $chr_name The name of the chromosome to retrieve features from Arg [2] : int $start The start coordinate of the chromosomal region to retrieve features from. Arg [3] : int $end The end coordinate of the chromosomal region to retrieve features from. Example : @features Description: Retrieves features on the region defined by the $chr_name, $start, and $end args in assembly (chromosomal) coordinates. If this method is overridden then the coordinate_systems method must return 'ASSEMBLY' as one of its values. This method will work as is (i.e. without overriding it) providing at least one of the other fetch methods is overridden. Returntype : reference to a list of Bio::SeqFeatures Exceptions : Thrown if the coordinate_systems method returns ASSEMBLY as a value and this method is not overridden. Thrown if any of the input arguments are incorrect Caller : general, fetch_all_by_Slice =cut sub fetch_all_by_chr_start_end { my ($self, $chr_name, $start, $end) = @_; unless($chr_name && defined $start && defined $end && $start < $end) { throw("Incorrect start [$start] end [$end] or chr [$chr_name] arg"); } unless($self->ensembl_db) { throw('DB attribute not set. This value must be set for the ' . 'ExternalFeatureAdaptor to function correctly'); } my $slice_adaptor = $self->ensembl_db->get_SliceAdaptor(); my $slice = $slice_adaptor->fetch_by_region('toplevel', $chr_name, $start, $end); return $self->fetch_all_by_Slice($slice); } =head2 _no_valid_coord_system Arg [1] : none Example : none Description: PRIVATE method - throws an error with a descriptive message Returntype : none Exceptions : always thrown Caller : internal =cut sub _no_valid_coord_system { my $self = shift; throw("This ExternalFeatureAdaptor does not support a known " . "coordinate system.\n Valid coordinate systems are: " . "[SLICE,ASSEMBLY,SUPERCONTIG,CONTIG,CLONE].\n This External Adaptor " . "supports: [" . join(', ', $self->coordinate_systems) . "]"); } =head2 _supported Arg [1] : string $system Example : print "CONTIG system supported" if($self->_supported('CONTIG')); Description: PRIVATE method. Tests if the coordinate system defined by the $system argument is implemented. Returntype : boolean Exceptions : none Caller : internal =cut sub _supported { my ($self, $system) = @_; #construct the hash of supported features if it has not been already unless(exists $self->{_supported}) { $self->{_supported} = {}; foreach my $coord_system ($self->coordinate_systems) { $self->{_supported}->{$coord_system} = 1; } } return $self->{_supported}->{$system}; } 1;
mjg17/ensembl
modules/Bio/EnsEMBL/External/ExternalFeatureAdaptor.pm
Perl
apache-2.0
24,722
#!/usr/bin/env perl use Sys::Hostname; use strict; use File::Path; use IO::Handle; # # Set Path for perl Libraries # unshift( @INC, "."); ######################################################################## # Sub: testcase # Prints the result for a test case. # # Parameters: # $class - the test file # $test - the test name # $time - the the total amount of time it took to run a test # # Returns: # None # sub getTestcase($$$$$$){ my ( $class_name, $group_name, $test_name, $time, $status, $msg )=@_; my $result = ""; if ( $status =~ "passed" ){ $result = "\n<testcase classname=\"$class_name\" name=\"$test_name\" time=\"$time\"/>"; } elsif ( $status =~ "skipped" ){ $result = "\n<testcase classname=\"$class_name\" name=\"$test_name\" time=\"0\">" . "\n<skipped type=\"$status\">$msg</skipped>" . "\n</testcase>" ; } else { $result = "\n<testcase classname=\"$class_name\" name=\"$test_name\" time=\"$time\">" . "\n<error type=\"$status\">$msg</error>" . "\n</testcase>" ; } return $result; } sub printXmlReport($) { my $host = Sys::Hostname::hostname(); my $tmpFileName = shift; my $reportFileName = shift; my $testcases = ""; my $total_time= 0; my $testnameSuffix = ""; if ($tmpFileName =~ m/-local/) { $testnameSuffix = "_local"; } my $passedCount = 0; my $failureCount = 0; my $errorCount = 0; my $skippedCount = 0; my $totalCount = 0; my %test2starttime = { '', 0 }; open( IN, "$tmpFileName") || die "Could not open $tmpFileName\n"; while(<IN>){ my $line = $_; # e.g.: "Beginning test Checkin_1 at 1346855793" if ( $line =~ m/Beginning test (.*) at (.*)/ ) { # put "test - start time" pair to the hash: $test2starttime{ $1 } = $2; } else { if ( $line =~ "TestDriver::run" ) { my $duration = 0; if ( $line =~ m/TestDriver::run.*Failed to run test (.*) <(.*)/ ) { # ERROR TestDriver::run at : 470 Failed to run test ClassResolution_1 <Failed running ./out/pigtest/hadoopqa/hadoopqa.1327755958/ClassResolution_1_benchmark.pig #print "test aborted: $line"; $testcases .= getTestcase ( $1, "group", $1 . $testnameSuffix, 0, "aborted", $2 ); $errorCount++; } elsif ( $line =~ m/TestDriver::run.*Test (.*) SUCCEEDED at (.*)/ ) { # INFO: TestDriver::run() at 444:Test Unicode_cmdline_1 SUCCEEDED at 1327751873 #print "test passed: $1 $2 line: $line"; $passedCount++; $duration = $2 - $test2starttime{ $1 }; $testcases .= getTestcase ( $1, "group", $1 . $testnameSuffix, $duration, "passed", "" ); } elsif ( $line =~ m/TestDriver::run.*Test (.*) FAILED at (.*)/ ) { $failureCount++; $duration = $2 - $test2starttime{ $1 }; $testcases .= getTestcase ( $1, "group", $1 . $testnameSuffix, $duration, "failed", "" ); #print "test failed: $1 $2 line: $line"; } elsif ($line =~ "Running TEST GROUP") { next; } elsif ($line =~ m/TestDriver::run.*Test (.*) SKIPPED at (.*)/) { # INFO: TestDriver::run() at 444:Test StreamingLocalErrors_1 SKIPPED at 1327923441 $skippedCount++; $duration = $2 - $test2starttime{ $1 }; $testcases .= getTestcase ( $1, "group", $1 . $testnameSuffix, $duration, "skipped", "" ); } else { print STDERR "Ignored line: $line"; next; } #$total_time= $total_time + $time; $totalCount++; } } } close(IN); #Report my $host = Sys::Hostname::hostname(); my $run_name = "e2e tests"; my $report= '<?xml version="1.0" encoding="UTF-8" ?>' . "\n<testsuite errors=\"$errorCount\" failures=\"$failureCount\" skips=\"$skippedCount\" hostname=\"$host\" name=\"$run_name\" tests=\"$totalCount\" time=\"$total_time\">" . "\n$testcases" . "\n</testsuite>" . "\n"; print $report; } if (!defined( $ARGV[0] )) { die "No input log file specified\n"; } printXmlReport($ARGV[0]);
Altiscale/pig
test/e2e/harness/xmlReport.pl
Perl
apache-2.0
4,240
#!/usr/bin/perl -w use strict; use CoGeX; use Getopt::Long; use vars qw($coge $name $desc $help); $coge = CoGeX->dbconnect(); GetOptions ("name|n=s"=>\$name, "desc|d=s"=>\$desc, "help|h"=>\$help, ); if ($help) { help(); } my $search = {}; $search->{description}={like=>"%".$desc."%"} if $desc; $search->{name}={like=>"%".$name."%"} if $name; foreach my $org ($coge->resultset("Organism")->search($search)) { print join ("\t", $org->name, $org->description),"\n"; } sub help { print qq{ Welcome to $0. This program searches for organisms in CoGe matching a name and/or description and generates a text list of the organism names and descriptions which match. If nothing is specified, all organisms are listed. Usage $0 -name <org_name> -desc <org_description> Options: -name | -n name of organisms to search (wildcards pre and post pended) -desc | -d description of organisms to search (wildcards pre and post pended) -hehlp | -h print this message }; exit; }
asherkhb/coge
scripts/old/get_org_list.pl
Perl
bsd-2-clause
1,025
package Action::workgroupManage; use ItemConstants; use File::Copy; use Session; sub run { our $q = shift; our $dbh = shift; our %in = map { $_ => $q->param($_) } $q->param; our $user = Session::getUser($q->env, $dbh); our $debug = 1; our $thisUrl = "${orcaUrl}cgi-bin/workgroupManage.pl"; our @workGroupFields = ($OC_CONTENT_AREA, $OC_GRADE_LEVEL); # Authorize user (must be user type UT_ITEM_EDITOR and be an admin) unless (exists( $user->{type} ) and int( $user->{type} ) == $UT_ITEM_EDITOR and $user->{adminType} ) { return [ $q->psgi_header('text/html'), [ &print_no_auth() ] ]; } our $banks = defined($user->{banks}) ? $user->{banks} : &getItemBanks( $dbh, $user->{id} ); $in{itemBankId} = (keys %$banks)[0] unless exists $in{itemBankId}; $in{myAction} = '' unless exists $in{myAction}; our $workGroups = &getWorkgroups($dbh, $in{itemBankId}); $in{workGroupId} = (keys %$banks)[0] unless exists($in{workGroupId}) || scalar(keys %$workGroups) == 0; if ( $in{myAction} eq '' ) { return [ $q->psgi_header('text/html'), [ &print_welcome() ] ]; } if ( $in{myAction} eq 'addWorkGroup' ) { my $sql = "SELECT * FROM workgroup WHERE w_name=" . $dbh->quote( $in{workGroupName} ); my $sth = $dbh->prepare($sql); $sth->execute(); if ( $sth->fetchrow_hashref ) { $in{errorMsg} = "Program '$in{workGroupName}' already exists."; return [ $q->psgi_header('text/html'), [ &print_welcome() ] ]; } # Create the 'workgroup' record $sql = sprintf('INSERT INTO workgroup SET w_name=%s, ib_id=%d, w_description=\'\'', $dbh->quote( $in{workGroupName} ), $in{itemBankId}); $sth = $dbh->prepare($sql); $sth->execute(); $in{workGroupId} = $dbh->{mysql_insertid}; # refresh the workgroup list $workGroups = &getWorkgroups($dbh, $in{itemBankId}); return [ $q->psgi_header('text/html'), [ &print_edit_workgroup() ] ]; } elsif ( $in{myAction} eq 'editWorkGroup' ) { return [ $q->psgi_header('text/html'), [ &print_edit_workgroup() ] ]; } elsif ( $in{myAction} eq 'addFilter' ) { my $sql = sprintf('INSERT INTO workgroup_filter SET w_id=%d', $in{workGroupId}); my $sth = $dbh->prepare($sql); $sth->execute(); my $wf_id = $dbh->{mysql_insertid}; foreach my $field (@workGroupFields) { $sql = sprintf('INSERT INTO workgroup_filter_part SET wf_id=%d, wf_type=%d, wf_value=%d', $wf_id, $field, $in{"filterField${field}"}); $sth = $dbh->prepare($sql); $sth->execute(); } return [ $q->psgi_header('text/html'), [ &print_edit_workgroup() ] ]; } elsif ( $in{myAction} eq 'deleteFilter' ) { my $sql = sprintf('DELETE FROM workgroup_filter_part WHERE wf_id=%d', $in{filterId}); my $sth = $dbh->prepare($sql); $sth->execute(); $sql = sprintf('DELETE FROM workgroup_filter WHERE wf_id=%d', $in{filterId}); $sth = $dbh->prepare($sql); $sth->execute(); $in{errorMsg} = 'Filter Deleted'; return [ $q->psgi_header('text/html'), [ &print_edit_workgroup() ] ]; } elsif ( $in{myAction} eq 'save' ) { my $sql = sprintf('UPDATE workgroup SET w_description=%s WHERE w_id=%d', $dbh->quote($in{description}), $in{workGroupId}); my $sth = $dbh->prepare($sql); $sth->execute(); # refresh the workgroup list $workGroups = &getWorkgroups($dbh, $in{itemBankId}); $in{errorMsg} = 'Updated Workgroup'; return [ $q->psgi_header('text/html'), [ &print_edit_workgroup() ] ]; } # rest of actions are related to user assignment our $usersInItemBank = &getUsersByItemBank($dbh, $in{itemBankId}); if ( $in{myAction} eq 'editUsers' ) { return [ $q->psgi_header('text/html'), [ &print_assign_users_to_workgroup() ] ]; } elsif ( $in{myAction} eq 'saveUsers' ) { # Put all of these statements in a transaction $dbh->{RaiseError} = 1; $dbh->{AutoCommit} = 0; { $sql = "DELETE FROM user_permission WHERE up_type=${UP_VIEW_WORKGROUP} AND up_value=$in{workGroupId}"; $sth = $dbh->prepare($sql); $sth->execute(); foreach ( grep { $_ =~ /^user/ } keys %in ) { $_ =~ /^user_(\d+)/; my $userId = $1; $sql = "INSERT INTO user_permission SET u_id=${userId}, up_type=${UP_VIEW_WORKGROUP}, up_value=$in{workGroupId}"; $sth = $dbh->prepare($sql); $sth->execute(); } }; if ($@) { $dbh->rollback(); $in{errorMsg} = 'Unable to update Workgroup user list'; } else { $dbh->commit(); $in{errorMsg} = 'Updated Workgroup user list'; } $dbh->{AutoCommit} = 1; $usersInItemBank = &getUsersByItemBank($dbh, $in{itemBankId}); return [ $q->psgi_header('text/html'), [ &print_assign_users_to_workgroup() ] ]; } } ### ALL DONE! ### sub print_welcome { my $psgi_out = ''; # Let the user select a workgroup to edit, or edit a workgroup my %bankHash = map { $_ => $banks->{$_}{name} } keys %$banks; my $itemBankHtml = &hashToSelect( 'itemBankId', \%bankHash, $in{itemBankId}, 'reloadForm(this.form);', '', 'value' ); my %wgHash = map { $_ => $workGroups->{$_}{name} } keys %$workGroups; my $wgHtml = &hashToSelect( 'workGroupId', \%wgHash, '', '', '', 'value' ); my $errorHtml = ( exists $in{errorMsg} ? '<div style="color:blue;">' . $in{errorMsg} . '</div>' : '' ); $psgi_out .= <<END_HERE; <!DOCTYPE HTML> <html> <head> <link href="${orcaUrl}style/text.css" rel="stylesheet" type="text/css"> <script language="JavaScript"> function reloadForm(f) { f.myAction.value = ''; f.submit(); } function editWorkGroupSubmit(f) { if( f.workGroupId.options[f.workGroupId.selectedIndex].value == '' ) { alert('Please Select a Workgroup to Edit.'); f.workGroupId.focus(); return false; } f.myAction.value = 'editWorkGroup'; f.submit(); } function assignUserWorkGroupSubmit(f) { if( f.workGroupId.options[f.workGroupId.selectedIndex].value == '' ) { alert('Please Select a Workgroup to Assign Users.'); f.workGroupId.focus(); return false; } f.myAction.value = 'editUsers'; f.submit(); } function addWorkGroupSubmit(f) { if( f.workGroupName.value.match(/^\\s*\$/) ) { alert('Please Enter a Workgroup Name to Add.'); f.workGroupName.focus(); return false; } f.myAction.value = 'addWorkGroup'; f.submit(); } </script> </head> <body> <div class="title">Workgroup Management</div> ${errorHtml} <form name="form1" action="${thisUrl}" method="POST"> <input type="hidden" name="myAction" value="" /> <table id="main" border="0" cellpadding="3" cellspacing="3" class="no-style"> <tr> <td>Program:</td> <td>${itemBankHtml}</td> </tr> <tr> <td>Edit Workgroup:</td> <td>${wgHtml}</td> </tr> <tr> <td colspan="2"> <input class="action_button" type="button" value="Edit" onClick="editWorkGroupSubmit(this.form);" /> &nbsp;&nbsp;&nbsp; <input class="action_button" type="button" value="Assign Users" onClick="assignUserWorkGroupSubmit(this.form);" /> </td> </tr> <tr> <td colspan="2">OR</td> </tr> <tr> <td colspan="2">Add Workgroup</td> </tr> <tr> <td>Name:</td><td><input class="value-long" type="text" size="20" name="workGroupName" maxlength="50" /></td> </tr> <tr> <td colspan="2"><input class="action_button" type="button" value="Add" onClick="addWorkGroupSubmit(this.form);" /></td> </tr> </table> </form> </body> </html> END_HERE return $psgi_out; } sub print_edit_workgroup { my $psgi_out = ''; my %wgHash = map { $_ => $workGroups->{$_}{name} } keys %$workGroups; my $wgHtml = &hashToSelect( 'workGroupId', \%wgHash, $in{workGroupId}, 'doWorkGroupSelect();', '', 'value' ); my $itemBankName = $banks->{$in{itemBankId}}{name}; my $errorHtml = ( exists $in{errorMsg} ? '<div style="color:blue;">' . $in{errorMsg} . '</div>' : '' ); my $workGroup = $workGroups->{ $in{workGroupId} }; my $filterSelect = ''; foreach my $field (@workGroupFields) { $filterSelect .= $labels[$field] . ' = ' . &hashToSelect('filterField' . $field, $const[$field]) . '&nbsp;&nbsp;&nbsp;'; } $psgi_out .= <<END_HERE; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link href="${orcaUrl}style/text.css" rel="stylesheet" type="text/css"> <script language="JavaScript"> function doSave(f) { f.myAction.value = 'save'; f.submit(); } function doBack(f) { f.myAction.value = ''; f.submit(); } function doItemBankSelect() { document.form1.myAction.value='editBank'; document.form1.submit(); } function doAddFilter(f) { f.myAction.value = 'addFilter'; f.submit(); } function doDeleteFilter(f, fId) { f.myAction.value = 'deleteFilter'; f.filterId.value = fId; f.submit(); } function showWG() { alert('WG = $workGroup->{name}'); alert('Desc = $workGroup->{description}'); } </script> </head> <body> <div class="title">Edit Workgroup</div> ${errorHtml} <form name="form1" action="${thisUrl}" method="POST"> <input type="hidden" name="myAction" value="" /> <input type="hidden" name="filterId" value="" /> <table id="main" border="0" cellpadding="3" cellspacing="2" class="no-style"> <tr> <td>Program:</td><td>${itemBankName}</td> </tr> <tr> <td>Workgroup:</td> <td>${wgHtml}</td> </tr> <tr> <td>Description:</td> <td><input type="text" name="description" size="40" value="$workGroup->{description}" maxlength="100" /></td> </tr> <tr> <td> <input type="button" value="Save" onClick="doSave(this.form);" /> </td> <td> <input type="button" value="Back" onClick="doBack(this.form);" /> </td> </tr> </table> <br /><br /> <div class="title">Filters</div> <p>New Filter: ${filterSelect}&nbsp;&nbsp; <input type="button" value="Add" onClick="doAddFilter(this.form);" /> </p> <table id="detail" border="1" cellpadding="2" cellspacing="2" > <tr> END_HERE foreach my $field (@workGroupFields) { $psgi_out .= '<th>' . $labels[$field] . '</th>'; } $psgi_out .= '<th>Action</th></tr>'; my $filters = &getWorkgroupFilters($dbh, $in{workGroupId}); if(scalar keys %{$filters}) { foreach my $filterKey (keys %{$filters}) { my $filter = $filters->{$filterKey}; $psgi_out .= '<tr>'; foreach my $field (@workGroupFields) { $psgi_out .= '<td>' . $const[$field]->{$filter->{parts}{$field}} . '</td>'; } $psgi_out .= '<td><input type="button" value="Delete" onClick="doDeleteFilter(this.form,' . $filterKey . ');" /></td></tr>'; } } else { $psgi_out .= '<tr><td colspan="3" align="center">No filters defined for this workgroup.</td></tr>'; } $psgi_out .= '</table></body></html>'; return $psgi_out; } sub print_assign_users_to_workgroup { my $psgi_out = ''; my %wgHash = map { $_ => $workGroups->{$_}{name} } keys %$workGroups; my $wgHtml = &hashToSelect( 'workGroupId', \%wgHash, $in{workGroupId}, 'doWorkGroupSelect();', '', 'value' ); my $itemBankName = $banks->{$in{itemBankId}}{name}; my $usersInWorkgroup = &getUsersInWorkgroup($in{workGroupId}); my $errorHtml = ( exists $in{errorMsg} ? '<div style="color:blue;">' . $in{errorMsg} . '</div>' : '' ); my $workGroup = $workGroups->{ $in{workGroupId} }; $psgi_out .= <<END_HERE; <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link href="${orcaUrl}style/text.css" rel="stylesheet" type="text/css"> <script language="JavaScript"> function doSaveSubmit() { document.form1.myAction.value = 'saveUsers'; document.form1.submit(); } function doWorkGroupSelect() { document.form1.myAction.value='editUsers'; document.form1.submit(); } function doBack(f) { f.myAction.value = ''; f.submit(); } </script> </head> <body> <div class="title">Edit Workgroup Users</div> ${errorHtml} <form name="form1" action="${thisUrl}" method="POST"> <input type="hidden" name="myAction" value="" /> <table id="users" border="0" cellpadding="3" cellspacing="2" class="no-style"> <tr> <td>Program:</td> <td>${itemBankName}</td> </tr> <tr> <td>Workgroup:</td> <td>${wgHtml}</td> </tr> END_HERE foreach my $role ( sort { $a <=> $b } keys %review_type ) { $psgi_out .= '<th align="left" width="190px">' . $review_type{$role} . "</th>\n"; } $psgi_out .= '</tr><tr>'; foreach my $role ( sort { $a <=> $b } keys %review_type ) { $psgi_out .= '<td valign="top">'; foreach my $key ( sort { $usersInItemBank->{$a}{name} cmp $usersInItemBank->{$b}{name} } grep { $usersInItemBank->{$_}{reviewType} == $role } keys %$usersInItemBank ) { my $checked = exists( $usersInWorkgroup->{$key} ) ? 'CHECKED' : ''; $psgi_out .= <<END_HERE; <div style="margin-top:2px;margin-bottom:2px;border-bottom:1px solid black;"><input type="checkbox" name="user_${key}" value="yes" ${checked} />&nbsp;&nbsp;$usersInItemBank->{$key}{name}</div> END_HERE } $psgi_out .= '&nbsp;</td>'; } $psgi_out .= '</tr>'; $psgi_out .= <<END_HERE; </table> <br /> <p><input type="button" value="Save" onClick="doSaveSubmit();" />&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="button" value="Back" onClick="doBack(this.form);" /> </p> </form> </body> </html> END_HERE return $psgi_out; } sub getUsersInWorkgroup { my $workGroupId = shift; my %users = (); my $sql = <<SQL; SELECT u_id FROM user_permission WHERE up_type=${UP_VIEW_WORKGROUP} AND up_value=${workGroupId} SQL my $sth = $dbh->prepare($sql); $sth->execute(); while(my $row = $sth->fetchrow_hashref) { $users{$row->{u_id}} = 1; } return \%users; } 1;
SmarterApp/ItemAuthoring
sbac-iaip/perl/Action/workgroupManage.pm
Perl
apache-2.0
14,622
package IO::Scalar; =head1 NAME IO::Scalar - IO:: interface for reading/writing a scalar =head1 SYNOPSIS Perform I/O on strings, using the basic OO interface... use 5.005; use IO::Scalar; $data = "My message:\n"; ### Open a handle on a string, and append to it: $SH = new IO::Scalar \$data; $SH->print("Hello"); $SH->print(", world!\nBye now!\n"); print "The string is now: ", $data, "\n"; ### Open a handle on a string, read it line-by-line, then close it: $SH = new IO::Scalar \$data; while (defined($_ = $SH->getline)) { print "Got line: $_"; } $SH->close; ### Open a handle on a string, and slurp in all the lines: $SH = new IO::Scalar \$data; print "All lines:\n", $SH->getlines; ### Get the current position (either of two ways): $pos = $SH->getpos; $offset = $SH->tell; ### Set the current position (either of two ways): $SH->setpos($pos); $SH->seek($offset, 0); ### Open an anonymous temporary scalar: $SH = new IO::Scalar; $SH->print("Hi there!"); print "I printed: ", ${$SH->sref}, "\n"; ### get at value Don't like OO for your I/O? No problem. Thanks to the magic of an invisible tie(), the following now works out of the box, just as it does with IO::Handle: use 5.005; use IO::Scalar; $data = "My message:\n"; ### Open a handle on a string, and append to it: $SH = new IO::Scalar \$data; print $SH "Hello"; print $SH ", world!\nBye now!\n"; print "The string is now: ", $data, "\n"; ### Open a handle on a string, read it line-by-line, then close it: $SH = new IO::Scalar \$data; while (<$SH>) { print "Got line: $_"; } close $SH; ### Open a handle on a string, and slurp in all the lines: $SH = new IO::Scalar \$data; print "All lines:\n", <$SH>; ### Get the current position (WARNING: requires 5.6): $offset = tell $SH; ### Set the current position (WARNING: requires 5.6): seek $SH, $offset, 0; ### Open an anonymous temporary scalar: $SH = new IO::Scalar; print $SH "Hi there!"; print "I printed: ", ${$SH->sref}, "\n"; ### get at value And for you folks with 1.x code out there: the old tie() style still works, though this is I<unnecessary and deprecated>: use IO::Scalar; ### Writing to a scalar... my $s; tie *OUT, 'IO::Scalar', \$s; print OUT "line 1\nline 2\n", "line 3\n"; print "String is now: $s\n" ### Reading and writing an anonymous scalar... tie *OUT, 'IO::Scalar'; print OUT "line 1\nline 2\n", "line 3\n"; tied(OUT)->seek(0,0); while (<OUT>) { print "Got line: ", $_; } Stringification works, too! my $SH = new IO::Scalar \$data; print $SH "Hello, "; print $SH "world!"; print "I printed: $SH\n"; =head1 DESCRIPTION This class is part of the IO::Stringy distribution; see L<IO::Stringy> for change log and general information. The IO::Scalar class implements objects which behave just like IO::Handle (or FileHandle) objects, except that you may use them to write to (or read from) scalars. These handles are automatically tiehandle'd (though please see L<"WARNINGS"> for information relevant to your Perl version). Basically, this: my $s; $SH = new IO::Scalar \$s; $SH->print("Hel", "lo, "); ### OO style $SH->print("world!\n"); ### ditto Or this: my $s; $SH = tie *OUT, 'IO::Scalar', \$s; print OUT "Hel", "lo, "; ### non-OO style print OUT "world!\n"; ### ditto Causes $s to be set to: "Hello, world!\n" =head1 PUBLIC INTERFACE =cut use Carp; use strict; use vars qw($VERSION @ISA); use IO::Handle; use 5.005; ### Stringification, courtesy of B. K. Oxley (binkley): :-) use overload '""' => sub { ${*{$_[0]}->{SR}} }; use overload 'bool' => sub { 1 }; ### have to do this, so object is true! ### The package version, both in 1.23 style *and* usable by MakeMaker: $VERSION = "2.110"; ### Inheritance: @ISA = qw(IO::Handle); ### This stuff should be got rid of ASAP. require IO::WrapTie and push @ISA, 'IO::WrapTie::Slave' if ($] >= 5.004); #============================== =head2 Construction =over 4 =cut #------------------------------ =item new [ARGS...] I<Class method.> Return a new, unattached scalar handle. If any arguments are given, they're sent to open(). =cut sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = bless \do { local *FH }, $class; tie *$self, $class, $self; $self->open(@_); ### open on anonymous by default $self; } sub DESTROY { shift->close; } #------------------------------ =item open [SCALARREF] I<Instance method.> Open the scalar handle on a new scalar, pointed to by SCALARREF. If no SCALARREF is given, a "private" scalar is created to hold the file data. Returns the self object on success, undefined on error. =cut sub open { my ($self, $sref) = @_; ### Sanity: defined($sref) or do {my $s = ''; $sref = \$s}; (ref($sref) eq "SCALAR") or croak "open() needs a ref to a scalar"; ### Setup: *$self->{Pos} = 0; ### seek position *$self->{SR} = $sref; ### scalar reference $self; } #------------------------------ =item opened I<Instance method.> Is the scalar handle opened on something? =cut sub opened { *{shift()}->{SR}; } #------------------------------ =item close I<Instance method.> Disassociate the scalar handle from its underlying scalar. Done automatically on destroy. =cut sub close { my $self = shift; %{*$self} = (); 1; } =back =cut #============================== =head2 Input and output =over 4 =cut #------------------------------ =item flush I<Instance method.> No-op, provided for OO compatibility. =cut sub flush { "0 but true" } #------------------------------ =item getc I<Instance method.> Return the next character, or undef if none remain. =cut sub getc { my $self = shift; ### Return undef right away if at EOF; else, move pos forward: return undef if $self->eof; substr(${*$self->{SR}}, *$self->{Pos}++, 1); } #------------------------------ =item getline I<Instance method.> Return the next line, or undef on end of string. Can safely be called in an array context. Currently, lines are delimited by "\n". =cut sub getline { my $self = shift; ### Return undef right away if at EOF: return undef if $self->eof; ### Get next line: my $sr = *$self->{SR}; my $i = *$self->{Pos}; ### Start matching at this point. ### Minimal impact implementation! ### We do the fast fast thing (no regexps) if using the ### classic input record separator. ### Case 1: $/ is undef: slurp all... if (!defined($/)) { *$self->{Pos} = length $$sr; return substr($$sr, $i); } ### Case 2: $/ is "\n": zoom zoom zoom... elsif ($/ eq "\012") { ### Seek ahead for "\n"... yes, this really is faster than regexps. my $len = length($$sr); for (; $i < $len; ++$i) { last if ord (substr ($$sr, $i, 1)) == 10; } ### Extract the line: my $line; if ($i < $len) { ### We found a "\n": $line = substr ($$sr, *$self->{Pos}, $i - *$self->{Pos} + 1); *$self->{Pos} = $i+1; ### Remember where we finished up. } else { ### No "\n"; slurp the remainder: $line = substr ($$sr, *$self->{Pos}, $i - *$self->{Pos}); *$self->{Pos} = $len; } return $line; } ### Case 3: $/ is ref to int. Do fixed-size records. ### (Thanks to Dominique Quatravaux.) elsif (ref($/)) { my $len = length($$sr); my $i = ${$/} + 0; my $line = substr ($$sr, *$self->{Pos}, $i); *$self->{Pos} += $i; *$self->{Pos} = $len if (*$self->{Pos} > $len); return $line; } ### Case 4: $/ is either "" (paragraphs) or something weird... ### This is Graham's general-purpose stuff, which might be ### a tad slower than Case 2 for typical data, because ### of the regexps. else { pos($$sr) = $i; ### If in paragraph mode, skip leading lines (and update i!): length($/) or (($$sr =~ m/\G\n*/g) and ($i = pos($$sr))); ### If we see the separator in the buffer ahead... if (length($/) ? $$sr =~ m,\Q$/\E,g ### (ordinary sep) TBD: precomp! : $$sr =~ m,\n\n,g ### (a paragraph) ) { *$self->{Pos} = pos $$sr; return substr($$sr, $i, *$self->{Pos}-$i); } ### Else if no separator remains, just slurp the rest: else { *$self->{Pos} = length $$sr; return substr($$sr, $i); } } } #------------------------------ =item getlines I<Instance method.> Get all remaining lines. It will croak() if accidentally called in a scalar context. =cut sub getlines { my $self = shift; wantarray or croak("can't call getlines in scalar context!"); my ($line, @lines); push @lines, $line while (defined($line = $self->getline)); @lines; } #------------------------------ =item print ARGS... I<Instance method.> Print ARGS to the underlying scalar. B<Warning:> this continues to always cause a seek to the end of the string, but if you perform seek()s and tell()s, it is still safer to explicitly seek-to-end before subsequent print()s. =cut sub print { my $self = shift; *$self->{Pos} = length(${*$self->{SR}} .= join('', @_) . (defined($\) ? $\ : "")); 1; } sub _unsafe_print { my $self = shift; my $append = join('', @_) . $\; ${*$self->{SR}} .= $append; *$self->{Pos} += length($append); 1; } sub _old_print { my $self = shift; ${*$self->{SR}} .= join('', @_) . $\; *$self->{Pos} = length(${*$self->{SR}}); 1; } #------------------------------ =item read BUF, NBYTES, [OFFSET] I<Instance method.> Read some bytes from the scalar. Returns the number of bytes actually read, 0 on end-of-file, undef on error. =cut sub read { my $self = $_[0]; my $n = $_[2]; my $off = $_[3] || 0; my $read = substr(${*$self->{SR}}, *$self->{Pos}, $n); $n = length($read); *$self->{Pos} += $n; ($off ? substr($_[1], $off) : $_[1]) = $read; return $n; } #------------------------------ =item write BUF, NBYTES, [OFFSET] I<Instance method.> Write some bytes to the scalar. =cut sub write { my $self = $_[0]; my $n = $_[2]; my $off = $_[3] || 0; my $data = substr($_[1], $off, $n); $n = length($data); $self->print($data); return $n; } #------------------------------ =item sysread BUF, LEN, [OFFSET] I<Instance method.> Read some bytes from the scalar. Returns the number of bytes actually read, 0 on end-of-file, undef on error. =cut sub sysread { my $self = shift; $self->read(@_); } #------------------------------ =item syswrite BUF, NBYTES, [OFFSET] I<Instance method.> Write some bytes to the scalar. =cut sub syswrite { my $self = shift; $self->write(@_); } =back =cut #============================== =head2 Seeking/telling and other attributes =over 4 =cut #------------------------------ =item autoflush I<Instance method.> No-op, provided for OO compatibility. =cut sub autoflush {} #------------------------------ =item binmode I<Instance method.> No-op, provided for OO compatibility. =cut sub binmode {} #------------------------------ =item clearerr I<Instance method.> Clear the error and EOF flags. A no-op. =cut sub clearerr { 1 } #------------------------------ =item eof I<Instance method.> Are we at end of file? =cut sub eof { my $self = shift; (*$self->{Pos} >= length(${*$self->{SR}})); } #------------------------------ =item seek OFFSET, WHENCE I<Instance method.> Seek to a given position in the stream. =cut sub seek { my ($self, $pos, $whence) = @_; my $eofpos = length(${*$self->{SR}}); ### Seek: if ($whence == 0) { *$self->{Pos} = $pos } ### SEEK_SET elsif ($whence == 1) { *$self->{Pos} += $pos } ### SEEK_CUR elsif ($whence == 2) { *$self->{Pos} = $eofpos + $pos} ### SEEK_END else { croak "bad seek whence ($whence)" } ### Fixup: if (*$self->{Pos} < 0) { *$self->{Pos} = 0 } if (*$self->{Pos} > $eofpos) { *$self->{Pos} = $eofpos } return 1; } #------------------------------ =item sysseek OFFSET, WHENCE I<Instance method.> Identical to C<seek OFFSET, WHENCE>, I<q.v.> =cut sub sysseek { my $self = shift; $self->seek (@_); } #------------------------------ =item tell I<Instance method.> Return the current position in the stream, as a numeric offset. =cut sub tell { *{shift()}->{Pos} } #------------------------------ # # use_RS [YESNO] # # I<Instance method.> # Obey the curent setting of $/, like IO::Handle does? # Default is false in 1.x, but cold-welded true in 2.x and later. # sub use_RS { my ($self, $yesno) = @_; carp "use_RS is deprecated and ignored; \$/ is always consulted\n"; } #------------------------------ =item setpos POS I<Instance method.> Set the current position, using the opaque value returned by C<getpos()>. =cut sub setpos { shift->seek($_[0],0) } #------------------------------ =item getpos I<Instance method.> Return the current position in the string, as an opaque object. =cut *getpos = \&tell; #------------------------------ =item sref I<Instance method.> Return a reference to the underlying scalar. =cut sub sref { *{shift()}->{SR} } #------------------------------ # Tied handle methods... #------------------------------ # Conventional tiehandle interface: sub TIEHANDLE { ((defined($_[1]) && UNIVERSAL::isa($_[1], "IO::Scalar")) ? $_[1] : shift->new(@_)); } sub GETC { shift->getc(@_) } sub PRINT { shift->print(@_) } sub PRINTF { shift->print(sprintf(shift, @_)) } sub READ { shift->read(@_) } sub READLINE { wantarray ? shift->getlines(@_) : shift->getline(@_) } sub WRITE { shift->write(@_); } sub CLOSE { shift->close(@_); } sub SEEK { shift->seek(@_); } sub TELL { shift->tell(@_); } sub EOF { shift->eof(@_); } #------------------------------------------------------------ 1; __END__ =back =cut =head1 WARNINGS Perl's TIEHANDLE spec was incomplete prior to 5.005_57; it was missing support for C<seek()>, C<tell()>, and C<eof()>. Attempting to use these functions with an IO::Scalar will not work prior to 5.005_57. IO::Scalar will not have the relevant methods invoked; and even worse, this kind of bug can lie dormant for a while. If you turn warnings on (via C<$^W> or C<perl -w>), and you see something like this... attempt to seek on unopened filehandle ...then you are probably trying to use one of these functions on an IO::Scalar with an old Perl. The remedy is to simply use the OO version; e.g.: $SH->seek(0,0); ### GOOD: will work on any 5.005 seek($SH,0,0); ### WARNING: will only work on 5.005_57 and beyond =head1 VERSION $Id: Scalar.pm 1248 2008-03-25 00:51:31Z warnes $ =head1 AUTHORS =head2 Primary Maintainer David F. Skoll (F<dfs@roaringpenguin.com>). =head2 Principal author Eryq (F<eryq@zeegee.com>). President, ZeeGee Software Inc (F<http://www.zeegee.com>). =head2 Other contributors The full set of contributors always includes the folks mentioned in L<IO::Stringy/"CHANGE LOG">. But just the same, special thanks to the following individuals for their invaluable contributions (if I've forgotten or misspelled your name, please email me!): I<Andy Glew,> for contributing C<getc()>. I<Brandon Browning,> for suggesting C<opened()>. I<David Richter,> for finding and fixing the bug in C<PRINTF()>. I<Eric L. Brine,> for his offset-using read() and write() implementations. I<Richard Jones,> for his patches to massively improve the performance of C<getline()> and add C<sysread> and C<syswrite>. I<B. K. Oxley (binkley),> for stringification and inheritance improvements, and sundry good ideas. I<Doug Wilson,> for the IO::Handle inheritance and automatic tie-ing. =head1 SEE ALSO L<IO::String>, which is quite similar but which was designed more-recently and with an IO::Handle-like interface in mind, so you could mix OO- and native-filehandle usage without using tied(). I<Note:> as of version 2.x, these classes all work like their IO::Handle counterparts, so we have comparable functionality to IO::String. =cut
LanceFiondella/srt.core
srt_packages/lib/gdata/perl/IO/Scalar.pm
Perl
mit
16,736
=pod =head1 NAME llvm-config - Print LLVM compilation options =head1 SYNOPSIS B<llvm-config> I<option> [I<components>...] =head1 DESCRIPTION B<llvm-config> makes it easier to build applications that use LLVM. It can print the compiler flags, linker flags and object libraries needed to link against LLVM. =head1 EXAMPLES To link against the JIT: g++ `llvm-config --cxxflags` -o HowToUseJIT.o -c HowToUseJIT.cpp g++ `llvm-config --ldflags` -o HowToUseJIT HowToUseJIT.o \ `llvm-config --libs engine bcreader scalaropts` =head1 OPTIONS =over =item B<--version> Print the version number of LLVM. =item B<-help> Print a summary of B<llvm-config> arguments. =item B<--prefix> Print the installation prefix for LLVM. =item B<--src-root> Print the source root from which LLVM was built. =item B<--obj-root> Print the object root used to build LLVM. =item B<--bindir> Print the installation directory for LLVM binaries. =item B<--includedir> Print the installation directory for LLVM headers. =item B<--libdir> Print the installation directory for LLVM libraries. =item B<--cxxflags> Print the C++ compiler flags needed to use LLVM headers. =item B<--ldflags> Print the flags needed to link against LLVM libraries. =item B<--libs> Print all the libraries needed to link against the specified LLVM I<components>, including any dependencies. =item B<--libnames> Similar to B<--libs>, but prints the bare filenames of the libraries without B<-l> or pathnames. Useful for linking against a not-yet-installed copy of LLVM. =item B<--libfiles> Similar to B<--libs>, but print the full path to each library file. This is useful when creating makefile dependencies, to ensure that a tool is relinked if any library it uses changes. =item B<--components> Print all valid component names. =item B<--targets-built> Print the component names for all targets supported by this copy of LLVM. =item B<--build-mode> Print the build mode used when LLVM was built (e.g. Debug or Release) =back =head1 COMPONENTS To print a list of all available components, run B<llvm-config --components>. In most cases, components correspond directly to LLVM libraries. Useful "virtual" components include: =over =item B<all> Includes all LLVM libaries. The default if no components are specified. =item B<backend> Includes either a native backend or the C backend. =item B<engine> Includes either a native JIT or the bitcode interpreter. =back =head1 EXIT STATUS If B<llvm-config> succeeds, it will exit with 0. Otherwise, if an error occurs, it will exit with a non-zero value. =head1 AUTHORS Maintained by the LLVM Team (L<http://llvm.org>). =cut
wrmsr/lljvm
thirdparty/llvm/docs/CommandGuide/llvm-config.pod
Perl
mit
2,684
#!./perl -w # Regression tests for attributes.pm and the C< : attrs> syntax. sub NTESTS () ; my ($test, $ntests); BEGIN {$ntests=0} $test=0; my $failed = 0; print "1..".NTESTS."\n"; $SIG{__WARN__} = sub { die @_ }; sub mytest { if (!$@ ne !$_[0] || $_[0] && $@ !~ $_[0]) { if ($@) { my $x = $@; $x =~ s/\n.*\z//s; print "# Got: $x\n" } else { print "# Got unexpected success\n"; } if ($_[0]) { print "# Expected: $_[0]\n"; } else { print "# Expected success\n"; } $failed = 1; print "not "; } elsif (@_ == 3 && $_[1] ne $_[2]) { print "# Got: $_[1]\n"; print "# Expected: $_[2]\n"; $failed = 1; print "not "; } print "ok ",++$test,"\n"; } eval 'sub t1 ($) : locked { $_[0]++ }'; mytest; BEGIN {++$ntests} eval 'sub t2 : locked { $_[0]++ }'; mytest; BEGIN {++$ntests} eval 'sub t3 ($) : locked ;'; mytest; BEGIN {++$ntests} eval 'sub t4 : locked ;'; mytest; BEGIN {++$ntests} my $anon1; eval '$anon1 = sub ($) : locked:method { $_[0]++ }'; mytest; BEGIN {++$ntests} my $anon2; eval '$anon2 = sub : locked : method { $_[0]++ }'; mytest; BEGIN {++$ntests} my $anon3; eval '$anon3 = sub : method { $_[0]->[1] }'; mytest; BEGIN {++$ntests} eval 'sub e1 ($) : plugh ;'; mytest qr/^Invalid CODE attributes?: ["']?plugh["']? at/; BEGIN {++$ntests} eval 'sub e2 ($) : plugh(0,0) xyzzy ;'; mytest qr/^Invalid CODE attributes: ["']?plugh\(0,0\)["']? /; BEGIN {++$ntests} eval 'sub e3 ($) : plugh(0,0 xyzzy ;'; mytest qr/Unterminated attribute parameter in attribute list at/; BEGIN {++$ntests} eval 'sub e4 ($) : plugh + xyzzy ;'; mytest qr/Invalid separator character '[+]' in attribute list at/; BEGIN {++$ntests} eval 'my main $x : = 0;'; mytest; BEGIN {++$ntests} eval 'my $x : = 0;'; mytest; BEGIN {++$ntests} eval 'my $x ;'; mytest; BEGIN {++$ntests} eval 'my ($x) : = 0;'; mytest; BEGIN {++$ntests} eval 'my ($x) ;'; mytest; BEGIN {++$ntests} eval 'my ($x) : ;'; mytest; BEGIN {++$ntests} eval 'my ($x,$y) : = 0;'; mytest; BEGIN {++$ntests} eval 'my ($x,$y) ;'; mytest; BEGIN {++$ntests} eval 'my ($x,$y) : ;'; mytest; BEGIN {++$ntests} eval 'my ($x,$y) : plugh;'; mytest qr/^Invalid SCALAR attribute: ["']?plugh["']? at/; BEGIN {++$ntests} sub A::MODIFY_SCALAR_ATTRIBUTES { return } eval 'my A $x : plugh;'; mytest qr/^SCALAR package attribute may clash with future reserved word: ["']?plugh["']? at/; BEGIN {++$ntests} eval 'my A $x : plugh plover;'; mytest qr/^SCALAR package attributes may clash with future reserved words: ["']?plugh["']? /; BEGIN {++$ntests} eval 'package Cat; my Cat @socks;'; mytest qr/^Can't declare class for non-scalar \@socks in "my"/; BEGIN {++$ntests} sub X::MODIFY_CODE_ATTRIBUTES { die "$_[0]" } sub X::foo { 1 } *Y::bar = \&X::foo; *Y::bar = \&X::foo; # second time for -w eval 'package Z; sub Y::bar : foo'; mytest qr/^X at /; BEGIN {++$ntests} eval 'package Z; sub Y::baz : locked {}'; my @attrs = eval 'attributes::get \&Y::baz'; mytest '', "@attrs", "locked"; BEGIN {++$ntests} @attrs = eval 'attributes::get $anon1'; mytest '', "@attrs", "locked method"; BEGIN {++$ntests} sub Z::DESTROY { } sub Z::FETCH_CODE_ATTRIBUTES { return 'Z' } my $thunk = eval 'bless +sub : method locked { 1 }, "Z"'; mytest '', ref($thunk), "Z"; BEGIN {++$ntests} @attrs = eval 'attributes::get $thunk'; mytest '', "@attrs", "locked method Z"; BEGIN {++$ntests} # Other tests should be added above this line sub NTESTS () { $ntests } #exit $failed; 1;
aferr/LatticeMemCtl
benchmarks/spec2k6bin/specint/perl_depends/attrs.pl
Perl
bsd-3-clause
3,469
require 5; package Pod::Simple::Progress; $VERSION = "1.01"; use strict; # Objects of this class are used for noting progress of an # operation every so often. Messages delivered more often than that # are suppressed. # # There's actually nothing in here that's specific to Pod processing; # but it's ad-hoc enough that I'm not willing to give it a name that # implies that it's generally useful, like "IO::Progress" or something. # # -- sburke # #-------------------------------------------------------------------------- sub new { my($class,$delay) = @_; my $self = bless {'quiet_until' => 1}, ref($class) || $class; $self->to(*STDOUT{IO}); $self->delay(defined($delay) ? $delay : 5); return $self; } sub copy { my $orig = shift; bless {%$orig, 'quiet_until' => 1}, ref($orig); } #-------------------------------------------------------------------------- sub reach { my($self, $point, $note) = @_; if( (my $now = time) >= $self->{'quiet_until'}) { my $goal; my $to = $self->{'to'}; print $to join('', ($self->{'quiet_until'} == 1) ? () : '... ', (defined $point) ? ( '#', ($goal = $self->{'goal'}) ? ( ' ' x (length($goal) - length($point)), $point, '/', $goal, ) : $point, $note ? ': ' : (), ) : (), $note || '', "\n" ); $self->{'quiet_until'} = $now + $self->{'delay'}; } return $self; } #-------------------------------------------------------------------------- sub done { my($self, $note) = @_; $self->{'quiet_until'} = 1; return $self->reach( undef, $note ); } #-------------------------------------------------------------------------- # Simple accessors: sub delay { return $_[0]{'delay'} if @_ == 1; $_[0]{'delay'} = $_[1]; return $_[0] } sub goal { return $_[0]{'goal' } if @_ == 1; $_[0]{'goal' } = $_[1]; return $_[0] } sub to { return $_[0]{'to' } if @_ == 1; $_[0]{'to' } = $_[1]; return $_[0] } #-------------------------------------------------------------------------- unless(caller) { # Simple self-test: my $p = __PACKAGE__->new->goal(5); $p->reach(1, "Primus!"); sleep 1; $p->reach(2, "Secundus!"); sleep 3; $p->reach(3, "Tertius!"); sleep 5; $p->reach(4); $p->reach(5, "Quintus!"); sleep 1; $p->done("All done"); } #-------------------------------------------------------------------------- 1; __END__
leighpauls/k2cro4
third_party/cygwin/lib/perl5/vendor_perl/5.10/Pod/Simple/Progress.pm
Perl
bsd-3-clause
2,413
#!/usr/bin/perl -w # # ***** BEGIN LICENSE BLOCK ***** # Zimbra Collaboration Suite Server # Copyright (C) 2008, 2009, 2010 Zimbra, Inc. # # The contents of this file are subject to the Zimbra Public License # Version 1.3 ("License"); you may not use this file except in # compliance with the License. You may obtain a copy of the License at # http://www.zimbra.com/license. # # Software distributed under the License is distributed on an "AS IS" # basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. # ***** END LICENSE BLOCK ***** # use strict; use lib '.'; use LWP::UserAgent; use Getopt::Long; use XmlDoc; use Soap; use ZimbraSoapTest; #standard options my ($sessionId, $authToken, $user, $pw, $host, $help, $verbose); #standard my ($idle); GetOptions("u|user=s" => \$user, "pw=s" => \$pw, "h|host=s" => \$host, "help|?" => \$help, "v" => \$verbose, "sessionId=s" => \$sessionId, "at=s" => \$authToken, "idle" => \$idle, ); my $usage = <<END_OF_USAGE; USAGE: $0 -u USER [-v] [-at authToken] [-s sessionId] [-idle] END_OF_USAGE if (!defined($user)) { die $usage; } my %soapargs; $soapargs{ 'NOTIFY'} = 1; if (defined($sessionId)) { $soapargs{'SESSIONID'} = $sessionId; } else { die $usage; } my $z = ZimbraSoapTest->new($user, $host, $pw, \%soapargs); $z->verbose(3); if (defined($sessionId) && defined($authToken)) { $z->setAuthContext($authToken, $sessionId, \%soapargs); } else { print "AUTH REQUEST:\n--------------------"; $z->doStdAuth(); } my $d = new XmlDoc; my %args = ( ); if (defined($idle)) { $args{'isIdle'} = 1; } else { $args{'isIdle'} = 0; } $args{'idleTime'} = 300; $d->add('IMSetIdleRequest', $Soap::ZIMBRA_IM_NS, \%args); print "\n\nEND_SESSION:\n--------------------"; my $response = $z->invokeMail($d->root()); #print "REQUEST:\n-------------\n".$z->to_string_simple($d); #print "RESPONSE:\n--------------\n".$z->to_string_simple($response);
nico01f/z-pec
ZimbraServer/src/perl/soap/imSetIdle.pl
Perl
mit
2,009
#!/usr/bin/env perl =head1 NAME AddTrialTypes.pm =head1 SYNOPSIS mx-run AddTrialTypes [options] -H hostname -D dbname -u username [-F] this is a subclass of L<CXGN::Metadata::Dbpatch> see the perldoc of parent class for more details. =head1 DESCRIPTION This patch adds a cv for trial types. This subclass uses L<Moose>. The parent class uses L<MooseX::Runnable> =head1 AUTHOR Jeremy D. Edwards <jde22@cornell.edu> Naama Menda <nm249@cornell.edu> =head1 COPYRIGHT & LICENSE Copyright 2010 Boyce Thompson Institute for Plant Research This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut package AddTrialTypes; use Moose; extends 'CXGN::Metadata::Dbpatch'; has '+description' => ( default => <<'' ); Description of this patch goes here has '+prereq' => ( default => sub { [ ], }, ); sub patch { my $self=shift; print STDOUT "Executing the patch:\n " . $self->name . ".\n\nDescription:\n ". $self->description . ".\n\nExecuted by:\n " . $self->username . " ."; print STDOUT "\nChecking if this db_patch was executed before or if previous db_patches have been executed.\n"; print STDOUT "\nExecuting the SQL commands.\n"; $self->dbh->do(<<EOSQL); --do your SQL here -- INSERT INTO cv (name, definition) VALUES ('trial type', ''); EOSQL print STDERR "INSERTING CV TERMS...\n"; my @terms = qw | phenotyping_trial genotyping_trial crossing_trial | ; foreach my $t (@terms) { $self->dbh->do(<<EOSQL); INSERT INTO dbxref (db_id, accession) VALUES ((SELECT db_id FROM db WHERE name='local'), '$t'); INSERT INTO cvterm (cv_id, name, definition, dbxref_id) VALUES ( (SELECT cv_id FROM cv where name='trial type' ), '$t', '$t', (SELECT dbxref_id FROM dbxref WHERE accession='$t')); EOSQL } print "Done!\n"; } #### 1; # ####
solgenomics/sgn
db/00032/AddTrialTypes.pm
Perl
mit
1,880
use strict; use warnings; # read in status file # status file has number last tested # status file has number currently being tested # status file has last number divided as a test # read in primes file into an array # loop through primes and print them # # start with next test # current number divied by last divided +1 until last divided = current number # if divide does not have a decimal (test using mod?) then exit loop and # increnemt current number # else loop again # (update files here in case of crash) # # my $currentNumber = 1000000000000; #TODO: or read in value if it exists my $sqrt = sqrt($currentNumber); my $currentDivisor; my $modRemainder; my @primes; #TODO: populate push(@primes, 2); push(@primes, 3); my $filename = "primes_".`date +%m\\_%d\\_%y\\_%H%M%S`; chomp $filename; #TODO improvements: # - only calculate up to the square root # - skip all even divisors logPrime(@primes); #read in stub #start timer stub do{ $currentDivisor = 2; #print "\n Current number being tested: ".$currentNumber; #print "\n Current divisor: ".$currentDivisor; while($sqrt > $currentDivisor){ #print "\n Current number being tested: ".$currentNumber; #print "\n Current divisor: ".$currentDivisor; $modRemainder = $currentNumber % $currentDivisor; #print "\nmodremainder is: ".$modRemainder; #if($modRemainder == 0){ # print "\n number:divisor ".$currentNumber.":".$currentDivisor; #} last if $modRemainder == 0; if($currentDivisor+1 > $sqrt){ push(@primes, $currentNumber); print "\n".$currentNumber." is prime number ".scalar @primes; logPrime(@primes); } $currentDivisor += 1; } $currentNumber += 1; $sqrt = sqrt($currentNumber); #write out stub #stub. write out time after adding time already passed }while 1; sub logPrime { my $fh; open($fh, '>>', $filename) or die "Cant open log file '$filename' $!"; print $fh (scalar @primes.", ".$currentNumber."\n"); close $fh; } __END__ sub writeLog { say "In writeLog()"; my $filename = shift; my $header = shift; my $log = shift; #print "Head: ".$header if $firstLoop; #print "Log: ".$log; open(my $fh, '>>', $filename) or die "Cant open log file '$filename' $!"; print $fh $header if $firstLoop; print $fh $log; close $fh; } sub getHosts { open(my $fh, '<', $HostFile) or die "Cant open host config file '$HostFile' $!"; while (my $IP = <$fh>) { next if substr($IP, 0, 1) eq '#'; chomp $IP; my @tuples = split(/\./,$IP); $Hosts{$IP}{'Last_Tuple'} = $tuples[3]; my $noUnderScore = $IP; $noUnderScore =~ s/\./_/g; $Hosts{$IP}{'Underscore_Host'} = $noUnderScore; } close $fh; }
AndrewRussellHayes/primes
trilprimegen.pl
Perl
mit
2,815
use strict; use Data::Dumper; use Carp; # # This is a SAS Component # =head1 NAME query_entity_Regulog =head1 SYNOPSIS query_entity_Regulog [--is field,value] [--like field,value] [--op operator,field,value] =head1 DESCRIPTION Query the entity Regulog. Results are limited using one or more of the query flags: =over 4 =item the C<--is> flag to match for exact values; =item the C<--like> flag for SQL LIKE searches, or =item the C<--op> flag for making other comparisons. =back Example: query_entity_Regulog -is id,exact-match-value -a > records =head2 Related entities The Regulog entity has the following relationship links: =over 4 =item HasRegulator Regulator =item IsInCollection RegulogCollection =item RegulogHasRegulon Regulon =back =head1 COMMAND-LINE OPTIONS query_entity_Regulog [arguments] > records =over 4 =item --is field,value Limit the results to entities where the given field has the given value. =item --like field,value Limit the results to entities where the given field is LIKE (in the sql sense) the given value. =item --op operator,field,value Limit the results to entities where the given field is related to the given value based on the given operator. The operators supported are as follows. We provide text based alternatives to the comparison operators so that extra quoting is not required to keep the command-line shell from confusing them with shell I/O redirection operators. =over 4 =item < or lt =item > or gt =item <= or le =item >= or ge =item = =item LIKE =back =item --a Return all fields. =item --show-fields Display a list of the fields available for use. =item --fields field-list Choose a set of fields to return. Field-list is a comma-separated list of strings. The following fields are available: =over 4 =item description =back =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 = ( 'description' ); my %all_fields = map { $_ => 1 } @all_fields, 'id'; our $usage = <<'END'; query_entity_Regulog [arguments] > records --is field,value Limit the results to entities where the given field has the given value. --like field,value Limit the results to entities where the given field is LIKE (in the sql sense) the given value. --op operator,field,value Limit the results to entities where the given field is related to the given value based on the given operator. The operators supported are as follows. We provide text based alternatives to the comparison operators so that extra quoting is not required to keep the command-line shell from confusing them with shell I/O redirection operators. < or lt > or gt <= or le >= or ge = LIKE -a Return all fields. --show-fields Display a list of the fields available for use. --fields field-list Choose a set of fields to return. Field-list is a comma-separated list of strings. The following fields are available: description END my $a; my $f; my @fields; my $help; my $show_fields; my @query_is; my @query_like; my @query_op; my %op_map = ('>', '>', 'gt', '>', '<', '<', 'lt', '<', '>=', '>=', 'ge', '>=', '<=', '<=', 'le', '<=', 'like', 'LIKE', ); my $geO = Bio::KBase::CDMI::CDMIClient->new_get_entity_for_script("all-fields|a" => \$a, "show-fields" => \$show_fields, "help|h" => \$help, "is=s" => \@query_is, "like=s" => \@query_like, "op=s" => \@query_op, "fields=s" => \$f); if ($help) { print $usage; exit 0; } elsif ($show_fields) { print STDERR "Available fields:\n"; print STDERR "\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_Regulog: unknown fields @err. Valid fields are: @all_fields\n"; exit 1; } } my @qry; for my $ent (@query_is) { my($field,$value) = split(/,/, $ent, 2); if (!$all_fields{$field}) { die "$field is not a valid field\n"; } push(@qry, [$field, '=', $value]); } for my $ent (@query_like) { my($field,$value) = split(/,/, $ent, 2); if (!$all_fields{$field}) { die "$field is not a valid field\n"; } push(@qry, [$field, 'LIKE', $value]); } for my $ent (@query_op) { my($op,$field,$value) = split(/,/, $ent, 3); if (!$all_fields{$field}) { die "$field is not a valid field\n"; } my $mapped_op = $op_map{lc($op)}; if (!$mapped_op) { die "$op is not a valid operator\n"; } push(@qry, [$field, $mapped_op, $value]); } my $h = $geO->query_entity_Regulog(\@qry, \@fields ); while (my($k, $v) = each %$h) { print join("\t", $k, map { ref($_) eq 'ARRAY' ? join(",", @$_) : $_ } @$v{@fields}), "\n"; }
kbase/kb_seed
scripts/query_entity_Regulog.pl
Perl
mit
5,201
package CXGN::List::FuzzySearch::Plugin::Plants; use Moose; use Data::Dumper; use SGN::Model::Cvterm; use CXGN::BreedersToolbox::StocksFuzzySearch; sub name { return "plants"; } sub fuzzysearch { my $self = shift; my $schema = shift; my $list = shift; my $max_distance = 0.2; my $fuzzy_search = CXGN::BreedersToolbox::StocksFuzzySearch->new({schema => $schema}); my $fuzzy_search_result = $fuzzy_search->get_matches($list, $max_distance, 'plant'); my $found = $fuzzy_search_result->{'found'}; my $fuzzy = $fuzzy_search_result->{'fuzzy'}; my $absent = $fuzzy_search_result->{'absent'}; my %return = ( success => "1", absent => $absent, fuzzy => $fuzzy, found => $found, ); if ($fuzzy_search_result->{'error'}){ $return{error} = $fuzzy_search_result->{'error'}; } return \%return; } 1;
solgenomics/sgn
lib/CXGN/List/FuzzySearch/Plugin/Plants.pm
Perl
mit
895
#!/usr/bin/env perl6 use v6.c; sub MAIN($file="08.in", Int :$rows=6, Int :$cols=50, Bool :$verbose) { my @screen = (1..$rows).map: { Array.new('.' xx $cols) }; for $file.IO.lines { when m:s/rect (\d+)x(\d+)/ { for ^$0 -> $x { for ^$1 -> $y { @screen[$y][$x] = '*'; } } } when m:s/rotate row y\=(\d+) by (\d+)/ { @screen[$0] .= rotate(-$1);# rotate() is backward from what I'd expect } when m:s/rotate column x\=(\d+) by (\d+)/ { my $brk = $rows - $1; # Oddly, "for eager flat($brk..^$rows, ^$brk).map({ @screen[$_][$0] }).kv -> ..." # doesn't work (list still evaluaed lazily, so items get oeverwritten before caching). my @tmp = flat($brk..^$rows, ^$brk).map({ @screen[$_][$0] }); for @tmp.kv -> $i, $val { @screen[$i][$0] = $val; } } default { die "Can't parse $_"; } NEXT { if $verbose { put "$_:"; @screen.map: *.put; } } } @screen.map: *.put; say [+] @screen».grep: { /"*"/ }; } # Bummer, get this error for most commands in here: # """Partially dimensioned views of arrays not yet implemented. Sorry.""" sub xxMAIN($file="08.in", Int :$rows=6, Int :$cols=50) { my int @screen[$rows;$cols] = (0 xx $cols) xx $rows; for $file.IO.lines { when m:s/rect (\d+)x(\d+)/ { @screen[^$1;^$0] = 1 xx ($1 * $0); } when m:s/rotate row y\=(\d+) by (\d+)/ { my $brk = $cols - $1; @screen[$0;*] = @screen[$0;$brk..^$cols, ^$brk]; } when m:s/rotate column x\=(\d+) by (\d+)/ { my $brk = $rows - $1; @screen[*;$0] = @screen[$brk..^$rows, ^$brk;$0]; } default { die "Can't parse $_"; } } @screen[$_;*].put for ^$rows; say [+] @screen; }
duelafn/advent-of-code-2016-in-perl6
2016/advent-of-code/08.pl
Perl
mit
2,036
# # (c) Jan Gehring <jan.gehring@gmail.com> # # vim: set ts=3 sw=3 tw=0: # vim: set expandtab: # use strict; use warnings; package Net::OpenNebula::User; $Net::OpenNebula::User::VERSION = '0.300.0'; use Net::OpenNebula::RPC; push our @ISA , qw(Net::OpenNebula::RPC); use constant ONERPC => 'user'; sub name { my ($self) = @_; $self->_get_info(); # if user NAME is set, use that instead of template NAME return $self->{data}->{NAME}->[0] || $self->{data}->{TEMPLATE}->[0]->{NAME}->[0]; } sub create { my ($self, $name, $password, $driver) = @_; if (! defined $driver) { $driver = "core"; } return $self->_allocate([ string => $name ], [ string => $password ], [ string => $driver ], ); } 1;
gitpan/Net-OpenNebula
lib/Net/OpenNebula/User.pm
Perl
apache-2.0
817
package Paws::CloudHSM::ListAvailableZones; use Moose; use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListAvailableZones'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::CloudHSM::ListAvailableZonesResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudHSM::ListAvailableZones - Arguments for method ListAvailableZones on Paws::CloudHSM =head1 DESCRIPTION This class represents the parameters used for calling the method ListAvailableZones on the Amazon CloudHSM service. Use the attributes of this class as arguments to method ListAvailableZones. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListAvailableZones. As an example: $service_obj->ListAvailableZones(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 =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method ListAvailableZones in L<Paws::CloudHSM> =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/CloudHSM/ListAvailableZones.pm
Perl
apache-2.0
1,500
package OpenXPKI::Client::Session::Driver; use Moose; use English; use warnings; use Log::Log4perl qw(:easy); use Log::Log4perl::MDC; use Data::Dumper; use MIME::Base64 qw( encode_base64 decode_base64 ); extends 'CGI::Session::Driver'; # the OXI::Client object has 'backend' => ( required => 1, is => 'rw', isa => 'OpenXPKI::Client', ); # should be passed by the ui script to be shared, if not we create it has 'logger' => ( required => 0, lazy => 1, is => 'ro', isa => 'Object', 'default' => sub{ Log::Log4perl->initialized() || Log::Log4perl->easy_init($ERROR); return Log::Log4perl->get_logger('session'); } ); sub init { 1 } sub dump { 1 } sub store { my ($self, $sid, $datastr) = @_; my $backend_sid = $self->backend()->get_session_id(); if (!$backend_sid) { $self->logger()->debug('Skipping session store for id ' . $sid . ' - backend already gone'); } elsif($backend_sid ne $sid) { $self->logger()->error("Backend session missmatches frontend session! ($backend_sid / $sid)"); } else { $self->logger()->debug('Session store with id ' . $sid); my $res = $self->backend()->send_receive_service_msg('FRONTEND_SESSION',{ # encode_base64 prevents problems with non-ASCII characters sent over the socket (Perls UTF-8 flag gets lost) SESSION_DATA => encode_base64($datastr), }); $self->logger()->trace('Session store result ' . Dumper $res); } } sub retrieve { my ($self, $sid) = @_; my $res = $self->backend()->send_receive_service_msg('FRONTEND_SESSION'); $res = $res->{SESSION_DATA} || ''; # TODO Remove "unless..." somewhen: it's only to restore old unencoded sessions $res = decode_base64($res) if ($res and $res !~ /\{/); $self->logger()->trace('Session retrieve ' . Dumper $res); return $res; }; sub remove { my ($self, $sid) = @_; my $backend_sid = $self->backend()->get_session_id(); if ($backend_sid && $backend_sid eq $sid) { my $res = $self->backend()->send_receive_service_msg('FRONTEND_SESSION',{ SESSION_DATA => undef, }); $self->logger()->debug('Session removed'); } else { $self->logger()->warn('Unable to remove session - backend already gone'); } return; } sub traverse { my $self = shift; die "traverse() is not supported"; } 1; __END__;
stefanomarty/openxpki
core/server/OpenXPKI/Client/Session/Driver.pm
Perl
apache-2.0
2,429