code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
package State::Programming; use strict; use warnings; use Card; use Deck; use List::MoreUtils qw/false none/; use Storable 'dclone'; use State::Setup; use parent 'State'; sub on_enter { my ( $self, $game ) = @_; my $ready = 0; my $total = 0; delete $game->{public}{option}{'Recompile'}{tapped}; $game->{movement}->reset->shuffle; for my $p ( values %{ $game->{player} } ) { if ( $p->{public}{shutdown} ) { $p->{public}{damage} = 0; $total++; $ready++; } if ( $p->{public}{dead} || $p->{public}{shutdown} ) { $p->{public}{ready} = 1; $p->{private}{registers} = State::Setup::CLEAN; $p->send( { cmd => 'programming' } ); next; } $total++; $p->{public}{ready} = ''; my $cards = $p->{public}{memory} - $p->{public}{damage}; $cards++ if exists $p->{public}{options}{'Extra Memory'}; my $flywheel = $p->{public}{options}{'Flywheel'}; if ( defined $flywheel ) { $self->{flywheel} = delete $flywheel->{card}; } my $cnd_program = $p->{public}{options}{'Conditional Program'}; if ( defined $cnd_program ) { delete $cnd_program->{card}; } map { $_->{program} = [] unless $_ && $_->{locked} } @{ $p->{public}{registers} }; $self->give_cards( $game, $p, $cards ); if ( $p->{private}{cards}->count < 2 && !exists $p->{public}{options}{'Recompile'} ) { $p->{public}{ready} = 1; $game->broadcast( ready => { player => $p->{id} } ); $ready++; } } if ( $game->ready ) { $game->set_state('ANNOUNCE'); } elsif ( $ready && $game->{opts}{timer} eq '1st+30s' ) { $game->timer( 30, \&Game::set_state, $game, 'ANNOUNCE' ); } elsif ( $ready == $total - 1 && $game->{opts}{timer} eq 'standard' ) { $game->timer( 30, \&Game::set_state, $game, 'ANNOUNCE' ); } elsif ( $game->{opts}{timer} eq '30s' ) { $game->timer( 30, \&Game::set_state, $game, 'ANNOUNCE' ); } elsif ( $game->{opts}{timer} eq '1m' ) { $game->timer( 60, \&Game::set_state, $game, 'ANNOUNCE' ); } } sub give_cards { my ( $self, $game, $p, $cards ) = @_; $p->{private}{cards} = Deck->new( $game->{movement}->deal($cards) ); if ( defined $self->{flywheel} && defined $p->{public}{options}{'Flywheel'} ) { $p->{private}{cards}->add( $self->{flywheel} ); } $p->{private}{registers} = [ map { dclone($_) } @{ $p->{public}{registers} } ]; $p->send( { cmd => 'programming', cards => $p->{private}{cards}, registers => $p->{private}{registers}, } ); } sub do_program { my ( $self, $game, $c, $msg ) = @_; if ( $c->{public}{ready} ) { $c->err('Registers are already programmed'); return; } if ( ref( $msg->{registers} ) ne 'ARRAY' || @{ $msg->{registers} } > 5 ) { $c->err("Invalid program"); return; } my @cards; for my $i ( 0 .. $#{ $msg->{registers} } ) { my $r = $msg->{registers}[$i]; if ( ref($r) ne 'ARRAY' || locked_but_not_matching( $i, $r, $c->{public}{registers} ) || ( @$r > 1 && invalid_combo( $r, $c ) ) ) { $c->err("Invalid program"); return; } push @cards, @$r unless $c->{public}{registers}[$i]{locked}; } if ( too_many_doubles( $msg->{registers}, $c ) ) { $c->err("Invalid program"); return; } for my $card (@cards) { unless ( $c->{private}{cards}->contains($card) ) { $c->err("Invalid card"); return; } } my %id; for my $card (@cards) { my $ref = ref($card); if ( ( $ref ne 'HASH' && $ref ne 'Card' ) || exists $id{ $card->{priority} } ) { $c->err("Invalid program"); return; } $id{ $card->{priority} } = (); } for my $i ( 0 .. 4 ) { my $r = $c->{private}{registers}[$i]; next if $r->{locked}; if ( defined $msg->{registers}[$i] ) { $r->{program} = $msg->{registers}[$i]; } else { $r->{program} = []; } } $c->send( program => { registers => $c->{private}{registers} } ); } sub do_recompile { my ( $self, $game, $c, $msg ) = @_; if ( $c->{public}{ready} ) { $c->err('Registers are already programmed'); return; } my $recompile = $c->{public}{options}{'Recompile'}; unless ( defined $recompile ) { $c->err('Invalid Option'); return; } if ( $recompile->{tapped} ) { $c->err('Already recompiled'); return; } $recompile->{tapped} = $c->{id}; my $cards = $c->{public}{memory} - $c->{public}{damage}; $cards++ if exists $c->{public}{options}{'Extra Memory'}; $self->give_cards( $game, $c, $cards ); $game->broadcast( { cmd => 'option', player => $c->{id}, option => $recompile } ); } sub too_many_doubles { my ( $program, $player ) = @_; my ( $used, $needed ) = ( 0, 0 ); my $registers = $player->{public}{registers}; for my $i ( 0 .. 4 ) { next if $registers->[$i]{locked}; if ( $program->[$i] ) { $used += @{ $program->[$i] }; } else { $needed++; } } my $have = $player->{private}{cards}->count; return $player->{private}{cards}->count - $used < $needed; } sub invalid_combo { my ( $register, $player ) = @_; my ( $move, $rot ) = map { $_->{name} } @$register; if ( exists $player->{public}{options}{'Crab Legs'} ) { if ( $move eq '1' ) { return none { $_ eq $rot } qw/r l/; } } if ( exists $player->{public}{options}{'Dual Processor'} ) { if ( $move eq '2' ) { return none { $_ eq $rot } qw/r l/; } if ( $move eq '3' ) { return none { $_ eq $rot } qw/r l u/; } } return 1; } sub do_ready { my ( $self, $game, $c, $msg ) = @_; if ( false { @{ $_->{program} } } @{ $c->{private}{registers} } ) { $c->err('Programming incomplete'); return; } $c->{public}{ready} = 1; $game->broadcast( ready => { player => $c->{id} } ); my $not_ready = false { $_->{public}{ready} } values %{ $game->{player} }; if ( $not_ready == 0 ) { $game->set_state('ANNOUNCE'); return; } return if $game->{timer}; if ( $game->{opts}{timer} eq '1st+30s' || $not_ready == 1 ) { $game->timer( 30, \&Game::set_state, $game, 'ANNOUNCE' ); } } sub locked_but_not_matching { my ( $i, $cards, $registers ) = @_; return unless $registers->[$i]{locked}; my $locked = $registers->[$i]{program}; return 1 unless @$cards == @$locked; for my $j ( 0 .. $#$cards ) { return 1 unless $cards->[$j]{priority} == $locked->[$j]{priority}; } return; } sub on_exit { my ( $self, $game ) = @_; for my $p ( values %{ $game->{player} } ) { my $cards = $p->{private}{cards}; my $registers = delete $p->{private}{registers}; for my $r (@$registers) { map { $cards->remove($_) } @{ $r->{program} } if !$r->{locked}; } if ( $p->{public}{ready} ) { $p->{public}{registers} = $registers; } else { $cards->shuffle; for my $i ( 0 .. 4 ) { my $r = $registers->[$i]; $r->{program}[0] = $cards->deal unless @{ $r->{program} }; $p->{public}{registers}[$i]{program} = $r->{program}; } } } } 1;
bpa/cyborg-rally
lib/State/Programming.pm
Perl
mit
7,815
# # 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 storage::qnap::snmp::mode::components::psu; use strict; use warnings; my $map_status = { 0 => 'ok', -1 => 'fail' }; my $mapping = { ex => { status => { oid => '.1.3.6.1.4.1.24681.1.4.1.1.1.1.3.2.1.4', map => $map_status }, # systemPowerStatus speed => { oid => '.1.3.6.1.4.1.24681.1.4.1.1.1.1.3.2.1.5' }, # systemPowerFanSpeed temperature => { oid => '.1.3.6.1.4.1.24681.1.4.1.1.1.1.3.2.1.6' } # systemPowerTemp }, es => { status => { oid => '.1.3.6.1.4.1.24681.2.2.21.1.4' }, # es-SysPowerStatus speed => { oid => '.1.3.6.1.4.1.24681.2.2.21.1.5' }, # es-SysPowerFanSpeed temperature => { oid => '.1.3.6.1.4.1.24681.2.2.21.1.6' } # es-SysPowerTemp } }; sub load {} sub check_psu_result { my ($self, %options) = @_; foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$options{snmp_result}})) { next if ($oid !~ /^$mapping->{ $options{type} }->{status}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping->{ $options{type} }, results => $options{snmp_result}, instance => $instance); next if ($self->check_filter(section => 'psu', instance => $instance)); $self->{components}->{psu}->{total}++; $self->{output}->output_add( long_msg => sprintf( "power supply '%s' status is '%s' [instance: %s, fan speed: %s, temperature: %s]", $instance, $result->{status}, $instance, $result->{speed}, $result->{temperature} ) ); my $exit = $self->get_severity(section => 'psu', value => $result->{status}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf( "Power supply '%s' status is '%s'", $instance, $result->{status} ) ); } if ($result->{speed} !~ /[0-9]/) { my ($exit2, $warn, $crit) = $self->get_severity_numeric(section => 'psu.fanspeed', instance => $instance, value => $result->{speed}); if (!$self->{output}->is_status(value => $exit2, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf( "Power supply '%s' fan speed is %s rpm", $instance, $result->{speed} ) ); } $self->{output}->perfdata_add( nlabel => 'hardware.powersupply.fan.speed.rpm', unit => 'rpm', instances => $instance, value => $result->{speed}, min => 0 ); } if ($result->{temperature} =~ /[0-9]/) { my ($exit2, $warn, $crit) = $self->get_severity_numeric(section => 'psu.temperature', instance => $instance, value => $result->{temperature}); if (!$self->{output}->is_status(value => $exit2, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf( "Power supply '%s' temperature is %s C", $instance, $result->{temperature} ) ); } $self->{output}->perfdata_add( nlabel => 'hardware.powersupply.temperature.celsius', unit => 'C', instances => $instance, value => $result->{temperature} ); } } } sub check_psu_qts { my ($self, %options) = @_; my $oid_sysPowerStatus = '.1.3.6.1.4.1.55062.1.12.19.0'; my $snmp_result = $self->{snmp}->get_leef( oids => [$oid_sysPowerStatus] ); return if (!defined($snmp_result->{$oid_sysPowerStatus})); my $instance = 1; my $status = $map_status->{ $snmp_result->{$oid_sysPowerStatus} }; return if ($self->check_filter(section => 'psu', instance => $instance)); $self->{components}->{psu}->{total}++; $self->{output}->output_add( long_msg => sprintf( "system power supply status is '%s' [instance: %s]", $status, $instance ) ); my $exit = $self->get_severity(section => 'psu', value => $status); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf( "Sytem power supply status is '%s'", $status ) ); } } sub check_psu_es { my ($self, %options) = @_; my $snmp_result = $self->{snmp}->get_table( oid => '.1.3.6.1.4.1.24681.2.2.21', # es-SystemPowerTable start => $mapping->{es}->{status}->{oid} ); check_psu_result($self, type => 'es', snmp_result => $snmp_result); } sub check_psu_ex { my ($self, %options) = @_; my $snmp_result = $self->{snmp}->get_table( oid => '.1.3.6.1.4.1.24681.1.4.1.1.1.1.3.2', # systemPowerTable start => $mapping->{ex}->{status}->{oid} ); check_psu_result($self, type => 'ex', snmp_result => $snmp_result); } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking power supplies"); $self->{components}->{psu} = { name => 'psu', total => 0, skip => 0 }; return if ($self->check_filter(section => 'psu')); if ($self->{is_qts} == 1) { check_psu_qts($self); } elsif ($self->{is_es} == 1) { check_psu_es($self); } else { check_psu_ex($self); } } 1;
Tpo76/centreon-plugins
storage/qnap/snmp/mode/components/psu.pm
Perl
apache-2.0
6,479
# # (c) Jan Gehring <jan.gehring@gmail.com> # # vim: set ts=2 sw=2 tw=0: # vim: set expandtab: package Rex::Repositorio::Server::Yum; use Mojo::Base 'Mojolicious'; use Data::Dumper; use JSON::XS; use File::Spec; use Params::Validate qw(:all); use File::Basename 'dirname'; use File::Spec::Functions 'catdir'; our $VERSION = '0.4.1'; # VERSION # This method will run once at server start sub startup { my $self = shift; $self->plugin("Rex::Repositorio::Server::Helper::Common"); $self->app->log( Mojo::Log->new( level => 'debug', ) ); $self->plugin("Rex::Repositorio::Server::Helper::RenderFile"); my $r = $self->routes; $r->get('/')->to('file#index'); $r->get('/:tag')->to('file#index'); $r->get('/:tag/:repo/errata')->to('errata#query'); $r->get('/*')->to('file#serve'); # Switch to installable home directory $self->home->parse( catdir( dirname(__FILE__), 'Yum' ) ); # Switch to installable "public" directory $self->static->paths->[0] = $self->home->rel_dir('public'); # Switch to installable "templates" directory $self->renderer->paths->[0] = $self->home->rel_dir('templates'); } 1;
gitpan/Rex-Repositorio
lib/Rex/Repositorio/Server/Yum.pm
Perl
apache-2.0
1,146
#!/usr/bin/perl -- #!/usr/bin/perl -- use strict; use warnings; use autodie qw/ chdir /; use Data::Dump qw/ dd pp /; use Path::Tiny qw/ path /; require 'ppixregexplain.pl'; my $here = path( __FILE__ )->realpath->parent; chdir $here; my $outfh = path( 'Tools.pm.html' )->openw_raw; select $outfh; my $re = path( 'Tools.pm' )->slurp_raw; MainXplain( '--html', $re ); __END__
mishin/presentation
test_re.pl
Perl
apache-2.0
374
#!/usr/bin/env perl # Copyright 2005,2006 WSO2, Inc. http://wso2.com # # 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 use WSO2::WSF; # This assumes you have installed WSF/PHP and all the samples can be accessed from # http://localhost/samples my $payload =<<E; <ns1:echo xmlns:ns1="http://php.axis2.org/samples"><text>Hello World!</text></ns1:echo> E open MYC, "< ../keys/alice_cert.cert"; undef $/; my $mycert = <MYC>; open MYK, "< ../keys/alice_key.pem"; undef $/; my $mykey = <MYK>; open REC, "< ../keys/bob_cert.cert"; undef $/; my $reccert = <REC>; my $msg = new WSO2::WSF::WSMessage( { 'to' => 'http://localhost/samples/security/complete/service.php', 'action' => 'http://php.axis2.org/samples/echoString', 'payload' => $payload } ); open XML, "< policy.xml"; undef $/; my $policy_xml = <XML>; my $policy = new WSO2::WSF::WSPolicy($policy_xml); my $sec_token = new WSO2::WSF::WSSecurityToken( { 'privateKey' => $mykey, 'certificate' => $mycert, 'receiverCertificate' => $reccert } ); my $client = new WSO2::WSF::WSClient( { 'useWSA' => 'TRUE', 'useSOAP' => '1.1', 'policy' => $policy, 'securityToken' => $sec_token } ); my $res_msg = $client->request( $msg ); print $res_msg->{str};
gitpan/WSO2-WSF-Perl
samples/security/complete/complete_sec_client.pl
Perl
apache-2.0
1,768
package Paws::CodeBuild::Tag; use Moose; has Key => (is => 'ro', isa => 'Str', request_name => 'key', traits => ['NameInRequest']); has Value => (is => 'ro', isa => 'Str', request_name => 'value', traits => ['NameInRequest']); 1; ### main pod documentation begin ### =head1 NAME Paws::CodeBuild::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::CodeBuild::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::CodeBuild::Tag object: $result = $service_obj->Method(...); $result->Att1->Key =head1 DESCRIPTION A tag, consisting of a key and a value. This tag is available for use by AWS services that support tags in AWS CodeBuild. =head1 ATTRIBUTES =head2 Key => Str The tag's key. =head2 Value => Str The tag's value. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CodeBuild> =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/CodeBuild/Tag.pm
Perl
apache-2.0
1,472
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V9::Services::CustomConversionGoalService; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseService); sub mutate { my $self = shift; my $request_body = shift; my $http_method = 'POST'; my $request_path = 'v9/customers/{+customerId}/customConversionGoals:mutate'; my $response_type = 'Google::Ads::GoogleAds::V9::Services::CustomConversionGoalService::MutateCustomConversionGoalsResponse'; return $self->SUPER::call($http_method, $request_path, $request_body, $response_type); } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Services/CustomConversionGoalService.pm
Perl
apache-2.0
1,135
package Google::Ads::AdWords::v201809::ConstantOperand::Unit; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809'}; # 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 ConstantOperand.Unit from the namespace https://adwords.google.com/api/adwords/cm/v201809. The units of constant operands, if applicable. 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
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/ConstantOperand/Unit.pm
Perl
apache-2.0
1,126
=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 package XrefParser::HGNCParser; use strict; use warnings; use File::Basename; use Carp; use base qw( XrefParser::BaseParser ); sub run { my ($self, $ref_arg) = @_; my $source_id = $ref_arg->{source_id}; my $species_id = $ref_arg->{species_id}; my $files = $ref_arg->{files}; my $verbose = $ref_arg->{verbose}; if((!defined $source_id) or (!defined $species_id) or (!defined $files) ){ croak "Need to pass source_id, species_id, files and rel_file as pairs"; } $verbose |=0; my $empty = q{}; my $file = @{$files}[0]; my (%swissprot) = %{$self->get_valid_codes('Uniprot/SWISSPROT',$species_id)}; my (%refseq) = %{$self->get_valid_codes('refseq',$species_id)}; my @list; push @list, 'refseq_peptide'; push @list, 'refseq_mRNA'; my (%entrezgene) = %{$self->get_valid_xrefs_for_dependencies('EntrezGene',@list)}; my %name_count; my $mismatch = 0; my $hugo_io = $self->get_filehandle($file); if ( !defined $hugo_io ) { print "ERROR: Can't open HGNC file $file\n"; return 1; } my $name_to_source_id = $self->get_hgnc_sources(); # Skip header $hugo_io->getline(); while ( $_ = $hugo_io->getline() ) { chomp; my @array = split /\t/x, $_; my $seen = 0; my $acc = $array[0]; my $symbol = $array[1]; my $name = $array[2]; my $previous_symbols = $array[3]; my $synonyms = $array[4]; my $type = 'lrg'; my $id = $array[11]; my $source_id = $name_to_source_id->{$type}; if($id and $id =~ m/http:\/\/www.lrg-sequence.org\/LRG\/(LRG_\d+)/x){ my $lrg_stable_id = $1; $self->add_to_direct_xrefs({ stable_id => $lrg_stable_id, type => 'gene', acc => $acc, label => $symbol, desc => $name, source_id => $source_id, species_id => $species_id} ); $self->add_synonyms_for_hgnc( {source_id => $source_id, name => $acc, species_id => $species_id, dead => $previous_symbols, alias => $synonyms} ); $name_count{$type}++; } # # Direct Ensembl mappings # $type = 'ensembl_manual'; $id = $array[9]; $source_id = $name_to_source_id->{$type}; if ($id){ # Ensembl direct xref $seen = 1; $name_count{$type}++; $self->add_to_direct_xrefs({ stable_id => $id, type => 'gene', acc => $acc, label => $symbol, desc => $name,, source_id => $source_id, species_id => $species_id} ); $self->add_synonyms_for_hgnc( {source_id => $source_id, name => $acc, species_id => $species_id, dead => $previous_symbols, alias => $synonyms}); } # # RefSeq # $type = 'refseq_mapped'; $id = $array[8]; $source_id = $name_to_source_id->{$type}; if ($id) { if(defined $refseq{$id} ){ $seen = 1; foreach my $xref_id (@{$refseq{$id}}){ $name_count{$type}++; $self->add_dependent_xref({ master_xref_id => $xref_id, acc => $acc, label => $symbol, desc => $name || '', source_id => $source_id, species_id => $species_id} ); } $self->add_synonyms_for_hgnc( {source_id => $source_id, name => $acc, species_id => $species_id, dead => $previous_symbols, alias => $synonyms}); } } $type = 'refseq_manual'; $id = $array[6]; $source_id = $name_to_source_id->{$type}; if ($id) { if(defined $refseq{$id} ){ $seen = 1; foreach my $xref_id (@{$refseq{$id}}){ $name_count{$type}++; $self->add_dependent_xref({ master_xref_id => $xref_id, acc => $acc, label => $symbol, desc => $name || '', source_id => $source_id, species_id => $species_id} ); } $self->add_synonyms_for_hgnc( {source_id => $source_id, name => $acc, species_id => $species_id, dead => $previous_symbols, alias => $synonyms}); } } # # Swissprot # Skip, Uniprot is protein-centric # $type = 'swissprot_manual'; # # EntrezGene # $type = 'entrezgene_manual'; $id = $array[5]; $source_id = $name_to_source_id->{$type}; if(defined $id ){ if(defined $entrezgene{$id} ){ $seen = 1; $self->add_dependent_xref({ master_xref_id => $entrezgene{$id}, acc => $acc, label => $symbol, desc => $name || '', source_id => $source_id, species_id => $species_id} ); $name_count{$type}++; $self->add_synonyms_for_hgnc( {source_id => $source_id, name => $acc, species_id => $species_id, dead => $previous_symbols, alias => $synonyms}); } } $type = 'entrezgene_mapped'; $id = $array[7]; if(defined $id ){ if(defined $entrezgene{$id} ){ $seen = 1; $self->add_dependent_xref({ master_xref_id => $entrezgene{$id}, acc => $acc, label => $symbol, desc => $name || '', source_id => $source_id, species_id => $species_id} ); $name_count{$type}++; $self->add_synonyms_for_hgnc( {source_id => $source_id, name => $acc, species_id => $species_id, dead => $previous_symbols, alias => $synonyms}); } } if(!$seen){ # Store to keep descriptions etc $type = 'desc_only'; $source_id = $name_to_source_id->{$type}; $self->add_xref({ acc => $acc, label => $symbol, desc => $name, source_id => $source_id, species_id => $species_id, info_type => "MISC"} ); $self->add_synonyms_for_hgnc( {source_id => $source_id, name => $acc, species_id => $species_id, dead => $previous_symbols, alias => $synonyms}); $mismatch++; } } $hugo_io->close(); if($verbose){ print 'Loaded a total of :-'; foreach my $type (keys %name_count){ print "\t".$type."\t".$name_count{$type}."\n"; } print "$mismatch xrefs could not be associated via RefSeq, EntrezGene or ensembl\n"; } return 0; # successful } sub get_hgnc_sources { my $self = shift; my %name_to_source_id; my @sources = ('entrezgene_manual', 'refseq_manual', 'entrezgene_mapped', 'refseq_mapped', 'ensembl_manual', 'swissprot_manual', 'desc_only'); foreach my $key (@sources) { my $source_id = $self->get_source_id_for_source_name('HGNC', $key); if(!(defined $source_id)){ die 'Could not get source id for HGNC and '. $key ."\n"; } $name_to_source_id{ $key } = $source_id; } my $source_id = $self->get_source_id_for_source_name('LRG_HGNC_notransfer'); if(!(defined $source_id) ){ die 'Could not get source id for LRG_HGNC_notransfer\n'; } $name_to_source_id{'lrg'} = $source_id; return \%name_to_source_id; } sub add_synonyms_for_hgnc{ my ($self, $ref_arg) = @_; my $source_id = $ref_arg->{source_id}; my $name = $ref_arg->{name}; my $species_id = $ref_arg->{species_id}; my $dead_name = $ref_arg->{dead}; my $alias = $ref_arg->{alias}; if (defined $dead_name ) { # dead name, add to synonym my @array2 = split ',\s*', $dead_name ; foreach my $arr (@array2){ $self->add_to_syn($name, $source_id, $arr, $species_id); } } if (defined $alias ) { # alias, add to synonym my @array2 = split ',\s*', $alias; foreach my $arr (@array2){ $self->add_to_syn($name, $source_id, $arr, $species_id); } } return; } 1;
mjg17/ensembl
misc-scripts/xref_mapping/XrefParser/HGNCParser.pm
Perl
apache-2.0
9,217
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package Bio::EnsEMBL::Production::Pipeline::ProteinFeatures::StoreGoXrefs; use strict; use warnings; use base ('Bio::EnsEMBL::Production::Pipeline::Common::Base'); use Bio::EnsEMBL::OntologyXref; sub run { my ($self) = @_; my $logic_name = $self->param_required('logic_name'); $self->hive_dbc()->disconnect_if_idle(); my $aa = $self->core_dba->get_adaptor('Analysis'); my $dbea = $self->core_dba->get_adaptor('DBEntry'); my $analysis = $aa->fetch_by_logic_name($logic_name); my $go = $self->parse_interpro2go(); $self->store_go_xref($dbea, $analysis, $go); $self->core_dbc()->disconnect_if_idle(); } sub parse_interpro2go { my ($self) = @_; my $interpro2go_file = $self->param_required('interpro2go_file'); my $interpro_sql = 'SELECT DISTINCT interpro_ac FROM interpro;'; my $accessions = $self->core_dbh->selectcol_arrayref($interpro_sql); my %accessions = map { $_ => 1} @$accessions; open (my $fh, '<', $interpro2go_file) or die "Failed to open $interpro2go_file: $!\n"; my %go; while (my $line = <$fh>) { next if ($line !~ /^InterPro/); my ($interpro_ac, $go_desc, $go_term) = $line =~ /^InterPro:(\S+).+\s+\>\s+GO:(.+)\s+;\s+(GO:\d+)/; if (exists $accessions{$interpro_ac}) { push @{$go{$interpro_ac}}, [$go_term, $go_desc]; } } close $fh; return \%go; } sub store_go_xref { my ($self, $dbea, $analysis, $go) = @_; my $sql = qq/ SELECT DISTINCT interpro_ac, transcript_id FROM interpro INNER JOIN protein_feature ON id = hit_name INNER JOIN translation USING (translation_id) /; my $sth = $self->core_dbh->prepare($sql); $sth->execute(); while (my $row = $sth->fetchrow_arrayref()) { my ($interpro_ac, $transcript_id) = @$row; if (exists $$go{$interpro_ac}) { my $interpro_xref = $self->get_interpro_xref($dbea, $interpro_ac); foreach my $go (@{$$go{$interpro_ac}}) { my %go_xref_args = ( -dbname => 'GO', -primary_id => $$go[0], -display_id => $$go[0], -description => $$go[1], -info_type => 'DEPENDENT', -analysis => $analysis, ); my $go_xref = Bio::EnsEMBL::OntologyXref->new(%go_xref_args); $go_xref->add_linkage_type('IEA', $interpro_xref); $go_xref->{version} = undef; $dbea->store($go_xref, $transcript_id, 'Transcript', 1); } } } } sub get_interpro_xref { my ($self, $dbea, $interpro_ac) = @_; my $interpro_xref = $self->{interpro}->{$interpro_ac}; if(!defined $interpro_xref) { $interpro_xref = $dbea->fetch_by_db_accession('Interpro', $interpro_ac); $self->{interpro}->{$interpro_ac} = $interpro_xref; } return $interpro_xref; } 1;
Ensembl/ensembl-production
modules/Bio/EnsEMBL/Production/Pipeline/ProteinFeatures/StoreGoXrefs.pm
Perl
apache-2.0
3,506
use 5.10.0; use strict; use warnings; use lib '../'; # Takes a CADD file and makes it into a bed-like file, retaining the property # That each base has 3 (or 4 for ambiguous) lines package Utils::CaddToBed; our $VERSION = '0.001'; use Mouse 2; use namespace::autoclean; use Path::Tiny qw/path/; use Seq::Tracks::Build::LocalFilesPaths; # # _localFilesDir, _decodedConfig, compress, _wantedTrack, _setConfig, and logPath extends 'Utils::Base'; # ########## Arguments accepted ############## # Expects tab delimited file; not allowing to be set because it probably won't ever be anything # other than tab, and because split('\'t') is faster # has delimiter => (is => 'ro', lazy => 1, default => "\t"); sub BUILD { my $self = shift; my $localFilesHandler = Seq::Tracks::Build::LocalFilesPaths->new(); my $localFilesAref = $localFilesHandler->makeAbsolutePaths($self->_decodedConfig->{files_dir}, $self->_wantedTrack->{name}, $self->_wantedTrack->{local_files}); if (@$localFilesAref != 1) { $self->log('fatal', "Expect a single cadd file, found " . (scalar @$localFilesAref) ); } $self->{_localFile} = $localFilesAref->[0]; } # TODO: error check opening of file handles, write tests sub go { my $self = shift; my %wantedChrs = map { $_ => 1 } @{ $self->_decodedConfig->{chromosomes} }; my $inFilePath = $self->{_localFile}; if(! -e $inFilePath) { $self->log('fatal', "input file path $inFilePath doesn't exist"); return; } # Store output handles by chromosome, so we can write even if input file # out of order my %outFhs; my %skippedBecauseExists; # We'll update this list of files in the config file $self->_wantedTrack->{local_files} = []; my $inFh = $self->get_read_fh($inFilePath); $self->log('info', "Reading $inFilePath"); my $versionLine = <$inFh>; chomp $versionLine; $self->log('info', "Cadd version line: $versionLine"); my $headerLine = <$inFh>; chomp $headerLine; $self->log('info', "Cadd header line: $headerLine"); my @headerFields = split('\t', $headerLine); # CADD seems to be 1-based, this is not documented however. my $based = 1; my $outPathBase = path($inFilePath)->basename(); my $outExt = 'bed' . ( $self->compress ? '.gz' : substr($outPathBase, rindex($outPathBase, '.') ) ); $outPathBase = substr($outPathBase , 0, rindex($outPathBase , '.') ); my $outPath = path($self->_localFilesDir)->child("$outPathBase.$outExt")->stringify(); if(-e $outPath && !$self->overwrite) { $self->log('fatal', "File $outPath exists, and overwrite is not set"); return; } my $outFh = $self->get_write_fh($outPath); $self->log('info', "Writing to $outPath"); say $outFh $versionLine; say $outFh join("\t", 'chrom', 'chromStart', 'chromEnd', @headerFields[2 .. $#headerFields]); while(my $l = $inFh->getline() ) { chomp $l; my @line = split('\t', $l); # The part that actually has the id, ex: in chrX "X" is the id my $chrIdPart; # Get the chromosome # It could be stored as a number/single character or "chr" # Grab the chr part, and normalize it to our case format (chr) if($line[0] =~ /chr/i) { $chrIdPart = substr($line[0], 3); } else { $chrIdPart = $line[0]; } # Don't forget to convert NCBI to UCSC-style mitochondral chr name if($chrIdPart eq 'MT') { $chrIdPart = 'M'; } my $chr = "chr$chrIdPart"; if(!exists $wantedChrs{$chr}) { $self->log('warn', "Chromosome $chr not recognized (from $chrIdPart), skipping: $l"); next; } my $start = $line[1] - $based; my $end = $start + 1; say $outFh join("\t", $chr, $start, $end, @line[2 .. $#line]); } $self->_wantedTrack->{local_files} = [$outPath]; $self->_wantedTrack->{caddToBed_date} = $self->_dateOfRun; $self->_backupAndWriteConfig(); } __PACKAGE__->meta->make_immutable; 1;
wingolab-org/seq2-annotator
lib/Utils/CaddToBed.pm
Perl
apache-2.0
3,893
=pod =head1 NAME MD2, MD4, MD5, MD2_Init, MD2_Update, MD2_Final, MD4_Init, MD4_Update, MD4_Final, MD5_Init, MD5_Update, MD5_Final - MD2, MD4, and MD5 hash functions =head1 SYNOPSIS #include <openssl/md2.h> The following functions have been deprecated since OpenSSL 3.0, and can be hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value, see L<openssl_user_macros(7)>: unsigned char *MD2(const unsigned char *d, unsigned long n, unsigned char *md); int MD2_Init(MD2_CTX *c); int MD2_Update(MD2_CTX *c, const unsigned char *data, unsigned long len); int MD2_Final(unsigned char *md, MD2_CTX *c); #include <openssl/md4.h> The following functions have been deprecated since OpenSSL 3.0, and can be hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value, see L<openssl_user_macros(7)>: unsigned char *MD4(const unsigned char *d, unsigned long n, unsigned char *md); int MD4_Init(MD4_CTX *c); int MD4_Update(MD4_CTX *c, const void *data, unsigned long len); int MD4_Final(unsigned char *md, MD4_CTX *c); #include <openssl/md5.h> The following functions have been deprecated since OpenSSL 3.0, and can be hidden entirely by defining B<OPENSSL_API_COMPAT> with a suitable version value, see L<openssl_user_macros(7)>: unsigned char *MD5(const unsigned char *d, unsigned long n, unsigned char *md); int MD5_Init(MD5_CTX *c); int MD5_Update(MD5_CTX *c, const void *data, unsigned long len); int MD5_Final(unsigned char *md, MD5_CTX *c); =head1 DESCRIPTION All of the functions described on this page are deprecated. Applications should instead use L<EVP_DigestInit_ex(3)>, L<EVP_DigestUpdate(3)> and L<EVP_DigestFinal_ex(3)>. MD2, MD4, and MD5 are cryptographic hash functions with a 128 bit output. MD2(), MD4(), and MD5() compute the MD2, MD4, and MD5 message digest of the B<n> bytes at B<d> and place it in B<md> (which must have space for MD2_DIGEST_LENGTH == MD4_DIGEST_LENGTH == MD5_DIGEST_LENGTH == 16 bytes of output). If B<md> is NULL, the digest is placed in a static array. The following functions may be used if the message is not completely stored in memory: MD2_Init() initializes a B<MD2_CTX> structure. MD2_Update() can be called repeatedly with chunks of the message to be hashed (B<len> bytes at B<data>). MD2_Final() places the message digest in B<md>, which must have space for MD2_DIGEST_LENGTH == 16 bytes of output, and erases the B<MD2_CTX>. MD4_Init(), MD4_Update(), MD4_Final(), MD5_Init(), MD5_Update(), and MD5_Final() are analogous using an B<MD4_CTX> and B<MD5_CTX> structure. Applications should use the higher level functions L<EVP_DigestInit(3)> etc. instead of calling the hash functions directly. =head1 NOTE MD2, MD4, and MD5 are recommended only for compatibility with existing applications. In new applications, SHA-1 or RIPEMD-160 should be preferred. =head1 RETURN VALUES MD2(), MD4(), and MD5() return pointers to the hash value. MD2_Init(), MD2_Update(), MD2_Final(), MD4_Init(), MD4_Update(), MD4_Final(), MD5_Init(), MD5_Update(), and MD5_Final() return 1 for success, 0 otherwise. =head1 CONFORMING TO RFC 1319, RFC 1320, RFC 1321 =head1 SEE ALSO L<EVP_DigestInit(3)> =head1 HISTORY All of these functions were deprecated in OpenSSL 3.0. =head1 COPYRIGHT Copyright 2000-2020 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
openssl/openssl
doc/man3/MD5.pod
Perl
apache-2.0
3,618
# # 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::throughput; use base qw(cloud::azure::custom::mode); use strict; use warnings; sub get_metrics_mapping { my ($self, %options) = @_; my $metrics_mapping = { 'throughput' => { 'output' => 'Throughput', 'label' => 'throughput', 'nlabel' => 'appgateway.throughput.bytespersecond', 'unit' => 'B/s', '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 throughput statistics. Example: Using resource name : perl centreon_plugins.pl --plugin=cloud::azure::network::appgateway::plugin --mode=throughput --custommode=api --resource=<appgateway_id> --resource-group=<resourcegroup_id> --aggregation='average' --warning-throughput='1000' --critical-throughput='2000' Using resource id : perl centreon_plugins.pl --plugin=cloud::azure::integration::servicebus::plugin --mode=throughput --custommode=api --resource='/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_id>/providers/Microsoft.Network/applicationGateways/<appgateway_id>' --aggregation='average' --warning-throughput='1000' --critical-throughput='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-throughput> Warning threshold. =item B<--critical-throughput> Critical threshold. =back =cut
centreon/centreon-plugins
cloud/azure/network/appgateway/mode/throughput.pm
Perl
apache-2.0
4,596
:- use_package(library('dclp/and')). :- use_module(library(prolog_sys), [statistics/2]). main(X,Y) :- store([X], 1), store([Y], 2), (X in 1..2, X .>. Y) @ 1, (Y in 1..2, X .<>. Y) @ 2, d_labeling([X,Y]).
leuschel/ecce
www/CiaoDE/ciao/library/dclp/and/benchmarks/benchmark15.pl
Perl
apache-2.0
214
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater; =pod =head1 NAME Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater =head1 SYNOPSIS This runnable can be used both as a Hive pipeline component or run in standalone mode. At the moment Compara runs it standalone, EnsEMBL Genomes runs it in both modes. In standalone mode you will need to set --reg_conf to your registry configuration file in order to access the core databases. You will have to refer to your compara database either via the full URL or (if you have a corresponding registry entry) via registry. Here are both examples: standaloneJob.pl Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater --reg_conf $ENSEMBL_CVS_ROOT_DIR/ensembl-compara/scripts/pipeline/production_reg_conf.pl --compara_db compara_homology_merged --debug 1 standaloneJob.pl Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater --reg_conf $ENSEMBL_CVS_ROOT_DIR/ensembl-compara/scripts/pipeline/production_reg_conf.pl --compara_db mysql://ensadmin:${ENSADMIN_PSW}@compara3:3306/lg4_compara_homology_merged_64 --debug 1 You should be able to limit the set of species being updated by adding --species "[ 90, 3 ]" or --species "[ 'human', 'rat' ]" =head1 DESCRIPTION The module loops through all genome_dbs given via the parameter C<species> and attempts to update any gene/translation with the display identifier from the core database. If the list of genome_dbs is not specified, it will attempt all genome_dbs with entries in the member table. This code uses direct SQL statements because of the relationship between translations and their display labels being stored at the transcript level. If the DB changes this will break. =head1 AUTHOR Andy Yates =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ =cut use strict; use warnings; use Scalar::Util qw(looks_like_number); use Bio::EnsEMBL::Utils::SqlHelper; use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable'); sub param_defaults { return { 'mode' => 'display_label', # one of 'display_label', 'description' }; } # # Hash containing the description of the possible modes # A mode entry must contain the following keys: # - perl_attr: perl method to get the value from a Member # - sql_column: column in the member table # - sql_lookups: SQLs to get the values from a core database # my $modes = { 'display_label' => { 'perl_attr' => 'display_label', 'sql_column' => 'display_label', 'sql_lookups' => { 'ENSEMBLGENE' => q{select g.stable_id, x.display_label FROM gene g join xref x on (g.display_xref_id = x.xref_id) join seq_region sr on (g.seq_region_id = sr.seq_region_id) join coord_system cs using (coord_system_id) where cs.species_id =?}, 'ENSEMBLPEP' => q{select tr.stable_id, x.display_label FROM translation tr join transcript t using (transcript_id) join xref x on (t.display_xref_id = x.xref_id) join seq_region sr on (t.seq_region_id = sr.seq_region_id) join coord_system cs using (coord_system_id) where cs.species_id =?}, }, }, 'description' => { 'perl_attr' => 'description', 'sql_column' => 'description', 'sql_lookups' => { 'ENSEMBLGENE' => q{select g.stable_id, g.description FROM gene g join seq_region sr on (g.seq_region_id = sr.seq_region_id) join coord_system cs using (coord_system_id) where cs.species_id =?}, }, }, }; =head2 fetch_input Title : fetch_input Usage : $self->fetch_input Function: prepares global variables and DB connections Returns : none Args : none =cut sub fetch_input { my ($self) = @_; die $self->param('mode').' is not a valid mode. Valid modes are: '.join(', ', keys %$modes) unless exists $modes->{$self->param('mode')}; my $species_list = $self->param('species') || $self->param('genome_db_ids'); unless( $species_list ) { my $h = Bio::EnsEMBL::Utils::SqlHelper->new(-DB_CONNECTION => $self->compara_dba()->dbc()); my $sql = q{SELECT DISTINCT genome_db_id FROM member WHERE genome_db_id IS NOT NULL AND genome_db_id <> 0}; $species_list = $h->execute_simple( -SQL => $sql); } my $genome_db_adaptor = $self->compara_dba()->get_GenomeDBAdaptor(); my @genome_dbs = (); foreach my $species (@$species_list) { my $genome_db = ( looks_like_number( $species ) ? $genome_db_adaptor->fetch_by_dbID( $species ) : $genome_db_adaptor->fetch_by_registry_name( $species ) ) or die "Could not fetch genome_db object given '$species'"; push @genome_dbs, $genome_db; } $self->param('genome_dbs', \@genome_dbs); } =head2 run Title : run Usage : $self->run Function: Retrives the Members to update Returns : none Args : none =cut sub run { my ($self) = @_; my $genome_dbs = $self->param('genome_dbs'); if($self->debug()) { my $names = join(q{, }, map { $_->name() } @$genome_dbs); print "Working with: [${names}]\n"; } my $results = $self->param('results', {}); foreach my $genome_db (@$genome_dbs) { my $output = $self->_process_genome_db($genome_db); $results->{$genome_db->dbID()} = $output; } } =head2 write_output Title : write_output Usage : $self->write_output Function: Writes the display labels/members back to the Compara DB Returns : none Args : none =cut sub write_output { my ($self) = @_; my $genome_dbs = $self->param('genome_dbs'); foreach my $genome_db (@$genome_dbs) { $self->_update_field($genome_db); } } #--- Generic Logic sub _process_genome_db { my ($self, $genome_db) = @_; my $name = $genome_db->name(); my $replace = $self->param('replace'); print "Processing ${name}\n" if $self->debug(); if(!$genome_db->db_adaptor()) { die 'Cannot get an adaptor for GenomeDB '.$name if $self->param('die_if_no_core_adaptor'); return; } my @members_to_update; my @sources = keys %{$modes->{$self->param('mode')}->{sql_lookups}}; foreach my $source_name (@sources) { print "Working with ${source_name}\n" if $self->debug(); if(!$self->_need_to_process_genome_db_source($genome_db, $source_name) && !$replace) { if($self->debug()) { print "No need to update as all members for ${name} and source ${source_name} have display labels\n"; } next; } my $results = $self->_process($genome_db, $source_name); push(@members_to_update, @{$results}); } return \@members_to_update; } sub _process { my ($self, $genome_db, $source_name) = @_; my @members_to_update; my $replace = $self->param('replace'); my $member_a = ($source_name eq 'ENSEMBLGENE') ? $self->compara_dba()->get_GeneMemberAdaptor() : $self->compara_dba()->get_SeqMemberAdaptor(); my $members = $member_a->fetch_all_by_source_genome_db_id($source_name, $genome_db->dbID()); if (scalar(@{$members})) { my $core_values = $self->_get_field_lookup($genome_db, $source_name); my $perl_attr = $modes->{$self->param('mode')}->{perl_attr}; foreach my $member (@{$members}) { #Skip if it's already got a value & we are not replacing things next if defined $member->$perl_attr() && !$replace; my $display_value = $core_values->{$member->stable_id}; push(@members_to_update, [$member->dbID, $display_value]); } } else { my $name = $genome_db->name(); print "No members found for ${name} and ${source_name}\n" if $self->debug(); } return \@members_to_update; } sub _need_to_process_genome_db_source { my ($self, $genome_db, $source_name) = @_; my $h = Bio::EnsEMBL::Utils::SqlHelper->new(-DB_CONNECTION => $self->compara_dba()->dbc()); my $sql = q{select count(*) from member where genome_db_id =? and source_name =?}; $sql .= sprintf("AND %s IS NULL", $modes->{$self->param('mode')}->{sql_column}); my $params = [$genome_db->dbID(), $source_name]; return $h->execute_single_result( -SQL => $sql, -PARAMS => $params); } # # Get the labels / descriptions as a hash for that species # sub _get_field_lookup { my ($self, $genome_db, $source_name) = @_; my $sql = $modes->{$self->param('mode')}->{sql_lookups}->{$source_name}; my $dba = $genome_db->db_adaptor(); my $h = Bio::EnsEMBL::Utils::SqlHelper->new(-DB_CONNECTION => $dba->dbc()); my $params = [$dba->species_id()]; my $hash = $h->execute_into_hash( -SQL => $sql, -PARAMS => $params ); return $hash; } # # Update the Compara db with the new labels / descriptions # sub _update_field { my ($self, $genome_db) = @_; my $name = $genome_db->name(); my $member_values = $self->param('results')->{$genome_db->dbID()}; if(! defined $member_values || scalar(@{$member_values}) == 0) { print "No members to write back for ${name}\n" if $self->debug(); return; } print "Writing members out for ${name}\n" if $self->debug(); my $total = 0; my $h = Bio::EnsEMBL::Utils::SqlHelper->new(-DB_CONNECTION => $self->compara_dba()->dbc()); my $sql_column = $modes->{$self->param('mode')}->{sql_column}; $h->transaction( -CALLBACK => sub { my $sql = "update member set $sql_column = ? where member_id =?"; $h->batch( -SQL => $sql, -CALLBACK => sub { my ($sth) = @_; foreach my $arr (@{$member_values}) { my $updated = $sth->execute($arr->[1], $arr->[0]); $total += $updated; } return; } ); }); print "Inserted ${total} member(s) for ${name}\n" if $self->debug(); return $total; } 1;
dbolser-ebi/ensembl-compara
modules/Bio/EnsEMBL/Compara/RunnableDB/MemberDisplayLabelUpdater.pm
Perl
apache-2.0
10,313
#!/usr/bin/perl # # Copyright 2006 Dr. Georg Fischer <punctum at punctum dot kom> # # 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. # #------------------------------------------------------------------ # Example client - short perl program # for SOAP access to UnitConverter service # @(#) $Id: client.pl 221 2009-08-11 06:08:05Z gfis $ # # Usage: # perl client.pl parm1 parm2 # # The essential 4 lines in the program below are marked with # <=== #------------------------------------------------------------------ use strict; use SOAP::Lite; # <=== # take up to 3 parameters from the command line my $from_unit = ""; my $to_unit = ""; if (scalar (@ARGV) > 0) { $from_unit = shift @ARGV; $from_unit =~ s[\W][]g; # remove any non-word characters if (scalar (@ARGV) > 0) { $to_unit = shift @ARGV; $to_unit =~ s[\W][]g; # remove any non-word characters } } else { print "usage: perl client.pl parm1 parm2\n"; } # create a new SOAP::Lite instance from the WSDL my $path = $0; $path =~ s[client\.pl][dbat.wsdl]; my $service = SOAP::Lite->service("file:$path"); # <=== # call UnitService my $results = $service->getResponse ($from_unit, $to_unit); # <=== print $results; # <===
gfis/ramath
test/experiment/client.pl
Perl
apache-2.0
1,885
#!/usr/bin/perl # WARNING: this only handles a single genbank file per program. # TODO: object-orient this. package Genbank; use strict; use FindBin; use lib "$FindBin::Bin/.."; use Subfunctions qw(split_seq reverse_complement); use Data::Dumper; BEGIN { require Exporter; # set the version for version checking our $VERSION = 1.00; # Inherit from Exporter to export functions and variables our @ISA = qw(Exporter); # Functions and variables which are exported by default our @EXPORT = qw(parse_genbank sequence_for_interval sequin_feature stringify_feature parse_feature_desc parse_interval parse_qualifiers within_interval write_sequin_tbl feature_table_from_genbank set_sequence get_sequence get_name write_features_as_fasta clone_features simplify_genbank_array); # Functions and variables which can be optionally exported our @EXPORT_OK = qw(); } my $line = ""; my $in_features = 0; my $in_sequence = 0; my $feat_desc_string = ""; my $sequence = ""; my $curr_gene = {}; my $gb_name = ""; sub set_sequence { $sequence = shift; } sub get_sequence { return $sequence; } sub get_name { return $gb_name; } sub parse_genbank { my $gbfile = shift; open FH, "<:crlf", $gbfile; my @gene_array = (); $line = ""; $in_features = 0; $in_sequence = 0; $feat_desc_string = ""; $sequence = ""; $curr_gene = {}; $gb_name = ""; $line = readline FH; while (defined $line) { if ($line =~ /^\s+$/) { # if the line is blank, skip to end } elsif ($line =~ /^\/\//) { # we've finished the file last; } elsif ($line =~ /^\S/) { # we're looking at a new section if ($line =~ /DEFINITION\s+(.*)$/) { # if line has the definition, keep this. $gb_name = $1; } elsif ($line =~ /FEATURES/) { # if we hit a line that says FEATURES, we're starting the features. $in_features = 1; } elsif ($line =~ /ORIGIN/) { # if we hit a line that says ORIGIN, we have sequence # this is the end of the features: process the last feature and finish. parse_feature_desc ($feat_desc_string, \@gene_array); $in_features = 0; $in_sequence = 1; } } elsif ($in_sequence == 1) { $line =~ s/\d//g; $line =~ s/\s//g; $sequence .= $line; # process lines in the sequence. } elsif ($in_features == 1) { # three types of lines in features: if ($line =~ /^\s{5}(\S.+)$/) { # start of a feature descriptor. Parse whatever feature and qualifiers we might've been working on and move on. if ($feat_desc_string ne "") { my $feat_desc_hash = parse_feature_desc ($feat_desc_string, \@gene_array); } $feat_desc_string = $1; } elsif ($line =~ /^\s{21}(\S.+)$/) { $feat_desc_string .= "+$1"; } } $line = readline FH; } close FH; return \@gene_array; } sub simplify_genbank_array { my $gene_array = shift; my @simplified_array = (); foreach my $feat (@$gene_array) { if ($feat->{'type'} =~ /gene|source/) { my @newcontains = (); foreach my $subfeat (@{$feat->{'contains'}}) { if ($subfeat->{'type'} !~ /exon|intron|STS/) { push @newcontains, $subfeat; } } $feat->{'contains'} = \@newcontains; push @simplified_array, $feat; } } return \@simplified_array; } sub parse_feature_sequences { my $gene_array = shift; my $gene_id = 0; foreach my $gene (@$gene_array) { if ($gene->{'type'} eq "gene") { my $interval_str = flatten_interval ($gene->{'region'}); my $geneseq = sequence_for_interval ($interval_str); my $genename = $gene->{'qualifiers'}->{'gene'}; foreach my $feat (@{$gene->{'contains'}}) { my $feat_id = 0; foreach my $reg (@{$feat->{'region'}}) { my $strand = "+"; my ($start, $end) = split (/\.\./, $reg); if ($end < $start) { $strand = "-"; my $oldend = $start; $start = $end; $end = $oldend; } my $regseq = sequence_for_interval ($reg); my $featname = $feat->{'type'}; $feat_id++; } } my $interval_str = flatten_interval ($gene->{'region'}); my @gene_interval = ($interval_str); $gene_id++; } } } sub clone_features { my $gene_array = shift; my $flattened_hash = {}; my @flattened_names = (); my $gene_id = 0; foreach my $gene (@$gene_array) { if ($gene->{'type'} eq "gene") { my $interval_str = flatten_interval ($gene->{'region'}); my @gene_interval = ($interval_str); # we need to disambiguate different copies of the gene my $genename = $gene->{'qualifiers'}->{'gene'} . "_$gene_id"; my $strand = "+"; my $reg = @{$gene->{'region'}}[0]; my ($start, $end) = split (/\.\./, $reg); if ($end < $start) { $strand = "-"; my $oldend = $start; $start = $end; $end = $oldend; } my $regseq = sequence_for_interval ($reg); push @flattened_names, $genename; $flattened_hash->{$genename}->{'strand'} = $strand; $flattened_hash->{$genename}->{'start'} = $start; $flattened_hash->{$genename}->{'end'} = $end; $flattened_hash->{$genename}->{'characters'} = $regseq; $flattened_hash->{$genename}->{'gene'} = $genename; $flattened_hash->{$genename}->{'type'} = "gene"; $flattened_hash->{$genename}->{'id'} = $gene_id; $flattened_hash->{$genename}->{'qualifiers'} = {}; add_qualifiers_to_feature_hash($flattened_hash->{$genename}->{'qualifiers'}, $gene); $flattened_hash->{$genename}->{'contains'} = []; foreach my $feat (@{$gene->{'contains'}}) { add_qualifiers_to_feature_hash($flattened_hash->{$genename}->{'qualifiers'}, $feat); my $feat_id = 0; foreach my $reg (@{$feat->{'region'}}) { my $strand = "+"; my ($start, $end) = split (/\.\./, $reg); if ($end < $start) { $strand = "-"; my $oldend = $start; $start = $end; $end = $oldend; } my $regseq = sequence_for_interval ($reg); my $featname = $feat->{'type'}; my $fullname = "$genename"."_$featname"."_$feat_id"; push @flattened_names, $fullname; push @{$flattened_hash->{$genename}->{'contains'}}, $fullname; $flattened_hash->{$fullname}->{'strand'} = $strand; $flattened_hash->{$fullname}->{'start'} = $start; $flattened_hash->{$fullname}->{'end'} = $end; $flattened_hash->{$fullname}->{'characters'} = $regseq; $flattened_hash->{$fullname}->{'gene'} = $genename; $flattened_hash->{$fullname}->{'type'} = $featname; $flattened_hash->{$fullname}->{'id'} = $gene_id; $feat_id++; } } $gene_id++; } } return ($flattened_hash, \@flattened_names); } sub write_features_as_fasta { my $gene_array = shift; my ($flattened_hash, $flattened_names) = clone_features ($gene_array); my $result_string = ""; foreach my $fullname (@$flattened_names) { my $strand = $flattened_hash->{$fullname}->{'strand'}; my $start = $flattened_hash->{$fullname}->{'start'}; my $end = $flattened_hash->{$fullname}->{'end'}; my $regseq = $flattened_hash->{$fullname}->{'characters'}; $result_string .= ">$fullname($strand)\t$start\t$end\n$regseq\n"; } return $result_string; } sub write_sequin_tbl { my $gene_array = shift; my $name = shift; # print header my $result_string = ">Features\t$name\n"; # start printing genes foreach my $gene (@$gene_array) { my $type = $gene->{'type'}; foreach my $r (@{$gene->{'region'}}) { if ($r =~ /(\d+)\.\.(\d+)/) { # first, print the main feature: $result_string .= "$1\t$2\t$type\n"; foreach my $q (keys %{$gene->{'qualifiers'}}) { my $qual = $gene->{qualifiers}->{$q}; $result_string .= "\t\t\t$q\t$qual\n"; } # then, print each feature contained. foreach my $feat (@{$gene->{'contains'}}) { $result_string .= Genbank::sequin_feature ($feat->{'region'}, $feat); } } } } return $result_string; } sub feature_table_from_genbank { my $gbfile = shift; my $gene_array = Genbank::simplify_genbank_array(Genbank::parse_genbank($gbfile)); my @feature_array = (); foreach my $gene (@$gene_array) { if ($gene->{'type'} eq "gene") { # make an entry for the main gene my $feat_hash = {}; $feat_hash->{'qualifiers'} = $gene->{'qualifiers'}; $feat_hash->{'region'} = flatten_interval ($gene->{'region'}); $feat_hash->{'type'} = $gene->{'type'}; $feat_hash->{'contains'} = []; push @feature_array, $feat_hash; foreach my $feat (@{$gene->{'contains'}}) { # then make an entry for each subcomponent my $subfeat_hash = {}; $subfeat_hash->{'qualifiers'} = $feat->{'qualifiers'}; $subfeat_hash->{'region'} = $feat->{'region'}; $subfeat_hash->{'type'} = $feat->{'type'}; push @{$feat_hash->{'contains'}}, $subfeat_hash; } } } return \@feature_array; } sub sequence_for_interval { my $interval_str = shift; my $revcomp = shift; $interval_str =~ /(\d+)\.\.(\d+)/; my $start = $1; my $end = $2; my $geneseq = ""; if ($start < $end) { (undef, $geneseq, undef) = Subfunctions::split_seq ($sequence, $start, $end); } else { (undef, $geneseq, undef) = Subfunctions::split_seq ($sequence, $end, $start); if ($revcomp == 1) { $geneseq = reverse_complement ($geneseq); } } return $geneseq; } sub sequin_feature { my $regions = shift; my $feature = shift; my $result_string = ""; my $first_int = shift @$regions; $first_int =~ /(\d+)\.\.(\d+)/; $result_string = "$1\t$2\t$feature->{type}\n"; foreach my $int (@$regions) { $int =~ /(\d+)\.\.(\d+)/; $result_string .= "$1\t$2\n"; } foreach my $key (keys %{$feature->{'qualifiers'}}) { $result_string .= "\t\t\t$key\t$feature->{qualifiers}->{$key}\n"; } return $result_string; } sub stringify_feature { my $regions = shift; my $feature = shift; my $result_string = ""; my @features = (); foreach my $key (keys %{$feature->{'qualifiers'}}) { my $feat = "$key=$feature->{qualifiers}->{$key}"; push @features, $feat; } $result_string = "$feature->{type}\t".join(",",@$regions)."\t".join("#",@features); return $result_string; } sub add_qualifiers_to_feature_hash { my $feature_hash = shift; my $feature_to_add = shift; foreach my $key (keys %{$feature_to_add->{'qualifiers'}}) { $feature_hash->{$key} = $feature_to_add->{'qualifiers'}->{$key}; } return $feature_hash; } sub flatten_interval { my $int_array = shift; # calculate the largest extent of the main interval. my @locs = (); foreach my $r (@$int_array) { if ($r =~ /(\d+)\.\.(\d+)/) { push @locs, $1; push @locs, $2; } } # sort all the listed locations, make the start be the smallest possible val and the end be the largest possible val. @locs = sort {$a <=> $b} @locs; my $main_start = shift @locs; my $main_end = pop @locs; # was the original interval complemented? my $r = @$int_array[0]; my ($loc1, $loc2) = split (/\.\./, $r); if ($loc1 < $loc2) { return "$main_start..$main_end"; } else { return "$main_end..$main_start"; } } sub parse_feature_desc { my $feat_desc_string = shift; my $gene_array_ptr = shift; my $feat_desc_hash = {}; my ($feature_desc, @feature_quals) = split (/\+\//, $feat_desc_string); #parse feature_desc into name and interval. $feature_desc =~ s/\+//g; $feature_desc =~ /^(.{16})(.+)$/; my $type = $1; my $region = $2; $type =~ s/ *$//; # remove trailing blanks. $feat_desc_hash->{'type'} = $type; $feat_desc_hash->{'region'} = parse_interval($region); $feat_desc_hash->{'qualifiers'} = parse_qualifiers(\@feature_quals); if ($feat_desc_hash->{'type'} eq "gene") { $curr_gene = {}; push @$gene_array_ptr, $curr_gene; $curr_gene->{'contains'} = (); $curr_gene->{'region'} = $feat_desc_hash->{'region'}; $curr_gene->{'qualifiers'} = $feat_desc_hash->{'qualifiers'}; $curr_gene->{'type'} = "gene"; } else { if (within_interval($curr_gene->{'region'}, $feat_desc_hash->{'region'})) { # this feat_desc_hash belongs to the current gene. push @{$curr_gene->{'contains'}}, $feat_desc_hash; } else { $curr_gene = $feat_desc_hash; push @$gene_array_ptr, $feat_desc_hash; } } return $feat_desc_hash; } sub parse_interval { my $intervalstr = shift; my @regions = (); if ($intervalstr =~ /^complement\s*\((.+)\)/) { # this is a complementary strand feature. my $subregions = parse_interval($1); foreach my $subreg (@$subregions) { if ($subreg =~ /(\d+)\.\.(\d+)/) { unshift @regions, "$2..$1"; } } } elsif ($intervalstr =~ /^join\s*\((.+)\)$/) { # this is a series of intervals my @subintervals = split(/,/, $1); foreach my $subint (@subintervals) { my $subregions = parse_interval($subint); push @regions, @$subregions; } } elsif ($intervalstr =~ /^order\s*\((.+)\)$/) { # this is a series of intervals, but there is no implication about joining them. my @subintervals = split(/,/, $1); my $max_interval = max_interval (\@subintervals); push @regions, @$max_interval; } elsif ($intervalstr =~ /(\d+)\.\.(\d+)/) { push @regions, "$intervalstr"; } return \@regions; } sub parse_qualifiers { my $qualifiers_ref = shift; my @qualifiers = @$qualifiers_ref; my $feature_hash = {}; while (@qualifiers > 0) { my $f = shift @qualifiers; $f =~ s/\+/ /g; if ($f =~ /(.+)=(.+)/) { my $key = $1; my $val = $2; if ($val =~ /"(.*)"/) { $val = $1; } if ($key eq "translation") { next; $val =~ s/ //g; } $feature_hash->{$key} = $val; } elsif ($f =~ /(.+)/) { my $key = $1; $feature_hash->{$key} = ""; } else { print "haven't dealt with this: $f\n"; } } return $feature_hash; } sub max_interval { my $regions = shift; # calculate the largest extent of the main interval. my @locs = (); my $strand = "+"; foreach my $r (@$regions) { if ($r =~ /(\d+)\.\.(\d+)/) { push @locs, $1; push @locs, $2; if ($2 < $1) { $strand = "-"; } } } # sort all the listed locations, make the start be the smallest possible val and the end be the largest possible val. @locs = sort {$a <=> $b} @locs; my $main_start = shift @locs; my $main_end = pop @locs; my @max_region = (); if ($strand eq "+") { push @max_region, "$main_start..$main_end"; } else { push @max_region, "$main_end..$main_start"; } return \@max_region; } sub within_interval { my $main_interval = shift; my $test_interval = shift; if (($main_interval eq "") || ($test_interval eq "")) { # if the interval we're testing for is blank, return 0. return 0; } if ((ref $test_interval) !~ /ARRAY/) { $test_interval = parse_interval($test_interval); } if ((ref $main_interval) !~ /ARRAY/) { $main_interval = parse_interval($main_interval); } # calculate the largest extent of the main interval. my @locs = (); foreach my $r (@$main_interval) { if ($r =~ /(\d+)\.\.(\d+)/) { push @locs, $1; push @locs, $2; } } # sort all the listed locations, make the start be the smallest possible val and the end be the largest possible val. @locs = sort {$a <=> $b} @locs; my $main_start = shift @locs; my $main_end = pop @locs; # do the same for the tested intervals. @locs = (); foreach my $r (@$test_interval) { if ($r =~ /(\d+)\.\.(\d+)/) { push @locs, $1; push @locs, $2; } } # sort all the listed locations, make the start be the smallest possible val and the end be the largest possible val. @locs = sort {$a <=> $b} @locs; my $test_start = shift @locs; my $test_end = pop @locs; if (($test_start >= $main_start) && ($test_end <= $main_end)) { return 1; } return 0; } return 1;
daisieh/phylogenomics
lib/Genbank.pm
Perl
bsd-3-clause
15,330
#!/usr/bin/perl -w use strict; use ParseUtils; # find the file in source directory with the latest update time (mtime) my ($indir,$outdir) = getFullDataPaths('image_clone'); #open source directory opendir(INDIR,$indir) or die "Couldn't open directory $indir ($!)\n"; #list of files in source_directory my @files = readdir(INDIR); closedir(INDIR); #open target directory opendir(OUTDIR,"$outdir") or die "Couldn't open directory $outdir ($!)\n"; #list of files in source_directory my @outdir_files = readdir(OUTDIR); closedir(OUTDIR); shift @files; shift @files; #shift @outdir_files; #shift @outdir_files; # print "@files\n"; # print "@outdir_files \n"; #sort to find newest file my @timesort = sort { -M "$indir/$b" <=> -M "$indir/$a" } @files; my $newest_file = $timesort[-1]; my $cp = "cp $indir/$newest_file $outdir"; system ($cp); my @go_array; my @go_array_01; my $input_file = "$outdir/$newest_file"; my $out_file = "$outdir/cumulative_arrayed_plates.out"; my $log_file = "IMAGE_CLONE_parser.log"; my $bad_file = "IMAGE_CLONE_parser.bad"; open (INFILE, "<$input_file") or die "Cannot open \"$input_file\" \n\n"; open (OUTFILE, ">$out_file") or die "Cannot open \"$out_file\" \n\n"; open (LOGFILE, ">$log_file") or die "Cannot open \"$log_file\" \n\n"; open (BADFILE, ">$bad_file") or die "Cannot open \"$bad_file\" \n\n"; #QA deliverables my $parsedRecords=0; my $badRecords=0; my $rawData=0; foreach my $line (<INFILE>) { $rawData++; if ($line =~ /[A-Z]{1,}\d{1,}/) { @go_array = split("\t", $line); if ($line =~ /[A-Z]{1,}\d{1,}\s{1,}[A-Z]{1,}\d{1,}/) { $go_array[7] =~ s/\s{1,}/,/g; @go_array_01 = split("\,", $go_array[7]); my $i = -1; foreach my $new_line(@go_array_01) { while ($i < $#go_array_01) { $i = $i + 1; $go_array_01[$i] =~ s/^\s+//; $go_array_01[$i] =~ s/\s+$//; print OUTFILE "$go_array[0]|$go_array[5]|$go_array[6]|$go_array_01[$i]\n"; } } } else { print OUTFILE "$go_array[0]|$go_array[5]|$go_array[6]|$go_array[7]"; } $parsedRecords++; } elsif ($line =~ /[A-Z]{1,}/) { @go_array = split("\t", $line); my $i = 0; print OUTFILE "$go_array[0]|$go_array[5]|$go_array[6]\n"; $parsedRecords++; } else { $badRecords++; print BADFILE $line; } } print LOGFILE "Data Source: IMAGE Consortium Clone Data\n"; print LOGFILE "Number of records in $input_file: $parsedRecords\n"; print LOGFILE "Number of records written to $out_file: $parsedRecords\n"; print LOGFILE "Number of skipped records: $badRecords\n"; close INFILE; close OUTFILE; close BADFILE; close LOGFILE; exit(0);
NCIP/cabio
software/cabio-database/scripts/parse/no_longer_used/image_clone/IMAGE_Clone_DataParser.pl
Perl
bsd-3-clause
2,844
# # ServiceClassCommonGrammar.pm : part of the Mace toolkit for building distributed systems # # Copyright (c) 2011, Charles Killian, James W. Anderson, Adolfo Rodriguez, Dejan Kostic # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the names of the contributors, nor their associated universities # or organizations may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # ----END-OF-LEGAL-STUFF---- package Mace::Compiler::ServiceClassCommonGrammar; use strict; use Mace::Compiler::Grammar; use Mace::Compiler::CommonGrammar; use constant SERVICE_CLASS_COMMON => Mace::Compiler::CommonGrammar::COMMON . q{ Reset : { $thisparser->{'local'}{'originaltext'} = $text; $thisparser->{'local'}{'serviceclass'} = Mace::Compiler::ServiceClass->new(); $thisparser->{'local'}{'classname'} = ""; } }; # SERVICE_CLASS_COMMON grammar 1;
jojochuang/eventwave
perl5/Mace/Compiler/ServiceClassCommonGrammar.pm
Perl
bsd-3-clause
2,202
#!/usr/bin/env perl ## Name........: tmesis ## Autor.......: Jens Steube <jens.steube@gmail.com> ## License.....: MIT use strict; use warnings; #tmesis will take a wordlist and produce insertion rules that would insert each word of the wordlist to preset positions. #For example: #Word ‘password’ will create insertion rules that would insert ‘password’ from position 0 to position F (15) and It will mutate the string ‘123456’ as follows. #password123456 #1password23456 #12password3456 #123password456 #1234password56 #12345password6 #123456password # #Hints: #*Use tmesis to create rules to attack hashlists the came from the source. Run initial analysis on the cracked passwords , collect the top 10 – 20 words appear on the passwords and use tmesis to generate rules. #*use tmesis generated rules in combination with best64.rules # # inspired by T0XlC my $min_rule_pos = 0; my $max_rule_pos = 15; my $db; my @intpos_to_rulepos = ('0'..'9', 'A'..'Z'); my $function = "i"; #my $function = "o"; while (my $word = <>) { chomp $word; my $word_len = length $word; my @word_buf = split "", $word; for (my $rule_pos = $min_rule_pos; $rule_pos < $max_rule_pos - $word_len; $rule_pos++) { my @rule; for (my $word_pos = 0; $word_pos < $word_len; $word_pos++) { my $function_full = $function . $intpos_to_rulepos[$rule_pos + $word_pos] . $word_buf[$word_pos]; push @rule, $function_full; } print join (" ", @rule), "\n"; } }
philsmd/hashcat-utils
src/tmesis.pl
Perl
mit
1,492
/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: J.Wielemaker@vu.nl WWW: http://www.swi-prolog.org Copyright (c) 1985-2020, University of Amsterdam VU University Amsterdam CWI, Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module('$autoload', [ '$find_library'/5, '$in_library'/3, '$define_predicate'/1, '$update_library_index'/0, '$autoload'/1, make_library_index/1, make_library_index/2, reload_library_index/0, autoload_path/1, autoload/1, % +File autoload/2, % +File, +Imports require/1 % +Predicates ]). :- meta_predicate '$autoload'(:), autoload(:), autoload(:, +), require(:). :- dynamic library_index/3, % Head x Module x Path autoload_directories/1, % List index_checked_at/1. % Time :- volatile library_index/3, autoload_directories/1, index_checked_at/1. user:file_search_path(autoload, swi(library)). user:file_search_path(autoload, pce(prolog/lib)). user:file_search_path(autoload, app_config(lib)). %! '$find_library'(+Module, +Name, +Arity, -LoadModule, -Library) is semidet. % % Locate a predicate in the library. Name and arity are the name % and arity of the predicate searched for. `Module' is the % preferred target module. The return values are the full path % name (excluding extension) of the library and module declared in % that file. '$find_library'(Module, Name, Arity, LoadModule, Library) :- load_library_index(Name, Arity), functor(Head, Name, Arity), ( library_index(Head, Module, Library), LoadModule = Module ; library_index(Head, LoadModule, Library) ), !. %! '$in_library'(+Name, +Arity, -Path) is semidet. %! '$in_library'(-Name, -Arity, -Path) is nondet. % % Is true if Name/Arity is in the autoload libraries. '$in_library'(Name, Arity, Path) :- atom(Name), integer(Arity), !, load_library_index(Name, Arity), functor(Head, Name, Arity), library_index(Head, _, Path). '$in_library'(Name, Arity, Path) :- load_library_index(Name, Arity), library_index(Head, _, Path), functor(Head, Name, Arity). %! '$define_predicate'(:Head) % % Make sure PredInd can be called. First test if the predicate is % defined. If not, invoke the autoloader. :- meta_predicate '$define_predicate'(:). '$define_predicate'(Head) :- '$defined_predicate'(Head), !. '$define_predicate'(Term) :- Term = Module:Head, ( compound(Head) -> compound_name_arity(Head, Name, Arity) ; Name = Head, Arity = 0 ), '$undefined_procedure'(Module, Name, Arity, retry). /******************************** * UPDATE INDEX * ********************************/ :- thread_local silent/0. %! '$update_library_index' % % Called from make/0 to update the index of the library for each % library directory that has a writable index. Note that in the % Windows version access_file/2 is mostly bogus. We assert % silent/0 to suppress error messages. '$update_library_index' :- setof(Dir, writable_indexed_directory(Dir), Dirs), !, setup_call_cleanup( asserta(silent, Ref), guarded_make_library_index(Dirs), erase(Ref)), ( flag('$modified_index', true, false) -> reload_library_index ; true ). '$update_library_index'. guarded_make_library_index([]). guarded_make_library_index([Dir|Dirs]) :- ( catch(make_library_index(Dir), E, print_message(error, E)) -> true ; print_message(warning, goal_failed(make_library_index(Dir))) ), guarded_make_library_index(Dirs). %! writable_indexed_directory(-Dir) is nondet. % % True when Dir is an indexed library directory with a writable % index, i.e., an index that can be updated. writable_indexed_directory(Dir) :- index_file_name(IndexFile, autoload('INDEX'), [access([read,write])]), file_directory_name(IndexFile, Dir). writable_indexed_directory(Dir) :- absolute_file_name(library('MKINDEX'), [ file_type(prolog), access(read), solutions(all), file_errors(fail) ], MkIndexFile), file_directory_name(MkIndexFile, Dir), plfile_in_dir(Dir, 'INDEX', _, IndexFile), access_file(IndexFile, write). /******************************** * LOAD INDEX * ********************************/ %! reload_library_index % % Reload the index on the next call reload_library_index :- context_module(M), reload_library_index(M). reload_library_index(M) :- with_mutex('$autoload', clear_library_index(M)). clear_library_index(M) :- retractall(M:library_index(_, _, _)), retractall(M:autoload_directories(_)), retractall(M:index_checked_at(_)). %! load_library_index(?Name, ?Arity) is det. %! load_library_index(?Name, ?Arity, :IndexSpec) is det. % % Try to find Name/Arity in the library. If the predicate is % there, we are happy. If not, we check whether the set of loaded % libraries has changed and if so we reload the index. :- meta_predicate load_library_index(?, ?, :). :- public load_library_index/3. load_library_index(Name, Arity) :- load_library_index(Name, Arity, autoload('INDEX')). load_library_index(Name, Arity, M:_Spec) :- atom(Name), integer(Arity), functor(Head, Name, Arity), M:library_index(Head, _, _), !. load_library_index(_, _, Spec) :- notrace(with_mutex('$autoload', load_library_index_p(Spec))). load_library_index_p(M:_) :- M:index_checked_at(Time), get_time(Now), Now-Time < 60, !. load_library_index_p(M:Spec) :- findall(Index, index_file_name(Index, Spec, [access(read)]), List0), '$list_to_set'(List0, List), retractall(M:index_checked_at(_)), get_time(Now), assert(M:index_checked_at(Now)), ( M:autoload_directories(List) -> true ; retractall(M:library_index(_, _, _)), retractall(M:autoload_directories(_)), read_index(List, M), assert(M:autoload_directories(List)) ). %! index_file_name(-IndexFile, +Spec, +Options) is nondet. % % True if IndexFile is an autoload index file. Options is passed % to absolute_file_name/3. This predicate searches the path % =autoload=. % % @see file_search_path/2. index_file_name(IndexFile, FileSpec, Options) :- absolute_file_name(FileSpec, IndexFile, [ file_type(prolog), solutions(all), file_errors(fail) | Options ]). read_index([], _) :- !. read_index([H|T], M) :- !, read_index(H, M), read_index(T, M). read_index(Index, M) :- print_message(silent, autoload(read_index(Dir))), file_directory_name(Index, Dir), setup_call_cleanup( '$push_input_context'(autoload_index), setup_call_cleanup( open(Index, read, In), read_index_from_stream(Dir, In, M), close(In)), '$pop_input_context'). read_index_from_stream(Dir, In, M) :- repeat, read(In, Term), assert_index(Term, Dir, M), !. assert_index(end_of_file, _, _) :- !. assert_index(index(Name, Arity, Module, File), Dir, M) :- !, functor(Head, Name, Arity), atomic_list_concat([Dir, '/', File], Path), assertz(M:library_index(Head, Module, Path)), fail. assert_index(Term, Dir, _) :- print_message(error, illegal_autoload_index(Dir, Term)), fail. /******************************** * CREATE INDEX.pl * ********************************/ %! make_library_index(+Dir) is det. % % Create an index for autoloading from the directory Dir. The % index file is called INDEX.pl. In Dir contains a file % MKINDEX.pl, this file is loaded and we assume that the index is % created by directives that appearin this file. Otherwise, all % source files are scanned for their module-header and all % exported predicates are added to the autoload index. % % @see make_library_index/2 make_library_index(Dir0) :- forall(absolute_file_name(Dir0, Dir, [ expand(true), file_type(directory), file_errors(fail), solutions(all) ]), make_library_index2(Dir)). make_library_index2(Dir) :- plfile_in_dir(Dir, 'MKINDEX', _MkIndex, AbsMkIndex), access_file(AbsMkIndex, read), !, load_files(user:AbsMkIndex, [silent(true)]). make_library_index2(Dir) :- findall(Pattern, source_file_pattern(Pattern), PatternList), make_library_index2(Dir, PatternList). %! make_library_index(+Dir, +Patterns:list(atom)) is det. % % Create an autoload index INDEX.pl for Dir by scanning all files % that match any of the file-patterns in Patterns. Typically, this % appears as a directive in MKINDEX.pl. For example: % % ``` % :- prolog_load_context(directory, Dir), % make_library_index(Dir, ['*.pl']). % ``` % % @see make_library_index/1. make_library_index(Dir0, Patterns) :- forall(absolute_file_name(Dir0, Dir, [ expand(true), file_type(directory), file_errors(fail), solutions(all) ]), make_library_index2(Dir, Patterns)). make_library_index2(Dir, Patterns) :- plfile_in_dir(Dir, 'INDEX', _Index, AbsIndex), ensure_slash(Dir, DirS), pattern_files(Patterns, DirS, Files), ( library_index_out_of_date(Dir, AbsIndex, Files) -> do_make_library_index(AbsIndex, DirS, Files), flag('$modified_index', _, true) ; true ). ensure_slash(Dir, DirS) :- ( sub_atom(Dir, _, _, 0, /) -> DirS = Dir ; atom_concat(Dir, /, DirS) ). source_file_pattern(Pattern) :- user:prolog_file_type(PlExt, prolog), PlExt \== qlf, atom_concat('*.', PlExt, Pattern). plfile_in_dir(Dir, Base, PlBase, File) :- file_name_extension(Base, pl, PlBase), atomic_list_concat([Dir, '/', PlBase], File). pattern_files([], _, []). pattern_files([H|T], DirS, Files) :- atom_concat(DirS, H, P0), expand_file_name(P0, Files0), '$append'(Files0, Rest, Files), pattern_files(T, DirS, Rest). library_index_out_of_date(_Dir, Index, _Files) :- \+ exists_file(Index), !. library_index_out_of_date(Dir, Index, Files) :- time_file(Index, IndexTime), ( time_file(Dir, DotTime), DotTime > IndexTime ; '$member'(File, Files), time_file(File, FileTime), FileTime > IndexTime ), !. do_make_library_index(Index, Dir, Files) :- ensure_slash(Dir, DirS), '$stage_file'(Index, StagedIndex), setup_call_catcher_cleanup( open(StagedIndex, write, Out), ( print_message(informational, make(library_index(Dir))), index_header(Out), index_files(Files, DirS, Out) ), Catcher, install_index(Out, Catcher, StagedIndex, Index)). install_index(Out, Catcher, StagedIndex, Index) :- catch(close(Out), Error, true), ( silent -> OnError = silent ; OnError = error ), ( var(Error) -> TheCatcher = Catcher ; TheCatcher = exception(Error) ), '$install_staged_file'(TheCatcher, StagedIndex, Index, OnError). %! index_files(+Files, +Directory, +Out:stream) is det. % % Write index for Files in Directory to the stream Out. index_files([], _, _). index_files([File|Files], DirS, Fd) :- catch(setup_call_cleanup( open(File, read, In), read(In, Term), close(In)), E, print_message(warning, E)), ( Term = (:- module(Module, Public)), is_list(Public) -> atom_concat(DirS, Local, File), file_name_extension(Base, _, Local), forall(public_predicate(Public, Name/Arity), format(Fd, 'index((~k), ~k, ~k, ~k).~n', [Name, Arity, Module, Base])) ; true ), index_files(Files, DirS, Fd). public_predicate(Public, PI) :- '$member'(PI0, Public), canonical_pi(PI0, PI). canonical_pi(Var, _) :- var(Var), !, fail. canonical_pi(Name/Arity, Name/Arity). canonical_pi(Name//A0, Name/Arity) :- Arity is A0 + 2. index_header(Fd):- format(Fd, '/* Creator: make/0~n~n', []), format(Fd, ' Purpose: Provide index for autoload~n', []), format(Fd, '*/~n~n', []). /******************************* * EXTENDING * *******************************/ %! autoload_path(+Path) is det. % % Add Path to the libraries that are used by the autoloader. This % extends the search path =autoload= and reloads the library % index. For example: % % == % :- autoload_path(library(http)). % == % % If this call appears as a directive, it is term-expanded into a % clause for user:file_search_path/2 and a directive calling % reload_library_index/0. This keeps source information and allows % for removing this directive. autoload_path(Alias) :- ( user:file_search_path(autoload, Alias) -> true ; assertz(user:file_search_path(autoload, Alias)), reload_library_index ). system:term_expansion((:- autoload_path(Alias)), [ user:file_search_path(autoload, Alias), (:- reload_library_index) ]). /******************************* * RUNTIME AUTOLOADER * *******************************/ %! $autoload'(:PI) is semidet. % % Provide PI by autoloading. This checks: % % - Explicit autoload/2 declarations % - Explicit autoload/1 declarations % - The library if current_prolog_flag(autoload, true) holds. '$autoload'(PI) :- source_location(File, _Line), !, setup_call_cleanup( '$start_aux'(File, Context), '$autoload2'(PI), '$end_aux'(File, Context)). '$autoload'(PI) :- '$autoload2'(PI). '$autoload2'(PI) :- setup_call_cleanup( leave_sandbox(Old), 'safe_autoload3'(PI), restore_sandbox(Old)). safe_autoload3(M:_/_):- \+ ground(M),!. safe_autoload3(PI) :- '$autoload3'(PI). leave_sandbox(Sandboxed) :- current_prolog_flag(sandboxed_load, Sandboxed), set_prolog_flag(sandboxed_load, false). restore_sandbox(Sandboxed) :- set_prolog_flag(sandboxed_load, Sandboxed). '$autoload3'(PI) :- autoload_from(PI, LoadModule, FullFile), do_autoload(FullFile, PI, LoadModule). %! autoload_from(+PI, -LoadModule, -File) is semidet. % % True when PI can be defined by loading File which is defined the % module LoadModule. autoload_from(Module:PI, LoadModule, FullFile) :- autoload_in(Module, explicit), current_autoload(Module:File, Ctx, import(Imports)), memberchk(PI, Imports), library_info(File, Ctx, FullFile, LoadModule, Exports), ( pi_in_exports(PI, Exports) -> ! ; autoload_error(Ctx, not_exported(PI, File, FullFile, Exports)), fail ). autoload_from(Module:Name/Arity, LoadModule, FullFile) :- autoload_in(Module, explicit), PI = Name/Arity, current_autoload(Module:File, Ctx, all), library_info(File, Ctx, FullFile, LoadModule, Exports), pi_in_exports(PI, Exports). autoload_from(Module:Name/Arity, LoadModule, Library) :- autoload_in(Module, general), '$find_library'(Module, Name, Arity, LoadModule, Library). :- public autoload_in/2. % used in syspred autoload_in(Module, How) :- current_prolog_flag(autoload, AutoLoad), autoload_in(AutoLoad, How, Module), !. %! autoload_in(+AutoloadFlag, +AutoloadMode, +TargetModule) is semidet. autoload_in(true, _, _). autoload_in(explicit, explicit, _). autoload_in(explicit_or_user, explicit, _). autoload_in(user, explicit, user). autoload_in(explicit_or_user, explicit, _). autoload_in(user, _, user). autoload_in(explicit_or_user, general, user). %! do_autoload(+File, :PI, +LoadModule) is det. % % Load File, importing PI into the qualified module. File is known to % define LoadModule. There are three cases: % % - The target is the autoload module itself. Uncommon. % - We already loaded this module. Note that % '$get_predicate_attribute'/3 alone is not enough as it will % consider auto-import from `user`. '$c_current_predicate'/2 % verifies the predicate really exists, but doesn't validate % that it is defined. % - We must load the module and import the target predicate. do_autoload(Library, Module:Name/Arity, LoadModule) :- functor(Head, Name, Arity), '$update_autoload_level'([autoload(true)], Old), verbose_autoload(Module:Name/Arity, Library), '$compilation_mode'(OldComp, database), ( Module == LoadModule -> ensure_loaded(Module:Library) ; ( '$c_current_predicate'(_, LoadModule:Head), '$get_predicate_attribute'(LoadModule:Head, defined, 1), \+ '$loading'(Library) -> Module:import(LoadModule:Name/Arity) ; use_module(Module:Library, [Name/Arity]) ) ), '$set_compilation_mode'(OldComp), '$set_autoload_level'(Old), '$c_current_predicate'(_, Module:Head). verbose_autoload(PI, Library) :- current_prolog_flag(verbose_autoload, true), !, set_prolog_flag(verbose_autoload, false), print_message(informational, autoload(PI, Library)), set_prolog_flag(verbose_autoload, true). verbose_autoload(PI, Library) :- print_message(silent, autoload(PI, Library)). %! autoloadable(:Head, -File) is nondet. % % True when Head can be autoloaded from File. This implements the % predicate_property/2 property autoload(File). The module muse be % instantiated. :- public % used from predicate_property/2 autoloadable/2. autoloadable(M:Head, FullFile) :- atom(M), current_module(M), autoload_in(M, explicit), ( callable(Head) -> goal_name_arity(Head, Name, Arity), autoload_from(M:Name/Arity, _, FullFile) ; findall((M:H)-F, autoloadable_2(M:H, F), Pairs), ( '$member'(M:Head-FullFile, Pairs) ; current_autoload(M:File, Ctx, all), library_info(File, Ctx, FullFile, _, Exports), '$member'(PI, Exports), '$pi_head'(PI, Head), \+ memberchk(M:Head-_, Pairs) ) ). autoloadable(M:Head, FullFile) :- ( var(M) -> autoload_in(any, general) ; autoload_in(M, general) ), ( callable(Head) -> goal_name_arity(Head, Name, Arity), ( '$find_library'(_, Name, Arity, _, FullFile) -> true ) ; '$in_library'(Name, Arity, autoload), functor(Head, Name, Arity) ). autoloadable_2(M:Head, FullFile) :- current_autoload(M:File, Ctx, import(Imports)), library_info(File, Ctx, FullFile, _LoadModule, _Exports), '$member'(PI, Imports), '$pi_head'(PI, Head). goal_name_arity(Head, Name, Arity) :- compound(Head), !, compound_name_arity(Head, Name, Arity). goal_name_arity(Head, Head, 0). %! library_info(+Spec, +AutoloadContext, -FullFile, -Module, -Exports) % % Find information about a library. library_info(Spec, _, FullFile, Module, Exports) :- '$resolved_source_path'(Spec, FullFile, []), !, ( \+ '$loading_file'(FullFile, _Queue, _LoadThread) -> '$current_module'(Module, FullFile), '$module_property'(Module, exports(Exports)) ; library_info_from_file(FullFile, Module, Exports) ). library_info(Spec, Context, FullFile, Module, Exports) :- ( Context = (Path:_Line) -> Extra = [relative_to(Path)] ; Extra = [] ), ( absolute_file_name(Spec, FullFile, [ file_type(prolog), access(read), file_errors(fail) | Extra ]) -> '$register_resolved_source_path'(Spec, FullFile), library_info_from_file(FullFile, Module, Exports) ; autoload_error(Context, no_file(Spec)), fail ). library_info_from_file(FullFile, Module, Exports) :- setup_call_cleanup( '$open_source'(FullFile, In, State, [], []), '$term_in_file'(In, _Read, _RLayout, Term, _TLayout, _Stream, [FullFile], []), '$close_source'(State, true)), ( Term = (:- module(Module, Exports)) -> ! ; nonvar(Term), skip_header(Term) -> fail ; '$domain_error'(module_header, Term) ). skip_header(begin_of_file). :- dynamic printed/3. :- volatile printed/3. autoload_error(Context, Error) :- suppress(Context, Error), !. autoload_error(Context, Error) :- get_time(Now), assertz(printed(Context, Error, Now)), print_message(warning, error(autoload(Error), autoload(Context))). suppress(Context, Error) :- printed(Context, Error, Printed), get_time(Now), ( Now - Printed < 1 -> true ; retractall(printed(Context, Error, _)), fail ). /******************************* * CALLBACK * *******************************/ :- public set_autoload/1. %! set_autoload(+Value) is det. % % Hook called from set_prolog_flag/2 when autoloading is switched. If % the desired value is `false` we should materialize all registered % requests for autoloading. We must do so before disabling autoloading % as loading the files may require autoloading. set_autoload(FlagValue) :- current_prolog_flag(autoload, FlagValue), !. set_autoload(FlagValue) :- \+ autoload_in(FlagValue, explicit, any), !, setup_call_cleanup( nb_setval('$autoload_disabling', true), materialize_autoload(Count), nb_delete('$autoload_disabling')), print_message(informational, autoload(disabled(Count))). set_autoload(_). materialize_autoload(Count) :- State = state(0), forall(current_predicate(M:'$autoload'/3), materialize_autoload(M, State)), arg(1, State, Count). materialize_autoload(M, State) :- ( current_autoload(M:File, Context, Import), library_info(File, Context, FullFile, _LoadModule, _Exports), arg(1, State, N0), N is N0+1, nb_setarg(1, State, N), ( Import == all -> verbose_autoload(M:all, FullFile), use_module(M:FullFile) ; Import = import(Preds) -> verbose_autoload(M:Preds, FullFile), use_module(M:FullFile, Preds) ), fail ; true ), abolish(M:'$autoload'/3). /******************************* * AUTOLOAD/2 * *******************************/ autoload(M:File) :- ( \+ autoload_in(M, explicit) ; nb_current('$autoload_disabling', true) ), !, use_module(M:File). autoload(M:File) :- '$must_be'(filespec, File), source_context(Context), retractall(M:'$autoload'(File, _, _)), assert_autoload(M:'$autoload'(File, Context, all)). autoload(M:File, Imports) :- ( \+ autoload_in(M, explicit) ; nb_current('$autoload_disabling', true) ), !, use_module(M:File, Imports). autoload(M:File, Imports0) :- '$must_be'(filespec, File), valid_imports(Imports0, Imports), source_context(Context), register_autoloads(Imports, M, File, Context), ( current_autoload(M:File, _, import(Imports)) -> true ; assert_autoload(M:'$autoload'(File, Context, import(Imports))) ). source_context(Path:Line) :- source_location(Path, Line), !. source_context(-). assert_autoload(Clause) :- '$initialization_context'(Source, Ctx), '$store_admin_clause2'(Clause, _Layout, Source, Ctx). valid_imports(Imports0, Imports) :- '$must_be'(list, Imports0), valid_import_list(Imports0, Imports). valid_import_list([], []). valid_import_list([H0|T0], [H|T]) :- '$pi_head'(H0, Head), '$pi_head'(H, Head), valid_import_list(T0, T). %! register_autoloads(+ListOfPI, +Module, +File, +Context) % % Put an `autoload` flag on all predicates declared using autoload/2 % to prevent duplicates or the user defining the same predicate. register_autoloads([], _, _, _). register_autoloads([PI|T], Module, File, Context) :- PI = Name/Arity, functor(Head, Name, Arity), ( '$get_predicate_attribute'(Module:Head, autoload, 1) -> ( current_autoload(Module:_File0, _Ctx0, import(Imports)), memberchk(PI, Imports) -> '$permission_error'(redefine, imported_procedure, PI), fail ; Done = true ) ; '$c_current_predicate'(_, Module:Head), % no auto-import '$get_predicate_attribute'(Module:Head, imported, From) -> ( ( '$resolved_source_path'(File, FullFile) -> true ; '$resolve_source_path'(File, FullFile, []) ), module_property(From, file(FullFile)) -> Done = true ; print_message(warning, autoload(already_defined(Module:PI, From))), Done = true ) ; true ), ( Done == true -> true ; '$set_predicate_attribute'(Module:Head, autoload, 1) ), register_autoloads(T, Module, File, Context). pi_in_exports(PI, Exports) :- '$member'(E, Exports), canonical_pi(E, PI), !. current_autoload(M:File, Context, Term) :- '$get_predicate_attribute'(M:'$autoload'(_,_,_), defined, 1), M:'$autoload'(File, Context, Term). /******************************* * REQUIRE * *******************************/ %! require(:ListOfPredIndicators) is det. % % Register the predicates in ListOfPredIndicators for autoloading % using autoload/2 if they are not system predicates. require(M:Spec) :- ( is_list(Spec) -> List = Spec ; phrase(comma_list(Spec), List) ), !, require(List, M, FromLib), keysort(FromLib, Sorted), by_file(Sorted, Autoload), forall('$member'(File-Import, Autoload), autoload(M:File, Import)). require(_:Spec) :- '$type_error'(list, Spec). require([],_, []). require([H|T], M, Needed) :- '$pi_head'(H, Head), ( '$get_predicate_attribute'(system:Head, defined, 1) -> require(T, M, Needed) ; '$pi_head'(Module:Name/Arity, M:Head), ( '$find_library'(Module, Name, Arity, _LoadModule, Library) -> Needed = [Library-H|More], require(T, M, More) ; print_message(error, error(existence_error(procedure, Name/Arity), _)), require(T, M, Needed) ) ). by_file([], []). by_file([File-PI|T0], [Spec-[PI|PIs]|T]) :- on_path(File, Spec), same_file(T0, File, PIs, T1), by_file(T1, T). on_path(Library, library(Base)) :- file_base_name(Library, Base), findall(Path, plain_source(library(Base), Path), [Library]), !. on_path(Library, Library). plain_source(Spec, Path) :- absolute_file_name(Spec, PathExt, [ file_type(prolog), access(read), file_errors(fail), solutions(all) ]), file_name_extension(Path, _, PathExt). same_file([File-PI|T0], File, [PI|PIs], T) :- !, same_file(T0, File, PIs, T). same_file(List, _, [], List). comma_list(Var) --> { var(Var), !, '$instantiation_error'(Var) }. comma_list((A,B)) --> !, comma_list(A), comma_list(B). comma_list(A) --> [A].
TeamSPoon/logicmoo_workspace
docker/rootfs/usr/local/lib/swipl/boot/autoload.pl
Perl
mit
29,714
package VSAP::Server::Modules::vsap::sys::security; use 5.008004; use strict; use warnings; use Carp; use VSAP::Server::Modules::vsap::logger; our $VERSION = '0.01'; our %_ERR = ( ERR_NOTAUTHORIZED => 100, ); use constant LOCK_EX => 2; ############################################################################## our $force_ssl_block = <<'_REWRITE_BLOCK_'; ## <===CPX: force ssl redirect start===> <IfModule mod_rewrite.c> RewriteCond %{REQUEST_URI} ^/ControlPanel/ RewriteCond %{SERVER_PORT} !^443$ RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R] </IfModule> ## <===CPX: force ssl redirect end===> _REWRITE_BLOCK_ # ---------------------------------------------------------------------------- sub _controlpanel_ssl_redirect_modify { my($modify_request) = @_; my $config_file = (-e "/www/conf.d/cpx.conf") ? "/www/conf.d/cpx.conf" : "/www/conf/httpd/conf"; open CONF, "+< $config_file" or do { carp "Could not open $config_file: $!\n"; return(0); }; flock CONF, LOCK_EX or do { carp "Could not lock $config_file: $!\n"; return(0); }; seek CONF, 0, 0; ## rewind my @conf = (); if ( $modify_request eq "disable" ) { my $skip = 0; local $_; while( <CONF> ) { if ( /CPX: force ssl redirect start/i ) { $skip = 1; } elsif ( /CPX: force ssl redirect end/i ) { $skip = 0; next; } next if ($skip); push @conf, $_; } } elsif ( $modify_request eq "enable" ) { my $scan_for_location = 0; local $_; while( <CONF> ) { push @conf, $_; if ( /require ControlPanel/i ) { $scan_for_location = 1; } elsif ( $scan_for_location && /<\/Location>/) { push(@conf, $force_ssl_block); } } } else { # unknown request close CONF; return(0); } seek CONF, 0, 0; ## rewind print CONF @conf; truncate CONF, tell CONF; close CONF; return(1); } # ---------------------------------------------------------------------------- sub _controlpanel_ssl_redirect_status { my $config_file = (-e "/www/conf.d/cpx.conf") ? "/www/conf.d/cpx.conf" : "/www/conf/httpd/conf"; open CONF, "$config_file" or do { carp "Could not open $config_file: $!\n"; return(-1); }; seek CONF, 0, 0; ## rewind my @conf = (); while( <CONF> ) { push @conf, $_; } close CONF; my $status = grep(/CPX: force ssl redirect start/i, @conf); return($status); } ############################################################################## package VSAP::Server::Modules::vsap::sys::security::controlpanel; sub handler { my $vsap = shift; my $xmlobj = shift; my $dom = $vsap->dom; my $sslr = $xmlobj->child('ssl_redirect') ? $xmlobj->child('ssl_redirect')->value : ''; # are we changing stuff? my $is_edit = ($sslr ne ''); if ($is_edit) { ## check for server admin unless ($vsap->{server_admin}) { $vsap->error($_ERR{ERR_NOTAUTHORIZED} => "Not authorized to set security preferences"); return; } } # handle ssl redirect change request (if made) my $ssl_redirect_status; my $ssls = VSAP::Server::Modules::vsap::sys::security::_controlpanel_ssl_redirect_status(); if ( (($sslr eq "disable") && ($ssls)) || (($sslr eq "enable") && (!$ssls)) ) { REWT: { local $> = $) = 0; ## regain privileges for a moment VSAP::Server::Modules::vsap::sys::security::_controlpanel_ssl_redirect_modify($sslr); $ssls = $ssls ? 0 : 1; # invert status $ssl_redirect_status = $ssls ? "enabled" : "disabled"; # add a trace to the message log VSAP::Server::Modules::vsap::logger::log_message("$vsap->{username} $ssl_redirect_status ssl_redirect"); # restart apache $vsap->need_apache_restart(); } } else { $ssl_redirect_status = $ssls ? "enabled" : "disabled"; } # build return dom my $root_node = $dom->createElement('vsap'); $root_node->setAttribute(type => 'sys:security:controlpanel'); $root_node->appendTextChild(ssl_redirect => $ssl_redirect_status); $dom->documentElement->appendChild($root_node); return; } ############################################################################## 1; __END__ =head1 NAME VSAP::Server::Modules::vsap::sys::security - VSAP module for managing Control Panel security policies =head1 SYNOPSIS use VSAP::Server::Modules::vsap::sys::security; blah blah blah =head1 DESCRIPTION =head2 EXPORT None by default. =head1 SEE ALSO =head1 AUTHOR Rus Berrett, E<lt>rus@berrett.orgE<gt> =head1 COPYRIGHT AND LICENSE Copyright (C) 2011 by MYNAMESERVER, LLC No part of this module may be duplicated in any form without written consent of the copyright holder. =cut
opencpx/opencpx
modules/VSAP-Server-Modules-vsap-sys-security/lib/VSAP/Server/Modules/vsap/sys/security.pm
Perl
apache-2.0
5,217
#$Id: sortEachShutdownTime.pl,v 1.1 2002-02-25 16:48:04 wilsonp Exp $ #!/usr/remote/bin/perl $header = <STDIN>; $sep = <STDIN>; chop($sep); @lines = <STDIN>; $total = $lines[$#lines]; @isotopes = @lines[0..$#lines-2]; $columns = split(/\s+/,$total)-1; $header = expand_header($columns,$header); $total = expand_total($columns,$total); for ($idx=1;$idx<=$columns;$idx++) { @sorted = sort by_column @isotopes; add_column(extract_column($idx,@sorted)); } print "$header\n$sep$sep\n$total\n$sep$sep\n"; print join("\n",@output) . "\n"; sub expand_total { my ($cols,$tot) = @_; my ($text,@totals) = split(/\s+/,$tot); my $new_tot = "$text\t$totals[0]"; for ($col=1;$col<$cols;$col++) { $new_tot .= "\t$text\t$totals[$col]"; } return $new_tot; } sub expand_header { my ($cols,$head) = @_; my ($col, $new_head); $new_head = "isotope\tshutdown"; for ($col=0;$col<$cols-1;$col++) { $header =~ /([0-9]+ [smhdwyc])/g; $new_head .= sprintf("\tisotope\t%10s",$1); } return $new_head; } sub add_column { my @new_column = @_; my $linNum; #print "$#output, $#new_column\n"; if ($#output < 0) { @output = @new_column; } else { for ($linNum=0;$linNum<=$#new_column;$linNum++) { $output[$linNum] .= "\t" . $new_column[$linNum]; } } } sub extract_column { my $idx = shift(@_); my @data = @_; my ($linNum,$isotope,@column); for ($linNum=0;$linNum<=$#data;$linNum++) { ($isotope,@columns) = split(/\s+/,$data[$linNum]); $column[$linNum] = "$isotope\t" . $columns[$idx-1]; #print "$linNum/$#data:\t$column[$linNum]\n"; } #print join("\n",@column) . "\n"; return @column; } sub by_column { $keyA = (split(/\s+/,$a))[$idx]; $keyB = (split(/\s+/,$b))[$idx]; $keyB <=> $keyA; } sub max { my ($a,$b) = @_; if ($a > $b) { return $a; } else { return $b; } }
elliottbiondo/ALARA
tools/sortEachShutdownTime.pl
Perl
bsd-3-clause
1,928
# $Id: RFC2806.pm,v 2.102 2008/05/23 21:30:10 abigail Exp $ package Regexp::Common::URI::RFC2806; use strict; local $^W = 1; use Regexp::Common::URI::RFC1035 qw /$domain/; use Regexp::Common::URI::RFC2396 qw /$unreserved $escaped $hex/; use vars qw /$VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS @ISA/; use Exporter (); @ISA = qw /Exporter/; ($VERSION) = q $Revision: 2.102 $ =~ /[\d.]+/g; my %vars; BEGIN { $vars {low} = [qw /$dtmf_digit $wait_for_dial_tone $one_second_pause $pause_character $visual_separator $phonedigit $escaped_no_dquote $quoted_string $token_char $token_chars/]; $vars {parts} = [qw /$future_extension/]; $vars {connect} = [qw /$provider_hostname $provider_tag $service_provider $private_prefix $local_network_prefix $global_network_prefix $network_prefix/]; $vars {phone} = [qw /$phone_context_ident $phone_context_tag $area_specifier $post_dial $isdn_subaddress $t33_subaddress $local_phone_number $local_phone_number_no_future $base_phone_number $global_phone_number $global_phone_number_no_future $telephone_subscriber $telephone_subscriber_no_future/]; $vars {fax} = [qw /$fax_local_phone $fax_local_phone_no_future $fax_global_phone $fax_global_phone_no_future $fax_subscriber $fax_subscriber_no_future/]; $vars {modem} = [qw //]; } use vars map {@$_} values %vars; @EXPORT = (); @EXPORT_OK = map {@$_} values %vars; %EXPORT_TAGS = (%vars, ALL => [@EXPORT_OK]); # RFC 2806, URIs for tel, fax & modem. $dtmf_digit = "(?:[*#ABCD])"; $wait_for_dial_tone= "(?:w)"; $one_second_pause = "(?:p)"; $pause_character = "(?:[wp])"; # wait_for_dial_tone | one_second_pause. $visual_separator = "(?:[\\-.()])"; $phonedigit = "(?:[0-9\\-.()])"; # DIGIT | visual_separator $escaped_no_dquote = "(?:%(?:[01]$hex)|2[013-9A-Fa-f]|[3-9A-Fa-f]$hex)"; $quoted_string = "(?:%22(?:(?:%5C(?:$unreserved|$escaped))|" . "$unreserved+|$escaped_no_dquote)*%22)"; # It is unclear wether we can allow only unreserved # characters to unescaped, or can we also use uric # characters that are unescaped? Or pchars? $token_char = "(?:[!'*\\-.0-9A-Z_a-z~]|" . "%(?:2[13-7ABDEabde]|3[0-9]|4[1-9A-Fa-f]|" . "5[AEFaef]|6[0-9A-Fa-f]|7[0-9ACEace]))"; # Only allowing unreserved chars to be unescaped. $token_chars = "(?:(?:[!'*\\-.0-9A-Z_a-z~]+|" . "%(?:2[13-7ABDEabde]|3[0-9]|4[1-9A-Fa-f]|" . "5[AEFaef]|6[0-9A-Fa-f]|7[0-9ACEace]))*)"; $future_extension = "(?:;$token_chars" . "(?:=(?:(?:$token_chars(?:[?]$token_chars)?)|" . "$quoted_string))?)"; $provider_hostname = $domain; $provider_tag = "(?:tsp)"; $service_provider = "(?:;$provider_tag=$provider_hostname)"; $private_prefix = "(?:(?:[!'E-OQ-VX-Z_e-oq-vx-z~]|" . "(?:%(?:2[124-7CFcf]|3[AC-Fac-f]|4[05-9A-Fa-f]|" . "5[1-689A-Fa-f]|6[05-9A-Fa-f]|" . "7[1-689A-Ea-e])))" . "(?:[!'()*\\-.0-9A-Z_a-z~]+|" . "(?:%(?:2[1-9A-Fa-f]|3[AC-Fac-f]|" . "[4-6][0-9A-Fa-f]|7[0-9A-Ea-e])))*)"; $local_network_prefix = "(?:[0-9\\-.()*#ABCDwp]+)"; $global_network_prefix = "(?:[+][0-9\\-.()]+)"; $network_prefix = "(?:$global_network_prefix|$local_network_prefix)"; $phone_context_ident = "(?:$network_prefix|$private_prefix)"; $phone_context_tag = "(?:phone-context)"; $area_specifier = "(?:;$phone_context_tag=$phone_context_ident)"; $post_dial = "(?:;postd=[0-9\\-.()*#ABCDwp]+)"; $isdn_subaddress = "(?:;isub=[0-9\\-.()]+)"; $t33_subaddress = "(?:;tsub=[0-9\\-.()]+)"; $local_phone_number= "(?:[0-9\\-.()*#ABCDwp]+$isdn_subaddress?" . "$post_dial?$area_specifier" . "(?:$area_specifier|$service_provider|" . "$future_extension)*)"; $local_phone_number_no_future = "(?:[0-9\\-.()*#ABCDwp]+$isdn_subaddress?" . "$post_dial?$area_specifier" . "(?:$area_specifier|$service_provider)*)"; $fax_local_phone = "(?:[0-9\\-.()*#ABCDwp]+$isdn_subaddress?" . "$t33_subaddress?$post_dial?$area_specifier" . "(?:$area_specifier|$service_provider|" . "$future_extension)*)"; $fax_local_phone_no_future = "(?:[0-9\\-.()*#ABCDwp]+$isdn_subaddress?" . "$t33_subaddress?$post_dial?$area_specifier" . "(?:$area_specifier|$service_provider)*)"; $base_phone_number = "(?:[0-9\\-.()]+)"; $global_phone_number = "(?:[+]$base_phone_number$isdn_subaddress?" . "$post_dial?" . "(?:$area_specifier|$service_provider|" . "$future_extension)*)"; $global_phone_number_no_future = "(?:[+]$base_phone_number$isdn_subaddress?" . "$post_dial?" . "(?:$area_specifier|$service_provider)*)"; $fax_global_phone = "(?:[+]$base_phone_number$isdn_subaddress?" . "$t33_subaddress?$post_dial?" . "(?:$area_specifier|$service_provider|" . "$future_extension)*)"; $fax_global_phone_no_future = "(?:[+]$base_phone_number$isdn_subaddress?" . "$t33_subaddress?$post_dial?" . "(?:$area_specifier|$service_provider)*)"; $telephone_subscriber = "(?:$global_phone_number|$local_phone_number)"; $telephone_subscriber_no_future = "(?:$global_phone_number_no_future|" . "$local_phone_number_no_future)"; $fax_subscriber = "(?:$fax_global_phone|$fax_local_phone)"; $fax_subscriber_no_future = "(?:$fax_global_phone_no_future|" . "$fax_local_phone_no_future)"; 1; __END__ =pod =head1 NAME Regexp::Common::URI::RFC2806 -- Definitions from RFC2806; =head1 SYNOPSIS use Regexp::Common::URI::RFC2806 qw /:ALL/; =head1 DESCRIPTION This package exports definitions from RFC2806. It's intended usage is for Regexp::Common::URI submodules only. Its interface might change without notice. =head1 REFERENCES =over 4 =item B<[RFC 2616]> Fielding, R., Gettys, J., Mogul, J., Frystyk, H., Masinter, L., Leach, P. and Berners-Lee, Tim: I<Hypertext Transfer Protocol -- HTTP/1.1>. June 1999. =back =head1 HISTORY $Log: RFC2806.pm,v $ Revision 2.102 2008/05/23 21:30:10 abigail Changed email address Revision 2.101 2008/05/23 21:28:02 abigail Changed license Revision 2.100 2003/02/10 21:04:34 abigail Definitions of RFC 2806 =head1 AUTHOR Damian Conway (damian@conway.org) =head1 MAINTAINANCE This package is maintained by Abigail S<(I<regexp-common@abigail.be>)>. =head1 BUGS AND IRRITATIONS Bound to be plenty. =head1 COPYRIGHT This software is Copyright (c) 2001 - 2008, Damian Conway and Abigail. This module is free software, and maybe used under any of the following licenses: 1) The Perl Artistic License. See the file COPYRIGHT.AL. 2) The Perl Artistic License 2.0. See the file COPYRIGHT.AL2. 3) The BSD Licence. See the file COPYRIGHT.BSD. 4) The MIT Licence. See the file COPYRIGHT.MIT. =cut
schwern/Regexp-Common
lib/Regexp/Common/URI/RFC2806.pm
Perl
mit
8,384
package IO::Compress::RawDeflate ; # create RFC1951 # use strict ; use warnings; use bytes; use IO::Compress::Base 2.069 ; use IO::Compress::Base::Common 2.069 qw(:Status ); use IO::Compress::Adapter::Deflate 2.069 ; require Exporter ; our ($VERSION, @ISA, @EXPORT_OK, %DEFLATE_CONSTANTS, %EXPORT_TAGS, $RawDeflateError); $VERSION = '2.069_001'; $RawDeflateError = ''; @ISA = qw(Exporter IO::Compress::Base); @EXPORT_OK = qw( $RawDeflateError rawdeflate ) ; push @EXPORT_OK, @IO::Compress::Adapter::Deflate::EXPORT_OK ; %EXPORT_TAGS = %IO::Compress::Adapter::Deflate::DEFLATE_CONSTANTS; { my %seen; foreach (keys %EXPORT_TAGS ) { push @{$EXPORT_TAGS{constants}}, grep { !$seen{$_}++ } @{ $EXPORT_TAGS{$_} } } $EXPORT_TAGS{all} = $EXPORT_TAGS{constants} ; } %DEFLATE_CONSTANTS = %EXPORT_TAGS; #push @{ $EXPORT_TAGS{all} }, @EXPORT_OK ; Exporter::export_ok_tags('all'); sub new { my $class = shift ; my $obj = IO::Compress::Base::Common::createSelfTiedObject($class, \$RawDeflateError); return $obj->_create(undef, @_); } sub rawdeflate { my $obj = IO::Compress::Base::Common::createSelfTiedObject(undef, \$RawDeflateError); return $obj->_def(@_); } sub ckParams { my $self = shift ; my $got = shift; return 1 ; } sub mkComp { my $self = shift ; my $got = shift ; my ($obj, $errstr, $errno) = IO::Compress::Adapter::Deflate::mkCompObject( $got->getValue('crc32'), $got->getValue('adler32'), $got->getValue('level'), $got->getValue('strategy') ); return $self->saveErrorString(undef, $errstr, $errno) if ! defined $obj; return $obj; } sub mkHeader { my $self = shift ; return ''; } sub mkTrailer { my $self = shift ; return ''; } sub mkFinalTrailer { return ''; } #sub newHeader #{ # my $self = shift ; # return ''; #} sub getExtraParams { my $self = shift ; return getZlibParams(); } use IO::Compress::Base::Common 2.069 qw(:Parse); use Compress::Raw::Zlib 2.069 qw(Z_DEFLATED Z_DEFAULT_COMPRESSION Z_DEFAULT_STRATEGY); our %PARAMS = ( #'method' => [IO::Compress::Base::Common::Parse_unsigned, Z_DEFLATED], 'level' => [IO::Compress::Base::Common::Parse_signed, Z_DEFAULT_COMPRESSION], 'strategy' => [IO::Compress::Base::Common::Parse_signed, Z_DEFAULT_STRATEGY], 'crc32' => [IO::Compress::Base::Common::Parse_boolean, 0], 'adler32' => [IO::Compress::Base::Common::Parse_boolean, 0], 'merge' => [IO::Compress::Base::Common::Parse_boolean, 0], ); sub getZlibParams { return %PARAMS; } sub getInverseClass { return ('IO::Uncompress::RawInflate', \$IO::Uncompress::RawInflate::RawInflateError); } sub getFileInfo { my $self = shift ; my $params = shift; my $file = shift ; } use Fcntl qw(SEEK_SET); sub createMerge { my $self = shift ; my $outValue = shift ; my $outType = shift ; my ($invClass, $error_ref) = $self->getInverseClass(); eval "require $invClass" or die "aaaahhhh" ; my $inf = $invClass->new( $outValue, Transparent => 0, #Strict => 1, AutoClose => 0, Scan => 1) or return $self->saveErrorString(undef, "Cannot create InflateScan object: $$error_ref" ) ; my $end_offset = 0; $inf->scan() or return $self->saveErrorString(undef, "Error Scanning: $$error_ref", $inf->errorNo) ; $inf->zap($end_offset) or return $self->saveErrorString(undef, "Error Zapping: $$error_ref", $inf->errorNo) ; my $def = *$self->{Compress} = $inf->createDeflate(); *$self->{Header} = *$inf->{Info}{Header}; *$self->{UnCompSize} = *$inf->{UnCompSize}->clone(); *$self->{CompSize} = *$inf->{CompSize}->clone(); # TODO -- fix this #*$self->{CompSize} = new U64(0, *$self->{UnCompSize_32bit}); if ( $outType eq 'buffer') { substr( ${ *$self->{Buffer} }, $end_offset) = '' } elsif ($outType eq 'handle' || $outType eq 'filename') { *$self->{FH} = *$inf->{FH} ; delete *$inf->{FH}; *$self->{FH}->flush() ; *$self->{Handle} = 1 if $outType eq 'handle'; #seek(*$self->{FH}, $end_offset, SEEK_SET) *$self->{FH}->seek($end_offset, SEEK_SET) or return $self->saveErrorString(undef, $!, $!) ; } return $def ; } #### zlib specific methods sub deflateParams { my $self = shift ; my $level = shift ; my $strategy = shift ; my $status = *$self->{Compress}->deflateParams(Level => $level, Strategy => $strategy) ; return $self->saveErrorString(0, *$self->{Compress}{Error}, *$self->{Compress}{ErrorNo}) if $status == STATUS_ERROR; return 1; } 1; __END__ =head1 NAME IO::Compress::RawDeflate - Write RFC 1951 files/buffers =head1 SYNOPSIS use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ; my $status = rawdeflate $input => $output [,OPTS] or die "rawdeflate failed: $RawDeflateError\n"; my $z = new IO::Compress::RawDeflate $output [,OPTS] or die "rawdeflate failed: $RawDeflateError\n"; $z->print($string); $z->printf($format, $string); $z->write($string); $z->syswrite($string [, $length, $offset]); $z->flush(); $z->tell(); $z->eof(); $z->seek($position, $whence); $z->binmode(); $z->fileno(); $z->opened(); $z->autoflush(); $z->input_line_number(); $z->newStream( [OPTS] ); $z->deflateParams(); $z->close() ; $RawDeflateError ; # IO::File mode print $z $string; printf $z $format, $string; tell $z eof $z seek $z, $position, $whence binmode $z fileno $z close $z ; =head1 DESCRIPTION This module provides a Perl interface that allows writing compressed data to files or buffer as defined in RFC 1951. Note that RFC 1951 data is not a good choice of compression format to use in isolation, especially if you want to auto-detect it. For reading RFC 1951 files/buffers, see the companion module L<IO::Uncompress::RawInflate|IO::Uncompress::RawInflate>. =head1 Functional Interface A top-level function, C<rawdeflate>, is provided to carry out "one-shot" compression between buffers and/or files. For finer control over the compression process, see the L</"OO Interface"> section. use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ; rawdeflate $input_filename_or_reference => $output_filename_or_reference [,OPTS] or die "rawdeflate failed: $RawDeflateError\n"; The functional interface needs Perl5.005 or better. =head2 rawdeflate $input_filename_or_reference => $output_filename_or_reference [, OPTS] C<rawdeflate> expects at least two parameters, C<$input_filename_or_reference> and C<$output_filename_or_reference>. =head3 The C<$input_filename_or_reference> parameter The parameter, C<$input_filename_or_reference>, is used to define the source of the uncompressed data. It can take one of the following forms: =over 5 =item A filename If the <$input_filename_or_reference> parameter is a simple scalar, it is assumed to be a filename. This file will be opened for reading and the input data will be read from it. =item A filehandle If the C<$input_filename_or_reference> parameter is a filehandle, the input data will be read from it. The string '-' can be used as an alias for standard input. =item A scalar reference If C<$input_filename_or_reference> is a scalar reference, the input data will be read from C<$$input_filename_or_reference>. =item An array reference If C<$input_filename_or_reference> is an array reference, each element in the array must be a filename. The input data will be read from each file in turn. The complete array will be walked to ensure that it only contains valid filenames before any data is compressed. =item An Input FileGlob string If C<$input_filename_or_reference> is a string that is delimited by the characters "<" and ">" C<rawdeflate> will assume that it is an I<input fileglob string>. The input is the list of files that match the fileglob. See L<File::GlobMapper|File::GlobMapper> for more details. =back If the C<$input_filename_or_reference> parameter is any other type, C<undef> will be returned. =head3 The C<$output_filename_or_reference> parameter The parameter C<$output_filename_or_reference> is used to control the destination of the compressed data. This parameter can take one of these forms. =over 5 =item A filename If the C<$output_filename_or_reference> parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the compressed data will be written to it. =item A filehandle If the C<$output_filename_or_reference> parameter is a filehandle, the compressed data will be written to it. The string '-' can be used as an alias for standard output. =item A scalar reference If C<$output_filename_or_reference> is a scalar reference, the compressed data will be stored in C<$$output_filename_or_reference>. =item An Array Reference If C<$output_filename_or_reference> is an array reference, the compressed data will be pushed onto the array. =item An Output FileGlob If C<$output_filename_or_reference> is a string that is delimited by the characters "<" and ">" C<rawdeflate> will assume that it is an I<output fileglob string>. The output is the list of files that match the fileglob. When C<$output_filename_or_reference> is an fileglob string, C<$input_filename_or_reference> must also be a fileglob string. Anything else is an error. See L<File::GlobMapper|File::GlobMapper> for more details. =back If the C<$output_filename_or_reference> parameter is any other type, C<undef> will be returned. =head2 Notes When C<$input_filename_or_reference> maps to multiple files/buffers and C<$output_filename_or_reference> is a single file/buffer the input files/buffers will be stored in C<$output_filename_or_reference> as a concatenated series of compressed data streams. =head2 Optional Parameters Unless specified below, the optional parameters for C<rawdeflate>, C<OPTS>, are the same as those used with the OO interface defined in the L</"Constructor Options"> section below. =over 5 =item C<< AutoClose => 0|1 >> This option applies to any input or output data streams to C<rawdeflate> that are filehandles. If C<AutoClose> is specified, and the value is true, it will result in all input and/or output filehandles being closed once C<rawdeflate> has completed. This parameter defaults to 0. =item C<< BinModeIn => 0|1 >> When reading from a file or filehandle, set C<binmode> before reading. Defaults to 0. =item C<< Append => 0|1 >> The behaviour of this option is dependent on the type of output data stream. =over 5 =item * A Buffer If C<Append> is enabled, all compressed data will be append to the end of the output buffer. Otherwise the output buffer will be cleared before any compressed data is written to it. =item * A Filename If C<Append> is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any compressed data is written to it. =item * A Filehandle If C<Append> is enabled, the filehandle will be positioned to the end of the file via a call to C<seek> before any compressed data is written to it. Otherwise the file pointer will not be moved. =back When C<Append> is specified, and set to true, it will I<append> all compressed data to the output data stream. So when the output is a filehandle it will carry out a seek to the eof before writing any compressed data. If the output is a filename, it will be opened for appending. If the output is a buffer, all compressed data will be appended to the existing buffer. Conversely when C<Append> is not specified, or it is present and is set to false, it will operate as follows. When the output is a filename, it will truncate the contents of the file before writing any compressed data. If the output is a filehandle its position will not be changed. If the output is a buffer, it will be wiped before any compressed data is output. Defaults to 0. =back =head2 Examples To read the contents of the file C<file1.txt> and write the compressed data to the file C<file1.txt.1951>. use strict ; use warnings ; use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ; my $input = "file1.txt"; rawdeflate $input => "$input.1951" or die "rawdeflate failed: $RawDeflateError\n"; To read from an existing Perl filehandle, C<$input>, and write the compressed data to a buffer, C<$buffer>. use strict ; use warnings ; use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ; use IO::File ; my $input = new IO::File "<file1.txt" or die "Cannot open 'file1.txt': $!\n" ; my $buffer ; rawdeflate $input => \$buffer or die "rawdeflate failed: $RawDeflateError\n"; To compress all files in the directory "/my/home" that match "*.txt" and store the compressed data in the same directory use strict ; use warnings ; use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ; rawdeflate '</my/home/*.txt>' => '<*.1951>' or die "rawdeflate failed: $RawDeflateError\n"; and if you want to compress each file one at a time, this will do the trick use strict ; use warnings ; use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError) ; for my $input ( glob "/my/home/*.txt" ) { my $output = "$input.1951" ; rawdeflate $input => $output or die "Error compressing '$input': $RawDeflateError\n"; } =head1 OO Interface =head2 Constructor The format of the constructor for C<IO::Compress::RawDeflate> is shown below my $z = new IO::Compress::RawDeflate $output [,OPTS] or die "IO::Compress::RawDeflate failed: $RawDeflateError\n"; It returns an C<IO::Compress::RawDeflate> object on success and undef on failure. The variable C<$RawDeflateError> will contain an error message on failure. If you are running Perl 5.005 or better the object, C<$z>, returned from IO::Compress::RawDeflate can be used exactly like an L<IO::File|IO::File> filehandle. This means that all normal output file operations can be carried out with C<$z>. For example, to write to a compressed file/buffer you can use either of these forms $z->print("hello world\n"); print $z "hello world\n"; The mandatory parameter C<$output> is used to control the destination of the compressed data. This parameter can take one of these forms. =over 5 =item A filename If the C<$output> parameter is a simple scalar, it is assumed to be a filename. This file will be opened for writing and the compressed data will be written to it. =item A filehandle If the C<$output> parameter is a filehandle, the compressed data will be written to it. The string '-' can be used as an alias for standard output. =item A scalar reference If C<$output> is a scalar reference, the compressed data will be stored in C<$$output>. =back If the C<$output> parameter is any other type, C<IO::Compress::RawDeflate>::new will return undef. =head2 Constructor Options C<OPTS> is any combination of the following options: =over 5 =item C<< AutoClose => 0|1 >> This option is only valid when the C<$output> parameter is a filehandle. If specified, and the value is true, it will result in the C<$output> being closed once either the C<close> method is called or the C<IO::Compress::RawDeflate> object is destroyed. This parameter defaults to 0. =item C<< Append => 0|1 >> Opens C<$output> in append mode. The behaviour of this option is dependent on the type of C<$output>. =over 5 =item * A Buffer If C<$output> is a buffer and C<Append> is enabled, all compressed data will be append to the end of C<$output>. Otherwise C<$output> will be cleared before any data is written to it. =item * A Filename If C<$output> is a filename and C<Append> is enabled, the file will be opened in append mode. Otherwise the contents of the file, if any, will be truncated before any compressed data is written to it. =item * A Filehandle If C<$output> is a filehandle, the file pointer will be positioned to the end of the file via a call to C<seek> before any compressed data is written to it. Otherwise the file pointer will not be moved. =back This parameter defaults to 0. =item C<< Merge => 0|1 >> This option is used to compress input data and append it to an existing compressed data stream in C<$output>. The end result is a single compressed data stream stored in C<$output>. It is a fatal error to attempt to use this option when C<$output> is not an RFC 1951 data stream. There are a number of other limitations with the C<Merge> option: =over 5 =item 1 This module needs to have been built with zlib 1.2.1 or better to work. A fatal error will be thrown if C<Merge> is used with an older version of zlib. =item 2 If C<$output> is a file or a filehandle, it must be seekable. =back This parameter defaults to 0. =item -Level Defines the compression level used by zlib. The value should either be a number between 0 and 9 (0 means no compression and 9 is maximum compression), or one of the symbolic constants defined below. Z_NO_COMPRESSION Z_BEST_SPEED Z_BEST_COMPRESSION Z_DEFAULT_COMPRESSION The default is Z_DEFAULT_COMPRESSION. Note, these constants are not imported by C<IO::Compress::RawDeflate> by default. use IO::Compress::RawDeflate qw(:strategy); use IO::Compress::RawDeflate qw(:constants); use IO::Compress::RawDeflate qw(:all); =item -Strategy Defines the strategy used to tune the compression. Use one of the symbolic constants defined below. Z_FILTERED Z_HUFFMAN_ONLY Z_RLE Z_FIXED Z_DEFAULT_STRATEGY The default is Z_DEFAULT_STRATEGY. =item C<< Strict => 0|1 >> This is a placeholder option. =back =head2 Examples TODO =head1 Methods =head2 print Usage is $z->print($data) print $z $data Compresses and outputs the contents of the C<$data> parameter. This has the same behaviour as the C<print> built-in. Returns true if successful. =head2 printf Usage is $z->printf($format, $data) printf $z $format, $data Compresses and outputs the contents of the C<$data> parameter. Returns true if successful. =head2 syswrite Usage is $z->syswrite $data $z->syswrite $data, $length $z->syswrite $data, $length, $offset Compresses and outputs the contents of the C<$data> parameter. Returns the number of uncompressed bytes written, or C<undef> if unsuccessful. =head2 write Usage is $z->write $data $z->write $data, $length $z->write $data, $length, $offset Compresses and outputs the contents of the C<$data> parameter. Returns the number of uncompressed bytes written, or C<undef> if unsuccessful. =head2 flush Usage is $z->flush; $z->flush($flush_type); Flushes any pending compressed data to the output file/buffer. This method takes an optional parameter, C<$flush_type>, that controls how the flushing will be carried out. By default the C<$flush_type> used is C<Z_FINISH>. Other valid values for C<$flush_type> are C<Z_NO_FLUSH>, C<Z_SYNC_FLUSH>, C<Z_FULL_FLUSH> and C<Z_BLOCK>. It is strongly recommended that you only set the C<flush_type> parameter if you fully understand the implications of what it does - overuse of C<flush> can seriously degrade the level of compression achieved. See the C<zlib> documentation for details. Returns true on success. =head2 tell Usage is $z->tell() tell $z Returns the uncompressed file offset. =head2 eof Usage is $z->eof(); eof($z); Returns true if the C<close> method has been called. =head2 seek $z->seek($position, $whence); seek($z, $position, $whence); Provides a sub-set of the C<seek> functionality, with the restriction that it is only legal to seek forward in the output file/buffer. It is a fatal error to attempt to seek backward. Empty parts of the file/buffer will have NULL (0x00) bytes written to them. The C<$whence> parameter takes one the usual values, namely SEEK_SET, SEEK_CUR or SEEK_END. Returns 1 on success, 0 on failure. =head2 binmode Usage is $z->binmode binmode $z ; This is a noop provided for completeness. =head2 opened $z->opened() Returns true if the object currently refers to a opened file/buffer. =head2 autoflush my $prev = $z->autoflush() my $prev = $z->autoflush(EXPR) If the C<$z> object is associated with a file or a filehandle, this method returns the current autoflush setting for the underlying filehandle. If C<EXPR> is present, and is non-zero, it will enable flushing after every write/print operation. If C<$z> is associated with a buffer, this method has no effect and always returns C<undef>. B<Note> that the special variable C<$|> B<cannot> be used to set or retrieve the autoflush setting. =head2 input_line_number $z->input_line_number() $z->input_line_number(EXPR) This method always returns C<undef> when compressing. =head2 fileno $z->fileno() fileno($z) If the C<$z> object is associated with a file or a filehandle, C<fileno> will return the underlying file descriptor. Once the C<close> method is called C<fileno> will return C<undef>. If the C<$z> object is associated with a buffer, this method will return C<undef>. =head2 close $z->close() ; close $z ; Flushes any pending compressed data and then closes the output file/buffer. For most versions of Perl this method will be automatically invoked if the IO::Compress::RawDeflate object is destroyed (either explicitly or by the variable with the reference to the object going out of scope). The exceptions are Perl versions 5.005 through 5.00504 and 5.8.0. In these cases, the C<close> method will be called automatically, but not until global destruction of all live objects when the program is terminating. Therefore, if you want your scripts to be able to run on all versions of Perl, you should call C<close> explicitly and not rely on automatic closing. Returns true on success, otherwise 0. If the C<AutoClose> option has been enabled when the IO::Compress::RawDeflate object was created, and the object is associated with a file, the underlying file will also be closed. =head2 newStream([OPTS]) Usage is $z->newStream( [OPTS] ) Closes the current compressed data stream and starts a new one. OPTS consists of any of the options that are available when creating the C<$z> object. See the L</"Constructor Options"> section for more details. =head2 deflateParams Usage is $z->deflateParams TODO =head1 Importing A number of symbolic constants are required by some methods in C<IO::Compress::RawDeflate>. None are imported by default. =over 5 =item :all Imports C<rawdeflate>, C<$RawDeflateError> and all symbolic constants that can be used by C<IO::Compress::RawDeflate>. Same as doing this use IO::Compress::RawDeflate qw(rawdeflate $RawDeflateError :constants) ; =item :constants Import all symbolic constants. Same as doing this use IO::Compress::RawDeflate qw(:flush :level :strategy) ; =item :flush These symbolic constants are used by the C<flush> method. Z_NO_FLUSH Z_PARTIAL_FLUSH Z_SYNC_FLUSH Z_FULL_FLUSH Z_FINISH Z_BLOCK =item :level These symbolic constants are used by the C<Level> option in the constructor. Z_NO_COMPRESSION Z_BEST_SPEED Z_BEST_COMPRESSION Z_DEFAULT_COMPRESSION =item :strategy These symbolic constants are used by the C<Strategy> option in the constructor. Z_FILTERED Z_HUFFMAN_ONLY Z_RLE Z_FIXED Z_DEFAULT_STRATEGY =back =head1 EXAMPLES =head2 Apache::GZip Revisited See L<IO::Compress::FAQ|IO::Compress::FAQ/"Apache::GZip Revisited"> =head2 Working with Net::FTP See L<IO::Compress::FAQ|IO::Compress::FAQ/"Compressed files and Net::FTP"> =head1 SEE ALSO L<Compress::Zlib>, L<IO::Compress::Gzip>, L<IO::Uncompress::Gunzip>, L<IO::Compress::Deflate>, L<IO::Uncompress::Inflate>, L<IO::Uncompress::RawInflate>, L<IO::Compress::Bzip2>, L<IO::Uncompress::Bunzip2>, L<IO::Compress::Lzma>, L<IO::Uncompress::UnLzma>, L<IO::Compress::Xz>, L<IO::Uncompress::UnXz>, L<IO::Compress::Lzop>, L<IO::Uncompress::UnLzop>, L<IO::Compress::Lzf>, L<IO::Uncompress::UnLzf>, L<IO::Uncompress::AnyInflate>, L<IO::Uncompress::AnyUncompress> L<IO::Compress::FAQ|IO::Compress::FAQ> L<File::GlobMapper|File::GlobMapper>, L<Archive::Zip|Archive::Zip>, L<Archive::Tar|Archive::Tar>, L<IO::Zlib|IO::Zlib> For RFC 1950, 1951 and 1952 see F<http://www.faqs.org/rfcs/rfc1950.html>, F<http://www.faqs.org/rfcs/rfc1951.html> and F<http://www.faqs.org/rfcs/rfc1952.html> The I<zlib> compression library was written by Jean-loup Gailly F<gzip@prep.ai.mit.edu> and Mark Adler F<madler@alumni.caltech.edu>. The primary site for the I<zlib> compression library is F<http://www.zlib.org>. The primary site for gzip is F<http://www.gzip.org>. =head1 AUTHOR This module was written by Paul Marquess, F<pmqs@cpan.org>. =head1 MODIFICATION HISTORY See the Changes file. =head1 COPYRIGHT AND LICENSE Copyright (c) 2005-2015 Paul Marquess. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
operepo/ope
bin/usr/share/perl5/core_perl/IO/Compress/RawDeflate.pm
Perl
mit
25,761
# # 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 hardware::server::sun::mgmt_cards::mode::showstatus; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::misc; my $thresholds = [ ['Faulted', 'CRITICAL'], ['Degraded', 'WARNING'], ['Deconfigured', 'WARNING'], ['Maintenance', 'OK'], ['Normal', 'OK'], ]; 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 => { "hostname:s" => { name => 'hostname' }, "username:s" => { name => 'username' }, "password:s" => { name => 'password' }, "timeout:s" => { name => 'timeout', default => 30 }, "command-plink:s" => { name => 'command_plink', default => 'plink' }, "threshold-overload:s@" => { name => 'threshold_overload' }, "exclude:s@" => { name => 'exclude' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (!defined($self->{option_results}->{hostname})) { $self->{output}->add_option_msg(short_msg => "Need to specify a hostname."); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{username})) { $self->{output}->add_option_msg(short_msg => "Need to specify a username."); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{password})) { $self->{output}->add_option_msg(short_msg => "Need to specify a password."); $self->{output}->option_exit(); } $self->{overload_th} = []; foreach my $val (@{$self->{option_results}->{threshold_overload}}) { if ($val !~ /^(.*?),(.*)$/) { $self->{output}->add_option_msg(short_msg => "Wrong threshold-overload option '" . $val . "'."); $self->{output}->option_exit(); } my ($status, $filter) = ($1, $2); if ($self->{output}->is_litteral_status(status => $status) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong threshold-overload status '" . $val . "'."); $self->{output}->option_exit(); } push @{$self->{overload_th}}, {filter => $filter, status => $status}; } } sub get_severity { my ($self, %options) = @_; my $status = 'unknown'; # default foreach (@{$self->{overload_th}}) { if ($options{value} =~ /$_->{filter}/msi) { $status = $_->{status}; return $status; } } foreach (@{$thresholds}) { if ($options{value} =~ /$$_[0]/msi) { $status = $$_[1]; return $status; } } return $status; } sub check_exclude { my ($self, %options) = @_; foreach (@{$self->{option_results}->{exclude}}) { if ($options{value} =~ /$_/i) { $self->{output}->output_add(long_msg => sprintf("Skip Component '%s'", $options{value})); return 1; } } return 0; } sub check_tree { my ($self) = @_; my $total_components = 0; my @stack = ({ indent => 0, long_instance => '', long_status => ''}); while ($self->{stdout} =~ /^([* \t]+)(.*)\s+Status:(.+?);/mg) { my ($indent, $unit_number, $status) = (length($1), $2, $3); my ($long_instance, $long_status); while ($indent <= $stack[$#stack]->{indent}) { pop @stack; } $long_instance = $stack[$#stack]->{long_instance} . '>' . $unit_number; $long_status = $stack[$#stack]->{long_status} . ' > ' . $unit_number . ' Status:' . $status; if ($indent > $stack[$#stack]->{indent}) { push @stack, { indent => $indent, long_instance => $stack[$#stack]->{long_instance} . '>' . $unit_number, long_status => $stack[$#stack]->{long_status} . ' > ' . $unit_number . ' Status:' . $status }; } next if ($self->check_exclude(value => $long_instance)); my $exit = $self->get_severity(value => $status); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Component '%s' status is '%s'", $unit_number, $status)); } $self->{output}->output_add(long_msg => sprintf("Component '%s' status is '%s' [%s] [%s]", $unit_number, $status, $long_instance, $long_status)); $total_components++; } $self->{output}->output_add(severity => 'OK', short_msg => sprintf("All %s components are ok.", $total_components) ); } sub run { my ($self, %options) = @_; my ($lerror, $exit_code); ###### # Command execution ###### ($lerror, $self->{stdout}, $exit_code) = centreon::plugins::misc::backtick( command => $self->{option_results}->{command_plink}, timeout => $self->{option_results}->{timeout}, arguments => ['-batch', '-l', $self->{option_results}->{username}, '-pw', $self->{option_results}->{password}, $self->{option_results}->{hostname}, 'showhardconf'], wait_exit => 1, redirect_stderr => 1 ); $self->{stdout} =~ s/\r//g; if ($lerror <= -1000) { $self->{output}->output_add(severity => 'UNKNOWN', short_msg => $self->{stdout}); $self->{output}->display(); $self->{output}->exit(); } if ($exit_code != 0) { $self->{stdout} =~ s/\n/ - /g; $self->{output}->output_add(severity => 'UNKNOWN', short_msg => "Command error: $self->{stdout}"); $self->{output}->display(); $self->{output}->exit(); } $self->check_tree(); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check Sun Mxxxx (M3000, M4000,...) Hardware (through XSCF). =over 8 =item B<--hostname> Hostname to query. =item B<--username> ssh username. =item B<--password> ssh password. =item B<--command-plink> Plink command (default: plink). Use to set a path. =item B<--timeout> Timeout in seconds for the command (Default: 30). =item B<--threshold-overload> Set to overload default threshold values (syntax: status,regexp) It used before default thresholds (order stays). Example: --threshold-overload='UNKNOWN,Normal' =item B<--exclude> Filter components (multiple) (can be a regexp). Example: --exclude='MEM#2B' --exclude='MBU_A>MEM#0B'. =back =cut
nichols-356/centreon-plugins
hardware/server/sun/mgmt_cards/mode/showstatus.pm
Perl
apache-2.0
8,328
=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::Compara::RunnableDB::GeneTrees::GeneGainLossCommon =head1 DESCRIPTION This RunnableDB calculates the dynamics of a GeneTree family (based on the tree obtained and the CAFE software) in terms of gains losses per branch tree. It needs a CAFE-compliant species tree. =head1 INHERITANCE TREE Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with an underscore (_) =cut package Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::GeneGainLossCommon; use strict; use warnings; use Data::Dumper; use Bio::EnsEMBL::Compara::Graph::NewickParser; use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable'); sub get_tree_string_from_mlss_tag { my ($self) = @_; my $mlss_id = $self->param('mlss_id'); my $sql = "SELECT value FROM method_link_species_set_tag WHERE tag = 'cafe_tree_string' AND method_link_species_set_id = ?"; my $sth = $self->compara_dba->dbc->prepare($sql); $sth->execute($mlss_id); my ($cafe_tree_string) = $sth->fetchrow_array(); $sth->finish; print STDERR "CAFE_TREE_STRING: $cafe_tree_string\n" if ($self->debug()); return $cafe_tree_string; } sub get_cafe_tree_from_string { my ($self) = @_; my $cafe_tree_string = $self->param('species_tree_string'); print STDERR "$cafe_tree_string\n" if ($self->debug()); my $cafe_tree = Bio::EnsEMBL::Compara::Graph::NewickParser::parse_newick_into_tree($cafe_tree_string, 'Bio::EnsEMBL::Compara::SpeciesTreeNode'); $self->param('cafe_tree', $cafe_tree); return; } sub load_split_genes { my ($self) = @_; my $member_id_to_gene_split_id; my $gene_split_id_to_member_ids; my $sql = "SELECT seq_member_id, gene_split_id FROM split_genes"; my $sth = $self->compara_dba->dbc->prepare($sql); $sth->execute(); my $n_split_genes = 0; while (my ($seq_member_id, $gene_split_id) = $sth->fetchrow_array()) { $n_split_genes++; $member_id_to_gene_split_id->{$seq_member_id} = $gene_split_id; push @{$gene_split_id_to_member_ids->{$gene_split_id}}, $seq_member_id; } if ($n_split_genes == 0) { $self->param('no_split_genes', 1); } $self->param('member_id_to_gene_split_id', $member_id_to_gene_split_id); $self->param('gene_split_id_to_member_ids', $gene_split_id_to_member_ids); return; } sub filter_split_genes { my ($self, $all_members) = @_; my $member_id_to_gene_split_id = $self->param('member_id_to_gene_split_id'); my $gene_split_id_to_member_ids = $self->param('gene_split_id_to_member_ids'); my %members_to_delete = (); my @filtered_members; for my $member (@$all_members) { my $seq_member_id = $member->dbID; if ($members_to_delete{$seq_member_id}) { delete $members_to_delete{$seq_member_id}; print STDERR "$seq_member_id has been removed because of split_genes filtering\n" if ($self->debug()); next; } if (exists $member_id_to_gene_split_id->{$seq_member_id}) { my $gene_split_id = $member_id_to_gene_split_id->{$seq_member_id}; my @member_ids_to_delete = grep {$_ ne $seq_member_id} @{$gene_split_id_to_member_ids->{$gene_split_id}}; for my $new_member_to_delete (@member_ids_to_delete) { $members_to_delete{$new_member_to_delete} = 1; } } push @filtered_members, $member; } if (scalar keys %members_to_delete) { my $msg = "Still have some members to delete!: \n"; $msg .= Dumper \%members_to_delete; die $msg; } return [@filtered_members]; } sub get_all_trees { my ($self, $species) = @_; my $adaptor = $self->param('adaptor'); my $all_trees = $adaptor->fetch_all(-tree_type => 'tree', -clusterset_id => 'default'); print STDERR scalar @$all_trees, " trees to process\n" if ($self->debug()); return sub { # $self is the outer var my $tree = shift @$all_trees; return undef unless ($tree); $tree->preload(); my $root_id = $tree->root_id; my $name = $root_id; my $full_tree_members = $tree->get_all_leaves(); my $tree_members = $self->param('no_split_genes') ? $full_tree_members : $self->filter_split_genes($full_tree_members); my %species; for my $member (@$tree_members) { my $sp; eval {$sp = $member->genome_db->name}; next if ($@); $sp =~ s/_/\./g; $species{$sp}++; } my @flds = map { { "species" => $_, "members" => $species{$_} || 0 } } @$species; $tree->release_tree(); return ($name, $root_id, [@flds]); }; } sub get_normalized_table { my ($self, $table, $n) = @_; my ($header, @table) = split /\n/, $table; my @species = split /\t/, $header; ## n_headers method has to be defined in the parent class, ## allowing for differentiation between 2-column names (ids, and names) ## as is needed by CAFE and 1-column names needed by badiRate my @headers = @species[0..$self->n_headers-1]; @species = @species[$self->n_headers..$#species]; my $data; my $fams; for my $row (@table) { chomp $row; my @flds = split/\t/, $row; push @$fams, [@flds]; for my $i ($self->n_headers..$#flds) { push @{$data->{$species[$i-$self->n_headers]}}, $flds[$i]; } } my $means_a; for my $sp (@species) { my $mean = mean(@{$data->{$sp}}); my $stdev = stdev($mean, @{$data->{$sp}}); # $means->{$sp} = {mean => $mean, stdev => $stdev}; push @$means_a, {mean => $mean, stdev => $stdev}; } my $newTable = join "\t", @headers, @species; $newTable .= "\n"; my $nfams = 0; for my $famdata (@$fams) { my $v = 0; for my $i (0 .. $#species) { my $vmean = $means_a->[$i]->{mean}; my $vstdev = $means_a->[$i]->{stdev}; my $vreal = $famdata->[$i+2]; $v++ if (($vreal > ($vmean - $vstdev/$n)) && ($vreal < ($vmean + $vstdev/$n))); } if ($v == scalar(@species)) { $newTable .= join "\t", @$famdata; $newTable .= "\n"; $nfams++; } } print STDERR "$nfams families written in tbl file\n" if ($self->debug()); $self->param('table', $newTable); return; } sub mean { my (@items) = @_; return sum(@items) / (scalar @items); } sub sum { my (@items) = @_; my $res; for my $next (@items) { die unless (defined $next); $res += $next; } return $res; } sub stdev { my ($mean, @items) = @_; my $var = 0; my $n_items = scalar @items; for my $item (@items) { $var += ($mean - $item) * ($mean - $item); } return sqrt($var / (scalar @items)); } 1;
ckongEbi/ensembl-compara
modules/Bio/EnsEMBL/Compara/RunnableDB/GeneTrees/GeneGainLossCommon.pm
Perl
apache-2.0
7,901
package API::Division; use UI::Utils; use UI::Division; use Mojo::Base 'Mojolicious::Controller'; use Data::Dumper; use JSON; use MojoPlugins::Response; sub index { my $self = shift; my @data; my $orderby = $self->param('orderby') || "name"; my $rs_data = $self->db->resultset("Division")->search( undef, { order_by => 'me.' . $orderby } ); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "name" => $row->name, "lastUpdated" => $row->last_updated } ); } $self->success( \@data ); } sub show { my $self = shift; my $id = $self->param('id'); my $rs_data = $self->db->resultset("Division")->search( { id => $id } ); my @data = (); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "name" => $row->name, "lastUpdated" => $row->last_updated } ); } $self->success( \@data ); } sub update { my $self = shift; my $id = $self->param('id'); my $params = $self->req->json; if ( !&is_oper($self) ) { return $self->forbidden(); } my $division = $self->db->resultset('Division')->find( { id => $id } ); if ( !defined($division) ) { return $self->not_found(); } if ( !defined($params) ) { return $self->alert("parameters must be in JSON format."); } if ( !defined( $params->{name} ) ) { return $self->alert("Division name is required."); } my $values = { name => $params->{name} }; my $rs = $division->update($values); if ($rs) { my $response; $response->{id} = $rs->id; $response->{name} = $rs->name; $response->{lastUpdated} = $rs->last_updated; &log( $self, "Updated Division name '" . $rs->name . "' for id: " . $rs->id, "APICHANGE" ); return $self->success( $response, "Division update was successful." ); } else { return $self->alert("Division update failed."); } } sub create { my $self = shift; my $params = $self->req->json; if ( !defined($params) ) { return $self->alert("parameters must be in JSON format, please check!"); } if ( !&is_oper($self) ) { return $self->alert( { Error => " - You must be an ADMIN or OPER to perform this operation!" } ); } my $name = $params->{name}; if ( !defined($name) ) { return $self->alert("division 'name' is not given."); } #Check for duplicate division name my $existing_division = $self->db->resultset('Division')->search( { name => $name } )->get_column('name')->single(); if ($existing_division) { return $self->alert("A division with name \"$name\" already exists."); } my $insert = $self->db->resultset('Division')->create( { name => $name } ); $insert->insert(); my $response; my $rs = $self->db->resultset('Division')->find( { id => $insert->id } ); if ( defined($rs) ) { $response->{id} = $rs->id; $response->{name} = $rs->name; return $self->success($response); } return $self->alert("create division failed."); } sub delete { my $self = shift; my $id = $self->param('id'); if ( !&is_oper($self) ) { return $self->forbidden(); } my $division = $self->db->resultset('Division')->find( { id => $id } ); if ( !defined($division) ) { return $self->not_found(); } my $regions = $self->db->resultset('Region')->find( { division => $division->id } ); if ( defined($regions) ) { return $self->alert("This division is currently used by regions."); } my $rs = $division->delete(); if ($rs) { return $self->success_message("Division deleted."); } else { return $self->alert( "Division delete failed." ); } } 1;
dneuman64/traffic_control
traffic_ops/app/lib/API/Division.pm
Perl
apache-2.0
3,530
package DDG::Goodie::Wavelength; # ABSTRACT: Frequency to wavelength use utf8; use DDG::Goodie; use constant SPEED_OF_LIGHT => 299792458; #meters/second use constant MULTIPLIER => { hz => 1, khz => 10**3, mhz => 10**6, ghz => 10**9, thz => 10**12 }; use constant FORMAT_UNITS => { hz => 'Hz', khz => 'kHz', mhz => 'MHz', ghz => 'GHz', thz => 'THz' }; zci answer_type => "wavelength"; zci is_cached => 1; # Triggers triggers any => "λ", "wavelength", "lambda"; # Handle statement handle remainder => sub { my ($query) = @_; my ($freq,$units) = $query =~ m/([\d\.]+)\s*((k|M|G|T)?hz)/i; return unless $freq and $units; my ($vf) = $query =~ m/\bvf[ =]([\d\.]+)/i; $vf = 1 if (!$vf or $vf>1 or $vf<0); my $velocity_text = ($vf == 1 ? '' : "$vf × ").'Speed of light in a vacuum'; my $mul = MULTIPLIER->{lc($units)}; my $hz_freq = $freq * $mul * (1/$vf); my $output_value = (SPEED_OF_LIGHT / $hz_freq); my $output_units = 'Meters'; # Express higher freqs in cm/mm. # eg UHF 70cm band, microwave 3mm, etc if ($output_value<1) { $output_units = 'Centimeters'; $output_value *= 100; if ($output_value<1) { $output_units = 'Millimeters'; $output_value *= 10; } } my $result_text = "λ = $output_value $output_units"; my $operation_text = "Wavelength of $freq ".FORMAT_UNITS->{lc($units)}." ($velocity_text)"; return $result_text, structured_answer => { data => { title => $result_text, subtitle => $operation_text }, templates => { group => 'text' } }; }; 1;
urohit011/zeroclickinfo-goodies
lib/DDG/Goodie/Wavelength.pm
Perl
apache-2.0
1,711
package DDG::Spice::Betterific; # ABSTRACT: Crowd-sourced innovation ideas use strict; use DDG::Spice; name "betterific"; description "Search Betterific for smart, innovative ideas to improve products and services."; source "betterific"; primary_example_queries "betterific Arby's"; secondary_example_queries "betterif General Electric"; category "special"; topics "entertainment", "everyday", "social", "special_interest"; code_url "https://github.com/bradcater/zeroclickinfo-spice/blob/master/lib/DDG/Spice/Betterific.pm"; attribution github => ["https://github.com/bradcater", "Brad Cater"], twitter => ["https://twitter.com/bradcater", "Brad Cater"]; triggers startend => "betterif", "better if", "betterific"; spice to => 'http://betterific.com/api/search/all?q=$1&page=1&per_page=2'; spice wrap_jsonp_callback => 1; handle remainder => sub { # If the query isn't blank, then use it for the API query. return $_ if length($_) > 0; return '' if $_ eq ''; return; }; 1;
jyounker/zeroclickinfo-spice
lib/DDG/Spice/Betterific.pm
Perl
apache-2.0
1,009
package CGI::OptimalQuery::EmailMergeTool; use strict; use warnings; use CGI(); use Mail::Sendmail(); use JSON::XS; no warnings qw( uninitialized ); =comment A ready to use tool that enhances CGI::OptimalQuery to allow users to create email merges from recordsets. EmailMergeTool also integrates with the AutomatedActionTool to allow users to run automated email merges based off a user configured recordset. use CGI::OptimalQuery::EmailMergeTool(); my $schema = { 'select' => { .. }, 'joins' => { .. }, 'tools' => { 'emailmerge' => { title => 'Email Merge', # default shown, only need to include the ones you want to override options => { # set this to 1 to make the to field readonly readonly_to => 0, # default email to # this must be defined if readonly_to is true # note: template vars are allowed. If template variable is used, it # must be a valid email address. # example: to => '<SESSION_USER_EMAIL>' to => '', # specify the default subject # note: template vars are allowed subject => '', # specify the email from address. the user cannot override this # note: template vars are NOT allowed # this must be defined! from => undef, # set this to 1 to make the from field readonly readonly_from => 0, # specify the default greeting # note: template vars are allowed greeting => '', # specify the default body # note: template vars are allowed body => '', # specify the default footer # note: template vars are allowed here footer => '', # specify additional template vars you would like made available in # the mailmerge template_vars => { # example: 'SESSION_USER_EMAIL' => get_current_session_user_email() }, # do not send more then 50 emails at any one time max_emails => 50, # default implementation using Mail::Sendmail is provided sendallemails => sub { my ($emailAr) = @_; ... } }, handler => \&CGI::OptimalQuery::EmailMergeTool::handler } } }; CGI::OptimalQuery->new($schema)->output(); =cut sub escapeHTML { return defined $_[0] ? CGI::escapeHTML($_[0]) : ''; } # simple function to fill data into a template string in the following format # filltemplate("hi <NAME>", { NAME => "bob" }) sub filltemplate { my ($template, $dat) = @_; my $rv = ''; foreach my $part (split /(\<\w+\>)/, $template) { if ($part =~ /^\<(\w+)\>$/) { my $k = uc($1); $rv .= $$dat{$k}; } else { $rv .= $part; } } return $rv; } # create the email merges from the data and return an array ref of emails sub create_emails { my ($o, $opts) = @_; my $q = $$o{q}; my %emails; # copy template vars my %dat = %{ $$opts{template_vars} }; my $from = $q->param('emailmergefrom'); # for each row in query, merge record into templates while (my $rec = $o->sth->fetchrow_hashref()) { @dat{keys %$rec} = values %$rec; my $to = filltemplate(scalar($q->param('emailmergeto')) ||'', \%dat); my $subject = filltemplate(scalar($q->param('emailmergesubject')), \%dat); my $greeting = filltemplate(scalar($q->param('emailmergegreeting')), \%dat); my $body = filltemplate(scalar($q->param('emailmergebody')), \%dat); my $footer = filltemplate(scalar($q->param('emailmergefooter')), \%dat); my @to = map { s/\s//g; lc($_) } split /\,/, $to; foreach my $emailAddress (@to) { $body = "\n".$body if $emails{$to}{$subject}{$greeting}{$footer} ne '' && $emails{$to}{$subject}{$greeting}{$footer} !~ /\n\s*$/s; $emails{$to}{$subject}{$greeting}{$footer} .= $body; } } my @rv; while (my ($to,$x) = each %emails) { while (my ($subject,$x) = each %$x) { while (my ($greeting,$x) = each %$x) { $greeting .= "\n" if $greeting; while (my ($footer,$body) = each %$x) { $body .= "\n" if $footer; push @rv, { to => $to, from => $from, subject => $subject, body => $greeting.$body.$footer }; } } } } return \@rv; } sub sendallemails { my ($emails) = @_; foreach my $email (@$emails) { $$email{rv} = Mail::Sendmail::sendmail(%$email); if (! $$email{rv}) { $$email{'error'} = $Mail::Sendmail::log; } } return undef; } sub handler { my ($o) = @_; my $q = $$o{q}; my $opts = $$o{schema}{tools}{emailmerge}{options}; # set default options $$opts{to} ||= ''; $q->param('emailmergeto', $$opts{to}) if $$opts{readonly_to}; $$opts{from} ||= ''; $q->param('emailmergefrom', $$opts{from}) if $$opts{readonly_from}; $$opts{subject} ||= ''; $$opts{greeting} ||= ''; $$opts{body} ||= ''; $$opts{footer} ||= ''; $$opts{max_emails} = 50 unless $$opts{max_emails} =~ /^\d+$/; $$opts{template_vars} ||= {}; $$opts{sendallemails} ||= \&sendallemails; # process action my $act = $$o{q}->param('act'); # execute preview if ($act eq 'preview') { # check required fields return "enter to email address" if $$o{q}->param('emailmergeto') eq ''; return "enter an email subject" if $$o{q}->param('emailmergesubject') eq ''; return "enter email from address" if $$o{q}->param('emailmergefrom') eq ''; return "enter an email body" if $$o{q}->param('emailmergebody') eq ''; my $emailAr = create_emails($o, $opts); my $totalEmails = $#$emailAr + 1; return "Total emails ($totalEmails) exceeds maximum limit of ($$opts{max_emails}). Please reduce the amount of emails sent." if ($#$emailAr + 1) > $$opts{max_emails}; my $buf = "<p><strong>Total email ($totalEmails)</strong></p>"; foreach my $email (@$emailAr) { $buf .= "<div><strong>To: </strong>".escapeHTML($$email{to})."<br><strong>Subject: </strong>".escapeHTML($$email{subject})."<p class=oqemailmergepreviewbody>".escapeHTML($$email{body})."</p></div><hr>"; } return " <div class=OQemailmergeview> <div class=OQemailmergemsgs> $buf </div> <p> <button type=button class=OQEmailMergePreviewBackBut>back</button> <button type=button class=OQEmailMergeSendEmailBut>send email</button></div> </p> </div>"; } # delete the auto action elsif ($act eq 'deleteautoaction') { my $id = int($$o{q}->param('id')); if ($id) { $$o{dbh}->do("DELETE FROM oq_autoaction WHERE id=?", undef, $id); return "autoaction deleted"; } else { return "missing id param"; } } # save the auto action elsif ($act eq 'saveautoaction') { # check required fields return "enter to email address" if $$o{q}->param('emailmergeto') eq ''; return "enter an email subject" if $$o{q}->param('emailmergesubject') eq ''; return "enter email from address" if $$o{q}->param('emailmergefrom') eq ''; return "enter an email body" if $$o{q}->param('emailmergebody') eq ''; my $id = $$o{q}->param('oq_autoaction_id'); my $trigger_mask = int($$o{q}->param('automateemailmergetype')); # get interval minutes my $min = int($q->param('automateemailmergerepeatintervalmin')); $min = 15 if $min < 15; # create a human description of the action my $user_title; { my @x; if ($trigger_mask & 1) { push @x, 'all'; } if ($trigger_mask & 2) { push @x, 'modified'; } if ($trigger_mask & 4) { push @x, 'created'; } my $trigger_descr = join('OR', @x); $user_title = "Send email to: ".$q->param('emailmergeto')."; subject: ".$q->param('emailmergesubject')." for $trigger_descr records in '$$o{schema}{title}'"; $user_title .= " matching filter: ".$q->param('filter_descr') if $q->param('filter_descr') ne ''; $user_title .= " every $min minutes."; } # save the params my $params; { my $x = {}; my @names = $$o{q}->param(); foreach my $n (@names) { $$x{$n} = $$o{q}->param($n); } delete $$x{page}; delete $$x{rows_page}; delete $$x{on_select}; delete $$x{act}; $params = encode_json($x); } # save record in database if ($id) { $$o{dbh}->do("UPDATE oq_autoaction SET uri=?, oq_title=?, user_title=?, params=?, repeat_interval_min=?, trigger_mask=?, error_txt=NULL WHERE id=?", undef, $$o{schema}{URI},$$o{schema}{title},$user_title,$params,$min,$trigger_mask,$id); } else { my @dt = localtime; my $now = ($dt[5] + 1900).'-'.sprintf('%02d',$dt[4] + 1).'-'.sprintf('%02d',$dt[3]).' '.sprintf('%02d',$dt[2]).':'.sprintf('%02d',$dt[1]); $$o{dbh}->do("INSERT INTO oq_autoaction (uri,oq_title,user_title,params,repeat_interval_min,trigger_mask,last_run_dt,start_dt) VALUES (?,?,?,?,?,?,?,?)", undef, $$o{schema}{URI},$$o{schema}{title},$user_title,$params,$min,$trigger_mask,$now,$now); } return "<strong>saved automated action:</strong> ".escapeHTML($user_title); } # execute an emailmerge given the configured params elsif ($act eq 'execute') { my $num_ok = 0; my $num_err = 0; my %errs; my $emailAr = create_emails($o, $opts); $$opts{sendallemails}->($emailAr); # look through sent emails, get stats foreach my $email (@$emailAr) { if ($$email{error}) { $num_err++; $errs{$$email{error}}++; } else { $num_ok++; } } my $rv = "<p>Sent: $num_ok; Errors: $num_err</p>"; if ($num_err > 0) { $rv .= "<p><h4>Error Messages</h4><table>"; foreach my $msg (sort %errs) { my $cnt = $errs{$msg}; $rv .= "<tr><td>".escapeHTML($msg)."</td><td>".escapeHTML($cnt)."</td></tr>"; } $rv .= "</table></p>"; } return "<div class=OQemailmergeview>".$rv."</div>"; } # render the default view my $buf; # set default params if we are creating a new record if (! defined $q->param('emailmergeto')) { $q->param('emailmergeto', $$opts{to}); $q->param('emailmergesubject', $$opts{subject}); $q->param('emailmergebody', $$opts{body}); $q->param('emailmergegreeting', $$opts{greeting}); $q->param('emailmergefooter', $$opts{footer}); } # find all template variables my @vars = ( keys %{$$opts{template_vars}}, keys %{$$o{schema}{select}} ); @vars = sort @vars; my $vars = join('', map { "<div class=OQTemplateVar>&lt;".escapeHTML($_)."&gt;</div>" } @vars); my $readonlyto = 'readonly' if $$opts{readonly_to}; my $readonlyfrom = 'readonly' if $$opts{readonly_from}; $buf .= " <div class=OQemailmergetool> <div class=OQemailmergeform> <p> <label>to</label><br> <input type=text name=emailmergeto value='".escapeHTML($$o{q}->param('emailmergeto'))."' $readonlyto> <p> <label>from</label><br> <input type=text name=emailmergefrom value='".escapeHTML($$o{q}->param('emailmergefrom'))."' $readonlyfrom> <p> <label>subject</label><br> <input type=text name=emailmergesubject value='".escapeHTML($$o{q}->param('emailmergesubject'))."'> <p> <label>greeting</label><br> <textarea name=emailmergegreeting>".escapeHTML($$o{q}->param('emailmergegreeting'))."</textarea><br> <small>Enter text that will appear at the top of the email.</small> <p> <label>body</label><br> <textarea name=emailmergebody>".escapeHTML($$o{q}->param('emailmergebody'))."</textarea><br> <small>Multiple emails to the same person with the same subject will have their bodies bundled together.</small> <p> <label>footer</label><br> <textarea name=emailmergefooter>".escapeHTML($$o{q}->param('emailmergefooter'))."</textarea><br> <small>Enter text that will appear at the bottom of the email.</small> <p> <input type=hidden name=oq_autoaction_id value='".escapeHTML($$o{q}->param('oq_autoaction_id'))."'> <label><input type=checkbox name=automateemailmerge value=1"; $buf .= " checked" if $$o{q}->param('automateemailmerge') eq '1'; $buf .= "> Automatically send email</label> for <select name=automateemailmergetype><option value=1>all"; if ($$o{schema}{select}{DTM}) { $buf .= "<option value=2"; $buf .= " selected" if $$o{q}->param('automateemailmergetype') eq '2'; $buf .= ">modified"; } if ($$o{schema}{select}{DTC}) { $buf .= "<option value=4"; $buf .= " selected" if $$o{q}->param('automateemailmergetype') eq '4'; $buf .= ">created"; } if ($$o{schema}{select}{DTC} && $$o{schema}{select}{DTM}) { $buf .= "<option value=6"; $buf .= " selected" if $$o{q}->param('automateemailmergetype') eq '6'; $buf .= ">modified OR created"; } $buf .= "</select> records every <input type=text style='width: 3em;' name=automateemailmergerepeatintervalmin value='" .escapeHTML($$o{q}->param('automateemailmergerepeatintervalmin') || 60)."'> minutes. <p class=EmailMergeCmdBar> <button type=button class=OQEmailMergeDeleteAutoActionBut>delete automatic action</button> <button type=button class=OQEmailMergeSaveAutoActionBut>save automatic action</button> <button type=button class=OQEmailMergePreviewBut>preview</button> </p> </div> <div class=OQemailmergetemplatevars> <h4>Template Variables</h4> <div class=OQemailmergetemplatevarlist> $vars </div> </div> </div> ".' <script> function updateemailmergecmdbar() { if ($("input[name=automateemailmerge]:checked").length==0) { $("button.OQEmailMergePreviewBut").css("visibility","visible"); $("button.OQEmailMergeSaveAutoActionBut").css("visibility","hidden"); $("button.OQEmailMergeDeleteAutoActionBut").css("visibility","hidden"); } else { $("button.OQEmailMergePreviewBut").css("visibility","hidden"); $("button.OQEmailMergeSaveAutoActionBut").css("visibility","visible"); if ($("input[name=oq_autoaction_id]").val()) { $("button.OQEmailMergeDeleteAutoActionBut").css("visibility","visible"); } else { $("button.OQEmailMergeDeleteAutoActionBut").css("visibility","hidden"); } } return true; } $("input[name=automateemailmerge]").click(updateemailmergecmdbar); updateemailmergecmdbar(); </script> '; return $buf; } 1;
gitpan/CGI-OptimalQuery
lib/CGI/OptimalQuery/EmailMergeTool.pm
Perl
mit
14,048
#!/usr/bin/perl # use FindBin qw($Bin); #BEGIN { # $ENV{'LD_LIBRARY_PATH'}.="$Bin/../lib/";# loading bamtools lib # exec($^X, $0, @ARGV); #} $EXT = "$Bin/../../external_bin"; $BAM = shift@ARGV; $BARCODE = $BAM.".AEGIS"; $FA_BWT = shift@ARGV; #just name $FA = shift@ARGV; $GAPFILE = "$Bin/../data/GAP_20140416"; #$GAPFILE = shift@ARGV; #"$Bin/../ManualGap"; ## with chr!! $P = shift@ARGV; use Parallel::ForkManager; $pm=new Parallel::ForkManager(2); =cut if(!(-e $FA)){ if(-e "$FA_BWT.fa"){ $FA = "$FA_BWT.fa"; } elsif(-e "$FA_BWT.fasta"){ $FA = "$FA_BWT.fasta"; } else{ die "fasta reference not found! Provide by -F \n"; } } die "$Bin/../../external_bin directory not working!" unless -x "$Bin/../../external_bin/bowtie"; die "GAP file not found!" unless -e $GAPFILE; die "bam file not exist!" unless -e $BAM; #system("export LD_LIBRARY_PATH=$Bin/../lib/:\$LD_LIBRARY_PATH"); for $i (0 .. 1){ my $pid = $pm->start and next; if($i == 0){ system("$Bin/Pair_bam $BAM > $BARCODE.NEAT"); system("$Bin/superPair $BARCODE.NEAT > $BARCODE.PAIR"); } else{ system("$Bin/Bam_distri $BAM > $BARCODE.soft.fastq"); system("$EXT/bowtie --suppress 6 --quiet --best -v 1 -p $P --un $BARCODE.soft.un.fastq $FA_BWT $BARCODE.soft.fastq $BARCODE.soft.bwt"); system("$EXT/bwa mem -t $P $FA $BARCODE.soft.un.fastq > $BARCODE.soft.un.bwa.sam"); system("cat $BARCODE.soft.un.bwa.sam | $Bin/format_bwa.pl > $BARCODE.bwa_partial_align");#change * system("cat $BARCODE.soft.bwt $BARCODE.bwa_partial_align | $Bin/breakpoint.pl > $BARCODE.all_soft");#change * system("sort -k 1,1 -k 2,2n $BARCODE.all_soft | $Bin/combine_soft.pl | sort -k 1,1 -k 2,2n | $Bin/combine_soft.pl | sort -k 1,1 -k 2,2n | $Bin/combine_soft.pl | sort -k 1,1 -k 2,2n > $BARCODE.SOFT"); my $Num=0; my $N=0; while(1){ open(I,"<$BARCODE.SOFT"); while(<I>){ $N++; } if($N == $Num){ system("rm $BARCODE.SOFT2"); last; } $Num = $N; $N=0; system("mv $BARCODE.SOFT $BARCODE.SOFT2"); system("sort -k 1,1 -k 2,2n $BARCODE.SOFT2 | $Bin/combine_soft.pl | sort -k 1,1 -k 2,2n > $BARCODE.SOFT"); print $Num,"\t",$N,"\n"; } system("$Bin/trans_sort.pl $BARCODE.SOFT > $BARCODE.SOFT_sort"); } $pm->finish; } $pm->wait_all_children; =cut system("cat $BARCODE.SOFT_sort > $BARCODE.SOFT_sort_2"); system("$Bin/combineSuperPair $BARCODE.PAIR $BARCODE.SOFT_sort_2 > $BARCODE.FINAL_SV_"); system("cat $BARCODE.FINAL_SV_ > $BARCODE.FINAL_SV"); system("cat Only_SOFT > $BARCODE.FINAL_SOFT"); system("cat Only_Pair > $BARCODE.FINAL_PAIR"); ## 5 as cutoff system("cat $BARCODE.FINAL_SV $BARCODE.FINAL_SOFT $BARCODE.FINAL_PAIR > $BARCODE.ALL_SV");## del or dup less than 2000 are discarted
ma-compbio/Weaver
Weaver_SV/bin/AEGIS_DREAM.pl
Perl
mit
2,707
use strict; use Data::Dumper; use Bio::KBase::GenomeAnnotation::GenomeAnnotationImpl; use Bio::KBase::HandleService; use JSON::XS; use File::Slurp qw(read_file write_file); use File::Temp ':POSIX'; use IO::File; use Capture::Tiny 'capture'; @ARGV == 2 or @ARGV == 4 or die "Usage: $0 genome-workflow-file output-file [stdout stderr]\n"; our $gwfile = shift; our $out_file = shift; my $stdout_file = shift; my $stderr_file = shift; if ($stdout_file) { my $stdout_fh = IO::File->new($stdout_file, "w+"); my $stderr_fh = IO::File->new($stderr_file, "w+"); capture(\&run, stdout => $stdout_fh, stderr => $stderr_fh); } else { run(); } sub run { my $json = JSON::XS->new->pretty(1); my $impl = Bio::KBase::GenomeAnnotation::GenomeAnnotationImpl->new(); my $hservice = Bio::KBase::HandleService->new(); my $ctx = ContextObj->new; $Bio::KBase::GenomeAnnotation::Service::CallContext = $ctx; open(OF, ">", $out_file) or die "Cannot open $out_file: $!"; my($hobj, $wobj); { my $gtext = read_file($gwfile); $gtext or die "Error reading $gwfile: $!"; my $obj = $json->decode($gtext); ($hobj, $wobj) = @$obj; } print STDERR Dumper($wobj); # # Our genome object is a handle. We need to pull it down and parse. # my $tmp = tmpnam(); print STDERR "tmp is $tmp\n"; $hservice->download($hobj, "" . $tmp); my $gtext = read_file($tmp); my $gobj = $json->decode($gtext); my $out; eval { $out = $impl->run_pipeline($gobj, $wobj); }; if ($@) { print STDERR "FAILURE running pipeline:\n$@\n"; print OF $json->encode({failure => $@}); } else { print OF $json->encode($out); } close(OF); } # # Do a fairly minor emulation of the call context. # We will need to at some point properly configure the auth stuff so that # incoming authentication tokens (via the AWE environment) are propagated # properly. # package ContextObj; use strict; use Data::Dumper; use base 'Class::Accessor'; BEGIN { ContextObj->mk_accessors(qw(user_id client_ip authenticated token module method call_id hostname stderr)); }; sub new { my($class) = @_; my $h = `hostname`; chomp $h; my $self = { hostname => $h }; bless $self, $class; $self->module("run_pipeline"); $self->method("unknown"); my $stderr = ServiceStderrWrapper->new($self); $self->stderr($stderr); return $self; } package ServiceStderrWrapper; use strict; use POSIX; use Time::HiRes 'gettimeofday'; sub new { my($class, $ctx) = @_; my $self = {}; my $dest = $ENV{KBRPC_ERROR_DEST}; my $tag = $ENV{KBRPC_TAG}; my ($t, $us) = gettimeofday(); $us = sprintf("%06d", $us); my $ts = strftime("%Y-%m-%dT%H:%M:%S.${us}Z", gmtime $t); my $name = join(".", $ctx->module, $ctx->method, $ctx->hostname, $ts); if ($dest =~ m,^/,) { # # File destination # my $fh; if ($tag) { $tag =~ s,/,_,g; $dest = "$dest/$tag"; if (! -d $dest) { mkdir($dest); } } if (open($fh, ">", "$dest/$name")) { $self->{file} = "$dest/$name"; $self->{dest} = $fh; } else { warn "Cannot open log file $dest/$name: $!"; } } else { # # Log to string. # my $stderr; $self->{dest} = \$stderr; } bless $self, $class; for my $e (sort { $a cmp $b } keys %ENV) { $self->log_cmd($e, $ENV{$e}); } return $self; } sub redirect { my($self) = @_; if ($self->{dest}) { return("2>", $self->{dest}); } else { return (); } } sub redirect_both { my($self) = @_; if ($self->{dest}) { return(">&", $self->{dest}); } else { return (); } } sub log { my($self, $str) = @_; my $d = $self->{dest}; if (ref($d) eq 'SCALAR') { $$d .= $str . "\n"; return 1; } elsif ($d) { print $d $str . "\n"; return 1; } return 0; } sub log_cmd { my($self, @cmd) = @_; my $d = $self->{dest}; my $str; if (ref($cmd[0])) { $str = join(" ", @{$cmd[0]}); } else { $str = join(" ", @cmd); } if (ref($d) eq 'SCALAR') { $$d .= $str . "\n"; } elsif ($d) { print $d $str . "\n"; } } sub dest { my($self) = @_; return $self->{dest}; } sub text_value { my($self) = @_; if (ref($self->{dest}) eq 'SCALAR') { my $r = $self->{dest}; return $$r; } else { return $self->{file}; } }
kbase/genome_annotation
service-scripts/rast_run_pipeline_local.pl
Perl
mit
4,490
/* Part of Extended Libraries for SWI-Prolog Author: Edison Mera Menendez E-mail: efmera@gmail.com WWW: https://github.com/edisonm/xlibrary Copyright (C): 2014, Process Design Center, Breda, The Netherlands. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(group_pairs_or_sort, [group_pairs_or_sort/2]). group_pairs_by_key_u([], []). group_pairs_by_key_u([M-N|T0], [M-[N|TN]|T]) :- same_key_u(M, T0, TN, T1), group_pairs_by_key_u(T1, T). same_key_u(M, [M-N|T0], [N|TN], T) :- !, same_key_u(M, T0, TN, T). same_key_u(_, L, [], L). group_pairs_or_sort(Pairs, Grouped) :- Pairs = [_-_|_], !, keysort(Pairs, Sorted), group_pairs_by_key_u(Sorted, UnGrouped), maplist(group_pairs_or_sort_into, UnGrouped, Grouped). group_pairs_or_sort(Unsorted, Sorted) :- sort(Unsorted, Sorted). group_pairs_or_sort_into(K-U, K-S) :- group_pairs_or_sort(U, S).
TeamSPoon/logicmoo_workspace
packs_lib/xlibrary/prolog/group_pairs_or_sort.pl
Perl
mit
2,247
#!/usr/bin/perl -w $count = 0; foreach $line (<STDIN>){ chomp($line); if ($line ne ""){ @string = (); @string = split /[^a-zA-Z]+/, $line; @string = grep { $_ ne '' } @string; if ($#string ne -1){ $count = scalar(@string) + $count; } #print join( ",", @string); #print $count; #print "\n"; } } print $count, "\n";
Knln/COMP2041
testinglab6/total_words.pl
Perl
mit
339
% vim: filetype=prolog % Count numbers that are doubled odd numbers. main :- new(Dir, directory('.')), new(Frame, frame('Select file')), new(Browser, browser), new(Dialog, dialog), send(Dialog, append(button( 'Process!', message(@prolog, processfile, Browser?selection?key)) )), send(Dialog, append(button( 'Quit', message(@prolog, halt)) )), send(Browser, members(Dir?files)), send(Frame, append(Browser)), send(Dialog, below(Browser)), send(Frame, open). processfile(F) :- see(F), count(0, N), showResult(N, F), seen. count(X, D) :- ( at_end_of_stream -> D is X; read(N), ( integer(N) -> ( isOurNumber(N) -> X1 is X + 1; X1 is X ), count(X1, D); not_integer(N), seen ) ). not_integer(X) :- new(D, dialog('Error')), send(D, append(text('Error!'))), send(D, append(text(X), right)), send(D, append(text('is not an integer'), right)), send(D, append(button('Okay', message(D, destroy), below))), send(D, open). isOurNumber(X) :- isEven(X), Y is X div 2, not(isEven(Y)). isEven(X) :- Y is X mod 2, Y =:= 0. showResult(X, F) :- new(D, dialog('RESULT')), new(V, view(F)), send(D, append(text('The result is'))), send(D, append(text(X), right)), send(D, append(V, below)), send(D, append(button('Close', message(D, destroy)), below)), send(V, load(F)), send(D, open).
MPogoda/prolog-labs
lab1/lab1.pl
Perl
mit
1,466
#!/usr/bin/env perl $infile = $ARGV[0]; $outname = $infile if (! $outname); open(IN, $infile) || die; open(GENE, ">$outname.gene") || die; open(TIT, ">$outname.tit") || die; while(<IN>){ chomp; if (/^>\s*(\S.*)/) { ($name0,$title0) = split(/\s+/, $1, 2); if ($seq) { ($sp, $gene) = split(/:/, $name); $seqlen = length($seq); print GENE "$sp $gene $seqlen\n"; print TIT "$sp:$gene\t$title\n"; } $name = $name0; $title = $title0; $seq = ''; } else { s/\s//g; $seq .= $_; } } close(IN); if ($seq) { ($sp, $gene) = split(/:/, $name); $seqlen = length($seq); print GENE "$sp $gene $seqlen\n"; print TIT "$sp:$gene\t$title\n"; }
PatrickRWright/CopraRNA
coprarna_aux/fasta2genefile.pl
Perl
mit
659
=head NAME URI::Title::PDF - get titles of PDF files =cut package URI::Title::PDF; use warnings; use strict; sub types {( 'application/pdf', )} sub title { my ($class, $url, $data, $type) = @_; my %fields = (); my $content = URI::Title::get_end($url) or return; foreach my $i (qw(Producer Creator CreationDate Author Title Subject)) { my @parts = $content =~ m#/$i \((.*?)\)#mgs; $fields{$i} = $parts[-1]; # grab the last one, hopefully right } my $title = ""; my @parts = (); if ($fields{Title}) { push @parts, "$fields{Title}"; if ($fields{Author}) { push @parts, "by $fields{Author}"; } if ($fields{Subject}) { push @parts, "($fields{Subject})"; } } if ($fields{Creator} and $fields{Creator} ne 'Not Available') { push @parts, "creator: $fields{Creator}"; } if ($fields{Producer} and $fields{Producer} ne 'Not Available') { push @parts, "produced: $fields{Producer}"; } $title = join(' ', @parts); return $title; } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/URI/Title/PDF.pm
Perl
mit
989
#!/usr/bin/perl -w ########################################################## # Author : Aurelie Kapusta # version : see below / see change log # email : 4urelie.k@gmail.com # PURPOSE : Extract random pieces of sequences, typically from a genome ########################################################## use strict; use warnings; use Carp; use Getopt::Long; use Bio::DB::Fasta; my $version = "1.1"; my $scriptname = "fasta_extract_random_pieces.pl"; my $changelog = " # - v1.0 = 27 Sept 2016 # - v1.1 = 28 Sept 2016 # add -a \n"; my $usage = "\nUsage [v$version]: perl $scriptname -i <in.fa> -l <min,max> [-n <X>] [-p <X>] [-o <out.fa] [-a <X>] [-u] [-s] [-b] [-v] [-h|help] PURPOSE: Extract random pieces of sequences, typically from a genome It will: 1. select randomly a sequence from the input file 2. select a random position in it 3. select a length between min and max set with -l 4. check if these coordinates overlap less than X% (set with -a) with previously extracted regions 5. if yes, extract that sub sequence MANDATORY ARGUMENTS: -i,--in => (STRING) fasta file to loop through. Need to be .fa or .fasta -l,--len => (STRING) to set the minimum and maximum lengths of extracted sequences CHOSE ONE OF -n or -p -n,--nb => (INT) number of sequences to extract -p,--per => (FLOAT) percentage of sequences to extract (eg if 1000 sequences in file.fa and 10 is chosen, 100 sequences are extracted) OPTIONAL ARGUMENTS -o,--out => (STRING) output file name [Default = in.nb.rand.min-max.fa] -a,--allow => (FLOAT) allowed overlap between extracted sequences, in % [default = 10] -u,--uc => (BOOL) write extracted sequences in uppercase -s,--skip => (BOOL) avoid Ns (any sequence is skipped if contains any Ns) -b,--bio => (BOOL) Bio::DB::Fasta won't extract sequence if it looks like ZZZ:XX-XX (XX-XX are see as coordinates in ZZZ). Chose this option if you headers may look like that, the : will be replaced by -- -v => (BOOL) verbose mode, make the script talks to you / version if only option -h|help => (BOOL) this usage -c,--chlog => (BOOL) print the change log (updates) \n"; ################################################################################ ### Get arguments/options ### check some of them, print details of the run if verbose chosen ################################################################################ my $allow = 10; my ($in,$len,$nb,$per,$out,$uc,$nrem,$dbhead,$help,$chlog,$v); GetOptions ('in=s' => \$in, 'len=s' => \$len, 'nb=s' => \$nb, 'per=s' => \$per, 'out=s' => \$out, 'allow=s' => \$allow, 'uc' => \$uc, 'skip' => \$nrem, 'bio' => \$dbhead, 'chlog' => \$chlog, 'help' => \$help, 'v' => \$v); #check step for options die "\n $scriptname version: $version\n\n" if ((! $in) && (! $len) && (! $help) && (! $chlog) && ($v)); die $changelog if ($chlog); die $usage if ($help); die "\n Please provide input fasta file (-i, use -h to see the usage)\n\n" if (! $in); die "\n File -i $in does not exist?\n\n" if (! -e $in); die "\n Please provide one of -n or -p\n\n" if ((! $nb) && (! $per)); die "\n -n $nb is not an integer?\n\n" if (($nb) && ($nb !~ /^[0-9]+$/)); die "\n -p $per is not a float?\n\n" if (($per) && ($per !~ /^[0-9\.]+$/)); die "\n Please provide min and max lengths (-l min,max)\n\n" if (! $len); die "\n Please provide min and max lengths (-l min,max) as integers\n\n" if ($len !~ /^[0-9]+?,[0-9]+?$/); die "\n -a $allow is not a float?\n\n" if ($allow !~ /^[0-9\.]+$/); ################################################################################ ### MAIN ################################################################################ print STDERR "\n --- Script to extract random pieces of fasta sequences from $in started (v$version)\n" if ($v); # get number of sequences to extract if $per print STDERR " WARN: -n and -p both chosen; -n wins\n" if (($v) && ($nb) && ($per)); undef ($per) if (($nb) && ($per)); $nb = get_nb($in,$per,$v) unless ($nb); print STDERR " -> $nb sequences will be extracted\n" if (($v) && ($nb)); print STDERR " -> $nb sequences will be extracted ($per %)\n" if (($v) && ($per)); # Other options print STDERR " --- Sequences with be allowed to overlap $allow % with each other\n" if ($v); print STDERR " --- Sequences will be in uppercase in the output\n" if (($v) && ($uc)); print STDERR " --- Sequences with Ns (1 or +) will be skipped\n" if (($v) && ($nrem)); ($uc)?($uc="y"):($uc="n"); ($nrem)?($nrem="y"):($nrem="n"); # index the fasta file if necessary and connect to the fasta obj my $reindex; my $index = "$in.index"; (-e $index)?($reindex = 0):($reindex = 1); print STDERR " --- Create Bio:DB:Fasta object + get all IDs in array...\n" if ($v); my $db; if ($dbhead) { print STDERR " -b chosen, all : in headers are replaced by -- while indexing\n" if ($v); $db = Bio::DB::Fasta->new($in, -reindex=>$reindex, -makeid=>\&make_my_id_m) or die "\n ERROR: Failed to open Bio::DB::Fasta object from $in $!\n"; } else { $db = Bio::DB::Fasta->new($in, -reindex=>$reindex, -makeid=>\&make_my_id) or die "\n ERROR: Failed to open Bio::DB::Fasta object from $in $!\n"; } #now extract random my ($min,$max) = split(",",$len); $out = $1.".$nb.rand.$min-$max.fa" if ((! $out) && ($in =~ /^(.*)\.fa/)); extract_random($in,$db,$nb,$out,$min,$max,$allow,$uc,$nrem,$v); print STDERR " --- Script done, sequences in $out\n" if ($v); print STDERR "\n"; exit; ########################################################################################################## # SUBROUTINES ########################################################################################################## #---------------------------------------------------------------------------- # Get number of sequences # $nb = get_nb($file,$per,$v) unless ($nb); #---------------------------------------------------------------------------- sub get_nb { my ($file,$per,$v) = @_; my $tot = `grep -c ">" $file`; chomp $tot; print STDERR " Total nb of sequences in file = $tot\n" if ($v); confess "\n ERROR (sub get_nb): no \">\" in $file?\n\n" if ($tot == 0); my $nb = int($tot/$per); return ($nb); } #---------------------------------------------------------------------------- # Extract random set of sequence pieces using a Bio::DB::Fasta object # extract_random($in,$db,$nb,$out,$min,$max,$allow,$uc,$nrem,$v); #---------------------------------------------------------------------------- sub extract_random { my ($in,$db,$nb,$out,$min,$max,$allow,$uc,$nrem,$v) = @_; print STDERR " --- Extracting sequences\n" if ($v); my $range = $max-$min+1; print STDERR " -> of lengths ranging from $min to $max nt (range = $range)\n" if ($v); my @dbIDs = $db->ids(); my %prev = (); open (my $fh, ">","$out") or confess "\n ERROR (sub extract_random): Failed to open to write $out $!\n"; SEQ: for (my $i=1;$i<=$nb;$i++) { #loop on total number of sequences to extract #get a random ID from the fasta file my $head = $dbIDs[int(rand($#dbIDs))]; #Get that sequence my $seq = $db->seq($head); #Get a random position in it my $end = int(rand(length($seq))); #Now get a start, random length within the range my $start = $end - $max + 1+int(rand($range)); #rand(5) is 0 to 4 #Check for overlap my $skip = "n"; $skip = check_overlap($prev{$head},$start,$end,$allow) if (exists $prev{$head}); if ($skip eq "y") { $i--; print STDERR " WARN: sequence skipped because overlapped with previously extracted one\n" if ($v); next SEQ; } ($prev{$head})?($prev{$head}.=",$start,$end"):($prev{$head} = "$start,$end"); #Get the new ID my @header = (); ($head =~ /\t/)?(@header = split(/\t/,$head)):(@header = ($head)); my $id = shift(@header); my $newid = $id."--$start-$end"; $newid = join("\t/",$id,@header) if ($header[0]); #will append description if any #get the subsequence my $subseq = $db->seq($head,$start,$end); $subseq = uc($subseq) if ($uc eq "y"); if (($nrem eq "y") && ($subseq =~ /[Nn]/)) { $i--; print STDERR " WARN: sequence skipped because Ns in it\n" if ($v); next SEQ; } print $fh ">$newid\n$subseq\n"; } close $fh; return 1; } #---------------------------------------------------------------------------- # Check for overlap between regions # $skip = check_overlap($prev{$head},$start,$end,$allow) if (exists $prev{$head}); #---------------------------------------------------------------------------- sub check_overlap { my ($already,$start,$end,$allow) = @_; my $skip = "n"; my @reg = split(",",$already); REGCHECK: for (my $i=0;$i<=$#reg;$i+=2) { my $prev_st = $reg[$i]; my $prev_en = $reg[$i+1]; if (($prev_en > $start) && ($prev_st < $end)) { #there is overlap my $o = 1; #if included it will be 100 % my $len = $end - $start +1; #region length #adjust $o if not included: $o = ($prev_en - $prev_st +1) / $len if (($start < $prev_st) && ($prev_en < $end)); #region overhangs 5' and 3' $o = ($end - $prev_st +1) / $len if (($start < $prev_st) && ($end < $prev_en)); #region overhangs 5' but not 3' $o = ($prev_en - $start +1) / $len if (($prev_st < $start) && ($prev_en < $end)); #region overhangs 3' but not 5' $skip = "y" if ($o*100 > $allow); # print STDERR "skip region (prev = $prev_st - $prev_en and curr = $start - $end => overlap = $o)\n" if ($skip eq "y"); last REGCHECK if ($skip eq "y"); } } return ($skip); } #---------------------------------------------------------------------------- # Subs for make id #---------------------------------------------------------------------------- sub make_my_id { my $line = shift; #$line =~ /^>(\S+)/; #original expression used, keep only the ID $line =~ s/\//.../g; #the / is a special char in Bio::DB => strand... $line =~ /^>(.*)$/; #keep description => the whole line is the ID return $1; } sub make_my_id_m { my $line = shift; $line =~ s/:/--/g; #replace any : by -- #$line =~ /^>(\S+)/; #original expression used, keep only the ID $line =~ /^>(.*)$/; #keep description return $1; }
4ureliek/Fasta
fasta_extract_random_pieces.pl
Perl
mit
10,828
check_header "unistd.h"; check_header "errno.h"; check_header "string.h"; check_header "stdlib.h"; needs_static_init; 1;
slash-lang/slash
ext/posix/configure.pl
Perl
mit
123
package WeblioSearch::DB; use parent 'Teng'; __PACKAGE__->load_plugin('SearchBySQLAbstractMore'); 1;
mshige1979/WeblioRank
weblio_search_web/lib/WeblioSearch/DB.pm
Perl
mit
100
%[a,b,c]=[T|Q]. %[a,b,c]=[T1,T2|Q]. %[a,b,c]=[T1,T2,T3|Q]. % Informations sur les listes liste([]). liste([_|Q]):- liste(Q). premier(X,[X,_]). dernier(X,[_,X]). dernier(X,[_|Q]):-liste(Q),dernier(X,Q). longueur(0,[]). longueur(N,[_|Q]):- longueur(M,Q),N is M+1. dans(X,[T|Q]):-premier(X,[T|Q]);dans(X,Q). % Manipulation de listes conc([],X,X). conc([T|Q1],X,[T|Q2]):-conc(Q1,X,Q2). ajouter(X,L,R):-conc(L,[X],R). supprimer(_,[],[]). supprimer(X,[X|Q],QT):-supprimer(X,Q,QT). supprimer(X,[T|Q],[T|QT]):-X\==T,supprimer(X,Q,QT). sub(_,_,[],[]). sub(X,Y,[X|Q],[Y|QT]):-sub(X,Y,Q,QT). sub(X,Y,[T|Q],[T|QT]):-X\==T,sub(X,Y,Q,QT).
kwnovi/prolog
IA_TP2.pl
Perl
mit
643
#!/usr/bin/env perl # # Author: Txor <txorlings@gmail.com> # use strict; use warnings; use MIME::Base64; use utf8; binmode STDOUT, ":utf8"; # Check program agruments die "Wrong number of arguments" unless $ARGV[0]; die "Can't read $ARGV[0]" unless -r $ARGV[0]; # Read the file open FILE, $ARGV[0] or die $!; my @lines = <FILE>; close FILE; # Process the log text my @operations; gatherData(\@operations, \@lines); prettyPrinting(\@operations); # Subroutines sub gatherData { my ($opsRef, $linesRef) = @_; my $dateRegex = qr{\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}\.\d{3}}; my $typeRegex = qr{(?:Request|Response)}; my $op; foreach (@$linesRef) { next unless /(?<date>$dateRegex).*(?<type>$typeRegex)/; my $type = $+{type}; my $date = $+{date}; my $params; $$params{$1} = decode_base64($2) while (/(\w+)=([^&]+)&/g); if (exists $$params{'ID_OPER'}) { $op = {}; $$op{'ID'} = $$params{'ID_OPER'}; } $$op{$type} = $params; $$op{"${type}Date"} = $date; push @$opsRef, $op unless exists $$params{'ID_OPER'}; } } sub prettyPrinting { my ($opRef) = @_; my $num = 0; foreach (@$opRef) { my $id = $$_{'ID'}; my $reqDate = $$_{'RequestDate'}; my $req = $$_{'Request'}; my $resDate = $$_{'ResponseDate'}; my $res = $$_{'Response'}; print "╒═OPERATION $num" . "═" x 67 . "\n"; print "│ $id\n"; print "│ ┌{REQUEST at $reqDate}" . "─" x 40 . "\n"; printf "│ │ %-20s %-20s\n", $_, $req->{$_} foreach (sort keys %$req); print "│ ├{RESPONSE at $resDate}" . "─" x 39 . "\n"; printf "│ │ %-20s %-20s\n", $_, $res->{$_} foreach (sort keys %$res); print "└──┴" . "─" x 76 . "\n"; $num++; } }
txor/talks
Perl/logParser/logParser.pl
Perl
cc0-1.0
1,705
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V10::Common::SitelinkFeedItem; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { finalMobileUrls => $args->{finalMobileUrls}, finalUrlSuffix => $args->{finalUrlSuffix}, finalUrls => $args->{finalUrls}, line1 => $args->{line1}, line2 => $args->{line2}, linkText => $args->{linkText}, trackingUrlTemplate => $args->{trackingUrlTemplate}, urlCustomParameters => $args->{urlCustomParameters}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V10/Common/SitelinkFeedItem.pm
Perl
apache-2.0
1,389
=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::Configuration::Webdata; use strict; use parent qw(EnsEMBL::Web::Configuration::Production); use constant DEFAULT_ACTION => 'Display'; 1;
muffato/public-plugins
admin/modules/EnsEMBL/Web/Configuration/Webdata.pm
Perl
apache-2.0
873
# # 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 apps::video::zixi::restapi::plugin; use strict; use warnings; use base qw(centreon::plugins::script_custom); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; %{$self->{modes}} = ( 'broadcaster-input-usage' => 'apps::video::zixi::restapi::mode::broadcasterinputusage', 'broadcaster-license-usage' => 'apps::video::zixi::restapi::mode::broadcasterlicenseusage', 'broadcaster-output-usage' => 'apps::video::zixi::restapi::mode::broadcasteroutputusage', 'broadcaster-system-usage' => 'apps::video::zixi::restapi::mode::broadcastersystemusage', 'feeder-input-usage' => 'apps::video::zixi::restapi::mode::feederinputusage', 'feeder-output-usage' => 'apps::video::zixi::restapi::mode::feederoutputusage', ); $self->{custom_modes}{api} = 'apps::video::zixi::restapi::custom::api'; return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Zixi through HTTP/REST API. =cut
Tpo76/centreon-plugins
apps/video/zixi/restapi/plugin.pm
Perl
apache-2.0
1,858
package B::Hooks::EndOfScope::PP; # ABSTRACT: Execute code after a scope finished compilation - PP implementation use warnings; use strict; our $VERSION = '0.14'; use Module::Runtime 'require_module'; use constant _PERL_VERSION => "$]"; BEGIN { if (_PERL_VERSION =~ /^5\.009/) { # CBA to figure out where %^H got broken and which H::U::HH is sane enough die "By design B::Hooks::EndOfScope does not operate in pure-perl mode on perl 5.9.X\n" } elsif (_PERL_VERSION < '5.010') { require_module('B::Hooks::EndOfScope::PP::HintHash'); *on_scope_end = \&B::Hooks::EndOfScope::PP::HintHash::on_scope_end; } else { require_module('B::Hooks::EndOfScope::PP::FieldHash'); *on_scope_end = \&B::Hooks::EndOfScope::PP::FieldHash::on_scope_end; } } use Sub::Exporter::Progressive -setup => { exports => ['on_scope_end'], groups => { default => ['on_scope_end'] }, }; sub __invoke_callback { local $@; eval { $_[0]->(); 1 } or do { my $err = $@; require Carp; Carp::cluck( (join ' ', 'A scope-end callback raised an exception, which can not be propagated when', 'B::Hooks::EndOfScope operates in pure-perl mode. Your program will CONTINUE', 'EXECUTION AS IF NOTHING HAPPENED AFTER THIS WARNING. Below is the complete', 'exception text, followed by a stack-trace of the callback execution:', ) . "\n\n$err\n\r" ); sleep 1 if -t *STDERR; # maybe a bad idea...? }; } #pod =head1 DESCRIPTION #pod #pod This is the pure-perl implementation of L<B::Hooks::EndOfScope> based only on #pod modules available as part of the perl core. Its leaner sibling #pod L<B::Hooks::EndOfScope::XS> will be automatically preferred if all #pod dependencies are available and C<$ENV{B_HOOKS_ENDOFSCOPE_IMPLEMENTATION}> is #pod not set to C<'PP'>. #pod #pod =func on_scope_end #pod #pod on_scope_end { ... }; #pod #pod on_scope_end $code; #pod #pod Registers C<$code> to be executed after the surrounding scope has been #pod compiled. #pod #pod This is exported by default. See L<Sub::Exporter> on how to customize it. #pod #pod =cut 1; __END__ =pod =encoding UTF-8 =head1 NAME B::Hooks::EndOfScope::PP - Execute code after a scope finished compilation - PP implementation =head1 VERSION version 0.14 =head1 DESCRIPTION This is the pure-perl implementation of L<B::Hooks::EndOfScope> based only on modules available as part of the perl core. Its leaner sibling L<B::Hooks::EndOfScope::XS> will be automatically preferred if all dependencies are available and C<$ENV{B_HOOKS_ENDOFSCOPE_IMPLEMENTATION}> is not set to C<'PP'>. =head1 FUNCTIONS =head2 on_scope_end on_scope_end { ... }; on_scope_end $code; Registers C<$code> to be executed after the surrounding scope has been compiled. This is exported by default. See L<Sub::Exporter> on how to customize it. =head1 AUTHORS =over 4 =item * Florian Ragwitz <rafl@debian.org> =item * Peter Rabbitson <ribasushi@cpan.org> =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2008 by Florian Ragwitz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut
ray66rus/vndrv
local/lib/perl5/B/Hooks/EndOfScope/PP.pm
Perl
apache-2.0
3,205
#!/usr/bin/env perl # Copyright 2015 Petr, Frank Breedijk # # 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. # ------------------------------------------------------------------------------ # Gets notificationdata # ------------------------------------------------------------------------------ use strict; use CGI; use CGI::Carp qw(fatalsToBrowser); use JSON; use lib ".."; use SeccubusV2; use SeccubusAssets; my $query = CGI::new(); my $json = JSON->new(); print $query->header(-type => "application/json", -expires => "-1d", -"Cache-Control"=>"no-store, no-cache, must-revalidate", -"X-Clacks-Overhead" => "GNU Terry Pratchett"); my $params = $query->Vars; my $scan_id = $params->{scanid}; # Return an error if the required parameters were not passed bye("Parameter scanid is missing") if (not (defined ($scan_id))); bye("scanid is not numeric") if ( $scan_id + 0 ne $scan_id ); eval { my @data = map { { scan_id => $_->[0], asset_id => $_->[1] } } @{get_asset2scan($scan_id)}; print $json->pretty->encode(\@data); } or do { bye(join "\n", $@); }; sub bye($) { my $error=shift; print $json->pretty->encode([{ error => $error }]); exit; }
vlamer/Seccubus_v2
json/getAsset2Scan.pl
Perl
apache-2.0
1,658
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2020] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =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::DBSQL::BaseMetaContainer - Encapsulates all generic access to database meta information =head1 SYNOPSIS my $meta_container = $db_adaptor->get_MetaContainer(); my @mapping_info = @{ $meta_container->list_value_by_key('assembly.mapping') }; =head1 DESCRIPTION An object that encapsulates access to db meta data =head1 METHODS =cut package Bio::EnsEMBL::DBSQL::BaseMetaContainer; use vars qw(@ISA); use strict; use Bio::EnsEMBL::DBSQL::BaseAdaptor; use Bio::EnsEMBL::Utils::Exception qw(throw warning); @ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor); # new() is inherited from Bio::EnsEMBL::DBSQL::BaseAdaptor =head2 get_schema_version Arg [1] : none Example : $schema_ver = $meta_container->get_schema_version(); Description: Retrieves the schema version from the database meta table Returntype : int Exceptions : none Caller : ? Status : Medium risk =cut sub get_schema_version { my $self = shift; my $arrRef = $self->list_value_by_key('schema_version'); if (@$arrRef) { my ($ver) = ( $arrRef->[0] =~ /^\s*(\d+)\s*$/ ); if ( !defined($ver) ) { # old style format return 0; } return $ver * 1; #multiply by 1 to get this into a number } else { warning( sprintf( "Please insert meta_key 'schema_version' " . "in meta table on core database '%s'\n", $self->dbc()->dbname() ) ); } return 0; } =head2 list_value_by_key Arg [1] : string $key the key to obtain values from the meta table with Example : my @values = @{ $meta_container->list_value_by_key($key) }; Description: gets a value for a key. Can be anything Returntype : listref of strings Exceptions : none Caller : ? Status : Stable =cut sub list_value_by_key { my ( $self, $key ) = @_; $self->{'cache'} ||= {}; if ( exists $self->{'cache'}->{$key} ) { return $self->{'cache'}->{$key}; } my $sth; if ( !$self->_species_specific_key($key) ) { $sth = $self->prepare( "SELECT meta_value " . "FROM meta " . "WHERE meta_key = ? " . "AND species_id IS NULL " . "ORDER BY meta_id" ); } else { $sth = $self->prepare( "SELECT meta_value " . "FROM meta " . "WHERE meta_key = ? " . "AND species_id = ? " . "ORDER BY meta_id" ); $sth->bind_param( 2, $self->species_id(), SQL_INTEGER ); } $sth->bind_param( 1, $key, SQL_VARCHAR ); $sth->execute(); my @result; while ( my $arrRef = $sth->fetchrow_arrayref() ) { push( @result, $arrRef->[0] ); } $sth->finish(); $self->{'cache'}->{$key} = \@result; return \@result; } ## end sub list_value_by_key =head2 single_value_by_key Arg [1] : string $key the key to obtain values from the meta table with Arg [2] : boolean $warn If true will cause the code to warn the non-existence of a value Example : my $value = $mc->single_value_by_key($key); Description: Gets a value for a key. Can be anything Returntype : Scalar Exceptions : Raised if more than 1 meta item is returned =cut sub single_value_by_key { my ($self, $key, $warn) = @_; my $results = $self->list_value_by_key($key); if(defined $results) { my $count = scalar(@{$results}); if($count == 1) { my ($value) = @{$results}; return $value; } elsif($count == 0) { if($warn) { my $group = $self->db()->group(); my $msg = sprintf(qq{Please insert meta_key '%s' in meta table at %s db\n}, $key, $group); warning($msg); } } else { my $values = join(q{,}, @{$results}); throw sprintf(q{Found the values [%s] for the key '%s'}, $values, $key); } } return; } ## end sub single_value_by_key =head2 store_key_value Arg [1] : string $key a key under which $value should be stored Arg [2] : string $value the value to store in the meta table Example : $meta_container->store_key_value($key, $value); Description: stores a value in the meta container, accessable by a key Returntype : none Exceptions : Thrown if the key/value already exists. Caller : ? Status : Stable =cut sub store_key_value { my ( $self, $key, $value ) = @_; if ( $self->key_value_exists( $key, $value ) ) { warn( "Key-value pair '$key'-'$value' " . "already exists in the meta table; " . "not storing duplicate" ); return; } my $sth; if ( !$self->_species_specific_key($key) ) { $sth = $self->prepare( 'INSERT INTO meta (meta_key, meta_value, species_id) ' . 'VALUES(?, ?, \N)' ); } else { $sth = $self->prepare( 'INSERT INTO meta (meta_key, meta_value, species_id) ' . 'VALUES (?, ?, ?)' ); $sth->bind_param( 3, $self->species_id(), SQL_INTEGER ); } $sth->bind_param( 1, $key, SQL_VARCHAR ); $sth->bind_param( 2, $value, SQL_VARCHAR ); $sth->execute(); $self->{'cache'} ||= {}; delete $self->{'cache'}->{$key}; } ## end sub store_key_value =head2 update_key_value Arg [1] : string $key a key under which $value should be updated Arg [2] : string $value the value to update in the meta table Example : $meta_container->update_key_value($key, $value); Description: update a value in the meta container, accessable by a key Returntype : none Exceptions : none Caller : ? Status : Stable =cut sub update_key_value { my ( $self, $key, $value ) = @_; my $sth; if ( !$self->_species_specific_key($key) ) { $sth = $self->prepare( 'UPDATE meta SET meta_value = ? ' . 'WHERE meta_key = ?' . 'AND species_id IS NULL' ); } else { $sth = $self->prepare( 'UPDATE meta ' . 'SET meta_value = ? ' . 'WHERE meta_key = ? ' . 'AND species_id = ?' ); $sth->bind_param( 3, $self->species_id(), SQL_INTEGER ); } $sth->bind_param( 1, $value, SQL_VARCHAR ); $sth->bind_param( 2, $key, SQL_VARCHAR ); $sth->execute(); } ## end sub update_key_value =head2 delete_key Arg [1] : string $key The key which should be removed from the database. Example : $meta_container->delete_key('sequence.compression'); Description: Removes all rows from the meta table which have a meta_key equal to $key. Returntype : none Exceptions : none Caller : dna_compress script, general Status : Stable =cut sub delete_key { my ( $self, $key ) = @_; my $sth; if ( !$self->_species_specific_key($key) ) { $sth = $self->prepare( 'DELETE FROM meta ' . 'WHERE meta_key = ?' . 'AND species_id IS NULL' ); } else { $sth = $self->prepare( 'DELETE FROM meta ' . 'WHERE meta_key = ? ' . 'AND species_id = ?' ); $sth->bind_param( 2, $self->species_id(), SQL_INTEGER ); } $sth->bind_param( 1, $key, SQL_VARCHAR ); $sth->execute(); delete $self->{'cache'}->{$key}; } =head2 delete_key_value Arg [1] : string $key The key which should be removed from the database. Arg [2] : string $value The value to be removed. Example : $meta_container->delete_key('patch', 'patch_39_40_b.sql|xref_unique_constraint'); Description: Removes all rows from the meta table which have a meta_key equal to $key, AND a meta_value equal to $value. Returntype : none Exceptions : none Caller : general Status : Stable =cut sub delete_key_value { my ( $self, $key, $value ) = @_; my $sth; if ( !$self->_species_specific_key($key) ) { $sth = $self->prepare( 'DELETE FROM meta ' . 'WHERE meta_key = ? ' . 'AND meta_value = ?' . 'AND species_id IS NULL' ); } else { $sth = $self->prepare( 'DELETE FROM meta ' . 'WHERE meta_key = ? ' . 'AND meta_value = ? ' . 'AND species_id = ?' ); $sth->bind_param( 3, $self->species_id(), SQL_INTEGER ); } $sth->bind_param( 1, $key, SQL_VARCHAR ); $sth->bind_param( 2, $value, SQL_VARCHAR ); $sth->execute(); delete $self->{'cache'}->{$key}; } ## end sub delete_key_value =head2 key_value_exists Arg [1] : string $key the key to check Arg [2] : string $value the value to check Example : if ($meta_container->key_value_exists($key, $value)) ... Description: Return true (1) if a particular key/value pair exists, false (0) otherwise. Returntype : boolean Exceptions : none Caller : ? Status : Stable =cut sub key_value_exists { my ( $self, $key, $value ) = @_; my $sth; if ( !$self->_species_specific_key($key) ) { $sth = $self->prepare( 'SELECT meta_value ' . 'FROM meta ' . 'WHERE meta_key = ? ' . 'AND meta_value = ?' . 'AND species_id IS NULL' ); } else { $sth = $self->prepare( 'SELECT meta_value ' . 'FROM meta ' . 'WHERE meta_key = ? ' . 'AND meta_value = ? ' . 'AND species_id = ?' ); $sth->bind_param( 3, $self->species_id(), SQL_INTEGER ); } $sth->bind_param( 1, $key, SQL_VARCHAR ); $sth->bind_param( 2, $value, SQL_VARCHAR ); $sth->execute(); return 0 unless $sth->fetchrow_arrayref(); return 1; } ## end sub key_value_exists # This utility method determines whether the key is a species-specific # meta key or not. If the key is either 'patch' or 'schema_version' # or 'schema_type', then it is not species-specific. # FIXME variation team messed up in release 65 and added the ploidy # entry without species_id - this will be corrected for release 66, # for now, I've added it to the list of allowed non-species specific sub _species_specific_key { my ( $self, $key ) = @_; return ( $key ne 'patch' && $key ne 'schema_version' && $key ne 'schema_type'); } 1;
james-monkeyshines/ensembl
modules/Bio/EnsEMBL/DBSQL/BaseMetaContainer.pm
Perl
apache-2.0
10,954
#!"E:\xampp\perl\bin\perl.exe" use HTML::Perlinfo; use CGI qw(header); $q = new CGI; print $q->header; $p = new HTML::Perlinfo; $p->info_general; $p->info_variables; $p->info_modules; $p->info_license;
ArcherCraftStore/ArcherVMPeridot
htdocs/xampp/perlinfo.pl
Perl
apache-2.0
205
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =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 # # Ensembl module for Bio::EnsEMBL::Variation::DBSQL::SupportingStructuralVariationAdaptor # # =head1 NAME Bio::EnsEMBL::Variation::DBSQL::SupportingStructuralVariationAdaptor =head1 SYNOPSIS $reg = 'Bio::EnsEMBL::Registry'; $reg->load_registry_from_db(-host => 'ensembldb.ensembl.org',-user => 'anonymous'); $ssva = $reg->get_adaptor("human","variation","supportingstructuralvariation"); # fetch a supporting structural variation by its name $ssv = $ssva->fetch_by_name('nssv133'); # fetch all supporting evidences for a structural variation $sva = $reg->get_adaptor("human","variation","structuralvariation"); $sv = $sva->fetch_by_dbID(145); foreach $ssv (@{$ssva->fetch_all_by_StructuralVariation($sv)}){ print $ssv->dbID, " - ", $ssv->name ,"\n"; } # Modify the include_failed_variations flag in DBAdaptor to also return supporting evidences that have been flagged as failed $va->db->include_failed_variations(1); =head1 DESCRIPTION This adaptor provides database connectivity for SupportingStructuralVariation objects. =head1 METHODS =cut use strict; use warnings; package Bio::EnsEMBL::Variation::DBSQL::SupportingStructuralVariationAdaptor; use Bio::EnsEMBL::Variation::DBSQL::BaseStructuralVariationAdaptor; use Bio::EnsEMBL::Utils::Exception qw(throw warning deprecate); use Bio::EnsEMBL::Variation::SupportingStructuralVariation; use DBI qw(:sql_types); our @ISA = ('Bio::EnsEMBL::Variation::DBSQL::BaseStructuralVariationAdaptor'); sub _default_where_clause { my $self = shift; return $self->SUPER::_default_where_clause().' AND is_evidence=1'; } sub _objs_from_sth { my ($self, $sth) = @_; # # This code is ugly because an attempt has been made to remove as many # function calls as possible for speed purposes. Thus many caches and # a fair bit of gymnastics is used. # my @svs; my ($struct_variation_id, $variation_name, $validation_status, $source_name, $source_version, $source_description, $class_attrib_id, $study_id, $is_evidence, $is_somatic, $alias, $clin_sign_attrib_id ); $sth->bind_columns(\$struct_variation_id, \$variation_name, \$validation_status, \$source_name, \$source_version, \$source_description, \$class_attrib_id, \$study_id, \$is_evidence, \$is_somatic, \$alias, \$clin_sign_attrib_id); my $aa = $self->db->get_AttributeAdaptor; my $sta = $self->db->get_StudyAdaptor(); while($sth->fetch()) { my $study; $study = $sta->fetch_by_dbID($study_id) if (defined($study_id)); # Get the validation status $validation_status ||= 0; my @states = split(/,/,$validation_status); push @svs, Bio::EnsEMBL::Variation::SupportingStructuralVariation->new( -dbID => $struct_variation_id, -VARIATION_NAME => $variation_name, -VALIDATION_STATES => \@states, -ADAPTOR => $self, -SOURCE => $source_name, -SOURCE_VERSION => $source_version, -SOURCE_DESCRIPTION => $source_description, -CLASS_SO_TERM => $aa->attrib_value_for_id($class_attrib_id), -STUDY => $study, -IS_EVIDENCE => $is_evidence || 0, -IS_SOMATIC => $is_somatic || 0, -ALIAS => $alias, -CLINICAL_SIGNIFICANCE => $aa->attrib_value_for_id($clin_sign_attrib_id) ); } return \@svs; } =head2 fetch_all_by_StructuralVariation Arg [1] : Bio::EnsEMBL::Variation::StructuralVariation $sv Example : my $sv = $sv_adaptor->fetch_by_name('esv9549'); foreach my $ssv (@{$ssv_adaptor->fetch_all_by_StructuralVariation($sv)}){ print $ssv->variation_name,"\n"; } Description : Retrieves all supporting evidences from a specified structural variant ReturnType : reference to list of Bio::EnsEMBL::Variation::SupportingStructuralVariation objects Exceptions : throw if incorrect argument is passed warning if provided structural variant does not have a dbID Caller : general Status : Stable =cut sub fetch_all_by_StructuralVariation { my $self = shift; my $sv = shift; if(!ref($sv) || !$sv->isa('Bio::EnsEMBL::Variation::StructuralVariation')) { throw("Bio::EnsEMBL::Variation::StructuralVariation arg expected"); } if(!$sv->dbID()) { warning("StructuralVariation does not have dbID, cannot retrieve structural variants"); return []; } my $cols = qq{ sa.supporting_structural_variation_id, sv.variation_name, sv.validation_status, s.name, s.version, s.description, sv.class_attrib_id, sv.study_id, sv.is_evidence, sv.somatic, sv.alias, sv.clinical_significance_attrib_id }; my $tables; foreach my $t ($self->_tables()) { next if ($t->[0] eq 'failed_structural_variation' and !$self->db->include_failed_variations()); $tables .= ',' if ($tables); $tables .= join(' ',@$t); # Adds a left join to the failed_structural_variation table if ($t->[0] eq 'structural_variation' and !$self->db->include_failed_variations()) { $tables .= qq{ LEFT JOIN failed_structural_variation fsv ON (fsv.structural_variation_id=sv.structural_variation_id)}; } } # Special case for one human study where SV can be a supporting evidence of an other SV my $constraint = $self->SUPER::_default_where_clause(); # Add the constraint for failed structural variant if (!$self->db->include_failed_variations()) { $constraint .= " AND " . $self->db->_exclude_failed_structural_variations_constraint(); } my $sth = $self->prepare(qq{SELECT $cols FROM $tables, structural_variation_association sa WHERE $constraint AND sa.supporting_structural_variation_id=sv.structural_variation_id AND sa.structural_variation_id = ?}); $sth->bind_param(1,$sv->dbID,SQL_INTEGER); $sth->execute(); my $results = $self->_objs_from_sth($sth); $sth->finish(); return $results; } =head2 fetch_all_SO_term_by_structural_variation_dbID Arg [1] : int $sv_id Example : my $sv = $sv_adaptor->fetch_by_name('esv9549'); foreach my $SO_term (@{$ssv_adaptor->fetch_all_SO_term_by_structural_variation_dbID($sv->dbID)}){ print $SO_term,"\n"; } Description : Retrieves all supporting evidences classes from a specified structural variant ID ReturnType : reference to list of strings Exceptions : throw if structural variation ID arg is not defined Caller : general Status : Stable =cut sub fetch_all_SO_term_by_structural_variation_dbID { my $self = shift; my $sv_id = shift; if(!defined($sv_id)) { throw("Structural variation ID arg expected"); } my @ssv_SO_list = (); # No failed SV/SSV in the structural_variation_feature table my $sth = $self->prepare(qq{SELECT distinct a.value FROM structural_variation_feature svf, structural_variation_association sa, attrib a WHERE sa.supporting_structural_variation_id=svf.structural_variation_id AND sa.structural_variation_id = ? AND svf.class_attrib_id=a.attrib_id }); $sth->bind_param(1,$sv_id,SQL_INTEGER); $sth->execute(); while (my ($SO_term) = $sth->fetchrow_array) { push (@ssv_SO_list, $SO_term); } return \@ssv_SO_list; } 1;
dbolser-ebi/ensembl-variation
modules/Bio/EnsEMBL/Variation/DBSQL/SupportingStructuralVariationAdaptor.pm
Perl
apache-2.0
8,664
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package os::mac::snmp::plugin; use strict; use warnings; use base qw(centreon::plugins::script_snmp); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; %{$self->{modes}} = ( 'cpu' => 'snmp_standard::mode::cpu', 'cpu-detailed' => 'snmp_standard::mode::cpudetailed', 'diskio' => 'snmp_standard::mode::diskio', 'disk-usage' => 'snmp_standard::mode::diskusage', 'inodes' => 'snmp_standard::mode::inodes', 'interfaces' => 'snmp_standard::mode::interfaces', 'load' => 'snmp_standard::mode::loadaverage', 'list-diskspath' => 'snmp_standard::mode::listdiskspath', 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'list-storages' => 'snmp_standard::mode::liststorages', 'memory' => 'os::mac::snmp::mode::memory', 'processcount' => 'snmp_standard::mode::processcount', 'storage' => 'snmp_standard::mode::storage', 'swap' => 'snmp_standard::mode::swap', 'time' => 'snmp_standard::mode::ntp', 'tcpcon' => 'snmp_standard::mode::tcpcon', 'uptime' => 'snmp_standard::mode::uptime', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Mac OS operating systems in SNMP. Some modes ('cpu', 'load, 'swap', 'memory') needs 'bsnmp-ucd'. =cut
Sims24/centreon-plugins
os/mac/snmp/plugin.pm
Perl
apache-2.0
2,619
package RPi::PIGPIO; =head1 NAME RPi::PIGPIO - remotely control the GPIO on a RaspberryPi using the pigpiod daemon =head1 DESCRIPTION This module impements a client for the pigpiod daemon, and can be used to control the GPIO on a local or remote RaspberryPi On every RapberryPi that you want to use you must have pigpiod daemon running! You can download pigpiod from here L<http://abyz.co.uk/rpi/pigpio/download.html> =head2 SYNOPSYS Blink a led connecyed to GPIO17 on the RasPi connected to the network with ip address 192.168.1.10 use RPi::PIGPIO ':all'; my $pi = RPi::PIGPIO->connect('192.168.1.10'); $pi->set_mode(17, PI_OUTPUT); $pi->write(17, HI); sleep 3; $pi->write(17, LOW); Easier mode to controll leds / switches : use RPi::PIGPIO; use RPi::PIGPIO::Device::LED; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $led = RPi::PIGPIO::Device::LED->new($pi,17); $led->on; sleep 3; $led->off; Same with a switch (relay): use RPi::PIGPIO; use RPi::PIGPIO::Device::Switch; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $switch = RPi::PIGPIO::Device::Switch->new($pi,4); $switch->on; sleep 3; $switch->off; Read the temperature and humidity from a DHT22 sensor connected to GPIO4 use RPi::PIGPIO; use RPi::PIGPIO::Device::DHT22; my $dht22 = RPi::PIGPIO::Device::DHT22->new($pi,4); $dht22->trigger(); #trigger a read print "Temperature : ".$dht22->temperature."\n"; print "Humidity : ".$dht22->humidity."\n"; =head1 ALREADY IMPLEMENTED DEVICES Note: you can write your own code using methods implemeted here to controll your own device This is just a list of devices for which we already implemented some functionalities to make your life easier =head2 Generic LED See complete documentations here: L<RPi::PIGPIO::Device::LED> Usage: use RPi::PIGPIO; use RPi::PIGPIO::Device::LED; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $led = RPi::PIGPIO::Device::LED->new($pi,17); $led->on; sleep 3; $led->off; =head2 Seneric switch / relay See complete documentations here: L<RPi::PIGPIO::Device::Switch> Usage: use RPi::PIGPIO; use RPi::PIGPIO::Device::Switch; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $switch = RPi::PIGPIO::Device::Switch->new($pi,4); $switch->on; sleep 3; $switch->off; =head2 DHT22 temperature/humidity sensor See complete documentations here : L<RPi::PIGPIO::Device::DHT22> Usage: use RPi::PIGPIO; use RPi::PIGPIO::Device::DHT22; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $dht22 = RPi::PIGPIO::Device::DHT22->new($pi,4); $dht22->trigger(); #trigger a read print "Temperature : ".$dht22->temperature."\n"; print "Humidity : ".$dht22->humidity."\n"; =head2 BMP180 atmospheric presure/temperature sensor See complete documentations here : L<RPi::PIGPIO::Device::BMP180> Usage: use RPi::PIGPIO; use RPi::PIGPIO::Device::BMP180; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $bmp180 = RPi::PIGPIO::Device::BMP180->new($pi,1); $bmp180->read_sensor(); #trigger a read print "Temperature : ".$bmp180->temperature." C\n"; print "Presure : ".$bmp180->presure." mbar\n"; =head2 DSM501A dust particle concentraction sensor See complete documentations here : L<RPi::PIGPIO::Device::DSM501A> Usage: use RPi::PIGPIO; use RPi::PIGPIO::Device::DSM501A; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $dust_sensor = RPi::PIGPIO::Device::DSM501A->new($pi,4); # Sample the air for 30 seconds and report my ($ratio, $mg_per_m3, $pcs_per_m3, $pcs_per_ft3) = $dust_sensor->sample(); =head2 MH-Z14 CO2 module See complete documentations here: L<RPi::PIGPIO::Device::MH_Z14> Usage: use RPi::PIGPIO; use RPi::PIGPIO::Device::MH_Z14; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $co2_sensor = RPi::PIGPIO::Device::MH_Z14->new($pi,mode => 'serial', tty => '/dev/ttyAMA0'); $ppm = $co2_sensor->read(); =head2 MCP3008/MCP3004 analog-to-digital convertor See complete documentations here: L<RPi::PIGPIO::Device::ADC::MCP300x> Usage: use feature 'say'; use RPi::PIGPIO; use RPi::PIGPIO::Device::ADC::MCP300x; my $pi = RPi::PIGPIO->connect('192.168.1.10'); my $mcp = RPi::PIGPIO::Device::ADC::MCP300x->new(0); say "Sensor 1: " .$mcp->read(0); say "Sensor 2: " .$mcp->read(1); =back =cut use strict; use warnings; our $VERSION = '0.017'; use Exporter 5.57 'import'; use Carp; use IO::Socket::INET; use Package::Constants; use constant { PI_INPUT => 0, PI_OUTPUT => 1, PI_ALT0 => 4, PI_ALT1 => 5, PI_ALT2 => 6, PI_ALT3 => 7, PI_ALT4 => 3, PI_ALT5 => 2, HI => 1, LOW => 0, RISING_EDGE => 0, FALLING_EDGE => 1, EITHER_EDGE => 2, PI_PUD_OFF => 0, PI_PUD_DOWN => 1, PI_PUD_UP => 2, }; use constant { PI_CMD_MODES => 0, PI_CMD_MODEG => 1, PI_CMD_PUD => 2, PI_CMD_READ => 3, PI_CMD_WRITE => 4, PI_CMD_PWM => 5, PI_CMD_PRS => 6, PI_CMD_PFS => 7, PI_CMD_SERVO => 8, PI_CMD_WDOG => 9, PI_CMD_BR1 => 10, PI_CMD_BR2 => 11, PI_CMD_BC1 => 12, PI_CMD_BC2 => 13, PI_CMD_BS1 => 14, PI_CMD_BS2 => 15, PI_CMD_TICK => 16, PI_CMD_HWVER => 17, PI_CMD_NO => 18, PI_CMD_NB => 19, PI_CMD_NP => 20, PI_CMD_NC => 21, PI_CMD_PRG => 22, PI_CMD_PFG => 23, PI_CMD_PRRG => 24, PI_CMD_HELP => 25, PI_CMD_PIGPV => 26, PI_CMD_WVCLR => 27, PI_CMD_WVAG => 28, PI_CMD_WVAS => 29, PI_CMD_WVGO => 30, PI_CMD_WVGOR => 31, PI_CMD_WVBSY => 32, PI_CMD_WVHLT => 33, PI_CMD_WVSM => 34, PI_CMD_WVSP => 35, PI_CMD_WVSC => 36, PI_CMD_TRIG => 37, PI_CMD_PROC => 38, PI_CMD_PROCD => 39, PI_CMD_PROCR => 40, PI_CMD_PROCS => 41, PI_CMD_SLRO => 42, PI_CMD_SLR => 43, PI_CMD_SLRC => 44, PI_CMD_PROCP => 45, PI_CMD_MICRO => 46, PI_CMD_MILLI => 47, PI_CMD_PARSE => 48, PI_CMD_WVCRE => 49, PI_CMD_WVDEL => 50, PI_CMD_WVTX => 51, PI_CMD_WVTXR => 52, PI_CMD_WVNEW => 53, PI_CMD_I2CO => 54, PI_CMD_I2CC => 55, PI_CMD_I2CRD => 56, PI_CMD_I2CWD => 57, PI_CMD_I2CWQ => 58, PI_CMD_I2CRS => 59, PI_CMD_I2CWS => 60, PI_CMD_I2CRB => 61, PI_CMD_I2CWB => 62, PI_CMD_I2CRW => 63, PI_CMD_I2CWW => 64, PI_CMD_I2CRK => 65, PI_CMD_I2CWK => 66, PI_CMD_I2CRI => 67, PI_CMD_I2CWI => 68, PI_CMD_I2CPC => 69, PI_CMD_I2CPK => 70, PI_CMD_SPIO => 71, PI_CMD_SPIC => 72, PI_CMD_SPIR => 73, PI_CMD_SPIW => 74, PI_CMD_SPIX => 75, PI_CMD_SERO => 76, PI_CMD_SERC => 77, PI_CMD_SERRB => 78, PI_CMD_SERWB => 79, PI_CMD_SERR => 80, PI_CMD_SERW => 81, PI_CMD_SERDA => 82, PI_CMD_GDC => 83, PI_CMD_GPW => 84, PI_CMD_HC => 85, PI_CMD_HP => 86, PI_CMD_CF1 => 87, PI_CMD_CF2 => 88, PI_CMD_NOIB => 99, PI_CMD_BI2CC => 89, PI_CMD_BI2CO => 90, PI_CMD_BI2CZ => 91, PI_CMD_I2CZ => 92, PI_CMD_WVCHA => 93, PI_CMD_SLRI => 94, PI_CMD_CGI => 95, PI_CMD_CSI => 96, PI_CMD_FG => 97, PI_CMD_FN => 98, PI_CMD_WVTXM => 100, PI_CMD_WVTAT => 101, PI_CMD_PADS => 102, PI_CMD_PADG => 103, PI_CMD_FO => 104, PI_CMD_FC => 105, PI_CMD_FR => 106, PI_CMD_FW => 107, PI_CMD_FS => 108, PI_CMD_FL => 109, PI_CMD_SHELL => 110, PI_CMD_BSPIC => 112, # bbSPIClose PI_CMD_BSPIO => 134, # bbSPIOpen PI_CMD_BSPIX => 193, # bbSPIXfer }; # notification flags use constant { NTFY_FLAGS_ALIVE => (1 << 6), NTFY_FLAGS_WDOG => (1 << 5), NTFY_FLAGS_GPIO => 31, }; our @EXPORT_OK = Package::Constants->list( __PACKAGE__ ); our %EXPORT_TAGS = ( 'all' => \@EXPORT_OK ); =head1 METHODS =head2 connect Connects to the pigpiod running on the given IP address/port and returns an object that will allow us to manipulate the GPIO on that Raspberry Pi Usage: my $pi = RPi::PIGPIO->connect('127.0.0.1'); Arguments: =over 4 =item * arg1: ip_address - The IP address of the pigpiod daemon =item * arg2: port - optional, defaults to 8888 =back Note: The pigiod daemon must be running on the raspi that you want to use =cut sub connect { my ($class,$address,$port) = @_; $port ||= 8888; my $sock = IO::Socket::INET->new( PeerAddr => $address, PeerPort => $port, Proto => 'tcp' ); my $pi = { sock => $sock, host => $address, port => $port, }; bless $pi, $class; } =head2 connected Returns true is we have an established connection with the remote pigpiod daemon =cut sub connected { my $self = shift; return $self->{sock} && $self->{sock}->connected(); } =head2 disconnect Disconnect from the gpiod daemon. The current object is no longer usable once we disconnect. =cut sub disconnect { my $self = shift; $self->prepare_for_exit(); undef $_[0]; } =head2 get_mode Returns the mode of a given GPIO pin Usage : my $mode = $pi->get_mode(4); Arguments: =over 4 =item * arg1: gpio - GPIO for which you want to change the mode =back Return values (constant exported by this module): 0 = PI_INPUT 1 = PI_OUTPUT 4 = PI_ALT0 5 = PI_ALT1 6 = PI_ALT2 7 = PI_ALT3 3 = PI_ALT4 2 = PI_ALT5 =cut sub get_mode { my $self = shift; my $gpio = shift; die "Usage : \$pi->get_mode(<gpio>)" unless (defined($gpio)); return $self->send_command(PI_CMD_MODEG,$gpio); } =head2 set_mode Sets the GPIO mode Usage: $pi->set_mode(17, PI_OUTPUT); Arguments : =over 4 =item * arg1: gpio - GPIO for which you want to change the mode =item * arg2: mode - the mode that you want to set. Valid values for I<mode> are exported as constants and are : PI_INPUT, PI_OUTPUT, PI_ALT0, PI_ALT1, PI_ALT2, PI_ALT3, PI_ALT4, PI_ALT5 =back Returns 0 if OK, otherwise PI_BAD_GPIO, PI_BAD_MODE, or PI_NOT_PERMITTED. =cut sub set_mode { my ($self,$gpio,$mode) = @_; die "Usage : \$pi->set_mode(<gpio>, <mode>)" unless (defined($gpio) && defined($mode)); return $self->send_command(PI_CMD_MODES,$gpio,$mode); } =head2 write Sets the voltage level on a GPIO pin to HI or LOW Note: You first must set the pin mode to PI_OUTPUT Usage : $pi->write(17, HI); or $pi->write(17, LOW); Arguments: =over 4 =item * arg1: gpio - GPIO to witch you want to write =item * arg2: level - The voltage level that you want to write (one of HI or LOW) =back Note: This method will set the GPIO mode to "OUTPUT" and leave it like this =cut sub write { my ($self,$gpio,$level) = @_; return $self->send_command(PI_CMD_WRITE,$gpio,$level); } =head2 read Gets the voltage level on a GPIO Note: You first must set the pin mode to PI_INPUT Usage : $pi->read(17); Arguments: =over 4 =item * arg1: gpio - gpio that you want to read =back Note: This method will set the GPIO mode to "INPUT" and leave it like this =cut sub read { my ($self,$gpio) = @_; return $self->send_command(PI_CMD_READ,$gpio); } =head2 set_watchdog If no level change has been detected for the GPIO for timeout milliseconds any notification for the GPIO has a report written to the fifo with the flags set to indicate a watchdog timeout. Arguments: =over 4 =item * arg1: gpio - GPIO for which to set the watchdog =item * arg2. timeout - time to wait for a level change in milliseconds. =back Only one watchdog may be registered per GPIO. The watchdog may be cancelled by setting timeout to 0. NOTE: This method requires another connection to be created and subcribed to notifications for this GPIO (see DHT22 implementation) =cut sub set_watchdog { my ($self,$gpio,$timeout) = @_; $self->send_command( PI_CMD_WDOG, $gpio, $timeout); } =head2 set_pull_up_down Set or clear the GPIO pull-up/down resistor. =over 4 =item * arg1: gpio - GPIO for which we want to modify the pull-up/down resistor =item * arg2: level - PI_PUD_UP, PI_PUD_DOWN, PI_PUD_OFF. =back Usage: $pi->set_pull_up_down(18, PI_PUD_DOWN); =cut sub set_pull_up_down { my ($self,$gpio,$level) = @_; $self->send_command(PI_CMD_PUD, $gpio, $level); } =head2 gpio_trigger This function sends a trigger pulse to a GPIO. The GPIO is set to level for pulseLen microseconds and then reset to not level. Arguments (in this order): =over 4 =item * arg1: gpio - number of the GPIO pin we want to monitor =item * arg2: length - pulse length in microseconds =item * arg3: level - level to use for the trigger (HI or LOW) =back Usage: $pi->gpio_trigger(4,17,LOW); Note: After running you call this method the GPIO is left in "INPUT" mode =cut sub gpio_trigger { my ($self,$gpio,$length,$level) = @_; $self->send_command_ext(PI_CMD_TRIG, $gpio, $length, [ $level ]); } =head2 SPI interface =head3 spi_open Comunication is done via harware SPI so MAKE SURE YOU ENABLED SPI on your RPi (use raspi-config command and go to "Advanced") Returns a handle for the SPI device on channel. Data will be transferred at baud bits per second. The flags may be used to modify the default behaviour of 4-wire operation, mode 0, active low chip select. An auxiliary SPI device is available on all models but the A and B and may be selected by setting the A bit in the flags. The auxiliary device has 3 chip selects and a selectable word size in bits. Arguments: =over 4 =item * arg1: spi_channel:= 0-1 (0-2 for the auxiliary SPI device). =item * arg2: baud:= 32K-125M (values above 30M are unlikely to work). =item * arg3: spi_flags:= see below. =back spi_flags consists of the least significant 22 bits. 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 b b b b b b R T n n n n W A u2 u1 u0 p2 p1 p0 m m mm defines the SPI mode. WARNING: modes 1 and 3 do not appear to work on the auxiliary device. Mode POL PHA 0 0 0 1 0 1 2 1 0 3 1 1 px is 0 if CEx is active low (default) and 1 for active high. ux is 0 if the CEx GPIO is reserved for SPI (default) and 1 otherwise. A is 0 for the standard SPI device, 1 for the auxiliary SPI. W is 0 if the device is not 3-wire, 1 if the device is 3-wire. Standard SPI device only. nnnn defines the number of bytes (0-15) to write before switching the MOSI line to MISO to read data. This field is ignored if W is not set. Standard SPI device only. T is 1 if the least significant bit is transmitted on MOSI first, the default (0) shifts the most significant bit out first. Auxiliary SPI device only. R is 1 if the least significant bit is received on MISO first, the default (0) receives the most significant bit first. Auxiliary SPI device only. bbbbbb defines the word size in bits (0-32). The default (0) sets 8 bits per word. Auxiliary SPI device only. The C<spi_read>, C<spi_write>, and C<spi_xfer> functions transfer data packed into 1, 2, or 4 bytes according to the word size in bits. For bits 1-8 there will be one byte per character. For bits 9-16 there will be two bytes per character. For bits 17-32 there will be four bytes per character. E.g. 32 12-bit words will be transferred in 64 bytes. The other bits in flags should be set to zero. Example: open SPI device on channel 1 in mode 3 at 50k bits per second my $spi_handle = $pi->spi_open(1, 50_000, 3); =cut sub spi_open { my ($self, $spi_channel, $baud, $spi_flags) = @_; $spi_flags //= 0; return $self->send_command_ext(PI_CMD_SPIO, $spi_channel, $baud, [ $spi_flags ]); } =head3 spi_close Closes an SPI channel Usage : my $spi = $pi->spi_open(0,32_000); ... $pi->spi_close($spi); =cut sub spi_close { my ($self, $handle) = @_; return $self->send_command(PI_CMD_SPIC, $handle, 0); } =head3 spi_read Arguments (in this order): =over 4 =item * arg1: handle= >=0 (as returned by a prior call to C<spi_open>). =item * arg2: count= >0, the number of bytes to read. =back The returned value is a bytearray containing the bytes. Usage: my $spi_handle = $pi->spi_open(1, 50_000, 3); my $data = $pi->spi_read($spi_handle, 12); $pi->spi_close($spi_handle); =cut sub spi_read { my ($self, $handle, $count) = @_; $self->send_command(PI_CMD_SPIR, $handle, $count); my $response; $self->{sock}->recv($response,3); return $response; } =head3 spi_write Writes the data bytes to the SPI device associated with handle. Arguments (in this order): =over 4 =item * arg1: handle:= >=0 (as returned by a prior call to C<spi_open>). =item * arg2: data:= the bytes to write. =back Examples : my $spi_handle = $pi->spi_open(1, 50_000, 3); $pi->spi_write($spi_handle, [2, 192, 128]); # write 3 bytes to device 1 =cut sub spi_write { my ($self, $handle, $data) = @_; if (! ref($data) ) { $data = [ map {ord} split("",$data) ]; } return $self->send_command_ext(PI_CMD_SPIW, $handle, 0, $data); } =head3 spi_xfer Writes the data bytes to the SPI device associated with handle, returning the data bytes read from the device. Arguments (in this order): =over 4 =item * arg1: handle= >=0 (as returned by a prior call to C<spi_open>). =item * arg2: data= the bytes to write. =back The returned value is a bytearray containing the bytes. Examples : my $spi_handle = $pi->spi_open(1, 50_000, 3); my $rx_data = $pi->spi_xfer($spi_handle, [1, 128, 0]); =cut sub spi_xfer { my ($self, $handle, $data) = @_; if (! ref($data) ) { $data = [ map {ord} split("",$data) ]; } my $bytes = $self->send_command_ext(PI_CMD_SPIX, $handle, 0, $data); my $response; $self->{sock}->recv($response,$bytes); return $response; } =head2 Serial interface =head3 serial_open Returns a handle for the serial tty device opened at baud bits per second. The device name must start with /dev/tty or /dev/serial. Arguments : =over 4 =item * arg1 : tty => the serial device to open. =item * arg2 : baud => baud rate in bits per second, see below. =back Returns: a handle for the serial connection which will be used in calls to C<serial_*> methods The baud rate must be one of 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, or 230400. Notes: On the raspi on which you want to use the serial device you have to : =over 4 =item 1 enable UART -> run C<sudo nano /boot/config.txt> and add the bottom C<enable_uart=1> =item 2 run C<sudo raspi-config> and disable the login via the Serial port =back More info (usefull for Raspi 3) here : L<http://spellfoundry.com/2016/05/29/configuring-gpio-serial-port-raspbian-jessie-including-pi-3/> Usage: $h1 = $pi->serial_open("/dev/ttyAMA0", 300) $h2 = $pi->serial_open("/dev/ttyUSB1", 19200, 0) $h3 = $pi->serial_open("/dev/serial0", 9600) =cut sub serial_open { my ($self,$tty,$baud) = @_; my $sock = $self->{sock}; my $msg = pack('IIII', PI_CMD_SERO, $baud, 0, length($tty)); $sock->send($msg); $sock->send($tty); my $response; $sock->recv($response,16); my ($x, $val) = unpack('a[12] I', $response); return $val; } =head3 serial_close Closes the serial device associated with handle. Arguments: =over 4 =item * arg1: handle => the connection as returned by a prior call to C<serial_open> =back Usage: $pi->serial_close($handle); =cut sub serial_close { my ($self,$handle) = @_; return $self->send_command(PI_CMD_SERC,$handle); } =head3 serial_write Write a string to the serial handle opened with C<serial_open> Arguments: =over 4 =item * arg1: handle => connection handle obtained from calling C<serial_open> =item * arg2: data => data to write (string) =back Usage : my $h = $pi->serial_open('/dev/ttyAMA0',9600); my $data = 'foo bar'; $pi->serial_write($h, $data); $pi->serial_close($h); =cut sub serial_write { my ($self,$handle,$data) = @_; my $sock = $self->{sock}; my $msg = pack('IIII', PI_CMD_SERW, $handle, 0, length($data)); $sock->send($msg); $sock->send($data); my $response; $sock->recv($response,16); my ($x, $val) = unpack('a[12] I', $response); } =head3 serial_read Read a string from the serial handle opened with C<serial_open> Arguments: =over 4 =item * arg1: handle => connection handle obtained from calling C<serial_open> =item * arg2: count => number of bytes to read =back Usage : my $h = $pi->serial_open('/dev/ttyAMA0',9600); my $data = $pi->serial_read($h, 10); #read 10 bytes $pi->serial_close($h); Note: Between a read and a write you might want to sleep for half a second =cut sub serial_read { my ($self,$handle,$count) = @_; my $bytes = $self->send_command(PI_CMD_SERR, $handle, $count); my $response; $self->{sock}->recv($response,$count); return $response; } =head3 serial_data_available Checks if we have any data waiting to be read from the serial handle Usage : my $h = $pi->serial_open('/dev/ttyAMA0',9600); my $count = $pi->serial_data_available($h); my $data = $pi->serial_read($h, $count); $pi->serial_close($h); =cut sub serial_data_available { my ($self,$handle) = @_; return $self->send_command(PI_CMD_SERDA, $handle); } =head2 I2C interface =head3 i2c_open Returns a handle (>=0) for the device at the I2C bus address. Arguments: =over 4 =item * i2c_bus: >=0 the i2c bus number =item * i2c_address: 0-0x7F => the address of the device on the bus =item * i2c_flags: defaults to 0, no flags are currently defined (optional). =back Physically buses 0 and 1 are available on the Pi. Higher numbered buses will be available if a kernel supported bus multiplexor is being used. Usage : my $handle = $pi->i2c_open(1, 0x53) # open device at address 0x53 on bus 1 =cut sub i2c_open { my ($self, $i2c_bus, $i2c_address, $i2c_flags) = @_; $i2c_flags ||= 0; return $self->send_command_ext(PI_CMD_I2CO, $i2c_bus, $i2c_address, [$i2c_flags]); } =head3 i2c_close Closes the I2C device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =back =cut sub i2c_close { my ($self, $handle) = @_; return $self->send_command(PI_CMD_I2CC, $handle, 0); } =head3 i2c_write_quick Sends a single bit to the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * bit: 0 or 1, the value to write. =back Usage: $pi->i2c_write_quick(0, 1) # send 1 to device 0 $pi->i2c_write_quick(3, 0) # send 0 to device 3 =cut sub i2c_write_quick { my ($self, $handle, $bit) = @_; return $self->send_command(PI_CMD_I2CWQ, $handle, $bit); } =head3 i2c_write_byte Sends a single byte to the device associated with handle. =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * byte_val: 0-255, the value to write. =back Usage: $pi->i2c_write_byte(1, 17) # send byte 17 to device 1 $pi->i2c_write_byte(2, 0x23) # send byte 0x23 to device 2 =cut sub i2c_write_byte { my ($self, $handle, $byte_val) = @_; return $self->send_command(PI_CMD_I2CWS, $handle, $byte_val); } =head3 i2c_read_byte Reads a single byte from the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =back Usage: my $val = $pi->i2c_read_byte(2) # read a byte from device 2 =cut sub i2c_read_byte { my ($self, $handle) = @_; return $self->send_command(PI_CMD_I2CRS, $handle, 0); } =head3 i2c_write_byte_data Writes a single byte to the specified register of the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =item * byte_val: 0-255, the value to write. =back Usage: # send byte 0xC5 to reg 2 of device 1 $pi->i2c_write_byte_data(1, 2, 0xC5); # send byte 9 to reg 4 of device 2 $pi->i2c_write_byte_data(2, 4, 9); =cut sub i2c_write_byte_data { my ($self, $handle, $reg, $byte_val) = @_; $self->send_command_ext(PI_CMD_I2CWB, $handle, $reg, [$byte_val]); } =head3 i2c_write_word_data Writes a single 16 bit word to the specified register of the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =item * word_val: 0-65535, the value to write. =back Usage: # send word 0xA0C5 to reg 5 of device 4 $pi->i2c_write_word_data(4, 5, 0xA0C5); # send word 2 to reg 2 of device 5 $pi->i2c_write_word_data(5, 2, 23); =cut sub i2c_write_word_data { my ($self, $handle, $reg, $word_val) = @_; return $self->send_command_ext(PI_CMD_I2CWW, $handle, $reg, [$word_val]); } =head3 i2c_read_byte_data Reads a single byte from the specified register of the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =back Usage: # read byte from reg 17 of device 2 my $b = $pi->i2c_read_byte_data(2, 17); # read byte from reg 1 of device 0 my $b = pi->i2c_read_byte_data(0, 1); =cut sub i2c_read_byte_data { my ($self, $handle, $reg) = @_; return $self->send_command(PI_CMD_I2CRB, $handle, $reg); } =head3 i2c_read_word_data Reads a single 16 bit word from the specified register of the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =back Usage: # read byte from reg 17 of device 2 my $w = $pi->i2c_read_word_data(2, 17); # read byte from reg 1 of device 0 my $w = pi->i2c_read_word_data(0, 1); =cut sub i2c_read_word_data { my ($self, $handle, $reg) = @_; return $self->send_command(PI_CMD_I2CRW, $handle, $reg); } =head3 i2c_process_call Writes 16 bits of data to the specified register of the device associated with handle and reads 16 bits of data in return. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =item * word_val: 0-65535, the value to write. =back Usage: my $r = $pi->i2c_process_call(1, 4, 0x1231); my $r = $pi->i2c_process_call(2, 6, 0); =cut sub i2c_process_call { my ($self, $handle, $reg, $word_val) = @_; return $self->send_command_ext(PI_CMD_I2CPC, $handle, $reg, [$word_val]); } =head3 i2c_write_block_data Writes up to 32 bytes to the specified register of the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =item * data: arrayref of bytes to write =back Usage: $pi->i2c_write_block_data(6, 2, [0, 1, 0x22]); =cut sub i2c_write_block_data { my ($self, $handle, $reg, $data) = @_; return 0 unless $data; croak "data needs to be an arrayref" unless (ref $data eq "ARRAY"); return $self->send_command_ext(PI_CMD_I2CWK, $handle, $reg, $data); } =head3 i2c_read_block_data Reads a block of up to 32 bytes from the specified register of the device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =back The amount of returned data is set by the device. The returned value is a tuple of the number of bytes read and a bytearray containing the bytes. If there was an error the number of bytes read will be less than zero (and will contain the error code). Usage: my ($bytes,$data) = $pi->i2c_read_block_data($handle, 10); =cut sub i2c_read_block_data { my ($self, $handle, $reg) = @_; my ($bytes, $data) = $self->send_i2c_command(PI_CMD_I2CRK, $handle, $reg); return ($bytes, $data); } =head3 i2c_block_process_call Writes data bytes to the specified register of the device associated with handle and reads a device specified number of bytes of data in return. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =item * data: arrayref of bytes to write =back Usage: my ($bytes,$data) = $pi->i2c_block_process_call($handle, 10, [2, 5, 16]); The returned value is a tuple of the number of bytes read and a bytearray containing the bytes. If there was an error the number of bytes read will be less than zero (and will contain the error code). =cut sub i2c_block_process_call { my ($self, $handle, $reg, $data) = @_; my ($bytes, $recv_data) = $self->send_i2c_command(PI_CMD_I2CPK, $handle, $reg, [$data]); return ($bytes, $recv_data); } =head3 i2c_write_i2c_block_data Writes data bytes to the specified register of the device associated with handle. 1-32 bytes may be written. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =item * data: arrayref of bytes to write =back Usage: $pi->i2c_write_i2c_block_data(6, 2, [0, 1, 0x22]); =cut sub i2c_write_i2c_block_data { my ($self, $handle, $reg, $data) = @_; return $self->send_command_ext(PI_CMD_I2CWI, $handle, $reg, $data); } =head3 i2c_read_i2c_block_data Reads count bytes from the specified register of the device associated with handle. The count may be 1-32. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * reg: >=0, the device register. =item * count: >0, the number of bytes to read (1-32). =back Usage: my ($bytes, $data) = $pi->i2c_read_i2c_block_data($handle, 4, 32); The returned value is a tuple of the number of bytes read and a bytearray containing the bytes. If there was an error the number of bytes read will be less than zero (and will contain the error code). =cut sub i2c_read_i2c_block_data { my ($self, $handle, $reg, $count) = @_; my ($bytes, $data) = $self->send_i2c_command(PI_CMD_I2CRI, $handle, $reg, [$count]); return ($bytes, $data); } =head3 i2c_read_device Returns count bytes read from the raw device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * count: >0, the number of bytes to read (1-32). =back Usage: my ($count, $data) = $pi->i2c_read_device($handle, 12); =cut sub i2c_read_device { my ($self, $handle, $count) = @_; my ($bytes, $data) = $self->send_i2c_command(PI_CMD_I2CRD, $handle, $count); return ($bytes, $data); } =head3 i2c_write_device Writes the data bytes to the raw device associated with handle. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * data: arrayref of bytes to write =back Usage: $pi->i2c_write_device($handle, [23, 56, 231]); =cut sub i2c_write_device { my ($self, $handle, $data) = @_; return $self->send_command_ext(PI_CMD_I2CWD, $handle, 0, $data); } =head3 i2c_zip This function executes a sequence of I2C operations. The operations to be performed are specified by the contents of data which contains the concatenated command codes and associated data. Arguments: =over 4 =item * handle: >=0 ( as returned by a prior call to C<i2c_open()> ) =item * data: arrayref of the concatenated I2C commands, see below =back The returned value is a tuple of the number of bytes read and a bytearray containing the bytes. If there was an error the number of bytes read will be less than zero (and will contain the error code). Usage: my ($count, $data) = $pi->i2c_zip($handle, [4, 0x53, 7, 1, 0x32, 6, 6, 0]) The following command codes are supported: Name @ Cmd & Data @ Meaning End @ 0 @ No more commands Escape @ 1 @ Next P is two bytes On @ 2 @ Switch combined flag on Off @ 3 @ Switch combined flag off Address @ 4 P @ Set I2C address to P Flags @ 5 lsb msb @ Set I2C flags to lsb + (msb << 8) Read @ 6 P @ Read P bytes of data Write @ 7 P ... @ Write P bytes of data The address, read, and write commands take a parameter P. Normally P is one byte (0-255). If the command is preceded by the Escape command then P is two bytes (0-65535, least significant byte first). The address defaults to that associated with the handle. The flags default to 0. The address and flags maintain their previous value until updated. Any read I2C data is concatenated in the returned bytearray. Set address 0x53, write 0x32, read 6 bytes Set address 0x1E, write 0x03, read 6 bytes Set address 0x68, write 0x1B, read 8 bytes End 0x04 0x53 0x07 0x01 0x32 0x06 0x06 0x04 0x1E 0x07 0x01 0x03 0x06 0x06 0x04 0x68 0x07 0x01 0x1B 0x06 0x08 0x00 =cut sub i2c_zip { my ($self, $handle, $commands) = @_; my ($bytes, $data) = $self->send_i2c_command(PI_CMD_I2CZ, $handle, 0, $commands); return ($bytes, $data); } =head2 PWM =head3 write_pwm Sets the voltage level on a GPIO pin to a value from 0-255 (PWM) approximating a lower voltage. Useful for dimming LEDs for example. Note: You first must set the pin mode to PI_OUTPUT Usage : $pi->write_pwm(17, 255); or $pi->write_pwm(17, 120); or $pi->write_pwm(17, 0); Arguments: =over 4 =item * arg1: gpio - GPIO to which you want to write =item * arg2: level - The voltage level that you want to write (one of 0-255) =back Note: This method will set the GPIO mode to "OUTPUT" and leave it like this =cut sub write_pwm { my ($self,$gpio,$level) = @_; return $self->send_command(PI_CMD_PWM,$gpio,$level); } ################################################################################################################################ =head1 PRIVATE METHODS =cut =head2 send_command Sends a command to the pigiod daemon and waits for a response =over 4 =item * arg1: command - code of the command you want to send (see package constants) =item * arg2: param1 - first parameter (usualy the GPIO) =item * arg3: param2 - second parameter - optional - usualy the level to which to set the GPIO (HI/LOW) =back =cut sub send_command { my $self = shift; if (! $self->{sock}->connected) { $self->{sock} = IO::Socket::INET->new( PeerAddr => $self->{address}, PeerPort => $self->{port}, Proto => 'tcp' ); } return unless $self->{sock}; return $self->send_command_on_socket($self->{sock},@_); } =head2 send_command_on_socket Same as C<send_command> but allows you to specify the socket you want to use The pourpose of this is to allow you to use the send_command functionality on secondary connections used to monitor changes on GPIO Arguments: =over 4 =item * arg1: socket - Instance of L<IO::Socket::INET> =item * arg2: command - code of the command you want to send (see package constants) =item * arg3: param1 - first parameter (usualy the GPIO) =item * arg3: param2 - second parameter - optional - usualy the level to which to set the GPIO (HI/LOW) =back =cut sub send_command_on_socket { my ($self, $sock, $cmd, $param1, $param2) = @_; $param2 //= 0; my $msg = pack('IIII', $cmd, $param1, $param2, 0); $sock->send($msg); my $response; $sock->recv($response,16); my ($x, $val) = unpack('a[12] I', $response); return $val; } =head2 send_command_ext Sends an I<extended command> to the pigpiod daemon =cut sub send_command_ext { my ($self,$cmd,$param1,$param2,$extra_params) = @_; my $sock; if (ref($self) ne "IO::Socket::INET") { $sock = $self->{sock}; } else { $sock = $self; } my $msg = pack('IIII', $cmd, $param1, $param2, 4 * scalar(@{$extra_params // []})); $sock->send($msg); foreach (@{$extra_params // []}) { $sock->send(pack("I",$_)); } my $response; $sock->recv($response,16); my ($x, $val) = unpack('a[12] I', $response); return $val; } =head2 send_i2c_command Method used for sending and reading back i2c data =cut sub send_i2c_command { my ($self, $command, $handle, $reg, $data) = @_; $data //= []; my $bytes = $self->send_command_ext($command, $handle, $reg, $data); if ($bytes > 0) { my $response; $self->{sock}->recv($response,$bytes); return $bytes, [unpack("C"x$bytes, $response)]; } else { return $bytes, ""; } } sub prepare_for_exit { my $self = shift; $self->{sock}->close() if $self->{sock}; } sub DESTROY { my $self = shift; $self->prepare_for_exit(); } 1;
gliganh/RPi-PIGPIO
lib/RPi/PIGPIO.pm
Perl
apache-2.0
37,602
package Bio::EnsEMBL::Funcgen::RunnableDB::PeakCalling::BrIdrComputePeakCallingInputs; use strict; use base 'Bio::EnsEMBL::Hive::Process'; use Data::Dumper; use constant { BRANCH_ALIGN_ALL_READ_FILES => 3, BRANCH_ALIGN_REPLICATES_FOR_IDR => 2, BRANCH_RUN_IDR_PEAK_CALLING => 4, }; sub run { my $self = shift; my $species = $self->param_required('species'); my $execution_plan = $self->param_required('execution_plan'); my $read_files = $execution_plan ->{call_peaks} ->{alignment} ->{source} ; my $run_idr = $execution_plan ->{call_peaks} ->{run_idr} ; my $alignment_replicates = $run_idr ->{alignment_replicates} ; $self->dataflow_output_id( { 'plan' => $read_files, 'species' => $species, }, BRANCH_ALIGN_ALL_READ_FILES ); foreach my $alignment_replicate (@$alignment_replicates) { $self->dataflow_output_id( { 'plan' => $alignment_replicate, 'species' => $species, }, BRANCH_ALIGN_REPLICATES_FOR_IDR ); $self->dataflow_output_id( { 'plan' => $alignment_replicate, 'species' => $species, }, BRANCH_RUN_IDR_PEAK_CALLING ); } } 1;
Ensembl/ensembl-funcgen
modules/Bio/EnsEMBL/Funcgen/RunnableDB/PeakCalling/BrIdrComputePeakCallingInputs.pm
Perl
apache-2.0
1,263
#! /usr/bin/env perl =head1 NAME ExtractSubtree<.pl> =head1 USAGE ExtractSubtree.pl -t <input tree> -ld <rooting life domain> -o <Output file> ExtractSubtree.pl [options -v,-d,-h] <ARGS> =head1 SYNOPSIS This script cuts out a section of the input newick tree(s) and outputs as a new newick file, as decided by a list of given taxa. Note that this includes all other members of the tree below the MRCA of the set of taxa given, unless the --remove flag is set to 1. The new trees are rooted on the MRCA of all members of the specified group (this can be a tab-seperated and/or newline seperated list as a file, genomes passed in through CLI or simply a SUPERFAMILY database life domain). =head1 AUTHOR B<Adam Sardar> - I<adam.sardar@bristol.ac.uk> =head1 COPYRIGHT Copyright 2011 Gough Group, University of Bristol. =cut # Strict Pragmas #---------------------------------------------------------------------------------------------------------------- use strict; use warnings; # Add Local Library to LibPath #---------------------------------------------------------------------------------------------------------------- use lib "$ENV{HOME}/bin/perl-libs-custom/"; # CPAN Includes #---------------------------------------------------------------------------------------------------------------- =head1 DEPENDANCY B<Getopt::Long> Used to parse command line options. B<Pod::Usage> Used for usage and help output. B<Data::Dumper> Used for debug output. =cut use Getopt::Long; #Deal with command line options use Pod::Usage; #Print a usage man page from the POD comments after __END__ use DBI; use Supfam::SQLFunc; use Supfam::TreeFuncs; use Bio::TreeIO; use Bio::Tree::TreeFunctionsI; use IO::String; # Command Line Options #---------------------------------------------------------------------------------------------------------------- my $verbose; #Flag for verbose output from command line opts my $debug; #As above for debug my $help; #Same again but this time should we output the POD man page defined after __END__ my $TreeFile; my $LifeDomain; my $outputfile; my $remove = 0; #Flag for removal of genomes not belonging to the extract genomes requested. Default is to include all genomes below the MRCA in the tree specified of all genomes asked. my $OutgroupGenomeFile; my @CLIOutgroupGenomes; my $outputformat = 'newick'; my $include = 1; #flag as to whether or not to include the 'include ='y'' genomes from the SUPERFAMILY database. This is only relevent to the life-domain option #Set command line flags and parameters. GetOptions("verbose|v!" => \$verbose, "debug|d!" => \$debug, "help|h!" => \$help, "tree|t:s" => \$TreeFile, "outgrouplifedomain|ld:s" => \$LifeDomain, "includeygenomes|iyg:s" => \$include, "outgroupgenome|og:s" => \@CLIOutgroupGenomes, "outgroupgenomefile|ogf:s" => \$OutgroupGenomeFile, "output|o:s" => \$outputfile, "outputformat|of:s" => \$outputformat, "remove|r:i" => \$remove, ) or die "Fatal Error: Problem parsing command-line ".$!; $outputfile = "$TreeFile.Extract" unless(defined($outputfile)); my $SelectedGroupNodes = []; #This is the ingroup for the tree #Populate $SelectedGroupNodes with outgroup; if($LifeDomain){ my $dbh = dbConnect(); my $sth; $sth = $dbh->prepare("SELECT genome FROM genome WHERE include = 'y' AND domain = ?;") ;#if($include); #$sth = $dbh->prepare("SELECT genome FROM genome WHERE domain = ?;") unless($include); $sth->execute($LifeDomain); while (my $genome = $sth->fetchrow_array() ) { push(@$SelectedGroupNodes,$genome);} #Populate @$SelectedGroupNodes with genomes from the chosen superfamily life domain dbDisconnect($dbh); } push(@$SelectedGroupNodes,@CLIOutgroupGenomes) if(scalar(@CLIOutgroupGenomes)); if($OutgroupGenomeFile){ open OUTGENOMES, "$OutgroupGenomeFile" or die $!; foreach my $line (<OUTGENOMES>){ chomp($line); next if ($line =~ m/^#/); #Weed out comment lines if($line =~ m/\t/){push(@$SelectedGroupNodes,split("\t",$line));}else{push(@$SelectedGroupNodes,$line);} #Input file can be any mixture of newlines and tab seperated entries, which this line catches and pushes onto @$SelectedGroupNodes } close OUTGENOMES; } die 'Selection must be larger than one gneome (a trvial tree). You must pass in a list of genomes, whose MRCA will serve as the root of the output tree!'."\n" unless (scalar(@$SelectedGroupNodes) > 1); # A little error checking #Read in a file of newick trees which to root. One tree per line open TREEFILE, "<$TreeFile"; my $out = Bio::TreeIO->new(-format => 'newick', -file => ">$outputfile"); while (my $FullTree = <TREEFILE>){ last if($FullTree =~ m/^#/ || $FullTree !~ m/;$/ ); #Weed out comments or lines that don't have a trailing ";" carachter. God knows why these are in there, but you never know ... chomp($FullTree); #Remove trailing newline carachter my $io = IO::String->new($FullTree); my $treeio = Bio::TreeIO->new(-fh => $io, -format => 'newick'); my $tree = $treeio->next_tree; my $subtree = ExtractSubtree($tree,$SelectedGroupNodes,$remove); $out->write_tree($subtree); #Thanks bioperl, you make everything easier! } close TREEFILE; __END__
adamsardar/TreeFuncs
ExtractSubtree.pl
Perl
apache-2.0
5,443
package Paws::SSM::UpdateAssociationStatus; use Moose; has AssociationStatus => (is => 'ro', isa => 'Paws::SSM::AssociationStatus', required => 1); has InstanceId => (is => 'ro', isa => 'Str', required => 1); has Name => (is => 'ro', isa => 'Str', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'UpdateAssociationStatus'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::SSM::UpdateAssociationStatusResult'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::SSM::UpdateAssociationStatus - Arguments for method UpdateAssociationStatus on Paws::SSM =head1 DESCRIPTION This class represents the parameters used for calling the method UpdateAssociationStatus on the Amazon Simple Systems Manager (SSM) service. Use the attributes of this class as arguments to method UpdateAssociationStatus. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to UpdateAssociationStatus. As an example: $service_obj->UpdateAssociationStatus(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> AssociationStatus => L<Paws::SSM::AssociationStatus> The association status. =head2 B<REQUIRED> InstanceId => Str The ID of the instance. =head2 B<REQUIRED> Name => Str The name of the Systems Manager document. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method UpdateAssociationStatus in L<Paws::SSM> =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/SSM/UpdateAssociationStatus.pm
Perl
apache-2.0
2,000
$_ = "Yabba dabba doo\n"; print;
kkdg/perl-jogging
01/0124/_.pl
Perl
apache-2.0
33
package InfoProcessing; use strict; ################################################################################ # # P E R L M O D U L E # ################################################################################ # # DATE OF ORIGIN : Mar 18, 2015 # #----------------------------------- PURPOSE ------------------------------------ #** @file InfoProcessing.pm # # This module will handle/process the information that has been gathered. # #* #----------------------------------- SYNOPSIS ----------------------------------- # CAUTIONS: # # ASSUMPTIONS/PRECONDITIONS: # # POSTCONDITIONS: # # PARAMETER DESCRIPTION: # Input: # # # Return value: # none # # #--------------------------- GLOBAL DATA DESCRIPTION ---------------------------- #---------------------------- PROJECT SPECIFIC DATA ----------------------------- # #---------------------------- DESCRIPTION OF LOGIC ------------------------------ # # ################################################################################ use vars qw(@ISA @EXPORT $VERSION); use Exporter; use Carp; use Data::Dumper; $VERSION = 0.1.3; @ISA = ('Exporter'); # List the functions and var's that must be available. # If you want to create a global var, create it as 'our' @EXPORT = qw( &IPMergeInstanceAndWrapperInfo &IPSetMachineConfiguration ); # ============================================================================== # V A R I A B L E S # ============================================================================== # ============================================================================== # F U N C T I O N S # ============================================================================== # ----------------------------------------------------------------- #** @function public IPMergeInstanceAndWrapperInfo # @brief Merge the Instance info and the, optional, install wrapper information. # The merged data is available in the $refhInstanceConfiguration. # # The section: FileProvidedDuringCloudInit will be merged and the InstallWrapper # configuration takes precedence to the Instance configuration. # # @params refhVirmanConfiguration required The Virman configuration Hash. # @params refhInstallWrapperConfiguration required The install wrapper data hash. # @retval value [details] # .... #* # --------------- sub IPMergeInstanceAndWrapperInfo { my $refhInstanceConfiguration = shift; my $refhInstallWrapperConfiguration = shift; #print "--- refhInstanceConfiguration\n"; #print Dumper($refhInstanceConfiguration); print "--- refhInstallWrapperConfiguration\n"; print Dumper($refhInstallWrapperConfiguration); # Get length of pre list. my @arInstWrapPreNetworkKeys = sort(keys $refhInstallWrapperConfiguration->{'PreNetworkConfiguration'}); my @arInstWrapPostNetworkKeys = sort(keys $refhInstallWrapperConfiguration->{'PostNetworkConfiguration'}); # reverse the list of instance network. my @arInstanceNetworkKeys = reverse(sort(keys $refhInstanceConfiguration->{'NetworkConfiguration'})); #print Dumper(\@arInstWrapPreNetworkKeys); #print Dumper(\@arInstanceNetworkKeys); #print Dumper(\@arInstWrapPostNetworkKeys); #print Dumper($refhInstallWrapperConfiguration); #print Dumper($refhInstanceConfiguration); # for each index, add the length of the pre lengt my $nElementsInInstWrapPreNetwork = $#arInstWrapPreNetworkKeys+1; foreach my $nIndex (@arInstanceNetworkKeys) { #$data->{key3}{key4}{key6} = delete $data->{key3}{key4}{key5} # see: http://stackoverflow.com/questions/1490356/how-to-replace-a-perl-hash-key #print "DDD nIndex: $nIndex arrayLength=$#arInstWrapPreNetworkKeys\n"; $refhInstanceConfiguration->{'NetworkConfiguration'}{$nIndex + $nElementsInInstWrapPreNetwork} = delete($refhInstanceConfiguration->{'NetworkConfiguration'}{$nIndex}); } # insert the pre list foreach my $nIndex (@arInstWrapPreNetworkKeys) { $refhInstanceConfiguration->{'NetworkConfiguration'}{$nIndex} = $refhInstallWrapperConfiguration->{'PreNetworkConfiguration'}{$nIndex}; } # insert the post list, add pre+instance number of entries to each post index. my $nElementsInInstanceNetwork = $#arInstanceNetworkKeys + 1; foreach my $nIndex (@arInstWrapPostNetworkKeys) { $refhInstanceConfiguration->{'NetworkConfiguration'}{$nIndex + $nElementsInInstWrapPreNetwork + $nElementsInInstanceNetwork} = $refhInstallWrapperConfiguration->{'PostNetworkConfiguration'}{$nIndex}; } #print Dumper($refhInstanceConfiguration->{'NetworkConfiguration'}); foreach my $szFileKey (keys $refhInstallWrapperConfiguration->{'FileProvidedDuringCloudInit'}) { $refhInstanceConfiguration->{'FileProvidedDuringCloudInit'}{$szFileKey} = $refhInstallWrapperConfiguration->{'FileProvidedDuringCloudInit'}{$szFileKey}; } if ( exists ($refhInstallWrapperConfiguration->{'PreAppRunCommand'}) ) { foreach my $szEntry (reverse(@{$refhInstallWrapperConfiguration->{'PreAppRunCommand'}}) ) { unshift($refhInstanceConfiguration->{'RunCommand'}, $szEntry); } } if ( exists ($refhInstallWrapperConfiguration->{'PostAppRunCommand'}) ) { foreach my $szEntry ( @{$refhInstallWrapperConfiguration->{'PostAppRunCommand'}} ) { push($refhInstanceConfiguration->{'RunCommand'}, $szEntry); } } if ( exists ($refhInstallWrapperConfiguration->{'ScalarKeyValues'}) ) { foreach my $szEntry ( keys %{$refhInstallWrapperConfiguration->{'ScalarKeyValues'}} ) { $refhInstanceConfiguration->{'ScalarKeyValues'}{$szEntry} = $refhInstallWrapperConfiguration->{'ScalarKeyValues'}{$szEntry}; } } #die("!!! Hey look here...."); } # end IPMergeInstanceAndWrapperInfo # ---------------------------------------------------- # This function populates the $refhMachineConfiguration, which is used for # filling in the domain.xml file, in the template file. # # @params $refhMachineConfiguration - reference to the hash that will be given to the domain.xml text texmplate. # @params $refhVirmanConfiguration - The virman /etc/virman/defaults.xml. # @params $refhInstanceConfiguration - The instance configuration. # TODO V Later merge this inst-conf with the install_wrapper file. # ---------------------------------------------------- sub IPSetMachineConfiguration { my $refhMachineConfiguration = shift; my $refhVirmanConfiguration = shift; my $refhInstanceConfiguration = shift; my $szDomainName = shift; my $szInstanceNumber = shift; confess("!!! szDomainName is not defined(4th parm)") unless(defined($szDomainName)); $refhMachineConfiguration->{'szGuestName'} = $szDomainName; # TODO C Support a dir for the instance machine dom.xml files. #$refhMachineConfiguration->{'szGasBaseDirectory'} = '/opt/gas'; # TODO title and description should be retrieved from the role.xml file. $refhMachineConfiguration->{'szGuestTitle'} = "Virtual $szDomainName"; # TODO V Take the description from the Instance conf description. if ( exists($refhInstanceConfiguration->{'Description'}) ) { $refhMachineConfiguration->{'szGuestDescription'} = $refhInstanceConfiguration->{'Description'}; } else { $refhMachineConfiguration->{'szGuestDescription'} = "Virtual $szDomainName."; } # The amount of memory allocate to the Guest in KiB. $refhMachineConfiguration->{'szGuestMemory'} = '786432'; # file: cqow2 $refhMachineConfiguration->{'szGuestDiskType'} = 'file'; $refhMachineConfiguration->{'szGuestDriverType'} = 'qcow2'; $refhMachineConfiguration->{'szGuestDiskSourceTypeName'} = 'file'; # TODO V When more than qcow is suppoerd the QcowFilePoolPath has to be interchangable iwth eg.g. LVMFilePoolPath. $refhMachineConfiguration->{'szGuestStorageDevice'} = "$refhVirmanConfiguration->{'QcowFilePoolPath'}/$refhMachineConfiguration->{'szGuestName'}.qcow2"; # TODO V put this in a proctected subdir. # This is where all the pre-instance files are stored. # TODO N Does this 'InstanceTempDirectory' really belong in the $refhMachineConfiguration or should it rather be in $refhInstanceConfiguration $refhMachineConfiguration->{'InstanceTempDirectory'} = "$refhVirmanConfiguration->{'CloudInitIsoFiles'}/$refhMachineConfiguration->{'szGuestName'}${szInstanceNumber}"; $refhMachineConfiguration->{'szIsoImage'} = "$refhMachineConfiguration->{'InstanceTempDirectory'}/$refhMachineConfiguration->{'szGuestName'}${szInstanceNumber}-cidata.iso"; # The Network list. # Sort the sub hash: NetworkConfiguration my @arBridgeTypeNetworkList; my @arPrivateNetworkTypeNetworkList; #print Dumper(%{$refhInstanceConfiguration->{'NetworkConfiguration'}}); #foreach my $refNetwork ( sort keys %{$refhInstanceConfiguration->{'NetworkConfiguration'}} ) { foreach my $refNetwork ( sort keys $refhInstanceConfiguration->{'NetworkConfiguration'} ) { # TODO V Later figure out if the refNetwork goes into the bridge or the network list. print "---\n"; push(@arPrivateNetworkTypeNetworkList, $refhInstanceConfiguration->{'NetworkConfiguration'}{$refNetwork}{'Name'}); } $refhMachineConfiguration->{'arPublicNetworkList'} = \@arBridgeTypeNetworkList; $refhMachineConfiguration->{'arPrivateNetworkList'} = \@arPrivateNetworkTypeNetworkList; #print Dumper($refhMachineConfiguration); #die("!!! TEST END."); } # This ends the perl module/package definition. 1;
henk52/virman
bin/InfoProcessing.pm
Perl
apache-2.0
9,582
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package storage::qnap::snmp::mode::memory; use base qw(centreon::plugins::mode); use strict; use warnings; 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 => { "warning:s" => { name => 'warning' }, "critical:s" => { name => 'critical' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); $self->{output}->option_exit(); } } sub convert_bytes { my ($self, %options) = @_; my $multiple = defined($options{network}) ? 1000 : 1024; my %units = (K => 1, M => 2, G => 3, T => 4); if ($options{value} !~ /^\s*([0-9\.\,]+)\s*(.)/) { $self->{output}->output_add(severity => 'UNKNOWN', output => "Cannot convert value '" . $options{value} . "'"); $self->{output}->display(); $self->{output}->exit(); } my ($bytes, $unit) = ($1, uc($2)); for (my $i = 0; $i < $units{$unit}; $i++) { $bytes *= $multiple; } return $bytes; } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; my $oid_SystemTotalMem = '.1.3.6.1.4.1.24681.1.2.2.0'; my $oid_SystemFreeMem = '.1.3.6.1.4.1.24681.1.2.3.0'; my $result = $self->{snmp}->get_leef(oids => [ $oid_SystemTotalMem, $oid_SystemFreeMem ], nothing_quit => 1); my $total_size = $self->convert_bytes(value => $result->{$oid_SystemTotalMem}); my $memory_free = $self->convert_bytes(value => $result->{$oid_SystemFreeMem}); my $memory_used = $total_size - $memory_free; my $prct_used = $memory_used * 100 / $total_size; my $prct_free = 100 - $prct_used; my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); my ($used_value, $used_unit) = $self->{perfdata}->change_bytes(value => $memory_used); my ($free_value, $free_unit) = $self->{perfdata}->change_bytes(value => $memory_free); $self->{output}->output_add(severity => $exit, short_msg => sprintf("Memory Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $total_value . " " . $total_unit, $used_value . " " . $used_unit, $prct_used, $free_value . " " . $free_unit, $prct_free)); $self->{output}->perfdata_add(label => "used", unit => 'B', value => int($memory_used), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size, cast_int => 1), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size, cast_int => 1), min => 0, max => int($total_size)); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check memory usage (NAS.mib). =over 8 =item B<--warning> Threshold warning in percent. =item B<--critical> Threshold critical in percent. =back =cut
wilfriedcomte/centreon-plugins
storage/qnap/snmp/mode/memory.pm
Perl
apache-2.0
4,922
#!/bin/perl use strict; my $version = shift; my %author_url = ( 'AlexElin' => 'https://github.com/AlexElin', 'aryabukhin' => 'https://github.com/aryabukhin', 'bd-infor' => 'https://github.com/bd-infor', 'Christian Ullrich' => 'https://github.com/chrullrich', 'Christopher Deckers' => 'https://github.com/Chrriis', 'Daniel Gustafsson' => 'https://github.com/danielgustafsson', 'Dave Cramer' => 'davec@postgresintl.com', 'Eric McCormack' => 'https://github.com/ericmack', 'Florin Asăvoaie' => 'https://github.com/FlorinAsavoaie', 'George Kankava' => 'https://github.com/georgekankava', 'goeland86' => 'https://github.com/goeland86', 'Jeremy Whiting' => 'https://github.com/whitingjr', 'Jordan Lewis' => 'https://github.com/jordanlewis', 'Jorge Solorzano' => 'https://github.com/jorsol', 'Laurenz Albe' => 'https://github.com/laurenz', 'Marc Petzold' => 'https://github.com/dosimeta', 'Marios Trivyzas' => 'https://github.com/matriv', 'Mathias Fußenegger' => 'https://github.com/mfussenegger', 'Minglei Tu' => 'https://github.com/tminglei', 'Pavel Raiskup' => 'https://github.com/praiskup', 'Petro Semeniuk' => 'https://github.com/PetroSemeniuk', 'Philippe Marschall' => 'https://github.com/marschall', 'Philippe Marschall' => 'https://github.com/marschall', 'Rikard Pavelic' => 'https://github.com/zapov', 'Roman Ivanov' => 'https://github.com/romani', 'Sebastian Utz' => 'https://github.com/seut', 'Steve Ungerer' => 'https://github.com/scubasau', 'Tanya Gordeeva' => 'https://github.com/tmgordeeva', 'Trygve Laugstøl' => 'https://github.com/trygvis', 'Vladimir Gordiychuk' => 'https://github.com/Gordiychuk', 'Vladimir Sitnikov' => 'https://github.com/vlsi', ); my %authors; while(<>) { if ($_ !~ /@@@/) { print $_; if ($_ =~ /(.*) \(\d+\):/) { $authors{$1} = 1; print "\n"; } next; } my @c = split('@@@', $_); my $subject = @c[0]; my $sha = @c[1]; my $shortSha = @c[2]; my $pr = ''; if ($subject =~ /\(#(\d+)\)/) { $subject =~ s;\(#(\d+)\);[PR#\1](https://github.com/pgjdbc/pgjdbc/pull/\1);; } else { my $body = `git log --format='%B' -n 1 $sha`; if ($body =~ /(?:fix|fixes|close|closes) *#?(\d+)/) { $pr = $1; } } if ($pr != '') { $pr = ' [PR#'.$pr.'](https://github.com/pgjdbc/pgjdbc/pull/'.$pr.')'; } $subject =~ s/^\s+/* /; print $subject.$pr." [".$shortSha."](https://github.com/pgjdbc/pgjdbc/commit/$sha)\n"; } print "<a name=\"contributors_$version\"></a>\n"; print "### Contributors to this release\n\n"; print "We thank the following people for their contributions to this release.\n\n"; for my $c (sort keys(%authors)) { if ($author_url{$c}) { print "[$c](".$author_url{$c}.")"; } else { print $c; } print " \n" }
jamesthomp/pgjdbc
release_notes_filter.pl
Perl
bsd-2-clause
2,799
package OpenResty::Backend::Empty; use strict; use warnings; #use Smart::Comments '####'; use base 'OpenResty::Backend::Base'; sub new { my $class = shift; return bless {}, $class; } sub ping { 1; } sub select { 1; } sub do { 1; } sub quote { my ($self, $val) = @_; if (!defined $val) { return 'NULL' } $val =~ s/'/''/g; $val =~ s{\\}{\\\\}g; "'$val'"; } sub quote_identifier { my ($self, $val) = @_; if (!defined $val) { return '""' } $val =~ s/"/""/g; $val =~ s{\\}{\\\\}g; qq{"$val"}; } sub last_insert_id { 1; } sub has_user { 1; } sub set_user { 1; } sub add_user { 1; } sub add_empty_user { 1; } sub drop_user { 1; } sub login { 1; } sub get_upgrading_base { -1; } sub _upgrade_metamodel { -1; } 1; __END__ =head1 NAME OpenResty::Backend::PgFarm - OpenResty backend for the PostgreSQL PL/Proxy-based cluster databases =head1 INHERITANCE OpenResty::Backend::PgFarm ISA OpenResty::Backend::Base =head1 SYNOPSIS =head1 DESCRIPTION =head1 AUTHOR Yichun Zhang (agentzh) C<< <agentzh@gmail.com> >> =head1 SEE ALSO L<OpenResty::Backend::Base>, L<OpenResty::Backend::Pg>, L<OpenResty::Backend::PLPerl>, L<OpenResty::Backend::PgMocked>, L<OpenResty>.
agentzh/old-openresty
lib/OpenResty/Backend/Empty.pm
Perl
bsd-3-clause
1,288
#!/usr/bin/env perl # # ==================================================================== # Written by Andy Polyakov <appro@fy.chalmers.se> for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # ==================================================================== # # July 2004 # # 2.22x RC4 tune-up:-) It should be noted though that my hand [as in # "hand-coded assembler"] doesn't stand for the whole improvement # coefficient. It turned out that eliminating RC4_CHAR from config # line results in ~40% improvement (yes, even for C implementation). # Presumably it has everything to do with AMD cache architecture and # RAW or whatever penalties. Once again! The module *requires* config # line *without* RC4_CHAR! As for coding "secret," I bet on partial # register arithmetics. For example instead of 'inc %r8; and $255,%r8' # I simply 'inc %r8b'. Even though optimization manual discourages # to operate on partial registers, it turned out to be the best bet. # At least for AMD... How IA32E would perform remains to be seen... # November 2004 # # As was shown by Marc Bevand reordering of couple of load operations # results in even higher performance gain of 3.3x:-) At least on # Opteron... For reference, 1x in this case is RC4_CHAR C-code # compiled with gcc 3.3.2, which performs at ~54MBps per 1GHz clock. # Latter means that if you want to *estimate* what to expect from # *your* Opteron, then multiply 54 by 3.3 and clock frequency in GHz. # November 2004 # # Intel P4 EM64T core was found to run the AMD64 code really slow... # The only way to achieve comparable performance on P4 was to keep # RC4_CHAR. Kind of ironic, huh? As it's apparently impossible to # compose blended code, which would perform even within 30% marginal # on either AMD and Intel platforms, I implement both cases. See # rc4_skey.c for further details... # April 2005 # # P4 EM64T core appears to be "allergic" to 64-bit inc/dec. Replacing # those with add/sub results in 50% performance improvement of folded # loop... # May 2005 # # As was shown by Zou Nanhai loop unrolling can improve Intel EM64T # performance by >30% [unlike P4 32-bit case that is]. But this is # provided that loads are reordered even more aggressively! Both code # pathes, AMD64 and EM64T, reorder loads in essentially same manner # as my IA-64 implementation. On Opteron this resulted in modest 5% # improvement [I had to test it], while final Intel P4 performance # achieves respectful 432MBps on 2.8GHz processor now. For reference. # If executed on Xeon, current RC4_CHAR code-path is 2.7x faster than # RC4_INT code-path. While if executed on Opteron, it's only 25% # slower than the RC4_INT one [meaning that if CPU µ-arch detection # is not implemented, then this final RC4_CHAR code-path should be # preferred, as it provides better *all-round* performance]. # March 2007 # # Intel Core2 was observed to perform poorly on both code paths:-( It # apparently suffers from some kind of partial register stall, which # occurs in 64-bit mode only [as virtually identical 32-bit loop was # observed to outperform 64-bit one by almost 50%]. Adding two movzb to # cloop1 boosts its performance by 80%! This loop appears to be optimal # fit for Core2 and therefore the code was modified to skip cloop8 on # this CPU. # May 2010 # # Intel Westmere was observed to perform suboptimally. Adding yet # another movzb to cloop1 improved performance by almost 50%! Core2 # performance is improved too, but nominally... # May 2011 # # The only code path that was not modified is P4-specific one. Non-P4 # Intel code path optimization is heavily based on submission by Maxim # Perminov, Maxim Locktyukhin and Jim Guilford of Intel. I've used # some of the ideas even in attempt to optmize the original RC4_INT # code path... Current performance in cycles per processed byte (less # is better) and improvement coefficients relative to previous # version of this module are: # # Opteron 5.3/+0%(*) # P4 6.5 # Core2 6.2/+15%(**) # Westmere 4.2/+60% # Sandy Bridge 4.2/+120% # Atom 9.3/+80% # # (*) But corresponding loop has less instructions, which should have # positive effect on upcoming Bulldozer, which has one less ALU. # For reference, Intel code runs at 6.8 cpb rate on Opteron. # (**) Note that Core2 result is ~15% lower than corresponding result # for 32-bit code, meaning that it's possible to improve it, # but more than likely at the cost of the others (see rc4-586.pl # to get the idea)... $flavour = shift; $output = shift; if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or die "can't locate x86_64-xlate.pl"; open STDOUT,"| $^X $xlate $flavour $output"; $dat="%rdi"; # arg1 $len="%rsi"; # arg2 $inp="%rdx"; # arg3 $out="%rcx"; # arg4 { $code=<<___; .text .extern OPENSSL_ia32cap_P .globl RC4 .type RC4,\@function,4 .align 16 RC4: or $len,$len jne .Lentry ret .Lentry: push %rbx push %r12 push %r13 .Lprologue: mov $len,%r11 mov $inp,%r12 mov $out,%r13 ___ my $len="%r11"; # reassign input arguments my $inp="%r12"; my $out="%r13"; my @XX=("%r10","%rsi"); my @TX=("%rax","%rbx"); my $YY="%rcx"; my $TY="%rdx"; $code.=<<___; xor $XX[0],$XX[0] xor $YY,$YY lea 8($dat),$dat mov -8($dat),$XX[0]#b mov -4($dat),$YY#b cmpl \$-1,256($dat) je .LRC4_CHAR mov OPENSSL_ia32cap_P(%rip),%r8d xor $TX[1],$TX[1] inc $XX[0]#b sub $XX[0],$TX[1] sub $inp,$out movl ($dat,$XX[0],4),$TX[0]#d test \$-16,$len jz .Lloop1 bt \$30,%r8d # Intel CPU? jc .Lintel and \$7,$TX[1] lea 1($XX[0]),$XX[1] jz .Loop8 sub $TX[1],$len .Loop8_warmup: add $TX[0]#b,$YY#b movl ($dat,$YY,4),$TY#d movl $TX[0]#d,($dat,$YY,4) movl $TY#d,($dat,$XX[0],4) add $TY#b,$TX[0]#b inc $XX[0]#b movl ($dat,$TX[0],4),$TY#d movl ($dat,$XX[0],4),$TX[0]#d xorb ($inp),$TY#b movb $TY#b,($out,$inp) lea 1($inp),$inp dec $TX[1] jnz .Loop8_warmup lea 1($XX[0]),$XX[1] jmp .Loop8 .align 16 .Loop8: ___ for ($i=0;$i<8;$i++) { $code.=<<___ if ($i==7); add \$8,$XX[1]#b ___ $code.=<<___; add $TX[0]#b,$YY#b movl ($dat,$YY,4),$TY#d movl $TX[0]#d,($dat,$YY,4) movl `4*($i==7?-1:$i)`($dat,$XX[1],4),$TX[1]#d ror \$8,%r8 # ror is redundant when $i=0 movl $TY#d,4*$i($dat,$XX[0],4) add $TX[0]#b,$TY#b movb ($dat,$TY,4),%r8b ___ push(@TX,shift(@TX)); #push(@XX,shift(@XX)); # "rotate" registers } $code.=<<___; add \$8,$XX[0]#b ror \$8,%r8 sub \$8,$len xor ($inp),%r8 mov %r8,($out,$inp) lea 8($inp),$inp test \$-8,$len jnz .Loop8 cmp \$0,$len jne .Lloop1 jmp .Lexit .align 16 .Lintel: test \$-32,$len jz .Lloop1 and \$15,$TX[1] jz .Loop16_is_hot sub $TX[1],$len .Loop16_warmup: add $TX[0]#b,$YY#b movl ($dat,$YY,4),$TY#d movl $TX[0]#d,($dat,$YY,4) movl $TY#d,($dat,$XX[0],4) add $TY#b,$TX[0]#b inc $XX[0]#b movl ($dat,$TX[0],4),$TY#d movl ($dat,$XX[0],4),$TX[0]#d xorb ($inp),$TY#b movb $TY#b,($out,$inp) lea 1($inp),$inp dec $TX[1] jnz .Loop16_warmup mov $YY,$TX[1] xor $YY,$YY mov $TX[1]#b,$YY#b .Loop16_is_hot: lea ($dat,$XX[0],4),$XX[1] ___ sub RC4_loop { my $i=shift; my $j=$i<0?0:$i; my $xmm="%xmm".($j&1); $code.=" add \$16,$XX[0]#b\n" if ($i==15); $code.=" movdqu ($inp),%xmm2\n" if ($i==15); $code.=" add $TX[0]#b,$YY#b\n" if ($i<=0); $code.=" movl ($dat,$YY,4),$TY#d\n"; $code.=" pxor %xmm0,%xmm2\n" if ($i==0); $code.=" psllq \$8,%xmm1\n" if ($i==0); $code.=" pxor $xmm,$xmm\n" if ($i<=1); $code.=" movl $TX[0]#d,($dat,$YY,4)\n"; $code.=" add $TY#b,$TX[0]#b\n"; $code.=" movl `4*($j+1)`($XX[1]),$TX[1]#d\n" if ($i<15); $code.=" movz $TX[0]#b,$TX[0]#d\n"; $code.=" movl $TY#d,4*$j($XX[1])\n"; $code.=" pxor %xmm1,%xmm2\n" if ($i==0); $code.=" lea ($dat,$XX[0],4),$XX[1]\n" if ($i==15); $code.=" add $TX[1]#b,$YY#b\n" if ($i<15); $code.=" pinsrw \$`($j>>1)&7`,($dat,$TX[0],4),$xmm\n"; $code.=" movdqu %xmm2,($out,$inp)\n" if ($i==0); $code.=" lea 16($inp),$inp\n" if ($i==0); $code.=" movl ($XX[1]),$TX[1]#d\n" if ($i==15); } RC4_loop(-1); $code.=<<___; jmp .Loop16_enter .align 16 .Loop16: ___ for ($i=0;$i<16;$i++) { $code.=".Loop16_enter:\n" if ($i==1); RC4_loop($i); push(@TX,shift(@TX)); # "rotate" registers } $code.=<<___; mov $YY,$TX[1] xor $YY,$YY # keyword to partial register sub \$16,$len mov $TX[1]#b,$YY#b test \$-16,$len jnz .Loop16 psllq \$8,%xmm1 pxor %xmm0,%xmm2 pxor %xmm1,%xmm2 movdqu %xmm2,($out,$inp) lea 16($inp),$inp cmp \$0,$len jne .Lloop1 jmp .Lexit .align 16 .Lloop1: add $TX[0]#b,$YY#b movl ($dat,$YY,4),$TY#d movl $TX[0]#d,($dat,$YY,4) movl $TY#d,($dat,$XX[0],4) add $TY#b,$TX[0]#b inc $XX[0]#b movl ($dat,$TX[0],4),$TY#d movl ($dat,$XX[0],4),$TX[0]#d xorb ($inp),$TY#b movb $TY#b,($out,$inp) lea 1($inp),$inp dec $len jnz .Lloop1 jmp .Lexit .align 16 .LRC4_CHAR: add \$1,$XX[0]#b movzb ($dat,$XX[0]),$TX[0]#d test \$-8,$len jz .Lcloop1 jmp .Lcloop8 .align 16 .Lcloop8: mov ($inp),%r8d mov 4($inp),%r9d ___ # unroll 2x4-wise, because 64-bit rotates kill Intel P4... for ($i=0;$i<4;$i++) { $code.=<<___; add $TX[0]#b,$YY#b lea 1($XX[0]),$XX[1] movzb ($dat,$YY),$TY#d movzb $XX[1]#b,$XX[1]#d movzb ($dat,$XX[1]),$TX[1]#d movb $TX[0]#b,($dat,$YY) cmp $XX[1],$YY movb $TY#b,($dat,$XX[0]) jne .Lcmov$i # Intel cmov is sloooow... mov $TX[0],$TX[1] .Lcmov$i: add $TX[0]#b,$TY#b xor ($dat,$TY),%r8b ror \$8,%r8d ___ push(@TX,shift(@TX)); push(@XX,shift(@XX)); # "rotate" registers } for ($i=4;$i<8;$i++) { $code.=<<___; add $TX[0]#b,$YY#b lea 1($XX[0]),$XX[1] movzb ($dat,$YY),$TY#d movzb $XX[1]#b,$XX[1]#d movzb ($dat,$XX[1]),$TX[1]#d movb $TX[0]#b,($dat,$YY) cmp $XX[1],$YY movb $TY#b,($dat,$XX[0]) jne .Lcmov$i # Intel cmov is sloooow... mov $TX[0],$TX[1] .Lcmov$i: add $TX[0]#b,$TY#b xor ($dat,$TY),%r9b ror \$8,%r9d ___ push(@TX,shift(@TX)); push(@XX,shift(@XX)); # "rotate" registers } $code.=<<___; lea -8($len),$len mov %r8d,($out) lea 8($inp),$inp mov %r9d,4($out) lea 8($out),$out test \$-8,$len jnz .Lcloop8 cmp \$0,$len jne .Lcloop1 jmp .Lexit ___ $code.=<<___; .align 16 .Lcloop1: add $TX[0]#b,$YY#b movzb $YY#b,$YY#d movzb ($dat,$YY),$TY#d movb $TX[0]#b,($dat,$YY) movb $TY#b,($dat,$XX[0]) add $TX[0]#b,$TY#b add \$1,$XX[0]#b movzb $TY#b,$TY#d movzb $XX[0]#b,$XX[0]#d movzb ($dat,$TY),$TY#d movzb ($dat,$XX[0]),$TX[0]#d xorb ($inp),$TY#b lea 1($inp),$inp movb $TY#b,($out) lea 1($out),$out sub \$1,$len jnz .Lcloop1 jmp .Lexit .align 16 .Lexit: sub \$1,$XX[0]#b movl $XX[0]#d,-8($dat) movl $YY#d,-4($dat) mov (%rsp),%r13 mov 8(%rsp),%r12 mov 16(%rsp),%rbx add \$24,%rsp .Lepilogue: ret .size RC4,.-RC4 ___ } $idx="%r8"; $ido="%r9"; $code.=<<___; .globl RC4_set_key .type RC4_set_key,\@function,3 .align 16 RC4_set_key: lea 8($dat),$dat lea ($inp,$len),$inp neg $len mov $len,%rcx xor %eax,%eax xor $ido,$ido xor %r10,%r10 xor %r11,%r11 mov OPENSSL_ia32cap_P(%rip),$idx#d bt \$20,$idx#d # RC4_CHAR? jc .Lc1stloop jmp .Lw1stloop .align 16 .Lw1stloop: mov %eax,($dat,%rax,4) add \$1,%al jnc .Lw1stloop xor $ido,$ido xor $idx,$idx .align 16 .Lw2ndloop: mov ($dat,$ido,4),%r10d add ($inp,$len,1),$idx#b add %r10b,$idx#b add \$1,$len mov ($dat,$idx,4),%r11d cmovz %rcx,$len mov %r10d,($dat,$idx,4) mov %r11d,($dat,$ido,4) add \$1,$ido#b jnc .Lw2ndloop jmp .Lexit_key .align 16 .Lc1stloop: mov %al,($dat,%rax) add \$1,%al jnc .Lc1stloop xor $ido,$ido xor $idx,$idx .align 16 .Lc2ndloop: mov ($dat,$ido),%r10b add ($inp,$len),$idx#b add %r10b,$idx#b add \$1,$len mov ($dat,$idx),%r11b jnz .Lcnowrap mov %rcx,$len .Lcnowrap: mov %r10b,($dat,$idx) mov %r11b,($dat,$ido) add \$1,$ido#b jnc .Lc2ndloop movl \$-1,256($dat) .align 16 .Lexit_key: xor %eax,%eax mov %eax,-8($dat) mov %eax,-4($dat) ret .size RC4_set_key,.-RC4_set_key .globl RC4_options .type RC4_options,\@abi-omnipotent .align 16 RC4_options: lea .Lopts(%rip),%rax mov OPENSSL_ia32cap_P(%rip),%edx bt \$20,%edx jc .L8xchar bt \$30,%edx jnc .Ldone add \$25,%rax ret .L8xchar: add \$12,%rax .Ldone: ret .align 64 .Lopts: .asciz "rc4(8x,int)" .asciz "rc4(8x,char)" .asciz "rc4(16x,int)" .asciz "RC4 for x86_64, CRYPTOGAMS by <appro\@openssl.org>" .align 64 .size RC4_options,.-RC4_options ___ # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, # CONTEXT *context,DISPATCHER_CONTEXT *disp) if ($win64) { $rec="%rcx"; $frame="%rdx"; $context="%r8"; $disp="%r9"; $code.=<<___; .extern __imp_RtlVirtualUnwind .type stream_se_handler,\@abi-omnipotent .align 16 stream_se_handler: push %rsi push %rdi push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 pushfq sub \$64,%rsp mov 120($context),%rax # pull context->Rax mov 248($context),%rbx # pull context->Rip lea .Lprologue(%rip),%r10 cmp %r10,%rbx # context->Rip<prologue label jb .Lin_prologue mov 152($context),%rax # pull context->Rsp lea .Lepilogue(%rip),%r10 cmp %r10,%rbx # context->Rip>=epilogue label jae .Lin_prologue lea 24(%rax),%rax mov -8(%rax),%rbx mov -16(%rax),%r12 mov -24(%rax),%r13 mov %rbx,144($context) # restore context->Rbx mov %r12,216($context) # restore context->R12 mov %r13,224($context) # restore context->R13 .Lin_prologue: mov 8(%rax),%rdi mov 16(%rax),%rsi mov %rax,152($context) # restore context->Rsp mov %rsi,168($context) # restore context->Rsi mov %rdi,176($context) # restore context->Rdi jmp .Lcommon_seh_exit .size stream_se_handler,.-stream_se_handler .type key_se_handler,\@abi-omnipotent .align 16 key_se_handler: push %rsi push %rdi push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 pushfq sub \$64,%rsp mov 152($context),%rax # pull context->Rsp mov 8(%rax),%rdi mov 16(%rax),%rsi mov %rsi,168($context) # restore context->Rsi mov %rdi,176($context) # restore context->Rdi .Lcommon_seh_exit: mov 40($disp),%rdi # disp->ContextRecord mov $context,%rsi # context mov \$154,%ecx # sizeof(CONTEXT) .long 0xa548f3fc # cld; rep movsq mov $disp,%rsi xor %rcx,%rcx # arg1, UNW_FLAG_NHANDLER mov 8(%rsi),%rdx # arg2, disp->ImageBase mov 0(%rsi),%r8 # arg3, disp->ControlPc mov 16(%rsi),%r9 # arg4, disp->FunctionEntry mov 40(%rsi),%r10 # disp->ContextRecord lea 56(%rsi),%r11 # &disp->HandlerData lea 24(%rsi),%r12 # &disp->EstablisherFrame mov %r10,32(%rsp) # arg5 mov %r11,40(%rsp) # arg6 mov %r12,48(%rsp) # arg7 mov %rcx,56(%rsp) # arg8, (NULL) call *__imp_RtlVirtualUnwind(%rip) mov \$1,%eax # ExceptionContinueSearch add \$64,%rsp popfq pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx pop %rdi pop %rsi ret .size key_se_handler,.-key_se_handler .section .pdata .align 4 .rva .LSEH_begin_RC4 .rva .LSEH_end_RC4 .rva .LSEH_info_RC4 .rva .LSEH_begin_RC4_set_key .rva .LSEH_end_RC4_set_key .rva .LSEH_info_RC4_set_key .section .xdata .align 8 .LSEH_info_RC4: .byte 9,0,0,0 .rva stream_se_handler .LSEH_info_RC4_set_key: .byte 9,0,0,0 .rva key_se_handler ___ } sub reg_part { my ($reg,$conv)=@_; if ($reg =~ /%r[0-9]+/) { $reg .= $conv; } elsif ($conv eq "b") { $reg =~ s/%[er]([^x]+)x?/%$1l/; } elsif ($conv eq "w") { $reg =~ s/%[er](.+)/%$1/; } elsif ($conv eq "d") { $reg =~ s/%[er](.+)/%e$1/; } return $reg; } $code =~ s/(%[a-z0-9]+)#([bwd])/reg_part($1,$2)/gem; $code =~ s/\`([^\`]*)\`/eval $1/gem; print $code; close STDOUT;
luwanjia/sdl_implementation_reference
src/3rd_party-static/openssl-fips-2.0.9/crypto/rc4/asm/rc4-x86_64.pl
Perl
bsd-3-clause
15,726
package Net::PMP::Credentials; use Moose; use Carp; use Data::Dump qw( dump ); has 'token_expires_in' => ( is => 'ro', isa => 'Int', required => 1, ); has 'client_id' => ( is => 'ro', isa => 'Str', required => 1, ); has 'client_secret' => ( is => 'ro', isa => 'Str', required => 1, ); has 'label' => ( is => 'ro', isa => 'Str', required => 1, ); has 'scope' => ( is => 'ro', isa => 'Str', required => 1, ); =head1 NAME Net::PMP::Credentials - PMP credentials object =head1 SYNOPSIS my $credentials = $pmp_client->create_credentials( username => 'i-am-a-user', password => 'secret-phrase-here', scope => 'read', expires => 86400, label => 'pmp ftw!', ); =head1 DESCRIPTION Net::PMP::Credentials represents a PMP API credentials object. See L<https://github.com/publicmediaplatform/pmpdocs/wiki/Authentication-Model#client-credentials-management>. =head1 METHODS =head2 token_expires_in =head2 client_id =head2 client_secret =head2 label =head2 scope =cut 1; __END__ =head1 AUTHOR Peter Karman, C<< <karman at cpan.org> >> =head1 BUGS Please report any bugs or feature requests to C<bug-net-pmp at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Net-PMP>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Net::PMP::CollectionDoc You can also look for information at: =over 4 =item * RT: CPAN's request tracker (report bugs here) L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Net-PMP> =item * AnnoCPAN: Annotated CPAN documentation L<http://annocpan.org/dist/Net-PMP> =item * CPAN Ratings L<http://cpanratings.perl.org/d/Net-PMP> =item * Search CPAN L<http://search.cpan.org/dist/Net-PMP/> =back =head1 ACKNOWLEDGEMENTS American Public Media and the Public Media Platform sponsored the development of this module. =head1 LICENSE AND COPYRIGHT Copyright 2013 American Public Media Group See the LICENSE file that accompanies this module. =cut
gitpan/Net-PMP
lib/Net/PMP/Credentials.pm
Perl
mit
2,141
use strict; package ENKI; use ENKI::Status; use Nginx::Simple; use LWP::UserAgent; use HTTP::Cookies; use HTTP::Request::Common; use URI; use Perl6::Slurp qw(slurp); sub main # mandatory { my $self = shift; $self->header_set('Content-Type' => 'text/plain'); my @uris = split(/\//, $self->uri); if ($uris[1] eq 'services') { my ($str, $h) = &ENKI::Status::services($self); if ( $h < 1 ) { $self->status(404); } else { $self->print($str); $self->status(200); } } elsif ($uris[1] eq 'status' || $uris[1] eq 'state') { my ($s, $h) = &ENKI::Status::status($self) ; $self->print($s) ; # $self->log("chad is in the house\n"); if ( $h == 0 ) { $self->status(503); } elsif ( $h == -1 ) { $self->status(404); } else { $self->status(200); } } else { $self->status(400); } } # (optional) triggered after main runs sub cleanup { my $self = shift; # do stuff here---like clean database connections? } # (optional) triggered on a server error, otherwise it will return a standard nginx 500 error sub error { my $self = shift; my $error = shift; $self->status(500); $self->print("ERROR: Problem with nginx ENKI::Status module.! ($error)"); } 1; __END__
slaught/enki_cloud
node_status/perl/ENKI.pm
Perl
mit
1,508
#!/usr/bin/perl package adjacency; BEGIN { push(@INC, "../../../lib"); } use strict; use ConfigCommon; use ConfigDB; use ConfigQueryISIS; my $cq = new ConfigQueryISIS; sub new { my ($class) = @_; my $self = {}; bless ($self, $class); return $self; } # Check that all edges are bi-directional sub check_dangling_adjacencies { my $self = shift; my $quiet = shift; my @errors = (); my $dangling_errors = 0; my $loopback_errors = 0; my $disabled_errors = 0; print STDERR "\nVerifying that every IS-IS adjacency is configured on both ends.\n\n" if !$quiet; my $q = "SELECT router_name, ipv4_address FROM $router_interfaces WHERE (interface_name != 'lo0.0' OR interface_name NOT REGEXP 'Loopback.*') AND ipv4_address != 'none'"; my $sth = $cq->query($q); while (my ($router, $ipv4_subnet_addr) = $sth->fetchrow_array()) { # check if another router has same subnet address my $q_ = "SELECT router_name FROM $router_interfaces WHERE ipv4_address = '$ipv4_subnet_addr' AND (interface_name != 'lo0.0' OR interface_name NOT REGEXP 'Loopback.*')"; my $sth_ = $cq->query($q_); my ($count) = $sth_->fetchrow_array(); if (!$count) { print STDERR "WARNING: Dangling IS-IS adjacency: $router -> $ipv4_subnet_addr\n" if !$quiet; push(@errors, ($router, $ipv4_subnet_addr)); $dangling_errors++; } # check to see if the adjacency is formed # with a loopback interface my $q_ = "SELECT router_name FROM $router_interfaces WHERE ipv4_address = '$ipv4_subnet_addr' AND (interface_name = 'lo0.0' or interface_name REGEXP 'Loopback')"; my $sth_ = $cq->query($q_); my ($count) = $sth_->fetchrow_array(); if ($count) { print STDERR "WARNING: IS-IS adjacency with a loopback interface: $router -> $ipv4_subnet_addr\n" if !$quiet; push(@errors, ($router, $ipv4_subnet_addr)); $loopback_errors++; } # check to see if the adjacency is formed # with a disabled interface my $q_ = "SELECT router_name FROM $router_interfaces WHERE ipv4_address = '$ipv4_subnet_addr' AND level1_routing = 0 AND level2_routing = 0"; my $sth_ = $cq->query($q_); my ($count) = $sth_->fetchrow_array(); if ($count) { print STDERR "WARNING: IS-IS adjacency with a disabled interface: $router -> $ipv4_subnet_addr\n" if !$quiet; push(@errors, ($router, $ipv4_subnet_addr)); $disabled_errors++; } } # print summary print STDERR "\n===Summary===\n"; print STDERR "Found $dangling_errors cases of dangling IS-IS adjacencies.\n"; print STDERR "Found $loopback_errors cases of IS-IS adjacencies with a loopback interface.\n"; print STDERR "Found $disabled_errors cases of IS-IS adjacencies with a disabled interface.\n"; # return errors? } # Check that adjacency levels are matched sub check_adjacency_levels { my $self = shift; my $quiet = shift; my @errors = (); print STDERR "\nVerifying that every IS-IS adjacency is configured for the same levels on each end.\n\n" if !$quiet; # Start with Level 1 Adjacencies print STDERR "\nChecking Level 1 Adjacencies.\n" if !$quiet; my $q1 = "SELECT router_name, ipv4_address FROM $router_interfaces WHERE (interface_name != 'lo0.0' OR interface_name NOT REGEXP 'Loopback') AND ipv4_address != 'none' AND level1_routing = 1 AND level2_routing = 0"; my $sth1 = $cq->query($q1); while (my ($router, $ipv4_subnet_addr) = $sth1->fetchrow_array()) { # check that all other routers with the # same subnet address have Level 1 ENABLED my $q_1 = "SELECT router_name FROM $router_interfaces WHERE ipv4_address = '$ipv4_subnet_addr' AND level1_routing = 0"; my $sth_1 = $cq->query($q_1); my ($count) = $sth_1->fetchrow_array(); if ($count) { print "WARNING: IS-IS adjacency DISABLED for Level 1 on other end: $router -> $ipv4_subnet_addr\n" if !$quiet; push(@errors, ($router, $ipv4_subnet_addr)); } } # Level 2 Adjacencies print STDERR "\nChecking Level 2 Adjacencies.\n" if !$quiet; my $q2 = "SELECT router_name, ipv4_address FROM $router_interfaces WHERE (interface_name != 'lo0.0' or interface_name NOT REGEXP 'Loopback.*') AND ipv4_address != 'none' AND level1_routing = 0 AND level2_routing = 1"; my $sth2 = $cq->query($q2); while (my ($router, $ipv4_subnet_addr) = $sth2->fetchrow_array()) { # check that all other routers with the # same subnet address have level 2 ENABLED my $q_2 = "SELECT router_name FROM $router_interfaces WHERE ipv4_address = '$ipv4_subnet_addr' AND level2_routing = 0"; my $sth_2 = $cq->query($q_2); my ($count) = $sth_2->fetchrow_array(); if ($count) { print STDERR "WARNING: IS-IS adjacency DISABLED for Level 2 on other end: $router -> $ipv4_subnet_addr\n" if !$quiet; push(@errors, ($router, $ipv4_subnet_addr)); } } # Level 1&2 Adjacencies print STDERR "\nChecking Level 1 and 2 Adjacencies.\n" if !$quiet; my $q3 = "SELECT router_name, ipv4_address FROM $router_interfaces WHERE (interface_name != 'lo0.0' or interface_name NOT REGEXP 'Loopback.*') AND ipv4_address != 'none' AND level1_routing = 1 AND level2_routing = 1"; my $sth3 = $cq->query($q3); while (my ($router, $ipv4_subnet_addr) = $sth3->fetchrow_array()) { # check that all other routers with the # same subnet address have Level 1 and/or Level 2 ENABLED my $q_1 = "SELECT router_name FROM $router_interfaces WHERE ipv4_address = '$ipv4_subnet_addr' AND level1_routing = 0 and level2_routing = 0"; my $sth_1 = $cq->query($q_1); my ($count) = $sth_1->fetchrow_array(); if ($count) { print STDERR "WARNING: IS-IS adjacency DISABLED for Level 1 and 2 on other end: $router -> $ipv4_subnet_addr\n" if !$quiet; push(@errors, ($router, $ipv4_subnet_addr)); } } # print summary info } # Check that inter-area adjacencies are configured for level 2 # and intra-area adjacencies are configured for level 1 sub check_area_adjacencies { my $self = shift; my $quiet = shift; my @errors = (); print STDERR "\nVerifying that every inter-area IS-IS adjacency is configured for Level 2 Routing.\n" if !$quiet; # Get the router names and their area addresses; my $q = "SELECT router_name, area_address FROM $router_info"; my $sth = $cq->query($q); while (my ($origin_router, $origin_area_addr) = $sth->fetchrow_array()) { # get its adjacencies from the "adjacencies" table my $q_ = "SELECT dest_router_name,ipv4_subnet_address FROM $adjacencies WHERE origin_router_name='$origin_router'"; my $sth_ = $cq->query($q_); while (my ($dest_router,$ipv4_subnet_address) = $sth_->fetchrow_array()) { # Check if $dest_router is in another area # and if so, that the adjacency is configured for # Level 2 routing my $q1 = "SELECT area_address FROM $router_info WHERE router_name = '$dest_router'"; my $sth1 = $cq->query($q1); my @row = $sth1->fetchrow_array(); my $dest_area_addr = $row[0]; # Compare to see if they match if ($origin_area_addr eq $dest_area_addr) { # I don't think this is correct -- they can form a level 2 adjacency # intra-area adjacency # Check if both interfaces are configured for # Level 1 routing and warn if they are not since # no adjacency will be formed here # my $q2 = "SELECT router_name,interface_name,level1_routing FROM $router_interfaces WHERE ipv4_address='$ipv4_subnet_address' AND (router_name='$origin_router' OR router_name='dest_router')"; # my $sth2 = $cq->query($q2); # while (my ($rtr,$interface,$level) = $sth2->fetchrow_array()) { # if ($level == 0) { # print "WARNING: $origin_router and $dest_router have INTRA-AREA connection\n but $rtr on $interface NOT configured for Level 1 routing.\n" if !$quiet; # } # } } else { # inter-area adjacency # Check if both interfaces are configured for # Level 2 routing and warn if they are not since # no adjacency will be formed here my $q2 = "SELECT router_name,interface_name,level2_routing FROM $router_interfaces WHERE ipv4_address='$ipv4_subnet_address' AND (router_name='$origin_router' OR router_name='dest_router')"; my $sth2 = $cq->query($q2); while (my ($rtr,$interface,$level) = $sth2->fetchrow_array()) { if ($level == 0) { print "WARNING: $origin_router and $dest_router have INTER-AREA connection\n but $rtr on $interface NOT configured for Level 2 routing.\n" if !$quiet; } } } } } # Handle printing summary info later } 1;
noise-lab/rcc
perl/src/queries/modules/isis/adjacency.pm
Perl
mit
8,563
#!/usr/bin/env perl use strict; use warnings; use v5.10; use lib 'auto-lib', 'lib'; use Paws; use Future; #use Mojo::IOLoop; #use Paws::Net::MojoAsyncCaller; use Data::Dumper; #my $loop = Mojo::IOLoop->new; #my $aws = Paws->new(config => { caller => Paws::Net::MojoAsyncCaller->new(loop => $loop) } ); my $aws = Paws->new(config => { caller => 'Paws::Net::MojoAsyncCaller' } ); my @fs; my $f = $aws->service('EC2', region => 'eu-west-1')->DescribeRegions->then(sub { my $res = shift; foreach my $reg (map { $_->RegionName } @{ $res->Regions }) { my $as = $aws->service('EC2', region => $reg, ); my $f = $as->DescribeSecurityGroups->then(sub { my ($res) = @_; my @sg_names = map { $_->GroupName . " (" . $_->GroupId . ")" } @{ $res->SecurityGroups }; say scalar(localtime) . " Got for $reg"; Future->done(@sg_names) })->else(sub { say scalar(localtime) . " Failed $reg"; Future->fail('Handled error'); })->then(sub { my @res = @_; say join "\n", scalar(localtime), @res; say scalar(localtime) . " End for $reg"; Future->done('DONE'); }); push @fs, $f; } Future->needs_all(@fs); }); $f->on_ready( sub { my $f = shift; my $res = $f->get; say scalar(localtime) . ' Done'; Mojo::IOLoop->stop; return Future->done($res); }); $f->on_fail( sub { say "Something failed spectacularly"; }); #Mojo::IOLoop->start; my $x = $f->get; say scalar(localtime) . " " . Dumper($x); say scalar(localtime) . " Done ioloop";
ioanrogers/aws-sdk-perl
examples/async-sg.pl
Perl
apache-2.0
1,537
# Copyright 2014 - present MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; use warnings; package MongoDB::Op::_ListCollections; # Encapsulate collection list operations; returns arrayref of collection # names use version; our $VERSION = 'v2.2.3'; use Moo; use MongoDB::Op::_Command; use MongoDB::Op::_Query; use MongoDB::ReadConcern; use MongoDB::ReadPreference; use MongoDB::_Types qw( Document ReadPreference ); use Types::Standard qw( HashRef InstanceOf Str ); use Tie::IxHash; use boolean; use namespace::clean; has client => ( is => 'ro', required => 1, isa => InstanceOf['MongoDB::MongoClient'], ); has filter => ( is => 'ro', required => 1, isa => Document, ); has options => ( is => 'ro', required => 1, isa => HashRef, ); has read_preference => ( is => 'rw', # rw for Op::_Query which can be modified by Cursor required => 1, isa => ReadPreference, ); with $_ for qw( MongoDB::Role::_PrivateConstructor MongoDB::Role::_DatabaseOp MongoDB::Role::_CommandCursorOp ); sub execute { my ( $self, $link, $topology ) = @_; my $res = $link->supports_list_commands ? $self->_command_list_colls( $link, $topology ) : $self->_legacy_list_colls( $link, $topology ); return $res; } sub _command_list_colls { my ( $self, $link, $topology ) = @_; my $options = $self->options; # batchSize is not a command parameter itself like other options my $batchSize = delete $options->{batchSize}; if ( defined $batchSize ) { $options->{cursor} = { batchSize => $batchSize }; } else { $options->{cursor} = {}; } # Normalize or delete 'nameOnly' if ($options->{nameOnly}) { $options->{nameOnly} = true; } else { delete $options->{nameOnly}; } my $filter = ref( $self->filter ) eq 'ARRAY' ? { @{ $self->filter } } : $self->filter; my $cmd = Tie::IxHash->new( listCollections => 1, filter => $filter, nameOnly => false, %{$self->options}, ); my $op = MongoDB::Op::_Command->_new( db_name => $self->db_name, query => $cmd, query_flags => {}, bson_codec => $self->bson_codec, session => $self->session, monitoring_callback => $self->monitoring_callback, read_preference => $self->read_preference, ); my $res = $op->execute( $link, $topology ); return $self->_build_result_from_cursor( $res ); } sub _legacy_list_colls { my ( $self, $link, $topology ) = @_; my $op = MongoDB::Op::_Query->_new( filter => $self->filter, options => MongoDB::Op::_Query->precondition_options($self->options), db_name => $self->db_name, coll_name => 'system.namespaces', full_name => $self->db_name . ".system.namespaces", bson_codec => $self->bson_codec, client => $self->client, read_preference => $self->read_preference || MongoDB::ReadPreference->new, read_concern => MongoDB::ReadConcern->new, post_filter => \&__filter_legacy_names, monitoring_callback => $self->monitoring_callback, ); return $op->execute( $link, $topology ); } # exclude names with '$' except oplog.$ # XXX why do we include oplog.$? sub __filter_legacy_names { my $doc = shift; # remove leading database name for compatibility with listCollections $doc->{name} =~ s/^[^.]+\.//; my $name = $doc->{name}; return !( index( $name, '$' ) >= 0 && index( $name, '.oplog.$' ) < 0 ); } 1;
xdg/mongo-perl-driver
lib/MongoDB/Op/_ListCollections.pm
Perl
apache-2.0
4,255
print "Is '^[0-9]+\$' mathed by '123456'?\n"; if ("123456" =~ /^[0-9]+$/){ print "yes"; }else{ print "no"; } print "Groups of '^([a-z]+)\\-(\\d+)\$' found in 'abcdef-12345'\n"; @matches = ("abcdef-12345" =~ /^([a-z]+)\-(\d+)$/); $matchCount = @matches; print "Found $matchCount groups.\n"; foreach $groupIndex (0..$#matches){ print "[$groupIndex] = $matches[$groupIndex]\n"; $groupIndex++; }
Bigsby/HelloLanguages
src/pl/regex.pl
Perl
apache-2.0
408
package TestModperl::subenv; use strict; use warnings FATAL => 'all'; use Apache2::RequestRec (); use APR::Table (); use Apache::Test; use Apache2::Const -compile => 'OK'; sub handler { my $r = shift; plan $r, tests => 31; # subprocess_env in void context with arguments does # nothing to %ENV { my $env = $r->subprocess_env; my $key = 'ONCE'; ok_false($r, $key); $r->subprocess_env($key => 1); # void context but with args ok_true($r, $key); ok ! $ENV{$key}; # %ENV not populated yet } # subprocess_env in void context with no arguments # populates the same as +SetEnv { my $env = $r->subprocess_env; my $key = 'REMOTE_ADDR'; ok_false($r, $key); # still not not there yet ok ! $ENV{$key}; # %ENV not populated yet $r->subprocess_env; # void context with no arguments ok_true($r, $key); ok $ENV{$key}; # mod_cgi emulation } # handlers can use a void context more than once to force # population of %ENV with new table entries { my $env = $r->subprocess_env; my $key = 'AGAIN'; $env->set($key => 1); # new table entry ok_true($r, $key); ok ! $ENV{$key}; # shouldn't affect %ENV yet $r->subprocess_env; # now called in in void context twice ok $ENV{$key}; # so %ENV is populated with new entry } { my $env = $r->subprocess_env; # table may have been overlayed my $key = 'FOO'; $env->set($key => 1); # direct call to set() ok_true($r, $key); ok ! $ENV{$key}; # shouldn't affect %ENV $r->subprocess_env($key => undef); ok_false($r, $key); # removed $r->subprocess_env($key => 1); ok_true($r, $key); # reset ok ! $ENV{$key}; # still shouldn't affect %ENV } Apache2::Const::OK; } sub ok_true { my ($r, $key) = @_; my $env = $r->subprocess_env; ok $env->get($key); ok $env->{$key}; ok $r->subprocess_env($key); } sub ok_false { my ($r, $key) = @_; my $env = $r->subprocess_env; ok ! $env->get($key); ok ! $env->{$key}; ok ! $r->subprocess_env($key); } 1; __END__ PerlOptions -SetupEnv
Distrotech/mod_perl
t/response/TestModperl/subenv.pm
Perl
apache-2.0
2,389
# Copyright 2017 - present MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use 5.008001; use strict; use warnings; package EvergreenHelper; use Config; use Carp 'croak'; use Cwd 'getcwd'; use File::Find qw/find/; use File::Path qw/mkpath rmtree/; use base 'Exporter'; our @EXPORT = qw( bootstrap_env bootstrap_locallib configure filter_file fix_config_files_in fix_shell_files_in fwd_slash get_info make maybe_prepend_env prepend_env run_in_dir run_local_cpanm run_perl5_cpanm slurp spew try_system ); #--------------------------------------------------------------------------# # constants #--------------------------------------------------------------------------# my $orig_dir = getcwd(); my $path_sep = $Config{path_sep}; my $perl5lib = "$orig_dir/perl5"; my $cpanm = "$orig_dir/cpanm"; #--------------------------------------------------------------------------# # functions #--------------------------------------------------------------------------# # bootstrap_env: bootstrap local libs and cpanm and clean up environment sub bootstrap_env { # bootstrap general perl local library bootstrap_locallib($perl5lib); # SHELL apparently causes trouble on MSWin32 perl launched from cygwin if ( $^O eq 'MSWin32' ) { delete $ENV{SHELL}; } # bootstrap cpanm unlink 'cpanm'; try_system(qw(curl -L https://cpanmin.us/ --fail --show-error --silent -o cpanm)); } # bootstrap_locallib: configure a local perl5 user directory in a path sub bootstrap_locallib { my $path = shift; for my $d (qw{bin lib/perl5}) { mkpath "$path/$d"; } maybe_prepend_env( PERL5LIB => "$path/lib/perl5" ); maybe_prepend_env( PATH => "$path/bin" ); require lib; lib->import("$path/lib/perl5"); } # configure: run Makefile.PL sub configure { try_system( $^X, "Makefile.PL" ) } # filter_file: given a path and a coderef that modifies $_, replace the # file with the modified contents sub filter_file { my ( $file, $code ) = @_; local $_ = slurp($file); $code->(); spew( $file, $_ ); } # fix_config_files_in: given a directory of mongo orchestration config # files, modify .json files to replace certain tokens sub fix_config_files_in { my $dir = shift; my $fixer = sub { return unless -f && /\.json$/; filter_file( $_, sub { s/ABSOLUTE_PATH_REPLACEMENT_TOKEN/$dir/g } ); }; find( $fixer, $dir ); } # fix_shell_files_in: given a directory with .sh files, clean them up # by removing CRs and fixing permissions sub fix_shell_files_in { my $dir = shift; my $fixer = sub { return unless -f && /\.sh$/; filter_file( $_, sub { s/\r//g } ); chmod 0755, $_ or croak chmod "$_: $!"; }; find( $fixer, $dir ); } # fwd_slash: change a path to have forward slashes sub fwd_slash { my $path = shift; $path =~ tr[\\][/]; return $path; } # get_info: print PATH and perl-V info sub get_info { print "PATH = $ENV{PATH}\n"; # perl -V prints all env vars starting with "PERL" try_system(qw(perl -V)); } # make: run 'make' or 'dmake' or whatever sub make { try_system( $Config{make}, @_ ) } # maybe_prepend_env: prepends a value to an ENV var if it doesn't exist. # This is currently hardcoded for PATH separators. sub maybe_prepend_env { my ( $key, $value ) = @_; my $orig = $ENV{$key}; return if defined $orig && ( $orig =~ m{ (?: ^ | $path_sep ) $value (?: $ | $path_sep ) }x ); my @orig = defined $ENV{$key} ? ( $ENV{$key} ) : (); $ENV{$key} = join( $path_sep, $value, @orig ); } # prepend_env: unconditionally prepend a value to an ENV var sub prepend_env { my ( $key, @list ) = @_; my @orig = defined $ENV{$key} ? ( $ENV{$key} ) : (); return join( $path_sep, @list, @orig ); } # run_in_dir: given a directory and code ref, temporarily change to that # directory for the duration of the code sub run_in_dir { my ( $dir, $code ) = @_; my $start_dir = getcwd(); my $guard = Local::TinyGuard->new( sub { chdir $start_dir } ); chdir $dir or croak "chdir $dir: $!\n"; $code->(); } # run_local_cpanm: run cpanm and install to a 'local' perl5lib sub run_local_cpanm { my @args = @_; my $locallib = getcwd() . "/local"; bootstrap_locallib($locallib); try_system( $^X, '--', $cpanm, qw( -v --no-lwp --no-interactive --skip-satisfied --with-recommends -l ), $locallib, @args ); } # run_perl5_cpanm: run cpanm and install to 'main' perl5lib sub run_perl5_cpanm { my @args = @_; try_system( $^X, '--', $cpanm, qw( -v --no-lwp --no-interactive --skip-satisfied --with-recommends -l ), $perl5lib, @args ); } # slurp: full file read sub slurp { my ($file) = @_; open my $fh, "<:raw", $file or croak "$file: $!"; return scalar do { local $/; <$fh> }; } # spew: full file write; NOT ATOMIC sub spew { my ( $file, @data ) = @_; open my $fh, ">:raw", $file or croak "$file: $!"; print {$fh} $_ for @data; close $fh or croak "closing $file: $!"; return 1; } # try_system: print and run a command and croak if exit code is non-zero sub try_system { my @command = @_; print "\nRunning: @command\n\n"; system(@command) and croak "Aborting: '@command' failed"; } # Local::TinyGuard -- an object that runs a closure on destruction package Local::TinyGuard; sub new { my ( $class, $code ) = @_; return bless $code, $class; } sub DESTROY { my $self = shift; $self->(); } 1;
dagolden/mongo-perl-driver
.evergreen/lib/EvergreenHelper.pm
Perl
apache-2.0
6,086
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package storage::ibm::storwize::ssh::mode::components::node; use strict; use warnings; sub load { my ($self) = @_; $self->{ssh_commands} .= 'echo "==========lsnode=========="; lsnode -delim : ; echo "===============";'; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking nodes"); $self->{components}->{node} = {name => 'nodes', total => 0, skip => 0}; return if ($self->check_filter(section => 'node')); return if ($self->{results} !~ /==========lsnode==.*?\n(.*?)==============/msi); my $content = $1; my $result = $self->get_hasharray(content => $content, delim => ':'); foreach (@$result) { next if ($self->check_filter(section => 'node', instance => $_->{id})); $self->{components}->{node}->{total}++; $self->{output}->output_add(long_msg => sprintf("node '%s' status is '%s' [instance: %s].", $_->{name}, $_->{status}, $_->{id} )); my $exit = $self->get_severity(label => 'default', section => 'node', value => $_->{status}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Node '%s' status is '%s'", $_->{name}, $_->{status})); } } } 1;
nichols-356/centreon-plugins
storage/ibm/storwize/ssh/mode/components/node.pm
Perl
apache-2.0
2,271
# # 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::securactive::mode::listbca; use base qw(centreon::plugins::mode); use strict; use warnings; my $oid_spvBCAName = '.1.3.6.1.4.1.36773.3.2.1.1.1.1'; 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 => { "name:s" => { name => 'name' }, "regexp" => { name => 'use_regexp' }, }); $self->{bca_id_selected} = []; return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub manage_selection { my ($self, %options) = @_; $self->{result_names} = $self->{snmp}->get_table(oid => $oid_spvBCAName, nothing_quit => 1); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{result_names}})) { next if ($oid !~ /\.([0-9]+)$/); my $instance = $1; # Get all without a name if (!defined($self->{option_results}->{name})) { push @{$self->{bca_id_selected}}, $instance; next; } $self->{result_names}->{$oid} = $self->{output}->to_utf8($self->{result_names}->{$oid}); if (!defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} eq $self->{option_results}->{name}) { push @{$self->{bca_id_selected}}, $instance; next; } if (defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} =~ /$self->{option_results}->{name}/) { push @{$self->{bca_id_selected}}, $instance; next; } $self->{output}->output_add(long_msg => "Skipping bca '" . $self->{result_names}->{$oid} . "': no matching filter name"); } } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->manage_selection(); foreach my $instance (sort @{$self->{bca_id_selected}}) { my $name = $self->{result_names}->{$oid_spvBCAName . '.' . $instance}; $self->{output}->output_add(long_msg => "'" . $name . "'"); } $self->{output}->output_add(severity => 'OK', short_msg => 'List bca:'); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } sub disco_format { my ($self, %options) = @_; $self->{output}->add_disco_format(elements => ['name']); } sub disco_show { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->manage_selection(); foreach my $instance (sort @{$self->{bca_id_selected}}) { my $name = $self->{result_names}->{$oid_spvBCAName . '.' . $instance}; $self->{output}->add_disco_entry(name => $name); } } 1; __END__ =head1 MODE List BCA. =over 8 =item B<--name> Set the bca name. =item B<--regexp> Allows to use regexp to filter bca name (with option --name). =back =cut
nichols-356/centreon-plugins
network/securactive/mode/listbca.pm
Perl
apache-2.0
3,912
=pod =head1 NAME OSSL_CRMF_MSG_get0_regCtrl_regToken, OSSL_CRMF_MSG_set1_regCtrl_regToken, OSSL_CRMF_MSG_get0_regCtrl_authenticator, OSSL_CRMF_MSG_set1_regCtrl_authenticator, OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo, OSSL_CRMF_MSG_set0_SinglePubInfo, OSSL_CRMF_MSG_set_PKIPublicationInfo_action, OSSL_CRMF_MSG_get0_regCtrl_pkiPublicationInfo, OSSL_CRMF_MSG_set1_regCtrl_pkiPublicationInfo, OSSL_CRMF_MSG_get0_regCtrl_protocolEncrKey, OSSL_CRMF_MSG_set1_regCtrl_protocolEncrKey, OSSL_CRMF_MSG_get0_regCtrl_oldCertID, OSSL_CRMF_MSG_set1_regCtrl_oldCertID, OSSL_CRMF_CERTID_gen - functions getting or setting CRMF Registration Controls =head1 SYNOPSIS #include <openssl/crmf.h> ASN1_UTF8STRING *OSSL_CRMF_MSG_get0_regCtrl_regToken(const OSSL_CRMF_MSG *msg); int OSSL_CRMF_MSG_set1_regCtrl_regToken(OSSL_CRMF_MSG *msg, const ASN1_UTF8STRING *tok); ASN1_UTF8STRING *OSSL_CRMF_MSG_get0_regCtrl_authenticator(const OSSL_CRMF_MSG *msg); int OSSL_CRMF_MSG_set1_regCtrl_authenticator(OSSL_CRMF_MSG *msg, const ASN1_UTF8STRING *auth); int OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo( OSSL_CRMF_PKIPUBLICATIONINFO *pi, OSSL_CRMF_SINGLEPUBINFO *spi); int OSSL_CRMF_MSG_set0_SinglePubInfo(OSSL_CRMF_SINGLEPUBINFO *spi, int method, GENERAL_NAME *nm); int OSSL_CRMF_MSG_set_PKIPublicationInfo_action( OSSL_CRMF_PKIPUBLICATIONINFO *pi, int action); OSSL_CRMF_PKIPUBLICATIONINFO *OSSL_CRMF_MSG_get0_regCtrl_pkiPublicationInfo(const OSSL_CRMF_MSG *msg); int OSSL_CRMF_MSG_set1_regCtrl_pkiPublicationInfo(OSSL_CRMF_MSG *msg, const OSSL_CRMF_PKIPUBLICATIONINFO *pi); X509_PUBKEY *OSSL_CRMF_MSG_get0_regCtrl_protocolEncrKey(const OSSL_CRMF_MSG *msg); int OSSL_CRMF_MSG_set1_regCtrl_protocolEncrKey(OSSL_CRMF_MSG *msg, const X509_PUBKEY *pubkey); OSSL_CRMF_CERTID *OSSL_CRMF_MSG_get0_regCtrl_oldCertID(const OSSL_CRMF_MSG *msg); int OSSL_CRMF_MSG_set1_regCtrl_oldCertID(OSSL_CRMF_MSG *msg, const OSSL_CRMF_CERTID *cid); OSSL_CRMF_CERTID *OSSL_CRMF_CERTID_gen(const X509_NAME *issuer, const ASN1_INTEGER *serial); =head1 DESCRIPTION Each of the OSSL_CRMF_MSG_get0_regCtrl_X() functions returns the respective control X in the given I<msg>, if present. OSSL_CRMF_MSG_set1_regCtrl_regToken() sets the regToken control in the given I<msg> copying the given I<tok> as value. See RFC 4211, section 6.1. OSSL_CRMF_MSG_set1_regCtrl_authenticator() sets the authenticator control in the given I<msg> copying the given I<auth> as value. See RFC 4211, section 6.2. OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo() pushes the given I<spi> to I<si>. Consumes the I<spi> pointer. OSSL_CRMF_MSG_set0_SinglePubInfo() sets in the given SinglePubInfo I<spi> the I<method> and publication location, in the form of a GeneralName, I<nm>. The publication location is optional, and therefore I<nm> may be NULL. The function consumes the I<nm> pointer if present. Available methods are: # define OSSL_CRMF_PUB_METHOD_DONTCARE 0 # define OSSL_CRMF_PUB_METHOD_X500 1 # define OSSL_CRMF_PUB_METHOD_WEB 2 # define OSSL_CRMF_PUB_METHOD_LDAP 3 OSSL_CRMF_MSG_set_PKIPublicationInfo_action() sets the action in the given I<pi> using the given I<action> as value. See RFC 4211, section 6.3. Available actions are: # define OSSL_CRMF_PUB_ACTION_DONTPUBLISH 0 # define OSSL_CRMF_PUB_ACTION_PLEASEPUBLISH 1 OSSL_CRMF_MSG_set1_regCtrl_pkiPublicationInfo() sets the pkiPublicationInfo control in the given I<msg> copying the given I<tok> as value. See RFC 4211, section 6.3. OSSL_CRMF_MSG_set1_regCtrl_protocolEncrKey() sets the protocolEncrKey control in the given I<msg> copying the given I<pubkey> as value. See RFC 4211 section 6.6. OSSL_CRMF_MSG_set1_regCtrl_oldCertID() sets the oldCertID control in the given I<msg> copying the given I<cid> as value. See RFC 4211, section 6.5. OSSL_CRMF_CERTID_gen produces an OSSL_CRMF_CERTID_gen structure copying the given I<issuer> name and I<serial> number. =head1 RETURN VALUES All OSSL_CRMF_MSG_get0_*() functions return the respective pointer value or NULL if not present and on error. All OSSL_CRMF_MSG_set1_*() functions return 1 on success, 0 on error. OSSL_CRMF_CERTID_gen() returns a pointer to the resulting structure or NULL on error. =head1 NOTES A function OSSL_CRMF_MSG_set1_regCtrl_pkiArchiveOptions() for setting an Archive Options Control is not yet implemented due to missing features to create the needed OSSL_CRMF_PKIARCHIVEOPTINS content. =head1 SEE ALSO RFC 4211 =head1 HISTORY The OpenSSL CRMF support was added in OpenSSL 3.0. =head1 COPYRIGHT Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
jens-maus/amissl
openssl/doc/man3/OSSL_CRMF_MSG_set1_regCtrl_regToken.pod
Perl
bsd-3-clause
5,282
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/ympzZnp0Uq/southamerica. Olson data version 2012c # # Do not edit this file directly. # package DateTime::TimeZone::America::Aruba; { $DateTime::TimeZone::America::Aruba::VERSION = '1.46'; } use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::Aruba::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, 60308944824, DateTime::TimeZone::NEG_INFINITY, 60308928000, -16824, 0, 'LMT' ], [ 60308944824, 61977933000, 60308928624, 61977916800, -16200, 0, 'ANT' ], [ 61977933000, DateTime::TimeZone::INFINITY, 61977918600, DateTime::TimeZone::INFINITY, -14400, 0, 'AST' ], ]; sub olson_version { '2012c' } sub has_dst_changes { 0 } sub _max_year { 2022 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
leighpauls/k2cro4
third_party/perl/perl/vendor/lib/DateTime/TimeZone/America/Aruba.pm
Perl
bsd-3-clause
1,098
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from /tmp/rnClxBLdxJ/australasia. Olson data version 2013a # # Do not edit this file directly. # package DateTime::TimeZone::Pacific::Fakaofo; { $DateTime::TimeZone::Pacific::Fakaofo::VERSION = '1.57'; } use strict; use Class::Singleton 1.03; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::Pacific::Fakaofo::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, # utc_start 59958271496, # utc_end 1901-01-01 11:24:56 (Tue) DateTime::TimeZone::NEG_INFINITY, # local_start 59958230400, # local_end 1901-01-01 00:00:00 (Tue) -41096, 0, 'LMT', ], [ 59958271496, # utc_start 1901-01-01 11:24:56 (Tue) 63460926000, # utc_end 2011-12-30 11:00:00 (Fri) 59958231896, # local_start 1901-01-01 00:24:56 (Tue) 63460886400, # local_end 2011-12-30 00:00:00 (Fri) -39600, 0, 'TKT', ], [ 63460926000, # utc_start 2011-12-30 11:00:00 (Fri) DateTime::TimeZone::INFINITY, # utc_end 63460972800, # local_start 2011-12-31 00:00:00 (Sat) DateTime::TimeZone::INFINITY, # local_end 46800, 0, 'TKT', ], ]; sub olson_version { '2013a' } sub has_dst_changes { 0 } sub _max_year { 2023 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/DateTime/TimeZone/Pacific/Fakaofo.pm
Perl
mit
1,493
# !!!!!!! 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'; 0620 0626 0628 062A 062E 0633 063F 0641 0647 0649 064A 066E 066F 0678 0687 069A 06BF 06C1 06C2 06CC 06CE 06D0 06D1 06FA 06FC 06FF 0712 0714 071A 071D 071F 0727 0729 072B 072D 072E 074E 0758 075C 076A 076D 0770 0772 0775 0777 077A 077F 07CA 07EA 0841 0845 0847 0848 084A 084E 0850 0853 0855 08A0 08A2 08A9 END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/lib/Jt/D.pl
Perl
mit
738
#! /usr/bin/env perl # Copyright 2005-2020 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the OpenSSL license (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 # ==================================================================== # Written by Andy Polyakov <appro@openssl.org> for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # ==================================================================== # October 2005 # # This is a "teaser" code, as it can be improved in several ways... # First of all non-SSE2 path should be implemented (yes, for now it # performs Montgomery multiplication/convolution only on SSE2-capable # CPUs such as P4, others fall down to original code). Then inner loop # can be unrolled and modulo-scheduled to improve ILP and possibly # moved to 128-bit XMM register bank (though it would require input # rearrangement and/or increase bus bandwidth utilization). Dedicated # squaring procedure should give further performance improvement... # Yet, for being draft, the code improves rsa512 *sign* benchmark by # 110%(!), rsa1024 one - by 70% and rsa4096 - by 20%:-) # December 2006 # # Modulo-scheduling SSE2 loops results in further 15-20% improvement. # Integer-only code [being equipped with dedicated squaring procedure] # gives ~40% on rsa512 sign benchmark... $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; push(@INC,"${dir}","${dir}../../perlasm"); require "x86asm.pl"; $output = pop; open STDOUT,">$output"; &asm_init($ARGV[0]); $sse2=0; for (@ARGV) { $sse2=1 if (/-DOPENSSL_IA32_SSE2/); } &external_label("OPENSSL_ia32cap_P") if ($sse2); &function_begin("bn_mul_mont"); $i="edx"; $j="ecx"; $ap="esi"; $tp="esi"; # overlapping variables!!! $rp="edi"; $bp="edi"; # overlapping variables!!! $np="ebp"; $num="ebx"; $_num=&DWP(4*0,"esp"); # stack top layout $_rp=&DWP(4*1,"esp"); $_ap=&DWP(4*2,"esp"); $_bp=&DWP(4*3,"esp"); $_np=&DWP(4*4,"esp"); $_n0=&DWP(4*5,"esp"); $_n0q=&QWP(4*5,"esp"); $_sp=&DWP(4*6,"esp"); $_bpend=&DWP(4*7,"esp"); $frame=32; # size of above frame rounded up to 16n &xor ("eax","eax"); &mov ("edi",&wparam(5)); # int num &cmp ("edi",4); &jl (&label("just_leave")); &lea ("esi",&wparam(0)); # put aside pointer to argument block &lea ("edx",&wparam(1)); # load ap &add ("edi",2); # extra two words on top of tp &neg ("edi"); &lea ("ebp",&DWP(-$frame,"esp","edi",4)); # future alloca($frame+4*(num+2)) &neg ("edi"); # minimize cache contention by arranging 2K window between stack # pointer and ap argument [np is also position sensitive vector, # but it's assumed to be near ap, as it's allocated at ~same # time]. &mov ("eax","ebp"); &sub ("eax","edx"); &and ("eax",2047); &sub ("ebp","eax"); # this aligns sp and ap modulo 2048 &xor ("edx","ebp"); &and ("edx",2048); &xor ("edx",2048); &sub ("ebp","edx"); # this splits them apart modulo 4096 &and ("ebp",-64); # align to cache line # An OS-agnostic version of __chkstk. # # Some OSes (Windows) insist on stack being "wired" to # physical memory in strictly sequential manner, i.e. if stack # allocation spans two pages, then reference to farmost one can # be punishable by SEGV. But page walking can do good even on # other OSes, because it guarantees that villain thread hits # the guard page before it can make damage to innocent one... &mov ("eax","esp"); &sub ("eax","ebp"); &and ("eax",-4096); &mov ("edx","esp"); # saved stack pointer! &lea ("esp",&DWP(0,"ebp","eax")); &mov ("eax",&DWP(0,"esp")); &cmp ("esp","ebp"); &ja (&label("page_walk")); &jmp (&label("page_walk_done")); &set_label("page_walk",16); &lea ("esp",&DWP(-4096,"esp")); &mov ("eax",&DWP(0,"esp")); &cmp ("esp","ebp"); &ja (&label("page_walk")); &set_label("page_walk_done"); ################################# load argument block... &mov ("eax",&DWP(0*4,"esi"));# BN_ULONG *rp &mov ("ebx",&DWP(1*4,"esi"));# const BN_ULONG *ap &mov ("ecx",&DWP(2*4,"esi"));# const BN_ULONG *bp &mov ("ebp",&DWP(3*4,"esi"));# const BN_ULONG *np &mov ("esi",&DWP(4*4,"esi"));# const BN_ULONG *n0 #&mov ("edi",&DWP(5*4,"esi"));# int num &mov ("esi",&DWP(0,"esi")); # pull n0[0] &mov ($_rp,"eax"); # ... save a copy of argument block &mov ($_ap,"ebx"); &mov ($_bp,"ecx"); &mov ($_np,"ebp"); &mov ($_n0,"esi"); &lea ($num,&DWP(-3,"edi")); # num=num-1 to assist modulo-scheduling #&mov ($_num,$num); # redundant as $num is not reused &mov ($_sp,"edx"); # saved stack pointer! if($sse2) { $acc0="mm0"; # mmx register bank layout $acc1="mm1"; $car0="mm2"; $car1="mm3"; $mul0="mm4"; $mul1="mm5"; $temp="mm6"; $mask="mm7"; &picmeup("eax","OPENSSL_ia32cap_P"); &bt (&DWP(0,"eax"),26); &jnc (&label("non_sse2")); &mov ("eax",-1); &movd ($mask,"eax"); # mask 32 lower bits &mov ($ap,$_ap); # load input pointers &mov ($bp,$_bp); &mov ($np,$_np); &xor ($i,$i); # i=0 &xor ($j,$j); # j=0 &movd ($mul0,&DWP(0,$bp)); # bp[0] &movd ($mul1,&DWP(0,$ap)); # ap[0] &movd ($car1,&DWP(0,$np)); # np[0] &pmuludq($mul1,$mul0); # ap[0]*bp[0] &movq ($car0,$mul1); &movq ($acc0,$mul1); # I wish movd worked for &pand ($acc0,$mask); # inter-register transfers &pmuludq($mul1,$_n0q); # *=n0 &pmuludq($car1,$mul1); # "t[0]"*np[0]*n0 &paddq ($car1,$acc0); &movd ($acc1,&DWP(4,$np)); # np[1] &movd ($acc0,&DWP(4,$ap)); # ap[1] &psrlq ($car0,32); &psrlq ($car1,32); &inc ($j); # j++ &set_label("1st",16); &pmuludq($acc0,$mul0); # ap[j]*bp[0] &pmuludq($acc1,$mul1); # np[j]*m1 &paddq ($car0,$acc0); # +=c0 &paddq ($car1,$acc1); # +=c1 &movq ($acc0,$car0); &pand ($acc0,$mask); &movd ($acc1,&DWP(4,$np,$j,4)); # np[j+1] &paddq ($car1,$acc0); # +=ap[j]*bp[0]; &movd ($acc0,&DWP(4,$ap,$j,4)); # ap[j+1] &psrlq ($car0,32); &movd (&DWP($frame-4,"esp",$j,4),$car1); # tp[j-1]= &psrlq ($car1,32); &lea ($j,&DWP(1,$j)); &cmp ($j,$num); &jl (&label("1st")); &pmuludq($acc0,$mul0); # ap[num-1]*bp[0] &pmuludq($acc1,$mul1); # np[num-1]*m1 &paddq ($car0,$acc0); # +=c0 &paddq ($car1,$acc1); # +=c1 &movq ($acc0,$car0); &pand ($acc0,$mask); &paddq ($car1,$acc0); # +=ap[num-1]*bp[0]; &movd (&DWP($frame-4,"esp",$j,4),$car1); # tp[num-2]= &psrlq ($car0,32); &psrlq ($car1,32); &paddq ($car1,$car0); &movq (&QWP($frame,"esp",$num,4),$car1); # tp[num].tp[num-1] &inc ($i); # i++ &set_label("outer"); &xor ($j,$j); # j=0 &movd ($mul0,&DWP(0,$bp,$i,4)); # bp[i] &movd ($mul1,&DWP(0,$ap)); # ap[0] &movd ($temp,&DWP($frame,"esp")); # tp[0] &movd ($car1,&DWP(0,$np)); # np[0] &pmuludq($mul1,$mul0); # ap[0]*bp[i] &paddq ($mul1,$temp); # +=tp[0] &movq ($acc0,$mul1); &movq ($car0,$mul1); &pand ($acc0,$mask); &pmuludq($mul1,$_n0q); # *=n0 &pmuludq($car1,$mul1); &paddq ($car1,$acc0); &movd ($temp,&DWP($frame+4,"esp")); # tp[1] &movd ($acc1,&DWP(4,$np)); # np[1] &movd ($acc0,&DWP(4,$ap)); # ap[1] &psrlq ($car0,32); &psrlq ($car1,32); &paddq ($car0,$temp); # +=tp[1] &inc ($j); # j++ &dec ($num); &set_label("inner"); &pmuludq($acc0,$mul0); # ap[j]*bp[i] &pmuludq($acc1,$mul1); # np[j]*m1 &paddq ($car0,$acc0); # +=c0 &paddq ($car1,$acc1); # +=c1 &movq ($acc0,$car0); &movd ($temp,&DWP($frame+4,"esp",$j,4));# tp[j+1] &pand ($acc0,$mask); &movd ($acc1,&DWP(4,$np,$j,4)); # np[j+1] &paddq ($car1,$acc0); # +=ap[j]*bp[i]+tp[j] &movd ($acc0,&DWP(4,$ap,$j,4)); # ap[j+1] &psrlq ($car0,32); &movd (&DWP($frame-4,"esp",$j,4),$car1);# tp[j-1]= &psrlq ($car1,32); &paddq ($car0,$temp); # +=tp[j+1] &dec ($num); &lea ($j,&DWP(1,$j)); # j++ &jnz (&label("inner")); &mov ($num,$j); &pmuludq($acc0,$mul0); # ap[num-1]*bp[i] &pmuludq($acc1,$mul1); # np[num-1]*m1 &paddq ($car0,$acc0); # +=c0 &paddq ($car1,$acc1); # +=c1 &movq ($acc0,$car0); &pand ($acc0,$mask); &paddq ($car1,$acc0); # +=ap[num-1]*bp[i]+tp[num-1] &movd (&DWP($frame-4,"esp",$j,4),$car1); # tp[num-2]= &psrlq ($car0,32); &psrlq ($car1,32); &movd ($temp,&DWP($frame+4,"esp",$num,4)); # += tp[num] &paddq ($car1,$car0); &paddq ($car1,$temp); &movq (&QWP($frame,"esp",$num,4),$car1); # tp[num].tp[num-1] &lea ($i,&DWP(1,$i)); # i++ &cmp ($i,$num); &jle (&label("outer")); &emms (); # done with mmx bank &jmp (&label("common_tail")); &set_label("non_sse2",16); } if (0) { &mov ("esp",$_sp); &xor ("eax","eax"); # signal "not fast enough [yet]" &jmp (&label("just_leave")); # While the below code provides competitive performance for # all key lengths on modern Intel cores, it's still more # than 10% slower for 4096-bit key elsewhere:-( "Competitive" # means compared to the original integer-only assembler. # 512-bit RSA sign is better by ~40%, but that's about all # one can say about all CPUs... } else { $inp="esi"; # integer path uses these registers differently $word="edi"; $carry="ebp"; &mov ($inp,$_ap); &lea ($carry,&DWP(1,$num)); &mov ($word,$_bp); &xor ($j,$j); # j=0 &mov ("edx",$inp); &and ($carry,1); # see if num is even &sub ("edx",$word); # see if ap==bp &lea ("eax",&DWP(4,$word,$num,4)); # &bp[num] &or ($carry,"edx"); &mov ($word,&DWP(0,$word)); # bp[0] &jz (&label("bn_sqr_mont")); &mov ($_bpend,"eax"); &mov ("eax",&DWP(0,$inp)); &xor ("edx","edx"); &set_label("mull",16); &mov ($carry,"edx"); &mul ($word); # ap[j]*bp[0] &add ($carry,"eax"); &lea ($j,&DWP(1,$j)); &adc ("edx",0); &mov ("eax",&DWP(0,$inp,$j,4)); # ap[j+1] &cmp ($j,$num); &mov (&DWP($frame-4,"esp",$j,4),$carry); # tp[j]= &jl (&label("mull")); &mov ($carry,"edx"); &mul ($word); # ap[num-1]*bp[0] &mov ($word,$_n0); &add ("eax",$carry); &mov ($inp,$_np); &adc ("edx",0); &imul ($word,&DWP($frame,"esp")); # n0*tp[0] &mov (&DWP($frame,"esp",$num,4),"eax"); # tp[num-1]= &xor ($j,$j); &mov (&DWP($frame+4,"esp",$num,4),"edx"); # tp[num]= &mov (&DWP($frame+8,"esp",$num,4),$j); # tp[num+1]= &mov ("eax",&DWP(0,$inp)); # np[0] &mul ($word); # np[0]*m &add ("eax",&DWP($frame,"esp")); # +=tp[0] &mov ("eax",&DWP(4,$inp)); # np[1] &adc ("edx",0); &inc ($j); &jmp (&label("2ndmadd")); &set_label("1stmadd",16); &mov ($carry,"edx"); &mul ($word); # ap[j]*bp[i] &add ($carry,&DWP($frame,"esp",$j,4)); # +=tp[j] &lea ($j,&DWP(1,$j)); &adc ("edx",0); &add ($carry,"eax"); &mov ("eax",&DWP(0,$inp,$j,4)); # ap[j+1] &adc ("edx",0); &cmp ($j,$num); &mov (&DWP($frame-4,"esp",$j,4),$carry); # tp[j]= &jl (&label("1stmadd")); &mov ($carry,"edx"); &mul ($word); # ap[num-1]*bp[i] &add ("eax",&DWP($frame,"esp",$num,4)); # +=tp[num-1] &mov ($word,$_n0); &adc ("edx",0); &mov ($inp,$_np); &add ($carry,"eax"); &adc ("edx",0); &imul ($word,&DWP($frame,"esp")); # n0*tp[0] &xor ($j,$j); &add ("edx",&DWP($frame+4,"esp",$num,4)); # carry+=tp[num] &mov (&DWP($frame,"esp",$num,4),$carry); # tp[num-1]= &adc ($j,0); &mov ("eax",&DWP(0,$inp)); # np[0] &mov (&DWP($frame+4,"esp",$num,4),"edx"); # tp[num]= &mov (&DWP($frame+8,"esp",$num,4),$j); # tp[num+1]= &mul ($word); # np[0]*m &add ("eax",&DWP($frame,"esp")); # +=tp[0] &mov ("eax",&DWP(4,$inp)); # np[1] &adc ("edx",0); &mov ($j,1); &set_label("2ndmadd",16); &mov ($carry,"edx"); &mul ($word); # np[j]*m &add ($carry,&DWP($frame,"esp",$j,4)); # +=tp[j] &lea ($j,&DWP(1,$j)); &adc ("edx",0); &add ($carry,"eax"); &mov ("eax",&DWP(0,$inp,$j,4)); # np[j+1] &adc ("edx",0); &cmp ($j,$num); &mov (&DWP($frame-8,"esp",$j,4),$carry); # tp[j-1]= &jl (&label("2ndmadd")); &mov ($carry,"edx"); &mul ($word); # np[j]*m &add ($carry,&DWP($frame,"esp",$num,4)); # +=tp[num-1] &adc ("edx",0); &add ($carry,"eax"); &adc ("edx",0); &mov (&DWP($frame-4,"esp",$num,4),$carry); # tp[num-2]= &xor ("eax","eax"); &mov ($j,$_bp); # &bp[i] &add ("edx",&DWP($frame+4,"esp",$num,4)); # carry+=tp[num] &adc ("eax",&DWP($frame+8,"esp",$num,4)); # +=tp[num+1] &lea ($j,&DWP(4,$j)); &mov (&DWP($frame,"esp",$num,4),"edx"); # tp[num-1]= &cmp ($j,$_bpend); &mov (&DWP($frame+4,"esp",$num,4),"eax"); # tp[num]= &je (&label("common_tail")); &mov ($word,&DWP(0,$j)); # bp[i+1] &mov ($inp,$_ap); &mov ($_bp,$j); # &bp[++i] &xor ($j,$j); &xor ("edx","edx"); &mov ("eax",&DWP(0,$inp)); &jmp (&label("1stmadd")); &set_label("bn_sqr_mont",16); $sbit=$num; &mov ($_num,$num); &mov ($_bp,$j); # i=0 &mov ("eax",$word); # ap[0] &mul ($word); # ap[0]*ap[0] &mov (&DWP($frame,"esp"),"eax"); # tp[0]= &mov ($sbit,"edx"); &shr ("edx",1); &and ($sbit,1); &inc ($j); &set_label("sqr",16); &mov ("eax",&DWP(0,$inp,$j,4)); # ap[j] &mov ($carry,"edx"); &mul ($word); # ap[j]*ap[0] &add ("eax",$carry); &lea ($j,&DWP(1,$j)); &adc ("edx",0); &lea ($carry,&DWP(0,$sbit,"eax",2)); &shr ("eax",31); &cmp ($j,$_num); &mov ($sbit,"eax"); &mov (&DWP($frame-4,"esp",$j,4),$carry); # tp[j]= &jl (&label("sqr")); &mov ("eax",&DWP(0,$inp,$j,4)); # ap[num-1] &mov ($carry,"edx"); &mul ($word); # ap[num-1]*ap[0] &add ("eax",$carry); &mov ($word,$_n0); &adc ("edx",0); &mov ($inp,$_np); &lea ($carry,&DWP(0,$sbit,"eax",2)); &imul ($word,&DWP($frame,"esp")); # n0*tp[0] &shr ("eax",31); &mov (&DWP($frame,"esp",$j,4),$carry); # tp[num-1]= &lea ($carry,&DWP(0,"eax","edx",2)); &mov ("eax",&DWP(0,$inp)); # np[0] &shr ("edx",31); &mov (&DWP($frame+4,"esp",$j,4),$carry); # tp[num]= &mov (&DWP($frame+8,"esp",$j,4),"edx"); # tp[num+1]= &mul ($word); # np[0]*m &add ("eax",&DWP($frame,"esp")); # +=tp[0] &mov ($num,$j); &adc ("edx",0); &mov ("eax",&DWP(4,$inp)); # np[1] &mov ($j,1); &set_label("3rdmadd",16); &mov ($carry,"edx"); &mul ($word); # np[j]*m &add ($carry,&DWP($frame,"esp",$j,4)); # +=tp[j] &adc ("edx",0); &add ($carry,"eax"); &mov ("eax",&DWP(4,$inp,$j,4)); # np[j+1] &adc ("edx",0); &mov (&DWP($frame-4,"esp",$j,4),$carry); # tp[j-1]= &mov ($carry,"edx"); &mul ($word); # np[j+1]*m &add ($carry,&DWP($frame+4,"esp",$j,4)); # +=tp[j+1] &lea ($j,&DWP(2,$j)); &adc ("edx",0); &add ($carry,"eax"); &mov ("eax",&DWP(0,$inp,$j,4)); # np[j+2] &adc ("edx",0); &cmp ($j,$num); &mov (&DWP($frame-8,"esp",$j,4),$carry); # tp[j]= &jl (&label("3rdmadd")); &mov ($carry,"edx"); &mul ($word); # np[j]*m &add ($carry,&DWP($frame,"esp",$num,4)); # +=tp[num-1] &adc ("edx",0); &add ($carry,"eax"); &adc ("edx",0); &mov (&DWP($frame-4,"esp",$num,4),$carry); # tp[num-2]= &mov ($j,$_bp); # i &xor ("eax","eax"); &mov ($inp,$_ap); &add ("edx",&DWP($frame+4,"esp",$num,4)); # carry+=tp[num] &adc ("eax",&DWP($frame+8,"esp",$num,4)); # +=tp[num+1] &mov (&DWP($frame,"esp",$num,4),"edx"); # tp[num-1]= &cmp ($j,$num); &mov (&DWP($frame+4,"esp",$num,4),"eax"); # tp[num]= &je (&label("common_tail")); &mov ($word,&DWP(4,$inp,$j,4)); # ap[i] &lea ($j,&DWP(1,$j)); &mov ("eax",$word); &mov ($_bp,$j); # ++i &mul ($word); # ap[i]*ap[i] &add ("eax",&DWP($frame,"esp",$j,4)); # +=tp[i] &adc ("edx",0); &mov (&DWP($frame,"esp",$j,4),"eax"); # tp[i]= &xor ($carry,$carry); &cmp ($j,$num); &lea ($j,&DWP(1,$j)); &je (&label("sqrlast")); &mov ($sbit,"edx"); # zaps $num &shr ("edx",1); &and ($sbit,1); &set_label("sqradd",16); &mov ("eax",&DWP(0,$inp,$j,4)); # ap[j] &mov ($carry,"edx"); &mul ($word); # ap[j]*ap[i] &add ("eax",$carry); &lea ($carry,&DWP(0,"eax","eax")); &adc ("edx",0); &shr ("eax",31); &add ($carry,&DWP($frame,"esp",$j,4)); # +=tp[j] &lea ($j,&DWP(1,$j)); &adc ("eax",0); &add ($carry,$sbit); &adc ("eax",0); &cmp ($j,$_num); &mov (&DWP($frame-4,"esp",$j,4),$carry); # tp[j]= &mov ($sbit,"eax"); &jle (&label("sqradd")); &mov ($carry,"edx"); &add ("edx","edx"); &shr ($carry,31); &add ("edx",$sbit); &adc ($carry,0); &set_label("sqrlast"); &mov ($word,$_n0); &mov ($inp,$_np); &imul ($word,&DWP($frame,"esp")); # n0*tp[0] &add ("edx",&DWP($frame,"esp",$j,4)); # +=tp[num] &mov ("eax",&DWP(0,$inp)); # np[0] &adc ($carry,0); &mov (&DWP($frame,"esp",$j,4),"edx"); # tp[num]= &mov (&DWP($frame+4,"esp",$j,4),$carry); # tp[num+1]= &mul ($word); # np[0]*m &add ("eax",&DWP($frame,"esp")); # +=tp[0] &lea ($num,&DWP(-1,$j)); &adc ("edx",0); &mov ($j,1); &mov ("eax",&DWP(4,$inp)); # np[1] &jmp (&label("3rdmadd")); } &set_label("common_tail",16); &mov ($np,$_np); # load modulus pointer &mov ($rp,$_rp); # load result pointer &lea ($tp,&DWP($frame,"esp")); # [$ap and $bp are zapped] &mov ("eax",&DWP(0,$tp)); # tp[0] &mov ($j,$num); # j=num-1 &xor ($i,$i); # i=0 and clear CF! &set_label("sub",16); &sbb ("eax",&DWP(0,$np,$i,4)); &mov (&DWP(0,$rp,$i,4),"eax"); # rp[i]=tp[i]-np[i] &dec ($j); # doesn't affect CF! &mov ("eax",&DWP(4,$tp,$i,4)); # tp[i+1] &lea ($i,&DWP(1,$i)); # i++ &jge (&label("sub")); &sbb ("eax",0); # handle upmost overflow bit &mov ("edx",-1); &xor ("edx","eax"); &jmp (&label("copy")); &set_label("copy",16); # conditional copy &mov ($tp,&DWP($frame,"esp",$num,4)); &mov ($np,&DWP(0,$rp,$num,4)); &mov (&DWP($frame,"esp",$num,4),$j); # zap temporary vector &and ($tp,"eax"); &and ($np,"edx"); &or ($np,$tp); &mov (&DWP(0,$rp,$num,4),$np); &dec ($num); &jge (&label("copy")); &mov ("esp",$_sp); # pull saved stack pointer &mov ("eax",1); &set_label("just_leave"); &function_end("bn_mul_mont"); &asciz("Montgomery Multiplication for x86, CRYPTOGAMS by <appro\@openssl.org>"); &asm_finish(); close STDOUT or die "error closing STDOUT: $!";
pmq20/ruby-compiler
vendor/openssl/crypto/bn/asm/x86-mont.pl
Perl
mit
17,701
#!/usr/bin/perl my $status = 200; if (defined $ENV{"QUERY_STRING"}) { $status = $ENV{"QUERY_STRING"}; } print "HTTP/1.0 ".$status." FooBar\r\n"; print "\r\n";
ctdk/lighttpd-1.4.x
tests/docroot/www/nph-status.pl
Perl
bsd-3-clause
163
=pod =head1 NAME SSL_CTX_set_tmp_rsa_callback, SSL_CTX_set_tmp_rsa, SSL_CTX_need_tmp_rsa, SSL_set_tmp_rsa_callback, SSL_set_tmp_rsa, SSL_need_tmp_rsa - handle RSA keys for ephemeral key exchange =head1 SYNOPSIS #include <openssl/ssl.h> void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*tmp_rsa_callback)(SSL *ssl, int is_export, int keylength)); long SSL_CTX_set_tmp_rsa(SSL_CTX *ctx, RSA *rsa); long SSL_CTX_need_tmp_rsa(SSL_CTX *ctx); void SSL_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*tmp_rsa_callback)(SSL *ssl, int is_export, int keylength)); long SSL_set_tmp_rsa(SSL *ssl, RSA *rsa) long SSL_need_tmp_rsa(SSL *ssl) RSA *(*tmp_rsa_callback)(SSL *ssl, int is_export, int keylength); =head1 DESCRIPTION SSL_CTX_set_tmp_rsa_callback() sets the callback function for B<ctx> to be used when a temporary/ephemeral RSA key is required to B<tmp_rsa_callback>. The callback is inherited by all SSL objects newly created from B<ctx> with <SSL_new(3)|SSL_new(3)>. Already created SSL objects are not affected. SSL_CTX_set_tmp_rsa() sets the temporary/ephemeral RSA key to be used to be B<rsa>. The key is inherited by all SSL objects newly created from B<ctx> with <SSL_new(3)|SSL_new(3)>. Already created SSL objects are not affected. SSL_CTX_need_tmp_rsa() returns 1, if a temporary/ephemeral RSA key is needed for RSA-based strength-limited 'exportable' ciphersuites because a RSA key with a keysize larger than 512 bits is installed. SSL_set_tmp_rsa_callback() sets the callback only for B<ssl>. SSL_set_tmp_rsa() sets the key only for B<ssl>. SSL_need_tmp_rsa() returns 1, if a temporary/ephemeral RSA key is needed, for RSA-based strength-limited 'exportable' ciphersuites because a RSA key with a keysize larger than 512 bits is installed. These functions apply to SSL/TLS servers only. =head1 NOTES When using a cipher with RSA authentication, an ephemeral RSA key exchange can take place. In this case the session data are negotiated using the ephemeral/temporary RSA key and the RSA key supplied and certified by the certificate chain is only used for signing. Under previous export restrictions, ciphers with RSA keys shorter (512 bits) than the usual key length of 1024 bits were created. To use these ciphers with RSA keys of usual length, an ephemeral key exchange must be performed, as the normal (certified) key cannot be directly used. Using ephemeral RSA key exchange yields forward secrecy, as the connection can only be decrypted, when the RSA key is known. By generating a temporary RSA key inside the server application that is lost when the application is left, it becomes impossible for an attacker to decrypt past sessions, even if he gets hold of the normal (certified) RSA key, as this key was used for signing only. The downside is that creating a RSA key is computationally expensive. Additionally, the use of ephemeral RSA key exchange is only allowed in the TLS standard, when the RSA key can be used for signing only, that is for export ciphers. Using ephemeral RSA key exchange for other purposes violates the standard and can break interoperability with clients. It is therefore strongly recommended to not use ephemeral RSA key exchange and use DHE (Ephemeral Diffie-Hellman) key exchange instead in order to achieve forward secrecy (see L<SSL_CTX_set_tmp_dh_callback(3)|SSL_CTX_set_tmp_dh_callback(3)>). An application may either directly specify the key or can supply the key via a callback function. The callback approach has the advantage, that the callback may generate the key only in case it is actually needed. As the generation of a RSA key is however costly, it will lead to a significant delay in the handshake procedure. Another advantage of the callback function is that it can supply keys of different size while the explicit setting of the key is only useful for key size of 512 bits to satisfy the export restricted ciphers and does give away key length if a longer key would be allowed. The B<tmp_rsa_callback> is called with the B<keylength> needed and the B<is_export> information. The B<is_export> flag is set, when the ephemeral RSA key exchange is performed with an export cipher. =head1 EXAMPLES Generate temporary RSA keys to prepare ephemeral RSA key exchange. As the generation of a RSA key costs a lot of computer time, they saved for later reuse. For demonstration purposes, two keys for 512 bits and 1024 bits respectively are generated. ... /* Set up ephemeral RSA stuff */ RSA *rsa_512 = NULL; RSA *rsa_1024 = NULL; rsa_512 = RSA_generate_key(512,RSA_F4,NULL,NULL); if (rsa_512 == NULL) evaluate_error_queue(); rsa_1024 = RSA_generate_key(1024,RSA_F4,NULL,NULL); if (rsa_1024 == NULL) evaluate_error_queue(); ... RSA *tmp_rsa_callback(SSL *s, int is_export, int keylength) { RSA *rsa_tmp=NULL; switch (keylength) { case 512: if (rsa_512) rsa_tmp = rsa_512; else { /* generate on the fly, should not happen in this example */ rsa_tmp = RSA_generate_key(keylength,RSA_F4,NULL,NULL); rsa_512 = rsa_tmp; /* Remember for later reuse */ } break; case 1024: if (rsa_1024) rsa_tmp=rsa_1024; else should_not_happen_in_this_example(); break; default: /* Generating a key on the fly is very costly, so use what is there */ if (rsa_1024) rsa_tmp=rsa_1024; else rsa_tmp=rsa_512; /* Use at least a shorter key */ } return(rsa_tmp); } =head1 RETURN VALUES SSL_CTX_set_tmp_rsa_callback() and SSL_set_tmp_rsa_callback() do not return diagnostic output. SSL_CTX_set_tmp_rsa() and SSL_set_tmp_rsa() do return 1 on success and 0 on failure. Check the error queue to find out the reason of failure. SSL_CTX_need_tmp_rsa() and SSL_need_tmp_rsa() return 1 if a temporary RSA key is needed and 0 otherwise. =head1 SEE ALSO L<ssl(3)|ssl(3)>, L<SSL_CTX_set_cipher_list(3)|SSL_CTX_set_cipher_list(3)>, L<SSL_CTX_set_options(3)|SSL_CTX_set_options(3)>, L<SSL_CTX_set_tmp_dh_callback(3)|SSL_CTX_set_tmp_dh_callback(3)>, L<SSL_new(3)|SSL_new(3)>, L<ciphers(1)|ciphers(1)> =cut
Gum-Joe/nodegit
vendor/openssl/openssl/doc/ssl/SSL_CTX_set_tmp_rsa_callback.pod
Perl
mit
6,146
use warnings; use strict; my $verbose_flag = 0; my $hashing_value = 100000; my %all_features; my %enst2type; my %enst2ensg; my %ensg2name; my %ensg2type; my $clip_fi1 = $ARGV[0]; my $output_fi = $ARGV[1]; if (-e $output_fi) { print STDERR "$output_fi already exists, skipping...\n"; exit; } open(OUT,">$output_fi"); &read_gencode_gtf(); &read_gencode(); my %readcounts_by_region; #my $clip_fi1 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/IGF2BP1-205-INPUT_S4_L001_R2.polyATrim.adapterTrim.rmRep.rmDup.sorted.bam.5.pos.bg"; #my $clip_fi2 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/IGF2BP1-205-INPUT_S4_L001_R2.polyATrim.adapterTrim.rmRep.rmDup.sorted.bam.5.neg.bg"; #my $clip_fi1 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/IGF2BP1_HepG2_205_02.bam.5.pos.bg"; #my $clip_fi2 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/IGF2BP1_HepG2_205_02.bam.5.neg.bg"; #my $clip_fi1 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/RBFOX2_HepG2_204_02.bam.5.pos.bg"; #my $clip_fi2 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/RBFOX2_HepG2_204_02.bam.5.neg.bg"; #my $clip_fi1 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/RBFOX2-204-INPUT_S2_L001_R2.polyATrim.adapterTrim.rmRep.rmDup.sorted.bam.5.pos.bg"; #my $clip_fi2 = "/home/elvannostrand/data/clip/CLIPseq_analysis/input_comparison/RBFOX2-204-INPUT_S2_L001_R2.polyATrim.adapterTrim.rmRep.rmDup.sorted.bam.5.neg.bg"; &read_bam_fi($clip_fi1); #&read_bgfi($clip_fi1,"+"); #&read_bgfi($clip_fi2,"-"); my @final_feature_types = ("CDS","5utr","3utr","5utr|3utr","intron","intergenic","noncoding_exon","noncoding_intron"); print OUT "ENSG"; for my $feature_type (@final_feature_types) { print OUT "\t$feature_type"; } print OUT "\n"; for my $key (keys %readcounts_by_region) { print OUT "$key"; for my $feature_type (@final_feature_types) { my $toprint = 0; if (exists $readcounts_by_region{$key}{$feature_type}) { $toprint = $readcounts_by_region{$key}{$feature_type}; } print OUT "\t$toprint"; } print OUT "\n"; } sub read_bam_fi { my $bamfile = shift; print STDERR "now doing $bamfile\n"; if ($bamfile =~ /\.bam/) { open(B,"samtools view -h $bamfile |") || die "no $bamfile\n"; } elsif ($bamfile =~ /\.sam/) { open(B,$bamfile) || die "no sam $bamfile\n"; } else { print STDERR "file format error not .sam or .bam \n"; exit; } while (<B>) { my $r1 = $_; if ($r1 =~ /^\@/) { next; } my @tmp_r1 = split(/\t/,$r1); my @read_name = split(/\:/,$tmp_r1[0]); my $randommer = $read_name[0]; my $r1_cigar = $tmp_r1[5]; my $r1sam_flag = $tmp_r1[1]; my $mismatch_flags = $tmp_r1[14]; my $r1_chr = $tmp_r1[2]; my $r1_start = $tmp_r1[3]; my $frag_strand; if ($r1sam_flag == 16) { $frag_strand = "-"; } elsif ($r1sam_flag == 0) { $frag_strand = "+"; } else { print STDERR "R1 strand error $r1sam_flag\n"; } my @read_regions = &parse_cigar_string($r1_start,$r1_cigar,$r1_chr,$frag_strand); my $feature_flag = 0; my %tmp_hash; for my $region (@read_regions) { my ($rchr,$rstr,$rpos) = split(/\:/,$region); my ($rstart,$rstop) = split(/\-/,$rpos); my $rx = int($rstart / $hashing_value); my $ry = int($rstop / $hashing_value); for my $ri ($rx..$ry) { for my $feature (@{$all_features{$rchr}{$rstr}{$ri}}) { my ($feature_enst,$feature_type,$feature_region) = split(/\|/,$feature); my ($feature_start,$feature_stop) = split(/\-/,$feature_region); if ($feature_start <= $rstart && $rstop <= $feature_stop) { # read start is within region # if ($feature_start == $rstart_i) { # if ($feature_stop == $rstop) { # if ($feature_start == $rstart) { # print "fi $bamfile r1 $r1 region $region strand $rstr\nrstarti $rstart $_ feature $feature\n"; # } my $feature_ensg = $enst2ensg{$feature_enst}; $tmp_hash{$feature_ensg}{$feature_type}=1; $feature_flag = 1; # $verbose_flag = 1 if ($feature_ensg eq "ENSG00000176124.7"); # $verbose_flag = 1 if ($feature_ensg eq "ENSG00000169683.3"); print "found feature $_ $feature $feature_ensg $feature_type\n" if ($verbose_flag == 1); } } } } if ($feature_flag == 1) { for my $feature_ensg (keys %tmp_hash) { my $final_feature_type = "intergenic"; if (exists $tmp_hash{$feature_ensg}{"CDS"}) { $final_feature_type = "CDS"; } elsif (exists $tmp_hash{$feature_ensg}{"3utr"} || exists $tmp_hash{$feature_ensg}{"5utr"}) { if (exists $tmp_hash{$feature_ensg}{"3utr"} && exists $tmp_hash{$feature_ensg}{"5utr"}) { $final_feature_type = "5utr|3utr"; } elsif (exists $tmp_hash{$feature_ensg}{"3utr"}) { $final_feature_type = "3utr"; } elsif (exists $tmp_hash{$feature_ensg}{"5utr"}) { $final_feature_type = "5utr"; } else { print STDERR "weird shouldn't hit this\n"; } } elsif (exists $tmp_hash{$feature_ensg}{"intron"}) { $final_feature_type = "intron"; } elsif (exists $tmp_hash{$feature_ensg}{"noncoding_exon"}) { $final_feature_type = "noncoding_exon"; } elsif (exists $tmp_hash{$feature_ensg}{"noncoding_intron"}) { $final_feature_type = "noncoding_intron"; } print "adding to $feature_ensg $final_feature_type \n" if ($verbose_flag == 1); $readcounts_by_region{$feature_ensg}{$final_feature_type} ++; $readcounts_by_region{$feature_ensg}{all} ++; $readcounts_by_region{all}{$final_feature_type} ++; $readcounts_by_region{all}{all} ++; } } else { my $final_feature_type = "intergenic"; print "adding to all $final_feature_type \n" if ($verbose_flag == 1); $readcounts_by_region{all}{$final_feature_type} ++; $readcounts_by_region{all}{all} ++; } } close(B); } sub parse_cigar_string { my $region_start_pos = shift; my $flags = shift; my $chr = shift; my $strand = shift; my $current_pos = $region_start_pos; my @regions; while ($flags =~ /(\d+)([A-Z])/g) { if ($2 eq "N") { #read has intron of N bases at location push @regions,$chr.":".$strand.":".$region_start_pos."-".($current_pos-1); $current_pos += $1; $region_start_pos = $current_pos; } elsif ($2 eq "M") { #read and genome match $current_pos += $1; } elsif ($2 eq "S") { #beginning of read is soft-clipped; mapped pos is actually start pos of mapping not start of read } elsif ($2 eq "I") { #read has insertion relative to genome; doesn't change genome position } elsif ($2 eq "D") { # push @read_regions,$chr.":".$current_pos."-".($current_pos+=$1); $current_pos += $1; #read has deletion relative to genome; genome position has to increase } else { print STDERR "flag $1 $2 $flags\n"; } } push @regions,$chr.":".$strand.":".$region_start_pos."-".($current_pos-1); return(@regions); } sub read_gencode { ## eric note: this has been tested yet for off-by-1 issues with ucsc brower table output 5/29/15 my $fi = "/projects/ps-yeolab/genomes/hg19/gencode_v19/gencodev19_comprehensive"; print STDERR "reading in $fi\n"; open(F,$fi); while (<F>) { chomp($_); my @tmp = split(/\t/,$_); my $enst = $tmp[1]; next if ($enst eq "name"); my $chr = $tmp[2]; my $str = $tmp[3]; my $txstart = $tmp[4]; my $txstop = $tmp[5]; my $cdsstart = $tmp[6]; my $cdsstop = $tmp[7]; my @starts = split(/\,/,$tmp[9]); my @stops = split(/\,/,$tmp[10]); my @tmp_features; my $transcript_type = $enst2type{$enst}; unless ($transcript_type) { print STDERR "error transcript_type $transcript_type $enst\n"; } if ($transcript_type eq "protein_coding") { for (my $i=0;$i<@starts;$i++) { if ($str eq "+") { if ($stops[$i] < $cdsstart) { # exon is all 5' utr push @tmp_features,$enst."|5utr|".($starts[$i]+1)."-".$stops[$i]; } elsif ($starts[$i] > $cdsstop) { #exon is all 3' utr push @tmp_features,$enst."|3utr|".($starts[$i]+1)."-".$stops[$i]; } elsif ($starts[$i] > $cdsstart && $stops[$i] < $cdsstop) { #exon is all coding push @tmp_features,$enst."|CDS|".($starts[$i]+1)."-".$stops[$i]; } else { my $cdsregion_start = $starts[$i]; my $cdsregion_stop = $stops[$i]; if ($starts[$i] <= $cdsstart && $cdsstart <= $stops[$i]) { #cdsstart is in exon my $five_region = ($starts[$i]+1)."-".$cdsstart; push @tmp_features,$enst."|5utr|".$five_region; $cdsregion_start = $cdsstart; } if ($starts[$i] <= $cdsstop && $cdsstop <= $stops[$i]) { #cdsstop is in exon my $three_region = ($cdsstop+1)."-".$stops[$i]; push @tmp_features,$enst."|3utr|".$three_region; $cdsregion_stop = $cdsstop; } my $cds_region = ($cdsregion_start+1)."-".$cdsregion_stop; push @tmp_features,$enst."|CDS|".$cds_region; } } elsif ($str eq "-") { if ($stops[$i] < $cdsstart) { # exon is all 5' utr push @tmp_features,$enst."|3utr|".($starts[$i]+1)."-".$stops[$i]; } elsif ($starts[$i] > $cdsstop) { #exon is all 3' utr push @tmp_features,$enst."|5utr|".($starts[$i]+1)."-".$stops[$i]; } elsif ($starts[$i] > $cdsstart &&$stops[$i] < $cdsstop) { #exon is all coding push @tmp_features,$enst."|CDS|".($starts[$i]+1)."-".$stops[$i]; } else { my $cdsregion_start = $starts[$i]; my $cdsregion_stop = $stops[$i]; if ($starts[$i] <= $cdsstart && $cdsstart <= $stops[$i]) { #cdsstart is in exon my $three_region = ($starts[$i]+1)."-".$cdsstart; push @tmp_features,$enst."|3utr|".$three_region; $cdsregion_start = $cdsstart; } if ($starts[$i] <= $cdsstop && $cdsstop <= $stops[$i]) { #cdsstop is in exon my $five_region = ($cdsstop+1)."-".$stops[$i]; push @tmp_features,$enst."|5utr|".$five_region; $cdsregion_stop = $cdsstop; } my $cds_region = ($cdsregion_start+1)."-".$cdsregion_stop; push @tmp_features,$enst."|CDS|".$cds_region; } } } for (my $i=0;$i<scalar(@starts)-1;$i++) { push @tmp_features,$enst."|intron|".($stops[$i]+1)."-".$starts[$i+1]; } } else { for (my $i=0;$i<@starts;$i++) { push @tmp_features,$enst."|noncoding_exon|".($starts[$i]+1)."-".$stops[$i]; } for (my $i=0;$i<scalar(@starts)-1;$i++) { push @tmp_features,$enst."|noncoding_intron|".($stops[$i]+1)."-".$starts[$i+1]; } } for my $feature (@tmp_features) { my ($enst,$type,$region) = split(/\|/,$feature); my ($reg_start,$reg_stop) = split(/\-/,$region); my $x = int($reg_start/$hashing_value); my $y = int($reg_stop /$hashing_value); for my $j ($x..$y) { push @{$all_features{$chr}{$str}{$j}},$feature; } } } close(F); } sub read_gencode_gtf { #my %gene_types; my $file = "/projects/ps-yeolab/genomes/hg19/gencode_v19/gencode.v19.chr_patch_hapl_scaff.annotation.gtf"; print STDERR "Reading in $file\n"; open(F,$file); for my $line (<F>) { chomp($line); next if ($line =~ /^\#/); my @tmp = split(/\t/,$line); my $stuff = $tmp[8]; my @stufff = split(/\;/,$stuff); my ($ensg_id,$gene_type,$gene_name,$enst_id,$transcript_type); for my $s (@stufff) { $s =~ s/^\s//g; $s =~ s/\s$//g; if ($s =~ /gene_id \"(.+?)\"/) { if ($ensg_id) { print STDERR "two ensg ids? $line\n"; } $ensg_id = $1; } if ($s =~ /transcript_id \"(.+?)\"/) { if ($enst_id) { prinst DERR "two enst ids? $line\n"; } $enst_id = $1; } if ($s =~ /gene_type \"(.+?)\"/) { if ($gene_type) { print STDERR "two gene types $line\n"; } $gene_type = $1; } if ($s =~ /transcript_type \"(.+?)\"/) { $transcript_type = $1; } if ($s =~ /gene_name \"(.+?)\"/) { $gene_name = $1; } } if (exists $enst2ensg{$enst_id} && $ensg_id ne $enst2ensg{$enst_id}) { print STDERR "error two ensgs for enst $enst_id $ensg_id $enst2ensg{$enst_id}\n"; } $enst2ensg{$enst_id} = $ensg_id; $ensg2name{$ensg_id}{$gene_name}=1; $ensg2type{$ensg_id}{$gene_type}=1; $enst2type{$enst_id} = $transcript_type; } close(F); }
YeoLab/gscripts
gscripts/rnaseq/count_reads_broadfeatures_frombamfi.pl
Perl
mit
13,431
package Nibelite::App; use 5.8.0; use strict; use warnings; use base qw(NetSDS::App); use constant CONF_DIR => '/opt/nibelite/etc'; =head1 NAME Nibelite::App - easy to use development API for Nibelite =head1 SYNOPSIS use base 'Nibelite::App'; sub process { my ($this) = @_; print $this->app_conf_param('secret_param'); } =head1 DESCRIPTION C<Nibelite::App> module provides easy to use framework for writing Nibelite applications. Nibelite is an old school mobile VAS application server developed to provide premium rate SMS services in short time. Later it was updated to handle MMS, WAP and WWW services as well. =cut use NetSDS::DBI; use Nibelite::Core; use version; our $VERSION = '0.001'; #=============================================================================== =head1 CLASS METHODS =over =item B<dbh()> - DBMS handler # Do platform suicide ;-) $app->dbh->call('delete from core.apps'); =cut #----------------------------------------------------------------------- __PACKAGE__->mk_accessors('dbh'); #=============================================================================== =item B<app_id()> - get application ID my $app_id = $this->app_id() =cut #----------------------------------------------------------------------- __PACKAGE__->mk_accessors('app_id'); # Optional #=============================================================================== =item B<app_name()> - get/set application name my $app_name = $this->app_name() =cut #----------------------------------------------------------------------- __PACKAGE__->mk_accessors('app_name'); # Optional #=============================================================================== =item B<core()> - Nibelite core API =cut #----------------------------------------------------------------------- __PACKAGE__->mk_accessors('core'); #----------------------------------------------------------------------- sub config_file { my ( $this, $file_name ) = @_; my $name = $this->SUPER::config_file($file_name); unless ( -f $name && -r $name ) { $name = $this->CONF_DIR . "/nibelite.conf"; } return $name; } sub initialize { my ( $this, %attrs ) = @_; $this->SUPER::initialize(%attrs); # Initialize DBMS connection $this->dbh( NetSDS::DBI->new( %{ $this->conf->{db}->{main} } ) ); unless ( $this->dbh->dbh ) { die "Can't connect to DBMS.\n"; } $this->core( Nibelite::Core->new( dbh => $this->dbh() ) ); # Get application ID if ( $this->conf->{app_name} ) { $this->{app_name} = $this->conf->{app_name}; $this->app_id( $this->get_app_id( $this->conf->{app_name} ) ); } else { $this->log('warning', "Unnamed application"); $this->{app_name} = undef; $this->app_id(undef); } } ## end sub initialize #*********************************************************************** =item B<get_app_id($app_name)> - get application id from DB Paramters: application name Returns: app id # Get application ID for 'chan_mts_1234' my $app_id = $this->get_app_id('chan_mts_1234'); =cut #----------------------------------------------------------------------- sub get_app_id { my ( $this, $app_name ) = @_; my $row = $this->dbh->fetch_call( "select id from core.apps where name = ?", $app_name ); return $row->[0]->{id} || undef; } #*********************************************************************** =item B<app_conf_param($tag)> - get application parameter from C<apps_conf> table Paramters: configuration tag Returns: configuration value Example: # Get 'sendsms_url' parameter for application my $url = $this->app_conf_param('sendsms_url'); =cut #----------------------------------------------------------------------- sub app_conf_param { my ( $this, $tag ) = @_; if ( $this->app_id ) { return $this->core->get_app_conf_param( $this->app_id, $tag ); } else { return $this->error("Can't get parameter for unknown application ID"); } } #*********************************************************************** =item B<get_app_conf($app_id)> - get application conf by id Paramters: application id Returns: application config as hash reference # Get config for application with id == 42 my $app_conf = $this->get_app_conf(42); # "Douglas Adams" expected :-) print $app_conf->{author}; =cut #----------------------------------------------------------------------- sub get_app_conf { my ( $this, $app_id ) = @_; my $res = $this->dbh->fetch_call( "select tag,value from core.apps_conf where app_id = ?", $app_id ); my $conf = {}; $conf->{ $_->{tag} } = $_->{value} for ( @{$res} ); # convert to hashref return $conf; } #*********************************************************************** =item B<get_channels($chan_type)> - get active channels IDs by type Paramters: channel type Returns: list of channels app_id my @kannel_channels = $app->get_channel('kannel'); =cut #----------------------------------------------------------------------- sub get_channels { my ( $this, $chan_type ) = @_; my @rows = map { $_->{id} } @{ $this->dbh->fetch_call( "select core.get_active_channels(?) as id", $chan_type ) }; return @rows; } 1; __END__ =back =head1 EXAMPLES =head1 BUGS Unknown yet =head1 SEE ALSO None =head1 TODO None =head1 AUTHOR Michael Bochkaryov <misha@rattler.kiev.ua> =cut
blinohod/nibelite
nibelite/lib/perl/Nibelite/App.pm
Perl
mit
5,327
package AgentSMS::Page; use strict; use warnings; use Carp; use English qw( -no_match_vars ); use Params::Validate qw( :all ); use Readonly; use LWP::UserAgent; use URI::URL; use AgentSMS::Config; use AgentSMS::Utils; Readonly::Scalar my $STATUS_OK => q{OK}; Readonly::Scalar my $METHOD_GET => q{get}; Readonly::Scalar my $METHOD_POST => q{post}; sub getAgentsmsPage { my ( $gate, $params, $method, $form_href ) = validate_pos( @_, { type => SCALAR }, { type => SCALAR }, { type => SCALAR }, { type => HASHREF, optional => 1 } ); my $gate_link = AgentSMS::Config::getAgentsmsLink( $gate ); my $url = sprintf( q{%s?%s}, $gate_link, $params ); my $url_ref = URI::URL::url $url; my $ua = LWP::UserAgent->new; my $hostport = sprintf( q{%s:%d}, $url_ref->host, $url_ref->port ); my $zone = AgentSMS::Config::getAgentsmsZone( $gate ); my $user = AgentSMS::Config::getAgentsmsUser( $gate ); my $pass = AgentSMS::Config::getAgentsmsPass( $gate ); $ua->credentials( $hostport, $zone, $user, $pass ); my $response; if ( $method eq $METHOD_GET ) { $response = $ua->get( $url ); } elsif ( $method eq $METHOD_POST ) { $response = $ua->post( $url, $form_href ); } if ($response->is_success) { return { result => $response->decoded_content, status => $STATUS_OK }; } else { die $response->status_line; } } sub getPartnerPageById { my ( $gate, $partner_id ) = validate_pos( @_, { type => SCALAR }, { type => SCALAR } ); my $params = sprintf( q{path=/partner/id:%d}, $partner_id ); return AgentSMS::Utils::extractResult( getAgentsmsPage( $gate, $params, $METHOD_GET ) ); } sub getPartnersPage { my ( $gate ) = validate_pos( @_, { type => SCALAR } ); my $params = q{path=/partner/all}; return AgentSMS::Utils::extractResult( getAgentsmsPage( $gate, $params, $METHOD_GET ) ); } sub addPartner { my ( $gate, $form_href ) = validate_pos( @_, { type => SCALAR }, { type => HASHREF } ); my $params = q{path=/partner}; return AgentSMS::Utils::extractResult( getAgentsmsPage( $gate, $params, $METHOD_POST, $form_href ) ); } sub getServicesPage { my ( $gate ) = validate_pos( @_, { type => SCALAR } ); my $params = q{path=/service_manager/all}; return AgentSMS::Utils::extractResult( getAgentsmsPage( $gate, $params, $METHOD_GET ) ); } sub getServicePageById { my ( $gate, $service_id ) = validate_pos( @_, { type => SCALAR }, { type => SCALAR } ); my $params = sprintf( q{path=/service_manager/id:%d}, $service_id ); return AgentSMS::Utils::extractResult( getAgentsmsPage( $gate, $params, $METHOD_GET ) ); } sub addService { my ( $gate, $form_href ) = validate_pos( @_, { type => SCALAR }, { type => HASHREF } ); my $params = q{path=/service_manager}; return AgentSMS::Utils::extractResult( getAgentsmsPage( $gate, $params, $METHOD_POST, $form_href ) ); } sub getSendingRulesPage { my ( $gate ) = validate_pos( @_, { type => SCALAR }, ); my $params = q{path=/sending_rules/all}; return AgentSMS::Utils::extractResult( getAgentsmsPage( $gate, $params, $METHOD_GET ) ); } 1;
maxim-komar/agentsms-utils
lib/AgentSMS/Page.pm
Perl
mit
3,342
:- module( graph_ext, [ arcs_to_vertices/2, % +Arcs, -Vertices edges_to_vertices/2 % +Edges, -Vertices ] ). /** <module> Generic support for graphs */ :- use_module(library(aggregate)). :- use_module(library(lists)). %! arcs_to_vertices(+Arcs:list(compound), -Vertices:ordset) is det. arcs_to_vertices(Arcs, Vertices) :- aggregate_all( set(Vertice), ( member(arc(X,_,Y), Arcs), member(Vertice, [X,Y]) ), Vertices ). %! edges_to_vertices(+Edges:list(compound), -Vertices:ordset) is det. edges_to_vertices(Edges, Vertices) :- aggregate_all( set(Vertice), ( member(edge(X,_,Y), Edges), member(Vertice, [X,Y]) ), Vertices ).
wouterbeek/Prolog_Library_Collection
prolog/graph_ext.pl
Perl
mit
713
#!/usr/bin/env perl # # file.pl - demostrate how iterator was used with match option # # Copyright (c) 2015, Oxnz # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use strict; use warnings; my $f; open($f, $0) or die("cannot open $0: $!"); while(<$f>) { print; } close($f);
oxnz/design-patterns
src/iterator/perl/file.pl
Perl
mit
1,532
% From E: % % ':-'(call_pel_directive(translate(unskipped,'/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.lps.pl'))). :- call_pel_directive(translate(unskipped, '/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.lps.pl')). :-include(library('ec_planner/ec_test_incl')). :-expects_dialect(lps). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Bomb.e',183). % From E: % % ':-'(call_pel_directive(translate(begining,'/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.lps.pl'))). :- call_pel_directive(translate(begining, '/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.lps.pl')). % Fri, 26 Mar 2021 01:05:56 GMT File: <stream>(0x555567dd7700)%; %; Copyright (c) 2005 IBM Corporation and others. %; All rights reserved. This program and the accompanying materials %; are made available under the terms of the Common Public License v1.0 %; which accompanies this distribution, and is available at %; http://www.eclipse.org/legal/cpl-v10.html %; %; Contributors: %; IBM - Initial implementation %; %; Book: book (a sort of device) %; % sort page: integer :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',14). % From E: % % subsort(page,integer). subsort(page, integer). %; agent opens book to page. % event BookOpenTo(agent,book,page) :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',16). % From E: % % event(bookOpenTo(agent,book,page)). events([bookOpenTo/3]). mpred_prop(bookOpenTo(agent, book, page), action). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',16). actions([bookOpenTo/3]). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',19). %; agent closes book. % event BookClose(agent,book) % From E: % % event(bookClose(agent,book)). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',19). events([bookClose/2]). mpred_prop(bookClose(agent, book), action). actions([bookClose/2]). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',22). %; book is open to page. % fluent BookIsOpenTo(book,page) % From E: % % fluent(bookIsOpenTo(book,page)). mpred_prop(bookIsOpenTo(book, page), fluent). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',22). fluents([bookIsOpenTo/2]). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',25). % fluent BookClosed(book) % From E: % % fluent(bookClosed(book)). mpred_prop(bookClosed(book), fluent). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',25). fluents([bookClosed/1]). % noninertial BookClosed % From E: % % ':-'(call_pel_directive(noninertial(bookClosed))). :- call_pel_directive(noninertial(bookClosed)). %; agent turns page of book to page. % event BookTurnPageTo(agent,book,page) :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',28). % From E: % % event(bookTurnPageTo(agent,book,page)). events([bookTurnPageTo/3]). mpred_prop(bookTurnPageTo(agent, book, page), action). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',28). actions([bookTurnPageTo/3]). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',31). % [book,page1,page2,time] % HoldsAt(BookIsOpenTo(book,page1),time) & % HoldsAt(BookIsOpenTo(book,page2),time) -> % page1=page2. % From E: % % '->'( % ','( % holds( % bookIsOpenTo(Book,Page1), % Time), % holds( % bookIsOpenTo(Book,Page2), % Time)), % Page1=Page2). ( equals(Page1, Page2) ; not bookIsOpenTo(Book, Page1)at Time ; not bookIsOpenTo(Book, Page2)at Time ). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',31). /* ( equals(Page1, Page2) ; at(not(bookIsOpenTo(Book, Page1)), Time) ; at(not(bookIsOpenTo(Book, Page2)), Time) ). */ % % =================================. % [book,time] % HoldsAt(BookClosed(book),time) <-> % ! {page} HoldsAt(BookIsOpenTo(book,page),time). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',37). % From E: % % <->( % holds( % bookClosed(Book), % Time), % not(thereExists(Page, % holds( % bookIsOpenTo(Book,Page), % Time)))). thereExists(Page, bookIsOpenTo(Book, Page)at Time)if not bookClosed(Book)at Time. /* if(thereExists(Page, at(bookIsOpenTo(Book,Page),Time)), at(not(bookClosed(Book)),Time)). */ % % =================================. ( bookClosed(Book)at Time ; thereExists(Page, bookIsOpenTo(Book, Page)at Time) ). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',37). /* ( at(bookClosed(Book), Time) ; thereExists(Page, at(bookIsOpenTo(Book, Page), Time)) ). */ % % =================================. %; A precondition axiom states that %; for an agent to open a book to a page, %; the agent must be awake, %; the book must be closed, and %; the agent must be holding the book. % [agent,book,page,time] % Happens(BookOpenTo(agent,book,page),time) -> % HoldsAt(Awake(agent),time) & % HoldsAt(BookClosed(book),time) & % HoldsAt(Holding(agent,book),time). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',45). % From E: % % '->'( % happens( % bookOpenTo(Agent,Book,Page), % Time), % ','( % holds( % awake(Agent), % Time), % ','( % holds( % bookClosed(Book), % Time), % holds( % holding(Agent,Book), % Time)))). ( awake(Agent)at Time, bookClosed(Book)at Time, holding(Agent, Book)at Time ; not happens(bookOpenTo(Agent, Book, Page), Time) ). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',45). /* ( at(awake(Agent), Time), at(bookClosed(Book), Time), at(holding(Agent, Book), Time) ; not(happens(bookOpenTo(Agent, Book, Page), Time)) ). */ % % =================================. %; An effect axiom states that %; if an agent opens a book to a page, %; the book will be open to the page: % [agent,book,page,time] % Initiates(BookOpenTo(agent,book,page),BookIsOpenTo(book,page),time). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',54). % From E: % % initiates_at( % bookOpenTo(Agent,Book,Page), % bookIsOpenTo(Book,Page), % Time). bookOpenTo(Agent, Book, Page)initiates bookIsOpenTo(Book, Page). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',54). /* initiated(happens(bookOpenTo(Agent,Book,Page), Time_from, Time_until), bookIsOpenTo(Book,Page), []). */ % % =================================. %; A precondition axiom states that %; for an agent to close a book, %; the agent must be awake, %; the book must not already be closed, and %; the agent must be holding the book. % [agent,book,time] % Happens(BookClose(agent,book),time) -> % HoldsAt(Awake(agent),time) & % !HoldsAt(BookClosed(book),time) & % HoldsAt(Holding(agent,book),time). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',62). % From E: % % '->'( % happens( % bookClose(Agent,Book), % Time), % ','( % holds( % awake(Agent), % Time), % ','( % holds( % not(bookClosed(Book)), % Time), % holds( % holding(Agent,Book), % Time)))). ( awake(Agent)at Time, not bookClosed(Book)at Time, holding(Agent, Book)at Time ; not happens(bookClose(Agent, Book), Time) ). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',62). /* ( at(awake(Agent), Time), at(not(bookClosed(Book)), Time), at(holding(Agent, Book), Time) ; not(happens(bookClose(Agent, Book), Time)) ). */ % % =================================. %; An effect axiom states that %; if an agent closes a book, %; the book will no longer be open: % [agent,book,page,time] % Terminates(BookClose(agent,book),BookIsOpenTo(book,page),time). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',71). % From E: % % terminates_at( % bookClose(Agent,Book), % bookIsOpenTo(Book,Page), % Time). bookClose(Agent, Book)terminates bookIsOpenTo(Book, Page). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',71). /* terminated(happens(bookClose(Agent,Book), Time_from, Time_until), bookIsOpenTo(Book,Page), []). */ % % =================================. % [agent,book,page,time] % Happens(BookTurnPageTo(agent,book,page),time) -> % HoldsAt(Awake(agent),time) & % ({page1} page1 != page & HoldsAt(BookIsOpenTo(book,page1),time)) & % HoldsAt(Holding(agent,book),time). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',75). % From E: % % '->'( % happens( % bookTurnPageTo(Agent,Book,Page), % Time), % ','( % holds( % awake(Agent), % Time), % ','( % thereExists(Page1, % ','( % Page1\=Page, % holds( % bookIsOpenTo(Book,Page1), % Time))), % holds( % holding(Agent,Book), % Time)))). ( awake(Agent)at Time, thereExists(Page1, ({dif(Page1, Page)}, bookIsOpenTo(Book, Page1)at Time)), holding(Agent, Book)at Time ; not happens(bookTurnPageTo(Agent, Book, Page), Time) ). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',75). /* ( at(awake(Agent), Time), thereExists(Page1, ({dif(Page1, Page)}, at(bookIsOpenTo(Book, Page1), Time))), at(holding(Agent, Book), Time) ; not(happens(bookTurnPageTo(Agent, Book, Page), Time)) ). */ % % =================================. % [agent,book,page,time] % Initiates(BookTurnPageTo(agent,book,page),BookIsOpenTo(book,page),time). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',81). % From E: % % initiates_at( % bookTurnPageTo(Agent,Book,Page), % bookIsOpenTo(Book,Page), % Time). bookTurnPageTo(Agent, Book, Page)initiates bookIsOpenTo(Book, Page). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',81). /* initiated(happens(bookTurnPageTo(Agent,Book,Page), Time_from, Time_until), bookIsOpenTo(Book,Page), []). */ % % =================================. :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',83). % [agent,book,page1,page2,time] % HoldsAt(BookIsOpenTo(book,page1),time) & % page1 != page2 -> % Terminates(BookTurnPageTo(agent,book,page2),BookIsOpenTo(book,page1),time). % From E: % % '->'( % ','( % holds( % bookIsOpenTo(Book,Page1), % Time), % Page1\=Page2), % terminates_at( % bookTurnPageTo(Agent,Book,Page2), % bookIsOpenTo(Book,Page1), % Time)). ( terminates(bookTurnPageTo(Agent, Book, Page2), bookIsOpenTo(Book, Page1)at Time) ; not bookIsOpenTo(Book, Page1)at Time ; not {dif(Page1, Page2)} ). :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',83). /* ( terminates(bookTurnPageTo(Agent, Book, Page2), at(bookIsOpenTo(Book, Page1), Time)) ; at(not(bookIsOpenTo(Book, Page1)), Time) ; not({dif(Page1, Page2)}) ). */ % % =================================. %; End of file. :-was_s_l('/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.e',87). % From E: % % ':-'(call_pel_directive(translate(ending,'/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.lps.pl'))). :- call_pel_directive(translate(ending, '/mnt/sdc1/logicmoo_workspace.1/packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.lps.pl')).
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_ec/ext/ec_sources/ecnet/Book.lps.pl
Perl
mit
12,824
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V9::Enums::HotelDateSelectionTypeEnum; use strict; use warnings; use Const::Exporter enums => [ UNSPECIFIED => "UNSPECIFIED", UNKNOWN => "UNKNOWN", DEFAULT_SELECTION => "DEFAULT_SELECTION", USER_SELECTED => "USER_SELECTED" ]; 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Enums/HotelDateSelectionTypeEnum.pm
Perl
apache-2.0
868
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2017] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. =pod =head1 NAME Bio::EnsEMBL::Analysis::RunnableDB::BWA =head1 SYNOPSIS my $runnableDB = Bio::EnsEMBL::Analysis::RunnableDB::BWA->new( ); $runnableDB->fetch_input(); $runnableDB->run(); =head1 DESCRIPTION This module uses BWA to align fastq to a genomic sequence =head1 CONTACT Post general queries to B<http://lists.ensembl.org/mailman/listinfo/dev> =head1 APPENDIX =cut package Bio::EnsEMBL::Analysis::RunnableDB::BWA2BAM; use warnings ; use strict; use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Analysis::Runnable::BWA2BAM; use Bio::EnsEMBL::Analysis::RunnableDB::BWA; use vars qw(@ISA); @ISA = ("Bio::EnsEMBL::Analysis::RunnableDB::BWA"); sub new { my ( $class, @args ) = @_; my $self = $class->SUPER::new(@args); return $self; } sub fetch_input { my ($self) = @_; my %parameters = %{$self->parameters_hash}; my $program = $self->analysis->program_file; $self->throw("BWA program not defined in analysis \n") if not defined $program; my $filename = $self->INDIR ."/" .$self->input_id; my $fastqpair; my $method; if ( $self->PAIRED ) { $method = " sampe " . $self->SAMPE_OPTIONS; # need to seaprate the 2 file names in the input id my @files = split(/:/,$self->input_id); $self->throw("Cannot parse 2 file names out of $self->input_id should be separated by :\n") unless scalar(@files) == 2; $filename = $self->INDIR ."/" .$files[0]; $fastqpair = $self->INDIR ."/" .$files[1]; } else { $method = " samse " . $self->SAMSE_OPTIONS; } $self->throw("Fastq file $filename not found\n") unless ( -e $filename ); if ( $self->PAIRED) { $self->throw("Fastq pair file $fastqpair not found\n") unless ( -e $fastqpair ); } my $runnable = Bio::EnsEMBL::Analysis::Runnable::BWA2BAM->new ( -analysis => $self->analysis, -program => $program, -fastq => $filename, -fastqpair => $fastqpair, -options => $self->OPTIONS, -outdir => $self->OUTDIR, -genome => $self->GENOMEFILE, -method => $method, -samtools => $self->SAMTOOLS_PATH, -header => $self->HEADER, -min_mapped => $self->MIN_MAPPED, -min_paired => $self->MIN_PAIRED, %parameters, ); $self->runnable($runnable); }
james-monkeyshines/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/RunnableDB/BWA2BAM.pm
Perl
apache-2.0
3,022
# # 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 apps::protocols::smtp::plugin; use strict; use warnings; use base qw(centreon::plugins::script_simple); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; %{$self->{modes}} = ( 'login' => 'apps::protocols::smtp::mode::login', 'message' => 'apps::protocols::smtp::mode::message', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check a SMTP server. =cut
centreon/centreon-plugins
apps/protocols/smtp/plugin.pm
Perl
apache-2.0
1,283
# # 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 apps::centreon::local::mode::metaservice; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::common::db; use centreon::common::logger; use vars qw($centreon_config); my %DSTYPE = ( '0' => 'g', '1' => 'c', '2' => 'd', '3' => 'a'); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { 'centreon-config:s' => { name => 'centreon_config', default => '/etc/centreon/centreon-config.pm' }, 'meta-id:s' => { name => 'meta_id' } }); $self->{metric_selected} = {}; return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (!defined($self->{option_results}->{meta_id}) || $self->{option_results}->{meta_id} !~ /^[0-9]+$/) { $self->{output}->add_option_msg(short_msg => "Need to specify meta-id (numeric value) option."); $self->{output}->option_exit(); } require $self->{option_results}->{centreon_config}; } sub execute_query { my ($self, $db, $query) = @_; my ($status, $stmt) = $db->query($query); if ($status == -1) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => 'SQL Query error: ' . $query ); $self->{output}->display(); $self->{output}->exit(); } return $stmt; } sub select_by_regexp { my ($self, %options) = @_; my $count = 0; my $stmt = $self->execute_query( $self->{centreon_db_centstorage}, "SELECT metrics.metric_id, metrics.metric_name, metrics.current_value FROM index_data, metrics WHERE index_data.service_description LIKE " . $self->{centreon_db_centstorage}->quote($options{regexp_str}) . " AND index_data.id = metrics.index_id" ); while ((my $row = $stmt->fetchrow_hashref())) { if ($options{metric_select} eq $row->{metric_name}) { $self->{metric_selected}->{$row->{metric_id}} = $row->{current_value}; $count++; } } if ($count == 0) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => 'Cannot find a metric.' ); $self->{output}->display(); $self->{output}->exit(); } } sub select_by_list { my ($self, %options) = @_; my $count = 0; my $metric_ids = {}; my $stmt = $self->execute_query($self->{centreon_db_centreon}, "SELECT metric_id FROM `meta_service_relation` WHERE meta_id = '". $self->{option_results}->{meta_id} . "' AND activate = '1'"); while ((my $row = $stmt->fetchrow_hashref())) { $metric_ids->{$row->{metric_id}} = 1; $count++; } if ($count == 0) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => 'Cannot find a metric_id in table meta_service_relation.' ); $self->{output}->display(); $self->{output}->exit(); } $count = 0; $stmt = $self->execute_query( $self->{centreon_db_centstorage}, "SELECT metric_id, current_value FROM metrics WHERE metric_id IN (" . join(',', keys %{$metric_ids}) . ")" ); while ((my $row = $stmt->fetchrow_hashref())) { $self->{metric_selected}->{$row->{metric_id}} = $row->{current_value}; $count++; } if ($count == 0) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => 'Cannot find a metric_id in metrics table.' ); $self->{output}->display(); $self->{output}->exit(); } } sub calculate { my ($self, %options) = @_; my $result = 0; if ($options{calculation} eq 'MIN') { my @values = sort { $a <=> $b } values(%{$self->{metric_selected}}); if (defined($values[0])) { $result = $values[0]; } } elsif ($options{calculation} eq 'MAX') { my @values = sort { $a <=> $b } values(%{$self->{metric_selected}}); if (defined($values[0])) { $result = $values[scalar(@values) - 1]; } } elsif ($options{calculation} eq 'SOM') { foreach my $value (values %{$self->{metric_selected}}) { $result += $value; } } elsif ($options{calculation} eq 'AVE') { my @values = values %{$self->{metric_selected}}; foreach my $value (@values) { $result += $value; } my $total = scalar(@values); if ($total == 0) { $total = 1; } $result = $result / $total; } return $result; } sub run { my ($self, %options) = @_; $self->{logger} = centreon::common::logger->new(); $self->{logger}->severity('none'); $self->{centreon_db_centreon} = centreon::common::db->new( db => $centreon_config->{centreon_db}, host => $centreon_config->{db_host}, port => $centreon_config->{db_port}, user => $centreon_config->{db_user}, password => $centreon_config->{db_passwd}, force => 0, logger => $self->{logger} ); my $status = $self->{centreon_db_centreon}->connect(); if ($status == -1) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => 'Cannot connect to Centreon Database.' ); $self->{output}->display(); $self->{output}->exit(); } $self->{centreon_db_centstorage} = centreon::common::db->new( db => $centreon_config->{centstorage_db}, host => $centreon_config->{db_host}, port => $centreon_config->{db_port}, user => $centreon_config->{db_user}, password => $centreon_config->{db_passwd}, force => 0, logger => $self->{logger} ); $status = $self->{centreon_db_centstorage}->connect(); if ($status == -1) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => 'Cannot connect to Centstorage Database.' ); $self->{output}->display(); $self->{output}->exit(); } my $stmt = $self->execute_query($self->{centreon_db_centreon}, "SELECT meta_display, calcul_type, regexp_str, warning, critical, metric, meta_select_mode, data_source_type FROM `meta_service` WHERE meta_id = '". $self->{option_results}->{meta_id} . "' LIMIT 1"); my $row = $stmt->fetchrow_hashref(); if (!defined($row)) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => 'Cannot get meta service informations.' ); $self->{output}->display(); $self->{output}->exit(); } # Set threshold if (($self->{perfdata}->threshold_validate(label => 'warning', value => $row->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $row->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $row->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $row->{critical} . "'."); $self->{output}->option_exit(); } if ($row->{meta_select_mode} == 2) { $self->select_by_regexp(regexp_str => $row->{regexp_str}, metric_select => $row->{metric}); } else { $self->select_by_list(); } my $result = $self->calculate(calculation => $row->{calcul_type}); my $exit = $self->{perfdata}->threshold_check(value => $result, threshold => [ { label => 'critical', exit_litteral => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my $display = defined($row->{meta_display}) ? $row->{meta_display} : $row->{calcul_type} . ' - value : %f'; $self->{output}->output_add( severity => $exit, short_msg => sprintf($display, $result) ); $self->{output}->perfdata_add( label => sprintf( '%s[%s]', (defined($DSTYPE{$row->{data_source_type}}) ? $DSTYPE{$row->{data_source_type}} : 'g'), defined($row->{metric}) && $row->{metric} ne '' ? $row->{metric} : 'value', ), value => sprintf('%02.2f', $result), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical') ); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Do Centreon meta-service checks. =over 8 =item B<--centreon-config> Centreon Database Config File (Default: '/etc/centreon/centreon-config.pm'). =item B<--meta-id> Meta-id to check (required). =back =cut
Tpo76/centreon-plugins
apps/centreon/local/mode/metaservice.pm
Perl
apache-2.0
9,434
use strict; use warnings; use FileHandle; my $dumps = {}; my $fh = FileHandle->new("/hps/nobackup/production/ensembl/anja/release_90/sheep/split_dumps/24_1000.txt", 'r'); while (<$fh>) { chomp; $dumps->{$_} = 1; } $fh->close; $fh = FileHandle->new("/hps/nobackup/production/ensembl/anja/release_90/sheep/dumps/24.txt", 'r'); while (<$fh>) { chomp; if (!$dumps->{$_}) { print STDERR $_, "\n"; } } $fh->close;
at7/work
api/compare_files.pl
Perl
apache-2.0
427
package EnsEMBL::Web::Document::FileCache; use strict; use warnings; use Fcntl ':flock'; my $debug = 0; sub read_html { my $self = shift; my $refresh_period = $_[0] || 86400; my $classname= (split/::/, ref($self))[-1]; my $content; my $time = time(); my $filename = "$SiteDefs::ENSEMBL_TMP_DIR/$classname.html"; $debug && warn ">>>> Refresh period is $refresh_period"; $debug && warn ">>>> File name is $filename"; if (-f $filename && -e $filename) { if (open my $fh, $filename) { flock($fh, LOCK_EX); local($/) = undef; my $last_mod_time = (stat ($fh))[9]; $content = <$fh>; close $fh; if ($time - $last_mod_time > $refresh_period) { $self->write_html($filename); } $debug && warn ">>>> Content length is " . length($content); return $content; } else { return "<p>Server side error loading this page<p>"; } } else { $self->write_html($filename); } } sub write_html { my $self = shift; my $filename = $_[0]; $debug && warn ">>>> Writing file $filename"; open my $fh, '>', $filename or die "Can't open $filename $!"; my $result = flock($fh, LOCK_EX); my $html = $self->make_html(); print $fh $html; close $fh; } 1;
EnsemblGenomes/eg-web-parasite
modules/EnsEMBL/Web/Document/FileCache.pm
Perl
apache-2.0
1,242
# # 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 network::fortinet::fortiauthenticator::snmp::mode::memory; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'memory', type => 0, skipped_code => { -10 => 1 } } ]; $self->{maps_counters}->{memory} = [ { label => 'usage-prct', nlabel => 'memory.usage.percentage', set => { key_values => [ { name => 'prct_used' } ], output_template => 'Memory used: %.2f %%', perfdatas => [ { template => '%.2f', min => 0, max => 100, unit => '%' } ] } } ]; } 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 => { }); return $self; } sub manage_selection { my ($self, %options) = @_; my $oid_facSysMemUsage = '.1.3.6.1.4.1.12356.113.1.5.0'; my $result = $options{snmp}->get_leef(oids => [$oid_facSysMemUsage], nothing_quit => 1); $self->{memory} = { prct_used => $result->{$oid_facSysMemUsage} } } 1; __END__ =head1 MODE Check memory usage. =over 8 =item B<--warning-*> B<--critical-*> Thresholds. Can be: 'usage-prct' (%). =back =cut
centreon/centreon-plugins
network/fortinet/fortiauthenticator/snmp/mode/memory.pm
Perl
apache-2.0
2,158
# 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::ConversionUploadService::ExternalAttributionData; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { externalAttributionCredit => $args->{externalAttributionCredit}, externalAttributionModel => $args->{externalAttributionModel}}; # 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/V8/Services/ConversionUploadService/ExternalAttributionData.pm
Perl
apache-2.0
1,161
# # 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 storage::emc::symmetrix::vmax::local::plugin; use strict; use warnings; use base qw(centreon::plugins::script_simple); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; %{$self->{modes}} = ( 'hardware' => 'storage::emc::symmetrix::vmax::local::mode::hardware', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check vmax storage. The plugin needs to be installed on Windows Management. =cut
centreon/centreon-plugins
storage/emc/symmetrix/vmax/local/plugin.pm
Perl
apache-2.0
1,311
# # 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 storage::hp::3par::ssh::mode::diskusage; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold catalog_status_calc); sub custom_status_output { my ($self, %options) = @_; my $msg = 'status : ' . $self->{result_values}->{status}; return $msg; } 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("Usage 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 set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'disk', type => 1, cb_prefix_output => 'prefix_disk_output', message_multiple => 'All disks are ok', sort_method => 'num' }, ]; $self->{maps_counters}->{disk} = [ { label => 'status', threshold => 0, set => { key_values => [ { name => 'status' }, { name => 'display' } ], closure_custom_calc => \&catalog_status_calc, closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => \&catalog_status_threshold, } }, { label => 'usage', nlabel => 'disk.space.usage.bytes', set => { key_values => [ { name => 'used' }, { name => 'free' }, { name => 'prct_used' }, { name => 'prct_free' }, { name => 'total' }, { name => 'display' }, ], closure_custom_output => $self->can('custom_usage_output'), perfdatas => [ { label => 'used', value => 'used', template => '%d', min => 0, max => 'total', unit => 'B', cast_int => 1, label_extra_instance => 1, instance_use => 'display' }, ], } }, { label => 'usage-free', display_ok => 0, nlabel => 'disk.space.free.bytes', set => { key_values => [ { name => 'free' }, { name => 'used' }, { name => 'prct_used' }, { name => 'prct_free' }, { name => 'total' }, { name => 'display' }, ], closure_custom_output => $self->can('custom_usage_output'), perfdatas => [ { label => 'free', value => 'free', template => '%d', min => 0, max => 'total', unit => 'B', cast_int => 1, label_extra_instance => 1, instance_use => 'display' }, ], } }, { label => 'usage-prct', display_ok => 0, nlabel => 'disk.space.usage.percentage', set => { key_values => [ { name => 'prct_used' }, { name => 'display' } ], output_template => 'Used : %.2f %%', perfdatas => [ { label => 'used_prct', value => 'prct_used', template => '%.2f', min => 0, max => 100, unit => '%', label_extra_instance => 1, instance_use => 'display' }, ], } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { "filter-name:s" => { name => 'filter_name' }, "warning-status:s" => { name => 'warning_status', default => '' }, "critical-status:s" => { name => 'critical_status', default => '%{status} !~ /normal/i' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->change_macros(macros => ['warning_status', 'critical_status']); } sub prefix_disk_output { my ($self, %options) = @_; return "Disk '" . $options{instance_value}->{display} . "' "; } sub manage_selection { my ($self, %options) = @_; my ($result, $exit) = $options{custom}->execute_command(commands => ['showpd -showcols Id,State,Type,Size_MB,Free_MB']); #Id State Type Size_MB Free_MB # 0 normal FC 838656 133120 # 1 normal FC 838656 101376 # 2 normal FC 838656 133120 $self->{disk} = {}; my @lines = split /\n/, $result; foreach (@lines) { next if (!/^\s*(\d+)\s+(\S+)\s+\S+\s+(\d+)\s+(\d+)/); my ($disk_id, $status, $total, $free) = ($1, $2, $3 * 1024 * 1024, $4 * 1024 * 1024); if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $disk_id !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping disk '" . $disk_id . "': no matching filter.", debug => 1); next; } $self->{disk}->{$disk_id} = { display => $disk_id, status => $status, total => $total, used => $total - $free, free => $free, prct_used => ($total - $free) * 100 / $total, prct_free => 100 - (($total - $free) * 100 / $total), }; } if (scalar(keys %{$self->{disk}}) <= 0) { $self->{output}->add_option_msg(short_msg => "No disk found."); $self->{output}->option_exit(); } } 1; __END__ =head1 MODE Check disk usages. =over 8 =item B<--filter-counters> Only display some counters (regexp can be used). Example: --filter-counters='^status$' =item B<--filter-name> Filter disk name (can be a regexp). =item B<--warning-status> Set warning threshold for status (Default: ''). Can used special variables like: %{status}, %{display} =item B<--critical-status> Set critical threshold for status (Default: '%{status} !~ /normal/i'). Can used special variables like: %{status}, %{display} =item B<--warning-*> B<--critical-*> Threshold warning. Can be: 'usage' (B), 'usage-free' (B), 'usage-prct' (%). =back =cut
centreon/centreon-plugins
storage/hp/3par/ssh/mode/diskusage.pm
Perl
apache-2.0
7,296
=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 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =head1 NAME Bio::EnsEMBL::Compara::RunnableDB::BaseAge::BaseAge =cut =head1 SYNOPSIS =cut =head1 DESCRIPTION =cut =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ =cut package Bio::EnsEMBL::Compara::RunnableDB::BaseAge::BigBed; use strict; use warnings; use Bio::EnsEMBL::Utils::Exception qw(throw); use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable'); =head2 fetch_input Title : fetch_input Usage : $self->fetch_input Function: Returns : none Args : none =cut sub fetch_input { my( $self) = @_; #concatenate all the sorted bed_files together my $concat_bed_file = $self->worker_temp_directory . "/concat_ages.bed"; my $bed_files = $self->param('bed_files'); my $file_list = join " ", (map {$bed_files->{$_}} sort {$a cmp $b} keys %$bed_files); my $cat_cmd = "cat $file_list > $concat_bed_file"; $self->run_command($cat_cmd, { die_on_failure => 1 }); $self->param('concat_file', $concat_bed_file); } sub write_output { my( $self) = @_; my $concat_file = $self->param('concat_file'); #First check concat_file is not empty if (-s $concat_file) { my $cmd = [$self->param('program'), '-as='.$self->param('baseage_autosql'), '-type=bed3+3', $concat_file, $self->param('chr_sizes'), $self->param('big_bed_file')]; $self->run_command($cmd, { die_on_failure => 1 }); } else { die "$concat_file empty so cannot produce Big Bed file"; } } 1;
Ensembl/ensembl-compara
modules/Bio/EnsEMBL/Compara/RunnableDB/BaseAge/BigBed.pm
Perl
apache-2.0
2,431
=encoding utf-8 =head1 Name lua-resty-core - New FFI-based Lua API for the ngx_lua module =head1 Status This library is production ready and under active development. =head1 Synopsis # nginx.conf http { # you do NOT need to configure the following line when you # are using the OpenResty bundle 1.4.3.9+. lua_package_path "/path/to/lua-resty-core/lib/?.lua;;"; init_by_lua_block { require "resty.core" collectgarbage("collect") -- just to collect any garbage } ... } =head1 Description This pure Lua library reimplements part of the L<ngx_lua|https://github.com/openresty/lua-nginx-module#readme> module's L<Nginx API for Lua|https://github.com/openresty/lua-nginx-module#nginx-api-for-lua> with LuaJIT FFI and installs the new FFI-based Lua API into the ngx.I< and ndk.> namespaces used by the ngx_lua module. In addition, this Lua library implements any significant new Lua APIs of the L<ngx_lua|https://github.com/openresty/lua-nginx-module#readme> module as proper Lua modules, like L<ngx.semaphore> and L<ngx.balancer>. The FFI-based Lua API can work with LuaJIT's JIT compiler. ngx_lua's default API is based on the standard Lua C API, which will never be JIT compiled and the user Lua code is always interpreted (slowly). This library is shipped with the OpenResty bundle by default. So you do not really need to worry about the dependencies and requirements. =head1 Prerequisites =over =item * LuaJIT 2.1 (for now, it is the v2.1 git branch in the official luajit-2.0 git repository: http://luajit.org/download.html ) =item * L<ngx_lua|https://github.com/openresty/lua-nginx-module> v0.10.7 or later. =item * L<lua-resty-lrucache|https://github.com/openresty/lua-resty-lrucache> =back =head1 API Implemented =head2 resty.core.hash =over =item * L<ngx.md5|https://github.com/openresty/lua-nginx-module#ngxmd5> =item * L<ngx.md5_bin|https://github.com/openresty/lua-nginx-module#ngxmd5_bin> =item * L<ngx.sha1_bin|https://github.com/openresty/lua-nginx-module#ngxsha1_bin> =back =head2 resty.core.base64 =over =item * L<ngx.encode_base64|https://github.com/openresty/lua-nginx-module#ngxencode_base64> =item * L<ngx.decode_base64|https://github.com/openresty/lua-nginx-module#ngxdecode_base64> =back =head2 resty.core.uri =over =item * L<ngx.escape_uri|https://github.com/openresty/lua-nginx-module#ngxescape_uri> =item * L<ngx.unescape_uri|https://github.com/openresty/lua-nginx-module#ngxunescape_uri> =back =head2 resty.core.regex =over =item * L<ngx.re.match|https://github.com/openresty/lua-nginx-module#ngxrematch> =item * L<ngx.re.find|https://github.com/openresty/lua-nginx-module#ngxrefind> =item * L<ngx.re.sub|https://github.com/openresty/lua-nginx-module#ngxresub> =item * L<ngx.re.gsub|https://github.com/openresty/lua-nginx-module#ngxregsub> =back =head2 resty.core.exit =over =item * L<ngx.exit|https://github.com/openresty/lua-nginx-module#ngxexit> =back =head2 resty.core.shdict =over =item * L<ngx.shared.DICT.get|https://github.com/openresty/lua-nginx-module#ngxshareddictget> =item * L<ngx.shared.DICT.get_stale|https://github.com/openresty/lua-nginx-module#ngxshareddictget_stale> =item * L<ngx.shared.DICT.incr|https://github.com/openresty/lua-nginx-module#ngxshareddictincr> =item * L<ngx.shared.DICT.set|https://github.com/openresty/lua-nginx-module#ngxshareddictset> =item * L<ngx.shared.DICT.safe_set|https://github.com/openresty/lua-nginx-module#ngxshareddictsafe_set> =item * L<ngx.shared.DICT.add|https://github.com/openresty/lua-nginx-module#ngxshareddictadd> =item * L<ngx.shared.DICT.safe_add|https://github.com/openresty/lua-nginx-module#ngxshareddictsafe_add> =item * L<ngx.shared.DICT.replace|https://github.com/openresty/lua-nginx-module#ngxshareddictreplace> =item * L<ngx.shared.DICT.delete|https://github.com/openresty/lua-nginx-module#ngxshareddictdelete> =item * L<ngx.shared.DICT.flush_all|https://github.com/openresty/lua-nginx-module#ngxshareddictflush_all> =back =head2 resty.core.var =over =item * L<ngx.var.VARIABLE|https://github.com/openresty/lua-nginx-module#ngxvarvariable> =back =head2 resty.core.ctx =over =item * L<ngx.ctx|https://github.com/openresty/lua-nginx-module#ngxctx> =back =head2 resty.core.request =over =item * L<ngx.req.get_headers|https://github.com/openresty/lua-nginx-module#ngxreqget_headers> =item * L<ngx.req.get_uri_args|https://github.com/openresty/lua-nginx-module#ngxreqget_uri_args> =item * L<ngx.req.start_time|https://github.com/openresty/lua-nginx-module#ngxreqstart_time> =item * L<ngx.req.get_method|https://github.com/openresty/lua-nginx-module#ngxreqget_method> =item * L<ngx.req.set_method|https://github.com/openresty/lua-nginx-module#ngxreqset_method> =item * L<ngx.req.set_header|https://github.com/openresty/lua-nginx-module#ngxreqset_header> (partial: table-typed header values not supported yet) =item * L<ngx.req.clear_header|https://github.com/openresty/lua-nginx-module#ngxreqclear_header> =back =head2 resty.core.response =over =item * L<ngx.header.HEADER|https://github.com/openresty/lua-nginx-module#ngxheaderheader> =back =head2 resty.core.misc =over =item * L<ngx.status|https://github.com/openresty/lua-nginx-module#ngxstatus> =item * L<ngx.is_subrequest|https://github.com/openresty/lua-nginx-module#ngxis_subrequest> =item * L<ngx.headers_sent|https://github.com/openresty/lua-nginx-module#ngxheaders_sent> =back =head2 resty.core.time =over =item * L<ngx.time|https://github.com/openresty/lua-nginx-module#ngxtime> =item * L<ngx.now|https://github.com/openresty/lua-nginx-module#ngxnow> =back =head2 resty.core.worker =over =item * L<ngx.worker.exiting|https://github.com/openresty/lua-nginx-module#ngxworkerexiting> =item * L<ngx.worker.pid|https://github.com/openresty/lua-nginx-module#ngxworkerpid> =item * L<ngx.worker.id|https://github.com/openresty/lua-nginx-module#ngxworkerid> =item * L<ngx.worker.count|https://github.com/openresty/lua-nginx-module#ngxworkercount> =back =head2 ngx.semaphore This Lua module implements a semaphore API for efficient "light thread" synchronization, which can work across different requests (but not across nginx worker processes). See the L<documentation|./lib/ngx/semaphore.md> for this Lua module for more details. =head2 ngx.balancer This Lua module implements for defining dynamic upstream balancers in Lua. See the L<documentation|./lib/ngx/balancer.md> for this Lua module for more details. =head2 ngx.ssl This Lua module provides a Lua API for controlling SSL certificates, private keys, SSL protocol versions, and etc in NGINX downstream SSL handshakes. See the L<documentation|./lib/ngx/ssl.md> for this Lua module for more details. =head2 ngx.ssl.session This Lua module provides a Lua API for manipulating SSL session data and IDs for NGINX downstream SSL connections. See the L<documentation|./lib/ngx/ssl/session.md> for this Lua module for more details. =head2 ngx.re This Lua module provides a Lua API which implements convenience utilities for the C<ngx.re> API. See the L<documentation|./lib/ngx/re.md> for this Lua module for more details. =head1 Caveat If the user Lua code is not JIT compiled, then use of this library may lead to performance drop in interpreted mode. You will only observe speedup when you get a good part of your user Lua code JIT compiled. =head1 TODO =over =item * Re-implement C<ngx_lua>'s cosocket API with FFI. =item * Re-implement C<ngx_lua>'s C<ngx.get_phase> API function with FFI. =item * Re-implement C<ngx_lua>'s C<ngx.eof> and C<ngx.flush> API functions with FFI. =back =head1 Author Yichun "agentzh" Zhang (章亦春) E<lt>agentzh@gmail.comE<gt>, CloudFlare Inc. =head1 Copyright and License This module is licensed under the BSD license. Copyright (C) 2013-2016, by Yichun "agentzh" Zhang, CloudFlare Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: =over =item * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. =back =over =item * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. =back THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =head1 See Also =over =item * the ngx_lua module: https://github.com/openresty/lua-nginx-module#readme =item * LuaJIT FFI: http://luajit.org/ext_ffi.html =back
LomoX-Offical/nginx-openresty-windows
src/pod/lua-resty-core-0.1.9/lua-resty-core-0.1.9.pod
Perl
bsd-2-clause
9,649
#!/usr/bin/perl -w # # MD5 optimized for AMD64. # # Author: Marc Bevand <bevand_m (at) epita.fr> # Licence: I hereby disclaim the copyright on this code and place it # in the public domain. # use strict; my $code; # round1_step() does: # dst = x + ((dst + F(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = z' (copy of z for the next step) # Each round1_step() takes about 5.3 clocks (9 instructions, 1.7 IPC) sub round1_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 0*4(%rsi), %r10d /* (NEXT STEP) X[0] */\n" if ($pos == -1); $code .= " mov %edx, %r11d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= <<EOF; xor $y, %r11d /* y ^ ... */ lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ and $x, %r11d /* x & ... */ xor $z, %r11d /* z ^ ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ add %r11d, $dst /* dst += ... */ rol \$$s, $dst /* dst <<< s */ mov $y, %r11d /* (NEXT STEP) z' = $y */ add $x, $dst /* dst += x */ EOF } # round2_step() does: # dst = x + ((dst + G(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = z' (copy of z for the next step) # %r12d = z' (copy of z for the next step) # Each round2_step() takes about 5.4 clocks (11 instructions, 2.0 IPC) sub round2_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 1*4(%rsi), %r10d /* (NEXT STEP) X[1] */\n" if ($pos == -1); $code .= " mov %edx, %r11d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= " mov %edx, %r12d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= <<EOF; not %r11d /* not z */ lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ and $x, %r12d /* x & z */ and $y, %r11d /* y & (not z) */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ or %r11d, %r12d /* (y & (not z)) | (x & z) */ mov $y, %r11d /* (NEXT STEP) z' = $y */ add %r12d, $dst /* dst += ... */ mov $y, %r12d /* (NEXT STEP) z' = $y */ rol \$$s, $dst /* dst <<< s */ add $x, $dst /* dst += x */ EOF } # round3_step() does: # dst = x + ((dst + H(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = y' (copy of y for the next step) # Each round3_step() takes about 4.2 clocks (8 instructions, 1.9 IPC) sub round3_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 5*4(%rsi), %r10d /* (NEXT STEP) X[5] */\n" if ($pos == -1); $code .= " mov %ecx, %r11d /* (NEXT STEP) y' = %ecx */\n" if ($pos == -1); $code .= <<EOF; lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ xor $z, %r11d /* z ^ ... */ xor $x, %r11d /* x ^ ... */ add %r11d, $dst /* dst += ... */ rol \$$s, $dst /* dst <<< s */ mov $x, %r11d /* (NEXT STEP) y' = $x */ add $x, $dst /* dst += x */ EOF } # round4_step() does: # dst = x + ((dst + I(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = not z' (copy of not z for the next step) # Each round4_step() takes about 5.2 clocks (9 instructions, 1.7 IPC) sub round4_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 0*4(%rsi), %r10d /* (NEXT STEP) X[0] */\n" if ($pos == -1); $code .= " mov \$0xffffffff, %r11d\n" if ($pos == -1); $code .= " xor %edx, %r11d /* (NEXT STEP) not z' = not %edx*/\n" if ($pos == -1); $code .= <<EOF; lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ or $x, %r11d /* x | ... */ xor $y, %r11d /* y ^ ... */ add %r11d, $dst /* dst += ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ mov \$0xffffffff, %r11d rol \$$s, $dst /* dst <<< s */ xor $y, %r11d /* (NEXT STEP) not z' = not $y */ add $x, $dst /* dst += x */ EOF } my $flavour = shift; my $output = shift; if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } my $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); $0 =~ m/(.*[\/\\])[^\/\\]+$/; my $dir=$1; my $xlate; ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or die "can't locate x86_64-xlate.pl"; no warnings qw(uninitialized); open OUT,"| \"$^X\" $xlate $flavour $output"; *STDOUT=*OUT; $code .= <<EOF; .text .align 16 .globl md5_block_asm_data_order .type md5_block_asm_data_order,\@function,3 md5_block_asm_data_order: push %rbp push %rbx push %r12 push %r14 push %r15 .Lprologue: # rdi = arg #1 (ctx, MD5_CTX pointer) # rsi = arg #2 (ptr, data pointer) # rdx = arg #3 (nbr, number of 16-word blocks to process) mov %rdi, %rbp # rbp = ctx shl \$6, %rdx # rdx = nbr in bytes lea (%rsi,%rdx), %rdi # rdi = end mov 0*4(%rbp), %eax # eax = ctx->A mov 1*4(%rbp), %ebx # ebx = ctx->B mov 2*4(%rbp), %ecx # ecx = ctx->C mov 3*4(%rbp), %edx # edx = ctx->D # end is 'rdi' # ptr is 'rsi' # A is 'eax' # B is 'ebx' # C is 'ecx' # D is 'edx' cmp %rdi, %rsi # cmp end with ptr je .Lend # jmp if ptr == end # BEGIN of loop over 16-word blocks .Lloop: # save old values of A, B, C, D mov %eax, %r8d mov %ebx, %r9d mov %ecx, %r14d mov %edx, %r15d EOF round1_step(-1,'%eax','%ebx','%ecx','%edx', '1','0xd76aa478', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx', '2','0xe8c7b756','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx', '3','0x242070db','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax', '4','0xc1bdceee','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx', '5','0xf57c0faf', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx', '6','0x4787c62a','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx', '7','0xa8304613','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax', '8','0xfd469501','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx', '9','0x698098d8', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx','10','0x8b44f7af','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx','11','0xffff5bb1','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax','12','0x895cd7be','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx','13','0x6b901122', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx','14','0xfd987193','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx','15','0xa679438e','17'); round1_step( 1,'%ebx','%ecx','%edx','%eax', '0','0x49b40821','22'); round2_step(-1,'%eax','%ebx','%ecx','%edx', '6','0xf61e2562', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx','11','0xc040b340', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '0','0x265e5a51','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax', '5','0xe9b6c7aa','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx','10','0xd62f105d', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx','15', '0x2441453', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '4','0xd8a1e681','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax', '9','0xe7d3fbc8','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx','14','0x21e1cde6', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx', '3','0xc33707d6', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '8','0xf4d50d87','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax','13','0x455a14ed','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx', '2','0xa9e3e905', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx', '7','0xfcefa3f8', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx','12','0x676f02d9','14'); round2_step( 1,'%ebx','%ecx','%edx','%eax', '0','0x8d2a4c8a','20'); round3_step(-1,'%eax','%ebx','%ecx','%edx', '8','0xfffa3942', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx','11','0x8771f681','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx','14','0x6d9d6122','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax', '1','0xfde5380c','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx', '4','0xa4beea44', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx', '7','0x4bdecfa9','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx','10','0xf6bb4b60','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax','13','0xbebfbc70','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx', '0','0x289b7ec6', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx', '3','0xeaa127fa','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx', '6','0xd4ef3085','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax', '9', '0x4881d05','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx','12','0xd9d4d039', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx','15','0xe6db99e5','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx', '2','0x1fa27cf8','16'); round3_step( 1,'%ebx','%ecx','%edx','%eax', '0','0xc4ac5665','23'); round4_step(-1,'%eax','%ebx','%ecx','%edx', '7','0xf4292244', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx','14','0x432aff97','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '5','0xab9423a7','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax','12','0xfc93a039','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx', '3','0x655b59c3', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx','10','0x8f0ccc92','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '1','0xffeff47d','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax', '8','0x85845dd1','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx','15','0x6fa87e4f', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx', '6','0xfe2ce6e0','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx','13','0xa3014314','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax', '4','0x4e0811a1','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx','11','0xf7537e82', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx', '2','0xbd3af235','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '9','0x2ad7d2bb','15'); round4_step( 1,'%ebx','%ecx','%edx','%eax', '0','0xeb86d391','21'); $code .= <<EOF; # add old values of A, B, C, D add %r8d, %eax add %r9d, %ebx add %r14d, %ecx add %r15d, %edx # loop control add \$64, %rsi # ptr += 64 cmp %rdi, %rsi # cmp end with ptr jb .Lloop # jmp if ptr < end # END of loop over 16-word blocks .Lend: mov %eax, 0*4(%rbp) # ctx->A = A mov %ebx, 1*4(%rbp) # ctx->B = B mov %ecx, 2*4(%rbp) # ctx->C = C mov %edx, 3*4(%rbp) # ctx->D = D mov (%rsp),%r15 mov 8(%rsp),%r14 mov 16(%rsp),%r12 mov 24(%rsp),%rbx mov 32(%rsp),%rbp add \$40,%rsp .Lepilogue: ret .size md5_block_asm_data_order,.-md5_block_asm_data_order EOF # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, # CONTEXT *context,DISPATCHER_CONTEXT *disp) if ($win64) { my $rec="%rcx"; my $frame="%rdx"; my $context="%r8"; my $disp="%r9"; $code.=<<___; .extern __imp_RtlVirtualUnwind .type se_handler,\@abi-omnipotent .align 16 se_handler: push %rsi push %rdi push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 pushfq sub \$64,%rsp mov 120($context),%rax # pull context->Rax mov 248($context),%rbx # pull context->Rip lea .Lprologue(%rip),%r10 cmp %r10,%rbx # context->Rip<.Lprologue jb .Lin_prologue mov 152($context),%rax # pull context->Rsp lea .Lepilogue(%rip),%r10 cmp %r10,%rbx # context->Rip>=.Lepilogue jae .Lin_prologue lea 40(%rax),%rax mov -8(%rax),%rbp mov -16(%rax),%rbx mov -24(%rax),%r12 mov -32(%rax),%r14 mov -40(%rax),%r15 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp mov %r12,216($context) # restore context->R12 mov %r14,232($context) # restore context->R14 mov %r15,240($context) # restore context->R15 .Lin_prologue: mov 8(%rax),%rdi mov 16(%rax),%rsi mov %rax,152($context) # restore context->Rsp mov %rsi,168($context) # restore context->Rsi mov %rdi,176($context) # restore context->Rdi mov 40($disp),%rdi # disp->ContextRecord mov $context,%rsi # context mov \$154,%ecx # sizeof(CONTEXT) .long 0xa548f3fc # cld; rep movsq mov $disp,%rsi xor %rcx,%rcx # arg1, UNW_FLAG_NHANDLER mov 8(%rsi),%rdx # arg2, disp->ImageBase mov 0(%rsi),%r8 # arg3, disp->ControlPc mov 16(%rsi),%r9 # arg4, disp->FunctionEntry mov 40(%rsi),%r10 # disp->ContextRecord lea 56(%rsi),%r11 # &disp->HandlerData lea 24(%rsi),%r12 # &disp->EstablisherFrame mov %r10,32(%rsp) # arg5 mov %r11,40(%rsp) # arg6 mov %r12,48(%rsp) # arg7 mov %rcx,56(%rsp) # arg8, (NULL) call *__imp_RtlVirtualUnwind(%rip) mov \$1,%eax # ExceptionContinueSearch add \$64,%rsp popfq pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx pop %rdi pop %rsi ret .size se_handler,.-se_handler .section .pdata .align 4 .rva .LSEH_begin_md5_block_asm_data_order .rva .LSEH_end_md5_block_asm_data_order .rva .LSEH_info_md5_block_asm_data_order .section .xdata .align 8 .LSEH_info_md5_block_asm_data_order: .byte 9,0,0,0 .rva se_handler ___ } print $code; close STDOUT;
caidongyun/nginx-openresty-windows
nginx/objs/lib/openssl-1.0.1g/crypto/md5/asm/md5-x86_64.pl
Perl
bsd-2-clause
12,818
package Sisimai::Lhost::SendGrid; use parent 'Sisimai::Lhost'; use feature ':5.10'; use strict; use warnings; sub description { 'SendGrid: https://sendgrid.com/' } sub make { # Detect an error from SendGrid # @param [Hash] mhead Message headers of a bounce email # @param [String] mbody Message body of a bounce email # @return [Hash] Bounce data list and message/rfc822 part # @return [Undef] failed to parse or the arguments are missing # @since v4.0.2 my $class = shift; my $mhead = shift // return undef; my $mbody = shift // return undef; # Return-Path: <apps@sendgrid.net> # X-Mailer: MIME-tools 5.502 (Entity 5.502) return undef unless $mhead->{'return-path'}; return undef unless $mhead->{'return-path'} eq '<apps@sendgrid.net>'; return undef unless $mhead->{'subject'} eq 'Undelivered Mail Returned to Sender'; state $indicators = __PACKAGE__->INDICATORS; state $rebackbone = qr|^Content-Type:[ ]message/rfc822|m; state $startingof = { 'message' => ['This is an automatically generated message from SendGrid.'] }; require Sisimai::RFC1894; my $fieldtable = Sisimai::RFC1894->FIELDTABLE; my $permessage = {}; # (Hash) Store values of each Per-Message field my $dscontents = [__PACKAGE__->DELIVERYSTATUS]; my $emailsteak = Sisimai::RFC5322->fillet($mbody, $rebackbone); my $readcursor = 0; # (Integer) Points the current cursor position my $recipients = 0; # (Integer) The number of 'Final-Recipient' header my $commandtxt = ''; # (String) SMTP Command name begin with the string '>>>' my $v = undef; my $p = ''; for my $e ( split("\n", $emailsteak->[0]) ) { # Read error messages and delivery status lines from the head of the email # to the previous line of the beginning of the original message. unless( $readcursor ) { # Beginning of the bounce message or message/delivery-status part $readcursor |= $indicators->{'deliverystatus'} if index($e, $startingof->{'message'}->[0]) == 0; next; } next unless $readcursor & $indicators->{'deliverystatus'}; next unless length $e; if( my $f = Sisimai::RFC1894->match($e) ) { # $e matched with any field defined in RFC3464 my $o = Sisimai::RFC1894->field($e); $v = $dscontents->[-1]; unless( $o ) { # Fallback code for empty value or invalid formatted value # - Status: (empty) # - Diagnostic-Code: 550 5.1.1 ... (No "diagnostic-type" sub field) $v->{'diagnosis'} = $1 if $e =~ /\ADiagnostic-Code:[ ]*(.+)/; next; } if( $o->[-1] eq 'addr' ) { # Final-Recipient: rfc822; kijitora@example.jp # X-Actual-Recipient: rfc822; kijitora@example.co.jp if( $o->[0] eq 'final-recipient' ) { # Final-Recipient: rfc822; kijitora@example.jp if( $v->{'recipient'} ) { # There are multiple recipient addresses in the message body. push @$dscontents, __PACKAGE__->DELIVERYSTATUS; $v = $dscontents->[-1]; } $v->{'recipient'} = $o->[2]; $recipients++; } else { # X-Actual-Recipient: rfc822; kijitora@example.co.jp $v->{'alias'} = $o->[2]; } } elsif( $o->[-1] eq 'code' ) { # Diagnostic-Code: SMTP; 550 5.1.1 <userunknown@example.jp>... User Unknown $v->{'spec'} = $o->[1]; $v->{'diagnosis'} = $o->[2]; } elsif( $o->[-1] eq 'date' ) { # Arrival-Date: 2012-12-31 23-59-59 next unless $e =~ /\AArrival-Date: (\d{4})[-](\d{2})[-](\d{2}) (\d{2})[-](\d{2})[-](\d{2})\z/; $o->[1] .= 'Thu, '.$3.' '; $o->[1] .= Sisimai::DateTime->monthname(0)->[int($2) - 1]; $o->[1] .= ' '.$1.' '.join(':', $4, $5, $6); $o->[1] .= ' '.Sisimai::DateTime->abbr2tz('CDT'); } else { # Other DSN fields defined in RFC3464 next unless exists $fieldtable->{ $o->[0] }; $v->{ $fieldtable->{ $o->[0] } } = $o->[2]; next unless $f == 1; $permessage->{ $fieldtable->{ $o->[0] } } = $o->[2]; } } else { # This is an automatically generated message from SendGrid. # # I'm sorry to have to tell you that your message was not able to be # delivered to one of its intended recipients. # # If you require assistance with this, please contact SendGrid support. # # shironekochan:000000:<kijitora@example.jp> : 192.0.2.250 : mx.example.jp:[192.0.2.153] : # 550 5.1.1 <userunknown@cubicroot.jp>... User Unknown in RCPT TO # # ------------=_1351676802-30315-116783 # Content-Type: message/delivery-status # Content-Disposition: inline # Content-Transfer-Encoding: 7bit # Content-Description: Delivery Report # # X-SendGrid-QueueID: 959479146 # X-SendGrid-Sender: <bounces+61689-10be-kijitora=example.jp@sendgrid.info> if( $e =~ /.+ in (?:End of )?([A-Z]{4}).*\z/ ) { # in RCPT TO, in MAIL FROM, end of DATA $commandtxt = $1; } else { # Continued line of the value of Diagnostic-Code field next unless index($p, 'Diagnostic-Code:') == 0; next unless $e =~ /\A[ \t]+(.+)\z/; $v->{'diagnosis'} .= ' '.$1; } } } continue { # Save the current line for the next loop $p = $e; } return undef unless $recipients; for my $e ( @$dscontents ) { # Get the value of SMTP status code as a pseudo D.S.N. $e->{'diagnosis'} = Sisimai::String->sweep($e->{'diagnosis'}); $e->{'status'} = $1.'.0.0' if $e->{'diagnosis'} =~ /\b([45])\d\d[ \t]*/; if( $e->{'status'} eq '5.0.0' || $e->{'status'} eq '4.0.0' ) { # Get the value of D.S.N. from the error message or the value of # Diagnostic-Code header. $e->{'status'} = Sisimai::SMTP::Status->find($e->{'diagnosis'}) || $e->{'status'}; } if( $e->{'action'} eq 'expired' ) { # Action: expired $e->{'reason'} = 'expired'; if( ! $e->{'status'} || substr($e->{'status'}, -4, 4) eq '.0.0' ) { # Set pseudo Status code value if the value of Status is not # defined or 4.0.0 or 5.0.0. $e->{'status'} = Sisimai::SMTP::Status->code('expired') || $e->{'status'}; } } $e->{'lhost'} ||= $permessage->{'rhost'}; $e->{'command'} ||= $commandtxt; } return { 'ds' => $dscontents, 'rfc822' => $emailsteak->[1] }; } 1; __END__ =encoding utf-8 =head1 NAME Sisimai::Lhost::SendGrid - bounce mail parser class for C<SendGrid>. =head1 SYNOPSIS use Sisimai::Lhost::SendGrid; =head1 DESCRIPTION Sisimai::Lhost::SendGrid parses a bounce email which created by C<SendGrid>. Methods in the module are called from only Sisimai::Message. =head1 CLASS METHODS =head2 C<B<description()>> C<description()> returns description string of this module. print Sisimai::Lhost::SendGrid->description; =head2 C<B<make(I<header data>, I<reference to body string>)>> C<make()> method parses a bounced email and return results as a array reference. See Sisimai::Message for more details. =head1 AUTHOR azumakuniyuki =head1 COPYRIGHT Copyright (C) 2014-2020 azumakuniyuki, All rights reserved. =head1 LICENSE This software is distributed under The BSD 2-Clause License. =cut
sisimai/p5-Sisimai
lib/Sisimai/Lhost/SendGrid.pm
Perl
bsd-2-clause
8,067
#!/usr/bin/perl -w use strict; use Data::Dumper; use lib './lib'; use Funknet::Node; my %networks; my %transit_networks; my @node_objects; my @cnode_objects; my @tunnels; my @autnums; my @required_node_values = qw/ endpoint mntner name networks /; my @required_cnode_values = qw/ endpoint mntner name transit_networks /; my $person = 'VPN-CONTACT'; my $mntner = 'VPN-MNT'; my $create_email = 'dunc@bleh.org'; my $source = 'FUNKNET'; my $tunnel_type = 'ipip'; my $first_as = 61000; my $node_list = [ { name => 'nodeA', networks => [ '192.168.10.0/24' ], endpoint => '1.2.3.4', mntner => 'NODEA-MNT' }, { name => 'nodeB', networks => [ '192.168.11.0/24' ], endpoint => '5.6.7.8', mntner => 'NODEB-MNT' }, { name => 'nodeC', networks => [ '192.168.12.0/24', '192.168.13.0/24' ], endpoint => '9.5.3.4', mntner => 'NODEC-MNT' }, ]; my $cnode_list = [ { name => 'CnodeA', transit_networks => [ '10.100.1.0/24' ], endpoint => '1.1.1.1', mntner => 'CNODEA-MNT' }, { name => 'CnodeB', transit_networks => [ '10.100.2.0/29', '10.100.3.0/24' ], endpoint => '2.2.2.2', mntner => 'CNODEB-MNT' }, ]; ####################################################################### for my $cnode (@$cnode_list) { for my $key (@required_cnode_values) { die "Missing value $key for CNode $cnode" unless defined $cnode->{$key}; } } for my $node (@$node_list) { for my $key (@required_node_values) { die "Missing value $key for Node $node" unless defined $node->{$key}; } } my $next_as = $first_as; for my $cnode (@$cnode_list) { my $new_cnode = Funknet::Node::CNode->new( $cnode->{transit_networks}, name => $cnode->{name}, endpoint => $cnode->{endpoint}, contact => $person, mntner => $cnode->{mntner}, as => "AS$next_as",); push (@cnode_objects, $new_cnode); $next_as++; } for my $node (@$node_list) { my $new_node = Funknet::Node::Node->new( $node->{networks}, name => $node->{name}, endpoint => $node->{endpoint}, contact => $person, mntner => $node->{mntner}, as => "AS$next_as",); push (@node_objects, $new_node); $next_as++; } # Iterate through Cnode->Node combinations for my $cnode (@cnode_objects) { for my $node (@node_objects) { my $transit_net = $cnode->next_transit_net; my $tunnel = Funknet::Node->new_tunnel(cnode => $cnode, node => $node, transit_net => $transit_net, changed => $create_email, source => $source, tunnel_type => $tunnel_type ); print $tunnel . "\n\n"; push (@tunnels, $tunnel); } }
chrisa/funknet-tools
bin/create_vpn_objects.pl
Perl
bsd-3-clause
2,652