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 Business::Price::Collection; our $VERSION = '1.000_1'; use Moose; __PACKAGE__->meta->make_immutable; __END__ =pod =head1 NAME Business::Price::Collection =head1 VERSION version 1.000_1 =head1 AUTHOR Moritz Onken <onken@netcubed.de> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2010 by Moritz Onken. This is free software, licensed under: The (three-clause) BSD License =cut
gitpan/Business-Price
lib/Business/Price/Collection.pm
Perl
bsd-3-clause
415
package PerlDaemon::ThreadedLogger; use strict; use warnings; $| = 1; sub new ($$) { my ($class, $conf) = @_; my $self = $SELF = bless { conf => $conf }, $class; return $self; } sub _pushmsg ($$) { my ($self, $msg) = @_; my $conf = $self->{conf}; my $msgqueue = $conf->{msgqueue}; push @$msgqueue, $msg; } sub logmsg ($$) { my ($self, $msg) = @_; my $logline = localtime()." (PID $$): $msg\n"; $self->_pushmsg($logline); return undef; } sub err ($$) { my ($self, $msg) = @_; $self->logmsg($msg); die "$msg\n"; } sub warn ($$) { my ($self, $msg) = @_; $self->logmsg("WARNING: $msg"); return undef; } 1;
buetow/perldaemon
lib/PerlDaemon/ThreadedLogger.pm
Perl
bsd-3-clause
649
package MailHog::Server::SMTP::RFC4954::LOGIN; # SASL LOGIN - probably not required use Modern::Perl; use Moose; use MIME::Base64 qw/ decode_base64 encode_base64 /; has 'rfc' => ( is => 'rw', isa => 'MailHog::Server::SMTP::RFC4954' ); #------------------------------------------------------------------------------ sub helo { my ($self, $session) = @_; return "LOGIN"; } #------------------------------------------------------------------------------ sub initial_response { my ($self, $session, $args) = @_; if(!$args) { $session->log("LOGIN received no args in initial response, returning 334"); $session->respond($MailHog::Server::SMTP::ReplyCodes{SERVER_CHALLENGE}, "VXNlcm5hbWU6"); return; } return $self->data($session, $args); } #------------------------------------------------------------------------------ sub data { my ($self, $session, $data) = @_; $session->log("Authenticating using LOGIN mechanism"); # Get the username first if(!$session->user || !$session->stash('username')) { my $username; eval { $session->log("Decoding data [$data]"); $username = decode_base64($data); $username =~ s/\r?\n$//s; }; if($@ || !$username) { $session->log("Error decoding base64 data: $@"); $session->respond($MailHog::Server::SMTP::ReplyCodes{SYNTAX_ERROR_IN_PARAMETERS}, "Not a valid BASE64 string"); $session->state('ACCEPT'); $session->user(undef); delete $session->stash->{username} if $session->stash->{username}; delete $session->stash->{password} if $session->stash->{password}; return; } $session->log("Got username: $username"); $session->stash(username => $username); $session->respond($MailHog::Server::SMTP::ReplyCodes{SERVER_CHALLENGE}, "UGFzc3dvcmQ6"); return; } my $password; eval { $session->log("Decoding data [$data]"); $password = decode_base64($data); $password =~ s/\r?\n$//s; }; if($@ || !$password) { $session->log("Error decoding base64 data: $@"); $session->respond($MailHog::Server::SMTP::ReplyCodes{SYNTAX_ERROR_IN_PARAMETERS}, "Not a valid BASE64 string"); $session->state('ACCEPT'); $session->user(undef); delete $session->stash->{username} if $session->stash->{username}; delete $session->stash->{password} if $session->stash->{password}; return; } $session->log("Got password: $password"); $session->stash(password => $password); $session->log("LOGIN: Username [" . $session->stash('username') . "], Password [$password]"); my $user = $session->smtp->get_user($session->stash('username'), $password); if(!$user) { $session->log("Authentication failed"); $session->respond($MailHog::Server::SMTP::ReplyCodes{AUTHENTICATION_FAILED}, "LOGIN authentication failed"); $session->user(undef); delete $session->stash->{username} if $session->stash->{username}; delete $session->stash->{password} if $session->stash->{password}; } else { $session->log("Authentication successful"); $session->respond($MailHog::Server::SMTP::ReplyCodes{AUTHENTICATION_SUCCESSFUL}, "authentication successful"); $session->user($user); } $session->state('ACCEPT'); } #------------------------------------------------------------------------------ __PACKAGE__->meta->make_immutable;
mehulsbhatt/MailHog
lib/MailHog/Server/SMTP/RFC4954/LOGIN.pm
Perl
mit
3,637
#!/usr/bin/env perl use warnings; use strict; use Data::Dumper; use Carp; use 5.010; use Bio::Gonzales::Util::Cerial; use Bio::Gonzales::Project::Functions; use GO::Parser; use Getopt::Long::Descriptive; my ( $opt, $usage ) = describe_options( '%c %o <obo file>', [ "format" => hidden => { one_of => [ [ "json|j" => "output in json format" ], [ "yaml|y" => "output in yaml format" ], ], default => 'json' } ], [ 'namespace|n=s', 'restrict to certain namespace' ], [ 'verbose|v', "print extra stuff" ], [ 'help', "print usage message and exit" ], ); print( $usage->text ), exit if $opt->help; my $file = shift; die "$file is no file" unless ( -f $file ); my %go; # ** FETCHING GRAPH OBJECTS FROM AN ONTOLOGY FILE ** my $parser = new GO::Parser( { handler => 'obj' } ); # create parser object $parser->parse($file); # parse file -> objects my $graph = $parser->handler->graph; # get L<GO::Model::Graph> object my @terms; if ( $opt->namespace ) { @terms = grep { $_->namespace eq $opt->namespace } @{ $graph->get_all_terms }; } else { @terms = @{ $graph->get_all_terms }; } my %gos; for my $t (@terms) { die Dumper $t if ( $t->acc !~ /^GO:/ ); $gos{ $t->acc } = { name => $t->name, def => $t->definition }; for my $alt_id ( @{ $t->alt_id_list } ) { $gos{$alt_id} = { name => $t->name, def => $t->definition }; } } if ( $opt->format eq 'json' ) { jspew( \*STDOUT, \%gos ); } elsif ( $opt->format eq 'yaml' ) { yspew( \*STDOUT, \%gos ); }
jwbargsten/bmrfweb-trait
bin/go_extract_desc.pl
Perl
mit
1,567
package DDG::Spice::Currency; # ABSTRACT: Currency Convertor provided by XE.com use strict; use DDG::Spice; with 'DDG::SpiceRole::NumberStyler'; use Text::Trim; use YAML::XS qw(LoadFile); # Get all the valid currencies from a text file. my @currTriggers; my @currencies = share('currencyNames.txt')->slurp; my %currHash = (); # load decimal => unicode currency codes my $currencyCodes = LoadFile share("currencySymbols.yml"); foreach my $currency (@currencies){ chomp($currency); my @currency = split(/,/,$currency); push(@currTriggers, @currency); $currHash{$currency[0]} = \@currency; } # Define the regexes here. my $currency_qr = join('|', @currTriggers); my $into_qr = qr/\s(?:en|in|to|in ?to|to)\s/i; my $vs_qr = qr/\sv(?:ersu|)s\.?\s/i; my $question_prefix = qr/(?:convert|what (?:is|are|does)|how (?:much|many) (?:is|are))?\s?/; my $number_re = number_style_regex(); my $cardinal_re = join('|', qw(hundred thousand k million m billion b trillion)); my $guard = qr/^$question_prefix(\p{Currency_Symbol})?\s?($number_re*)\s?(\p{Currency_Symbol})?\s?($cardinal_re)?\s?($currency_qr)?(?:s)?(?:$into_qr|$vs_qr|\/|\s)?($number_re*)\s?($currency_qr)?(\p{Currency_Symbol})?(?:s)?\??$/i; triggers query_lc => qr/\p{Currency_Symbol}|$currency_qr/; spice from => '([^/]+)/([^/]+)/([^/]+)'; spice to => 'http://www.xe.com/tmi/xe-output.php?amount=$1&from=$2&to=$3&appid={{ENV{DDG_SPICE_CURRENCY_APIKEY}}}'; spice wrap_jsonp_callback => 1; spice is_cached => 0; spice proxy_cache_valid => "200 5m"; # This function converts things like "us dollars" to the standard "usd". sub getCode { my $input = shift; foreach my $key (keys %currHash) { if(exists $currHash{$key}) { my @currValues = @{$currHash{$key}}; foreach my $value (@currValues) { if($input eq $value) { return $key; } } } } } # This function is responsible for processing the input. # - Setting default values. # - Checking if the input number is valid. sub checkCurrencyCode { my($amount, $from, $to) = @_; # Check if it's a valid number. # If it isn't, return early. my $styler = number_style_for($amount); return unless $styler; # Choose the default currency. # If the user types in 10 usd, it should default to eur. # If the user types in 10 eur, it should default to usd. # my $default_to = getCode($from) eq "usd" ? "eur" : "usd"; my $normalized_number = $styler->for_computation($amount); # There are cases where people type in "2016 euro" or "1999 php", so we don't want to trigger on those queries. if($normalized_number >= 1900 && $normalized_number < 2100 && (length($from) == 0 || length($to) == 0)) { return; } $from = getCode($from) || ''; $to = getCode($to) || ''; # Return early if we get a query like "usd to usd". if($from eq $to) { return; } # Return early if we don't get a currency to convert from. if($from eq '') { return; } # If we don't get a currency to convert to, e.g., the user types in "usd" # we set them to be the same thing. This will trigger our tile view. if($to eq '') { if($normalized_number == 1) { $to = $from; } else { # This should probably depend on the user's location. # For example, if I was in the Philippines, I would expect "10 usd" to mean "10 usd to php" # But this would mean mapping currencies to countries. $to = $from eq 'usd' ? 'eur' : 'usd'; } } return $normalized_number, $from, $to; } handle query_lc => sub { if(/$guard/) { my ($fromSymbol, $amount, $cardinal, $from, $alt_amount, $to, $toSymbol) = ($1 || $3 || '', $2, $4 || '', $5 || '', $6 || '' , $7 || '', $8 || ''); if ($from eq '' && $fromSymbol) { $from = $currencyCodes->{ord($fromSymbol)}; } if ($to eq '' && $toSymbol) { $to = $currencyCodes->{ord($toSymbol)}; } my $styler = number_style_for($amount); return unless $styler; if ($cardinal ne '') { $amount = $styler->for_computation($amount); if ($cardinal eq 'hundred') { $amount *= 100 } elsif ($cardinal =~ /(thousand|k)/i) { $amount *= 1000 } elsif ($cardinal =~ /(million|m)/i) { $amount *= 1000000 } elsif ($cardinal =~ /(billion|b)/i) { $amount *= 1000000000 } elsif ($cardinal =~ /(trillion|t)/i) { $amount *= 1000000000000 } } # If two amounts are available, exit early. It's ambiguous. # We use the length function to check if it's an empty string or not. if(length($amount) && length($alt_amount)) { return; } # Case where the first amount is available. elsif(length($amount)) { return checkCurrencyCode($amount, $from, $to); } # Case where the second amount is available. # We switch the $from and $to here. elsif(length($alt_amount)) { return checkCurrencyCode($alt_amount, $to, $from); } # Case where neither of them are available. else { return checkCurrencyCode(1, $from, $to); } } return; }; 1;
andrey-p/zeroclickinfo-spice
lib/DDG/Spice/Currency.pm
Perl
apache-2.0
5,411
#!/usr/bin/perl # count_dix_entries # # Input: bilingual dictionary in Matxin XML format # Output: the number of entries in given categories use strict; use utf8; use XML::LibXML; #use DateTime; #use POSIX qw/strftime/; #my $date = strftime "%Y-%m-%d", localtime; my $totalentries =0; my $totalunspec =0; my $totaltranslated =0; my $dom = XML::LibXML->load_xml( IO => *STDIN ); # foreach my $section ($dom->getElementsByTagName('section')) # { # print STDOUT "section ".$section->getAttribute('id').": "; #print STDOUT scalar(@entries)."\n"; #$total = $total + scalar(@entries); # my ($verbsection) = $dom->findnodes('descendant::section[@id="verbs"]'); # my @entries = $verbsection->findnodes('child::e'); # my %entries = []; # foreach my $e (@entries){ # my ($r) = $e->findnodes('child::p/r[1]'); # # if($entries{$e}){ # push($entries{$e}, $r); # # print $e->toString()."\n"; # } # else{ # $entries{$e} = [$r]; # } # } # # my $nbrOfUntranslated =0; # my $nbrOfTranslated =0; # # foreach my $e (keys %entries){ # #print "test ".$entries{$e}[0]->textContent."\n"; # my $rs = $entries{$e}; # #print "test ".@$rs[0]->textContent."\n"; # if($rs && scalar(@$rs) ==1 && @$rs[0]->textContent =~ 'unspecified' ){ # $nbrOfUntranslated++; # } # elsif($rs){ # $nbrOfTranslated++; # } # else{ # delete $entries{$e}; # print "no rs: $e\n"; # } # } foreach my $section ($dom->getElementsByTagName('section')){ my $translated =0; my $untranslated =0; my @entries = $section->findnodes('child::e'); my %entries = []; foreach my $e (@entries){ my ($r) = $e->findnodes('child::p/r[1]'); if($entries{$e}){ push($entries{$e}, $r); # print $e->toString()."\n"; } else{ $entries{$e} = [$r]; } } foreach my $e (keys %entries){ #print "test ".$entries{$e}[0]->textContent."\n"; my $rs = $entries{$e}; #print "test ".@$rs[0]->textContent."\n"; if($rs && scalar(@$rs) ==1 && @$rs[0]->textContent eq 'unspecified' ){ $untranslated++; } elsif($rs){ $translated++; } else{ print "no r's: ".$entries{$e}."\n"; delete $entries{$e}; } } $totalentries += scalar(keys %entries); $totaltranslated += $translated; $totalunspec += $untranslated; print "total number of lemmas in section ".$section->getAttribute('id').": ".scalar(keys %entries)."\n"; print "number of entries with at least one translation: $translated\n"; print "number of entries with no translation: $untranslated\n"; } print "total number of lemmas in dix: ".$totalentries."\n"; print "number of entries with at least one translation: $totaltranslated\n"; print "number of entries with no translation: $totalunspec\n"; #print STDOUT "total number of entries: $total\n"; # my $total = 0; # print "Number of entries in the bilingual dictionary\n"; # print "POS\tSize\tCategory\n"; # $total = $total + &count_entries("A","adjectives"); # $total = $total + &count_entries("C","conjunctions"); # $total = $total + &count_entries("D","determiners"); # $total = $total + &count_entries("NC","common nouns"); # $total = $total + &count_entries("NP","named entities"); # $total = $total + &count_entries("PI","indef pronouns"); # $total = $total + &count_entries("SP","prepositions"); # $total = $total + &count_entries("R","adverbs"); # $total = $total + &count_entries("V","verbs"); # # print "Total\t$total\tentries ($date)\n";
ariosquoia/squoia
MT_systems/squoia/esqu/lexica/count_dix_entries.pl
Perl
apache-2.0
3,484
############################################################################# ## Name: lib/Wx/GLCanvas.pm ## Purpose: loader for Wx::GLCanvas.pm ## Author: Mattia Barbon ## Modified by: ## Created: 26/07/2003 ## RCS-ID: $Id: GLCanvas.pm 2489 2008-10-27 19:50:51Z mbarbon $ ## Copyright: (c) 2003, 2005, 2007-2009 Mattia Barbon ## Licence: This program is free software; you can redistribute it and/or ## modify it under the same terms as Perl itself ############################################################################# package Wx::GLCanvas; use strict; use Wx; use base 'Wx::ScrolledWindow'; require Exporter; *import = \&Exporter::import; our @EXPORT_OK = ( qw(WX_GL_RGBA WX_GL_BUFFER_SIZE WX_GL_LEVEL WX_GL_DOUBLEBUFFER WX_GL_STEREO WX_GL_AUX_BUFFERS WX_GL_MIN_RED WX_GL_MIN_GREEN WX_GL_MIN_BLUE WX_GL_MIN_ALPHA WX_GL_DEPTH_SIZE WX_GL_STENCIL_SIZE WX_GL_MIN_ACCUM_RED WX_GL_MIN_ACCUM_GREEN WX_GL_MIN_ACCUM_BLUE WX_GL_MIN_ACCUM_ALPHA) ); our %EXPORT_TAGS = ( all => \@EXPORT_OK, everything => \@EXPORT_OK, ); $Wx::GLCanvas::VERSION = '0.09'; Wx::load_dll( 'gl' ); Wx::wx_boot( 'Wx::GLCanvas', $Wx::GLCanvas::VERSION ); our $AUTOLOAD; sub AUTOLOAD { ( my $constname = $AUTOLOAD ) =~ s<^.*::>{}; return if $constname eq 'DESTROY'; my $val = constant( $constname, 0 ); if( $! != 0 ) { # re-add this if need support for autosplitted subroutines # $AutoLoader::AUTOLOAD = $AUTOLOAD; # goto &AutoLoader::AUTOLOAD; Wx::_croak( "Error while autoloading '$AUTOLOAD'" ); } eval "sub $AUTOLOAD() { $val }"; goto &$AUTOLOAD; } 1; __END__ =head1 NAME Wx::GLCanvas - interface to wxWidgets' OpenGL canvas =head1 SYNOPSIS use OpenGL; # or any other module providing OpenGL API use Wx::GLCanvas; =head1 DESCRIPTION The documentation for this module is included in the main wxPerl distribution (wxGLCanvas). =head1 AUTHOR Mattia Barbon <mbarbon@cpan.org> =head1 LICENSE This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut # local variables: # mode: cperl # end:
thomaspreece10/STLExtract
Slic3r/Linux/lib/std/Wx/GLCanvas.pm
Perl
mit
2,162
package Sisimai::Bite; use feature ':5.10'; use strict; use warnings; sub DELIVERYSTATUS { # Data structure for parsed bounce messages # @private # @return [Hash] Data structure for delivery status return { 'spec' => '', # Protocl specification 'date' => '', # The value of Last-Attempt-Date header 'rhost' => '', # The value of Remote-MTA header 'lhost' => '', # The value of Received-From-MTA header 'alias' => '', # The value of alias entry(RHS) 'agent' => '', # MTA name 'action' => '', # The value of Action header 'status' => '', # The value of Status header 'reason' => '', # Temporary reason of bounce 'command' => '', # SMTP command in the message body 'replycode', => '', # SMTP Reply Code 'diagnosis' => '', # The value of Diagnostic-Code header 'recipient' => '', # The value of Final-Recipient header 'softbounce' => '', # Soft bounce or not 'feedbacktype' => '', # Feedback Type }; } sub smtpagent { my $v = shift; $v =~ s/\ASisimai::Bite:://; return $v } sub description { return '' } 1; __END__ =encoding utf-8 =head1 NAME Sisimai::Bite - Base class for Sisimai::Bite::* =head1 SYNOPSIS Sisimai::Bite is a base class for keeping all the MTA modules. Do not use this class and child classes of Sisimai::Bite::* directly. Use Sisimai::Bite::*::*, such as Sisimai::Bite::Email::Sendmail, instead. =head1 DESCRIPTION Sisimai::Bite is a base class for keeping all the MTA modules. =head1 AUTHOR azumakuniyuki =head1 COPYRIGHT Copyright (C) 2017 azumakuniyuki, All rights reserved. =head1 LICENSE This software is distributed under The BSD 2-Clause License. =cut
azumakuniyuki/p5-Sisimai
lib/Sisimai/Bite.pm
Perl
bsd-2-clause
1,839
package AI::MXNet; use v5.14.0; use strict; use warnings; use AI::MXNet::Base; use AI::MXNet::Callback; use AI::MXNet::NDArray; use AI::MXNet::Symbol; use AI::MXNet::Executor; use AI::MXNet::Executor::Group; use AI::MXNet::Rtc; use AI::MXNet::Random; use AI::MXNet::Initializer; use AI::MXNet::Optimizer; use AI::MXNet::KVStore; use AI::MXNet::KVStoreServer; use AI::MXNet::IO; use AI::MXNet::Metric; use AI::MXNet::LRScheduler; use AI::MXNet::Monitor; use AI::MXNet::Profiler; use AI::MXNet::Module::Base; use AI::MXNet::Module; use AI::MXNet::Module::Bucketing; use AI::MXNet::RNN; use AI::MXNet::Visualization; use AI::MXNet::RecordIO; use AI::MXNet::Image; use AI::MXNet::Contrib; use AI::MXNet::Contrib::AutoGrad; our $VERSION = '1.01'; sub import { my ($class, $short_name) = @_; if($short_name) { $short_name =~ s/[^\w:]//g; if(length $short_name) { my $short_name_package =<<"EOP"; package $short_name; no warnings 'redefine'; sub nd { 'AI::MXNet::NDArray' } sub sym { 'AI::MXNet::Symbol' } sub symbol { 'AI::MXNet::Symbol' } sub init { 'AI::MXNet::Initializer' } sub initializer { 'AI::MXNet::Initializer' } sub optimizer { 'AI::MXNet::Optimizer' } sub opt { 'AI::MXNet::Optimizer' } sub rnd { 'AI::MXNet::Random' } sub random { 'AI::MXNet::Random' } sub Context { shift; AI::MXNet::Context->new(\@_) } sub cpu { AI::MXNet::Context->cpu(\$_[1]//0) } sub gpu { AI::MXNet::Context->gpu(\$_[1]//0) } sub kv { 'AI::MXNet::KVStore' } sub recordio { 'AI::MXNet::RecordIO' } sub io { 'AI::MXNet::IO' } sub metric { 'AI::MXNet::Metric' } sub mod { 'AI::MXNet::Module' } sub mon { 'AI::MXNet::Monitor' } sub viz { 'AI::MXNet::Visualization' } sub rnn { 'AI::MXNet::RNN' } sub callback { 'AI::MXNet::Callback' } sub img { 'AI::MXNet::Image' } sub contrib { 'AI::MXNet::Contrib' } sub name { '$short_name' } sub AttrScope { shift; AI::MXNet::Symbol::AttrScope->new(\@_) } *AI::MXNet::Symbol::AttrScope::current = sub { \$${short_name}::AttrScope; }; \$${short_name}::AttrScope = AI::MXNet::Symbol::AttrScope->new; sub Prefix { AI::MXNet::Symbol::Prefix->new(prefix => \$_[1]) } *AI::MXNet::Symbol::NameManager::current = sub { \$${short_name}::NameManager; }; \$${short_name}::NameManager = AI::MXNet::Symbol::NameManager->new; *AI::MXNet::Context::current_ctx = sub { \$${short_name}::Context; }; \$${short_name}::Context = AI::MXNet::Context->new(device_type => 'cpu', device_id => 0); 1; EOP eval $short_name_package; } } } 1; __END__ =encoding UTF-8 =head1 NAME AI::MXNet - Perl interface to MXNet machine learning library =head1 SYNOPSIS ## Convolutional NN for recognizing hand-written digits in MNIST dataset ## It's considered "Hello, World" for Neural Networks ## For more info about the MNIST problem please refer to http://neuralnetworksanddeeplearning.com/chap1.html use strict; use warnings; use AI::MXNet qw(mx); use AI::MXNet::TestUtils qw(GetMNIST_ubyte); use Test::More tests => 1; # symbol net my $batch_size = 100; ### model my $data = mx->symbol->Variable('data'); my $conv1= mx->symbol->Convolution(data => $data, name => 'conv1', num_filter => 32, kernel => [3,3], stride => [2,2]); my $bn1 = mx->symbol->BatchNorm(data => $conv1, name => "bn1"); my $act1 = mx->symbol->Activation(data => $bn1, name => 'relu1', act_type => "relu"); my $mp1 = mx->symbol->Pooling(data => $act1, name => 'mp1', kernel => [2,2], stride =>[2,2], pool_type=>'max'); my $conv2= mx->symbol->Convolution(data => $mp1, name => 'conv2', num_filter => 32, kernel=>[3,3], stride=>[2,2]); my $bn2 = mx->symbol->BatchNorm(data => $conv2, name=>"bn2"); my $act2 = mx->symbol->Activation(data => $bn2, name=>'relu2', act_type=>"relu"); my $mp2 = mx->symbol->Pooling(data => $act2, name => 'mp2', kernel=>[2,2], stride=>[2,2], pool_type=>'max'); my $fl = mx->symbol->Flatten(data => $mp2, name=>"flatten"); my $fc1 = mx->symbol->FullyConnected(data => $fl, name=>"fc1", num_hidden=>30); my $act3 = mx->symbol->Activation(data => $fc1, name=>'relu3', act_type=>"relu"); my $fc2 = mx->symbol->FullyConnected(data => $act3, name=>'fc2', num_hidden=>10); my $softmax = mx->symbol->SoftmaxOutput(data => $fc2, name => 'softmax'); # check data GetMNIST_ubyte(); my $train_dataiter = mx->io->MNISTIter({ image=>"data/train-images-idx3-ubyte", label=>"data/train-labels-idx1-ubyte", data_shape=>[1, 28, 28], batch_size=>$batch_size, shuffle=>1, flat=>0, silent=>0, seed=>10}); my $val_dataiter = mx->io->MNISTIter({ image=>"data/t10k-images-idx3-ubyte", label=>"data/t10k-labels-idx1-ubyte", data_shape=>[1, 28, 28], batch_size=>$batch_size, shuffle=>1, flat=>0, silent=>0}); my $n_epoch = 1; my $mod = mx->mod->new(symbol => $softmax); $mod->fit( $train_dataiter, eval_data => $val_dataiter, optimizer_params=>{learning_rate=>0.01, momentum=> 0.9}, num_epoch=>$n_epoch ); my $res = $mod->score($val_dataiter, mx->metric->create('acc')); ok($res->{accuracy} > 0.8); =head1 DESCRIPTION Perl interface to MXNet machine learning library. =head1 BUGS AND INCOMPATIBILITIES Parity with Python inteface is mostly achieved, few deprecated and not often used features left unported for now. =head1 SEE ALSO http://mxnet.io/ https://github.com/dmlc/mxnet/tree/master/perl-package Function::Parameters, Mouse =head1 AUTHOR Sergey Kolychev, <sergeykolychev.github@gmail.com> =head1 COPYRIGHT & LICENSE Copyright (C) 2017 by Sergey Kolychev <sergeykolychev.github@gmail.com> This library is licensed under Apache 2.0 license https://www.apache.org/licenses/LICENSE-2.0 =cut
EvanzzzZ/mxnet
perl-package/AI-MXNet/lib/AI/MXNet.pm
Perl
apache-2.0
6,242
##### # FCKeditor - The text editor for Internet - http://www.fckeditor.net # Copyright (C) 2003-2007 Frederico Caldeira Knabben # # == BEGIN LICENSE == # # Licensed under the terms of any of the following licenses at your # choice: # # - GNU General Public License Version 2 or later (the "GPL") # http://www.gnu.org/licenses/gpl.html # # - GNU Lesser General Public License Version 2.1 or later (the "LGPL") # http://www.gnu.org/licenses/lgpl.html # # - Mozilla Public License Version 1.1 or later (the "MPL") # http://www.mozilla.org/MPL/MPL-1.1.html # # == END LICENSE == # # This is the File Manager Connector for Perl. ##### sub RemoveFromStart { local($sourceString, $charToRemove) = @_; $sPattern = '^' . $charToRemove . '+' ; $sourceString =~ s/^$charToRemove+//g; return $sourceString; } sub RemoveFromEnd { local($sourceString, $charToRemove) = @_; $sPattern = $charToRemove . '+$' ; $sourceString =~ s/$charToRemove+$//g; return $sourceString; } sub ConvertToXmlAttribute { local($value) = @_; return $value; # return utf8_encode(htmlspecialchars($value)); } sub specialchar_cnv { local($ch) = @_; $ch =~ s/&/&amp;/g; # & $ch =~ s/\"/&quot;/g; #" $ch =~ s/\'/&#39;/g; # ' $ch =~ s/</&lt;/g; # < $ch =~ s/>/&gt;/g; # > return($ch); } sub JS_cnv { local($ch) = @_; $ch =~ s/\"/\\\"/g; #" return($ch); } 1;
kalebecalixto/webEntregas
webEntregas/public_html/modelos/ADI_Bin/utilitarios/FCKeditor/editor/filemanager/connectors/perl/util.pl
Perl
apache-2.0
1,373
package Text::Xslate::Parser; use Mouse; use Scalar::Util (); use Text::Xslate::Symbol; use Text::Xslate::Util qw( $DEBUG $STRING $NUMBER is_int any_in neat literal_to_value make_error p ); use constant _DUMP_PROTO => scalar($DEBUG =~ /\b dump=proto \b/xmsi); use constant _DUMP_TOKEN => scalar($DEBUG =~ /\b dump=token \b/xmsi); our @CARP_NOT = qw(Text::Xslate::Compiler Text::Xslate::Symbol); my $CODE = qr/ (?: $STRING | [^'"] ) /xms; my $COMMENT = qr/\# [^\n;]* (?= [;\n] | \z)/xms; # Operator tokens that the parser recognizes. # All the single characters are tokenized as an operator. my $OPERATOR_TOKEN = sprintf '(?:%s|[^ \t\r\n])', join('|', map{ quotemeta } qw( ... .. == != <=> <= >= << >> += -= *= /= %= ~= &&= ||= //= ~~ =~ && || // -> => :: ++ -- +| +& +^ +< +> +~ ), ','); my %shortcut_table = ( '=' => 'print', ); my $CHOMP_FLAGS = qr/-/xms; has identity_pattern => ( is => 'ro', isa => 'RegexpRef', builder => '_build_identity_pattern', init_arg => undef, ); sub _build_identity_pattern { return qr/(?: (?:[A-Za-z_]|\$\~?) [A-Za-z0-9_]* )/xms; } has [qw(compiler engine)] => ( is => 'rw', required => 0, weak_ref => 1, ); has symbol_table => ( # the global symbol table is => 'ro', isa => 'HashRef', default => sub{ {} }, init_arg => undef, ); has iterator_element => ( is => 'ro', isa => 'HashRef', lazy => 1, builder => '_build_iterator_element', init_arg => undef, ); has scope => ( is => 'rw', isa => 'ArrayRef[HashRef]', clearer => 'init_scope', lazy => 1, default => sub{ [ {} ] }, init_arg => undef, ); has token => ( is => 'rw', isa => 'Maybe[Object]', init_arg => undef, ); has next_token => ( # to peek the next token is => 'rw', isa => 'Maybe[ArrayRef]', init_arg => undef, ); has statement_is_finished => ( is => 'rw', isa => 'Bool', init_arg => undef, ); has following_newline => ( is => 'rw', isa => 'Int', default => 0, init_arg => undef, ); has input => ( is => 'rw', isa => 'Str', init_arg => undef, ); has line_start => ( is => 'ro', isa => 'Maybe[Str]', builder => '_build_line_start', ); sub _build_line_start { ':' } has tag_start => ( is => 'ro', isa => 'Str', builder => '_build_tag_start', ); sub _build_tag_start { '<:' } has tag_end => ( is => 'ro', isa => 'Str', builder => '_build_tag_end', ); sub _build_tag_end { ':>' } has comment_pattern => ( is => 'ro', isa => 'RegexpRef', builder => '_build_comment_pattern', ); sub _build_comment_pattern { $COMMENT } has shortcut_table => ( is => 'ro', isa => 'HashRef[Str]', builder => '_build_shortcut_table', ); sub _build_shortcut_table { \%shortcut_table } has in_given => ( is => 'rw', isa => 'Bool', init_arg => undef, ); # attributes for error messages has near_token => ( is => 'rw', init_arg => undef, ); has file => ( is => 'rw', required => 0, ); has line => ( is => 'rw', required => 0, ); has input_layer => ( is => 'ro', default => ':utf8', ); sub symbol_class() { 'Text::Xslate::Symbol' } # the entry point sub parse { my($parser, $input, %args) = @_; local $parser->{file} = $args{file} || \$input; local $parser->{line} = $args{line} || 1; local $parser->{in_given} = 0; local $parser->{scope} = [ map { +{ %{$_} } } @{ $parser->scope } ]; local $parser->{symbol_table} = { %{ $parser->symbol_table } }; local $parser->{near_token}; local $parser->{next_token}; local $parser->{token}; local $parser->{input}; $parser->input( $parser->preprocess($input) ); $parser->next_token( $parser->tokenize() ); $parser->advance(); my $ast = $parser->statements(); if(my $input_pos = pos $parser->{input}) { if($input_pos != length($parser->{input})) { $parser->_error("Syntax error", $parser->token); } } return $ast; } sub trim_code { my($parser, $s) = @_; $s =~ s/\A [ \t]+ //xms; $s =~ s/ [ \t]+ \n?\z//xms; return $s; } sub auto_chomp { my($parser, $tokens_ref, $i, $s_ref) = @_; my $p; my $nl = 0; # postchomp if($i >= 1 and ($p = $tokens_ref->[$i-1])->[0] eq 'postchomp') { # [ CODE ][*][ TEXT ] # <: ... -:> \nfoobar # ^^^^ ${$s_ref} =~ s/\A [ \t]* (\n)//xms; if($1) { $nl++; } } # prechomp if(($i+1) < @{$tokens_ref} and ($p = $tokens_ref->[$i+1])->[0] eq 'prechomp') { if(${$s_ref} !~ / [^ \t] /xms) { # HERE # [ TEXT ][*][ CODE ] # <:- ... :> # ^^^^^^^^ ${$s_ref} = ''; } else { # HERE # [ TEXT ][*][ CODE ] # \n<:- ... :> # ^^ $nl += chomp ${$s_ref}; } } elsif(($i+2) < @{$tokens_ref} and ($p = $tokens_ref->[$i+2])->[0] eq 'prechomp' and ($p = $tokens_ref->[$i+1])->[0] eq 'text' and $p->[1] !~ / [^ \t] /xms) { # HERE # [ TEXT ][ TEXT ][*][ CODE ] # \n <:- ... :> # ^^^^^^^^^^ $p->[1] = ''; $nl += chomp ${$s_ref}; } return $nl; } # split templates by tags before tokenizing sub split :method { my $parser = shift; local($_) = @_; my @tokens; my $line_start = $parser->line_start; my $tag_start = $parser->tag_start; my $tag_end = $parser->tag_end; my $lex_line_code = defined($line_start) && qr/\A ^ [ \t]* \Q$line_start\E ([^\n]* \n?) /xms; my $lex_tag_start = qr/\A \Q$tag_start\E ($CHOMP_FLAGS?)/xms; # 'text' is a something without newlines # follwoing a newline, $tag_start, or end of the input my $lex_text = qr/\A ( [^\n]*? (?: \n | (?= \Q$tag_start\E ) | \z ) ) /xms; my $lex_comment = $parser->comment_pattern; my $lex_code = qr/(?: $lex_comment | $CODE )/xms; my $in_tag = 0; while($_) { if($in_tag) { my $start = 0; my $pos; while( ($pos = index $_, $tag_end, $start) >= 0 ) { my $code = substr $_, 0, $pos; $code =~ s/$lex_code//xmsg; if(length($code) == 0) { last; } $start = $pos + 1; } if($pos >= 0) { my $code = substr $_, 0, $pos, ''; $code =~ s/($CHOMP_FLAGS?) \z//xmso; my $chomp = $1; s/\A \Q$tag_end\E //xms or die "Oops!"; push @tokens, [ code => $code ]; if($chomp) { push @tokens, [ postchomp => $chomp ]; } $in_tag = 0; } else { last; # the end tag is not found } } # not $in_tag elsif($lex_line_code && (@tokens == 0 || $tokens[-1][1] =~ /\n\z/xms) && s/$lex_line_code//xms) { push @tokens, [ code => $1 ]; } elsif(s/$lex_tag_start//xms) { $in_tag = 1; my $chomp = $1; if($chomp) { push @tokens, [ prechomp => $chomp ]; } } elsif(s/$lex_text//xms) { push @tokens, [ text => $1 ]; } else { confess "Oops: Unreached code, near" . p($_); } } if($in_tag) { # calculate line number my $orig_src = $_[0]; substr $orig_src, -length($_), length($_), ''; my $line = ($orig_src =~ tr/\n/\n/); $parser->_error("Malformed templates detected", neat((split /\n/, $_)[0]), ++$line, ); } #p(\@tokens); return \@tokens; } sub preprocess { my($parser, $input) = @_; # tokenization my $tokens_ref = $parser->split($input); my $code = ''; my $shortcut_table = $parser->shortcut_table; my $shortcut = join('|', map{ quotemeta } keys %shortcut_table); my $shortcut_rx = qr/\A ($shortcut)/xms; for(my $i = 0; $i < @{$tokens_ref}; $i++) { my($type, $s) = @{ $tokens_ref->[$i] }; if($type eq 'text') { my $nl = $parser->auto_chomp($tokens_ref, $i, \$s); $s =~ s/(["\\])/\\$1/gxms; # " for poor editors # $s may have single new line $nl += ($s =~ s/\n/\\n/xms); $code .= qq{print_raw "$s";}; # must set even if $s is empty $code .= qq{\n} if $nl > 0; } elsif($type eq 'code') { # shortcut commands $s =~ s/$shortcut_rx/$shortcut_table->{$1}/xms if $shortcut; $s = $parser->trim_code($s); if($s =~ /\A \s* [}] \s* \z/xms){ $code .= $s; } elsif(chomp $s) { $code .= qq{$s\n}; } else { $code .= qq{$s;}; # auto semicolon insertion } } elsif($type eq 'prechomp') { # noop, just a marker } elsif($type eq 'postchomp') { # noop, just a marker } else { $parser->_error("Oops: Unknown token: $s ($type)"); } } print STDOUT $code, "\n" if _DUMP_PROTO; return $code; } sub BUILD { my($parser) = @_; $parser->_init_basic_symbols(); $parser->init_symbols(); return; } # The grammer sub _init_basic_symbols { my($parser) = @_; $parser->symbol('(end)')->is_block_end(1); # EOF # prototypes of value symbols foreach my $type (qw(name variable literal)) { my $s = $parser->symbol("($type)"); $s->arity($type); $s->set_nud( $parser->can("nud_$type") ); } # common separators $parser->symbol(';')->set_nud(\&nud_separator); $parser->define_pair('(' => ')'); $parser->define_pair('{' => '}'); $parser->define_pair('[' => ']'); $parser->symbol(',') ->is_comma(1); $parser->symbol('=>') ->is_comma(1); # common commands $parser->symbol('print') ->set_std(\&std_print); $parser->symbol('print_raw')->set_std(\&std_print); # special literals $parser->define_literal(nil => undef); $parser->define_literal(true => 1); $parser->define_literal(false => 0); # special tokens $parser->symbol('__FILE__')->set_nud(\&nud_current_file); $parser->symbol('__LINE__')->set_nud(\&nud_current_line); $parser->symbol('__ROOT__')->set_nud(\&nud_current_vars); return; } sub init_basic_operators { my($parser) = @_; # define operator precedence $parser->prefix('{', 256, \&nud_brace); $parser->prefix('[', 256, \&nud_brace); $parser->infix('(', 256, \&led_call); $parser->infix('.', 256, \&led_dot); $parser->infix('[', 256, \&led_fetch); $parser->prefix('(', 256, \&nud_paren); $parser->prefix('!', 200)->is_logical(1); $parser->prefix('+', 200); $parser->prefix('-', 200); $parser->prefix('+^', 200); # numeric bitwise negate $parser->infix('*', 190); $parser->infix('/', 190); $parser->infix('%', 190); $parser->infix('x', 190); $parser->infix('+&', 190); # numeric bitwise and $parser->infix('+', 180); $parser->infix('-', 180); $parser->infix('~', 180); # connect $parser->infix('+|', 180); # numeric bitwise or $parser->infix('+^', 180); # numeric bitwise xor $parser->prefix('defined', 170, \&nud_defined); # named unary operator $parser->infix('<', 160)->is_logical(1); $parser->infix('<=', 160)->is_logical(1); $parser->infix('>', 160)->is_logical(1); $parser->infix('>=', 160)->is_logical(1); $parser->infix('==', 150)->is_logical(1); $parser->infix('!=', 150)->is_logical(1); $parser->infix('<=>', 150); $parser->infix('cmp', 150); $parser->infix('~~', 150); $parser->infix('|', 140, \&led_pipe); $parser->infix('&&', 130)->is_logical(1); $parser->infix('||', 120)->is_logical(1); $parser->infix('//', 120)->is_logical(1); $parser->infix('min', 120); $parser->infix('max', 120); $parser->infix('..', 110, \&led_range); $parser->symbol(':'); $parser->infixr('?', 100, \&led_ternary); $parser->assignment('=', 90); $parser->assignment('+=', 90); $parser->assignment('-=', 90); $parser->assignment('*=', 90); $parser->assignment('/=', 90); $parser->assignment('%=', 90); $parser->assignment('~=', 90); $parser->assignment('&&=', 90); $parser->assignment('||=', 90); $parser->assignment('//=', 90); $parser->make_alias('!' => 'not')->ubp(70); $parser->make_alias('&&' => 'and')->lbp(60); $parser->make_alias('||' => 'or') ->lbp(50); return; } sub init_symbols { my($parser) = @_; my $s; # syntax specific separators $parser->symbol('{'); $parser->symbol('}')->is_block_end(1); # block end $parser->symbol('->'); $parser->symbol('else'); $parser->symbol('with'); $parser->symbol('::'); # operators $parser->init_basic_operators(); # statements $s = $parser->symbol('if'); $s->set_std(\&std_if); $s->can_be_modifier(1); $parser->symbol('for') ->set_std(\&std_for); $parser->symbol('while' ) ->set_std(\&std_while); $parser->symbol('given') ->set_std(\&std_given); $parser->symbol('when') ->set_std(\&std_when); $parser->symbol('default') ->set_std(\&std_when); $parser->symbol('include') ->set_std(\&std_include); $parser->symbol('last') ->set_std(\&std_last); $parser->symbol('next') ->set_std(\&std_next); # macros $parser->symbol('cascade') ->set_std(\&std_cascade); $parser->symbol('macro') ->set_std(\&std_proc); $parser->symbol('around') ->set_std(\&std_proc); $parser->symbol('before') ->set_std(\&std_proc); $parser->symbol('after') ->set_std(\&std_proc); $parser->symbol('block') ->set_std(\&std_macro_block); $parser->symbol('super') ->set_std(\&std_super); $parser->symbol('override') ->set_std(\&std_override); $parser->symbol('->') ->set_nud(\&nud_lambda); # lexical variables/constants stuff $parser->symbol('constant')->set_nud(\&nud_constant); $parser->symbol('my' )->set_nud(\&nud_constant); return; } sub _build_iterator_element { return { index => \&iterator_index, count => \&iterator_count, is_first => \&iterator_is_first, is_last => \&iterator_is_last, body => \&iterator_body, size => \&iterator_size, max_index => \&iterator_max_index, peek_next => \&iterator_peek_next, peek_prev => \&iterator_peek_prev, cycle => \&iterator_cycle, }; } sub symbol { my($parser, $id, $lbp) = @_; my $stash = $parser->symbol_table; my $s = $stash->{$id}; if(defined $s) { if(defined $lbp) { $s->lbp($lbp); } } else { # create a new symbol $s = $parser->symbol_class->new(id => $id, lbp => $lbp || 0); $stash->{$id} = $s; } return $s; } sub define_pair { my($parser, $left, $right) = @_; $parser->symbol($left) ->counterpart($right); $parser->symbol($right)->counterpart($left); return; } # the low-level tokenizer. Don't use it directly, use advance() instead. sub tokenize { my($parser) = @_; local *_ = \$parser->{input}; my $comment_rx = $parser->comment_pattern; my $id_rx = $parser->identity_pattern; my $count = 0; TRY: { /\G (\s*) /xmsgc; $count += ( $1 =~ tr/\n/\n/); $parser->following_newline( $count ); if(/\G $comment_rx /xmsgc) { redo TRY; # retry } elsif(/\G ($id_rx)/xmsgc){ return [ name => $1 ]; } elsif(/\G ($NUMBER | $STRING)/xmsogc){ return [ literal => $1 ]; } elsif(/\G ($OPERATOR_TOKEN)/xmsogc){ return [ operator => $1 ]; } elsif(/\G (\S+)/xmsgc) { Carp::confess("Oops: Unexpected token '$1'"); } else { # empty return [ special => '(end)' ]; } } } sub next_token_is { my($parser, $token) = @_; return $parser->next_token->[1] eq $token; } # the high-level tokenizer sub advance { my($parser, $expect) = @_; my $t = $parser->token; if(defined($expect) && $t->id ne $expect) { $parser->_unexpected(neat($expect), $t); } $parser->near_token($t); my $stash = $parser->symbol_table; $t = $parser->next_token; if($t->[0] eq 'special') { return $parser->token( $stash->{ $t->[1] } ); } $parser->statement_is_finished( $parser->following_newline != 0 ); my $line = $parser->line( $parser->line + $parser->following_newline ); $parser->next_token( $parser->tokenize() ); my($arity, $id) = @{$t}; if( $arity eq "name" && $parser->next_token_is("=>") ) { $arity = "literal"; } print STDOUT "[$arity => $id] #$line\n" if _DUMP_TOKEN; my $symbol; if($arity eq "literal") { $symbol = $parser->symbol('(literal)')->clone( id => $id, value => $parser->parse_literal($id) ); } elsif($arity eq "operator") { $symbol = $stash->{$id}; if(not defined $symbol) { $parser->_error("Unknown operator '$id'"); } $symbol = $symbol->clone( arity => $arity, # to make error messages clearer ); } else { # name # find_or_create() returns a cloned symbol, # so there's not need to clone() here $symbol = $parser->find_or_create($id); } $symbol->line($line); return $parser->token($symbol); } sub parse_literal { my($parser, $literal) = @_; return literal_to_value($literal); } sub nud_name { my($parser, $symbol) = @_; return $symbol->clone( arity => 'name', ); } sub nud_variable { my($parser, $symbol) = @_; return $symbol->clone( arity => 'variable', ); } sub nud_literal { my($parser, $symbol) = @_; return $symbol->clone( arity => 'literal', ); } sub default_nud { my($parser, $symbol) = @_; return $symbol->clone(); # as is } sub default_led { my($parser, $symbol) = @_; $parser->near_token($parser->token); $parser->_error( sprintf 'Missing operator (%s): %s', $symbol->arity, $symbol->id); } sub default_std { my($parser, $symbol) = @_; $parser->near_token($parser->token); $parser->_error( sprintf 'Not a statement (%s): %s', $symbol->arity, $symbol->id); } sub expression { my($parser, $rbp) = @_; my $t = $parser->token; $parser->advance(); my $left = $t->nud($parser); while($rbp < $parser->token->lbp) { $t = $parser->token; $parser->advance(); $left = $t->led($parser, $left); } return $left; } sub expression_list { my($parser) = @_; my @list; while(1) { if($parser->token->is_value) { push @list, $parser->expression(0); } if(!$parser->token->is_comma) { last; } $parser->advance(); # comma } return \@list; } # for left associative infix operators sub led_infix { my($parser, $symbol, $left) = @_; return $parser->binary( $symbol, $left, $parser->expression($symbol->lbp) ); } sub infix { my($parser, $id, $bp, $led) = @_; my $symbol = $parser->symbol($id, $bp); $symbol->set_led($led || \&led_infix); return $symbol; } # for right associative infix operators sub led_infixr { my($parser, $symbol, $left) = @_; return $parser->binary( $symbol, $left, $parser->expression($symbol->lbp - 1) ); } sub infixr { my($parser, $id, $bp, $led) = @_; my $symbol = $parser->symbol($id, $bp); $symbol->set_led($led || \&led_infixr); return $symbol; } # for prefix operators sub prefix { my($parser, $id, $bp, $nud) = @_; my $symbol = $parser->symbol($id); $symbol->ubp($bp); $symbol->set_nud($nud || \&nud_prefix); return $symbol; } sub nud_prefix { my($parser, $symbol) = @_; my $un = $symbol->clone(arity => 'unary'); $parser->reserve($un); $un->first($parser->expression($symbol->ubp)); return $un; } sub led_assignment { my($parser, $symbol, $left) = @_; $parser->_error("Assignment ($symbol) is forbidden", $left); } sub assignment { my($parser, $id, $bp) = @_; $parser->symbol($id, $bp)->set_led(\&led_assignment); return; } # the ternary is a right associative operator sub led_ternary { my($parser, $symbol, $left) = @_; my $if = $symbol->clone(arity => 'if'); $if->first($left); $if->second([$parser->expression( $symbol->lbp - 1 )]); $parser->advance(":"); $if->third([$parser->expression( $symbol->lbp - 1 )]); return $if; } sub is_valid_field { my($parser, $token) = @_; my $arity = $token->arity; if($arity eq "name") { return 1; } elsif($arity eq "literal") { return is_int($token->id); } return 0; } sub led_dot { my($parser, $symbol, $left) = @_; my $t = $parser->token; if(!$parser->is_valid_field($t)) { $parser->_unexpected("a field name", $t); } my $dot = $symbol->clone( arity => "field", first => $left, second => $t->clone(arity => 'literal'), ); $t = $parser->advance(); if($t->id eq "(") { $parser->advance(); # "(" $dot->third( $parser->expression_list() ); $parser->advance(")"); $dot->arity("methodcall"); } return $dot; } sub led_fetch { # $h[$field] my($parser, $symbol, $left) = @_; my $fetch = $symbol->clone( arity => "field", first => $left, second => $parser->expression(0), ); $parser->advance("]"); return $fetch; } sub call { my($parser, $function, @args) = @_; if(not ref $function) { $function = $parser->symbol('(name)')->clone( arity => 'name', id => $function, line => $parser->line, ); } return $parser->symbol('(call)')->clone( arity => 'call', first => $function, second => \@args, ); } sub led_call { my($parser, $symbol, $left) = @_; my $call = $symbol->clone(arity => 'call'); $call->first($left); $call->second( $parser->expression_list() ); $parser->advance(")"); return $call; } sub led_pipe { # filter my($parser, $symbol, $left) = @_; # a | b -> b(a) return $parser->call($parser->expression($symbol->lbp), $left); } sub led_range { # x .. y my($parser, $symbol, $left) = @_; return $symbol->clone( arity => 'range', first => $left, second => $parser->expression(0), ); } sub nil { my($parser) = @_; return $parser->symbol('nil')->nud($parser); } sub nud_defined { my($parser, $symbol) = @_; $parser->reserve( $symbol->clone() ); # prefix:<defined> is a syntactic sugar to $a != nil return $parser->binary( '!=', $parser->expression($symbol->ubp), $parser->nil, ); } # for special literals (e.g. nil, true, false) sub nud_special { my($parser, $symbol) = @_; return $symbol->first; } sub define_literal { # special literals my($parser, $id, $value) = @_; my $symbol = $parser->symbol($id); $symbol->first( $symbol->clone( arity => defined($value) ? 'literal' : 'nil', value => $value, ) ); $symbol->set_nud(\&nud_special); $symbol->is_defined(1); return $symbol; } sub new_scope { my($parser) = @_; push @{ $parser->scope }, {}; return; } sub pop_scope { my($parser) = @_; pop @{ $parser->scope }; return; } sub undefined_name { my($parser, $name) = @_; if($name =~ /\A \$/xms) { return $parser->symbol_table->{'(variable)'}->clone( id => $name, ); } else { return $parser->symbol_table->{'(name)'}->clone( id => $name, ); } } sub find_or_create { # find a name from all the scopes my($parser, $name) = @_; my $s; foreach my $scope(reverse @{$parser->scope}){ $s = $scope->{$name}; if(defined $s) { return $s->clone(); } } $s = $parser->symbol_table->{$name}; return defined($s) ? $s : $parser->undefined_name($name); } sub reserve { # reserve a name to the scope my($parser, $symbol) = @_; if($symbol->arity ne 'name' or $symbol->is_reserved) { return $symbol; } my $top = $parser->scope->[-1]; my $t = $top->{$symbol->id}; if($t) { if($t->is_reserved) { return $symbol; } if($t->arity eq "name") { $parser->_error("Already defined: $symbol"); } } $top->{$symbol->id} = $symbol; $symbol->is_reserved(1); #$symbol->scope($top); return $symbol; } sub define { # define a name to the scope my($parser, $symbol) = @_; my $top = $parser->scope->[-1]; my $t = $top->{$symbol->id}; if(defined $t) { $parser->_error($t->is_reserved ? "Already is_reserved: $t" : "Already defined: $t"); } $top->{$symbol->id} = $symbol; $symbol->is_defined(1); $symbol->is_reserved(0); $symbol->remove_nud(); $symbol->remove_led(); $symbol->remove_std(); $symbol->lbp(0); #$symbol->scope($top); return $symbol; } sub print { my($parser, @args) = @_; return $parser->symbol('print')->clone( arity => 'print', first => \@args, line => $parser->line, ); } sub binary { my($parser, $symbol, $lhs, $rhs) = @_; if(!ref $symbol) { # operator $symbol = $parser->symbol($symbol); } if(!ref $lhs) { # literal $lhs = $parser->symbol('(literal)')->clone( id => $lhs, ); } if(!ref $rhs) { # literal $rhs = $parser->symbol('(literal)')->clone( id => $rhs, ); } return $symbol->clone( arity => 'binary', first => $lhs, second => $rhs, ); } sub define_function { my($parser, @names) = @_; foreach my $name(@names) { my $s = $parser->symbol($name); $s->set_nud(\&nud_name); $s->is_defined(1); } return; } sub finish_statement { my($parser, $expr) = @_; my $t = $parser->token; if($t->can_be_modifier) { $parser->advance(); $expr = $t->std($parser, $expr); $t = $parser->token; } if($t->is_block_end or $parser->statement_is_finished) { # noop } elsif($t->id eq ";") { $parser->advance(); } else { $parser->_unexpected("a semicolon or block end", $t); } return $expr; } sub statement { # process one or more statements my($parser) = @_; my $t = $parser->token; if($t->id eq ";"){ $parser->advance(); # ";" return; } if($t->has_std) { # is $t a statement? $parser->reserve($t); $parser->advance(); # std() can return a list of nodes return $t->std($parser); } my $expr = $parser->auto_command( $parser->expression(0) ); return $parser->finish_statement($expr); } sub auto_command { my($parser, $expr) = @_; if($expr->is_statement) { # expressions can produce pure statements (e.g. assignment ) return $expr; } else { return $parser->print($expr); } } sub statements { # process statements my($parser) = @_; my @a; for(my $t = $parser->token; !$t->is_block_end; $t = $parser->token) { push @a, $parser->statement(); } return \@a; } sub block { my($parser) = @_; $parser->new_scope(); $parser->advance("{"); my $a = $parser->statements(); $parser->advance("}"); $parser->pop_scope(); return $a; } sub nud_paren { my($parser, $symbol) = @_; my $expr = $parser->expression(0); $parser->advance( $symbol->counterpart ); return $expr; } # for object literals sub nud_brace { my($parser, $symbol) = @_; my $list = $parser->expression_list(); $parser->advance($symbol->counterpart); return $symbol->clone( arity => 'composer', first => $list, ); } # iterator variables ($~iterator) # $~iterator . NAME | NAME() sub nud_iterator { my($parser, $symbol) = @_; my $iterator = $symbol->clone(); if($parser->token->id eq ".") { $parser->advance(); my $t = $parser->token; if(!any_in($t->arity, qw(variable name))) { $parser->_unexpected("a field name", $t); } my $generator = $parser->iterator_element->{$t->value}; if(!$generator) { $parser->_error("Undefined iterator element: $t"); } $parser->advance(); # element name my $args; if($parser->token->id eq "(") { $parser->advance(); $args = $parser->expression_list(); $parser->advance(")"); } $iterator->second($t); return $generator->($parser, $iterator, @{$args}); } return $iterator; } sub nud_constant { my($parser, $symbol) = @_; my $t = $parser->token; my $expect = $symbol->id eq 'constant' ? 'name' : $symbol->id eq 'my' ? 'variable' : die "Oops: $symbol"; if($t->arity ne $expect) { $parser->_unexpected("a $expect", $t); } $parser->define($t)->arity("name"); $parser->advance(); $parser->advance("="); return $symbol->clone( arity => 'constant', first => $t, second => $parser->expression(0), is_statement => 1, ); } my $lambda_id = 0; sub lambda { my($parser, $proto) = @_; my $name = $parser->symbol('(name)')->clone( id => sprintf('lambda@%s:%d', $parser->file, $lambda_id++), ); return $parser->symbol('(name)')->clone( arity => 'proc', id => 'macro', first => $name, line => $proto->line, ); } # -> $x { ... } sub nud_lambda { my($parser, $symbol) = @_; my $pointy = $parser->lambda($symbol); $parser->new_scope(); my @params; if($parser->token->id ne "{") { # has params my $paren = ($parser->token->id eq "("); $parser->advance("(") if $paren; # optional my $t = $parser->token; while($t->arity eq "variable") { push @params, $t; $parser->define($t); $t = $parser->advance(); if($t->id eq ",") { $t = $parser->advance(); # "," } else { last; } } $parser->advance(")") if $paren; } $pointy->second( \@params ); $parser->advance("{"); $pointy->third($parser->statements()); $parser->advance("}"); $parser->pop_scope(); return $symbol->clone( arity => 'lambda', first => $pointy, ); } sub nud_current_file { my($self, $symbol) = @_; my $file = $self->file; return $symbol->clone( arity => 'literal', value => ref($file) ? '<string>' : $file, ); } sub nud_current_line { my($self, $symbol) = @_; return $symbol->clone( arity => 'literal', value => $symbol->line, ); } sub nud_current_vars { my($self, $symbol) = @_; return $symbol->clone( arity => 'vars', ); } sub nud_separator { my($self, $symbol) = @_; $self->_error("Invalid expression found", $symbol); } # -> VARS { STATEMENTS } # -> { STATEMENTS } # { STATEMENTS } sub pointy { my($parser, $pointy, $in_for) = @_; my @params; $parser->new_scope(); if($parser->token->id eq "->") { $parser->advance(); if($parser->token->id ne "{") { my $paren = ($parser->token->id eq "("); $parser->advance("(") if $paren; my $t = $parser->token; while($t->arity eq "variable") { push @params, $t; $parser->define($t); if($in_for) { $parser->define_iterator($t); } $t = $parser->advance(); if($t->id eq ",") { $t = $parser->advance(); # "," } else { last; } } $parser->advance(")") if $paren; } } $pointy->second( \@params ); $parser->advance("{"); $pointy->third($parser->statements()); $parser->advance("}"); $parser->pop_scope(); return; } sub iterator_name { my($parser, $var) = @_; # $foo -> $~foo (my $it_name = $var->id) =~ s/\A (\$?) /${1}~/xms; return $it_name; } sub define_iterator { my($parser, $var) = @_; my $it = $parser->symbol( $parser->iterator_name($var) )->clone( arity => 'iterator', first => $var, ); $parser->define($it); $it->set_nud(\&nud_iterator); return $it; } sub std_for { my($parser, $symbol) = @_; my $proc = $symbol->clone(arity => 'for'); $proc->first( $parser->expression(0) ); $parser->pointy($proc, 1); # for-else support if($parser->token eq 'else') { $parser->advance(); my $else = $parser->block(); $proc = $symbol->clone( arity => 'for_else', first => $proc, second => $else, ) } return $proc; } sub std_while { my($parser, $symbol) = @_; my $proc = $symbol->clone(arity => 'while'); $proc->first( $parser->expression(0) ); $parser->pointy($proc); return $proc; } # macro name -> { ... } sub std_proc { my($parser, $symbol) = @_; my $macro = $symbol->clone(arity => "proc"); my $name = $parser->token; if($name->arity ne "name") { $parser->_unexpected("a name", $name); } $parser->define_function($name->id); $macro->first($name); $parser->advance(); $parser->pointy($macro); return $macro; } # block name -> { ... } # block name | filter -> { ... } sub std_macro_block { my($parser, $symbol) = @_; my $macro = $symbol->clone(arity => "proc"); my $name = $parser->token; if($name->arity ne "name") { $parser->_unexpected("a name", $name); } # auto filters my @filters; my $t = $parser->advance(); while($t->id eq "|") { $t = $parser->advance(); if($t->arity ne "name") { $parser->_unexpected("a name", $name); } my $filter = $t->clone(); $t = $parser->advance(); my $args; if($t->id eq "(") { $parser->advance(); $args = $parser->expression_list(); $t = $parser->advance(")"); } push @filters, $args ? $parser->call($filter, @{$args}) : $filter; } $parser->define_function($name->id); $macro->first($name); $parser->pointy($macro); my $call = $parser->call($macro->first); if(@filters) { foreach my $filter(@filters) { # apply filters $call = $parser->call($filter, $call); } } # std() can return a list return( $macro, $parser->print($call) ); } sub std_override { # synonym to 'around' my($parser, $symbol) = @_; return $parser->std_proc($symbol->clone(id => 'around')); } sub std_if { my($parser, $symbol, $expr) = @_; my $if = $symbol->clone(arity => "if"); $if->first( $parser->expression(0) ); if(defined $expr) { # statement modifier $if->second([$expr]); return $if; } $if->second( $parser->block() ); my $top_if = $if; my $t = $parser->token; while($t->id eq "elsif") { $parser->reserve($t); $parser->advance(); # "elsif" my $elsif = $t->clone(arity => "if"); $elsif->first( $parser->expression(0) ); $elsif->second( $parser->block() ); $if->third([$elsif]); $if = $elsif; $t = $parser->token; } if($t->id eq "else") { $parser->reserve($t); $t = $parser->advance(); # "else" $if->third( $t->id eq "if" ? [$parser->statement()] : $parser->block()); } return $top_if; } sub std_given { my($parser, $symbol) = @_; my $given = $symbol->clone(arity => 'given'); $given->first( $parser->expression(0) ); local $parser->{in_given} = 1; $parser->pointy($given); if(!(defined $given->second && @{$given->second})) { # if no topic vars $given->second([ $parser->symbol('($_)')->clone(arity => 'variable' ) ]); } $parser->build_given_body($given, "when"); return $given; } # when/default sub std_when { my($parser, $symbol) = @_; if(!$parser->in_given) { $parser->_error("You cannot use $symbol blocks outside given blocks"); } my $proc = $symbol->clone(arity => 'when'); if($symbol->id eq "when") { $proc->first( $parser->expression(0) ); } $proc->second( $parser->block() ); return $proc; } sub _only_white_spaces { my($s) = @_; return $s->arity eq "literal" && $s->value =~ m{\A [ \t\r\n]* \z}xms } sub build_given_body { my($parser, $given, $expect) = @_; my($topic) = @{$given->second}; # make if-elsif-else chain from given-when my $if; my $elsif; my $else; foreach my $when(@{$given->third}) { if($when->arity ne $expect) { # ignore white space if($when->id eq "print_raw" && !grep { !_only_white_spaces($_) } @{$when->first}) { next; } $parser->_unexpected("$expect blocks", $when); } $when->arity("if"); # change the arity if(defined(my $test = $when->first)) { # when if(!$test->is_logical) { $when->first( $parser->binary('~~', $topic, $test) ); } } else { # default $when->first( $parser->symbol('true')->nud($parser) ); $else = $when; next; } if(!defined $if) { $if = $when; $elsif = $when; } else { $elsif->third([$when]); $elsif = $when; } } if(defined $else) { # default if(defined $elsif) { $elsif->third([$else]); } else { $if = $else; # only default } } $given->third(defined $if ? [$if] : undef); return; } sub std_include { my($parser, $symbol) = @_; my $arg = $parser->barename(); my $vars = $parser->localize_vars(); my $stmt = $symbol->clone( first => $arg, second => $vars, arity => 'include', ); return $parser->finish_statement($stmt); } sub std_print { my($parser, $symbol) = @_; my $args; if($parser->token->id ne ";") { $args = $parser->expression_list(); } my $stmt = $symbol->clone( arity => 'print', first => $args, ); return $parser->finish_statement($stmt); } # for cascade() and include() sub barename { my($parser) = @_; my $t = $parser->token; if($t->arity ne 'name' or $t->is_defined) { # string literal for 'cascade', or any expression for 'include' return $parser->expression(0); } # path::to::name my @parts; push @parts, $t; $parser->advance(); while(1) { my $t = $parser->token; if($t->id eq "::") { $t = $parser->advance(); # "::" if($t->arity ne "name") { $parser->_unexpected("a name", $t); } push @parts, $t; $parser->advance(); } else { last; } } return \@parts; } # NOTHING | { expression-list } sub localize_vars { my($parser) = @_; if($parser->token->id eq "{") { $parser->advance(); $parser->new_scope(); my $vars = $parser->expression_list(); $parser->pop_scope(); $parser->advance("}"); return $vars; } return undef; } sub std_cascade { my($parser, $symbol) = @_; my $base; if($parser->token->id ne "with") { $base = $parser->barename(); } my $components; if($parser->token->id eq "with") { $parser->advance(); # "with" my @c = $parser->barename(); while($parser->token->id eq ",") { $parser->advance(); # "," push @c, $parser->barename(); } $components = \@c; } my $vars = $parser->localize_vars(); my $stmt = $symbol->clone( arity => 'cascade', first => $base, second => $components, third => $vars, ); return $parser->finish_statement($stmt); } sub std_super { my($parser, $symbol) = @_; my $stmt = $symbol->clone(arity => 'super'); return $parser->finish_statement($stmt); } sub std_next { my($parser, $symbol) = @_; my $stmt = $symbol->clone(arity => 'loop_control', id => 'next'); return $parser->finish_statement($stmt); } sub std_last { my($parser, $symbol) = @_; my $stmt = $symbol->clone(arity => 'loop_control', id => 'last'); return $parser->finish_statement($stmt); } # iterator elements sub bad_iterator_args { my($parser, $iterator) = @_; $parser->_error("Wrong number of arguments for $iterator." . $iterator->second); } sub iterator_index { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator return $iterator; } sub iterator_count { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator + 1 return $parser->binary('+', $iterator, 1); } sub iterator_is_first { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator == 0 return $parser->binary('==', $iterator, 0); } sub iterator_is_last { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator == $~iterator.max_index return $parser->binary('==', $iterator, $parser->iterator_max_index($iterator)); } sub iterator_body { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator.body return $iterator->clone( arity => 'iterator_body', ); } sub iterator_size { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator.max_index + 1 return $parser->binary('+', $parser->iterator_max_index($iterator), 1); } sub iterator_max_index { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # __builtin_max_index($~iterator.body) return $parser->symbol('max_index')->clone( arity => 'unary', first => $parser->iterator_body($iterator), ); } sub _iterator_peek { my($parser, $iterator, $pos) = @_; # $~iterator.body[ $~iterator.index + $pos ] return $parser->binary('[', $parser->iterator_body($iterator), $parser->binary('+', $parser->iterator_index($iterator), $pos), ); } sub iterator_peek_next { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; return $parser->_iterator_peek($iterator, +1); } sub iterator_peek_prev { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator.is_first ? nil : <prev> return $parser->symbol('?')->clone( arity => 'if', first => $parser->iterator_is_first($iterator), second => [$parser->nil], third => [$parser->_iterator_peek($iterator, -1)], ); } sub iterator_cycle { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args < 2; # $iterator.cycle("foo", "bar", "baz") makes: # ($tmp = $~iterator % n) == 0 ? "foo" # : $tmp == 1 ? "bar" # : "baz" $parser->new_scope(); my $mod = $parser->binary('%', $iterator, scalar @args); # for the second time my $tmp = $parser->symbol('($cycle)')->clone(arity => 'name'); # for the first time my $cond = $iterator->clone( arity => 'constant', first => $tmp, second => $mod, ); my $parent = $iterator->clone( arity => 'if', first => $parser->binary('==', $cond, 0), second => [ $args[0] ], ); my $child = $parent; my $last = pop @args; for(my $i = 1; $i < @args; $i++) { my $nth = $iterator->clone( arity => 'if', id => "$iterator.cycle: $i", first => $parser->binary('==', $tmp, $i), second => [$args[$i]], ); $child->third([$nth]); $child = $nth; } $child->third([$last]); $parser->pop_scope(); return $parent; } # utils sub make_alias { # alas(from => to) my($parser, $from, $to) = @_; my $stash = $parser->symbol_table; if(exists $parser->symbol_table->{$to}) { Carp::confess( "Cannot make an alias to an existing symbol ($from => $to / " . p($parser->symbol_table->{$to}) .")"); } # make a snapshot return $stash->{$to} = $parser->symbol($from)->clone( value => $to, # real id ); } sub not_supported { my($parser, $symbol) = @_; $parser->_error("'$symbol' is not supported"); } sub _unexpected { my($parser, $expected, $got) = @_; if(defined($got) && $got ne ";") { if($got eq '(end)') { $parser->_error("Expected $expected, but reached EOF"); } else { $parser->_error("Expected $expected, but got " . neat("$got")); } } else { $parser->_error("Expected $expected"); } } sub _error { my($parser, $message, $near, $line) = @_; $near ||= $parser->near_token || ";"; if($near ne ";" && $message !~ /\b \Q$near\E \b/xms) { $message .= ", near $near"; } die $parser->make_error($message . ", while parsing templates", $parser->file, $line || $parser->line); } no Mouse; __PACKAGE__->meta->make_immutable; __END__ =head1 NAME Text::Xslate::Parser - The base class of template parsers =head1 DESCRIPTION This is a parser to build the abstract syntax tree from templates. The basis of the parser is Top Down Operator Precedence. =head1 SEE ALSO L<http://javascript.crockford.com/tdop/tdop.html> - Top Down Operator Precedence (Douglas Crockford) L<Text::Xslate> L<Text::Xslate::Compiler> L<Text::Xslate::Symbol> =cut
waniji/isucon3-yosen
perl/local/lib/perl5/x86_64-linux/Text/Xslate/Parser.pm
Perl
mit
47,591
# !!!!!!! 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'; 3041 3096 309D 309F 1B001 1F200 END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/lib/Sc/Hira.pl
Perl
mit
447
package Crypt::OpenPGP::Plaintext; use strict; use Crypt::OpenPGP::Buffer; use Crypt::OpenPGP::ErrorHandler; use base qw( Crypt::OpenPGP::ErrorHandler ); sub new { my $class = shift; my $pt = bless { }, $class; $pt->init(@_); } sub data { $_[0]->{data} } sub mode { $_[0]->{mode} } sub init { my $pt = shift; my %param = @_; if (my $data = $param{Data}) { $pt->{data} = $data; $pt->{mode} = $param{Mode} || 'b'; $pt->{timestamp} = time; $pt->{filename} = $param{Filename} || ''; } $pt; } sub parse { my $class = shift; my($buf) = @_; my $pt = $class->new; $pt->{mode} = $buf->get_char; $pt->{filename} = $buf->get_bytes($buf->get_int8); $pt->{timestamp} = $buf->get_int32; $pt->{data} = $buf->get_bytes( $buf->length - $buf->offset ); $pt; } sub save { my $pt = shift; my $buf = Crypt::OpenPGP::Buffer->new; $buf->put_char($pt->{mode}); $buf->put_int8(length $pt->{filename}); $buf->put_bytes($pt->{filename}); $buf->put_int32($pt->{timestamp}); $buf->put_bytes($pt->{data}); $buf->bytes; } 1; __END__ =head1 NAME Crypt::OpenPGP::Plaintext - A plaintext, literal-data packet =head1 SYNOPSIS use Crypt::OpenPGP::Plaintext; my $data = 'foo bar'; my $file = 'foo.txt'; my $pt = Crypt::OpenPGP::Plaintext->new( Data => $data, Filename => $file, ); my $serialized = $pt->save; =head1 DESCRIPTION I<Crypt::OpenPGP::Plaintext> implements plaintext literal-data packets, and is essentially just a container for a string of octets, along with some meta-data about the plaintext. =head1 USAGE =head2 Crypt::OpenPGP::Plaintext->new( %arg ) Creates a new plaintext data packet object and returns that object. If there are no arguments in I<%arg>, the object is created with an empty data container; this is used, for example, in I<parse> (below), to create an empty packet which is then filled from the data in the buffer. If you wish to initialize a non-empty object, I<%arg> can contain: =over 4 =item * Data A block of octets that make up the plaintext data. This argument is required (for a non-empty object). =item * Filename The name of the file that this data came from, or the name of a file where it should be saved upon extraction from the packet (after decryption, for example, if this packet is going to be encrypted). =item * Mode The mode in which the data is formatted. Valid values are C<t> and C<b>, meaning "text" and "binary", respectively. This argument is optional; I<Mode> defaults to C<b>. =back =head2 $pt->save Returns the serialized form of the plaintext object, which is the plaintext data, preceded by some meta-data describing the data. =head2 Crypt::OpenPGP::Plaintext->parse($buffer) Given I<$buffer>, a I<Crypt::OpenPGP::Buffer> object holding (or with offset pointing to) a plaintext data packet, returns a new I<Crypt::OpenPGP::Ciphertext> object, initialized with the data in the buffer. =head2 $pt->data Returns the plaintext data. =head2 $pt->mode Returns the mode of the packet (either C<t> or C<b>). =head1 AUTHOR & COPYRIGHTS Please see the Crypt::OpenPGP manpage for author, copyright, and license information. =cut
liuyangning/WX_web
xampp/perl/vendor/lib/Crypt/OpenPGP/Plaintext.pm
Perl
mit
3,315
#!/usr/bin/perl # # Copyright (c) 2006 David Thompson # da.thompson@yahoo.com # Fri Nov 17 20:41:23 PST 2006 # License: GPL # Purpose of this script is to process config files and # produce a comparision chart of values. The input files # are simple series of parameter definitions, of the form # 'name=value' pairs, whitespace and comments are correctly # ignored. Invoke on multiple config files to compare # parameter values for all files, try this, # cd /usr/local/share/uncrustify # cmpcfg.pl *.cfg # first build hashes from all input files # 1. %name is a master hash of all parameter names found # across all files, we use a hash to remember the keys, # we don't compare about the values stored for each key # 2. %table is a per file 2 dimensional hash array indexed # by the current filename and parameter; ie, this hash # stores the 'name=value' pairs on per file basis foreach my $file (@ARGV) { open FH, "<$file" or die "Can't open file: $file"; while (<FH>) { chomp; next if (/^[ \t]*$/); # ignore blank lines next if (/^[ \t]*#/); # ignore comment lines s/#.*$//; # strip trailing comments s/^[ \t]*//; # strip leading whitespace s/[ \t]*$//; # strip trailing whitespace s/[ \t]*=[ \t]*/=/; # remove whitespace around '=' $_ = lc; # lowercase everything ($name, $value) = split /=/; # extract name and value $names{$name} = $name; # master hash of all names $table{$file}{$name} = $value; # per file hash of names } close FH; } # find longest parameter name # we'll use this later for report printing foreach $name (sort keys %names) { if (length($name) > $maxlen) { $maxlen = length($name); } } $maxlen += 4; # add extra padding # return string centered in specified width sub center { ($wid, $str) = @_; $flg = 0; while (length($str) < $wid) { if ($flg) { $flg = 0; $str = " " . $str; } else { $flg = 1; $str = $str . " "; } } return $str; } # print legend for filenames $cnt = 0; foreach $file (@ARGV) { $cnt++; print " <$cnt> $file\n"; } # blank line separates legend & header print "\n"; # print header line print " " x $maxlen . " "; $cnt = 0; foreach (@ARGV) { $cnt++; $fmt = "<$cnt>"; print " ".&center(6, $fmt); } print "\n"; # print body of report, one line per parameter name foreach $name (sort keys %names) { printf "%-*s ", $maxlen, $name; foreach $file (@ARGV) { if (defined($table{$file}{$name})) { print " ".&center(6, $table{$file}{$name}); } else { # parameter not defined for this file print " ".&center(6, "*"); } } print "\n"; }
eoswald/hdb
uncrustify/scripts/cmpcfg.pl
Perl
mit
2,959
# This class exists to represent a relationship between two ::Source's within # the Sims. It will have a link back to two ::Source's. package DBIx::Class::Sims::Relationship; use 5.010_001; use strictures 2; use DDP; use DBIx::Class::Sims::Util qw( reftype ); # Requires the following attributes: # * source # * name # * info # * constraints sub new { my $class = shift; my $self = bless {@_}, $class; $self->initialize; return $self; } # Possible TODO: # 1. Identify source / target and parent / child sub initialize { my $self = shift; return; } sub name { shift->{name} } sub source { shift->{source} } sub constraints { shift->{constraints} } sub full_name { my $self = shift; return $self->source->name . '->' . $self->name; } # Yes, this method breaks ::Runner's encapsulation, but this (should) be # temporary until someone else sets this for ::Relationship or maybe ::Source # builds its relationships after ::Runner has built all ::Source objects first. sub target { my $self = shift; return $self->source->runner->{sources}{$self->short_fk_source}; } sub is_fk { my $self = shift; return exists $self->{info}{attrs}{is_foreign_key_constraint}; } sub short_fk_source { my $self = shift; (my $x = $self->{info}{source}) =~ s/.*:://; return $x; } sub is_multi_col { my $self = shift; keys %{$self->cond(@_)} > 1; } sub cond { my $self = shift; my $x = $self->{info}{cond}; if (reftype($x) eq 'CODE') { $x = $x->({ foreign_alias => 'foreign', self_alias => 'self', }); } if (reftype($x) ne 'HASH') { die "cond is not a HASH\n" . np($self->{info}); } return $x; } sub self_fk_cols { my $self = shift; return map {/^self\.(.*)/; $1} values %{$self->cond(@_)}; } sub self_fk_col { my $self = shift; return ($self->self_fk_cols(@_))[0]; } sub foreign_fk_cols { my $self = shift; return map {/^foreign\.(.*)/; $1} keys %{$self->cond(@_)}; } sub foreign_fk_col { my $self = shift; return ($self->foreign_fk_cols(@_))[0]; } sub foreign_class { my $self = shift; return $self->{info}{class}; } sub is_single_accessor { my $self = shift; return $self->{info}{attrs}{accessor} eq 'single'; } sub is_multi_accessor { return ! $_[0]->is_single_accessor; } 1; __END__ =head1 NAME DBIx::Class::Sims::Relationship - The Sims wrapper of a L<DBIx::Class::Relationship/> =head1 PURPOSE This object wraps a L<DBIx::Class::Relationship/> and provides a set of useful methods around it. =head1 METHODS =head2 name() Returns the name of this relationship. =head2 source() Returns the L<DBIx::Class::Sims::Source/> this relationships is defined in. =head2 target() Returns the L<DBIx::Class::Sims::Source/> this relationships connects to. =head2 is_fk() Returns a boolean indicating if this is a parent relationship or not. =head1 AUTHOR Rob Kinyon <rob.kinyon@gmail.com> =head1 LICENSE Copyright (c) 2013 Rob Kinyon. All Rights Reserved. This is free software, you may use it and distribute it under the same terms as Perl itself. =cut
robkinyon/dbix-class-sims
lib/DBIx/Class/Sims/Relationship.pm
Perl
mit
3,060
my $read = undef, $sum = 0; for (my $i = 0; $i < 4; $i++) { $read = <>; $sum += $read if $read % 2 == 0; }
fgomezrdz/DSA_encrypt
test.pl
Perl
mit
115
:- module(dlist,[ ]). /* HOMEWORK: Create a term_expansion/2 that will magically convert naive sort into quick sort Which algrytems are better or worse at already sorted lists? learn to spell 'algorithm' cases: % we have 100 elements with exactly 100 array indexes */ cfib(0, 1) :- !. cfib(1, 1) :- !. cfib(N, F) :- N1 is N-1, cfib(N1, F1), N2 is N-2, cfib(N2, F2), F is F1 + F2. % fibonacci.pl :- dynamic(stored/1). memo(Goal) :- stored(Goal) -> true; Goal, assertz(stored(Goal)). mfib(0,1). mfib(1,1). mfib(2,1). mfib(N,F) :- N1 is N-1, memo(mfib(N1,F1)), N2 is N-2, memo(mfib(N2,F2)), F is F1 + F2. mofib(N,F) :- (N =< 2) -> F = 1 ; (N1 is N-1, memo(mofib(N1,F1)), N2 is N-2, memo(mofib(N2,F2)), F is F1 + F2). ofib(N,F) :- Self = ofib(N,F), repeat, (arg(1,Self,N), arg(2,Self,F)), (N =< 2) -> F = 1 ; (N1 is N-1, ofib(N1,F1), N2 is N-2, ofib(N2,F2), F is F1 + F2). % interactive % [fibonacci]. % ?- fib(16,X), write('...'), nl. lmember(El, [H|T]) :- lmember_(T, El, H). lmember_(_, El, El). lmember_([H|T], El, _) :- lmember_(T, El, H). mk_test(S,lo(S), L):- numlist(1, S, L). mk_test(S,lr(S), R):- numlist(1, S, L),reverse(L,R). mk_test(S,lu(S), R):- numlist(1, S, L),random_permutation(L,R). :- dynamic(stest/2). :- forall((mk_test(50,X,Y), \+ stest(X,_)),assert(stest(X,Y))). test(lo1, [1]). test(lo2, [1,2]). test(lr2, [2,1]). test(X,Y):- stest(X,Y). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % naive sort % Naive sort is not very efficient algorithm. It generates all permutations and then it tests if the permutation is a sorted list. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% perm([], []). perm(List, [First|Perm]) :- sselect(First, List, Rest), perm(Rest, Perm). sselect(X, [X|Tail], Tail). sselect(Elem, [Head|Tail], [Head|Rest]) :- sselect(Elem, Tail, Rest). do_while_loop(Test,Goal):- repeat, once(Goal), (Test->fail; (!)). is_sorted([X,Y|T]):- !, X=<Y, is_sorted([Y|T]). is_sorted(_). is_sorted_nd(In):- List = value(In), repeat, (List = value([X,Y|T]) -> ((X=<Y->(nb_setarg(1,List,[Y|T]),fail);(!,fail))); !). :- discontiguous dlist:is_sorter/1. is_sorter(sort). % Naive sort uses the generate and test approach to solving problems which is usually utilized in case when everything else failed. However, sort is not such case. % is_sorter(naive_sort). naive_sort(List,Sorted):- perm(List,Sorted), is_sorted(Sorted). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % insert sort % Insert sort is a traditional sort algorithm. Prolog implementation of insert sort is based on idea of accumulator. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% is_sorter(insert_sort). insert_sort(List,Sorted):-i_sort(List,[],Sorted). i_sort([],Acc,Acc). i_sort([H|T],Acc,Sorted):-insert(H,Acc,NAcc),i_sort(T,NAcc,Sorted). insert(X,[Y|T],[Y|NT]):-X>Y,insert(X,T,NT). insert(X,[Y|T],[X,Y|T]):-X=<Y. insert(X,[],[X]). stest:- forall((is_sorter(A), SORT =..[A,Y,S]), forall((test(X,Y),nl,nl,dmsg(test(A,X)),dmsg(input=Y)), once((prolog_statistics:time(SORT), dmsg(output=S))))). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % bubble sort % Bubble sort is another traditional sort algorithm which is not very effective. % Again, we use accumulator to implement bubble sort. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% is_sorter(bubble_sort). bubble_sort(List,Sorted):-b_sort(List,[],Sorted). b_sort([],Acc,Acc). b_sort([H|T],Acc,Sorted):-bubble(H,T,NT,Max),b_sort(NT,[Max|Acc],Sorted). bubble(X,[],[],X). bubble(X,[Y|T],[Y|NT],Max):-X>Y,bubble(X,T,NT,Max). bubble(X,[Y|T],[X|NT],Max):-X=<Y,bubble(Y,T,NT,Max). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % merge sort % Merge sort is usually used to sort large files but its idea can be utilized to every list. If properly implemented it could be a very efficient algorithm. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % is_sorter(merge_sort). merge_sort([],[]):-!. % empty list is already sorted merge_sort([X],[X]):-!. % single element list is already sorted merge_sort(List,Sorted):- List=[_,_|_], divide_3(List,L1,L2), % list with at least two elements is divided into two parts merge_sort(L1,Sorted1),merge_sort(L2,Sorted2), % then each part is sorted merge(Sorted1,Sorted2,Sorted),!. % and sorted parts are merged merge([],L,L). merge(L,[],L):-L\=[]. merge([X|T1],[Y|T2],[X|T]):-X=<Y,merge(T1,[Y|T2],T). merge([X|T1],[Y|T2],[Y|T]):-X>Y,merge([X|T1],T2,T). % We can use distribution into even and odd elements of list is_even(E):- (0 is E /\ 1). even_odd(L,L1,L2):- partition(is_even, L, L1, L2). halve([X,Y|L],[X|L1],[Y|L2]):- !, halve(L,L1,L2). halve(X,[],X). divide_3(L,L1,L2):-even_odd(L,L1,L2),!. % or traditional distribution into first and second half (other distibutions are also possible) divide_3(L,L1,L2):-halve(L,L1,L2). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % quick sort % Quick sort is one of the fastest sort algorithms. However, its power is often overvalued. The efficiency of quick sort is sensitive to choice of pivot which is used to distribute list into two "halfs". %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% is_sorter(quick_sort). quick_sort([],[]). quick_sort([H|T],Sorted):- pivoting(H,T,L1,L2),quick_sort(L1,Sorted1),quick_sort(L2,Sorted2), append(Sorted1,[H|Sorted2],Sorted). append([], L, L). append([H|T], L, [H|R]) :- append(T, L, R). pivoting(_,[],[],[]). pivoting(H,[X|T],[X|L],G):-X=<H,pivoting(H,T,L,G). pivoting(H,[X|T],L,[X|G]):-X>H,pivoting(H,T,L,G). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Similarly to merge sort, quick sort exploits the divide and conquer method of solving problems. % The above implementation of quick sort using append is not very effective. We can write better program using accumulator. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% is_sorter(quick_sort2). quick_sort2(List,Sorted):-q_sort(List,[],Sorted). q_sort([],Acc,Acc). q_sort([H|T],Acc,Sorted):- pivoting(H,T,L1,L2), q_sort(L1,Acc,Sorted1), q_sort(L2,[H|Sorted1],Sorted). uncons(H,T,[H|T]). headOf([H|_],H). tailOf([_|T],T). % -1.404600 BTC 6,416.27186388 11,092 conj_goal(A,True,A):-True=='true',!. conj_goal(True,A,A):-True=='true',!. conj_goal(A,B,(A,B)). unlistify_clause((P:-B),(NewP:-PBody)):- !, unlistify_head(P,NewP,Pre1), unlistify_goal(B,Body), conj_goal(Pre1,Body,PBody). unlistify_clause(P,POut):- unlistify_head(P,NewP,Pre1),!, (Pre1==true-> POut= P; POut =(NewP:-Pre1)). unlistify_goal(P,P):- \+ compound(P),!. unlistify_goal((P,B),PBody):-!, unlistify_goal(P,NewP),unlistify_goal(B,Body), conj_goal(NewP,Body,PBody). unlistify_goal(P,PO):- unlistify_head(P,NewP,Pre), conj_goal(Pre,NewP,PO). unlistify_head(P,NewP,Pre):- compound(P),!,unlistify_cmp(P,NewP,'true',Pre),!. unlistify_head(P,P,'true'). unlistify_cmp(P,NewP,In,Out):- P=..[F|ARGS], unlistify_args(P,F,ARGS,ARGSO,In,Out), NewP=..[F|ARGSO]. unlistify_args(_P,_F,[],[],In,In):-!. unlistify_args(P,F,[E|ARGS],[E|ARGSO],In,Post):- \+ compound(E),!, unlistify_args(P,F,ARGS,ARGSO,In,Post). unlistify_args(P,F,[[H|T]|ARGS],[NewE|ARGSO],In,Post):- conj_goal(uncons(H,T,NewE),In,Pre),!, unlistify_args(P,F,ARGS,ARGSO,Pre,Post). unlistify_args(P,F,[E|ARGS],[NewE|ARGSO],In,Post):- unlistify_cmp(E,NewE,In,Pre), unlistify_args(P,F,ARGS,ARGSO,Pre,Post). :- fixup_exports.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_utils/prolog/logicmoo/util_dlist.pl
Perl
mit
7,448
use utf8; package eduity::Schema::Challange; # Created by DBIx::Class::Schema::Loader # DO NOT MODIFY THE FIRST PART OF THIS FILE =head1 NAME eduity::Schema::Challange =cut use strict; use warnings; use Moose; use MooseX::NonMoose; use MooseX::MarkAsMethods autoclean => 1; extends 'DBIx::Class::Core'; =head1 COMPONENTS LOADED =over 4 =item * L<DBIx::Class::InflateColumn::DateTime> =item * L<DBIx::Class::InflateColumn::FS> =back =cut __PACKAGE__->load_components("InflateColumn::DateTime", "InflateColumn::FS"); =head1 TABLE: C<challanges> =cut __PACKAGE__->table("challanges"); =head1 ACCESSORS =head2 id data_type: 'integer' is_auto_increment: 1 is_nullable: 0 sequence: 'challanges_id_seq' =head2 challanged data_type: 'integer' is_nullable: 0 =head2 challangeby data_type: 'integer' is_nullable: 0 =head2 created data_type: 'timestamp with time zone' default_value: current_timestamp is_nullable: 0 original: {default_value => \"now()"} =head2 challange data_type: 'text' is_nullable: 0 =head2 complete data_type: 'boolean' default_value: false is_nullable: 0 =head2 goal data_type: 'varchar' is_nullable: 0 size: 20 =cut __PACKAGE__->add_columns( "id", { data_type => "integer", is_auto_increment => 1, is_nullable => 0, sequence => "challanges_id_seq", }, "challanged", { data_type => "integer", is_nullable => 0 }, "challangeby", { data_type => "integer", is_nullable => 0 }, "created", { data_type => "timestamp with time zone", default_value => \"current_timestamp", is_nullable => 0, original => { default_value => \"now()" }, }, "challange", { data_type => "text", is_nullable => 0 }, "complete", { data_type => "boolean", default_value => \"false", is_nullable => 0 }, "goal", { data_type => "varchar", is_nullable => 0, size => 20 }, ); =head1 PRIMARY KEY =over 4 =item * L</id> =back =cut __PACKAGE__->set_primary_key("id"); # Created by DBIx::Class::Schema::Loader v0.07024 @ 2012-09-16 11:06:41 # DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:C0cG602lY/fESIa7j5DHGQ # You can replace this text with custom code or comments, and it will be preserved on regeneration __PACKAGE__->meta->make_immutable; 1;
vendion/Eduity
lib/eduity/Schema/Challange.pm
Perl
mit
2,302
# # 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 os::windows::local::mode::liststorages; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::common::powershell::windows::liststorages; use centreon::plugins::misc; use JSON::XS; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { 'no-ps' => { name => 'no_ps', }, 'timeout:s' => { name => 'timeout', default => 50 }, 'command:s' => { name => 'command', default => 'powershell.exe' }, 'command-path:s' => { name => 'command_path' }, 'command-options:s' => { name => 'command_options', default => '-InputFormat none -NoLogo -EncodedCommand' }, 'ps-exec-only' => { name => 'ps_exec_only', }, 'ps-display' => { name => 'ps_display' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } my $map_type = { 0 => 'unknown', 1 => 'noRootDirectory', 2 => 'removableDisk', 3 => 'localDisk', 4 => 'networkDrive', 5 => 'compactDisc', 6 => 'ramDisk' }; sub manage_selection { my ($self, %options) = @_; if (!defined($self->{option_results}->{no_ps})) { my $ps = centreon::common::powershell::windows::liststorages::get_powershell(); if (defined($self->{option_results}->{ps_display})) { $self->{output}->output_add( severity => 'OK', short_msg => $ps ); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } $self->{option_results}->{command_options} .= " " . centreon::plugins::misc::powershell_encoded($ps); } my ($stdout) = centreon::plugins::misc::execute( output => $self->{output}, options => $self->{option_results}, command => $self->{option_results}->{command}, command_path => $self->{option_results}->{command_path}, command_options => $self->{option_results}->{command_options} ); if (defined($self->{option_results}->{ps_exec_only})) { $self->{output}->output_add( severity => 'OK', short_msg => $stdout ); $self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1); $self->{output}->exit(); } my $decoded; eval { $decoded = JSON::XS->new->utf8->decode($stdout); }; if ($@) { $self->{output}->add_option_msg(short_msg => "Cannot decode json response: $@"); $self->{output}->option_exit(); } return $decoded; } sub run { my ($self, %options) = @_; my $result = $self->manage_selection(); foreach (@$result) { $self->{output}->output_add( long_msg => sprintf( "'%s' [size: %s][free: %s][desc: %s][type: %s]", $_->{name}, defined($_->{size}) ? $_->{size} : '', defined($_->{freespace}) ? $_->{freespace} : '', defined($_->{desc}) ? $_->{desc} : '', $map_type->{ $_->{type} } ) ); } $self->{output}->output_add( severity => 'OK', short_msg => 'List disks:' ); $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', 'size', 'free', 'type', 'desc']); } sub disco_show { my ($self, %options) = @_; my $result = $self->manage_selection(); foreach (@$result) { $self->{output}->add_disco_entry( name => $_->{name}, size => defined($_->{size}) ? $_->{size} : '', free => defined($_->{freespace}) ? $_->{freespace} : '', type => $map_type->{ $_->{type} }, desc => defined($_->{desc}) ? $_->{desc} : '' ); } } 1; __END__ =head1 MODE List Windows disks. =over 8 =item B<--timeout> Set timeout time for command execution (Default: 50 sec) =item B<--no-ps> Don't encode powershell. To be used with --command and 'type' command. =item B<--command> Command to get information (Default: 'powershell.exe'). Can be changed if you have output in a file. To be used with --no-ps option!!! =item B<--command-path> Command path (Default: none). =item B<--command-options> Command options (Default: '-InputFormat none -NoLogo -EncodedCommand'). =item B<--ps-display> Display powershell script. =item B<--ps-exec-only> Print powershell output. =item B<--filter-type> Filter database (only wilcard 'FileSystem' can be used. In Powershell). =back =cut
centreon/centreon-plugins
os/windows/local/mode/liststorages.pm
Perl
apache-2.0
5,617
# # 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 hardware::server::sun::sfxxk::mode::failover; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::misc; 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' }, "remote" => { name => 'remote' }, "ssh-option:s@" => { name => 'ssh_option' }, "ssh-path:s" => { name => 'ssh_path' }, "ssh-command:s" => { name => 'ssh_command', default => 'ssh' }, "timeout:s" => { name => 'timeout', default => 30 }, "sudo-pasv" => { name => 'sudo_pasv' }, "command-pasv:s" => { name => 'command_pasv', default => 'showfailover' }, "command-path-pasv:s" => { name => 'command_path_pasv', default => '/opt/SUNWSMS/bin' }, "command-options-pasv:s" => { name => 'command_options_pasv', default => '-r 2>&1' }, "sudo" => { name => 'sudo' }, "command:s" => { name => 'command', default => 'showfailover' }, "command-path:s" => { name => 'command_path', default => '/opt/SUNWSMS/bin' }, "command-options:s" => { name => 'command_options', default => '2>&1' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub run { my ($self, %options) = @_; my $stdout; $stdout = centreon::plugins::misc::execute(output => $self->{output}, options => $self->{option_results}, sudo => $self->{option_results}->{sudo_pasv}, command => $self->{option_results}->{command_pasv}, command_path => $self->{option_results}->{command_path_pasv}, command_options => $self->{option_results}->{command_options_pasv}); if ($stdout =~ /SPARE/i) { $self->{output}->output_add(severity => 'OK', short_msg => "System Controller is in spare mode."); $self->{output}->display(); $self->{output}->exit(); } elsif ($stdout !~ /MAIN/i) { $self->{output}->output_add(long_msg => $stdout); $self->{output}->output_add(severity => 'UNKNOWN', short_msg => "Command problems (see additional info)."); $self->{output}->display(); $self->{output}->exit(); } $stdout = centreon::plugins::misc::execute(output => $self->{output}, options => $self->{option_results}, sudo => $self->{option_results}->{sudo}, command => $self->{option_results}->{command}, command_path => $self->{option_results}->{command_path}, command_options => $self->{option_results}->{command_options}); # 'ACTIVITING' is like 'ACTIVE' for us. $self->{output}->output_add(severity => 'OK', short_msg => "System Controller Failover Status is ACTIVE."); if ($stdout =~ /^SC Failover Status:(.*?)($|\n)/ims) { my $failover_status = $1; $failover_status = centreon::plugins::misc::trim($failover_status); # Can be FAILED or DISABLED if ($failover_status !~ /ACTIVE/i) { $self->{output}->output_add(severity => 'CRITICAL', short_msg => "System Controller Failover Status is " . $failover_status . "."); } } $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check Sun 'sfxxk' system controller failover status. =over 8 =item B<--remote> Execute command remotely in 'ssh'. =item B<--hostname> Hostname to query (need --remote). =item B<--ssh-option> Specify multiple options like the user (example: --ssh-option='-l=centreon-engine' --ssh-option='-p=52'). =item B<--ssh-path> Specify ssh command path (default: none) =item B<--ssh-command> Specify ssh command (default: 'ssh'). Useful to use 'plink'. =item B<--timeout> Timeout in seconds for the command (Default: 30). =item B<--sudo-pasv> Use 'sudo' to execute the command pasv. =item B<--command-pasv> Command to know if system controller is 'active' (Default: 'showfailover'). =item B<--command-path-pasv> Command pasv path (Default: '/opt/SUNWSMS/bin'). =item B<--command-options-pasv> Command pasv options (Default: '-r 2>&1'). =item B<--sudo> Use 'sudo' to execute the command. =item B<--command> Command to get information (Default: 'showfailover'). Can be changed if you have output in a file. =item B<--command-path> Command path (Default: '/opt/SUNWSMS/bin'). =item B<--command-options> Command options (Default: '2>&1'). =back =cut
wilfriedcomte/centreon-plugins
hardware/server/sun/sfxxk/mode/failover.pm
Perl
apache-2.0
6,346
package Google::Ads::AdWords::v201809::AdParamService::ResponseHeader; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' } __PACKAGE__->__set_name('ResponseHeader'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201809::SoapResponseHeader ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201809::AdParamService::ResponseHeader =head1 DESCRIPTION Perl data type class for the XML Schema defined element ResponseHeader from the namespace https://adwords.google.com/api/adwords/cm/v201809. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201809::AdParamService::ResponseHeader->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201809::SoapResponseHeader =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/AdParamService/ResponseHeader.pm
Perl
apache-2.0
1,038
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V9::Common::TargetRestriction; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { bidOnly => $args->{bidOnly}, targetingDimension => $args->{targetingDimension}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Common/TargetRestriction.pm
Perl
apache-2.0
1,090
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::cisco::asa::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} = '1.0'; %{$self->{modes}} = ( 'cpu' => 'centreon::common::cisco::standard::snmp::mode::cpu', 'failover' => 'network::cisco::asa::snmp::mode::failover', 'interfaces' => 'snmp_standard::mode::interfaces', 'ipsec-tunnel' => 'centreon::common::cisco::standard::snmp::mode::ipsectunnel', 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'memory' => 'centreon::common::cisco::standard::snmp::mode::memory', 'sensors' => 'snmp_standard::mode::entity', 'sessions' => 'centreon::common::cisco::standard::snmp::mode::sessions', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Cisco ASA in SNMP. !!! Be careful: Cisco ASA had an internal SNMP buffer of 512B. Use --subsetleef=20 (or lower) option !!! =cut
Sims24/centreon-plugins
network/cisco/asa/snmp/plugin.pm
Perl
apache-2.0
2,054
=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. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Analysis::RunnableDB::GeneBuilder - =head1 SYNOPSIS =head1 DESCRIPTION =head1 METHODS =cut package Bio::EnsEMBL::Analysis::RunnableDB::HiveGeneBuilder; use warnings ; use vars qw(@ISA); use strict; use Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild; use Bio::EnsEMBL::Analysis::Config::GeneBuild::GeneBuilder qw(GENEBUILDER_CONFIG_BY_LOGIC); use Bio::EnsEMBL::Analysis::Runnable::GeneBuilder; use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Utils::Argument qw (rearrange); use Bio::EnsEMBL::Analysis::Tools::GeneBuildUtils qw(id coord_string lies_inside_of_slice); use Bio::EnsEMBL::Analysis::Tools::GeneBuildUtils::GeneUtils qw(Gene_info attach_Analysis_to_Gene_no_support empty_Gene); use Bio::EnsEMBL::Analysis::Tools::GeneBuildUtils::TranscriptUtils qw(are_strands_consistent are_phases_consistent is_not_folded all_exons_are_valid intron_lengths_all_less_than_maximum); use Bio::EnsEMBL::Analysis::Tools::GeneBuildUtils::ExonUtils qw(exon_length_less_than_maximum); use Bio::EnsEMBL::Analysis::Tools::GeneBuildUtils::TranslationUtils qw(validate_Translation_coords contains_internal_stops print_Translation print_peptide); use Bio::EnsEMBL::Analysis::Tools::Logger; @ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild); =head2 new Arg [1] : Bio::EnsEMBL::Analysis::RunnableDB::GeneBuilder Function : instatiates a GeneBuilder object and reads and checks the config file Returntype: Bio::EnsEMBL::Analysis::RunnableDB::GeneBuilder Exceptions: Example : =cut sub new { my ($class,@args) = @_; my $self = $class->SUPER::new(@args); $self->read_and_check_config($GENEBUILDER_CONFIG_BY_LOGIC); return $self; } sub fetch_input{ my ($self) = @_; #fetch sequence $self->query($self->fetch_sequence); #fetch genes $self->get_Genes; #print "Have ".@{$self->input_genes}." genes to cluster\n"; #filter genes my @filtered_genes = @{$self->filter_genes($self->input_genes)}; #print "Have ".@filtered_genes." filtered genes\n"; #create genebuilder runnable my $runnable = Bio::EnsEMBL::Analysis::Runnable::GeneBuilder ->new( -query => $self->query, -analysis => $self->analysis, -genes => \@filtered_genes, -output_biotype => $self->OUTPUT_BIOTYPE, -max_transcripts_per_cluster => $self->MAX_TRANSCRIPTS_PER_CLUSTER, -min_short_intron_len => $self->MIN_SHORT_INTRON_LEN, -max_short_intron_len => $self->MAX_SHORT_INTRON_LEN, -blessed_biotypes => $self->BLESSED_BIOTYPES, -coding_only => $self->CODING_ONLY, ); $self->runnable($runnable); }; sub write_output{ my ($self) = @_; my $ga = $self->get_adaptor; my $sucessful_count = 0; logger_info("WRITE OUTPUT have ".@{$self->output}." genes to write"); foreach my $gene(@{$self->output}){ my $attach = 0; if(!$gene->analysis){ my $attach = 1; attach_Analysis_to_Gene_no_support($gene, $self->analysis); } if($attach == 0){ TRANSCRIPT:foreach my $transcript(@{$gene->get_all_Transcripts}){ if(!$transcript->analysis){ attach_Analysis_to_Gene_no_support($gene, $self->analysis); last TRANSCRIPT; } } } foreach my $transcript ( @{ $gene->get_all_Transcripts() } ) { $transcript->load ; $transcript->dbID(0); } empty_Gene($gene); eval{ $ga->store($gene); }; if($@){ warning("Failed to write gene ".id($gene)." ".coord_string($gene)." $@"); }else{ $sucessful_count++; logger_info("STORED GENE ".$gene->dbID); } } if($sucessful_count != @{$self->output}){ throw("Failed to write some genes"); } } sub output_db{ my ($self, $db) = @_; if($db){ $self->param('_output_db',$db); } if(!$self->param('_output_db')){ my $db = $self->get_dbadaptor($self->OUTPUT_DB); $self->param('_output_db',$db); } return $self->param('_output_db'); } sub get_adaptor{ my ($self) = @_; return $self->output_db->get_GeneAdaptor; } sub get_Genes{ my ($self) = @_; my @genes; foreach my $db_name(keys(%{$self->INPUT_GENES})){ my $gene_db = $self->get_dbadaptor($db_name); my $slice = $self->fetch_sequence($self->input_id, $gene_db); my $biotypes = $self->INPUT_GENES->{$db_name}; foreach my $biotype(@$biotypes){ my $genes = $slice->get_all_Genes_by_type($biotype); print "Retrieved ".@$genes." of type ".$biotype."\n"; push(@genes, @$genes); } } $self->input_genes(\@genes); } sub input_genes { my ($self, $arg) = @_; unless($self->param_is_defined('_input_genes')) { $self->param('_input_genes',[]); } if($arg){ if(!ref($arg) || ref($arg) ne 'ARRAY') { throw("Need to pass input genes an arrayref not ".$arg); } push(@{$self->param('_input_genes')},@$arg); } return $self->param('_input_genes'); } sub filter_genes{ my ($self, $genes) = @_; $genes = $self->input_genes if(!$genes); print "Have ".@$genes." to filter\n"; my @filtered; GENE:foreach my $gene(@$genes) { #throw("Genebuilder only works with one gene one transcript structures") # if(@{$gene->get_all_Transcripts} >= 2); foreach my $transcript(@{$gene->get_all_Transcripts}) { if($self->validate_Transcript($transcript)) { push(@filtered, $gene); next GENE; } else { print Gene_info($gene)." is invalid skipping\n"; next GENE; } } } return \@filtered; } sub validate_Transcript{ my ($self, $transcript) = @_; my $slice = $self->query; $slice = $transcript->slice if(!$slice); my $is_valid = 0; #basic transcript validation unless(are_strands_consistent($transcript)) { print "Transcript has inconsistent strands. "; $is_valid++; } unless(are_phases_consistent($transcript)) { print "Transcript has inconsistent exon phases. "; $is_valid++; } unless(is_not_folded($transcript)) { print "Transcript seems to be folded (with secondary structure). "; $is_valid++; } EXON:foreach my $exon(@{$transcript->get_all_Exons}){ if(exon_length_less_than_maximum($exon, $self->MAX_EXON_LENGTH)) { next EXON; } else { print "Exon in transcript exceeds max length. "; $is_valid++; last EXON; } } if(contains_internal_stops($transcript)) { print "Transcript contains internal stops. "; $is_valid++; } unless(validate_Translation_coords($transcript)) { print "Transcript contains invalid translation coords. "; $is_valid++; } return 0 if($is_valid >= 1); return 1; } #CONFIG METHODS sub hive_set_config { my ($self, $hash) = @_; # Throw is these aren't present as they should both be defined unless($self->param_is_defined('logic_name') && $self->param_is_defined('module')) { throw("You must define 'logic_name' and 'module' in the parameters hash of your analysis in the pipeline config file, ". "even if they are already defined in the analysis hash itself. This is because the hive will not allow the runnableDB ". "to read values of the analysis hash unless they are in the parameters hash. However we need to have a logic name to ". "write the genes to and this should also include the module name even if it isn't strictly necessary" ); } # Make an analysis object and set it, this will allow the module to write to the output db my $analysis = new Bio::EnsEMBL::Analysis( -logic_name => $self->param('logic_name'), -module => $self->param('module'), ); $self->analysis($analysis); # Now loop through all the keys in the parameters hash and set anything that can be set my $config_hash = $self->param('config_settings'); foreach my $config_key (keys(%{$config_hash})) { if(defined &$config_key) { $self->$config_key($config_hash->{$config_key}); } else { throw("You have a key defined in the config_settings hash (in the analysis hash in the pipeline config) that does ". "not have a corresponding getter/setter subroutine. Either remove the key or add the getter/setter. Offending ". "key:\n".$config_key ); } } foreach my $var (qw(INPUT_GENES OUTPUT_DB)) { unless($self->$var) { throw("Hive::RunnableDB::HiveGeneBuilder ".$var." config variable is not defined"); } } my @keys = keys(%{$self->INPUT_GENES}); unless(@keys) { throw("Hive::RunnableDB::GeneBuilder INPUT_GENES has needs to contain values"); } my %unique; foreach my $key(@keys) { my $biotypes = $self->INPUT_GENES->{$key}; foreach my $biotype(@$biotypes) { if(!$unique{$biotype}) { $unique{$biotype} = $key; } else { if($self->BLESSED_BIOTYPES->{$biotype}){ throw($biotype." is defined for both ".$key." and ".$unique{$biotype}. " and is found in the blessed biotype hash\n". "This is likely to cause problems for the filtering done in ". "the genebuilder code"); } else { warning($biotype." appears twice in your listing, make sure this ". "isn't for the same database otherwise it will cause issue"); } } } } $self->OUTPUT_BIOTYPE($self->analysis->logic_name) if(!$self->OUTPUT_BIOTYPE); } =head2 INPUT_GENES Arg [1] : Bio::EnsEMBL::Analysis::RunnableDB::GeneBuilder Arg [2] : Varies, tends to be boolean, a string, a arrayref or a hashref Function : Getter/Setter for config variables Returntype: again varies Exceptions: Example : =cut #Note the function of these variables is better described in the #config file itself Bio::EnsEMBL::Analysis::Config::GeneBuild::GeneBuilder sub INPUT_GENES { my ($self, $arg) = @_; if(defined $arg){ $self->param('_INPUT_GENES',$arg); } return $self->param('_INPUT_GENES'); } sub OUTPUT_DB { my ($self, $arg) = @_; if(defined $arg){ $self->param('_OUTPUT_DB',$arg); } return $self->param('_OUTPUT_DB'); } sub OUTPUT_BIOTYPE { my ($self, $arg) = @_; if(defined $arg){ $self->param('_OUTPUT_BIOTYPE',$arg); } return $self->param('_OUTPUT_BIOTYPE'); } sub MAX_TRANSCRIPTS_PER_CLUSTER { my ($self, $arg) = @_; if(defined $arg){ $self->param('_MAX_TRANSCRIPTS_PER_CLUSTER',$arg); } return $self->param('_MAX_TRANSCRIPTS_PER_CLUSTER'); } sub MIN_SHORT_INTRON_LEN { my ($self, $arg) = @_; if(defined $arg){ $self->param('_MIN_SHORT_INTRON_LEN',$arg); } return $self->param('_MIN_SHORT_INTRON_LEN'); } sub MAX_SHORT_INTRON_LEN { my ($self, $arg) = @_; if(defined $arg){ $self->param('_MAX_SHORT_INTRON_LEN',$arg); } return $self->param('_MAX_SHORT_INTRON_LEN'); } sub BLESSED_BIOTYPES { my ($self, $arg) = @_; if(defined $arg){ $self->param('_BLESSED_BIOTYPES',$arg); } return $self->param('_BLESSED_BIOTYPES'); } sub MAX_EXON_LENGTH { my ($self, $arg) = @_; if(defined $arg){ $self->param('_MAX_EXON_LENGTH',$arg); } return $self->param('_MAX_EXON_LENGTH'); } sub CODING_ONLY { my ($self, $arg) = @_; if(defined $arg){ $self->param('_CODING_ONLY',$arg); } return $self->param('_CODING_ONLY'); } 1;
mn1/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/Hive/RunnableDB/HiveGeneBuilder.pm
Perl
apache-2.0
12,318
#!/usr/bin/perl # # $Id:$ # # perl test driver use Atrshmlog; $index = shift @ARGV; $result = Atrshmlog::attach(); $area = Atrshmlog::get_area(); @r = Atrshmlog::read($area, $index); print "read : $r[0] : \n"; if ($r[0] == 0) { print "read : $r[2] : \n"; } print " \n"; exit (0); # end of main
atrsoftgmbh/atrshmlog
perl/src/tests/t_read.pl
Perl
apache-2.0
309
=head1 LICENSE Copyright [2014-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Web::Document::HTML::HomeSearch; ### Generates the search form used on the main home page and species ### home pages, with sample search terms taken from ini files use strict; use base qw(EnsEMBL::Web::Document::HTML); use EnsEMBL::Web::Form; sub render { my $self = shift; my $hub = $self->hub; my $species_defs = $hub->species_defs; my $page_species = $hub->species || 'Multi'; my $species_name = $page_species eq 'Multi' ? '' : $hub->species; my $species_display = $page_species eq 'Multi' ? '' : $species_defs->DISPLAY_NAME; my $search_url = $species_defs->ENSEMBL_WEB_ROOT . "$page_species/Search/Results"; my $html = qq{<form action="$search_url" method="GET"><div class="search" style="width: 420px; border: 1px solid lightgrey"><input type="hidden" name="site" value="ensemblthis" /><input type="hidden" name="filter_species" value="$species_name" /><input type="text" id="q" name="q" class="query" style="width: 378px" required placeholder="Search $species_display&hellip;" /><input type="submit" value="1"/></div></form>}; return sprintf '<div id="SpeciesSearch" class="js_panel home-search-flex"><input type="hidden" class="panel_type" value="SearchBox" />%s</div>', $html; } 1;
EnsemblGenomes/eg-web-parasite
modules/EnsEMBL/Web/Document/HTML/HomeSearch.pm
Perl
apache-2.0
1,896
# # 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::pfsense::snmp::mode::listpfinterfaces; use base qw(centreon::plugins::mode); use strict; use warnings; my $oid_pfInterfacesIfDescr = '.1.3.6.1.4.1.12325.1.200.1.8.2.1.2'; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { 'filter-name:s' => { name => 'filter_name' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub manage_selection { my ($self, %options) = @_; my $snmp_result = $self->{snmp}->get_table(oid => $oid_pfInterfacesIfDescr, nothing_quit => 1); $self->{pfint} = {}; foreach my $oid (keys %{$snmp_result}) { if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $snmp_result->{$oid} !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping pfInteface '" . $snmp_result->{$oid} . "'.", debug => 1); next; } $self->{pfint}->{$snmp_result->{$oid}} = { name => $snmp_result->{$oid} }; } } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->manage_selection(); foreach my $name (sort keys %{$self->{pfint}}) { $self->{output}->output_add(long_msg => "'" . $name . "'"); } $self->{output}->output_add(severity => 'OK', short_msg => 'List pfIntefaces:'); $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 $name (sort keys %{$self->{pfint}}) { $self->{output}->add_disco_entry(name => $name); } } 1; __END__ =head1 MODE List pfInteface. =over 8 =item B<--filter-name> Filter by pfinterface name. =back =cut
Tpo76/centreon-plugins
apps/pfsense/snmp/mode/listpfinterfaces.pm
Perl
apache-2.0
2,954
#!/usr/bin/perl =head1 NAME lod-materialize.pl - Materialize the files necessary to host slash-based linked data. =head1 SYNOPSIS lod-materialize.pl [OPTIONS] data.rdf http://base /path/to/www =head1 DESCRIPTION This script will materialize the necessary files for serving static linked data. Given an input file data.rdf, this script will find all triples that use a URI as subject or object that contains the supplied base URI, and serialize the matching triples to the appropriate files for serving as linked data. =head1 OPTIONS Valid command line options are: =over 4 =item * -in=FORMAT =item * -i=FORMAT Specify the name of the RDF format used by the input file. Defaults to "ntriples". =item * -out=FORMAT,FORMAT =item * -o=FORMAT,FORMAT Specify a comma-seperated list of RDF formats used for serializing the output files. Defaults to "rdfxml,turtle,ntriples". =item * --define ns=URI =item * -D ns=URI Specify a namespace mapping used by the serializers. =item * --verbose Print information about file modifications to STDERR. =item * -n Perform a dry-run without modifying any files on disk. =item * --progress[=N] Prints out periodic progress of the materialization process. If specified, the frequency argument N is used to only print the progress information on every Nth triple. =item * --concurrency=N Performs the transcoding of materialized files into secondary RDF formats using the specified number of threads. =item * --uripattern=PATTERN Specifies the URI pattern to match against URIs used in the input RDF. URIs in the input RDF are matched against this pattern appended to the base URI (http://base above). =item * --filepattern=PATTERN Specifies the path template to use in constructing data filenames. This pattern will be used to construct an absolute filename by interpreting it relative to the path specified for the document root (/path/to/www above). =item * --directoryindex=FILE If specified, will look for any files created that share a base name with a created directory (e.g. ./foo.rdf and ./foo/), move the file into the directory, and rename it to the specified directoryindex FILE name with its original file extension intact (e.g. ./foo/index.rdf). This will allow Apache's MultiViews mechanism to properly serve the data. =item * --apache Print the Apache configuration needed to serve the produced RDF files as linked data. This includes setting Multiview for content negotiation, the media type registration for RDF files and mod_rewrite rules for giving 303 redirects from resource URIs to the content negotiated data URIs. =item * --buffer-size=TRIPLES Specifies the number of output triples to buffer before flushing data to disk. This can dramatically improve performance as writes to commonly used files can be aggregated into a single large IO ops instead of many small IO ops. =back =cut use strict; use warnings; use threads; use FindBin qw($Bin); use File::Copy; use Fcntl qw(LOCK_EX LOCK_UN); use File::Spec; use File::Find; use File::Path 2.06 qw(make_path); use Getopt::Long; use Data::Dumper; use List::MoreUtils qw(part); $| = 1; my %namespaces; my $in = 'ntriples'; my $out = 'rdfxml,turtle,ntriples'; my $matchre = q</resource/(.*)>; my $outre = '/data/$1'; my $dryrun = 0; my $debug = 0; my $apache = 0; my $count = 0; my $threads = 1; my $cache_size = 1; my $files_per_dir = 0; my $dir_index; my $result = GetOptions ( "in=s" => \$in, "out=s" => \$out, "define=s" => \%namespaces, "D=s" => \%namespaces, "uripattern=s" => \$matchre, "filepattern=s" => \$outre, "verbose+" => \$debug, "n" => \$dryrun, "progress:1" => \$count, "apache" => \$apache, "concurrency|j=s" => \$threads, "filelimit|L=i" => \$files_per_dir, "directoryindex=s" => \$dir_index, "buffer-size|S=i" => \$cache_size, ); if ($in ne 'ntriples') { warn "Input for materialization must be ntriples but '$in' requested\n"; exit(2); } unless (@ARGV) { print <<"END"; Usage: $0 [OPTIONS] data.rdf http://base /path/to/www/ END exit(1); } my $file = shift or die "An RDF filename must be given"; my $url = shift or die "A URL base must be given"; my $base = shift or die "A path to the base URL must be given"; my @out = split(',', $out); my %files; my %paths; if ($url =~ m<[/]$>) { chop($url); } if ($debug) { warn "Input file : $file\n"; warn "Input format : $in\n"; warn "Output formats : " . join(', ', @out) . "\n"; warn "URL Pattern : $matchre\n"; warn "File Pattern : $outre\n"; warn "Output path : " . File::Spec->rel2abs($base) . "\n"; warn "File Limit per Directory : $files_per_dir\n" if ($files_per_dir); } if ($apache) { print "\n# Apache Configuration:\n"; print "#######################\n"; my $match = substr($matchre,1); my $redir = $outre; $redir =~ s/\\(\d+)/\$$1/g; if ($dir_index) { print "DirectoryIndex $dir_index\n\n"; } print <<"END"; Options +MultiViews AddType text/turtle .ttl AddType text/plain .nt AddType application/rdf+xml .rdf RewriteEngine On RewriteBase / RewriteRule ^${match}\$ $redir [R=303,L] ####################### END exit; } my $lodc = File::Spec->catfile( $Bin, 'lod-materialize' ); system($lodc, "--uripattern=$matchre", "--filepattern=$outre", "--progress=$count", "--directoryindex=$dir_index", $file, $url, $base); my %ext = ( rdfxml => 'rdf', 'rdfxml-abbrev' => 'rdf', turtle => 'ttl', ntriples => 'nt' ); my @new_formats = grep { $_ ne 'ntriples' } @out; my $format_string = '' . join(' ', map {qq[-f 'xmlns:$_="$namespaces{$_}"']} (keys %namespaces)); if (@new_formats) { my $i = 0; my @files; find( { no_chdir => 1, wanted => sub { local($/) = undef; return unless ($File::Find::name =~ /[.]nt$/); my $input = File::Spec->rel2abs( $File::Find::name ); push(@files, $input); } }, $base ); if ($threads == 1) { transcode_file( 1, \@files ); } else { my @partitions = part { $i++ % $threads } @files; my @threads; foreach my $pnum (0 .. $#partitions) { my $t = threads->create( \&transcode_files, $pnum, $partitions[ $pnum ] ); push(@threads, $t); } $_->join() for (@threads); } } sub transcode_files { my $process = shift; my $files = shift; my $total = scalar(@$files); foreach my $i (0 .. $#{ $files }) { my $filename = $files->[ $i ]; if ($dir_index) { my ($dir) = ($filename =~ /^(.*)[.]nt$/); if (-d $dir) { my $newfilename = File::Spec->catfile($dir, "${dir_index}.nt"); # warn "*** SHOULD RENAME $filename to $newfilename\n"; rename($filename, $newfilename); $filename = $newfilename; } } if ($count) { my $num = $i+1; my $perc = ($num/$total) * 100; printf("\rProcess $process transcoding file $num / $total (%3.1f%%)\t\t", $perc); } foreach my $format (@new_formats) { my $ext = $ext{ $format }; my $outfile = $filename; $outfile =~ s/[.]nt/.$ext/; if (-r $outfile) { my $in_mtime = (stat($filename))[9]; my $out_mtime = (stat($outfile))[9]; if ($out_mtime > $in_mtime) { # warn "*** $filename seems to already have been transcoded to $format\n"; next; } } warn "Creating file $outfile ...\n" if ($debug > 1); unless ($dryrun) { my $cmd = "rapper -q -i ntriples -o $format $format_string $filename"; open(my $fh, "$cmd|") or do { warn $!; next; }; open(my $tfh, '>', $outfile) or do { warn $!; next }; print {$tfh} <$fh>; } } } printf("\n"); } __END__ # # warn "transcoding file $input\n"; # foreach my $format (@new_formats) { # my $output = $input; # my $ext = $ext{ $format }; # $output =~ s{[.]nt$}{.$ext}; # # warn "-> $format: $output\n"; # my $cmd = "rapper -q -i ntriples -o $format $input"; # open(my $fh, "$cmd|") or do { warn $!; next; }; # open(my $tfh, '>', $output) or do { warn $!; next }; # print {$tfh} <$fh>; # } # $count++; # print STDERR "\r$count files transcoded" # # if ($count % 10 == 0) { # # } if (@new_formats) { my @files : shared; @files = sort keys %files; my $i = 0; if ($threads == 1) { transcode_files( 1, \@files ); } else { my @partitions = part { $i++ % $threads } @files; my @threads; foreach my $pnum (0 .. $#partitions) { my $t = threads->create( \&transcode_files, $pnum, $partitions[ $pnum ] ); push(@threads, $t); # transcode_files( $pnum, $partitions[ $pnum ] ); } $_->join() for (@threads); } print "\n" if ($count); } if (defined($dir_index)) { foreach my $f (keys %files) { my $abs = File::Spec->rel2abs($f); $abs =~ s/[.]nt//; my $dir = $abs; if (-d $dir) { foreach my $f2 (glob("${abs}.*")) { my ($ext) = $f2 =~ /.*[.](.*)$/ or do { warn $f2; next }; my $new = File::Spec->catfile( File::Spec->rel2abs( $dir ), $dir_index . ".$ext" ); if ($debug > 1) { my $f2rel = File::Spec->abs2rel( $f2 ); my $newrel = File::Spec->abs2rel( $new ); warn "Renaming $f2rel -> $newrel\n"; } unless ($dryrun) { copy($f2, $new) or warn "Failed to copy $f2 to $new: $!"; } } } } } sub transcode_files { my $process = shift; my $files = shift; my $total = scalar(@$files); foreach my $i (0 .. $#{ $files }) { my $filename = $files->[ $i ]; if ($count) { my $num = $i+1; my $perc = ($num/$total) * 100; printf("\rProcess $process transcoding file $num / $total (%3.1f%%)\t\t", $perc); } my $parser = RDF::Trine::Parser->new('ntriples'); my $store = RDF::Trine::Store::DBI->temporary_store; my $model = RDF::Trine::Model->new( $store ); warn "Parsing file $filename ...\n" if ($debug > 1); unless ($dryrun) { open( my $fh, '<:utf8', $filename ) or do { warn $!; next }; $parser->parse_file_into_model( $url, $fh, $model ); } while (my($name, $s) = each(%serializers)) { my $ext = $ext{ $name }; my $outfile = $filename; $outfile =~ s/[.]nt/.$ext/; warn "Creating file $outfile ...\n" if ($debug > 1); unless ($dryrun) { open( my $out, '>:utf8', $outfile ) or do { warn $!; next }; flock( $out, LOCK_EX ); $s->serialize_model_to_file( $out, $model ); flock( $out, LOCK_UN ); } } unless (exists $serializers{'ntriples'}) { warn "Removing file $filename ...\n" if ($debug > 1); unless ($dryrun) { unlink($filename); } } } }
timrdf/csv2rdf4lod-automation
bin/lod-materialize/c/lod-materialize.pl
Perl
apache-2.0
10,341
# # 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 cloud::azure::management::resource::mode::listgroups; 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; $options{options}->add_options(arguments => { "location:s" => { name => 'location' }, "filter-name:s" => { name => 'filter_name' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub manage_selection { my ($self, %options) = @_; $self->{groups} = $options{custom}->azure_list_groups(); } sub run { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $group (@{$self->{groups}}) { next if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $group->{name} !~ /$self->{option_results}->{filter_name}/); next if (defined($self->{option_results}->{location}) && $self->{option_results}->{location} ne '' && $group->{location} !~ /$self->{option_results}->{location}/); my @tags; foreach my $tag (keys %{$group->{tags}}) { push @tags, $tag . ':' . $group->{tags}->{$tag}; } $self->{output}->output_add(long_msg => sprintf("[name = %s][location = %s][id = %s][tags = %s]", $group->{name}, $group->{location}, $group->{id}, join(',', @tags))); } $self->{output}->output_add(severity => 'OK', short_msg => 'List groups:'); $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', 'location', 'id', 'tags']); } sub disco_show { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $group (@{$self->{groups}}) { my @tags; foreach my $tag (keys %{$group->{tags}}) { push @tags, $tag . ':' . $group->{tags}->{$tag}; } $self->{output}->add_disco_entry( name => $group->{name}, location => $group->{location}, id => $group->{id}, tags => join(',', @tags), ); } } 1; __END__ =head1 MODE List resources groups. =over 8 =item B<--location> Set group location (Can be a regexp). =item B<--filter-name> Filter group name (Can be a regexp). =back =cut
Tpo76/centreon-plugins
cloud/azure/management/resource/mode/listgroups.pm
Perl
apache-2.0
3,466
# # 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 cloud::azure::compute::virtualmachine::mode::health; use base qw(cloud::azure::management::monitor::mode::health); use strict; use warnings; sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->{az_resource_namespace} = 'Microsoft.Compute'; $self->{az_resource_type} = 'virtualMachines'; } 1; __END__ =head1 MODE Check Virtual Machine health status. (Usefull to determine host status) =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-status> Set warning threshold for status (Default: ''). Can used special variables like: %{status}, %{summary} =item B<--critical-status> Set critical threshold for status (Default: '%{status} =~ /^Unavailable$/'). Can used special variables like: %{status}, %{summary} =item B<--unknown-status> Set unknown threshold for status (Default: '%{status} =~ /^Unknown$/'). Can used special variables like: %{status}, %{summary} =item B<--ok-status> Set ok threshold for status (Default: '%{status} =~ /^Available$/'). Can used special variables like: %{status}, %{summary} =back =cut
Tpo76/centreon-plugins
cloud/azure/compute/virtualmachine/mode/health.pm
Perl
apache-2.0
1,978
package WebShortcutUtil; use strict; use warnings; our $VERSION = '0.21'; # REFERENCES # # Free Desktop: # http://standards.freedesktop.org/desktop-entry-spec/latest/ (used Version 1.1-draft) # # Windows URL (also applicable to Website): # http://stackoverflow.com/questions/539962/creating-a-web-shortcut-on-user-desktop-programmatically # http://stackoverflow.com/questions/234231/creating-application-shortcut-in-a-directory # http://delphi.about.com/od/internetintranet/a/lnk-shortcut.htm # http://read.pudn.com/downloads3/sourcecode/windows/system/11495/shell/shlwapi/inistr.cpp__.htm # http://epiphany-browser.sourcearchive.com/documentation/2.24.0/plugin_8cpp-source.html # http://epiphany-browser.sourcearchive.com/documentation/2.24.0/plugin_8cpp-source.html # # Webloc / Plist: # http://search.cpan.org/~bdfoy/Mac-PropertyList-1.38/ # or https://github.com/briandfoy/mac-propertylist # http://opensource.apple.com/source/CF/CF-550/CFBinaryPList.c # http://code.google.com/p/cocotron/source/browse/Foundation/NSPropertyList/NSPropertyListReader_binary1.m # http://www.apple.com/DTDs/PropertyList-1.0.dtd =head1 NAME WebShortcutUtil - Perl module for reading and writing web shortcut files =head1 DESCRIPTION This module is part of the WebShortcutUtil suite. For more details see the main website at http://beckus.github.io/WebShortcutUtil/ . All of the subroutines are contained in the Read and Write submodules. See those submodules for usage information. A brief list of the supported shortcut types: =over 4 =item * .desktop - Free Desktop shortcut (used by Linux) =item * .url - Used by Windows =item * .website - Used by Windows =item * .webloc - Used by Mac =back In order to read/write ".webloc" files, the Mac::PropertyList module (http://search.cpan.org/~bdfoy/Mac-PropertyList/) must be installed. Mac::PropertyList is listed as a dependency, but the the WebShortcutUtil module will still test out and install properly if it is not present. The webloc subroutines will die if the Mac::PropertyList module is not installed. Note that this module is still beta-quality, and the interface is subject to change. =head1 SOURCE https://github.com/beckus/WebShortcutUtil-Perl =head1 FUTURE IDEAS Some ideas for enhanced functionality: =over 4 =item * For ".desktop" files, add logic to extract the names embedded in a shortcut (including all localized versions of the name). Similar logic could also be written for ".website" files. =item * Explore unicode functionality for ".webloc" files. Will a Mac open a URL that has unicode characters? =item * Add an ASCII conversion option to the filename creation routines (i.e. to remove unicode characters). =back =head1 AUTHOR Andre Beckus E<lt>beckus@cpan.orgE<gt> =head1 SEE ALSO =over 4 =item * Main project website: http://beckus.github.io/WebShortcutUtil/ =item * Read module: http://search.cpan.org/~beckus/WebShortcutUtil/lib/WebShortcutUtil/Read.pm =item * Write module: http://search.cpan.org/~beckus/WebShortcutUtil/lib/WebShortcutUtil/Write.pm =item * Perl module for using Windows shortcuts: http://search.cpan.org/~ishigaki/Win32-InternetShortcut/ =back =head1 COPYRIGHT AND LICENSE Copyright (C) 2013 by Andre Beckus This library is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language itself. =cut 1; __END__
abcodeworks/WebShortcut-Website
src/html/WebShortcut/cgi/lib/WebShortcutUtil.pm
Perl
apache-2.0
3,446
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::mrv::optiswitch::snmp::mode::components::psu; use strict; use warnings; my %map_psu_status = ( 1 => 'none', 2 => 'active', 3 => 'notActive', ); my $mapping = { nbsDevPSOperStatus => { oid => '.1.3.6.1.4.1.629.1.50.11.1.8.2.1.5', map => \%map_psu_status }, }; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $mapping->{nbsDevPSOperStatus}->{oid} }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking power supply"); $self->{components}->{psu} = {name => 'psu', total => 0, skip => 0}; return if ($self->check_filter(section => 'psu')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$mapping->{nbsDevPSOperStatus}->{oid}}})) { next if ($oid !~ /^$mapping->{nbsDevPSOperStatus}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$mapping->{nbsDevPSOperStatus}->{oid}}, 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' state is %s [instance: %s].", $instance, $result->{nbsDevPSOperStatus}, $instance )); my $exit = $self->get_severity(section => 'psu', value => $result->{nbsDevPSOperStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("power supply '%s' state is %s", $instance, $result->{nbsDevPSOperStatus})); } } } 1;
Tpo76/centreon-plugins
network/mrv/optiswitch/snmp/mode/components/psu.pm
Perl
apache-2.0
2,636
package Paws::WAF::GetSampledRequestsResponse; use Moose; has PopulationSize => (is => 'ro', isa => 'Int'); has SampledRequests => (is => 'ro', isa => 'ArrayRef[Paws::WAF::SampledHTTPRequest]'); has TimeWindow => (is => 'ro', isa => 'Paws::WAF::TimeWindow'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::WAF::GetSampledRequestsResponse =head1 ATTRIBUTES =head2 PopulationSize => Int The total number of requests from which C<GetSampledRequests> got a sample of C<MaxItems> requests. If C<PopulationSize> is less than C<MaxItems>, the sample includes every request that your AWS resource received during the specified time range. =head2 SampledRequests => ArrayRef[L<Paws::WAF::SampledHTTPRequest>] A complex type that contains detailed information about each of the requests in the sample. =head2 TimeWindow => L<Paws::WAF::TimeWindow> Usually, C<TimeWindow> is the time range that you specified in the C<GetSampledRequests> request. However, if your AWS resource received more than 5,000 requests during the time range that you specified in the request, C<GetSampledRequests> returns the time range for the first 5,000 requests. =head2 _request_id => Str =cut 1;
ioanrogers/aws-sdk-perl
auto-lib/Paws/WAF/GetSampledRequestsResponse.pm
Perl
apache-2.0
1,250
package Paws::Kinesis::SequenceNumberRange; use Moose; has EndingSequenceNumber => (is => 'ro', isa => 'Str'); has StartingSequenceNumber => (is => 'ro', isa => 'Str', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::Kinesis::SequenceNumberRange =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::Kinesis::SequenceNumberRange object: $service_obj->Method(Att1 => { EndingSequenceNumber => $value, ..., StartingSequenceNumber => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::Kinesis::SequenceNumberRange object: $result = $service_obj->Method(...); $result->Att1->EndingSequenceNumber =head1 DESCRIPTION The range of possible sequence numbers for the shard. =head1 ATTRIBUTES =head2 EndingSequenceNumber => Str The ending sequence number for the range. Shards that are in the OPEN state have an ending sequence number of C<null>. =head2 B<REQUIRED> StartingSequenceNumber => Str The starting sequence number for the range. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::Kinesis> =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/Kinesis/SequenceNumberRange.pm
Perl
apache-2.0
1,628
#!/usr/bin/perl -w use strict; use Admin; use CGI; my $cgi = CGI->new; $cgi->param(-name => 'action', -values => 'displayMainPage') unless $cgi->param('action'); print $cgi->header( -type => 'text/html' ); my $admin = new Admin( cgi => $cgi ); $admin->run(); exit;
SmarterApp/ItemAuthoring
sbac-iaip-rpm-installer/iaip-wwwcde-rpm/src/main/www/admin/index.pl
Perl
apache-2.0
269
# Copyright 2018 - 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::_SessionPool; use version; our $VERSION = 'v2.2.2'; use Moo; use MongoDB::_ServerSession; use Types::Standard qw( ArrayRef InstanceOf ); has dispatcher => ( is => 'ro', required => 1, isa => InstanceOf['MongoDB::_Dispatcher'], ); has topology=> ( is => 'ro', required => 1, isa => InstanceOf['MongoDB::_Topology'], ); has _server_session_pool => ( is => 'lazy', isa => ArrayRef[InstanceOf['MongoDB::_ServerSession']], init_arg => undef, clearer => 1, builder => sub { [] }, ); has _pool_epoch => ( is => 'rwp', init_arg => undef, default => 0, ); # Returns a L<MongoDB::ServerSession> that was at least one minute remaining # before session times out. Returns undef if no sessions available. # # Also retires any expiring sessions from the front of the queue as requried. sub get_server_session { my ( $self ) = @_; if ( scalar( @{ $self->_server_session_pool } ) > 0 ) { my $session_timeout = $self->topology->logical_session_timeout_minutes; # if undefined, sessions not actually supported so drop out here while ( my $session = shift @{ $self->_server_session_pool } ) { next if $session->_is_expiring( $session_timeout ); return $session; } } return MongoDB::_ServerSession->new( pool_epoch => $self->_pool_epoch ); } # Place a session back into the pool for use. Will check that there is at least # one minute remaining in the session, and if so will place the session at the # front of the pool. # # Also checks for expiring sessions at the back of the pool, and retires as # required. sub retire_server_session { my ( $self, $server_session ) = @_; return if $server_session->pool_epoch != $self->_pool_epoch; my $session_timeout = $self->topology->logical_session_timeout_minutes; # Expire old sessions from back of queue while ( my $session = $self->_server_session_pool->[-1] ) { last unless $session->_is_expiring( $session_timeout ); pop @{ $self->_server_session_pool }; } unless ( $server_session->_is_expiring( $session_timeout ) ) { unshift @{ $self->_server_session_pool }, $server_session unless $server_session->dirty; } return; } # Close all sessions registered with the server. Used during global cleanup. sub end_all_sessions { my ( $self ) = @_; my @batches; push @batches, [ splice @{ $self->_server_session_pool }, 0, 10_000 ] while @{ $self->_server_session_pool }; for my $batch ( @batches ) { my $sessions = [ map { defined $_ ? $_->session_id : () } @$batch ]; # Ignore any errors generated from this eval { $self->dispatcher->send_admin_command([ endSessions => $sessions, ], 'primaryPreferred'); }; } } # When reconnecting a client after a fork, we need to clear the pool # without ending sessions with the server and increment the pool epoch # so existing sessions aren't checked back in. sub reset_pool { my ( $self ) = @_; $self->_clear_server_session_pool; $self->_set__pool_epoch( $self->_pool_epoch + 1 ); } sub DEMOLISH { my ( $self, $in_global_destruction ) = @_; $self->end_all_sessions; } 1;
mongodb/mongo-perl-driver
lib/MongoDB/_SessionPool.pm
Perl
apache-2.0
3,953
#!/usr/bin/perl package GATK::VariantFilterVQSR; use strict; use warnings; use File::Basename; use CQS::PBS; use CQS::ConfigUtils; use CQS::SystemUtils; use CQS::FileUtils; use CQS::NGSCommon; use CQS::StringUtils; use CQS::UniqueTask; our @ISA = qw(CQS::UniqueTask); sub new { my ($class) = @_; my $self = $class->SUPER::new(); $self->{_name} = "VariantFilterVQSR"; $self->{_suffix} = "_vf"; bless $self, $class; return $self; } sub perform { my ( $self, $config, $section ) = @_; my ( $task_name, $path_file, $pbsDesc, $target_dir, $logDir, $pbsDir, $resultDir, $option, $sh_direct, $cluster, $thread, $memory ) = get_parameter( $config, $section ); my $dbsnp = get_param_file( $config->{$section}{dbsnp_vcf}, "dbsnp_vcf", 1 ); my $hapmap = get_param_file( $config->{$section}{hapmap_vcf}, "hapmap_vcf", 1 ); my $omni = get_param_file( $config->{$section}{omni_vcf}, "omni_vcf", 1 ); my $g1000 = get_param_file( $config->{$section}{g1000_vcf}, "g1000_vcf", 1 ); my $mills = get_param_file( $config->{$section}{mills_vcf}, "mills_vcf", 1 ); my $faFile = get_param_file( $config->{$section}{fasta_file}, "fasta_file", 1 ); my $gatk_jar = get_param_file( $config->{$section}{gatk_jar}, "gatk_jar", 1 ); my $java_option = $config->{$section}{java_option}; if ( !defined $java_option || $java_option eq "" ) { $java_option = "-Xmx${memory}"; } my %gvcfFiles = %{ get_raw_files( $config, $section ) }; my $pbsFile = $self->pbsfile( $pbsDir, $task_name ); my $pbsName = basename($pbsFile); my $log = $self->logfile( $logDir, $task_name ); my $merged_file = $task_name . ".vcf"; my $recal_snp_file = $task_name . ".recal.snp.vcf"; my $recal_snp_indel_file = $task_name . ".recalibrated_variants.vcf"; my $recal_snp_indel_pass_file = $task_name . ".recalibrated_variants.pass.vcf"; my $log_desc = $cluster->get_log_desc($log); open( OUT, ">$pbsFile" ) or die $!; print OUT "$pbsDesc $log_desc $path_file cd $resultDir echo VariantFilterVQSR=`date` if [ ! -s $merged_file ]; then echo GenotypeGVCFs=`date` java $java_option -jar $gatk_jar -T GenotypeGVCFs $option -nt $thread -D $dbsnp -R $faFile \\ "; for my $sampleName ( sort keys %gvcfFiles ) { my @sampleFiles = @{ $gvcfFiles{$sampleName} }; my $gvcfFile = $sampleFiles[0]; print OUT " --variant $gvcfFile \\\n"; } print OUT " -o $merged_file fi if [[ -s $merged_file && ! -s recalibrate_SNP.recal ]]; then echo VariantRecalibratorSNP=`date` java $java_option -jar $gatk_jar \\ -T VariantRecalibrator -nt $thread \\ -R $faFile \\ -input $merged_file \\ -resource:hapmap,known=false,training=true,truth=true,prior=15.0 $hapmap \\ -resource:omni,known=false,training=true,truth=true,prior=12.0 $omni \\ -resource:1000G,known=false,training=true,truth=false,prior=10.0 $g1000 \\ -resource:dbsnp,known=true,training=false,truth=false,prior=2.0 $dbsnp \\ -an DP \\ -an QD \\ -an FS \\ -an SOR \\ -an MQ \\ -an MQRankSum \\ -an ReadPosRankSum \\ -an InbreedingCoeff \\ -mode SNP \\ -tranche 100.0 -tranche 99.9 -tranche 99.0 -tranche 90.0 \\ -recalFile recalibrate_SNP.recal \\ -tranchesFile recalibrate_SNP.tranches \\ -rscriptFile recalibrate_SNP_plots.R fi if [[ -s recalibrate_SNP.recal && ! -s $recal_snp_file ]]; then echo ApplyRecalibrationSNP=`date` java $java_option -jar $gatk_jar \\ -T ApplyRecalibration -nt $thread \\ -R $faFile \\ -input $merged_file \\ -mode SNP \\ --ts_filter_level 99.0 \\ -recalFile recalibrate_SNP.recal \\ -tranchesFile recalibrate_SNP.tranches \\ -o $recal_snp_file fi if [[ -s $recal_snp_file && ! -s recalibrate_INDEL.recal ]]; then echo VariantRecalibratorIndel=`date` java $java_option -jar $gatk_jar \\ -T VariantRecalibrator -nt $thread \\ -R $faFile \\ -input $recal_snp_file \\ -resource:mills,known=true,training=true,truth=true,prior=12.0 $mills \\ -an QD \\ -an DP \\ -an FS \\ -an SOR \\ -an MQRankSum \\ -an ReadPosRankSum \\ -an InbreedingCoeff \\ -mode INDEL \\ -tranche 100.0 -tranche 99.9 -tranche 99.0 -tranche 90.0 \\ --maxGaussians 4 \\ -recalFile recalibrate_INDEL.recal \\ -tranchesFile recalibrate_INDEL.tranches \\ -rscriptFile recalibrate_INDEL_plots.R fi if [[ -s $recal_snp_file && -s recalibrate_INDEL.recal && ! -s $recal_snp_indel_file ]]; then echo ApplyRecalibrationIndel=`date` java $java_option -jar $gatk_jar \\ -T ApplyRecalibration -nt $thread \\ -R $faFile \\ -input $recal_snp_file \\ -mode INDEL \\ --ts_filter_level 99.0 \\ -recalFile recalibrate_INDEL.recal \\ -tranchesFile recalibrate_INDEL.tranches \\ -o $recal_snp_indel_file fi if [[ -s $recal_snp_indel_file && ! -s $recal_snp_indel_pass_file ]]; then grep -e \"^#\" $recal_snp_indel_file > $recal_snp_indel_pass_file grep PASS $recal_snp_indel_file >> $recal_snp_indel_pass_file fi echo finished=`date` exit 0 "; close(OUT); print "$pbsFile created\n"; } sub result { my ( $self, $config, $section, $pattern ) = @_; my ( $task_name, $path_file, $pbsDesc, $target_dir, $logDir, $pbsDir, $resultDir, $option, $sh_direct ) = get_parameter( $config, $section ); my $recal_snp_indel_pass_file = $task_name . ".recalibrated_variants.pass.vcf"; my $result = { $task_name => [ $resultDir . "/${recal_snp_indel_pass_file}" ] }; return $result; } 1;
realizor/ngsperl
lib/GATK/VariantFilterVQSR.pm
Perl
apache-2.0
5,696
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package Bio::EnsEMBL::Production::Pipeline::FtpChecker::CheckComparaFtp; use strict; use warnings; use base qw/Bio::EnsEMBL::Production::Pipeline::FtpChecker::CheckFtp/; use Bio::EnsEMBL::Utils::Exception qw(throw); use Bio::EnsEMBL::DBSQL::DBAdaptor; use Data::Dumper; use Log::Log4perl qw/:easy/; my $expected_files = { "tsv" =>{"dir" => "{division}tsv/ensembl-compara/homologies/", "expected" =>[ 'Compara.*.homologies.tsv.gz', 'README.*', 'MD5SUM*' ]}, "emf" =>{"dir" => "{division}emf/ensembl-compara/homologies/", "expected" =>[ 'Compara.*.fasta.gz', 'Compara.*.emf.gz', 'README.*', 'MD5SUM' ]}, "xml" => {"dir" => "{division}xml/ensembl-compara/homologies/", "expected" =>[ 'Compara.*.xml.gz', 'Compara.*phyloxml.xml.tar', 'Compara.*.orthoxml.xml.tar', 'README.*', 'MD5SUM*' ]}, }; sub run { my ($self) = @_; my $species = $self->param('species'); Log::Log4perl->easy_init($DEBUG); $self->{logger} = get_logger(); my $base_path = $self->param('base_path'); $self->{logger}->info("Checking $species on $base_path"); my $division; if($species eq 'multi') { $division = ""; }elsif($species eq 'pan_homology') { $division = "pan_ensembl/"; }elsif($species eq 'bacteria'){ #Bacteria compara is only a subset of data, we don't generate dumps for this database return; }else { $division = "$species/"; } my $vals = { division => $division }; $self->check_files($species, 'compara', $base_path, $expected_files, $vals); return; } 1;
Ensembl/ensembl-production
modules/Bio/EnsEMBL/Production/Pipeline/FtpChecker/CheckComparaFtp.pm
Perl
apache-2.0
2,426
#!/usr/bin/perl -w use strict; while(<>) { #s/ (pre|anti|re|pro|inter|intra|multi|e|x|neo) - / $1- /ig; #s/ - (year) - (old)/ -$1-$2/ig; s/ ' (s|m|ll|re|d|ve) / '$1 /ig; s/n ' t / n't /ig; print; }
kho/mr-cdec
corpus/support/fix-contract.pl
Perl
apache-2.0
209
package VMOMI::AdminDisabled; use parent 'VMOMI::HostConfigFault'; use strict; use warnings; our @class_ancestors = ( 'HostConfigFault', 'VimFault', 'MethodFault', ); our @class_members = ( ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/AdminDisabled.pm
Perl
apache-2.0
426
#!/usr/bin/env perl # This just tests whether it works without crashing. # # I am not a Perl programmer!!! # # MJ, 03-Jun-2015 use xixeventlib; xixeventlib::xix_event_set_notification_2("127.0.0.1", "public", "id", "text"); xixeventlib::xix_event_set_inform_2("127.0.0.1", "public", "id", "text"); xixeventlib::xix_event_clear_notification_2("127.0.0.1", "public", "id"); xixeventlib::xix_event_clear_inform_2("127.0.0.1", "public", "id"); xixeventlib::xix_event_set("127.0.0.1", "public", "id", "text"); xixeventlib::xix_event_clear("127.0.0.1", "public", "id"); xixeventlib::xix_event_set_inform("127.0.0.1", "public", "id", "text"); xixeventlib::xix_event_clear_inform("127.0.0.1", "public", "id");
mjuenema/xix-event-mib
api/perl/test_xixeventlib.pl
Perl
bsd-2-clause
713
package bus2db; =pod =head1 NAME bus2db.pl =head1 SYNOPSIS A bus-aware plugin that passes messages from an Openkore instance to a standalone bus client (bus2db-client.pl), which updates the koreInventory database. =head1 DESCRIPTION This Openkore plugin communicates with a separate, standalone bus client that does the actual database queries/updates. This architecture allows for multiple Openkore instances to update the database, without concern about queuing or slowdowns for higher volumes of querying. Also, the standalone script being the sole gateway to the database allows it to act as the gatekeeper, authenticating clients, authorizing those allowed to interact, and validating messages sent. =head1 IMPLEMENTATION NOTES: The hash of hashes listed below... should probably be pulled out into a module in future revisions, to contain all it's behavior and simplify this unit. =head2 Data Structures: %busClients - hash of hashes, holding info about each of the connected bus clients. Key Value BusID => { clientInfo hash holding various values } (^ as seen in the LIST_CLIENTS message) "%clientInfo" - a hash stored within %busClients, with the following entries: Key Value --- ----- ServerIdx => (Positive Integer) # must match ServerIdx in Accounts AccountName => (String) CharIdx => (Positive Integer, unique) CharName => (String) -- unique pair - ServerIdx integer - AccountName -- - CharIdx integer (unique) - CharName - InZone boolean - Authenticated boolean (for security purposes) From server: AccountNumber (ID in Account, match by AccountID in Characters, and AccountName from client) CharacterNumber (ID in Characters) Match these in Characters table, by name from client. =head2 Requirements: Openkore, revision r8965 or later (this plugin requires the "zeny_change" callback hook to exist, or it'll never report a thing that will update your koreInventory Database. =cut #======================================================================== # Modifications: # by ChrstphrR # # Intent: change the behaviour of this plugin, so that it implements the # suggestion of EternalHarvest in the source thread on the openkore forums: # # "Wouldn't it be nice to have different commands for invoking commands and for # messaging mode, so they can be used simultaneously and without configuration?" # # 2012/09/03rd: Planning stage: # - added a BUS_MESSAGE constant to mimic BUS_COMMAND, this will be used for # sending the messages only, instead of only relying on the "MESSENGER_MODE" # check to determine that. # # - the constants as used are too simple - these should be (private?) variables, # that are initialized using defaults shown OR via well documented config.txt # values for this plugin. The rigidity here is what makes it difficult to # implement simultaneous bus commands/messages both... # #======================================================================== use strict; #use warnings; #no warnings 'redefine'; use Plugins; use Log qw( warning message error ); use Globals; ## While testing, we'll be using this to help debug... :P use Data::Dumper; use Bus::Client; #Constants, used in Bus::Client # State constants. use constant { NOT_CONNECTED => 1, STARTING_SERVER => 2, HANDSHAKING => 3, CONNECTED => 4 }; use constant { VERSION => '0.1.0.0' # Alpha }; use constant { PLUGIN => 'bus2db', # Custom bus messages to talk to bus2db.pl plugin: # BMC_* BMC_MESSAGE => 'BROADCAST_MSG', BMC_REGISTER => 'B2DB_REGISTER', # sent by db-client to plugins BMC_REGISTER_ME => 'B2DB_REGISTER_ME', # reply to above from plugin. # Custom messages that should interact with the database: BMC_ZENY => 'B2DB_ZENY', # Standard bus messages # BM_* BM_LISTCLIENTS => "LIST_CLIENTS", # command line constants # CMD_* CMD_MESSAGE => "bmsg", CMD_LISTCLIENTS => "lc", #msglevel constants (used in sub msg) MLVL_NONE => 0, MLVL_MSG => 1, MLVL_WARNING => 2, MLVL_ERROR => 3 }; # Plugin setup: Register Plugin, commands, hooks used Plugins::register(PLUGIN, "receive/send commands (and messages) via BUS system", \&unload, \&reload); my $myCmds = Commands::register( [ CMD_MESSAGE, "use ".CMD_MESSAGE." <all|player name|map name> <message here>", \&sendBusMessage ], [ CMD_LISTCLIENTS, "use ".CMD_LISTCLIENTS, \&sendListClients ] ); # separate hook/var for this, because we tend to alter it my $networkHook = Plugins::addHook('Network::stateChanged',\&checkNetworkState); my $hooks = Plugins::addHooks( ['zeny_change',\&zenyChange] #this hook implemented in Openkore r8965 ); ## my $bus_message_received; my $bus2db_busID; ## Send a normal bus message instead of a command # sub sendBusMessage { my (undef, $cmm) = @_; $cmm =~ m/^"(.*)" (.*)$/; $cmm =~ m/^(\w+) (.*)$/ unless ($1); unless ($1 && $2) { msg("Command \"".CMD_MESSAGE."\" failed, please use ".CMD_MESSAGE." <all|player name|map name> <command>.", 3); return; } if ($char && $bus->getState == CONNECTED) { my %args; $args{player} = $1; $args{msg} = $2; $args{FromName} = $char->name; # Hey, let's tell them our name? $bus->send(BMC_MESSAGE, \%args); } if ( ($1 eq $char->name) || $1 eq "all" || ($field) && ($1 eq $field->name) ) { Plugins::callHook('bus_received', {message => $2}); msg("bmsg: ".$2); } }#sub sendBusMessage ## zeny_change callback : # args: # zeny amt of zeny player has after # change change in zeny - pos or negative. # sub zenyChange { if (!$char) { msg("Early Exit zenyChange.1"); return; } if (!$bus2db_busID) { msg("Early Exit zenyChange.2"); return; } my ($msgID, $args) = @_; # $msgID = 'zeny_change' the callback tag #$args refers to the hash stated above. Extract what we need: my $Zeny = $args->{zeny}; my $Change = $args->{change}; if (abs($Change) > 0) { #if there was a change (don't care which!) #send a bus packet to bus2db-client, please... msg("sending zeny message to bus2db..."); $bus->send( BMC_ZENY, { 'TO' => $bus2db_busID, #This is not seen by the other client, server removes it. 'zeny' => $Zeny, 'change' => $Change } ); #account name #message T("AccountName: $config{'username'} \n"), "info"; #account ID #message T("AccountID: $char->{'nameID'} *\n"), "info"; } ## Test phase: ensure this routine receives the zeny_change callback calls... ## Later, once this is ensured, then we'll send a message over the bus to bus2db-client, ## where it will update the database. =pod if ($Change > 0) { msg("You gained $Change to have $Zeny"); } elsif ($Change < 0) { msg('You lost '. abs($Change) ." to have $Zeny"); } else { #Will it trigger with no zeny change? #Maybe an initial packet set on map load? # - when interacting with npc - seems to double send, in fact... # maybe we should ignore a zero change to prevent unnecessary messages? msg("You have $Zeny"); } =cut }; # zenyChange ## Send request to bus server to list clients connected. # # Borrowed idea/command from /src/test/bus-clients-test.pl # sub sendListClients { my @args = @_; if ($bus->getState == CONNECTED) { if (@_ > 1) { $bus->send( 'LIST_CLIENTS', { 'SEQ' => $_[1] } ); msg("list clients->busServer: SEQ = $_[1]"); } else { $bus->send('LIST_CLIENTS'); msg('list clients->busServer:'); } } }#sub sendListClients # handle plugin loaded manually if ($::net) { if ($::net->getState() > NOT_CONNECTED) { $bus_message_received = $bus->onMessageReceived->add(undef, \&bus_message_received); if ($networkHook) { Plugins::delHooks($networkHook); undef $networkHook; } } } sub checkNetworkState { return if ($::net->getState() == NOT_CONNECTED); if (!$bus) { die("\n\n[".PLUGIN."] You MUST start BUS server and configure each bot to use it in order to use this plugin. Open and edit line bus 0 to bus 1 inside control/sys.txt \n\n", 3, 0); } elsif (!$bus_message_received) { $bus_message_received = $bus->onMessageReceived->add(undef, \&busMessageReceived); Plugins::delHook($networkHook); undef $networkHook; } } ## Recieved a bus message of some sort, let's check and see if we're # supposed to handle it or not! # receives all bus messages -- note, this means even ones we aren't # generating, that other bus clients DID. sub busMessageReceived { my (undef, undef, $msg) = @_; return if (!$char); my $isBMsg = ($msg->{messageID} eq BMC_MESSAGE); my $isRego = ($msg->{messageID} eq BMC_REGISTER); my $isList = ($msg->{messageID} eq BM_LISTCLIENTS); return unless ($isBMsg || $isList || $isRego); my $msgTarget = $msg->{args}{player}; if ( ($msgTarget eq $char->name) || ($msgTarget eq "all") || ($field && $msgTarget eq $field->name) ) { Plugins::callHook('bus_received', {message => $msg->{args}{msg}}); if ($isBMsg) { ###print Dumper($msg); # $msg has this structure: # $msg { # messageID => 'busMsg' # args { # 'FROM' => '9', #numeric ID assigned by the Bus? # 'FromName' => 'Joe', # Nickname passed by sender # 'msg' => 'Hello?', # Actual message contents # 'player => 'all' # This is the target of the msg # } # }//$msg msg("[".$msg->{args}{FromName}."]->[".$msg->{args}{player}."]: ".$msg->{args}{msg}); } } elsif ($isRego) { #send info so we can be registered to send DB info... msg("REGISTER received -- sending REGISTER ME!"); $bus2db_busID = $msg->{args}{FROM}; $bus->send( BMC_REGISTER_ME, { TO => $bus2db_busID, #privmsg to the bus2db client AName => $config{username}, AID => $char->{nameID}, CName => $char->{name}, CIdx => $config{char} } ); } elsif ($isList) { #LIST_CLIENTS message received from server. msg("------- Client list --------"); ###print Dumper($msg); # $msg has this structure: # $msg = { # 'messageID' => 'LIST_CLIENTS', # 'args' => { # 'IRY' => 1, # 'clientUserAgent0' => 'OpenKore', # 'clientUserAgent1' => 'OpenKore', # 'clientUserAgent2' => 'OpenKore', # 'clientUserAgent3' => 'OpenKore', # 'client0' => 41 # 'client1' => 33, # 'client2' => 34, # 'client3' => 35, # 'count' => 4, # } # }; for (my $i = 0; $i < $msg->{args}{count}; $i++) { msg($msg->{args}{"client$i"} ." : ". $msg->{args}{"clientUserAgent$i"}); } msg("----------------------------"); } else { msg("-----------------------"); msg("Message from bus server: $msg->{messageID}"); if (ref($msg) eq 'HASH') { foreach my $key (keys %{$msg}) { msg("$key => $msg->{$key}"); } } else { foreach my $entry (@{$msg}) { msg("$entry"); } } msg("-----------------------"); } } ## sub msg(<message> [, <msglevel>[, <debug>]]) ## Utility routine: # Sends a text message, where? Depends on the message level! # # Parameters: # <message> : The text string of the message sent. # [msglevel] : Optional parameter # MLVL_NONE, MLVL_WARNING, null, or undefined: # display as a warning (unless SILENT constant is 1) # MLVL_MSG: # display as a normally to console (unless SILENT constant is 1) # MLVL_ERROR: # display as an error message to stderr # # Side effects: # SILENT constant: will suppress all but msglevel = 3, if set to 1 # DEBUG constant: will suppress all messages from this routine, # unless <debug> is 1, and DEBUG != 0 # ##messages to console (or warnings, or errors... gosh it'd be nice if these msglevel things were documented, too.. sub msg { # SILENT constant support and sprintf. my ($msg, $msglevel, $debug) = @_; unless ($debug eq 1) { $msg = "[".PLUGIN."] ".$msg."\n"; if ( !defined $msglevel || $msglevel == "" || $msglevel == MLVL_NONE || $msglevel == MLVL_WARNING ) { warning($msg); } elsif ($msglevel == MLVL_MSG) { message($msg); } } return 1; } # Plugin unload sub unload { __unload("\n[".PLUGIN."] unloading.\n\n"); } ## Bug - after reloading, the plugin crashes kore when one of its commands ## is invoked. # # Plugin reload sub reload { __unload("\n[".PLUGIN."] reloading.\n\n"); } # Common bits for the unload/reload routines - they pass the message as the only argument. sub __unload { if (@_ == 1) { message($_[0]); } Plugins::delHooks($hooks) if $hooks; undef $hooks; Commands::unregister($myCmds); undef $myCmds; if ($bus_message_received) { $bus->onMessageReceived->remove($bus_message_received); undef $bus_message_received; } undef $bus2db_busID; } 1; =pod =head1 SUPPORT No support is available, expressed, or implied. =head1 AUTHOR Copyright 2015, ChrstphrR. =head1 LICENSE (Licensed under BSD 3-clause / BSD "New" see: http://opensource.org/licenses/BSD-3-Clause ) Copyright (c) 2015, ChrstphrR All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of ChrstphrR nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =cut
ChrstphrR/koreInventory
bus2db.pl
Perl
bsd-3-clause
14,184
package NTPPool::Control; use strict; use utf8; use Combust::Constant qw(OK); use base qw(Combust::Control Combust::Control::StaticFiles Combust::Control::Bitcard); use Carp qw(cluck); use Storable qw(retrieve); use I18N::LangTags qw(implicate_supers); use I18N::LangTags::Detect (); use List::Util qw(first); use NP::I18N; use NP::Version; $Combust::Control::Bitcard::cookie_name = 'npuid'; my $version = NP::Version->new; my $config = Combust::Config->new; our %valid_languages = ( bg => {name => "Български", testing => 1}, ca => {name => "Català", testing => 1}, de => {name => "Deutsch"}, da => {name => "Danish", testing => 1,}, en => {name => "English",}, es => {name => "Español"}, fi => {name => "Suomi"}, fr => {name => "Français",}, it => {name => "Italiano", testing => 1}, ja => {name => "日本語"}, ko => {name => "한국어",}, kz => {name => "Қазақша", testing => 1}, nl => {name => "Nederlands",}, pl => {name => "Polish", testing => 1}, pt => {name => "Português"}, ro => {name => "Română", testing => 1}, rs => {name => "српски srpski"}, ru => {name => "русский",}, sv => {name => "Svenska"}, tr => {name => "Türkçe", testing => 1}, uk => {name => "Українська"}, zh => {name => "中国(简体)", testing => 1 }, ); NP::I18N::loc_lang('en'); my $ctemplate; sub tt { $ctemplate ||= Combust::Template->new( filters => { l => [\&loc_filter, 1], loc => [\&loc_filter, 1], } ) or die "Could not initialize Combust::Template object: $Template::ERROR"; } sub init { my $self = shift; NP::Model->db->ping; if ($self->site ne 'manage') { # delete combust cookie from non-manage sites if ($self->plain_cookie('c')) { $self->plain_cookie('c', '', {expires => '-1'}); } } if ($config->site->{$self->site}->{ssl_only}) { if (($self->request->header_in('X-Forwarded-Proto') || 'http') eq 'http') { return $self->redirect($self->_url($self->site, $self->request->path)); } else { # we're setting Strict-Transport-Security with haproxy # $self->request->header_out('Strict-Transport-Security', 'max-age=' . (86400 * 7 * 20)); } } my $path = $self->request->path; if ($path !~ m!(^/static/|\.png|\.json$)!) { my $lang = $self->language; NP::I18N::loc_lang($lang); $self->tpl_param('current_language', $lang); } else { $self->tpl_param('current_language', 'en'); } if ($path !~ m{^/s(cores)?/.*::$} and $path =~ s/[\).:>}]+$//) { # :: is for ipv6 "null" addresses in /scores urls return $self->redirect($path, 301); } return OK; } sub loc_filter { my $tt = shift; my @args = @_; return sub { NP::I18N::loc($_[0], @args) }; } # should be moved to the manage class when sure we don't use is_logged_in on the ntppool site sub is_logged_in { my $self = shift; my $user_info = $self->user; return 1 if $user_info and $user_info->username; return 0; } sub get_include_path { my $self = shift; my $path = $self->SUPER::get_include_path; return $path if $self->request->path =~ m!(^/static/|\.png$)!; my ($language) = $self->language; # Always use the 'en' file as last resort. Maybe this should come # in before "shared" etc... if ($language ne 'en') { push @$path, $path->[0] . "en"; } # try the $language version first unshift @$path, $path->[0] . "$language/"; return $path; } # Because of how the varnish caching works there's just one language # with fallback to English. If we ever get more dialects we'll worry # about that then. sub language { my $self = shift; return $self->{_lang} if $self->{_lang}; my $language = $self->path_language || $self->detect_language; return $self->{_lang} = $language || 'en'; } sub valid_language { my $self = shift; my @languages = @_; return first { $valid_languages{$_} } @languages; } sub valid_languages { \%NTPPool::Control::valid_languages; } sub path_language { my $self = shift; my $path_language = $self->request->notes('lang'); return $path_language; } sub detect_language { my $self = shift; if ($self->plain_cookie('lang')) { $self->plain_cookie('lang', '', {expires => '-1'}); } $self->request->header_out('Vary', 'Accept-Language'); my $language_choice = $self->request->header_in('X-Varnish-Accept-Language'); return $language_choice if $self->valid_language($language_choice); $ENV{REQUEST_METHOD} = $self->request->method; $ENV{HTTP_ACCEPT_LANGUAGE} = $self->request->header_in('Accept-Language') || ''; my @lang = implicate_supers(I18N::LangTags::Detect::detect()); my $lang = $self->valid_language(@lang); return $lang; } *loc = \&localize; sub localize { my $self = shift; my $lang = $self->language; } sub localize_url { my $self = shift; if ($self->request->path eq '/' # this short-circuits some of the rest and !$self->path_language and $self->request->method =~ m/^(head|get)$/ and $self->request->uri !~ m{^/(manage|static)} ) { my $lang = $self->language; my $uri = URI->new($self->config->base_url('ntppool') . $self->request->uri . ($self->request->args ? '?' . $self->request->args : '')); $uri->path("/$lang" . $uri->path); $self->request->header_out('Vary', 'Accept-Language'); $self->cache_control('s-maxage=900, maxage=3600'); return $self->redirect($uri->as_string); } return; } sub _url { my ($self, $site, $url, $args) = @_; my $uri = URI->new($config->base_url($site) . $url); if ($config->site->{$site}->{ssl_only}) { $uri->scheme('https'); } if ($args) { if (ref $args) { $uri->query_form(%$args); } else { $uri->query($args); } } return $uri->as_string; } sub www_url { my $self = shift; return $self->_url('ntppool', @_); } sub manage_url { my $self = shift; return $self->_url('manage', @_); } sub count_by_continent { my $self = shift; my $global = NP::Model->zone->fetch(name => '@'); unless ($global) { warn "zones appear not to be setup, run ./bin/populate_zones!"; return; } my @zones = sort { $a->description cmp $b->description } $global->zones; push @zones, $global; my $total = NP::Model->zone->fetch(name => '.'); push @zones, $total; \@zones; } sub redirect { my ($self, $url) = (shift, shift); $self->post_process; return $self->SUPER::redirect($url, @_); } sub cache_control { my $self = shift; return $self->{cache_control} unless @_; return $self->{cache_control} = shift; } sub post_process { my $self = shift; # IE8 is old cruft by now. $self->request->header_out('X-UA-Compatible', 'IE=9'); $self->request->header_out('X-NPV', $version->current_release . " (" . $version->hostname . ")"); if (my $cache = $self->cache_control) { my $req = $self->request; $req->header_out('Cache-Control', $cache); } return OK; } sub plain_cookie { my $self = shift; my $cookie = shift; my $value = shift || ''; my $args = shift || {}; my $ocookie = $self->request->get_cookie($cookie) || ''; unless (defined $value and $value ne ($ocookie || '')) { return $ocookie; } $args->{domain} = delete $args->{domain} || $self->site && $self->config->site->{$self->site}->{cookie_domain} || $self->request->uri->host || ''; $args->{path} ||= '/'; $args->{expires} = time + (30 * 86400) unless defined $args->{expires}; if ($args->{expires} =~ m/^-/) { $args->{expires} = 1; } $args->{value} = $value; return $self->request->response->cookies->{$cookie} = $args; } 1;
punitvara/ntppool
lib/NTPPool/Control.pm
Perl
apache-2.0
8,259
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 8.0.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V10 8583 8584 65839 65840 65863 65864 65878 65879 68072 68073 END
operepo/ope
bin/usr/share/perl5/core_perl/unicore/lib/Nv/50000.pl
Perl
mit
548
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 8.0.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V1221 888 890 896 900 907 908 909 910 930 931 1328 1329 1367 1369 1376 1377 1416 1417 1419 1421 1424 1425 1480 1488 1515 1520 1525 1536 1565 1566 1806 1807 1867 1869 1970 1984 2043 2048 2094 2096 2111 2112 2140 2142 2143 2208 2229 2275 2436 2437 2445 2447 2449 2451 2473 2474 2481 2482 2483 2486 2490 2492 2501 2503 2505 2507 2511 2519 2520 2524 2526 2527 2532 2534 2556 2561 2564 2565 2571 2575 2577 2579 2601 2602 2609 2610 2612 2613 2615 2616 2618 2620 2621 2622 2627 2631 2633 2635 2638 2641 2642 2649 2653 2654 2655 2662 2678 2689 2692 2693 2702 2703 2706 2707 2729 2730 2737 2738 2740 2741 2746 2748 2758 2759 2762 2763 2766 2768 2769 2784 2788 2790 2802 2809 2810 2817 2820 2821 2829 2831 2833 2835 2857 2858 2865 2866 2868 2869 2874 2876 2885 2887 2889 2891 2894 2902 2904 2908 2910 2911 2916 2918 2936 2946 2948 2949 2955 2958 2961 2962 2966 2969 2971 2972 2973 2974 2976 2979 2981 2984 2987 2990 3002 3006 3011 3014 3017 3018 3022 3024 3025 3031 3032 3046 3067 3072 3076 3077 3085 3086 3089 3090 3113 3114 3130 3133 3141 3142 3145 3146 3150 3157 3159 3160 3163 3168 3172 3174 3184 3192 3200 3201 3204 3205 3213 3214 3217 3218 3241 3242 3252 3253 3258 3260 3269 3270 3273 3274 3278 3285 3287 3294 3295 3296 3300 3302 3312 3313 3315 3329 3332 3333 3341 3342 3345 3346 3387 3389 3397 3398 3401 3402 3407 3415 3416 3423 3428 3430 3446 3449 3456 3458 3460 3461 3479 3482 3506 3507 3516 3517 3518 3520 3527 3530 3531 3535 3541 3542 3543 3544 3552 3558 3568 3570 3573 3585 3643 3647 3676 3713 3715 3716 3717 3719 3721 3722 3723 3725 3726 3732 3736 3737 3744 3745 3748 3749 3750 3751 3752 3754 3756 3757 3770 3771 3774 3776 3781 3782 3783 3784 3790 3792 3802 3804 3808 3840 3912 3913 3949 3953 3992 3993 4029 4030 4045 4046 4059 4096 4294 4295 4296 4301 4302 4304 4681 4682 4686 4688 4695 4696 4697 4698 4702 4704 4745 4746 4750 4752 4785 4786 4790 4792 4799 4800 4801 4802 4806 4808 4823 4824 4881 4882 4886 4888 4955 4957 4989 4992 5018 5024 5110 5112 5118 5120 5789 5792 5881 5888 5901 5902 5909 5920 5943 5952 5972 5984 5997 5998 6001 6002 6004 6016 6110 6112 6122 6128 6138 6144 6159 6160 6170 6176 6264 6272 6315 6320 6390 6400 6431 6432 6444 6448 6460 6464 6465 6468 6510 6512 6517 6528 6572 6576 6602 6608 6619 6622 6684 6686 6751 6752 6781 6783 6794 6800 6810 6816 6830 6832 6847 6912 6988 6992 7037 7040 7156 7164 7224 7227 7242 7245 7296 7360 7368 7376 7415 7416 7418 7424 7670 7676 7958 7960 7966 7968 8006 8008 8014 8016 8024 8025 8026 8027 8028 8029 8030 8031 8062 8064 8117 8118 8133 8134 8148 8150 8156 8157 8176 8178 8181 8182 8191 8192 8293 8294 8306 8308 8335 8336 8349 8352 8383 8400 8433 8448 8588 8592 9211 9216 9255 9280 9291 9312 11124 11126 11158 11160 11194 11197 11209 11210 11218 11244 11248 11264 11311 11312 11359 11360 11508 11513 11558 11559 11560 11565 11566 11568 11624 11631 11633 11647 11671 11680 11687 11688 11695 11696 11703 11704 11711 11712 11719 11720 11727 11728 11735 11736 11743 11744 11843 11904 11930 11931 12020 12032 12246 12272 12284 12288 12352 12353 12439 12441 12544 12549 12590 12593 12687 12688 12731 12736 12772 12784 12831 12832 13055 13056 19894 19904 40918 40960 42125 42128 42183 42192 42540 42560 42744 42752 42926 42928 42936 42999 43052 43056 43066 43072 43128 43136 43205 43214 43226 43232 43262 43264 43348 43359 43389 43392 43470 43471 43482 43486 43519 43520 43575 43584 43598 43600 43610 43612 43715 43739 43767 43777 43783 43785 43791 43793 43799 43808 43815 43816 43823 43824 43878 43888 44014 44016 44026 44032 55204 55216 55239 55243 55292 63744 64110 64112 64218 64256 64263 64275 64280 64285 64311 64312 64317 64318 64319 64320 64322 64323 64325 64326 64450 64467 64832 64848 64912 64914 64968 65008 65022 65024 65050 65056 65107 65108 65127 65128 65132 65136 65141 65142 65277 65279 65280 65281 65471 65474 65480 65482 65488 65490 65496 65498 65501 65504 65511 65512 65519 65529 65534 65536 65548 65549 65575 65576 65595 65596 65598 65599 65614 65616 65630 65664 65787 65792 65795 65799 65844 65847 65933 65936 65948 65952 65953 66000 66046 66176 66205 66208 66257 66272 66300 66304 66340 66352 66379 66384 66427 66432 66462 66463 66500 66504 66518 66560 66718 66720 66730 66816 66856 66864 66916 66927 66928 67072 67383 67392 67414 67424 67432 67584 67590 67592 67593 67594 67638 67639 67641 67644 67645 67647 67670 67671 67743 67751 67760 67808 67827 67828 67830 67835 67868 67871 67898 67903 67904 67968 68024 68028 68048 68050 68100 68101 68103 68108 68116 68117 68120 68121 68148 68152 68155 68159 68168 68176 68185 68192 68256 68288 68327 68331 68343 68352 68406 68409 68438 68440 68467 68472 68498 68505 68509 68521 68528 68608 68681 68736 68787 68800 68851 68858 68864 69216 69247 69632 69710 69714 69744 69759 69826 69840 69865 69872 69882 69888 69941 69942 69956 69968 70007 70016 70094 70096 70112 70113 70133 70144 70162 70163 70206 70272 70279 70280 70281 70282 70286 70287 70302 70303 70314 70320 70379 70384 70394 70400 70404 70405 70413 70415 70417 70419 70441 70442 70449 70450 70452 70453 70458 70460 70469 70471 70473 70475 70478 70480 70481 70487 70488 70493 70500 70502 70509 70512 70517 70784 70856 70864 70874 71040 71094 71096 71134 71168 71237 71248 71258 71296 71352 71360 71370 71424 71450 71453 71468 71472 71488 71840 71923 71935 71936 72384 72441 73728 74650 74752 74863 74864 74869 74880 75076 77824 78895 82944 83527 92160 92729 92736 92767 92768 92778 92782 92784 92880 92910 92912 92918 92928 92998 93008 93018 93019 93026 93027 93048 93053 93072 93952 94021 94032 94079 94095 94112 110592 110594 113664 113771 113776 113789 113792 113801 113808 113818 113820 113828 118784 119030 119040 119079 119081 119273 119296 119366 119552 119639 119648 119666 119808 119893 119894 119965 119966 119968 119970 119971 119973 119975 119977 119981 119982 119994 119995 119996 119997 120004 120005 120070 120071 120075 120077 120085 120086 120093 120094 120122 120123 120127 120128 120133 120134 120135 120138 120145 120146 120486 120488 120780 120782 121484 121499 121504 121505 121520 124928 125125 125127 125143 126464 126468 126469 126496 126497 126499 126500 126501 126503 126504 126505 126515 126516 126520 126521 126522 126523 126524 126530 126531 126535 126536 126537 126538 126539 126540 126541 126544 126545 126547 126548 126549 126551 126552 126553 126554 126555 126556 126557 126558 126559 126560 126561 126563 126564 126565 126567 126571 126572 126579 126580 126584 126585 126589 126590 126591 126592 126602 126603 126620 126625 126628 126629 126634 126635 126652 126704 126706 126976 127020 127024 127124 127136 127151 127153 127168 127169 127184 127185 127222 127232 127245 127248 127279 127280 127340 127344 127387 127462 127491 127504 127547 127552 127561 127568 127570 127744 128378 128379 128420 128421 128721 128736 128749 128752 128756 128768 128884 128896 128981 129024 129036 129040 129096 129104 129114 129120 129160 129168 129198 129296 129305 129408 129413 129472 129473 131072 173783 173824 177973 177984 178206 178208 183970 194560 195102 917505 917506 917536 917632 917760 918000 END
operepo/ope
bin/usr/share/perl5/core_perl/unicore/lib/Sc/Zzzz.pl
Perl
mit
7,492
package AsposeBarCodeCloud::Object::HttpStatusCode; require 5.6.0; use strict; use warnings; use utf8; use JSON qw(decode_json); use Data::Dumper; use Module::Runtime qw(use_module); use Log::Any qw($log); use Date::Parse; use DateTime; use base "AsposeBarCodeCloud::Object::BaseObject"; # # # #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # my $swagger_types = { }; my $attribute_map = { }; # new object sub new { my ($class, %args) = @_; my $self = { }; return bless $self, $class; } # get swagger type of the attribute sub get_swagger_types { return $swagger_types; } # get attribute mappping sub get_attribute_map { return $attribute_map; } 1;
asposebarcode/Aspose_BarCode_Cloud
SDKs/Aspose.BarCode-Cloud-SDK-for-Perl/lib/AsposeBarCodeCloud/Object/HttpStatusCode.pm
Perl
mit
769
#!/usr/bin/env perl use strict; use warnings; use File::Path; use Carp; use Getopt::Long qw(:config no_ignore_case bundling pass_through); use File::Basename; use FindBin; use lib ("$FindBin::Bin/../../PerlLib"); use Nuc_translator; use SAM_reader; use SAM_entry; my $usage = <<__EOUSAGE__; ################################################################ # # Required: # # --partitions_gff <string> list of partitions in gff format. # --coord_sorted_SAM <string> coordinate-sorted SAM file # # Options: # # --SS_lib_type <string> [SS_lib_type=F,R,FR,RF] # # --parts_per_directory <int> default: 100 # --min_reads_per_partition <int> default: 10 # ################################################################# __EOUSAGE__ ; my $partitions; my $alignments_sam; my $SS_lib_type; my $PARTS_PER_DIR = 100; my $MIN_READS_PER_PARTITION = 10; &GetOptions ( 'partitions_gff=s' => \$partitions, 'coord_sorted_SAM=s' => \$alignments_sam, 'SS_lib_type=s' => \$SS_lib_type, 'parts_per_directory=i' => \$PARTS_PER_DIR, 'min_reads_per_partition=i' => \$MIN_READS_PER_PARTITION, ); unless ($partitions && $alignments_sam) { die $usage; } main: { my $partitions_dir = "Dir_". basename($partitions); unless (-d $partitions_dir) { mkdir ($partitions_dir) or die "Error, cannot mkdir $partitions_dir"; } open (my $track_fh, ">$partitions_dir.listing") or die $!; my %scaff_to_partitions = &parse_partitions($partitions); my @ordered_partitions; my $current_partition = undef; my $ofh; my $sam_ofh; my $partition_counter = 0; my $part_file = ""; my $sam_part_file = ""; my $read_counter = 0; my $current_scaff = ""; my $sam_reader = new SAM_reader($alignments_sam); while (my $sam_entry = $sam_reader->get_next()) { my $acc = $sam_entry->reconstruct_full_read_name(); my $scaff = $sam_entry->get_scaffold_name(); next if $scaff eq '*'; my $seq = $sam_entry->get_sequence(); my $start = $sam_entry->get_aligned_position(); my $read_name = $sam_entry->get_read_name(); # raw from sam file if ($acc !~ /\/[12]$/ && $read_name =~ /\/[12]$/) { $acc = $read_name; } if (! exists $scaff_to_partitions{$scaff}) { # no partitions... should explore why this is. print STDERR "-warning, no read partitions defined for scaffold: $scaff\n"; next; } my $aligned_strand = $sam_entry->get_query_strand(); my $opposite_strand = ($aligned_strand eq '+') ? '-' : '+'; if ($aligned_strand eq '-') { # restore to actual sequenced bases $seq = &reverse_complement($seq); } if ($SS_lib_type) { ## got SS data my $transcribed_orient; if (! $sam_entry->is_paired()) { if ($SS_lib_type !~ /^(F|R)$/) { confess "Error, read is not paired but SS_lib_type set to paired: $SS_lib_type\nread:\n$_"; } if ($SS_lib_type eq "R") { $seq = &reverse_complement($seq); } } else { ## Paired reads. if ($SS_lib_type !~ /^(FR|RF)$/) { confess "Error, read is paired but SS_lib_type set to unpaired: $SS_lib_type\nread:\n$_"; } my $first_in_pair = $sam_entry->is_first_in_pair(); if ( ($first_in_pair && $SS_lib_type eq "RF") || ( (! $first_in_pair) && $SS_lib_type eq "FR") ) { $seq = &reverse_complement($seq); } } } my $new_partition_flag = 0; ## prime ordered partitions if first entry or if switching scaffolds. if ($scaff ne $current_scaff) { $current_scaff = $scaff; @ordered_partitions = @{$scaff_to_partitions{$scaff}}; $current_partition = shift @ordered_partitions; $partition_counter = 0; $new_partition_flag = 1; } elsif ($current_partition && $start > $current_partition->{rend}) { $current_partition = shift @ordered_partitions; $partition_counter++; $new_partition_flag = 1; } if ($new_partition_flag) { close $ofh if $ofh; $ofh = undef; close $sam_ofh if $sam_ofh; $sam_ofh = undef; if ($read_counter < $MIN_READS_PER_PARTITION) { # delete these read files. #print STDERR "-- too few reads ($read_counter), removing partition: $part_file\n"; unlink($part_file, $sam_part_file); } $read_counter = 0; } ## check to see if we're in a partition if (defined($current_partition) && $start >= $current_partition->{lend} && $start <= $current_partition->{rend}) { # may need to start a new ofh for this partition if not already established. unless ($ofh) { # create new one. my $file_part_count = int($partition_counter/$PARTS_PER_DIR); my $outdir = "$partitions_dir/" . $current_partition->{scaff} . "/$file_part_count"; $outdir =~ s/[\;\|]/_/g; mkpath($outdir) if (! -d $outdir); unless (-d $outdir) { die "Error, cannot mkdpath $outdir"; } $part_file = "$outdir/" . join("_", $current_partition->{lend}, $current_partition->{rend}) . ".trinity.reads"; open ($ofh, ">$part_file") or die "Error, cannot write ot $part_file"; print STDERR "-writing to $part_file\n"; print $track_fh join("\t", $scaff, $current_partition->{lend}, $current_partition->{rend}, $part_file) . "\n"; $sam_part_file = "$outdir/" . join("_", $current_partition->{lend}, $current_partition->{rend}) . ".sam"; open ($sam_ofh, ">$sam_part_file") or die "Error, cannot open $sam_part_file"; } # write to partition print $ofh ">$acc\n$seq\n"; print $sam_ofh join("\t", $sam_entry->get_fields()) . "\n";; $read_counter++; } } close $track_fh; close $ofh if $ofh; close $sam_ofh if $sam_ofh; exit(0); } #### sub parse_partitions { my ($partitions_file) = @_; my %scaff_to_parts; print STDERR "// parsing paritions.\n"; my $counter = 0; open (my $fh, $partitions_file) or die "Error, cannot open file $partitions_file"; while (<$fh>) { chomp; if (/^\#/) { next; } unless (/\w/) { next; } $counter++; print STDERR "\r[$counter] " if $counter % 100 == 0; my @x = split(/\t/); my $scaff = $x[0]; my $lend = $x[3]; my $rend = $x[4]; my $orient = $x[6]; push (@{$scaff_to_parts{$scaff}}, { scaff => $scaff, lend => $lend, rend => $rend, } ); } print STDERR "\r[$counter] "; close $fh; # should be sorted, but let's just be sure: foreach my $scaff (keys %scaff_to_parts) { @{$scaff_to_parts{$scaff}} = sort {$a->{lend}<=>$b->{lend}} @{$scaff_to_parts{$scaff}}; } return(%scaff_to_parts); }
ssn1306/trinityrnaseq
util/support_scripts/extract_reads_per_partition.pl
Perl
bsd-3-clause
7,038
package DDG::Goodie::IsAwesome::gokul1794; # ABSTRACT: gokul1794's first goodie use DDG::Goodie; use strict; zci answer_type => "is_awesome_gokul1794"; zci is_cached => 1; triggers start => "duckduckhack gokul1794"; handle remainder => sub { return if $_; return "gokul1794 is awesome and has successfully completed the DuckDuckHack Goodie tutorial!"; }; 1;
aleksandar-todorovic/zeroclickinfo-goodies
lib/DDG/Goodie/IsAwesome/gokul1794.pm
Perl
apache-2.0
373
#!/opt/lampp/bin/perl use DBI; print "Content-Type: text/html\n\n"; my $dsn="dbi:mysql:phonebook:localhost"; my $dbh=DBI->connect("$dsn","oswald","geheim") or die "Kann Datenbank nicht erreichen!"; print "<html>"; print "<head>"; print "<title>Perl und MySQL</title>"; print "</head>"; print "<body>"; print "<h1>Perl und MySQL</h1>"; print "<table border=\"1\">"; print "<tr>"; print "<th>Vorname</th>"; print "<th>Nachname</th>"; print "<th>Telefonnummer</th>"; print "</tr>"; my $query="SELECT * FROM users"; my $prep_sql=$dbh->prepare($query) or die print "Can't prepare"; $prep_sql->execute() or die print "Can't execute"; while (my @row = $prep_sql->fetchrow_array()) { print "<tr>"; print "<td>".$row[1]."</td>"; print "<td>".$row[2]."</td>"; print "<td>".$row[3]."</td>"; print "</tr>"; } $prep_sql->finish(); $dbh->disconnect(); print "</table>"; print "</body>"; print "</html>";
Dokaponteam/ITF_Project
xampp/contrib/mysql.pl
Perl
mit
928
%Source: https://sites.google.com/site/prologsite/prolog-problems %query:slice(g,g,g,f). % 1.18 (**): Extract a slice from a list % slice(L1,I,K,L2) :- L2 is the list of the elements of L1 between % index I and index K (both included). % (list,integer,integer,list) (?,+,+,?) slice([X|_],1,1,[X]). slice([X|Xs],1,K,[X|Ys]) :- K > 1, K1 is K - 1, slice(Xs,1,K1,Ys). slice([_|Xs],I,K,Ys) :- I > 1, I1 is I - 1, K1 is K - 1, slice(Xs,I1,K1,Ys).
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Prolog/Hett/p1_18.pl
Perl
mit
471
use v5.14; use utf8; use encoding 'utf8'; use IO::All; use Perl6::Perl qw(perl); use Data::Dumper; my $in = io("twzip.txt")->utf8->chomp; my %zip; my $area; while(defined($_ = $in->getline)) { next unless $_; if (/^\s*(.+)\s+(\d+)$/) { if (exists $zip{$1}) { $zip{$1} = undef; } else { $zip{$1} = $2; } $zip{"$area$1"} = $2; $zip{$2} = "$area$1"; } else { $area = $_; } } # say perl(\%zip); $Data::Dumper::Useqq = 1; $Data::Dumper::Terse = 1; { no warnings 'redefine'; sub Data::Dumper::qquote { my $s = shift; return "'$s'"; } } print 'my $ZIPCODE = ' . Dumper(\%zip) . ";\n";
gitpan/Data-Zipcode-TW
doc/twzip.pl
Perl
mit
715
package CXGN::BrAPI::v1::ObservationUnits; use Moose; use Data::Dumper; use SGN::Model::Cvterm; use CXGN::Trial; use CXGN::Trait; use CXGN::Phenotypes::SearchFactory; use CXGN::BrAPI::Pagination; use CXGN::BrAPI::JSONResponse; use Try::Tiny; use CXGN::Phenotypes::PhenotypeMatrix; use CXGN::List::Transform; extends 'CXGN::BrAPI::v1::Common'; sub search { my $self = shift; my $params = shift; my $page_size = $self->page_size; my $page = $self->page; my $status = $self->status; my @data_files; my $data_level = $params->{observationLevel}->[0] || 'all'; my $years_arrayref = $params->{seasonDbId} || ($params->{seasonDbIds} || ()); my $location_ids_arrayref = $params->{locationDbId} || ($params->{locationDbIds} || ()); my $study_ids_arrayref = $params->{studyDbId} || ($params->{studyDbIds} || ()); my $accession_ids_arrayref = $params->{germplasmDbId} || ($params->{germplasmDbIds} || ()); my $observation_unit_names_list = $params->{observationUnitName} || ($params->{observationUnitNames} || ()); my $trait_list_arrayref = $params->{observationVariableDbId} || ($params->{observationVariableDbIds} || ()); my $program_ids_arrayref = $params->{programDbId} || ($params->{programDbIds} || ()); my $folder_ids_arrayref = $params->{trialDbId} || ($params->{trialDbIds} || ()); my $start_time = $params->{observationTimeStampRangeStart}->[0] || undef; my $end_time = $params->{observationTimeStampRangeEnd}->[0] || undef; # not part of brapi standard yet # my $phenotype_min_value = $params->{phenotype_min_value}; # my $phenotype_max_value = $params->{phenotype_max_value}; # my $exclude_phenotype_outlier = $params->{exclude_phenotype_outlier} || 0; # my $search_type = $params->{search_type}->[0] || 'MaterializedViewTable'; my $lt = CXGN::List::Transform->new(); my $trait_ids_arrayref = $lt->transform($self->bcs_schema, "traits_2_trait_ids", $trait_list_arrayref)->{transform}; my $limit = $page_size*($page+1)-1; my $offset = $page_size*$page; my $phenotypes_search = CXGN::Phenotypes::SearchFactory->instantiate( 'MaterializedViewTable', { bcs_schema=>$self->bcs_schema, data_level=>$data_level, trial_list=>$study_ids_arrayref, trait_list=>$trait_ids_arrayref, include_timestamp=>1, year_list=>$years_arrayref, location_list=>$location_ids_arrayref, accession_list=>$accession_ids_arrayref, folder_list=>$folder_ids_arrayref, program_list=>$program_ids_arrayref, observation_unit_names_list=>$observation_unit_names_list, limit=>$limit, offset=>$offset, # phenotype_min_value=>$phenotype_min_value, # phenotype_max_value=>$phenotype_max_value, # exclude_phenotype_outlier=>$exclude_phenotype_outlier } ); my ($data, $unique_traits) = $phenotypes_search->search(); # print STDERR Dumper $data; my @data_window; my $total_count = 0; foreach my $obs_unit (@$data){ my @brapi_observations; my $observations = $obs_unit->{observations}; foreach (@$observations){ my $obs_timestamp = $_->{collect_date} ? $_->{collect_date} : $_->{timestamp}; if ( $start_time && $obs_timestamp < $start_time ) { next; } #skip observations before date range if ( $end_time && $obs_timestamp > $end_time ) { next; } #skip observations after date range push @brapi_observations, { observationDbId => qq|$_->{phenotype_id}|, observationVariableDbId => qq|$_->{trait_id}|, observationVariableName => $_->{trait_name}, observationTimeStamp => $obs_timestamp, season => $obs_unit->{year}, collector => $_->{operator}, value => qq|$_->{value}|, }; } my @brapi_treatments; my $treatments = $obs_unit->{treatments}; while (my ($factor, $modality) = each %$treatments){ my $modality = $modality ? $modality : ''; push @brapi_treatments, { factor => $factor, modality => $modality, }; } my $entry_type = $obs_unit->{obsunit_is_a_control} ? 'check' : 'test'; push @data_window, { observationUnitDbId => qq|$obs_unit->{observationunit_stock_id}|, observationLevel => $obs_unit->{observationunit_type_name}, observationLevels => $obs_unit->{observationunit_type_name}, plotNumber => $obs_unit->{obsunit_plot_number}, plantNumber => $obs_unit->{obsunit_plant_number}, blockNumber => $obs_unit->{obsunit_block}, replicate => $obs_unit->{obsunit_rep}, observationUnitName => $obs_unit->{observationunit_uniquename}, germplasmDbId => qq|$obs_unit->{germplasm_stock_id}|, germplasmName => $obs_unit->{germplasm_uniquename}, studyDbId => qq|$obs_unit->{trial_id}|, studyName => $obs_unit->{trial_name}, studyLocationDbId => qq|$obs_unit->{trial_location_id}|, studyLocation => $obs_unit->{trial_location_name}, programName => $obs_unit->{breeding_program_name}, X => $obs_unit->{obsunit_col_number}, Y => $obs_unit->{obsunit_row_number}, entryType => $entry_type, entryNumber => '', treatments => \@brapi_treatments, observations => \@brapi_observations, observationUnitXref => [], pedigree => undef }; $total_count = $obs_unit->{full_count}; } my %result = (data=>\@data_window); my $pagination = CXGN::BrAPI::Pagination->pagination_response($total_count,$page_size,$page); return CXGN::BrAPI::JSONResponse->return_success(\%result, $pagination, \@data_files, $status, 'Phenotype search result constructed'); } 1;
solgenomics/sgn
lib/CXGN/BrAPI/v1/ObservationUnits.pm
Perl
mit
6,070
%query: type(i,i,o). type(E,var(X),T) :- in(E,X,T). type(E,apply(M,N),T) :- type(E,M,arrow(S,T)),type(E,N,S). type(E,lambda(X,M),arrow(S,T)) :- type([(X,S)|E],M,T). in([(X,T)|E],X,T). in([(Y,T)|E],X,T) :- X\==Y, in(E,X,T).
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Prolog/prolog_mixed/curry_ap.pl
Perl
mit
225
package HMF::Pipeline::PipelineCheck; use FindBin::libs; use discipline; use File::Spec::Functions; use HMF::Pipeline::Functions::Config qw(allRunningJobs createDirs); use HMF::Pipeline::Functions::Sge qw(qsubTemplate); use HMF::Pipeline::Functions::Job qw(fromTemplate); use parent qw(Exporter); our @EXPORT_OK = qw(run); sub run { my ($opt) = @_; say "\n### SCHEDULING PIPELINE CHECK ###"; my $dirs = createDirs($opt->{OUTPUT_DIR}); my $pipeline_check_file = "PipelineCheck.log"; my $pipeline_check_job_id = fromTemplate( "PipelineCheck", undef, 0, qsubTemplate($opt, "PIPELINE_CHECK"), allRunningJobs($opt), $dirs, $opt, done_files => $opt->{DONE_FILES}, log_file => catfile($dirs->{log}, $pipeline_check_file), ); push @{$opt->{RUNNING_JOBS}->{pipelinecheck}}, $pipeline_check_job_id; return; } 1;
hartwigmedical/pipeline
lib/HMF/Pipeline/PipelineCheck.pm
Perl
mit
917
use utf8; package Schema; use strict; use warnings; use base 'DBIx::Class::Schema'; our $VERSION = <%= version %>; __PACKAGE__->load_namespaces; 1;
rayokota/generator-angular-mojolicious
app/templates/lib/_Schema.pm
Perl
mit
153
############################################################################## # Copyright (c) 2009 Six Apart # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom # the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR # THE USE OR OTHER DEALINGS IN THE SOFTWARE. package reCaptcha; use strict; use warnings; use base qw(MT::ErrorHandler); sub debuglog { return unless MT->config->ReCaptchaDebug; my $msg = shift || return; require MT; MT->log({ message => "reCaptcha: $msg", level => MT::Log::DEBUG(), }); } sub form_fields { my $self = shift; my ($blog_id) = @_; my $plugin = MT::Plugin::reCaptcha->instance; my $config = $plugin->get_config_hash("blog:$blog_id"); my $publickey = $config->{recaptcha_publickey}; my $privatekey = $config->{recaptcha_privatekey}; return q() unless $publickey && $privatekey; return <<FORM_FIELD; <script type="text/javascript" src="//www.google.com/recaptcha/api.js" async defer> </script> <div id="recaptcha_script" class="g-recaptcha" data-sitekey="$publickey"> </div> <noscript> <iframe src="//www.google.com/recaptcha/api/fallback?k=$publickey" height="302" width="422" frameborder="0"></iframe><br> <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response"></textarea> </noscript> <script type="text/javascript"> if ( typeof(mtCaptchaVisible) != "undefined" ) mtCaptchaVisible = true; else if ( typeof(commenter_name) != "undefined" ) { var div = document.getElementById("recaptcha_script"); if (commenter_name) div.style.display = "none"; else div.style.display = "block"; } </script> FORM_FIELD } sub validate_captcha { my $self = shift; my ($app) = @_; my $blog_id = $app->param('blog_id'); if ( my $entry_id = $app->param('entry_id') ) { my $entry = $app->model('entry')->load($entry_id) or return 0; $blog_id = $entry->blog_id; }; return 0 unless $blog_id; return 0 unless $app->model('blog')->count( { id => $blog_id } ); my $config = MT::Plugin::reCaptcha->instance->get_config_hash("blog:$blog_id"); my $privatekey = $config->{recaptcha_privatekey}; my $response = $app->param('g-recaptcha-response'); my $ua = $app->new_ua({ timeout => 15, max_size => undef }); return 0 unless $ua; require HTTP::Request; my $req = HTTP::Request->new(POST => 'https://www.google.com/recaptcha/api/siteverify'); $req->content_type("application/x-www-form-urlencoded"); require MT::Util; my $content = 'secret=' . MT::Util::encode_url($privatekey); $content .= '&remoteip=' . MT::Util::encode_url($app->remote_ip); $content .= '&response=' . MT::Util::encode_url($response); $req->content($content); debuglog("sending verification request: '$content'"); my $res = $ua->request($req); my $c = $res->content; if (substr($res->code, 0, 1) eq '2') { if ($c =~ /[{,]\s*"success"\s*:\s*true\s*[,}]\n/) { debuglog("submitted code is valid: '$c'"); return 1; } debuglog("submitted code is not valid: '$c'"); } else { debuglog("verification failed: response code: '" . $res->code . "', content: '$c'"); } return 0; } sub generate_captcha { # This won't be called since there is no link which requests to "generate_captcha" mode. my $self = shift; 1; } 1;
movabletype/mt-plugin-recaptcha
plugins/reCaptcha/lib/reCaptcha.pm
Perl
mit
4,360
/************************************************************************* File: alphaConversion.pl Copyright (C) 2004 Patrick Blackburn & Johan Bos This file is part of BB1, version 1.2 (August 2005). BB1 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. BB1 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with BB1; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ :- module(alphaConversion,[alphaConvert/2, alphabeticVariants/2]). :- use_module(comsemPredicates,[compose/3, memberList/2]). /*======================================================================== Alpha Conversion (introducing substitutions) ========================================================================*/ alphaConvert(F1,F2):- alphaConvert(F1,[],[]-_,F2). /*======================================================================== Alpha Conversion ========================================================================*/ alphaConvert(X,Sub,Free1-Free2,Y):- var(X), ( memberList(sub(Z,Y),Sub), X==Z, !, Free2=Free1 ; Y=X, Free2=[X|Free1] ). alphaConvert(Expression,Sub,Free1-Free2,some(Y,F2)):- nonvar(Expression), Expression = some(X,F1), alphaConvert(F1,[sub(X,Y)|Sub],Free1-Free2,F2). alphaConvert(Expression,Sub,Free1-Free2,all(Y,F2)):- nonvar(Expression), Expression = all(X,F1), alphaConvert(F1,[sub(X,Y)|Sub],Free1-Free2,F2). alphaConvert(Expression,Sub,Free1-Free2,lam(Y,F2)):- nonvar(Expression), Expression = lam(X,F1), alphaConvert(F1,[sub(X,Y)|Sub],Free1-Free2,F2). alphaConvert(Expression,Sub,Free1-Free3,que(Y,F3,F4)):- nonvar(Expression), Expression = que(X,F1,F2), alphaConvert(F1,[sub(X,Y)|Sub],Free1-Free2,F3), alphaConvert(F2,[sub(X,Y)|Sub],Free2-Free3,F4). alphaConvert(F1,Sub,Free1-Free2,F2):- nonvar(F1), \+ F1 = some(_,_), \+ F1 = all(_,_), \+ F1 = lam(_,_), \+ F1 = que(_,_,_), compose(F1,Symbol,Args1), alphaConvertList(Args1,Sub,Free1-Free2,Args2), compose(F2,Symbol,Args2). /*======================================================================== Alpha Conversion (listwise) ========================================================================*/ alphaConvertList([],_,Free-Free,[]). alphaConvertList([X|L1],Sub,Free1-Free3,[Y|L2]):- alphaConvert(X,Sub,Free1-Free2,Y), alphaConvertList(L1,Sub,Free2-Free3,L2). /*======================================================================== Alphabetic Variants ========================================================================*/ alphabeticVariants(Term1,Term2):- alphaConvert(Term1,[],[]-Free1,Term3), alphaConvert(Term2,[],[]-Free2,Term4), Free1==Free2, numbervars(Term3,0,_), numbervars(Term4,0,_), Term3=Term4.
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/CURT/bb1/alphaConversion.pl
Perl
mit
3,400
#!/usr/bin/perl #use LaTeX::TOM; use Data::Dumper; use HTML::Entities; use Cwd; use File::Basename; $timeout = 60; # seconds until render call is considered locked $timeoutprog = "/var/www/noosphere/bin/timeout -t 30"; #writing my own math mode latex parser # foreach my $f (@ARGV) { runme($f); } exit(); sub runme { my $filename = shift; #my $parser = new LaTeX::TOM->new(0,0,1); my $latexsource = `texexpand $filename`; $latexsource =~ s/[^\\]\\\[/\$\$/g; $latexsource =~ s/[^\\]\\\]/\$\$/g; #my $document = $parser->parse($latexsource); #print Dumper ($parser->{USED_COMMANDS}); #print "parsing done"; #$latexsource = $document->toLaTeX; # # don't uncomment this #print STDERR "After parsing:\n$latexsource\n"; #build the jsMath macros for user defined commands #This is the form of newcommand: #\newcommand{\ad}{\mathrm{ad}} # #\newcommand{\Aff}[2]{ \mathrm{Aff}_{#1} #2} #\def\Bset{\mathbb{B}} #% \frac overwrites LaTeX's one (use TeX \over instead) #%def\fraq#1#2{{}^{#1}\!/\!{}_{\,#2}} #\def\frac#1#2{\mathord{\mathchoice% #{\T{#1\over#2}} #{\T{#1\over#2}} #{\S{#1\over#2}} #{\SS{#1\over#2}}}} #%def\half{\frac12} # we need to genereate the jsMath javacript code #this is a list of unsupported environments and commands that we force l2h to handle # once jsmath supports the environment it should be removed from this list my @unsupported = ("\\begin{pspicture}", "\\xymatrix", "\\mathbbm", "\\mathbbmss", "\\begin{align", "\\ensuremath", "\\begin{picture}" , "\\lhd", "\\\$", "\\mathscr", "\\begin{array", "\\dotsc", "\\qedhere" , "\\Box", "\\hspace", "\\boldmath", "\\dotsb", "\\mathsf" , "\\begin{cases", "\\begin{xy", "\\hdots", "\\label"); my $commands = ""; #while ( $latexsource =~ /\\newcommand{(.*)}(\[\d+\])?{(.*)}/g ) { # my $command = $1; # my $num = $2; # my $content = $3; # $num =~ s/\[//g; # $num =~ s/\]//g; # $content =~ s/\\/\\\\/g; # print STDERR "defining '$command' '$num' '$content'\n"; # $command =~ s/^\\//; # $num = 0 if ( $num eq '' ); # $commands .= "<SCRIPT> jsMath.Macro( '$command', '$content', $num) </SCRIPT>\n"; #} # if a definied command actually uses an unsupported environment call we must also put # it in the unsupported list - nifty huh? my @chars = split( /(\W)/, $latexsource ); for ( my $i = 0; $i < @chars; $i++ ) { if ( $chars[$i] eq "" ) { splice ( @chars, $i, 1 ); } } for ( my $i = 0; $i < @chars; $i++ ) { # print "$chars[$i]\n"; if ( $chars[$i] eq "\\" ) { $i++; if ( ($chars[$i] eq "def") || ($chars[$i] =~ /command/) ) { if ( $chars[$i] eq "newcommand" || $chars[$i] eq "providecommand" ) { $i++; my $command = ""; ($command, $i) = readToNextMatch( '{' , '}', \@chars, $i); # print "detected new or provide command: $command\n"; $i++; my $numargs = 0; if ( $chars[$i] eq '[' ) { ($numargs,$i) = readToNextMatch( '[' , ']', \@chars, $i); $i++; } my $content = ""; ($content, $i) = readToNextMatch( '{' , '}', \@chars, $i); # print "Building (\n$command\n$numargs\n$content\n)\n"; $command =~ s/\\//; foreach my $u ( @unsupported ) { # print "checking if $content contains $u\n"; my $b = $u; $b =~ s/\\/\\\\/; if ( $content =~ /$b/ ) { # print "adding \\$command to unsupported becaues of $b\n"; push @unsupported, "\\$command"; last; } } $content =~ s/\\/\\\\/g; $commands .= "<SCRIPT> jsMath.Macro( '$command', '$content', $numargs) </SCRIPT>\n"; } elsif ( $chars[$i] eq "def" ) { $i++; print "i = $i and chars[i] = $chars[$i]\n"; my $command = ""; ($command, $i) = readToNextMatch( "\\" , '{', \@chars, $i); # print "detected def $command\n"; my $numargs = 0; if ( $command =~ /(\w+)#.*(\d+)/ ) { $command = $1; $numargs = $2; } my $content = ""; ($content, $i) = readToNextMatch ( '{', '}', \@chars, $i); # print "Building (\n$command\n$numargs\n$content\n)\n"; $command =~ s/\\//; foreach my $u ( @unsupported ) { my $b = $u; $b =~ s/\\/\\\\/; if ( $content =~ /$b/ ) { push @unsupported, "\\$command"; last; } } $content =~ s/\\/\\\\/g; $commands .= "<SCRIPT> jsMath.Macro( '$command', '$content', $numargs) </SCRIPT>\n"; } } elsif ( $chars[$i] eq "DeclareMathOperator" ) { $i++; my $command = ""; ($command, $i) = readToNextMatch( '{', '}', \@chars, $i); $command =~ s/\\//; $i++; my $content = ""; ($content, $i) = readToNextMatch( '{', '}', \@chars, $i); $commands .= "<SCRIPT> jsMath.Macro( '$command', '\\\\mathop{\\\\rm $content}', 0) </SCRIPT>\n"; } } } sub readToNextMatch { my $mbegin = shift; #first char to match e.g. ( my $mend = shift; #matching char to first e.g. ) my $charptr = shift; my $index = shift; #(chars can actually be strings) to be parsed in the chars array. my $j = 0; # $j is the number of $m remaining that need to be matched my $textRead = ""; for ( my $i = $index; $i < @$charptr; $i++ ) { if ( $charptr->[$i] eq "$mbegin" ) { $j++; #this is the stack (we only need to count). next if ( $j == 1 ); } elsif ( $charptr->[$i] eq "$mend") { $j--; if ( $j == 0 ) { #done we found the matching } #return all of the text read up until now #and return the number of characters read. # or we could return the rest of the characters. return ( $textRead, $i ); } } if ( $j > 0 ) { $textRead .= $charptr->[$i]; } } } my @matharray = (); my $mathcnt = 0; my @results = (); my @tokens = split( /(\W)/ , $latexsource ); for (my $i = 0; $i < $#tokens+1; $i++ ) { if ( $tokens[$i] eq '' ) { splice( @tokens, $i, 1); } } # these commands switch out of math mode. #(\\textrm|\\textsl|\\textit|\\texttt|\\textbf|\\text|\\hbox) my $j = 0; my $mathcontent = ""; #we should rework this parsing. It relies a little too much on string matching #which can cause errors based on the content of the articles. for (my $i = 0; $i < $#tokens+1; $i++) { if ( $tokens[$i] eq '$' && $tokens[$i-1] ne "\\" ) { $mathcontent = ""; if ( $tokens[$i+1] eq '$' ) { # print "found begin of newline \$\$\n"; #this is seperate line math mode; for( $j=$i+2; $j < $#tokens+1; $j++ ) { if ( $tokens[$j] eq '$' && $tokens[$j+1] eq '$' ) { # print "found end of \$\$\n"; last; } $mathcontent .= $tokens[$j]; } $i = $j+1; $mathcontent = "\$\$$mathcontent\$\$"; } else { #this is inline math mode; # print "found begin of inline \$\n"; my $waitForBrace = 0; for( $j=$i+1; $j < $#tokens+1; $j++ ) { if ( $tokens[$j] eq "\\" && $tokens[$j+1] =~ /(textrm|textsl|textit|texttt|textbf|text|hbox)/ ) { my $numlbrace = 0; my $k = $j+2; for ( $k = $j+2; $k < $#tokens+1; $k++ ) { $mathcontent .= $tokens[$k]; if ( $tokens[$k] eq '{' ) { $numlbrace++; } elsif ( $tokens[$k] eq '}' ) { $numlbrace--; if ( $numlbrace == 0 ) { last; } } } $j = $k+1; } if ( $tokens[$j] eq '$') { #print "found end of \$\n"; last; } $mathcontent .= $tokens[$j]; } $i = $j; $mathcontent = "\$$mathcontent\$"; } # print "Storing math: [$mathcontent]\n"; $matharray[$mathcnt] = $mathcontent; push @results, "JG-" . $mathcnt++ . "-JG "; } elsif ($tokens[$i] eq "\\" && $tokens[$i+1] !~ /htmladdn/) { my $text = join( '', @tokens[$i..($i+4)] ); my $j = 0; if ( $text =~ /begin{eqnarray/ || $text=~ /begin{equation/ || $text =~ /begin{align/ || $text =~ /begin{pspicture/ || $text =~ /begin{picture/ || $text =~ /begin{array/ ) { # print "begin equation type environment\n"; # print "[$text]\n"; $mathcontent = $text; for ( $j = $i+5; $j < $#tokens+1; $j++ ) { $text = join( '', @tokens[$j..($j+4)] ); if ( $text =~ /end{eqnarray.*}/ || $text =~ /end{equation.*}/ || $text =~ /end{align.*}/ || $text =~ /end{pspicture}/ || $text =~ /end{array.*}/ ) { # print "end equation type environment\n"; $mathcontent .= $text; last; } else { $mathcontent .= $tokens[$j]; } } $matharray[$mathcnt] = $mathcontent; push @results, "JG-" . $mathcnt++ . "-JG"; $i = $j+5; } else { push @results, $tokens[$i]; } #handle environments } else { push @results, $tokens[$i]; } } #foreach my $r ( @results ) { # print "[$r]\n"; #} #print STDERR Dumper( \@matharray ); my $preprocessedTex = join( '', @results ); #we now loop through and replace the environments that are currently not supported by jsmath. #Note we still leave align and equation stuff even though it causes jsmath to crash because jsmath # is supposed to support it #print "unsupported used commands in this article are @unsupported\n"; for ( my $i = 0; $i < $#matharray+1; $i++ ) { my $math = $matharray[$i]; foreach my $u ( @unsupported ) { my $b = $u; $b =~ s/\\/\\\\/; if ( $math =~ /$b/ ) { $preprocessedTex =~ s/JG-$i-JG/$math/; last; } } } $filename =~ s/\.tex/-pre.tex/; open ( OUT, ">$filename" ); #open ( OUT, ">./temp/$filename" ); print OUT $preprocessedTex; close (OUT); #chdir( "./temp/" ); #`latex \"$filename\"`; #`bibtex \"$short\"`; #`latex \"$filename\"`; #`latex \"$filename\"`; # we need to change to the correct directory. my $dir = dirname( $filename ); my $currentdir = `pwd`; chdir "$dir"; print "checkpoint 1\n"; #we need to implement this if statment and only run latex if # we need to. #my $reruns = "ref|eqref|cite"; #if ($latex =~ /\\($reruns)\W/) { `latex "$filename" 1>&2 2>/dev/null`; #} print "checkpoint 2\n"; #`ulimit -t $timeout ; latex2html "$filename" 1>&2 2>/dev/null`; `$timeoutprog latex2html "$filename" 1>&2 2>/dev/null`; chdir "$currentdir"; print "checkpoint 3\n"; open( IN, "index.html" ); my $html = ""; while ( <IN> ) { $html .= $_; } close( IN ); print "checkpoint 4\n"; for (my $i=0; $i < $#matharray+1; $i++ ){ my $math = $matharray[$i]; encode_entities($math, q{<>&"'}); $html =~ s/JG-$i-JG/<SPAN class=\"nolink\">$math<\/SPAN>/g; } #my $script = "<SCRIPT SRC=\"http://images.planetmath.org:8089/jsMath/easy/load.js\"></SCRIPT>"; $html =~ s/<body.*?>/<body>$commands/i; print "checkpoint 5\n"; open( OUT , ">index.html" ); print OUT $html; close( OUT ); #chdir ( ".."); }
holtzermann17/Noosphere
bin/preprocess-jsmath.pl
Perl
mit
10,268
use MooseX::Declare; use strict; use warnings; class Bwa extends Common { #####////}}}}} use FindBin qw($Bin); use Agua::CLI::App; use Conf::Yaml; # Strings has 'batchsize' => ( isa => 'Int|Undef', is => 'rw', default => 5 ); # Strings has 'sleep' => ( isa => 'Str|Undef', is => 'rw', default => 10 ); has 'version' => ( isa => 'Str|Undef', is => 'rw', default => "v1.0.4" ); # Objects has 'conf' => ( isa => 'Conf::Yaml', is => 'rw', lazy => 1, builder => "setConf" ); method align ($inputdir, $inputsuffix, $filename, $outputdir, $reference, $threads, $workdir, $version, $batchsize) { $self->logDebug("inputdir", $inputdir); $self->logDebug("inputsuffix", $inputsuffix); $self->logDebug("filename", $filename); $self->logDebug("outputdir", $outputdir); $self->logDebug("workdir", $workdir); $self->logDebug("version", $version); $self->logDebug("reference", $reference); #### SET VERSION $version = $self->version() if not defined $version; $self->logDebug("FINAL version", $version); #### GET EXECUTABLE my $installdir = $self->getInstallDir("pcap"); $self->logDebug("installdir", $installdir); my $executable = "$installdir/bin/bwa_mem.pl"; #### GET INPUT FILES my $regex = $inputsuffix; $regex =~ s/\./\\./g; $regex .= "\$"; $self->logDebug("regex", $regex); my $inputfiles = $self->getFilesByRegex($inputdir, $regex); $self->logDebug("inputfiles", $inputfiles); foreach my $inputfile ( @$inputfiles ) { $inputfile = "$inputdir/$inputfile"; } #### SET FILE STUB my ($filestub) = $filename =~ /^(.+)\.[^\.]+$/; $self->logDebug("filestub", $filestub); #### SET THREADS $threads = $self->getCpus() if not defined $threads; print "threads: $threads\n"; #### RUN $batchsize = $self->batchsize() if not defined $batchsize; $self->logDebug("batchsize", $batchsize); #### CREATE OUTPUTDIR `mkdir -p $outputdir` if not -d $outputdir; my $counter = 1; while ( scalar(@$inputfiles) > 0 ) { my $batch; @$batch = splice(@$inputfiles, 0, $batchsize); $self->logDebug("batch", $batch); my $outfile = $filestub . "-$counter"; my $command = "$executable -r $reference -t $threads -o $outputdir -s $outfile @$batch -workdir $workdir"; $self->logDebug("command", $command); print "Bwa command: $command\n"; `$command`; $counter++; } } }
agua/dnaseq
lib/Bwa.pm
Perl
mit
2,344
package Database::Connect; use Moose; use autodie; use re 'taint'; use 5.010; our $VERSION = 1.0529;# Created: 2010-03-16 use Config::Tiny; use Path::Class; =pod =head1 NAME Database::Connect - Connect to your databases =head1 SYNOPSIS use strict; use Database::Connect; my $dbc = Database::Connect->new; # information gathering say $dbc->dsn("mydb"); # Use with DBI my $dbh = $dbc->dbh("mydb"); my $dbh2 = DBI->connect( $dbc->dbi_args("mydb") ); $dbc->on_connect("mydb")->($dbh2); # DBIx::Simple my $dbs = $dbc->dbix_simple("mydb"); # DBIx::Class my $schema = $dbc->dbic_schema_connect("mydb"); my $schema1 = $dbc->dbic_schema_connect("mydb", undef, 'My::Other::Schema'); my $schema2 = MySchema->connect( $dbc->dbi_args("mydb"), { AutoCommit => 1, RaiseError => 1 }, { on_connect_do => [ $dbc->on_connect_sql("mydb") ] }, ); # Catalyst::Model::DBIC::Schema my $mydb = "mydb"; __PACKAGE__->config( schema_class => $dbc->dbic_schema($mydb), connect_info => [ $dbc->dbi_args($mydb), { AutoCommit => 1, RaiseError => 1 }, { on_connect_do => [ $dbc->on_connect_sql($mydb) ] }, ], ); =head1 DESCRIPTION Reads and processes Database connection information from: /etc/databases/conf.d/* $ENV{HOME}/.databases/* A configuration file contains one or more sections of the form: [mydb] dbd = Pg schema_search_path = foo, public dbic_schema = My::Schema::Class dbname = my_test_db host = 127.0.0.1 username = guest password = 12345 Access to these files should be controlled by standard operating system file access permissions; If the runner of the script can read the file, they will be granted access. It is the goal of this module to (as much as is reasonable) relieve the burden of managing database connection information. Including, but not limited to: =over 4 =item * Switching database names, drivers, and/or hosts without requiring modification of source code (assuming code uses an ORM or compatible SQL). =item * Support Pg schemas as painlessly as possible. =back =head1 USAGE =cut has search_paths => traits => ['Array'], is => 'ro', isa => 'ArrayRef[Str]', handles => { push_path => 'push', unshift_path => 'unshift', remove_path => 'delete', set_paths => 'set', }, lazy_build => 1, ; has sources => traits => ['Hash'], isa => 'HashRef[HashRef[Str]]', default => sub { {} }, handles => { _set_source => 'set', _get_source => 'get', delete_source => 'delete', has_source => 'exists', forget_sources => 'clear', sources => 'keys', }, ; has loaded => traits => ['Bool'], is => 'ro', isa => 'Bool', default => 0, handles => { _set_loaded => 'set', reload_sources => 'unset', }, ; our %DBD_PARAMS; $DBD_PARAMS{pg} ||= [ qw/ host hostaddr port options service sslmode /, [qw/ database dbname db /] ]; $DBD_PARAMS{mysql} ||= [ qw/ host port mysql_client_found_rows mysql_compression mysql_connect_timeout mysql_read_default_file mysql_read_default_group mysql_socket mysql_ssl mysql_ssl_client_key mysql_ssl_client_cert mysql_ssl_ca_file mysql_ssl_ca_path mysql_ssl_cipher mysql_local_infile mysql_multi_statements mysql_server_prepare mysql_embedded_options mysql_embedded_groups /, [qw/ database dbname db /] ]; $DBD_PARAMS{sqlite} ||= [ [qw/ dbname database db /] ]; $DBD_PARAMS{csv} ||= [qw/ f_dir csv_eol csv_sep_char csv_quote_char csv_escape_char csv_class /]; $DBD_PARAMS{dbm} ||= [qw/ f_dir ext mldbm lockfile store_metadata cols /, [qw/ type dbm_type /]]; before qw/ has_source sources _get_source /, sub { my $self = shift; $self->_load_sources unless $self->loaded; }; sub _build_search_paths { [ "/etc/databases/conf.d", ($ENV{HOME} ? "$ENV{HOME}/.databases" : ()), ] } =head2 Getting Information About a Source =head3 dsn(Str|HashRef $source) =head3 dbd(Str|HashRef $source) =head3 username(Str|HashRef $source) =head3 password(Str|HashRef $source) =head3 schema_search_path(Str|HashRef $source) =head3 dbic_schema(Str|HashRef $source) Each of the above return a string containing the requested information. =head3 db_params(Str|HashRef $source) The parameter portion of the DSN (example: "host=127.0.0.1;database=test_db") =head3 dbi_args(Str|HashRef $source) A list of three items, the dsn, username, and password. Useful when you want to create your own DBI connection. =head3 dbh(Str|HashRef $source, HashRef $dbi_opts?) Open a new DBI connection to the database and execute any C<on_connect> commands. =head3 dbic_schema_connect(Str|HashRef $source, HashRef $dbi_opts?, Str $dbic_schema?) Use the DBIx::Schema class given to connect to the given data source. =cut # $source is Auto-extended via method modifier sub dbh { my ($self, $source, $dbi_opts) = @_; require DBI; my $dbh = DBI->connect($self->dbi_args($source), $dbi_opts || { AutoCommit => 1, RaiseError => 1 }); $self->on_connect($source)->($dbh); return $dbh; } sub dbix_simple { my $self = shift; require DBIx::Simple; DBIx::Simple->connect($self->dbh(@_)); } # $source is Auto-extended via method modifier sub dbic_schema_connect { my ($self, $source, $dbi_opts, $schema_class) = @_; $schema_class ||= $self->dbic_schema($source); eval "require $schema_class; 1" or die $@; $schema_class->connect( $self->dbi_args($source), $dbi_opts || { AutoCommit => 1, RaiseError => 1 }, { on_connect_do => [ $self->on_connect_sql($source) ] } ); } # $source is Auto-extended via method modifier sub dsn { my ($self, $source) = @_; sprintf "dbi:%s:%s", $self->dbd($source), $self->db_params($source); } # $source is Auto-extended via method modifier sub dbi_args { my ($self, $source) = @_; ($self->dsn($source), $self->username($source)//undef, $self->password($source)//undef); } # $source is Auto-extended via method modifier sub on_connect_sql { my ($self, $source) = @_; my @sql; if ($self->dbd($source) eq 'Pg' and $self->schema_search_path($source)) { push @sql, sprintf "SET search_path = '%s'", $self->schema_search_path($source); } return @sql; } # $source is Auto-extended via method modifier sub on_connect { my ($self, $source) = @_; sub { my $dbh = shift; $dbh->do($_) for $self->on_connect_sql($source); } } for (qw/ dbd username password schema_search_path dbic_schema /) { my $prop = $_; no strict 'refs'; *{$prop} = sub { my ($self, $source) = @_; $self->_get_field($source, $prop); } } # $source is Auto-extended via method modifier sub db_params { my ($self, $source) = @_; join ";", map "$$_[0]=$$_[1]", grep 1 < @$_, map [('ARRAY' eq ref($_)?$$_[0]:$_), $self->_get_field($source, $_)], $self->_db_param_fields( $source ); } =head2 Data Loading Connection information is searched for in all files contained in directories in the search path. Standard unix permissions should be used to restrict access to passwords. Files at the beginning of the search path take priority over files at the end if more than one happen to define the same source. =head3 search_paths() ArrayRef of paths to look in to find database connection information. =head3 push_path(Str $new_path) =head3 unshift_path(Str $new_path) =head3 remove_path(Str $old_path) =head3 set_paths =head2 Source Management =head3 delete_source(Str $source) =head3 has_source(Str $source) =head3 forget_sources() =head3 sources() =head3 reload_sources() =cut =head1 CONFIG FILE FORMAT The configuration files use the INI format as parsed by L<Config::Tiny|Config::Tiny>. =over 4 =item * Each section represents one source =item * Multiple sections may appear in each file =back =head2 Source Parameters =over 4 =item dbd [REQUIRED] Database driver as would be used in the second component of a DSN (see L<DBI|DBI>). =item username Database user =item password Database password for user given above =item schema_search_path Search path for use with PostgreSQL. Only used when C<dbd> is "Pg". Should be a comma-separated list of schemas to use as the search path. Identifiers should be quoted as appropriate since this module will not do that for you. =back In addition to the above parameters, any DBD-specific connection parameters may also be present. Some of these parameters are treated specially: =over 4 =item dbname | database | db [TYPICALLY REQUIRED] The database to connect to. Note: Some drivers accept only a subset of the above; You do not need to worry about that as this module will always use whichever name is appropriate for the driver. =back =head1 PRIVATE METHODS =head3 _get_field(HashRef $source, Str|ArrayRef $key) Extract value associated with key from C<$source>. Returns empty list if key does not exist. If C<$key> is an ArrayRef, tries all keys in the array until one exists. =cut # $source is Auto-extended via method modifier sub _get_field { my ($self, $source, $key) = @_; if ('ARRAY' eq ref($key)) { for (@$key) { my @res = $self->_get_field($source, $_); return $res[0] if @res; } } elsif (exists $$source{$key}) { return $$source{$key}; } return; } =head3 _db_param_fields(HashRef $source) Returns list of parameters that are accepted by the DBD associated with C<$source>. =cut sub _db_param_fields { my ($self, $source) = @_; my $dbd = $self->dbd($source); die "Unrecognized DBD '$dbd'" unless exists $DBD_PARAMS{lc $dbd}; @{$DBD_PARAMS{lc $dbd}}; } =head3 _load_sources() Loops through search path and loads all readable config files therein. Does not check that sources were already loaded and does not clear existing sources. =cut sub _load_sources { my $self = shift; for (reverse @{$self->search_paths}) { next unless -d $_; for my $f (grep !$_->is_dir, dir($_)->children) { next unless $f =~ m#/[\w.+-]+$# and -r $f; my $config = Config::Tiny->read( $f ); $self->_set_source( $_, { %{$$config{$_}} } ) for keys %$config; } } $self->_set_loaded; } around qw/ _get_field dbh dbi_args dsn db_params on_connect_sql on_connect dbic_schema_connect /, sub { my ($code, $self, $arg, @rest) = @_; $arg = $self->_get_source($arg) || return unless 'HASH' eq ref($arg); $code->($self, $arg, @rest); }; no Moose; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 AUTHOR Dean Serenevy dean@serenevy.net http://dean.serenevy.net/ =head1 COPYRIGHT This software is hereby placed into the public domain. If you use this code, a simple comment in your code giving credit and an email letting me know that you find it useful would be courteous but is not required. The software is provided "as is" without warranty of any kind, either expressed or implied including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. =head1 SEE ALSO perl(1)
duelafn/perl-misc
lib/Database/Connect.pm
Perl
cc0-1.0
11,269
#!/usr/bin/env perl =head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2020] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut use strict; use Bio::EnsEMBL::Registry; Bio::EnsEMBL::Registry->load_registry_from_db( -host => 'ensembldb.ensembl.org', -user => 'anonymous', ); my $array_adaptor = Bio::EnsEMBL::Registry->get_adaptor('human', 'Funcgen', 'Array'); my $array = $array_adaptor->fetch_by_name_vendor('WholeGenome_4x44k_v1', 'AGILENT'); my $array_chips = $array->get_ArrayChips; # Print some ArrayChip info foreach my $current_array_chip (@$array_chips) { print "ArrayChip: " . $current_array_chip->name . " DesignID: " . $current_array_chip->design_id . "\n"; }
Ensembl/ensembl-funcgen
scripts/examples/arraychip_example.pl
Perl
apache-2.0
1,551
=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 =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 package Bio::EnsEMBL::Variation::Pipeline::SpliceAI::RunSpliceAI; use strict; use warnings; use base ('Bio::EnsEMBL::Variation::Pipeline::SpliceAI::BaseSpliceAI'); use FileHandle; use Bio::EnsEMBL::IO::Parser::BedTabix; use Bio::EnsEMBL::IO::Parser::VCF4Tabix; sub run { my $self = shift; $self->set_chr_from_filename(); $self->run_spliceai(); } sub run_spliceai { my $self = shift; my $main_dir = $self->param_required('main_dir'); my $vcf_input_dir = $self->param('split_vcf_input_dir'); my $vcf_file = $self->param('input_file'); my $split_vcf_output_dir = $self->param_required('split_vcf_output_dir'); my $fasta_file = $self->param_required('fasta_file'); my $gene_annotation = $self->param_required('gene_annotation'); my $chr = $self->param('chr'); my $vcf_input_dir_chr = $vcf_input_dir.'/chr'.$chr; if (! -d $vcf_input_dir_chr) { die("Directory ($vcf_input_dir_chr) doesn't exist"); } my $split_vcf_output_dir_chr = $split_vcf_output_dir."/chr".$chr; my $output_vcf_files_dir = $split_vcf_output_dir_chr."/vcf_files"; if (! -d $output_vcf_files_dir) { die("Directory ($output_vcf_files_dir) doesn't exist"); } my $cmd = "spliceai -I $vcf_input_dir_chr/$vcf_file -O $output_vcf_files_dir/$vcf_file -R $fasta_file -A $gene_annotation"; $self->run_system_command($cmd); } 1;
Ensembl/ensembl-variation
modules/Bio/EnsEMBL/Variation/Pipeline/SpliceAI/RunSpliceAI.pm
Perl
apache-2.0
2,290
#!/usr/bin/perl -w # Copyright 2008-2010,2014-2016 BitMover, 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. # create all the files for fslayer stubs # fslayer.h # fslayer_XXX_stub.c # fslayer.makefile chdir "fslayer"; $bigcmt = "// *******************************************************\n" . "// XXX This file is automatically generated.\n" . "// Edit gen_fslayer.pl instead\n" . "//\n" . "// DO NOT EDIT THIS FILE, YOUR CHANGES WILL BE LOST !!!!!!\n" . "// *******************************************************\n\n"; while(<DATA>) { ($ret, $fcn, $args) = /^(.*)\s+fslayer_(.*)\((.*)\);/; next unless $ret; @args = split(/,\s*/, $args); push(@fcns, $fcn); $data{$fcn} = { RET => $ret, ARGS => join(", ", @args), # args with types ANAMES => join(", ", map {$1 if /(\w+)$/} @args), #arg names }; } unlink "fslayer.h"; open(H, ">fslayer.h") or die; print H "// fslayer.h\n"; print H $bigcmt; print H "#ifndef\tFSLAYER_NODEFINES\n"; foreach (@fcns) { print H "#undef\t$_\n"; print H "#define\t$_($data{$_}{ANAMES}) fslayer_$_($data{$_}{ANAMES})\n"; } print H "#endif\n\n"; foreach (@fcns) { print H "$data{$_}{RET}\tfslayer_$_($data{$_}{ARGS});\n"; } close(H); chmod 0444, "fslayer.h"; foreach $fcn (@fcns) { $fname = "fslayer_${fcn}_stub.c"; unlink $fname; open(S, ">$fname") or die; print S "// $fname\n"; print S $bigcmt; print S "#define\tFSLAYER_NODEFINES\n"; print S "#include \"system.h\"\n"; print S "#include \"win_remap.h\"\n"; print S "\n"; print S "$data{$fcn}{RET}\n"; print S "fslayer_$fcn($data{$fcn}{ARGS})\n"; print S "{\n"; print S "\treturn ($fcn($data{$fcn}{ANAMES}));\n"; print S "}\n"; close(S); chmod 0444, $fname; } unlink "fslayer.makefile"; open(M, ">fslayer.makefile\n"); print M "# fslayer.makefile\n"; $bigcmt =~ s/\/\//#/g; print M $bigcmt; print M "FSLAYER_OBJS = "; print M join(" ", map {"fslayer/fslayer_${_}_stub.o"} @fcns); print M "\n\n"; print M "FSLAYER_HDRS = fslayer/fslayer.h\n"; print M "\n"; print M "JUNK += fslayer/fslayer.h fslayer/fslayer.makefile \\\n"; print M "\t" . join(" ", map {"fslayer/fslayer_${_}_stub.c"} @fcns) . "\n"; print M "\n"; print M "fslayer: \$(FSLAYER_OBJS)\n"; close(M); chmod 0444, "fslayer.makefile"; __DATA__ int fslayer_open(const char *path, int flags, mode_t mode); int fslayer_close(int fd); ssize_t fslayer_read(int fd, void *buf, size_t count); ssize_t fslayer_write(int fd, const void *buf, size_t count); off_t fslayer_lseek(int fildes, off_t offset, int whence); int fslayer_lstat(const char *path, struct stat *buf); int fslayer_linkcount(const char *path, struct stat *buf); int fslayer_fstat(int fd, struct stat *buf); int fslayer_stat(const char *path, struct stat *buf); int fslayer_unlink(const char *path); int fslayer_rename(const char *old, const char *new); int fslayer_chmod(const char *path, mode_t mode); int fslayer_link(const char *old, const char *new); int fslayer_symlink(const char *old, const char *new); char** fslayer_getdir(char *dir); int fslayer_access(const char *path, int mode); int fslayer_utime(const char *path, const struct utimbuf *buf); int fslayer_mkdir(const char *path, mode_t mode); int fslayer_rmdir(const char *path); int fslayer_rmIfRepo(char *path); char* fslayer_realBasename(const char *path, char *realname);
bitkeeper-scm/bitkeeper
src/libc/fslayer/gen_fslayer.pl
Perl
apache-2.0
3,873
%Contains utilities for making tables and forms and such: %A DCG for a checked radio button with the given Name and Value checked_radio_button(Name, Value) --> html_begin(input(type(radio), name(Name), value(Value), checked("checked"))),[" ", Value, " "]. %A DCG for an unchecked radio button with the given Name and Value radio_button(Name,Value) --> html_begin(input(type(radio), name(Name), value(Value))), [" ", Value, " "]. %Creates a table column with the specified value table_column(X) --> html_begin(td), html([ \[X] ]), html_end(td). %Creates a paragraph tag with the specified contents paragraph(X) --> html_begin(p), html([ \[X] ]), html_end(p). %DCG for table header with the specified text table_header(X) --> html_begin(th), html([ \[X] ]), html_end(th). table_data([Value|T]) --> { data(Value, Hint, Answer) }, html_begin(tr), table_column(Value), table_column(Hint), table_column(Answer), html_begin(td), checkbox("data_key", Value), html_end(td), html_end(tr), table_data(T). table_data([]) --> []. checkbox(Name, Value) --> html_begin(input(type(checkbox), name(Name), value(Value))).
JustAnotherSoul/01
server/web_utils.pl
Perl
apache-2.0
1,232
package VMOMI::ArrayOfVirtualMachineFileLayoutExDiskUnit; use parent 'VMOMI::ComplexType'; use strict; use warnings; our @class_ancestors = ( ); our @class_members = ( ['VirtualMachineFileLayoutExDiskUnit', 'VirtualMachineFileLayoutExDiskUnit', 1, 1], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/ArrayOfVirtualMachineFileLayoutExDiskUnit.pm
Perl
apache-2.0
480
# 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::BlastRNASeqPep =head1 SYNOPSIS my $db = Bio::EnsEMBL::DBAdaptor->new($locator); my $btpep = Bio::EnsEMBL::Analysis::RunnableDB::BlastRNASeqPep->new ( -dbobj => $db, -input_id => $input_id -analysis => $analysis ); $btpep->fetch_input(); $btpep->run(); $btpep->output(); =head1 DESCRIPTION This object runs Bio::EnsEMBL::Analysis::Runnable::Blast on peptides obtained by translating a representative transcript from each gene in the region. The resulting blast hits are written back as DnaPepAlignFeature's. The appropriate Bio::EnsEMBL::Analysis object must be passed for extraction of appropriate parameters. =head1 CONTACT =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _' =cut package Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveBlastRNASeqPep; use warnings ; use strict; use Bio::EnsEMBL::Analysis::Runnable::BlastTranscriptPep; use Bio::EnsEMBL::Pipeline::SeqFetcher::OBDAIndexSeqFetcher; use Bio::EnsEMBL::Analysis::Tools::GeneBuildUtils::GeneUtils; use parent ('Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveBlast'); =head2 fetch_input Args : none Example : $runnable->fetch_input Description: Fetches input data for BlastRNASeqPep and makes runnable Returntype : none Exceptions : $self->input_id is not defined Caller : run_RunnableDB, Bio::EnsEMBL::Pipeline::Job =cut sub fetch_input { my($self) = @_; $self->throw("No input id") unless defined($self->input_id); # $self->create_analysis(1, {-db_file => join(',', @{$self->param('uniprot_index')}), -program_file => $self->param('blast_program')}); $self->create_analysis(1); $self->hrdb_set_con($self->get_database_by_name('dna_db'), 'dna_db'); my $slice = $self->fetch_sequence($self->input_id, $self->hrdb_get_con('dna_db')); $self->query($slice); $self->hive_set_config; my %blast = %{$self->BLAST_PARAMS}; my $parser = $self->make_parser; my $filter; my %store_genes; if($self->BLAST_FILTER){ $filter = $self->make_filter; } my $ga = $self->get_database_by_name($self->MODEL_DB)->get_GeneAdaptor; my $genes; my $logicname = $self->LOGICNAME; if ( $logicname) { $genes = $ga->fetch_all_by_Slice($self->query, $logicname, 1); } else { $genes = $ga->fetch_all_by_Slice($self->query,undef,1); } print "Found " . scalar(@$genes) . " genes "; if ( $logicname ) { print " of type " . $logicname . "\n"; } else { print "\n"; } foreach my $gene (@$genes) { foreach my $tran (@{$gene->get_all_Transcripts}) { $store_genes{$tran->dbID} = $gene; if ($tran->translation) { # foreach my $db (split ',', ($self->analysis->db_file)) { foreach my $db (@{$self->param('uniprot_index')}) { $self->runnable(Bio::EnsEMBL::Analysis::Runnable::BlastTranscriptPep->new( -transcript => $tran, -query => $self->query, -program => $self->param('blast_program'), -parser => $parser, -filter => $filter, -database => $db, -analysis => $self->analysis, %blast, )); } } } } $self->genes_by_tran_id(\%store_genes); return 1; } sub run { my ($self) = @_; my @runnables = @{$self->runnable}; foreach my $runnable(@runnables){ eval{ $runnable->run; }; if(my $err = $@){ chomp $err; # only match '"ABC_DEFGH"' and not all possible throws if ($err =~ /^\"([A-Z_]{1,40})\"$/i) { my $code = $1; # treat VOID errors in a special way; they are really just # BLASTs way of saying "won't bother searching because # won't find anything" if ($code ne 'VOID') { $self->throw("Blast::run failed $@"); } } elsif ($err) { $self->throw("Blast Runnable returned unrecognised error string: $err"); } } $self->add_supporting_features($runnable->transcript,$runnable->output); } return 1; } sub add_supporting_features { my ($self,$transcript,$features) = @_; my %gene_store = %{$self->genes_by_tran_id}; my @output; my %feature_hash; my %name_hash; my @best; my $gene = $gene_store{$transcript->dbID}; $self->throw("Gene not found using id " .$transcript->dbID ."\n") unless $gene; print "Got gene " . $gene->stable_id ."\n"; my $sa = $self->get_database_by_name($self->OUTPUT_DB)->get_SliceAdaptor; my $chr_slice = $sa->fetch_by_region('toplevel',$gene->seq_region_name); foreach my $tran ( @{$gene->get_all_Transcripts} ) { $tran = $tran->transfer($chr_slice); # order them by name foreach my $f ( @$features ) { push(@{$name_hash{$f->hseqname}}, $f->transfer($chr_slice)); } # get the lowest eval and highest score for each protein foreach my $name ( keys %name_hash ) { my $protein = $name_hash{$name}; my @p_val = sort { $a->p_value <=> $b->p_value } @{$protein}; my @pid = sort { $b->percent_id <=> $a->percent_id } @{$protein}; my @score = sort { $b->score <=> $a->score } @{$protein}; print STDERR "$name "; print STDERR " highest scoring HSP " . $p_val[0]->p_value . " " . $score[0]->score ."\n"; # store all this data protein by highest score - lowest eval push @{$feature_hash{$p_val[0]->p_value}{$score[0]->score}{$name}},@{$protein}; } # sort the alignments first by p_val then by score my @sorted_alignments; print "Sorted hits\n"; foreach my $key ( sort { $a <=> $b } keys %feature_hash ) { foreach my $score ( sort { $b <=> $a } keys %{$feature_hash{$key}} ) { foreach my $name (keys %{$feature_hash{$key}{$score}} ) { print "$name $score $key\n"; push @sorted_alignments, $feature_hash{$key}{$score}{$name}; } } } ALIGN: while ( scalar(@sorted_alignments) > 0 ) { my @tmp; my @hsps = @{shift(@sorted_alignments)}; # make the HSPS non overlapping unless they are full length my @contigs; HSP: foreach my $hsp ( sort { $b->score <=> $a->score } @hsps ) { print "HSP " . $hsp->hseqname ." " . $hsp->hstart . " " . $hsp->hend ."\n"; # does it overlap with another HSP foreach my $contig ( @contigs ) { if ( $hsp->start <= $contig->end && $hsp->end >= $contig->start ) { # reject it print "REJECT\n"; next HSP; } if ( $hsp->hstart <= $contig->hend && $hsp->hend >= $contig->hstart ) { # reject it print "REJECT\n"; next HSP; } } # not overlapping keep it push @contigs, $hsp; } @best = sort { $a->hstart <=> $b->hstart } @contigs ; # we need to know they are all in order if ( $self->check_order(\@best) ) { # order got messed up, try the next best hit # empty the array @best = []; pop(@best); } else { last; } } if ( scalar(@best > 0 ) ) { # we want to make a single transcript supporting feature # using the highest scoring alignment and computing the peptide coverage print STDERR "Best hit\n"; my $hlen= 0; my @filtered_best; # set the p_val score and %ID to be the same for all hsps or # it will throw when you try to make a protien_align_feature my $pval = 10000000 ; my $pid = 0; my $score = 0; foreach my $f (@best ) { $score = $f->score if $f->score > $score; $pid = $f->percent_id if $f->percent_id > $pid; $pval = $f->p_value if $f->p_value < $pval; } foreach my $gf (@best ) { #need to break them back into ungapped features to get them to work consistantly foreach my $f ($gf->ungapped_features) { print join(' ', $f->seq_region_name, $f->start, $f->end, $f->strand, $f->hstart, $f->hend, $f->score, $f->p_value, $f->percent_id, $f->hseqname)."\n"; my $flen = $f->hend - $f->hstart + 1 ; $hlen += $flen ; $f->score($score); $f->percent_id($pid); $f->p_value($pval); push @filtered_best,$f; } } # make a transcript supporting feature my $coverage = sprintf("%.3f",( $hlen / length($tran->translation->seq) ) * 100); my $tsf = Bio::EnsEMBL::DnaPepAlignFeature->new(-features => \@filtered_best); # hijack percent_id - not going to use it $tsf->percent_id( $coverage ) ; $tsf->analysis($tran->analysis); print STDERR "coverage $coverage\n"; # calculate the hcoverage my $seqfetcher =Bio::EnsEMBL::Pipeline::SeqFetcher::OBDAIndexSeqFetcher->new ( -db => [$self->INDEX], -format => 'fasta' ); my $seq = $seqfetcher->get_Seq_by_acc($tsf->hseqname); my $hcoverage = sprintf("%.3f",( $hlen / length($seq->seq) ) * 100); $tsf->hcoverage( $hcoverage ) ; print STDERR "hcoverage $hcoverage\n"; $tran->add_supporting_features($tsf); } } push @output,$gene; $self->output(\@output); } sub write_output { my ($self) = @_; my $outdb = $self->get_database_by_name($self->OUTPUT_DB, $self->hrdb_get_con('dna_db')); my $gene_adaptor = $outdb->get_GeneAdaptor; my $fails = 0; my $total = 0; foreach my $gene (@{$self->output}){ #$gene->analysis($self->analysis); empty_Gene($gene); eval { $gene_adaptor->store($gene); }; if ($@){ $self->warning("Unable to store gene!!\n"); print STDERR "$@\n"; $fails++; } $total++; } if ($fails > 0) { $self->throw("Not all genes could be written successfully " . "($fails fails out of $total)"); } } sub check_order { my ( $self, $hsps ) = @_; # should be the same order if sorted by hstart or start dependant on strand my $hstring; my $tstring; my @hsps = sort { $a->hstart <=> $b->hstart } @$hsps ; foreach my $h ( @hsps ) { $hstring .= $h->start.":"; } if ( $hsps[0]->strand == 1 ) { @hsps = sort { $a->start <=> $b->start } @$hsps ; } else { @hsps = sort { $b->start <=> $a->start } @$hsps ; } foreach my $h ( @hsps ) { $tstring .= $h->start.":"; } print STDERR "\nCheck all hsps are contiguous\n$hstring\n$tstring\n\n"; if ( $hstring eq $tstring ) { return; } else { print STDERR "HSP ORDER DOESNT MATCH EXON ORDER GETTING NEXT BEST HIT $hstring\n$tstring\n"; return 1; } } sub genes_by_tran_id { my ($self,$value) = @_; if (defined $value) { $self->param('_gbtid', $value); } return $self->param('_gbtid'); } sub OUTPUT_DB { my ($self,$value) = @_; return 'output_db'; } sub MODEL_DB { my ($self,$value) = @_; return 'input_db'; } sub LOGICNAME { my ($self) = @_; return $self->param('logic_name'); } sub INDEX { my ($self,$value) = @_; return $self->param('indicate_index'); } 1;
james-monkeyshines/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/Hive/RunnableDB/HiveBlastRNASeqPep.pm
Perl
apache-2.0
12,097
#!/usr/bin/env perl use strict; use warnings; use Error::Pure::Output::Text qw(err_bt_pretty_rev); # Fictional error structure. my @err = ( { 'msg' => [ 'FOO', 'BAR', ], 'stack' => [ { 'args' => '(2)', 'class' => 'main', 'line' => 1, 'prog' => 'script.pl', 'sub' => 'err', }, { 'args' => '', 'class' => 'main', 'line' => 20, 'prog' => 'script.pl', 'sub' => 'eval {...}', } ], }, { 'msg' => ['XXX'], 'stack' => [ { 'args' => '', 'class' => 'main', 'line' => 2, 'prog' => 'script.pl', 'sub' => 'err', }, ], } ); # Print out. print scalar err_bt_pretty_rev(@err); # Output: # ERROR: XXX # main err script.pl 2 # ERROR: FOO # BAR # main err script.pl 1 # main eval {...} script.pl 20
tupinek/Error-Pure-Output-Text
examples/ex5.pl
Perl
bsd-2-clause
1,491
package WebService::MorphIO; use strict; use warnings; use Class::Utils qw(set_params); use Encode qw(encode_utf8); use Error::Pure qw(err); use IO::Barf qw(barf); use LWP::Simple qw(get); use URI; use URI::Escape qw(uri_escape); our $VERSION = 0.05; # Constructor. sub new { my ($class, @params) = @_; # Create object. my $self = bless {}, $class; # Morph.io API key. $self->{'api_key'} = undef; # Project. $self->{'project'} = undef; # Select. $self->{'select'} = 'SELECT * FROM data'; # Web URI of service. $self->{'web_uri'} = 'https://morph.io/'; # Process params. set_params($self, @params); # Check API key. if (! defined $self->{'api_key'}) { err "Parameter 'api_key' is required."; } # Check project. if (! defined $self->{'project'}) { err "Parameter 'project' is required."; } if ($self->{'project'} !~ m/\/$/ms) { $self->{'project'} .= '/'; } # Web URI. if ($self->{'web_uri'} !~ m/\/$/ms) { $self->{'web_uri'} .= '/'; } # Object. return $self; } # Get CSV file. sub csv { my ($self, $output_file) = @_; my $uri = URI->new($self->{'web_uri'}.$self->{'project'}. 'data.csv?key='.$self->{'api_key'}.'&query='. uri_escape($self->{'select'})); return $self->_save($uri, $output_file); } # Get sqlite file. sub sqlite { my ($self, $output_file) = @_; my $uri = URI->new($self->{'web_uri'}.$self->{'project'}. 'data.sqlite?key='.$self->{'api_key'}); return $self->_save($uri, $output_file); } # Save file. sub _save { my ($self, $uri, $output_file) = @_; my $content = get($uri->as_string); if (! $content) { err "Cannot get '".$uri->as_string."'."; } barf($output_file, encode_utf8($content)); return; } 1; __END__ =pod =encoding utf8 =head1 NAME WebService::MorphIO - Perl class to communication with morph.io. =head1 SYNOPSIS use WebService::MorphIO; my $obj = WebService::MorphIO->new(%parameters); $obj->csv('output.csv'); $obj->sqlite('output.sqlite'); =head1 METHODS =over 8 =item C<new(%parameters)> Constructor. =over 8 =item * C<api_key> Morph.io API key. It is required. Default value is undef. =item * C<project> Project. It is required. Default value is undef. =item * C<select> Select. It is usable for csv() method. Default value is 'SELECT * FROM data'. =item * C<web_uri> Web URI of service. Default value is 'https://morph.io/'. =back =item C<csv($output_file)> Get CSV file and save to output file. It is affected by 'select' parameter. Returns undef. =item C<sqlite($output_file)> Get sqlite file and save to output file. Returns undef. =back =head1 ERRORS new(): Parameter 'api_key' is required. Parameter 'project' is required. From Class::Utils::set_params(): Unknown parameter '%s'. csv(): Cannot get '%s'. sqlite(): Cannot get '%s'. =head1 EXAMPLE use strict; use warnings; use File::Temp qw(tempfile); use Perl6::Slurp qw(slurp); use WebService::MorphIO; # Arguments. if (@ARGV < 2) { print STDERR "Usage: $0 api_key project\n"; exit 1; } my $api_key = $ARGV[0]; my $project = $ARGV[1]; # Temp file. my (undef, $temp_file) = tempfile(); # Object. my $obj = WebService::MorphIO->new( 'api_key' => $api_key, 'project' => $project, ); # Save CSV file. $obj->csv($temp_file); # Print to output. print slurp($temp_file); # Clean. unlink $temp_file; # Output: # Usage: ./examples/ex1.pl api_key project =head1 DEPENDENCIES L<Class::Utils>, L<Encode>, L<Error::Pure>, L<IO::Barf>, L<LWP::Simple>, L<URI>, L<URI::Escape>. =head1 REPOSITORY L<https://github.com/michal-josef-spacek/WebService-MorphIO> =head1 AUTHOR Michal Josef Špaček L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT © 2014-2020 Michal Josef Špaček BSD 2-Clause License =head1 VERSION 0.05 =cut
tupinek/WebService-MorphIO
MorphIO.pm
Perl
bsd-2-clause
3,883
=head1 AmiGO::KVStore::Filesystem A library to store blobs on the file system. This is supposed to be used for files, but it seems to work with scalar (string?) data in general. NOTE: While sharing the safe namespace and interface as KVStore, this is not actually a subclass--it works directly with the filesystem and does not use SQLite3. NOTE/TODO: You'll notice some very...strange...things going on with the handling of numbers in _make_file_key. This is because different versions of perl have (or don't have) bignum hex--which is necessary to what I'm doing in there. To get around this in a non-platform specific way, I'm making a detour through BigInt and strings. After a year or so, when all of the machines are off of 8.04, we can flip it back to the obvious way (and all of that goes for rmtree vs. remove_tree in File::Path). use AmiGO::KVStore::Filesystem; my $foo = AmiGO::KVStore::Filesystem->new('blah') $foo->put('a', 'b') print $foo->get('a') =cut package AmiGO::KVStore::Filesystem; use base 'AmiGO'; #use File::Path; use File::Slurp; use File::Path qw(make_path); use Digest::SHA; #use bignum qw/hex/; #use bignum; use Math::BigInt; my $AFSS_PREFIX = 'afs_'; my $AFSS_SUFFIX = '_files'; my $AFSS_KEY_PREFIX = 'key_'; my $AFSS_WRAP = 1000; # default number of mapable subdirectories. =item new Args: name/id, fs wrap (optional int) Returns: Creates (or recognizes an extant) filesystem store. =cut sub new { ## my $class = shift; my $loc = shift || die "gotta have a name path here $!"; my $wrap = shift || $AFSS_WRAP; my $self = $class->SUPER::new(); ## Create canonical name. $self->{AFSS_LOCATION} = $self->amigo_env('AMIGO_CACHE_DIR') . '/' . $AFSS_PREFIX . $loc . $AFSS_SUFFIX; $self->{AFSS_WRAP} = $wrap; ## Create if not already on the filesystem... $self->kvetch('checking store: ' . $self->{AFSS_LOCATION}); if( -d $self->{AFSS_LOCATION} && ! -W $self->{AFSS_LOCATION} ){ die "some permission issues here..."; }else{ $self->kvetch('making store: ' . $self->{AFSS_LOCATION}); # mkdir $self->{AFSS_LOCATION} || die "unable to create directory..."; # chmod 0777, $self->{AFSS_LOCATION} || die "unable to chmod directory..."; make_path($self->{AFSS_LOCATION}, {mode=>0777}) || die "unable to create directory..."; } bless $self, $class; return $self; } ## Turn a key into a filesystem location. If that location involves a ## non-existant directory, create it. sub _make_file_key { my $self = shift; my $in_key = shift || die "need key here"; ## Generate subdir. # my $shash = hex(Digest::SHA::sha1_hex($in_key)); # my $sub_int = $shash % $self->{AFSS_WRAP}; my $shash = Digest::SHA::sha1_hex($in_key); my $y = sprintf("0x%s", $shash); my $z = Math::BigInt->new($y); my $sub_int = $z->bmod( $self->{AFSS_WRAP} ); $self->kvetch('shash: ' . $shash); $self->kvetch('sub_int: ' . $sub_int); my $sub_dir = $self->{AFSS_LOCATION} . '/' . $sub_int; if( ! -d $sub_dir ){ $self->kvetch('making sub-store: ' . $sub_dir); # mkdir $sub_dir || die "unable to create sub-directory..."; # chmod 0777, $sub_dir || die "unable to make permissive sub-directory..."; make_path($sub_dir, {mode=>0777}) || die "unable to create directory..."; } ## Return fully qualified return $sub_dir . '/' . $AFSS_KEY_PREFIX . $in_key; } =item get Args: key Ret: undef or blob--your job to figure out what it is... =cut sub get { my $self = shift; my $key = shift || die "need key here"; my $retval = undef; ## my $file_key = $self->_make_file_key($key); if( -f $file_key ){ $retval = read_file($file_key, binmode => ':raw'); } return $retval; } =item put Args: key, blob Ret: 1/0 =cut sub put { my $self = shift; my $key = shift || die "need key"; my $val = shift || die "need val"; my $file_key = $self->_make_file_key($key); my $retval = write_file($file_key, {binmode => ':raw', atomic => 1}, $val); chmod 0666, $file_key || die "permissions problem here..."; return $retval; } =item list Args: n/a Returns: array ref of fully qualified strings for AmiGO::KVStore databases. Useful for cleaning duties. =cut sub list { my $a = AmiGO->new(); my $gpat = $a->amigo_env('AMIGO_CACHE_DIR') . '/' . $AFSS_PREFIX . '*' . $AFSS_SUFFIX; my @all = glob($gpat); return \@all; } 1;
raymond91125/amigo
perl/lib/AmiGO/KVStore/Filesystem.pm
Perl
bsd-3-clause
4,381
num(num(X)) --> [X], {number(X)}. var(var(X)) --> [X], {atom(X), X \== '(', X \== ')', X \== ']', X \== '[', X \== '{', X \== '}', X \== ','}. str(str(X)) --> ['"'], atom(X), ['"']. /* * Arguments are a list of names */ args(args(X)) --> var(X). args(args(X, Y)) --> var(X), args(Y). /* * A literal is a string, number or a variable. */ literal(X) --> var(X); num(X); str(X). literal(X) --> ['('], expr(X), [')']. /* * An expression can be a literal */ expr(expr(X)) --> literal(X). /* * Calling a message (or list of messages) on a literal * (an what is returned) * * Eg. Object clone() clone() */ expr(call(X, Y)) --> literal(X), message_list(Y). /* * A block is an argument list followed by a pipe and statement list * * Eg. [ | x, y | x show(y) ] */ expr(block(X, Y)) --> ['['], args(X), ['|'], statements(Y), [']']. expr(block(X)) --> ['['], ['|'], statements(X), [']']. expr(list(X)) --> ['{'], expr_list(X), ['}']. /* * A list of expressions, separated by commas * * Eg. 1, 2, Receiver message() */ expr_list(X) --> expr(X). expr_list(exprs(X, Y)) --> expr(X), [','], expr_list(Y). /* * A message is a literal followed by starting and ending parentheses, * with or without an expression list in between. * * Eg. message() or message(1,2,3), +(3), or + 3 */ message(message(X)) --> var(X), ['('], [')']. message(message(X, Y)) --> var(X), ['('], expr_list(Y), [')']. message(message(X, Y)) --> var(X), expr_list(Y). /* * A message list is a message follwed by a list of messages * * Eg. message() message2(2,2) */ message_list(X) --> message(X). message_list(messages(X,Y)) --> message(X), message_list(Y). /* * A statement is either an expression, or an assignment */ statement(assign(X, Y)) --> var(X), [:=], expr(Y), ['.']. statement(X) --> expr(X), ['.']. /* * A program is composed of a list of statements */ program(X) --> statement(X). statements(X) --> statement(X). statements(statements(X, Y)) --> statement(X), statements(Y). % var = Receiver message(arg, Receiver message()) message() message(). % 1 >=(2) isTrue([ % Transcript show("hello world"). % ], [ % Transcript show("Hello world %s", "isak"). % ]). % % % % a = Object clone(10, 10) clone() clone()
isakkarlsson/bs
src/prolog/syntax.pl
Perl
bsd-3-clause
2,289
#!/usr/bin/perl ##---------------------------------------------------------------------------## ## File: ## @(#) dfamConsensusTool ## Author: ## Robert M. Hubley rhubley@systemsbiology.org ## Description: ## A command-line utitility for working with the Dfam_consensus ## database. ## #****************************************************************************** #* This software is provided ``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 authors or the Institute for Systems Biology * #* 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. * #* * #****************************************************************************** # # ChangeLog # # $Log: dfamConsensusTool.pl,v $ # Revision 1.4 2017/04/05 19:05:24 rhubley # - Doc improvements # # Revision 1.3 2017/04/05 00:03:32 rhubley # Cleanup before a distribution # # ############################################################################### # # To Do: # =head1 NAME dfamConsensusTool - Command line tool for working with the Dfam_consensus database =head1 SYNOPSIS dfamConsensusTool [options] -register dfamConsensusTool [options] -validate <stockholm_file> dfamConsensusTool [options] -upload <stockholm_file> dfamConsensusTool [options] -classification =head1 DESCRIPTION The Dfam_consensus database is an open collection of Repetitive DNA consensus sequence models and corresponding seed alignments. It is directly compatible with the RepeatMasker program and any consensus-based search tools. It is freely available and distribued under the Creative Commons Zero ( "CC0" ) license. The dfamConsensusTool.pl script is a command-line utility to aid with submission of new families to the Dfam_consensus database and is distributed as part of the RepeatModeler package. This utility provides the following basic features: =over 4 Account Registration - Dfam_consensus submitters must have an account in order to submit families to the editors. The registration process is quick and can be conducted at the website ( http://www.repeatmasker.org/Dfam_consensus/#/login ) or through the dfamConsensus.pl tool itself. Data Validation - The basic data format for Dfam/Dfam_conensus is a variant of the Stockholm format. This tool can be used to validate a particular Stockholm file prior to submission. Data Submission - The primary role of this tool is to provide a reliable method for uploading a single curated family or a complete library of curated families to the database quickly and reliably. =back Full documentation can be found at: http://www.repeatmasker.org/RepeatModeler/dfamConsensusTool/ The options are: =over 4 =item -version Displays the version of the program =item -register Setup an account at the Dfam_consensus site. =item -validate <stockholm_file> Validate the format/data in a Stockholm file. =item -upload <stockholm_file> Submit new families to the Dfam_consensus database. =back =head1 SEE ALSO =head1 COPYRIGHT Copyright 2017 Robert Hubley, Institute for Systems Biology =head1 LICENSE This code may be used in accordance with the Open Source License v. 3.0 http://opensource.org/licenses/OSL-3.0 =head1 AUTHOR Robert Hubley <rhubley@systemsbiology.org> =cut # # Module Dependence # use strict; use Carp; use Getopt::Long; use Data::Dumper; use FindBin; use lib $FindBin::RealBin; use lib "$FindBin::RealBin/.."; use MultAln; use SeedAlignmentCollection; use SeedAlignment; ## These are probably not already on the users ## default perl installation. use JSON; use URI; use LWP::UserAgent; # # Version # -- NOTE: This is filled in by configure my $Version = "open-1.0.11"; $Version = "DEV" if ( $Version =~ /\#VERSION\#/ ); # # Magic numbers/constants here # ie. my $PI = 3.14159; # my $DEBUG = 0; my $apiMajor = 0; # Version of the API we speak my $apiMinor = 0; # .. my $apiBugfix = 0; # .. my $dfamConsWebsite = "http://www.repeatmasker.org/Dfam_consensus"; my $server = "www.repeatmasker.org"; my $port = "10010"; my $adminEmail = "help\@dfam.org"; my $failedFile; my $username; my $password; my $sFilename; # # Option processing # e.g. # -t: Single letter binary option # -t=s: String parameters # -t=i: Number paramters # my @getopt_args = ( '-version', # print out the version and exit '-register', '-upload=s', '-validate=s', '-classification', '-status', '-user=s', '-pass=s', '-server=s', '-port=s' ); my %options = (); Getopt::Long::config( "noignorecase", "bundling_override" ); unless ( GetOptions( \%options, @getopt_args ) ) { usage(); } sub usage { print "$0 - $Version\n\n"; exec "pod2text $0"; exit; } if ( $options{'version'} ) { print "$Version\n"; exit; } $server = $options{'server'} if ( $options{'server'} ); $port = $options{'port'} if ( $options{'port'} ); unless ( $options{'validate'} || $options{'register'} || $options{'status'} || $options{'upload'} || $options{'classification'} ) { usage(); } # # Setup the User Agent # my $ua = LWP::UserAgent->new; $ua->timeout( 10 ); # # Make sure we have contact with the server and # we can speak the same API version. # my $apiVersion = ""; my $res = $ua->get( "http://$server:$port/version" ); if ( $res->decoded_content && !$res->is_error ) { my $data = from_json( $res->decoded_content ); if ( !defined $data || !defined $data->{'major'} ) { die "\nError in version response from the server [$server:$port]: " . Dumper( $res->decoded_content ) . "\n\n"; } $apiVersion = $data->{'major'} . "." . $data->{'minor'} . "." . $data->{'bugfix'}; if ( $data->{'major'} > $apiMajor ) { die "\nError the server is running a newer API ( web: $apiVersion,\n" . "tool: $apiMajor.$apiMinor.$apiBugfix ) than this tool was designed for.\n" . "Please update RepeatModeler to obtain the most current version.\n\n"; } elsif ( $data->{'minor'} > $apiMinor ) { # TODO: Consider warning about minor level updates to API. } } else { print "\n[$server:$port - " . localtime() . "] Could not get a response from \n" . "the server. Please try again, check the Dfam_consensus website\n" . "($dfamConsWebsite) for notices of scheduled maintenance or write\n" . "$adminEmail to report this problem.\n\n"; die; } # # Say hello # print "\nDfam_consensus Tool - version $Version ( API: $apiVersion )\n"; print "-------------------------------------------------------\n"; # # Register # if ( $options{'register'} ) { my $fullname; print "Registration to submit to Dfam_consensus is a two step process:\n" . " 1. Submit your account preferences using the form below.\n" . " 2. Send an email to $adminEmail to request \"submitter\" access\n" . " to the system. Once this has been approved you will be able to\n" . " begin uploading and viewing the status of sequences using this\n" . " tool.\n"; print "Email: "; chomp( $username = <STDIN> ); print "Full Name: "; chomp( $fullname = <STDIN> ); print "Password: "; system "stty -echo"; chomp( $password = <STDIN> ); system "stty echo"; print "\n\n"; if ( $username !~ /^(\S+)\@(\S+)$/ ) { croak "Email address <$username> is not in the correct form.\n"; } if ( $fullname eq "" ) { croak "Missing Full Name. This is a required field.\n"; } if ( $password eq "" ) { croak "Missing Password. This is a required field.\n"; } my $res = $ua->post( "http://$server:$port/register", { 'email' => $username, 'name' => $fullname, 'password' => $password } ); if ( $res->decoded_content || $res->is_error ) { die "Error logging into server [$server:$port]: " . Dumper( $res->decoded_content ) . "\n"; } print "Registration successful! Now you can send an email\n" . "to \"$adminEmail\" and request \"submitter\" access to\n" . "Dfam_consensus.\n"; exit; } # # Validation part-1 # - Parse the input file and attempt to do non-database # validation first. That way we do not bother the # user with login prompts just to do a pre-check of # the file. # my $stockholmFile = SeedAlignmentCollection->new(); if ( $options{'upload'} || $options{'validate'} ) { $sFilename = $options{'upload'}; $sFilename = $options{'validate'} if ( $options{'validate'} ); open my $IN, "<$sFilename" or die "Could not open up stockholm file $sFilename for reading!\n"; $stockholmFile->read_stockholm( $IN ); close $IN; print "File $sFilename contains " . $stockholmFile->size() . " families.\n"; print "[test] Stockholm Format: valid\n"; } # # Login # if ( $options{'validate'} ) { print "\nLogging into server [$server:$port] to further\n" . "validate the input file. If you do not already have\n" . "an account you can register by running this tool with\n" . "the \"-register\" option.\n"; } else { print "\nLogging into server [$server:$port]. If\n" . "you do not already have an account you can register\n" . "by running this tool with the \"-register\" option.\n"; } if ( !$options{'user'} ) { print "Username: "; chomp( $username = <STDIN> ); } else { $username = $options{'user'}; } if ( !$options{'pass'} ) { print "Password: "; system "stty -echo"; chomp( $password = <STDIN> ); system "stty echo"; print "\n\n"; } else { $password = $options{'pass'}; } # # Obtain an OAuth token # $res = $ua->post( "http://$server:$port/login", { 'email' => $username, 'password' => $password } ); my $data; if ( $res->decoded_content && !$res->is_error ) { $data = from_json( $res->decoded_content ); if ( !defined $data || !defined $data->{'token'} ) { if ( defined $data && $data->{'message'} ) { die "Error logging into server[$server:$port]: " . $data->{'message'} . "\n"; } else { die "Error logging into server[$server:$port]: " . Dumper( $res->decoded_content ) . "\n"; } } } else { print "[$server:$port - " . localtime() . "] Could not get a response from \n" . "the server. Please try again, check the Dfam_consensus website\n" . "($dfamConsWebsite) for notices of scheduled maintenance or write\n" . "$adminEmail to report this problem.\n\n"; die; } my $datestring = localtime(); print "Login at $datestring\n"; # # Now place the token in the header of all future # requests. # $ua->default_header( 'authorization' => "Bearer " . $data->{'token'} ); # # Get the classification heirarchy # if ( $options{'classification'} ) { print "Dfam_consensus Classification System\n"; print " The following list represents the valid\n" . " classes for families in Dfam_consensus:\n"; } $res = $ua->get( "http://$server:$port/classification" ); my %validClassification = (); if ( $res->decoded_content && !$res->is_error ) { #print ">" . $res->decoded_content . "<\n"; my $data = from_json( $res->decoded_content ); my @stack = ( $data ); while ( @stack ) { my $node = pop( @stack ); if ( !defined $node->{'found'} ) { $node->{'found'} = 1; my $type = ""; $type = "\"" . $node->{'repeatmasker_type'} . "\"" if ( exists $node->{'repeatmasker_type'} ); my $subtype = ""; $subtype = ", \"" . $node->{'repeatmasker_subtype'} . "\"" if ( exists $node->{'repeatmasker_subtype'} ); #print " " . $node->{'full_name'} . "\n" print " \"" . lc( $node->{'full_name'} ) . "\" => [ $type $subtype ], \n" if ( $options{'classification'} ); $validClassification{ lc( $node->{'full_name'} ) } = 1; foreach my $child ( @{ $node->{'children'} } ) { push @stack, $child; } } } } else { print "[$server:$port - " . localtime() . "] Could not get a response from \n" . "the server. Please try again, check the Dfam_consensus website\n" . "($dfamConsWebsite) for notices of scheduled maintenance or write\n" . "$adminEmail to report this problem.\n\n"; #print "Error returned from LWP: " . $res->decoded_content . "\n"; exit; } exit if ( $options{'classification'} ); # # Validation revisited ( a.k.a part-2 ) # - now do database-based validation and the slow consensus # generation. # if ( $options{'upload'} || $options{'validate'} ) { my $overallFailure = 0; # Gather some intel my %clades = (); my %ids = (); for ( my $i = 0 ; $i < $stockholmFile->size() ; $i++ ) { my $seedAlign = $stockholmFile->get( $i ); my $id = $seedAlign->getId(); for ( my $j = 0 ; $j < $seedAlign->cladeCount() ; $j++ ) { push @{ $clades{ $seedAlign->getClade( $j ) } }, $id; } $ids{$id}++; } # Sanity check the names my @repModelName = (); my @nonUniq = (); my @tooLong = (); foreach my $id ( keys %ids ) { # rnd-1_family-138#LINE/L1 if ( $id =~ /^rnd-\d+_family-\d+.*/ ) { push @repModelName, $id; } if ( $ids{$id} > 1 ) { push @nonUniq, $id; } if ( length( $id ) > 45 ) { push @tooLong, $id; } } if ( @tooLong ) { $overallFailure = 1; print "[test] Identifier Length: failed\n" . " Identifiers are currently limited to 45 characters in length.\n" . " The following identifiers are too long:\n"; my $nameStr = join( ", ", @tooLong ); $nameStr =~ s/(.{60}[^,]*,\s*)/$1\n/g; $nameStr = " " . $nameStr; $nameStr =~ s/\n(\S.*)/\n $1/g; $nameStr .= "\n" if ( substr( $nameStr, -1, 1 ) ne "\n" ); print $nameStr; } else { print "[test] Identifier Length: valid\n"; } if ( @repModelName ) { $overallFailure = 1; print "[test] Custom Identifiers: failed\n" . " Submissions to Dfam_consensus must be assigned names\n" . " that are unique to the database. Use of the RepeatModeler\n" . " automatically assigned names would therefore not be\n" . " unique. Please see the help ( use \"-h\" ) for some\n" . " pointers on naming your families and/or use the\n" . " \"util/renameIDs.pl\" script to automatically rename\n" . " the identifiers.\n\n" . " The following identifiers look like a RepeatModeler\n" . " assigned name:\n"; my $nameStr = join( ", ", @repModelName ); $nameStr =~ s/(.{60}[^,]*,\s*)/$1\n/g; $nameStr = " " . $nameStr; $nameStr =~ s/\n(\S.*)/\n $1/g; $nameStr .= "\n" if ( substr( $nameStr, -1, 1 ) ne "\n" ); print $nameStr; } else { print "[test] Custom Identifiers: valid\n"; } if ( @nonUniq ) { $overallFailure = 1; print "[test] Unique (in-file) Identifiers: failed\n" . " Non-unique seed alignment identifiers. The following\n" . " identifiers where used more than once in the stockholm\n" . " file:\n"; foreach my $id ( @nonUniq ) { print " $id\n"; } } else { print "[test] Unique Identifiers: valid\n"; } # Verify the clades my $failures = ""; if ( keys( %clades ) ) { foreach my $clade ( keys( %clades ) ) { # Lookup in db my $url = URI->new( "http://$server:$port/taxonomy" ); $url->query_form( { name => $clade, limit => 3 } ); my $res = $ua->get( $url ); if ( $res->decoded_content && !$res->is_error ) { my $data = from_json( $res->decoded_content ); if ( defined $data && defined $data->{'taxa'} ) { if ( @{ $data->{'taxa'} } != 1 || $data->{'taxa'}->[ 0 ]->{'species_name'} !~ /$clade/i ) { $failures .= " Clade \"$clade\" found in seed alignments: " . join( ", ", @{ $clades{$clade} } ) . "\n" . " does not uniquely map to an NCBI Taxonomy record.\n"; if ( @{ $data->{'taxa'} } ) { $failures .= " Here are a few potential matches:\n"; for my $name ( @{ $data->{'taxa'} } ) { $failures .= " " . $name->{'species_name'} . "\n"; } } } } elsif ( defined $data && defined $data->{'message'} ) { $failures .= " Failed to verify clade \"$clade\" due to an\n" . " error from the server:\n" . $data->{'message'} . "\n"; } else { $failures .= " Clade \"$clade\" found in seed alignments:\n" . " " . join( ", ", @{ $clades{$clade} } ) . "\n" . " does not map to an NCBI Taxonomy record.\n" . " Please check the name at https://www.ncbi.nlm.nih.gov/taxonomy\n" . " and correct the record in the stockholm file.\n"; } } else { $failures .= " Clade \"$clade\" found in seed alignments:\n" . " " . join( ", ", @{ $clades{$clade} } ) . "\n" . " does not map to an NCBI Taxonomy record.\n" . " Please check the name at https://www.ncbi.nlm.nih.gov/taxonomy\n" . " and correct the record in the stockholm file.\n"; } } if ( $failures ne "" ) { $overallFailure = 1; print "[test] NCBI Clade Names: failed\n$failures"; } else { print "[test] NCBI Clade Names: valid\n"; } } # TODO: Verify classification # TODO: Consider limiting the number of sequences per family -- don't overwhelm the db! # TODO: Actually lookup IDs in db to make sure they are unique # TODO: Lookup PMIDs? # TODO: Verify DB Aliases # TODO: Can we do a better job of validating the assembly/seqid/coordinates? if ( $overallFailure ) { if ( $options{'validate'} ) { print "\nFile failed validation.\n"; exit; } else { print "\nFile failed validation - upload canceled.\n"; exit; } } else { print "\nFile passes validation\n"; } # Only used prefix of previously failed runs. This way it will continue # to increment the ".failed.#" suffix. $failedFile = $sFilename; if ( $failedFile =~ /(.*)\.failed\.\d+$/ ) { $failedFile = $1; } my $index = 1; while ( $index <= 15 && -s "$failedFile.failed.$index" ) { $index++; } if ( $index == 16 ) { die "There are 15 version of the $failedFile.failed file in this directory.\n" . "Is there a problem we can help with? Try emailing $adminEmail.\n"; } $failedFile = "$failedFile.failed.$index"; } if ( $options{'upload'} ) { # Basic request my $req = HTTP::Request->new( POST => "http://$server:$port/rmlibRepeat" ); $req->content_type( 'application/json' ); my $numErrs = 0; open OUT, ">$failedFile" or die "Could not open $failedFile for writing!\n"; for ( my $i = 0 ; $i < $stockholmFile->size() ; $i++ ) { my $seedAlign = $stockholmFile->get( $i ); print "Working on " . $seedAlign->getId() . "\n"; # Generate the consensus # - TODO: Allow the users to use the RF line to specify their own??? print " - building consensus...\n"; my @sequences = (); for ( my $j = 0 ; $j < $seedAlign->alignmentCount() ; $j++ ) { my ( $assemblyName, $sequenceName, $start, $end, $orient, $sequence ) = $seedAlign->getAlignment( $j ); # Replace prefix "." with spaces if ( $sequence =~ /^([\.]+)/ ) { substr( $sequence, 0, length( $1 ) ) = " " x ( length( $1 ) ); } # Replace suffixe "." with spaces if ( $sequence =~ /[^\.]([\.]+)$/ ) { substr( $sequence, length( $sequence ) - length( $1 ), length( $1 ) ) = " " x ( length( $1 ) ); } # Replace "." with "-" $sequence =~ s/\./\-/g; push @sequences, $sequence; } # Get the spaced (i.e with gaps) consensus my $consensus = MultAln::buildConsensusFromArray( sequences => \@sequences ); $consensus =~ s/-//g; # Generate the minimal stockholm format to send along my $minStockholm = "# STOCKHOLM 1.0\n"; $minStockholm .= "#=GC RF " . $seedAlign->getRfLine() . "\n"; for ( my $j = 0 ; $j < $seedAlign->alignmentCount() ; $j++ ) { my ( $assemblyName, $sequenceName, $start, $end, $orient, $sequence ) = $seedAlign->getAlignment( $j ); my $id; $id .= "$assemblyName:" if ( $assemblyName ); $id .= "$sequenceName:" if ( $sequenceName ); if ( $orient eq "+" ) { $id .= "$start-$end"; } else { $id .= "$end-$start"; } $minStockholm .= "$id $sequence\n"; } $minStockholm .= "//"; # prepare JSON my $record = { 'name' => $seedAlign->getId(), 'sequence' => $consensus, 'dfam_consensus' => "1", 'seed_alignment' => $minStockholm }; # clades if ( $seedAlign->cladeCount() ) { $record->{'clades'} = []; for ( my $j = 0 ; $j < $seedAlign->cladeCount() ; $j++ ) { my $clade = $seedAlign->getClade( $j ); push @{ $record->{'clades'} }, { 'name' => $clade }; } } # description if ( $seedAlign->getDescription() ) { $record->{'description'} = $seedAlign->getDescription(); } # TODO: DB references # citations if ( $seedAlign->citationCount() ) { $record->{'citations'} = []; for ( my $j = 0 ; $j < $seedAlign->citationCount() ; $j++ ) { my ( $pmid, $title, $author, $journal ) = $seedAlign->getCitation( $j ); my $citation = { 'pmid' => $pmid }; $citation->{'title'} = $title if ( $title ); $citation->{'author'} = $author if ( $author ); $citation->{'journal'} = $journal if ( $journal ); push @{ $record->{'citations'} }, $citation; } } # classification if ( $seedAlign->getClassification() ) { $record->{'classification'} = $seedAlign->getClassification(); } my $recJson = to_json( $record ); print " - uploading to the server...\n"; #print " -- JSON = " . $recJson . "\n"; # Send to the server $req->content( $recJson ); my $res = $ua->request( $req ); my $message = ""; if ( $res->decoded_content && !$res->is_error ) { my $data = from_json( $res->decoded_content ); #print "" . $res->decoded_content . "\n"; if ( !defined $data || !defined $data->{'token'} ) { $message = "[$server:$port - " . localtime() . "] Unknown failure"; if ( defined $data && $data->{'message'} ) { $message = "[$server:$port - " . localtime() . "] " . $data->{'message'}; if ( defined $data->{'results'} ) { $message .= " details: " . $data->{'results'}; } } } } if ( $message ne "" ) { print " - upload failed: $message\n"; # Write record + message to failed file. $seedAlign->setComment( $message . "\n" ); print OUT "" . $seedAlign->toString(); $numErrs++; } } close OUT; if ( $numErrs ) { # TODO: if ( $numErrs == $stockholmFile->size() ) { unlink( $failedFile ) if ( -s $failedFile ); print "\nNone of the families were uploaded successfully the server.\n" . "Please send the error messages to $adminEmail to seek help\n" . "with this matter.\n\n"; } else { my $successful = $stockholmFile->size() - $numErrs; print "\n$successful out of " . $stockholmFile->size() . " families were uploaded\n" . "successfully. Failed families have been copied to $failedFile\n" . "along with the error message for each. Once these errors have been\n" . "corrected this file can be used to upload the failed families.\n\n"; } } } elsif ( $options{'status'} ) { print "Status is not implemented yet!\n"; } ######################## S U B R O U T I N E S ############################ ##-------------------------------------------------------------------------## ## Use: my _privateMethod( $parameter => value ); ## ## $parameter : A parameter to the method ## ## Returns ## Methods with the prefix "_" are conventionally considered ## private. This bit-o-documentation is not formatted to ## print out when perldoc is run on this file. ## ##-------------------------------------------------------------------------## sub _privateMethod { my %parameters = @_; my $subroutine = ( caller( 0 ) )[ 0 ] . "::" . ( caller( 0 ) )[ 3 ]; print "$subroutine( " . @{ [ %parameters ] } . "): Called\n" if ( $DEBUG ); } 1;
vetscience/Tools
Cwl/repeatmodeler/RepeatModelerConf/util/dfamConsensusTool.pl
Perl
bsd-3-clause
26,096
package Google::Ads::AdWords::v201409::ManualCPCAdGroupCriterionExperimentBidMultiplier; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201409::AdGroupCriterionExperimentBidMultiplier); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %AdGroupCriterionExperimentBidMultiplier__Type_of :ATTR(:get<AdGroupCriterionExperimentBidMultiplier__Type>); my %maxCpcMultiplier_of :ATTR(:get<maxCpcMultiplier>); my %multiplierSource_of :ATTR(:get<multiplierSource>); __PACKAGE__->_factory( [ qw( AdGroupCriterionExperimentBidMultiplier__Type maxCpcMultiplier multiplierSource ) ], { 'AdGroupCriterionExperimentBidMultiplier__Type' => \%AdGroupCriterionExperimentBidMultiplier__Type_of, 'maxCpcMultiplier' => \%maxCpcMultiplier_of, 'multiplierSource' => \%multiplierSource_of, }, { 'AdGroupCriterionExperimentBidMultiplier__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'maxCpcMultiplier' => 'Google::Ads::AdWords::v201409::BidMultiplier', 'multiplierSource' => 'Google::Ads::AdWords::v201409::MultiplierSource', }, { 'AdGroupCriterionExperimentBidMultiplier__Type' => 'AdGroupCriterionExperimentBidMultiplier.Type', 'maxCpcMultiplier' => 'maxCpcMultiplier', 'multiplierSource' => 'multiplierSource', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201409::ManualCPCAdGroupCriterionExperimentBidMultiplier =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType ManualCPCAdGroupCriterionExperimentBidMultiplier from the namespace https://adwords.google.com/api/adwords/cm/v201409. AdGroupCriterion level bid multiplier used in manual CPC bidding strategies. <span class="constraint AdxEnabled">This is disabled for AdX.</span> =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * maxCpcMultiplier =item * multiplierSource =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/ManualCPCAdGroupCriterionExperimentBidMultiplier.pm
Perl
apache-2.0
2,492
#!/usr/bin/perl -w #================================================================ # (C) 2013-2014 Dena Group Holding Limited. # # This program is used to operate the process of # login & web server. # Please check the options before using. # # Authors: # Edison Chow <zhou.liyang@dena.jp> #================================================================ use warnings; use strict; use Net::OpenSSH; use Getopt::Long; my $num; my %opt; GetOptions(\%opt, 'h|help', 'n|num=i' ) or &print_usage(); if (!scalar(%opt) ) { &print_usage(); } $opt{'h'} and &print_usage(); $opt{'n'} and $num=$opt{'n'}; sub print_usage() { printf <<EOF; #================================================================ # (C) 2013-2014 Dena Group Holding Limited. # # This program is used to operate the process of # login & web server. # Please check the options before using. # # Authors: # Edison Chow <zhou.liyang\@dena.jp> #================================================================ ================================================================= -h,--help Print Help Info. -n,--num The num of Staticdata. Sample : shell > ./nba.pl -n 100 ================================================================= EOF exit; } #================================================================ # Function total #================================================================ sub total() { my $flag1; my $flag2; print "将获取以下版本号的静态数据到正服\n"; print "$num\n"; print "\n确定吗? (yes/no): "; my $ret = <STDIN>; chomp($ret); die "abort\n" if ($ret ne 'yes'); my $ssh1 = Net::OpenSSH->new("twnba_common1"); $ssh1->error and warn "can not connect to twnba_common1" . $ssh1->error; my $ssh2 = Net::OpenSSH->new("twnba_common2"); $ssh2->error and warn "can not connect to twnba_common2" . $ssh2->error; print "twnba_common1 IOS downloading:"; $ssh1->system("cd /www/doc/1/ios/StaticData/ && wget 119.15.139.6/1/ios/StaticData/StaticData_$num\_0.unity3d "); print "twnba_common1 Android downloading:"; $ssh1->system("cd /www/doc/1/android/StaticData/ && wget 119.15.139.6/1/android/StaticData/StaticData_$num\_0.unity3d"); print "twnba_common2 IOS downloading:"; $ssh2->system("cd /www/doc/1/ios/StaticData/ && wget 119.15.139.6/1/ios/StaticData/StaticData_$num\_0.unity3d "); print "twnba_common2 Android downloading:"; $ssh2->system("cd /www/doc/1/android/StaticData/ && wget 119.15.139.6/1/android/StaticData/StaticData_$num\_0.unity3d"); my $a1; my $a2; my $a4; my $a5; $a1=$ssh1->capture("cd /www/doc/1/ios/StaticData/ && ls -l|grep -v grep|grep StaticData_$num\_0 |wc -l "); $a2=$ssh1->capture("cd /www/doc/1/android/StaticData/ && ls -l|grep -v grep|grep StaticData_$num\_0 |wc -l "); $a4=$ssh2->capture("cd /www/doc/1/ios/StaticData/ && ls -l|grep -v grep|grep StaticData_$num\_0 |wc -l "); $a5=$ssh2->capture("cd /www/doc/1/android/StaticData/ && ls -l|grep -v grep |grep StaticData_$num\_0 |wc -l "); if($a1==1 && $a2==1 && $a4==1 && $a5==1 ) { print "\n\n\n"; print "====================================\n"; print "||版本号为$num的静态数据传输完毕!||\n"; print "====================================\n"; print "\n\n\n"; } else{ print "\n\n\n"; print "================================\n"; print "||静态数据传输未成功,请检查!||\n"; print "================================\n"; print "\n\n\n"; exit; } } &total();
eshujiushiwo/eshu-devops
tools/tw/scp_staticdata.pl
Perl
apache-2.0
3,487
package DMOZ::EntryNode; use strict; use warnings; use Data::Dumper; use DMOZ::Node; use base qw(DMOZ::Node); # constructor sub new { my $that = shift; my $url = shift; my $title = shift; my $description = shift; my $category = shift; my $class = ref($that) || $that; # object ref / build base class my $hash = $that->SUPER::new(join("/", ($category,$url)), 'entry'); # set fields $hash->{url} = $url; $hash->{title} = $title; $hash->{description} = $description; $hash->{category} = $category; bless $hash, $class; return $hash; } # title getter sub title { my $this = shift; return $this->get('title'); } # description getter sub description { my $this = shift; return $this->get('description'); } # string representation of this entry sub as_string { my $this = shift; return Dumper( { url => $this->{url}, title => $this->title(), description => $this->description(), index => $this->{_index}, _processing => { map { $_ => $this->get($_) } $this->getHierarchy->listProcessingFields($this) }, parent => $this->{_parent} } ); } # can this node be processed sub processable { my $this = shift; my $label = shift; if ( ! defined($label) ) { return 1; } my $node_label = $this->get("label"); if ( ! defined($node_label) ) { return 1; } return ($label eq $node_label); } 1;
ypetinot/web-summarization
models/topic-models/confusius-tm/src/DMOZ/EntryNode.pm
Perl
apache-2.0
1,454
package # Date::Manip::Offset::off031; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 11:03:44 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.orgtz use strict; use warnings; require 5.010000; our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } our ($Offset,%Offset); END { undef $Offset; undef %Offset; } $Offset = '+01:22:00'; %Offset = ( 0 => [ 'europe/kaliningrad', 'europe/belgrade', ], ); 1;
nriley/Pester
Source/Manip/Offset/off031.pm
Perl
bsd-2-clause
881
#!/usr/bin/perl -w use v5.10; use strict; no warnings 'redefine'; use Getopt::Long; use CoGe::Accessory::Web; our ( $infile, $outfile, $orgratio1, $orgratio2, $overlap, $P, $QUOTA_ALIGN, $CLUSTER_UTILS, $CONFIG); GetOptions( "infile|if=s" => \$infile, "outfile|of=s" => \$outfile, "depth_ratio_org1|d1=s" => \$orgratio1, "depth_ratio_org2|d2=s" => \$orgratio2, "depth_overlap|o=s" => \$overlap, "config|cfg=s" => \$CONFIG,); $P = CoGe::Accessory::Web::get_defaults($CONFIG); $ENV{PATH} = join ":", ( $P->{COGEDIR}, $P->{BINDIR}, $P->{BINDIR} . "SynMap", "/usr/bin", "/usr/local/bin"); $QUOTA_ALIGN = $P->{QUOTA_ALIGN}; #the program $CLUSTER_UTILS = $P->{CLUSTER_UTILS}; #convert dag output to quota_align input run_quota_align_coverage( infile => $infile, outfile => $outfile, org1 => $orgratio1, org2 => $orgratio2, overlap => $overlap); sub run_quota_align_coverage { my %opts = @_; my $infile = $opts{infile}; my $org1 = $opts{org1}; #ratio of org1 my $org2 = $opts{org2}; #ratio of org2 my $overlap_dist = $opts{overlap}; my $outfile = $opts{outfile}; #convert to quota-align format my $cov_cmd = $CLUSTER_UTILS . " --format=dag --log_evalue $infile $infile.qa"; my $qa_cmd = $QUOTA_ALIGN . " --Nm=$overlap_dist --quota=$org1:$org2 $infile.qa > $outfile.tmp"; say "Convert command: $cov_cmd"; say "Quota Align command: $qa_cmd"; say "Converting dag output to quota_align format."; `$cov_cmd`; say "Running quota_align to find syntenic coverage."; my $qa_output = `$qa_cmd`; if (-r "$outfile.tmp") { my %data; $/ = "\n"; open(IN, $infile); while (<IN>) { next if /^#/; my @line = split /\t/; $data{join("_", $line[0], $line[2], $line[4], $line[6])} = $_; } close IN; open(OUT, ">$outfile"); open(IN, "$outfile.tmp"); while (<IN>) { if (/^#/) { print OUT $_; } else { chomp; my @line = split /\t/; print OUT $data{ join("_", $line[0], $line[1], $line[2], $line[3])}; } } close IN; close OUT; generate_grimm_input(infile => $outfile); } else { say "Syntenic coverage failed to output $outfile.tmp"; } } sub generate_grimm_input { my %opts = @_; my $infile = $opts{infile}; CoGe::Accessory::Web::gunzip($infile . ".gz") if -r $infile . ".gz"; CoGe::Accessory::Web::gunzip($infile . ".qa.gz") if -r $infile . ".qa.gz"; my $cmd = $CLUSTER_UTILS . " --format=dag --log_evalue $infile $infile.qa"; say "\nGenerating input data for GRIMM"; say "Converting dag output to quota_align format: $cmd"; `$cmd`; $cmd = $CLUSTER_UTILS . " --print_grimm $infile.qa"; say "running cluster_utils to generating grimm input:\n\t$cmd"; my $output; open(IN, "$cmd |"); while (<IN>) { $output .= $_; } close IN; my @seqs; foreach my $item (split /\n>/, $output) { $item =~ s/>//g; my ($name, $seq) = split /\n/, $item, 2; $seq =~ s/\n$//; push @seqs, $seq; } return \@seqs; }
asherkhb/coge
scripts/synmap/quota_align_coverage.pl
Perl
bsd-2-clause
3,424
package # Date::Manip::Offset::off304; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Fri Nov 21 11:03:46 EST 2014 # Data version: tzdata2014j # Code version: tzcode2014j # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.orgtz use strict; use warnings; require 5.010000; our ($VERSION); $VERSION='6.48'; END { undef $VERSION; } our ($Offset,%Offset); END { undef $Offset; undef %Offset; } $Offset = '-04:19:18'; %Offset = ( 0 => [ 'atlantic/bermuda', ], ); 1;
nriley/Pester
Source/Manip/Offset/off304.pm
Perl
bsd-2-clause
854
######################################################################## # Bio::KBase::ObjectAPI::KBasePhenotypes::PhenotypeSet - This is the moose object corresponding to the KBasePhenotypes.PhenotypeSet object # Authors: Christopher Henry, Scott Devoid, Paul Frybarger # Contact email: chenry@mcs.anl.gov # Development location: Mathematics and Computer Science Division, Argonne National Lab # Date of module creation: 2014-01-05T15:36:51 ######################################################################## use strict; use Bio::KBase::ObjectAPI::KBasePhenotypes::DB::PhenotypeSet; package Bio::KBase::ObjectAPI::KBasePhenotypes::PhenotypeSet; use Moose; use namespace::autoclean; extends 'Bio::KBase::ObjectAPI::KBasePhenotypes::DB::PhenotypeSet'; #*********************************************************************************************************** # ADDITIONAL ATTRIBUTES: #*********************************************************************************************************** #*********************************************************************************************************** # BUILDERS: #*********************************************************************************************************** #*********************************************************************************************************** # CONSTANTS: #*********************************************************************************************************** #*********************************************************************************************************** # FUNCTIONS: #*********************************************************************************************************** sub import_phenotype_table { my $self = shift; my $args = Bio::KBase::ObjectAPI::utilities::args(["data","biochem"], {}, @_ ); my $genomeObj = $self->genome(); my $genehash = {}; my $ftrs = $genomeObj->features(); for (my $i=0; $i < @{$ftrs}; $i++) { my $ftr = $ftrs->[$i]; $genehash->{$ftr->id()} = $ftr; if ($ftr->id() =~ m/\.(peg\.\d+)/) { $genehash->{$1} = $ftr; } for (my $j=0; $j < @{$ftr->aliases()}; $j++) { $genehash->{$ftr->aliases()->[$j]} = $ftr; } } #Validating media, genes, and compounds my $missingMedia = {}; my $missingGenes = {}; my $missingCompounds = {}; my $mediaChecked = {}; my $cpdChecked = {}; my $data = $args->{data}; my $bio = $args->{biochem}; my $count = 1; my $mediaHash = {}; for (my $i=0; $i < @{$data}; $i++) { $mediaHash->{$data->[$i]->[2]}->{$data->[$i]->[1]} = 0; } my $output = $self->parent()->workspace()->list_objects({ workspaces => [keys(%{$mediaHash})], type => "KBaseBiochem.Media", }); for (my $i=0; $i < @{$output}; $i++) { if (defined($mediaHash->{$output->[$i]->[7]}->{$output->[$i]->[1]})) { $mediaHash->{$output->[$i]->[7]}->{$output->[$i]->[1]} = $output->[$i]->[6]."/".$output->[$i]->[0]; } } for (my $i=0; $i < @{$data}; $i++) { my $phenotype = $data->[$i]; #Validating gene IDs my $allfound = 1; my $generefs = []; for (my $j=0;$j < @{$phenotype->[0]};$j++) { if (!defined($genehash->{$phenotype->[0]->[$j]})) { $missingGenes->{$phenotype->[0]->[$j]} = 1; $allfound = 0; } else { $generefs->[$j] = $genehash->{$phenotype->[0]->[$j]}->_reference(); } } if ($allfound == 0) { next; } #Validating compounds $allfound = 1; my $cpdrefs = []; for (my $j=0;$j < @{$phenotype->[3]};$j++) { my $cpd = $bio->searchForCompound($phenotype->[3]->[$j]); if (!defined($cpd)) { $missingCompounds->{$phenotype->[3]->[$j]} = 1; $allfound = 0; } else { $cpdrefs->[$j] = $cpd->_reference(); } } if ($allfound == 0) { next; } #Validating media if ($mediaHash->{$phenotype->[2]}->{$phenotype->[1]} eq "0") { $missingMedia->{$phenotype->[2]."/".$phenotype->[1]} = 1; next; } #Adding phenotype to object $self->add("phenotypes",{ id => $self->id().".phe.".$count, media_ref => $mediaHash->{$phenotype->[2]}->{$phenotype->[1]}, geneko_refs => $generefs, additionalcompound_refs => $cpdrefs, normalizedGrowth => $phenotype->[4], name => $self->id().".phe.".$count }); $count++; } #Printing error if any entities could not be validated my $msg = ""; if (keys(%{$missingCompounds}) > 0) { $msg .= "Could not find compounds:".join(";",keys(%{$missingCompounds}))."\n"; } if (keys(%{$missingGenes}) > 0) { $msg .= "Could not find genes:".join(";",keys(%{$missingGenes}))."\n"; } if (keys(%{$missingMedia}) > 0) { $msg .= "Could not find media:".join(";",keys(%{$missingMedia}))."\n"; } $self->importErrors($msg); } __PACKAGE__->meta->make_immutable; 1;
kbase/KBaseFBAModeling
lib/Bio/KBase/ObjectAPI/KBasePhenotypes/PhenotypeSet.pm
Perl
mit
4,928
#, $in{'mode'} == 1 Functions for parsing the various RBAC configuration files BEGIN { push(@INC, ".."); }; use WebminCore; &init_config(); %access = &get_module_acl(); ####################### functions for users ####################### # list_user_attrs() # Returns a list of user attribute objects sub list_user_attrs { if (!scalar(@list_user_attrs_cache)) { @list_user_attrs_cache = ( ); local $lnum = 0; open(ATTR, $config{'user_attr'}); while(<ATTR>) { s/\r|\n//g; s/#.*$//; local @w = split(/:/, $_, -1); if (@w == 5) { local $attr = { 'user' => $w[0], 'qualifier' => $w[1], 'res1' => $w[2], 'res2' => $w[3], 'type' => 'user', 'line' => $lnum, 'index' => scalar(@list_user_attrs_cache) }; local $a; foreach $a (split(/;/, $w[4])) { local ($an, $av) = split(/=/, $a, 2); $attr->{'attr'}->{$an} = $av; } push(@list_user_attrs_cache, $attr); } $lnum++; } close(ATTR); } return \@list_user_attrs_cache; } # create_user_attr(&attr) # Add a new user attribute sub create_user_attr { local ($attr) = @_; &list_user_attrs(); # init cache local $lref = &read_file_lines($config{'user_attr'}); $attr->{'line'} = scalar(@$lref); push(@$lref, &user_attr_line($attr)); $attr->{'index'} = scalar(@list_user_attrs_cache); push(@list_user_attrs_cache, $attr); &flush_file_lines(); } # modify_user_attr(&attr) # Updates an existing user attribute in the config file sub modify_user_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'user_attr'}); $lref->[$attr->{'line'}] = &user_attr_line($attr); &flush_file_lines(); } # delete_user_attr(&attr) # Removes one user attribute entry sub delete_user_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'user_attr'}); splice(@$lref, $attr->{'line'}, 1); splice(@list_user_attrs_cache, $attr->{'index'}, 1); local $c; foreach $c (@list_user_attrs_cache) { $c->{'line'}-- if ($c->{'line'} > $attr->{'line'}); $c->{'index'}-- if ($c->{'index'} > $attr->{'index'}); } &flush_file_lines(); } # user_attr_line(&attr) # Returns the text for a user attribute line sub user_attr_line { local ($attr) = @_; local $rv = $attr->{'user'}.":".$attr->{'qualifier'}.":".$attr->{'res1'}.":". $attr->{'res2'}.":"; $rv .= join(";", map { $_."=".$attr->{'attr'}->{$_} } keys %{$attr->{'attr'}}); return $rv; } # attr_input(name, value, [type], [acl-restrict]) # Returns HTML for selecting one or more user attrs sub attr_input { local ($name, $value, $type, $restrict) = @_; local @values = split(/,+/, $value); local $users = &list_user_attrs(); local ($u, @sel); foreach $u (@$users) { local $utype = $u->{'attr'}->{'type'} || "normal"; if ((!$type || $utype eq $type) && (!$restrict || &can_assign_role($u))) { push(@sel, [ $u->{'user'} ]); } } if (@sel) { return &ui_select($name, \@values, \@sel, 5, 1, 1); } else { return $text{'attr_none'.$type}; } } # attr_parse(name) # Returns a comma-separated list of values from an attrs field sub attr_parse { return join(",", split(/\0/, $in{$_[0]})); } # all_recursive_roles(username) # Returns all roles and sub-roles for some user sub all_recursive_roles { local $users = &list_user_attrs(); local ($user) = grep { $_->{'user'} eq $_[0] } @$users; local (@rv, $r); foreach $r (split(/,/, $user->{'attr'}->{'roles'})) { push(@rv, $r, &all_recursive_roles($r)); } return @rv; } ####################### functions for profiles ####################### # list_prof_attrs() # Returns a list of all profiles sub list_prof_attrs { if (!scalar(@list_prof_attrs_cache)) { @list_prof_attrs_cache = ( ); local $lnum = 0; open(ATTR, $config{'prof_attr'}); while(<ATTR>) { s/\r|\n//g; s/#.*$//; local @w = split(/:/, $_, -1); if (@w == 5) { local $attr = { 'name' => $w[0], 'res1' => $w[1], 'res2' => $w[2], 'desc' => $w[3], 'line' => $lnum, 'type' => 'prof', 'index' => scalar(@list_prof_attrs_cache) }; local $a; foreach $a (split(/;/, $w[4])) { local ($an, $av) = split(/=/, $a, 2); $attr->{'attr'}->{$an} = $av; } push(@list_prof_attrs_cache, $attr); } $lnum++; } close(ATTR); $lnum++; } return \@list_prof_attrs_cache; } # create_prof_attr(&attr) # Add a new profile sub create_prof_attr { local ($attr) = @_; &list_prof_attrs(); # init cache local $lref = &read_file_lines($config{'prof_attr'}); $attr->{'line'} = scalar(@$lref); push(@$lref, &prof_attr_line($attr)); $attr->{'index'} = scalar(@list_prof_attrs_cache); push(@list_prof_attrs_cache, $attr); &flush_file_lines(); } # modify_prof_attr(&attr) # Updates an existing profile in the config file sub modify_prof_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'prof_attr'}); $lref->[$attr->{'line'}] = &prof_attr_line($attr); &flush_file_lines(); } # delete_prof_attr(&attr) # Removes one profile sub delete_prof_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'prof_attr'}); splice(@$lref, $attr->{'line'}, 1); splice(@list_prof_attrs_cache, $attr->{'index'}, 1); local $c; foreach $c (@list_prof_attrs_cache) { $c->{'line'}-- if ($c->{'line'} > $attr->{'line'}); $c->{'index'}-- if ($c->{'index'} > $attr->{'index'}); } &flush_file_lines(); } # prof_attr_line(&attr) # Returns the text for a prof attribute line sub prof_attr_line { local ($attr) = @_; local $rv = $attr->{'name'}.":".$attr->{'res1'}.":".$attr->{'res2'}.":". $attr->{'desc'}.":"; $rv .= join(";", map { $_."=".$attr->{'attr'}->{$_} } keys %{$attr->{'attr'}}); return $rv; } # profiles_input(name, comma-sep-value, acl-restrict) # Returns HTML for a field for selecting multiple profiles sub profiles_input { local ($name, $value, $restrict) = @_; local @values = split(/,/, $value); local $profs = &list_prof_attrs(); local @canprofs = $restrict ? grep { &can_assign_profile($_) } @$profs : @$profs; if (@canprofs) { return &ui_select($name, \@values, [ map { [ $_->{'name'}, "$_->{'name'} ($_->{'desc'})" ] } sort { $a->{'name'} cmp $b->{'name'} } @canprofs ], 10, 1, 1); } else { return $text{'prof_none'}; } } # profiles_parse(name) # Returns a comma-separated list of values from a profiles field sub profiles_parse { return join(",", split(/\0/, $in{$_[0]})); } # all_recursive_profs(username|profilename) # Returns all profiles and sub-profiles for some user sub all_recursive_profs { local $users = &list_user_attrs(); local ($user) = grep { $_->{'user'} eq $_[0] } @$users; local $profs = &list_prof_attrs(); local ($prof) = grep { $_->{'name'} eq $_[0] } @$profs; local (@rv, $r); if ($user) { # Return all profiles from roles, direct profiles and sub-profiles foreach $r (split(/,/, $user->{'attr'}->{'roles'})) { push(@rv, &all_recursive_profs($r)); } foreach $r (split(/,/, $user->{'attr'}->{'profiles'})) { push(@rv, $r, &all_recursive_profs($r)); } } elsif ($prof) { # Return all sub-profiles foreach $r (split(/,/, $prof->{'attr'}->{'profs'})) { push(@rv, &all_recursive_profs($r)); } } return @rv; } ####################### functions for authorizations ####################### # list_auth_attrs() # Returns a user of all authorizations sub list_auth_attrs { if (!scalar(@list_auth_attrs_cache)) { @list_auth_attrs_cache = ( ); local $lnum = 0; open(ATTR, $config{'auth_attr'}); while(<ATTR>) { s/\r|\n//g; s/#.*$//; local @w = split(/:/, $_, -1); if (@w == 6) { local $attr = { 'name' => $w[0], 'res1' => $w[1], 'res2' => $w[2], 'short' => $w[3], 'desc' => $w[4], 'line' => $lnum, 'type' => 'auth', 'index' => scalar(@list_auth_attrs_cache) }; local $a; foreach $a (split(/;/, $w[5])) { local ($an, $av) = split(/=/, $a, 2); $attr->{'attr'}->{$an} = $av; } push(@list_auth_attrs_cache, $attr); } $lnum++; } close(ATTR); $lnum++; } return \@list_auth_attrs_cache; } # create_auth_attr(&attr) # Add a new authorization sub create_auth_attr { local ($attr) = @_; &list_auth_attrs(); # init cache local $lref = &read_file_lines($config{'auth_attr'}); $attr->{'line'} = scalar(@$lref); push(@$lref, &auth_attr_line($attr)); $attr->{'index'} = scalar(@list_auth_attrs_cache); push(@list_auth_attrs_cache, $attr); &flush_file_lines(); } # modify_auth_attr(&attr) # Updates an existing authorization in the config file sub modify_auth_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'auth_attr'}); $lref->[$attr->{'line'}] = &auth_attr_line($attr); &flush_file_lines(); } # delete_auth_attr(&attr) # Removes one authorization sub delete_auth_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'auth_attr'}); splice(@$lref, $attr->{'line'}, 1); splice(@list_auth_attrs_cache, $attr->{'index'}, 1); local $c; foreach $c (@list_auth_attrs_cache) { $c->{'line'}-- if ($c->{'line'} > $attr->{'line'}); $c->{'index'}-- if ($c->{'index'} > $attr->{'index'}); } &flush_file_lines(); } # auth_attr_line(&attr) # Returns the text for a auth attribute line sub auth_attr_line { local ($attr) = @_; local $rv = $attr->{'name'}.":".$attr->{'res1'}.":".$attr->{'res2'}.":". $attr->{'short'}.":".$attr->{'desc'}.":"; $rv .= join(";", map { $_."=".$attr->{'attr'}->{$_} } keys %{$attr->{'attr'}}); return $rv; } # auths_input(name, value) # Returns HTML for a text area for entering and choosing authorizations sub auths_input { local ($name, $value) = @_; return "<table cellpadding=0 cellspacing=0><tr><td>". &ui_textarea($name, join("\n", split(/,/, $value)), 3, 50). "</td><td valign=top>&nbsp;". &auth_chooser($name). "</td></tr></table>"; } # auth_chooser(field) # Returns HTML for a button that pops up an authorization chooser window sub auth_chooser { return "<input type=button onClick='ifield = form.$_[0]; chooser = window.open(\"auth_chooser.cgi\", \"chooser\", \"toolbar=no,menubar=no,scrollbars=yes,width=500,height=400\"); chooser.ifield = ifield; window.ifield = ifield' value=\"...\">\n"; } # auths_parse(name) # Returns a comma-separated list of auths sub auths_parse { local @auths = split(/[\r\n]+/, $in{$_[0]}); local $a; foreach $a (@auths) { $a =~ /^\S+$/ || &error(&text('user_eauth', $a)); } return join(",", @auths); } ####################### functions for exec attributes ####################### # list_exec_attrs() # Returns a user of all execorizations sub list_exec_attrs { if (!scalar(@list_exec_attrs_cache)) { @list_exec_attrs_cache = ( ); local $lnum = 0; open(ATTR, $config{'exec_attr'}); while(<ATTR>) { s/\r|\n//g; s/#.*$//; local @w = split(/:/, $_, -1); if (@w == 7) { local $attr = { 'name' => $w[0], 'policy' => $w[1], 'cmd' => $w[2], 'res1' => $w[3], 'res2' => $w[4], 'id' => $w[5], 'type' => 'exec', 'index' => scalar(@list_exec_attrs_cache) }; local $a; foreach $a (split(/;/, $w[6])) { local ($an, $av) = split(/=/, $a, 2); $attr->{'attr'}->{$an} = $av; } push(@list_exec_attrs_cache, $attr); } $lnum++; } close(ATTR); $lnum++; } return \@list_exec_attrs_cache; } # create_exec_attr(&attr) # Add a new execorization sub create_exec_attr { local ($attr) = @_; &list_exec_attrs(); # init cache local $lref = &read_file_lines($config{'exec_attr'}); $attr->{'line'} = scalar(@$lref); push(@$lref, &exec_attr_line($attr)); $attr->{'index'} = scalar(@list_exec_attrs_cache); push(@list_exec_attrs_cache, $attr); &flush_file_lines(); } # modify_exec_attr(&attr) # Updates an existing execorization in the config file sub modify_exec_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'exec_attr'}); $lref->[$attr->{'line'}] = &exec_attr_line($attr); &flush_file_lines(); } # delete_exec_attr(&attr) # Removes one execorization sub delete_exec_attr { local ($attr) = @_; local $lref = &read_file_lines($config{'exec_attr'}); splice(@$lref, $attr->{'line'}, 1); splice(@list_exec_attrs_cache, $attr->{'index'}, 1); local $c; foreach $c (@list_exec_attrs_cache) { $c->{'line'}-- if ($c->{'line'} > $attr->{'line'}); $c->{'index'}-- if ($c->{'index'} > $attr->{'index'}); } &flush_file_lines(); } # exec_attr_line(&attr) # Returns the text for a exec attribute line sub exec_attr_line { local ($attr) = @_; local $rv = $attr->{'name'}.":".$attr->{'policy'}.":".$attr->{'cmd'}.":". $attr->{'res1'}.":".$attr->{'res2'}.":".$attr->{'id'}.":"; $rv .= join(";", map { $_."=".$attr->{'attr'}->{$_} } keys %{$attr->{'attr'}}); return $rv; } ####################### policy.conf functions ####################### # get_policy_config() # Returns a list of policy config file directives sub get_policy_config { if (!scalar(@policy_conf_cache)) { @policy_conf_cache = ( ); local $lnum = 0; open(ATTR, $config{'policy_conf'}); while(<ATTR>) { s/\r|\n//g; s/\s+$//; if (/^\s*(#*)\s*([^= ]+)\s*=\s*(\S.*)$/) { local $pol = { 'name' => $2, 'value' => $3, 'enabled' => !$1, 'line' => $lnum, 'index' => scalar(@policy_conf_cache) }; push(@policy_conf_cache, $pol); } $lnum++; } close(ATTR); $lnum++; } return \@policy_conf_cache; } # find_policy(name, &conf, [enabled]) sub find_policy { local ($name, $conf, $ena) = @_; local ($rv) = grep { lc($_->{'name'}) eq lc($name) && (!defined($ena) || defined($ena) && $ena == $_->{'enabled'}) } @$conf; return $rv; } # find_policy_value(name, &conf); sub find_policy_value { local ($name, $conf) = @_; local $rv = &find_policy($name, $conf, 1); return $rv ? $rv->{'value'} : undef; } # save_policy(&conf, name, [value]) # Update or delete an entry in policy.conf sub save_policy { local ($conf, $name, $value) = @_; local $old = &find_policy($name, $conf); local $lref = &read_file_lines($config{'policy_conf'}); if (!$old && $value) { # Need to add push(@$lref, "$name=$value"); push(@$conf, { 'name' => $name, 'value' => $value, 'index' => scalar(@$conf), 'line' => scalar(@$lref) - 1 }); } elsif ($old && $value) { # Need to update (and perhaps comment in) $old->{'value'} = $value; $old->{'enabled'} = 1; $lref->[$old->{'line'}] = "$name=$value"; } elsif ($old && $old->{'enabled'} && !$value) { # Need to comment out $old->{'enabled'} = 0; $lref->[$old->{'line'}] = "#$name=$old->{'value'}"; } } ####################### functions for projects ####################### # list_projects() # Returns a list of project objects sub list_projects { if (!scalar(@list_projects_cache)) { @list_projects_cache = ( ); local $lnum = 0; open(ATTR, $config{'project'}); while(<ATTR>) { s/\r|\n//g; s/#.*$//; local @w = split(/:/, $_, -1); if (@w >= 2) { local $attr = { 'name' => $w[0], 'id' => $w[1], 'desc' => $w[2], 'users' => $w[3], 'groups' => $w[4], 'line' => $lnum, 'type' => 'project', 'index' => scalar(@list_projects_cache) }; local $a; foreach $a (split(/;/, $w[5])) { local ($an, $av) = split(/=/, $a, 2); $attr->{'attr'}->{$an} = $av; } push(@list_projects_cache, $attr); } $lnum++; } close(ATTR); } return \@list_projects_cache; } # create_project(&attr) # Add a new project sub create_project { local ($attr) = @_; &list_projects(); # init cache local $lref = &read_file_lines($config{'project'}); $attr->{'line'} = scalar(@$lref); push(@$lref, &project_line($attr)); $attr->{'index'} = scalar(@list_projects_cache); push(@list_projects_cache, $attr); &flush_file_lines(); } # modify_project(&attr) # Updates an existing project in the config file sub modify_project { local ($attr) = @_; local $lref = &read_file_lines($config{'project'}); $lref->[$attr->{'line'}] = &project_line($attr); &flush_file_lines(); } # delete_project(&attr) # Removes one project entry sub delete_project { local ($attr) = @_; local $lref = &read_file_lines($config{'project'}); splice(@$lref, $attr->{'line'}, 1); splice(@list_projects_cache, $attr->{'index'}, 1); local $c; foreach $c (@list_projects_cache) { $c->{'line'}-- if ($c->{'line'} > $attr->{'line'}); $c->{'index'}-- if ($c->{'index'} > $attr->{'index'}); } &flush_file_lines(); } # project_line(&attr) # Returns the text for a project file line sub project_line { local ($attr) = @_; local $rv = $attr->{'name'}.":".$attr->{'id'}.":".$attr->{'desc'}.":". $attr->{'users'}.":".$attr->{'groups'}.":"; $rv .= join(";", map { defined($attr->{'attr'}->{$_}) ? $_."=".$attr->{'attr'}->{$_} : $_ } keys %{$attr->{'attr'}}); return $rv; } # project_input(name, value) # Returns HTML for selecting one project sub project_input { local ($name, $value) = @_; local $projects = &list_projects(); return &ui_select($name, $value, [ map { [ $_->{'name'}, $_->{'name'}.($_->{'desc'} ? " ($_->{'desc'})" : "") ] } @$projects ], 0, 0, $value ? 1 : 0); } # project_members_input(name, comma-separated-members) # Returns HTML for selecting users or groups in a project. These may be all, # none, all except or only some sub project_members_input { local ($name, $users) = @_; local @users = split(/,/, $users); local %users = map { $_, 1 } @users; local (@canusers, @cannotuser, $mode); if ($users{'*'} && @users == 1) { $mode = 0; } elsif (@users == 0 || $users{'!*'} && @users == 1) { $mode = 1; } elsif ($users{'*'}) { # All except some $mode = 3; @cannotusers = map { /^\!(.*)/; $1 } grep { /^\!/ } @users[1..$#users]; } elsif ($users{'!*'}) { # Only some $mode = 2; @canusers = grep { !/^\!/ } @users[1..$#users]; } else { # Only listed $mode = 2; @canusers = @users; } local $cb = $name =~ /user/ ? \&user_chooser_button : \&group_chooser_button; return &ui_radio($name."_mode", $mode, [ [ 0, $text{'projects_all'.$name} ], [ 1, $text{'projects_none'.$name}."<br>" ], [ 2, &text('projects_only'.$name, &ui_textbox($name."_can", join(" ", @canusers), 40)." ". &$cb($name."_can", 1))."<br>" ], [ 3, &text('projects_except'.$name, &ui_textbox($name."_cannot", join(" ", @cannotusers), 40)." ". &$cb($name."_cannot", 1)) ] ]); } # parse_project_members(name) sub parse_project_members { local ($name) = @_; if ($in{$name."_mode"} == 0) { return "*"; } elsif ($in{$name."_mode"} == 1) { return ""; } elsif ($in{$name."_mode"} == 2) { $in{$name."_can"} || &error($text{'project_e'.$name.'can'}); return join(",", split(/\s+/, $in{$name."_can"})); } elsif ($in{$name."_mode"} == 3) { $in{$name."_cannot"} || &error($text{'project_e'.$name.'cannot'}); return join(",", "*", map { "!$_" } split(/\s+/, $in{$name."_cannot"})); } } ####################### miscellaneous functions ####################### # nice_comma_list(comma-separated-value) # Nicely formats and shortens a comma-separated string sub nice_comma_list { local @l = split(/,/, $_[0]); if (@l > 2) { return join(" , ", @l[0..1], "..."); } else { return join(" , ", @l); } } # rbac_help_file(&object) sub rbac_help_file { local $hf = $config{$_[0]->{'type'}.'_help_dir'}."/$_[0]->{'attr'}->{'help'}"; return -r $hf && !-d $hf ? $hf : undef; } # rbac_help_link(&object, desc) sub rbac_help_link { local $hf = &rbac_help_file($_[0]); local $rv = "<table cellpadding=0 cellspacing=0 width=100%><tr><td>$_[1]</td>"; if ($hf) { $hf = &urlize($hf); $rv .= "<td align=right><a onClick='window.open(\"rbac_help.cgi?help=$hf\", \"help\", \"toolbar=no,menubar=no,scrollbars=yes,width=400,height=300,resizable=yes\"); return false' href=\"rbac_help.cgi?help=$hf\"><img src=images/help.gif border=0></a></td>"; } $rv .= "</tr></table>"; return $rv; } # rbac_config_files() # Returns a list of all config files managed by this module sub rbac_config_files { return map { $config{$_} } ('user_attr', 'prof_attr', 'auth_attr', 'exec_attr', 'policy_conf', 'project'); } # missing_rbac_config_file() # Returns the path to any missing config file sub missing_rbac_config_file { foreach $c (&rbac_config_files()) { return $c if (!-r $c); } return undef; } # lock_rbac_files() # Lock all config files used by RBAC sub lock_rbac_files { local $c; foreach $c (&rbac_config_files()) { &lock_file($c); } } # unlock_rbac_files() # Unlock all config files used by RBAC sub unlock_rbac_files { local $c; foreach $c (&rbac_config_files()) { &unlock_file($c); } } # list_crypt_algorithms() # Returns 1 list of all encryption algorithms, including the internal __unix__ sub list_crypt_algorithms { if (!scalar(@list_crypt_algorithms_cache)) { push(@list_crypt_algorithms_cache, { 'name' => '__unix__' } ); local $lnum = 0; open(CRYPT, $config{'crypt_conf'}); while(<CRYPT>) { s/\r|\n//g; s/#.*$//; if (/^\s*(\S+)\s+(\S+)/) { push(@list_crypt_algorithms_cache, { 'name' => $1, 'lib' => $2, 'line' => $lnum, 'index' => scalar(@list_crypt_algorithms_cache) }); } $lnum++; } close(CRYPT); } return \@list_crypt_algorithms_cache; } # crypt_algorithms_input(name, value, multiple) # Returns HTML for selecting one or many crypt algorithms sub crypt_algorithms_input { local ($name, $value, $multiple) = @_; local @values = split(/,/, $value); local $crypts = &list_crypt_algorithms(); return &ui_select($name, \@values, [ map { [ $_->{'name'}, $text{'crypt_'.$_->{'name'}} ] } @$crypts ], $multiple ? scalar(@$crypts) : undef, $multiple, 1); } # can_edit_user(&user) # Returns 1 if some user can be edited sub can_edit_user { local ($user) = @_; return 0 if ($user->{'attr'}->{'type'} eq 'role' && !$access{'roles'}); return 0 if ($user->{'attr'}->{'type'} ne 'role' && !$access{'users'}); return 1; } # can_assign_role(&role|rolename) # Returns 1 if some role can be assigned sub can_assign_role { local ($role) = @_; local $rolename = ref($role) ? $role->{'user'} : $role; if ($access{'roleassign'} eq '*') { return 1; } else { local @canroles; if ($access{'roleassign'} eq 'x') { # Work out Webmin user's roles @canroles = &all_recursive_roles($remote_user); } else { @canroles = split(/,/, $access{'roleassign'}); } return &indexof($rolename, @canroles) != -1; } } # can_assign_profile(&profile|profilename) # Returns 1 if some profile can be assigned sub can_assign_profile { local ($prof) = @_; local $profname = ref($prof) ? $prof->{'name'} : $prof; if ($access{'profassign'} eq '*') { return 1; } else { local @canprofs; if ($access{'profassign'} eq 'x') { # Work out Webmin user's profs @canprofs = &all_recursive_profs($remote_user); } else { @canprofs = split(/,/, $access{'profassign'}); } return &indexof($profname, @canprofs) != -1; } } # list_rctls() # Returns a list of possible resource control names sub list_rctls { local @rv; open(RCTL, "rctladm -l |"); while(<RCTL>) { if (/^(\S+)\s+(\S+)=(\S+)/) { push(@rv, $1); } } close(RCTL); return @rv; } # list_rctl_signals() # Returns a list of allowed signals for rctl actions sub list_rctl_signals { return ( [ "SIGABRT", "Abort the process" ], [ "SIGHUP", "Send a hangup signal" ], [ "SIGTERM", "Terminate the process" ], [ "SIGKILL", "Kill the process" ], [ "SIGSTOP", "Stop the process" ], [ "SIGXRES", "Resource control limit exceeded" ], [ "SIGXFSZ", "File size limit exceeded" ], [ "SIGXCPU", "CPU time limit exceeded" ] ); } # list_resource_controls(type, id) # Returns a list of resource controls for some project, zone or process sub list_resource_controls { local ($type, $id) = @_; &open_execute_command(PRCTL, "prctl -i ".quotemeta($type)." ".quotemeta($id), 1); local (@rv, $res); while(<PRCTL>) { s/\r|\n//g; next if (/^NAME/); # skip header if (/^(\S+)\s*$/) { # Start of a new resource $res = $1; } elsif (/^\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ && $res) { # A limit within a resource push(@rv, { 'res' => $res, 'priv' => $1, 'limit' => $2, 'flag' => $3 eq "-" ? undef : $3, 'action' => $4 }); } } close(PRCTL); return @rv; } 1;
BangL/webmin
rbac/rbac-lib.pl
Perl
bsd-3-clause
23,850
package DDG::Goodie::UnixTime; # ABSTRACT: epoch -> human readable time use strict; use DDG::Goodie; use DateTime; use List::MoreUtils qw( uniq ); use Try::Tiny; my @trigger_words = ("unixtime", "datetime", "unix timestamp", "unix time stamp", "unix epoch", "epoch", "timestamp", "unix time", "utc time", "utc now", "current utc", "time since epoch"); triggers startend => @trigger_words; zci answer_type => "time_conversion"; zci is_cached => 0; attribution github => ['codejoust', 'Iain ']; primary_example_queries 'unix time 0000000000000'; secondary_example_queries 'epoch 0', 'epoch 2147483647'; description 'convert a unix epoch to human-readable time'; code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/UnixTime.pm'; category 'calculations'; topics 'sysadmin'; my $default_tz = 'UTC'; my $time_format = '%a %b %d %T %Y %Z'; my $header_format = "Time (%s)"; my %no_default_triggers = map { $_ => 1 } qw(timestamp epoch); my $triggers = join('|', @trigger_words); my $extract_qr = qr/^(?<trigger>$triggers)?\s*(?<epoch>-?\d+)?\s*(?<trigger>$triggers)?$/; handle query => sub { my $query = shift; $query =~ $extract_qr; my $time_input = $+{'epoch'}; # If there was nothing in there, we must want now... unless we're not supposed to default for this trigger. $time_input //= time unless ($no_default_triggers{$+{'trigger'}}); return unless defined $time_input; my $dt = try { DateTime->from_epoch(epoch => $time_input) }; return unless $dt; my $time_output; my @table_data = (['Unix Epoch', $time_input]); foreach my $tz (uniq grep { $_ } ($loc->time_zone, $default_tz)) { $dt->set_time_zone($tz); push @table_data, [sprintf($header_format, $tz), $dt->strftime($time_format)]; } my $text = join(' | ', (map { join(' => ', @{$_}) } @table_data)); return $text, html => to_html(@table_data); }; sub to_html { my $results = ""; my $minwidth = "90px"; foreach my $result (@_) { $results .= "<div><span class=\"unixtime__label text--secondary\">$result->[0]: </span><span class=\"text--primary\">$result->[1]</span></div>"; $minwidth = "180px" if length($result->[0]) > 10; } return $results . "<style> .zci--answer .unixtime__label {display: inline-block; min-width: $minwidth}</style>"; } 1;
aasoliz/zeroclickinfo-goodies
lib/DDG/Goodie/UnixTime.pm
Perl
apache-2.0
2,410
use Mojolicious::Lite; use Mojo::Pg; use Cpanel::JSON::XS 'encode_json'; use Scalar::Util 'looks_like_number'; # configuration { my $nproc = `nproc`; app->config(hypnotoad => { accepts => 0, clients => int( 256 / $nproc ) + 1, graceful_timeout => 1, requests => 10000, workers => $nproc, }); } { my $db_host = $ENV{DBHOST} || 'localhost'; helper pg => sub { state $pg = Mojo::Pg->new('postgresql://benchmarkdbuser:benchmarkdbpass@' . $db_host . '/hello_world') }; } helper render_json => sub { my $c = shift; $c->res->headers->content_type('application/json'); $c->render( data => encode_json(shift) ); }; # Routes get '/json' => sub { shift->helpers->render_json({message => 'Hello, World!'}) }; get '/db' => sub { shift->helpers->render_query(1, {single => 1}) }; get '/queries' => sub { my $c = shift; $c->helpers->render_query(scalar $c->param('queries')); }; get '/fortunes' => sub { my $c = shift; my $docs = $c->helpers->pg->db->query('SELECT id, message FROM Fortune')->arrays; push @$docs, [0, 'Additional fortune added at request time.']; $c->render( fortunes => docs => $docs->sort(sub{ $a->[1] cmp $b->[1] }) ); }; get '/updates' => sub { my $c = shift; $c->helpers->render_query(scalar $c->param('queries'), {update => 1}); }; get '/plaintext' => sub { my $c = shift; $c->res->headers->content_type('text/plain'); $c->render( text => 'Hello, World!' ); }; # Additional helpers (shared code) helper 'render_query' => sub { my ($self, $q, $args) = @_; $args ||= {}; my $update = $args->{update}; $q = 1 unless looks_like_number($q); $q = 1 if $q < 1; $q = 500 if $q > 500; my $r = []; my $tx = $self->tx; my $db = $self->helpers->pg->db; foreach (1 .. $q) { my $id = int rand 10_000; my $randomNumber = $db->query('SELECT randomnumber FROM World WHERE id=?', $id)->array->[0]; $db->query('UPDATE World SET randomnumber=? WHERE id=?', ($randomNumber = 1 + int rand 10_000), $id) if $update; push @$r, { id => $id, randomNumber => $randomNumber }; } $r = $r->[0] if $args->{single}; $self->helpers->render_json($r); }; app->start; __DATA__ @@ fortunes.html.ep <!DOCTYPE html> <html> <head><title>Fortunes</title></head> <body> <table> <tr><th>id</th><th>message</th></tr> % foreach my $doc (@$docs) { <tr> <td><%= $doc->[0] %></td> <td><%= $doc->[1] %></td> </tr> % } </table> </body> </html>
grob/FrameworkBenchmarks
frameworks/Perl/mojolicious/app.pl
Perl
bsd-3-clause
2,495
=pod =head1 NAME EVP_CIPHER_CTX_init, EVP_EncryptInit_ex, EVP_EncryptUpdate, EVP_EncryptFinal_ex, EVP_DecryptInit_ex, EVP_DecryptUpdate, EVP_DecryptFinal_ex, EVP_CipherInit_ex, EVP_CipherUpdate, EVP_CipherFinal_ex, EVP_CIPHER_CTX_set_key_length, EVP_CIPHER_CTX_ctrl, EVP_CIPHER_CTX_cleanup, EVP_EncryptInit, EVP_EncryptFinal, EVP_DecryptInit, EVP_DecryptFinal, EVP_CipherInit, EVP_CipherFinal, EVP_get_cipherbyname, EVP_get_cipherbynid, EVP_get_cipherbyobj, EVP_CIPHER_nid, EVP_CIPHER_block_size, EVP_CIPHER_key_length, EVP_CIPHER_iv_length, EVP_CIPHER_flags, EVP_CIPHER_mode, EVP_CIPHER_type, EVP_CIPHER_CTX_cipher, EVP_CIPHER_CTX_nid, EVP_CIPHER_CTX_block_size, EVP_CIPHER_CTX_key_length, EVP_CIPHER_CTX_iv_length, EVP_CIPHER_CTX_get_app_data, EVP_CIPHER_CTX_set_app_data, EVP_CIPHER_CTX_type, EVP_CIPHER_CTX_flags, EVP_CIPHER_CTX_mode, EVP_CIPHER_param_to_asn1, EVP_CIPHER_asn1_to_param, EVP_CIPHER_CTX_set_padding, EVP_enc_null, EVP_des_cbc, EVP_des_ecb, EVP_des_cfb, EVP_des_ofb, EVP_des_ede_cbc, EVP_des_ede, EVP_des_ede_ofb, EVP_des_ede_cfb, EVP_des_ede3_cbc, EVP_des_ede3, EVP_des_ede3_ofb, EVP_des_ede3_cfb, EVP_desx_cbc, EVP_rc4, EVP_rc4_40, EVP_idea_cbc, EVP_idea_ecb, EVP_idea_cfb, EVP_idea_ofb, EVP_idea_cbc, EVP_rc2_cbc, EVP_rc2_ecb, EVP_rc2_cfb, EVP_rc2_ofb, EVP_rc2_40_cbc, EVP_rc2_64_cbc, EVP_bf_cbc, EVP_bf_ecb, EVP_bf_cfb, EVP_bf_ofb, EVP_cast5_cbc, EVP_cast5_ecb, EVP_cast5_cfb, EVP_cast5_ofb, EVP_rc5_32_12_16_cbc, EVP_rc5_32_12_16_ecb, EVP_rc5_32_12_16_cfb, EVP_rc5_32_12_16_ofb, EVP_aes_128_gcm, EVP_aes_192_gcm, EVP_aes_256_gcm, EVP_aes_128_ccm, EVP_aes_192_ccm, EVP_aes_256_ccm - EVP cipher routines =head1 SYNOPSIS #include <openssl/evp.h> void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *a); int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, unsigned char *key, unsigned char *iv); int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl); int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, unsigned char *key, unsigned char *iv); int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl); int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, ENGINE *impl, unsigned char *key, unsigned char *iv, int enc); int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, unsigned char *in, int inl); int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char *key, unsigned char *iv); int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char *key, unsigned char *iv); int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type, unsigned char *key, unsigned char *iv, int enc); int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm, int *outl); int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *x, int padding); int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen); int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr); int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *a); const EVP_CIPHER *EVP_get_cipherbyname(const char *name); #define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a)) #define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a)) #define EVP_CIPHER_nid(e) ((e)->nid) #define EVP_CIPHER_block_size(e) ((e)->block_size) #define EVP_CIPHER_key_length(e) ((e)->key_len) #define EVP_CIPHER_iv_length(e) ((e)->iv_len) #define EVP_CIPHER_flags(e) ((e)->flags) #define EVP_CIPHER_mode(e) ((e)->flags) & EVP_CIPH_MODE) int EVP_CIPHER_type(const EVP_CIPHER *ctx); #define EVP_CIPHER_CTX_cipher(e) ((e)->cipher) #define EVP_CIPHER_CTX_nid(e) ((e)->cipher->nid) #define EVP_CIPHER_CTX_block_size(e) ((e)->cipher->block_size) #define EVP_CIPHER_CTX_key_length(e) ((e)->key_len) #define EVP_CIPHER_CTX_iv_length(e) ((e)->cipher->iv_len) #define EVP_CIPHER_CTX_get_app_data(e) ((e)->app_data) #define EVP_CIPHER_CTX_set_app_data(e,d) ((e)->app_data=(char *)(d)) #define EVP_CIPHER_CTX_type(c) EVP_CIPHER_type(EVP_CIPHER_CTX_cipher(c)) #define EVP_CIPHER_CTX_flags(e) ((e)->cipher->flags) #define EVP_CIPHER_CTX_mode(e) ((e)->cipher->flags & EVP_CIPH_MODE) int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type); int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type); =head1 DESCRIPTION The EVP cipher routines are a high level interface to certain symmetric ciphers. EVP_CIPHER_CTX_init() initializes cipher contex B<ctx>. EVP_EncryptInit_ex() sets up cipher context B<ctx> for encryption with cipher B<type> from ENGINE B<impl>. B<ctx> must be initialized before calling this function. B<type> is normally supplied by a function such as EVP_des_cbc(). If B<impl> is NULL then the default implementation is used. B<key> is the symmetric key to use and B<iv> is the IV to use (if necessary), the actual number of bytes used for the key and IV depends on the cipher. It is possible to set all parameters to NULL except B<type> in an initial call and supply the remaining parameters in subsequent calls, all of which have B<type> set to NULL. This is done when the default cipher parameters are not appropriate. EVP_EncryptUpdate() encrypts B<inl> bytes from the buffer B<in> and writes the encrypted version to B<out>. This function can be called multiple times to encrypt successive blocks of data. The amount of data written depends on the block alignment of the encrypted data: as a result the amount of data written may be anything from zero bytes to (inl + cipher_block_size - 1) so B<out> should contain sufficient room. The actual number of bytes written is placed in B<outl>. If padding is enabled (the default) then EVP_EncryptFinal_ex() encrypts the "final" data, that is any data that remains in a partial block. It uses L<standard block padding|/NOTES> (aka PKCS padding). The encrypted final data is written to B<out> which should have sufficient space for one cipher block. The number of bytes written is placed in B<outl>. After this function is called the encryption operation is finished and no further calls to EVP_EncryptUpdate() should be made. If padding is disabled then EVP_EncryptFinal_ex() will not encrypt any more data and it will return an error if any data remains in a partial block: that is if the total data length is not a multiple of the block size. EVP_DecryptInit_ex(), EVP_DecryptUpdate() and EVP_DecryptFinal_ex() are the corresponding decryption operations. EVP_DecryptFinal() will return an error code if padding is enabled and the final block is not correctly formatted. The parameters and restrictions are identical to the encryption operations except that if padding is enabled the decrypted data buffer B<out> passed to EVP_DecryptUpdate() should have sufficient room for (B<inl> + cipher_block_size) bytes unless the cipher block size is 1 in which case B<inl> bytes is sufficient. EVP_CipherInit_ex(), EVP_CipherUpdate() and EVP_CipherFinal_ex() are functions that can be used for decryption or encryption. The operation performed depends on the value of the B<enc> parameter. It should be set to 1 for encryption, 0 for decryption and -1 to leave the value unchanged (the actual value of 'enc' being supplied in a previous call). EVP_CIPHER_CTX_cleanup() clears all information from a cipher context and free up any allocated memory associate with it. It should be called after all operations using a cipher are complete so sensitive information does not remain in memory. EVP_EncryptInit(), EVP_DecryptInit() and EVP_CipherInit() behave in a similar way to EVP_EncryptInit_ex(), EVP_DecryptInit_ex and EVP_CipherInit_ex() except the B<ctx> parameter does not need to be initialized and they always use the default cipher implementation. EVP_EncryptFinal(), EVP_DecryptFinal() and EVP_CipherFinal() behave in a similar way to EVP_EncryptFinal_ex(), EVP_DecryptFinal_ex() and EVP_CipherFinal_ex() except B<ctx> is automatically cleaned up after the call. EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj() return an EVP_CIPHER structure when passed a cipher name, a NID or an ASN1_OBJECT structure. EVP_CIPHER_nid() and EVP_CIPHER_CTX_nid() return the NID of a cipher when passed an B<EVP_CIPHER> or B<EVP_CIPHER_CTX> structure. The actual NID value is an internal value which may not have a corresponding OBJECT IDENTIFIER. EVP_CIPHER_CTX_set_padding() enables or disables padding. By default encryption operations are padded using standard block padding and the padding is checked and removed when decrypting. If the B<pad> parameter is zero then no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur. EVP_CIPHER_key_length() and EVP_CIPHER_CTX_key_length() return the key length of a cipher when passed an B<EVP_CIPHER> or B<EVP_CIPHER_CTX> structure. The constant B<EVP_MAX_KEY_LENGTH> is the maximum key length for all ciphers. Note: although EVP_CIPHER_key_length() is fixed for a given cipher, the value of EVP_CIPHER_CTX_key_length() may be different for variable key length ciphers. EVP_CIPHER_CTX_set_key_length() sets the key length of the cipher ctx. If the cipher is a fixed length cipher then attempting to set the key length to any value other than the fixed value is an error. EVP_CIPHER_iv_length() and EVP_CIPHER_CTX_iv_length() return the IV length of a cipher when passed an B<EVP_CIPHER> or B<EVP_CIPHER_CTX>. It will return zero if the cipher does not use an IV. The constant B<EVP_MAX_IV_LENGTH> is the maximum IV length for all ciphers. EVP_CIPHER_block_size() and EVP_CIPHER_CTX_block_size() return the block size of a cipher when passed an B<EVP_CIPHER> or B<EVP_CIPHER_CTX> structure. The constant B<EVP_MAX_IV_LENGTH> is also the maximum block length for all ciphers. EVP_CIPHER_type() and EVP_CIPHER_CTX_type() return the type of the passed cipher or context. This "type" is the actual NID of the cipher OBJECT IDENTIFIER as such it ignores the cipher parameters and 40 bit RC2 and 128 bit RC2 have the same NID. If the cipher does not have an object identifier or does not have ASN1 support this function will return B<NID_undef>. EVP_CIPHER_CTX_cipher() returns the B<EVP_CIPHER> structure when passed an B<EVP_CIPHER_CTX> structure. EVP_CIPHER_mode() and EVP_CIPHER_CTX_mode() return the block cipher mode: EVP_CIPH_ECB_MODE, EVP_CIPH_CBC_MODE, EVP_CIPH_CFB_MODE or EVP_CIPH_OFB_MODE. If the cipher is a stream cipher then EVP_CIPH_STREAM_CIPHER is returned. EVP_CIPHER_param_to_asn1() sets the AlgorithmIdentifier "parameter" based on the passed cipher. This will typically include any parameters and an IV. The cipher IV (if any) must be set when this call is made. This call should be made before the cipher is actually "used" (before any EVP_EncryptUpdate(), EVP_DecryptUpdate() calls for example). This function may fail if the cipher does not have any ASN1 support. EVP_CIPHER_asn1_to_param() sets the cipher parameters based on an ASN1 AlgorithmIdentifier "parameter". The precise effect depends on the cipher In the case of RC2, for example, it will set the IV and effective key length. This function should be called after the base cipher type is set but before the key is set. For example EVP_CipherInit() will be called with the IV and key set to NULL, EVP_CIPHER_asn1_to_param() will be called and finally EVP_CipherInit() again with all parameters except the key set to NULL. It is possible for this function to fail if the cipher does not have any ASN1 support or the parameters cannot be set (for example the RC2 effective key length is not supported. EVP_CIPHER_CTX_ctrl() allows various cipher specific parameters to be determined and set. =head1 RETURN VALUES EVP_EncryptInit_ex(), EVP_EncryptUpdate() and EVP_EncryptFinal_ex() return 1 for success and 0 for failure. EVP_DecryptInit_ex() and EVP_DecryptUpdate() return 1 for success and 0 for failure. EVP_DecryptFinal_ex() returns 0 if the decrypt failed or 1 for success. EVP_CipherInit_ex() and EVP_CipherUpdate() return 1 for success and 0 for failure. EVP_CipherFinal_ex() returns 0 for a decryption failure or 1 for success. EVP_CIPHER_CTX_cleanup() returns 1 for success and 0 for failure. EVP_get_cipherbyname(), EVP_get_cipherbynid() and EVP_get_cipherbyobj() return an B<EVP_CIPHER> structure or NULL on error. EVP_CIPHER_nid() and EVP_CIPHER_CTX_nid() return a NID. EVP_CIPHER_block_size() and EVP_CIPHER_CTX_block_size() return the block size. EVP_CIPHER_key_length() and EVP_CIPHER_CTX_key_length() return the key length. EVP_CIPHER_CTX_set_padding() always returns 1. EVP_CIPHER_iv_length() and EVP_CIPHER_CTX_iv_length() return the IV length or zero if the cipher does not use an IV. EVP_CIPHER_type() and EVP_CIPHER_CTX_type() return the NID of the cipher's OBJECT IDENTIFIER or NID_undef if it has no defined OBJECT IDENTIFIER. EVP_CIPHER_CTX_cipher() returns an B<EVP_CIPHER> structure. EVP_CIPHER_param_to_asn1() and EVP_CIPHER_asn1_to_param() return 1 for success or zero for failure. =head1 CIPHER LISTING All algorithms have a fixed key length unless otherwise stated. =over 4 =item EVP_enc_null() Null cipher: does nothing. =item EVP_des_cbc(void), EVP_des_ecb(void), EVP_des_cfb(void), EVP_des_ofb(void) DES in CBC, ECB, CFB and OFB modes respectively. =item EVP_des_ede_cbc(void), EVP_des_ede(), EVP_des_ede_ofb(void), EVP_des_ede_cfb(void) Two key triple DES in CBC, ECB, CFB and OFB modes respectively. =item EVP_des_ede3_cbc(void), EVP_des_ede3(), EVP_des_ede3_ofb(void), EVP_des_ede3_cfb(void) Three key triple DES in CBC, ECB, CFB and OFB modes respectively. =item EVP_desx_cbc(void) DESX algorithm in CBC mode. =item EVP_rc4(void) RC4 stream cipher. This is a variable key length cipher with default key length 128 bits. =item EVP_rc4_40(void) RC4 stream cipher with 40 bit key length. This is obsolete and new code should use EVP_rc4() and the EVP_CIPHER_CTX_set_key_length() function. =item EVP_idea_cbc() EVP_idea_ecb(void), EVP_idea_cfb(void), EVP_idea_ofb(void), EVP_idea_cbc(void) IDEA encryption algorithm in CBC, ECB, CFB and OFB modes respectively. =item EVP_rc2_cbc(void), EVP_rc2_ecb(void), EVP_rc2_cfb(void), EVP_rc2_ofb(void) RC2 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key length cipher with an additional parameter called "effective key bits" or "effective key length". By default both are set to 128 bits. =item EVP_rc2_40_cbc(void), EVP_rc2_64_cbc(void) RC2 algorithm in CBC mode with a default key length and effective key length of 40 and 64 bits. These are obsolete and new code should use EVP_rc2_cbc(), EVP_CIPHER_CTX_set_key_length() and EVP_CIPHER_CTX_ctrl() to set the key length and effective key length. =item EVP_bf_cbc(void), EVP_bf_ecb(void), EVP_bf_cfb(void), EVP_bf_ofb(void); Blowfish encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key length cipher. =item EVP_cast5_cbc(void), EVP_cast5_ecb(void), EVP_cast5_cfb(void), EVP_cast5_ofb(void) CAST encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key length cipher. =item EVP_rc5_32_12_16_cbc(void), EVP_rc5_32_12_16_ecb(void), EVP_rc5_32_12_16_cfb(void), EVP_rc5_32_12_16_ofb(void) RC5 encryption algorithm in CBC, ECB, CFB and OFB modes respectively. This is a variable key length cipher with an additional "number of rounds" parameter. By default the key length is set to 128 bits and 12 rounds. =item EVP_aes_128_gcm(void), EVP_aes_192_gcm(void), EVP_aes_256_gcm(void) AES Galois Counter Mode (GCM) for 128, 192 and 256 bit keys respectively. These ciphers require additional control operations to function correctly: see L<GCM mode> section below for details. =item EVP_aes_128_ccm(void), EVP_aes_192_ccm(void), EVP_aes_256_ccm(void) AES Counter with CBC-MAC Mode (CCM) for 128, 192 and 256 bit keys respectively. These ciphers require additional control operations to function correctly: see CCM mode section below for details. =back =head1 GCM Mode For GCM mode ciphers the behaviour of the EVP interface is subtly altered and several GCM specific ctrl operations are supported. To specify any additional authenticated data (AAD) a call to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() should be made with the output parameter B<out> set to B<NULL>. When decrypting the return value of EVP_DecryptFinal() or EVP_CipherFinal() indicates if the operation was successful. If it does not indicate success the authentication operation has failed and any output data B<MUST NOT> be used as it is corrupted. The following ctrls are supported in GCM mode: EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, ivlen, NULL); Sets the GCM IV length: this call can only be made before specifying an IV. If not called a default IV length is used (96 bits for AES). EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, taglen, tag); Writes B<taglen> bytes of the tag value to the buffer indicated by B<tag>. This call can only be made when encrypting data and B<after> all data has been processed (e.g. after an EVP_EncryptFinal() call). EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, taglen, tag); Sets the expected tag to B<taglen> bytes from B<tag>. This call is only legal when decrypting data and must be made B<before> any data is processed (e.g. before any EVP_DecryptUpdate() call). See L<EXAMPLES> below for an example of the use of GCM mode. =head1 CCM Mode The behaviour of CCM mode ciphers is similar to CCM mode but with a few additional requirements and different ctrl values. Like GCM mode any additional authenticated data (AAD) is passed by calling EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output parameter B<out> set to B<NULL>. Additionally the total plaintext or ciphertext length B<MUST> be passed to EVP_CipherUpdate(), EVP_EncryptUpdate() or EVP_DecryptUpdate() with the output and input parameters (B<in> and B<out>) set to B<NULL> and the length passed in the B<inl> parameter. The following ctrls are supported in CCM mode: EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, taglen, tag); This call is made to set the expected B<CCM> tag value when decrypting or the length of the tag (with the B<tag> parameter set to NULL) when encrypting. The tag length is often referred to as B<M>. If not set a default value is used (12 for AES). EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_L, ivlen, NULL); Sets the CCM B<L> value. If not set a default is used (8 for AES). EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, ivlen, NULL); Sets the CCM nonce (IV) length: this call can only be made before specifying an nonce value. The nonce length is given by B<15 - L> so it is 7 by default for AES. =head1 NOTES Where possible the B<EVP> interface to symmetric ciphers should be used in preference to the low level interfaces. This is because the code then becomes transparent to the cipher used and much more flexible. Additionally, the B<EVP> interface will ensure the use of platform specific cryptographic acceleration such as AES-NI (the low level interfaces do not provide the guarantee). PKCS padding works by adding B<n> padding bytes of value B<n> to make the total length of the encrypted data a multiple of the block size. Padding is always added so if the data is already a multiple of the block size B<n> will equal the block size. For example if the block size is 8 and 11 bytes are to be encrypted then 5 padding bytes of value 5 will be added. When decrypting the final block is checked to see if it has the correct form. Although the decryption operation can produce an error if padding is enabled, it is not a strong test that the input data or key is correct. A random block has better than 1 in 256 chance of being of the correct format and problems with the input data earlier on will not produce a final decrypt error. If padding is disabled then the decryption operation will always succeed if the total amount of data decrypted is a multiple of the block size. The functions EVP_EncryptInit(), EVP_EncryptFinal(), EVP_DecryptInit(), EVP_CipherInit() and EVP_CipherFinal() are obsolete but are retained for compatibility with existing code. New code should use EVP_EncryptInit_ex(), EVP_EncryptFinal_ex(), EVP_DecryptInit_ex(), EVP_DecryptFinal_ex(), EVP_CipherInit_ex() and EVP_CipherFinal_ex() because they can reuse an existing context without allocating and freeing it up on each call. =head1 BUGS For RC5 the number of rounds can currently only be set to 8, 12 or 16. This is a limitation of the current RC5 code rather than the EVP interface. EVP_MAX_KEY_LENGTH and EVP_MAX_IV_LENGTH only refer to the internal ciphers with default key lengths. If custom ciphers exceed these values the results are unpredictable. This is because it has become standard practice to define a generic key as a fixed unsigned char array containing EVP_MAX_KEY_LENGTH bytes. The ASN1 code is incomplete (and sometimes inaccurate) it has only been tested for certain common S/MIME ciphers (RC2, DES, triple DES) in CBC mode. =head1 EXAMPLES Encrypt a string using IDEA: int do_crypt(char *outfile) { unsigned char outbuf[1024]; int outlen, tmplen; /* Bogus key and IV: we'd normally set these from * another source. */ unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; unsigned char iv[] = {1,2,3,4,5,6,7,8}; char intext[] = "Some Crypto Text"; EVP_CIPHER_CTX ctx; FILE *out; EVP_CIPHER_CTX_init(&ctx); EVP_EncryptInit_ex(&ctx, EVP_idea_cbc(), NULL, key, iv); if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, intext, strlen(intext))) { /* Error */ return 0; } /* Buffer passed to EVP_EncryptFinal() must be after data just * encrypted to avoid overwriting it. */ if(!EVP_EncryptFinal_ex(&ctx, outbuf + outlen, &tmplen)) { /* Error */ return 0; } outlen += tmplen; EVP_CIPHER_CTX_cleanup(&ctx); /* Need binary mode for fopen because encrypted data is * binary data. Also cannot use strlen() on it because * it wont be null terminated and may contain embedded * nulls. */ out = fopen(outfile, "wb"); fwrite(outbuf, 1, outlen, out); fclose(out); return 1; } The ciphertext from the above example can be decrypted using the B<openssl> utility with the command line (shown on two lines for clarity): openssl idea -d <filename -K 000102030405060708090A0B0C0D0E0F -iv 0102030405060708 General encryption and decryption function example using FILE I/O and AES128 with a 128-bit key: int do_crypt(FILE *in, FILE *out, int do_encrypt) { /* Allow enough space in output buffer for additional block */ unsigned char inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH]; int inlen, outlen; EVP_CIPHER_CTX ctx; /* Bogus key and IV: we'd normally set these from * another source. */ unsigned char key[] = "0123456789abcdeF"; unsigned char iv[] = "1234567887654321"; /* Don't set key or IV right away; we want to check lengths */ EVP_CIPHER_CTX_init(&ctx); EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, NULL, NULL, do_encrypt); OPENSSL_assert(EVP_CIPHER_CTX_key_length(&ctx) == 16); OPENSSL_assert(EVP_CIPHER_CTX_iv_length(&ctx) == 16); /* Now we can set key and IV */ EVP_CipherInit_ex(&ctx, NULL, NULL, key, iv, do_encrypt); for(;;) { inlen = fread(inbuf, 1, 1024, in); if(inlen <= 0) break; if(!EVP_CipherUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) { /* Error */ EVP_CIPHER_CTX_cleanup(&ctx); return 0; } fwrite(outbuf, 1, outlen, out); } if(!EVP_CipherFinal_ex(&ctx, outbuf, &outlen)) { /* Error */ EVP_CIPHER_CTX_cleanup(&ctx); return 0; } fwrite(outbuf, 1, outlen, out); EVP_CIPHER_CTX_cleanup(&ctx); return 1; } =head1 SEE ALSO L<evp(3)|evp(3)> =head1 HISTORY EVP_CIPHER_CTX_init(), EVP_EncryptInit_ex(), EVP_EncryptFinal_ex(), EVP_DecryptInit_ex(), EVP_DecryptFinal_ex(), EVP_CipherInit_ex(), EVP_CipherFinal_ex() and EVP_CIPHER_CTX_set_padding() appeared in OpenSSL 0.9.7. IDEA appeared in OpenSSL 0.9.7 but was often disabled due to patent concerns; the last patents expired in 2012. =cut
cbargren/nodegit
vendor/openssl/openssl/doc/crypto/EVP_EncryptInit.pod
Perl
mit
24,702
package MEModeling::MEModelingClient; use JSON::RPC::Client; use POSIX; use strict; use Data::Dumper; use URI; use Bio::KBase::Exceptions; my $get_time = sub { time, 0 }; eval { require Time::HiRes; $get_time = sub { Time::HiRes::gettimeofday() }; }; use Bio::KBase::AuthToken; # Client version should match Impl version # This is a Semantic Version number, # http://semver.org our $VERSION = "0.1.0"; =head1 NAME MEModeling::MEModelingClient =head1 DESCRIPTION A KBase module: MEModeling =cut sub new { my($class, $url, @args) = @_; my $self = { client => MEModeling::MEModelingClient::RpcClient->new, url => $url, headers => [], }; chomp($self->{hostname} = `hostname`); $self->{hostname} ||= 'unknown-host'; # # Set up for propagating KBRPC_TAG and KBRPC_METADATA environment variables through # to invoked services. If these values are not set, we create a new tag # and a metadata field with basic information about the invoking script. # if ($ENV{KBRPC_TAG}) { $self->{kbrpc_tag} = $ENV{KBRPC_TAG}; } else { my ($t, $us) = &$get_time(); $us = sprintf("%06d", $us); my $ts = strftime("%Y-%m-%dT%H:%M:%S.${us}Z", gmtime $t); $self->{kbrpc_tag} = "C:$0:$self->{hostname}:$$:$ts"; } push(@{$self->{headers}}, 'Kbrpc-Tag', $self->{kbrpc_tag}); if ($ENV{KBRPC_METADATA}) { $self->{kbrpc_metadata} = $ENV{KBRPC_METADATA}; push(@{$self->{headers}}, 'Kbrpc-Metadata', $self->{kbrpc_metadata}); } if ($ENV{KBRPC_ERROR_DEST}) { $self->{kbrpc_error_dest} = $ENV{KBRPC_ERROR_DEST}; push(@{$self->{headers}}, 'Kbrpc-Errordest', $self->{kbrpc_error_dest}); } # # This module requires authentication. # # We create an auth token, passing through the arguments that we were (hopefully) given. { my $token = Bio::KBase::AuthToken->new(@args); if (!$token->error_message) { $self->{token} = $token->token; $self->{client}->{token} = $token->token; } else { # # All methods in this module require authentication. In this case, if we # don't have a token, we can't continue. # die "Authentication failed: " . $token->error_message; } } my $ua = $self->{client}->ua; my $timeout = $ENV{CDMI_TIMEOUT} || (30 * 60); $ua->timeout($timeout); bless $self, $class; # $self->_validate_version(); return $self; } =head2 build_me_model $return = $obj->build_me_model($BuildMEModelParams) =over 4 =item Parameter and return types =begin html <pre> $BuildMEModelParams is a MEModeling.BuildMEModelParams $return is a MEModeling.MEModelingResult BuildMEModelParams is a reference to a hash where the following keys are defined: model_ref has a value which is a string workspace has a value which is a string output_id has a value which is a string MEModelingResult is a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string me_model_ref has a value which is a string </pre> =end html =begin text $BuildMEModelParams is a MEModeling.BuildMEModelParams $return is a MEModeling.MEModelingResult BuildMEModelParams is a reference to a hash where the following keys are defined: model_ref has a value which is a string workspace has a value which is a string output_id has a value which is a string MEModelingResult is a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string me_model_ref has a value which is a string =end text =item Description Build a Metabolic/Expression model =back =cut sub build_me_model { my($self, @args) = @_; # Authentication: required if ((my $n = @args) != 1) { Bio::KBase::Exceptions::ArgumentValidationError->throw(error => "Invalid argument count for function build_me_model (received $n, expecting 1)"); } { my($BuildMEModelParams) = @args; my @_bad_arguments; (ref($BuildMEModelParams) eq 'HASH') or push(@_bad_arguments, "Invalid type for argument 1 \"BuildMEModelParams\" (value was \"$BuildMEModelParams\")"); if (@_bad_arguments) { my $msg = "Invalid arguments passed to build_me_model:\n" . join("", map { "\t$_\n" } @_bad_arguments); Bio::KBase::Exceptions::ArgumentValidationError->throw(error => $msg, method_name => 'build_me_model'); } } my $result = $self->{client}->call($self->{url}, $self->{headers}, { method => "MEModeling.build_me_model", params => \@args, }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw(error => $result->error_message, code => $result->content->{error}->{code}, method_name => 'build_me_model', data => $result->content->{error}->{error} # JSON::RPC::ReturnObject only supports JSONRPC 1.1 or 1.O ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw(error => "Error invoking method build_me_model", status_line => $self->{client}->status_line, method_name => 'build_me_model', ); } } sub version { my ($self) = @_; my $result = $self->{client}->call($self->{url}, $self->{headers}, { method => "MEModeling.version", params => [], }); if ($result) { if ($result->is_error) { Bio::KBase::Exceptions::JSONRPC->throw( error => $result->error_message, code => $result->content->{code}, method_name => 'build_me_model', ); } else { return wantarray ? @{$result->result} : $result->result->[0]; } } else { Bio::KBase::Exceptions::HTTP->throw( error => "Error invoking method build_me_model", status_line => $self->{client}->status_line, method_name => 'build_me_model', ); } } sub _validate_version { my ($self) = @_; my $svr_version = $self->version(); my $client_version = $VERSION; my ($cMajor, $cMinor) = split(/\./, $client_version); my ($sMajor, $sMinor) = split(/\./, $svr_version); if ($sMajor != $cMajor) { Bio::KBase::Exceptions::ClientServerIncompatible->throw( error => "Major version numbers differ.", server_version => $svr_version, client_version => $client_version ); } if ($sMinor < $cMinor) { Bio::KBase::Exceptions::ClientServerIncompatible->throw( error => "Client minor version greater than Server minor version.", server_version => $svr_version, client_version => $client_version ); } if ($sMinor > $cMinor) { warn "New client version available for MEModeling::MEModelingClient\n"; } if ($sMajor == 0) { warn "MEModeling::MEModelingClient version is $svr_version. API subject to change.\n"; } } =head1 TYPES =head2 BuildMEModelParams =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: model_ref has a value which is a string workspace has a value which is a string output_id has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: model_ref has a value which is a string workspace has a value which is a string output_id has a value which is a string =end text =back =head2 MEModelingResult =over 4 =item Definition =begin html <pre> a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string me_model_ref has a value which is a string </pre> =end html =begin text a reference to a hash where the following keys are defined: report_name has a value which is a string report_ref has a value which is a string me_model_ref has a value which is a string =end text =back =cut package MEModeling::MEModelingClient::RpcClient; use base 'JSON::RPC::Client'; use POSIX; use strict; # # Override JSON::RPC::Client::call because it doesn't handle error returns properly. # sub call { my ($self, $uri, $headers, $obj) = @_; my $result; { if ($uri =~ /\?/) { $result = $self->_get($uri); } else { Carp::croak "not hashref." unless (ref $obj eq 'HASH'); $result = $self->_post($uri, $headers, $obj); } } my $service = $obj->{method} =~ /^system\./ if ( $obj ); $self->status_line($result->status_line); if ($result->is_success) { return unless($result->content); # notification? if ($service) { return JSON::RPC::ServiceObject->new($result, $self->json); } return JSON::RPC::ReturnObject->new($result, $self->json); } elsif ($result->content_type eq 'application/json') { return JSON::RPC::ReturnObject->new($result, $self->json); } else { return; } } sub _post { my ($self, $uri, $headers, $obj) = @_; my $json = $self->json; $obj->{version} ||= $self->{version} || '1.1'; if ($obj->{version} eq '1.0') { delete $obj->{version}; if (exists $obj->{id}) { $self->id($obj->{id}) if ($obj->{id}); # if undef, it is notification. } else { $obj->{id} = $self->id || ($self->id('JSON::RPC::Client')); } } else { # $obj->{id} = $self->id if (defined $self->id); # Assign a random number to the id if one hasn't been set $obj->{id} = (defined $self->id) ? $self->id : substr(rand(),2); } my $content = $json->encode($obj); $self->ua->post( $uri, Content_Type => $self->{content_type}, Content => $content, Accept => 'application/json', @$headers, ($self->{token} ? (Authorization => $self->{token}) : ()), ); } 1;
mdejongh/MEModeling
lib/MEModeling/MEModelingClient.pm
Perl
mit
10,039
% Q1 - maximum predicate - outputs maximum value X from list L maximum([X],X). % boundary case (X must be X) maximum([H|T], H) :- maximum(T, Y), H >= Y. % general case (highest value is H) maximum([H|T], X) :- maximum(T, X), X > H. % general case (highest value is X) % Q2 - duplicate_nth predicate - duplicates index N in L1 to output L2 duplicate_nth(1, [H|T], [H,H|T]). % boundary case (duplicate H) duplicate_nth(N, [H|T], [H|T2]) :- % general case (no duplication) N > 1, N1 is N - 1, duplicate_nth(N1, T, T2). % Q3 - semantic network inheritance instance(city, london). instance(city, lincoln). instance(town, boston). instance(cathedral, stmarys). subclass(settlement, city). subclass(settlement, town). subclass(building, cathedral). subclass(building, townhall). has(city, cathedral). has(city, townhall). has(town, townhall). has(lincoln, stmarys). has(X, Y) :- instance(C, X), has(C, Y). has(X, Y) :- instance(C, X), has(C, D), subclass(Y, D).
daleluck/Year2-AI-Assignments
Assignment 2/source.pl
Perl
mit
980
package Test::ModPerimeterX use strict; use warnings; $Test::ModPerimeterX::VERSION = '0.0.1'; 1; __END__
PerimeterX/mod_perimeterx
t/lib/Test/ModPerimeterX.pm
Perl
mit
110
# # $Header: svn://svn/SWM/trunk/web/MCache.pm 8251 2013-04-08 09:00:53Z rlee $ # package MCache; use lib ".."; use Defs; use Cache::Memcached::Fast; use strict; my %cachetypes = ( sww => 1, #Sportzware Websites swm => 2, #Sportzware Membership mem => 3, #MySport based queries that would be useful in multiple systems ls => 4, #Livestats ); sub new { my $this = shift; my $class = ref($this) || $this; my $self ={ }; if(@Defs::MemCacheServers) { $self->{'OBJ'} = new Cache::Memcached::Fast({ servers => \@Defs::MemCacheServers, }); } else { warn("No Memcache servers defined"); $self->{'OBJ'} = undef; } bless $self, $class; return $self; } sub set { #Insert/Update value into Memcache my $self = shift; my ( $type, $key, $value, $group, $expiry, ) = @_; return undef if !$self->{'OBJ'}; return undef if !$key; $value ||= ''; $group ||= ''; $expiry ||= 0; my $typeprefix =$cachetypes{$type} || ''; my $ret = $self->{'OBJ'}->set("$typeprefix~$key", $value, $expiry); if($ret and $group) { $self->_addtogroup( $type, $group, $key, ); } return $ret; } sub get { #Get value from Memcache my $self = shift; my ( $type, $key, ) = @_; return undef if !$self->{'OBJ'}; return undef if !$key; my $typeprefix =$cachetypes{$type} || ''; return $self->{'OBJ'}->get("$typeprefix~$key"); } sub delete { #Get value from Memcache my $self = shift; my ( $type, $key, ) = @_; return undef if !$self->{'OBJ'}; return undef if !$key; my $typeprefix =$cachetypes{$type} || ''; return $self->{'OBJ'}->delete("$typeprefix~$key"); } sub _addtogroup { my $self = shift; my ( $type, $group, $key, ) = @_; return undef if !$self->{'OBJ'}; my $typeprefix =$cachetypes{$type} || ''; my $groupkey = "$typeprefix~$group"; my $existingnum = $self->{'OBJ'}->get("$groupkey-0") || 0; if(!$existingnum) { $self->{'OBJ'}->set("$groupkey-0",0); } my $newnum = $self->{'OBJ'}->incr("$groupkey-0") || 0; $self->{'OBJ'}->set("$groupkey-$newnum", "$typeprefix~$key"); } sub delgroup { my $self = shift; my ( $type, $group, ) = @_; return undef if !$self->{'OBJ'}; my $typeprefix =$cachetypes{$type} || ''; my $groupkey = "$typeprefix~$group"; my @groupkeys = (); for my $i (0 .. $self->{'OBJ'}->get("$groupkey-0")) { push @groupkeys, "$groupkey-$i"; } my $groupvalues= $self->{'OBJ'}->get_multi(@groupkeys); my @groupvals = values %{$groupvalues}; $self->{'OBJ'}->delete_multi(@groupkeys); $self->{'OBJ'}->delete_multi(@groupvals); return 1; } sub stats { my $self = shift; #This is not supported by the api so we'll do it the old fashioned way use Net::Telnet (); my ($host,$port) = split/:/, $Defs::MemCacheServers[0]{'address'}; my $connection = new Net::Telnet ( Host => $host, Port => $port, Timeout => 10, ); $connection->print("stats"); my %stats= (); while(1) { my $line = $connection->getline(); chomp $line; if($line =~/END/) { $connection->close(); last; } my($k, $v) = $line =~/^STAT\s*(.*)\s+(.*)$/; $stats{$k} = $v; } return \%stats; } 1;
facascante/slimerp
fifs/web/MCache.pm
Perl
mit
3,103
package EABShortener; use 5.010; use utf8; use strict; use warnings; use threads; use Dancer ':syntax'; use Dancer::Plugin::Database; our $VERSION = '1.1'; use Data::Validate::URI 'is_uri'; use LWP::UserAgent; use HTML::TreeBuilder::Select; use URI; my $ua = LWP::UserAgent->new( timeout => 5, parse_head => 0, agent => config->{appname} . '/' . $VERSION ); if ($ENV{DATABASE_URL}) { debug "Database URL: $ENV{DATABASE_URL}"; my ($scheme, $user, $pass, $host, $port, $path) = ($ENV{DATABASE_URL} =~ m|^(\w+)://(.+?):(.+?)@(.+?):(\d+?)/(\w+)$|); my $driver = ''; if ($scheme eq 'postgres') { $driver = 'Pg'; } config->{plugins}{Database} = { driver => $driver, database => $path, host => $host, port => $port, username => $user, password => $pass, }; } my %ext_map = ( 'image/jpeg' => '.jpg', 'image/png' => '.png', 'image/gif' => '.gif', 'text/plain' => '.txt', 'text/html' => '.html', ); my @thumb_selectors = ( 'img#prodImage', # amazon single 'img#main-image', # amazon multi '#comic img', # xkcd 'img.comic', # qwantz 'table.infobox img', # wikipedia ); sub get_extension { my ($type) = @_; return $ext_map{$type} if exists $ext_map{$type}; return ''; } sub get_title { my ($type, $body) = @_; if (not defined $type) { return 'Unknown link'; } elsif ($type eq 'text/html') { if ($body =~ m|<title>(.*?)</title>|si) { my $title = $1; $title =~ s/\s+/ /g; $title =~ s/^\s+//; $title =~ s/\s+$//; $title = substr($title, 0, 99) . '…' if length($title) > 100; return $title; } else { return 'Untitled link'; } } else { return $type; } } sub get_thumb { my ($uri, $type, $body) = @_; return $uri if $type =~ m{^image/}; my $tree = HTML::TreeBuilder::Select->new_from_content($body); my $thumb; my $elem; if ($elem = $tree->look_down(_tag => 'link', rel => 'image_src')) { $thumb = $elem->attr('href'); } elsif ($elem = $tree->look_down(_tag => 'meta', name => 'twitter:image')) { $thumb = $elem->attr('value'); } elsif ($elem = $tree->look_down(_tag => 'meta', property => 'og:image')) { $thumb = $elem->attr('content'); } else { foreach (@thumb_selectors) { if ($elem = $tree->select($_)) { $thumb = $elem->attr('src'); last; } } } $tree->delete; return URI->new_abs($thumb, $uri)->as_string if $thumb; return undef; } sub get_links { my $after = param('a'); my $before = param('b'); my $query = param('q'); my $user = param('u'); my $number = param('n') || 25; my $opts = { order_by => { desc => 'created' }, limit => $number, }; my $where = {}; $where->{title} = { like => "%$query%" } if $query; $where->{user} = $user if $user; $where->{created}{gt} = $after if $after; $where->{created}{lt} = $before if $before; return [ database->quick_select('links', $where, $opts) ]; } my @chars = split //, 'abcdefghijklmnopqrstuvwxyz0123456789'; post '/' => sub { content_type 'application/json'; my $uri = param('uri'); $uri = "http://$uri" unless $uri =~ m{^[a-z]+://}i; if (is_uri($uri)) { my $token = join '', map $chars[ int(rand(@chars)) ], 1 .. 6; my $resp = $ua->get($uri); if ($resp->is_success) { (my $type = $resp->header('Content-Type')) =~ s/;.*$//; $token .= get_extension($type); my $title = get_title($type, $resp->decoded_content); my $thumb = get_thumb($uri, $type, $resp->decoded_content); my $author = substr(param('user'), 0, 50) || 'Some asshole'; database->quick_insert( links => { token => $token, uri => $uri, title => $title, user => $author, created => time, thumb => $thumb, }); async { if (defined $ENV{SLACK_HOOK_URL}) { $ua->post( $ENV{SLACK_HOOK_URL}, { payload => qq{ { "text": "$title <http://eab.so/$token> ($author)", "username": "eab.so", "icon_emoji": ":bricky:" } }, }); } } ->detach(); return to_json { result => "http://eab.so/$token" }; } else { return to_json { error => $resp->status_line }; } } else { return to_json { error => 'invalid uri' }; } }; get '/' => sub { template 'links', { links => get_links }; }; get '/json' => sub { content_type 'application/json'; to_json get_links; }; get '/rss' => sub { content_type 'text/xml'; template 'rss', { links => get_links }, { layout => undef }; }; get '/crx' => sub { redirect 'https://chrome.google.com/webstore/detail/cdjnlghjdbiambiakngkffonbaeoikcn'; }; any '/new.pl' => sub { content_type 'application/json'; return to_json { error => 'update extension' }; }; get '/:token' => sub { my $link = database->quick_select(links => { token => param('token') }); if ($link) { redirect $link->{uri}; } else { status 'not_found'; template '404'; } }; any qr{.*} => sub { status 'not_found'; template '404'; }; true;
bentglasstube/eabso-shortener
lib/EABShortener.pm
Perl
mit
5,316
package Hadouken::Plugin::IMDB; use strict; use warnings; use Hadouken ':acl_modes'; use TryCatch; #use Data::Dumper; use IMDB::Film; our $VERSION = '0.2'; our $AUTHOR = 'dek'; # Description of this command. sub command_comment { my $self = shift; return "Perform IMDb search."; } # Clean name of command. sub command_name { my $self = shift; return "imdb"; } sub command_regex { my $self = shift; return 'imdb\s.+?'; } # Return 1 if OK. # 0 if does not pass ACL. sub acl_check { my ( $self, %aclentry ) = @_; my $permissions = $aclentry{'permissions'}; #if($self->check_acl_bit($permissions, Hadouken::BIT_ADMIN) # || $self->check_acl_bit($permissions, Hadouken::BIT_WHITELIST) # || $self->check_acl_bit($permissions, Hadouken::BIT_OP)) { # # return 1; #} if ( $self->check_acl_bit( $permissions, Hadouken::BIT_BLACKLIST ) ) { return 0; } return 1; } ## ---------- end sub acl_check # Return 1 if OK (and then callback can be called) # Return 0 and the callback will not be called. sub command_run { my ( $self, $nick, $host, $message, $channel, $is_admin, $is_whitelisted ) = @_; my ( $cmd, $arg ) = split( / /, $message, 2 ); # DO NOT LC THE MESSAGE! return unless defined $arg; my $summary = ''; my $title = $arg; try { my $imdb = new IMDB::Film( crit => $title ); #, search => 'find?tt=on;mx=20;q='); # Try searching if we do not get a result. unless ( $imdb->status ) { $imdb = new IMDB::Film( crit => $title, search => 'find?tt=on;mx=20;q=' ); } if ( $imdb->status ) { $summary = "[imdb] " . $imdb->title() . " "; $summary .= "(" . $imdb->year() . ") - " if defined $imdb->year && length $imdb->year; if ( defined $imdb->rating && length $imdb->rating ) { my $rating = $imdb->rating(); $rating =~ s/\.?0*$//; $summary .= $rating . "/10 - "; } my $storyline = $imdb->storyline(); $storyline =~ s/Plot Summary \| Add Synopsis//; $summary .= "http://www.imdb.com/title/tt" . $imdb->code . "/"; $self->send_server( PRIVMSG => $channel, $summary ); # Wrap the summary, might be big. my $wrapped; ( $wrapped = $storyline ) =~ s/(.{0,300}(?:\s|$))/$1\n/g; my @lines = split( /\n/, $wrapped ); my $cnt = 0; foreach my $l (@lines) { next unless defined $l && length $l; next if $l eq 'Add Full Plot | Add Synopsis'; $cnt++; $self->send_server( PRIVMSG => $channel, $cnt > 1 ? $l : "Summary - $l" ); } } else { # warn "Something wrong: ".$imdb->error; #warn Dumper($imdb); } } catch ($e) { $summary = ''; } return 1; } ## ---------- end sub command_run 1; __END__ =pod =encoding UTF-8 =head1 NAME Hadouken::Plugin::IMDB - IMDb plugin. =head1 DESCRIPTION IMDb plugin for Hadouken. =head1 AUTHOR dek <dek@whilefalsedo.com> =cut
gitdek/hadouken
bin/plugins/IMDB.pm
Perl
mit
3,317
#!/usr/bin/perl #/home/tbooth/scripts/make_package_list.perl - created Tue Aug 13 14:13:48 BST 2013 use strict; use warnings; use Data::Dumper; # Currently, the /home/manager/package_scripts/update_repository script on Envgen # makes a list of packages for the website. This is very incomplete and # is missing versions. How to fix it? # 1) Look at ~/sandbox/bl7_things/bl_master_package_list.txt # (trim anything after a space) # But this has loads of system crud in, and will miss new stuff added to # launchpad. Maybe just search for "Science"? # 2) Grab list from Launchpad. This gets a few bits of crud but we can # blacklist. # 3) Grab from Envgen as before. If anything has 'bl' in the version then # add all dependencies that are in section "Science", else chop name. # # OK, that's complicated. Let's give it a whirl. my @master_package_list; my @lp_package_list; my @envgen_package_list; my @dep_package_list; my @blacklist = qw( arb-common estscan libarb prot4est *-all *-data *-data-* *-examples *-test ); my %pkgs; #For the final result. # 1 @master_package_list = wgrab("http://nebc.nerc.ac.uk/downloads/bl7_only/bl_master_package_list.txt"); map { s/ .*// } @master_package_list; @lp_package_list = wgrab("http://ppa.launchpad.net/nebc/bio-linux/ubuntu/dists/precise/main/binary-amd64/Packages.bz2"); @envgen_package_list = wgrab("http://nebc.nerc.ac.uk/bio-linux/dists/unstable/bio-linux/binary-amd64/Packages.gz"); MPL: for(@master_package_list) { chomp; #Skip bio-linux- packages at this stage. /^bio-linux-/ && next; my @showlines = `apt-cache show $_`; my %showinfo; for(@showlines) { chomp; #Only get the first bit. $_ eq '' and last; /^([A-Za-z-]+): ?(.*)/ or next; $showinfo{$1} = $2; } for($showinfo{Section}) { $_ or die "No info found - maybe this machine doesn't have the right sources configured?\n", "HINT- this script won't work on Envgen, it needs to be run on a BL machine.\n", Dumper(\%showinfo); /(?:^|\/)science/ or /(?:^|\/)gnu-r/ or next MPL; } my $item = $pkgs{$_} = []; $item->[0] = $showinfo{Version} || "unknown"; $item->[1] = $showinfo{Description} || $showinfo{"Description-en"} || "No description"; } # 2 push @lp_package_list, ''; my %showinfo; LPL: for(@lp_package_list) { chomp; if($_ eq '' and %showinfo) { for($showinfo{Section}) { /(?:^|\/)science/ or /(?:^|\/)gnu-r/ or next LPL; } $showinfo{Package} or die Dumper(\%showinfo); my $item = $pkgs{$showinfo{Package}} = []; $item->[0] = $showinfo{Version} || "unknown"; $item->[1] = $showinfo{Description} || $showinfo{"Description-en"} || "No description"; %showinfo = (); next; } /^([A-Za-z-]+): ?(.*)/ or next; $showinfo{$1} = $2; } # 3 my $lastfield = ''; push @envgen_package_list, ''; %showinfo = (); EPL: for(@envgen_package_list) { chomp; if($_ eq '' and %showinfo) { for($showinfo{Package}) { $_ or die Dumper(\%showinfo); #Skip non bio-linux- stuff for now /^bio-linux-(.+)/ or next EPL; $showinfo{Pkg} = $1; } #If this is a wrapper, add all deps in Science. Else add the package. for($showinfo{Version}) { if(/bl/ or $pkgs{$showinfo{Pkg}}) { for(split(/[,|]/, $showinfo{Depends} || '')) { s/\(.*//; s/\s+$//; s/^\s+//; push @dep_package_list, $_ if $_ and ( ! /^bio-linux-/) ; } } else { my $item = $pkgs{$showinfo{Pkg}} = []; $item->[0] = $showinfo{Version} || "unknown"; $item->[1] = $showinfo{Description} || $showinfo{"Description-en"} || "No description"; } } %showinfo = (); $lastfield = ''; next EPL; } if(/^([A-Za-z-]+): ?(.*)/) { $lastfield = $1; $showinfo{$1} = $2; } elsif($lastfield eq 'Depends') { $showinfo{Depends} .= $_; } } DPL: for(@dep_package_list) { chomp; #Skip repeats $pkgs{$_} and next; my @showlines = `apt-cache show $_`; my %showinfo; #Some deps are not available. next unless @showlines; for(@showlines) { chomp; #Only get the first bit. $_ eq '' and last; /^([A-Za-z-]+): ?(.*)/ or next; $showinfo{$1} = $2; } if(!$showinfo{Section}){ die Dumper $_, \@showlines, \%showinfo } for($showinfo{Section}) { /(?:^|\/)science/ or /(?:^|\/)gnu-r/ or next DPL; } my $item = $pkgs{$_} = []; $item->[0] = $showinfo{Version} || "unknown"; $item->[1] = $showinfo{Description} || $showinfo{"Description-en"} || "No description"; } # OK, that should have hoovered up everything. Now just dump it out. for(sort keys(%pkgs)) { next if contains_glob( \@blacklist, $_ ); #Prune -rev off version $pkgs{$_}->[0] =~ s/(.*)-.*/$1/; print "$_\t$pkgs{$_}->[0]\t$pkgs{$_}->[1]\n"; } sub contains_glob { my ( $list, $item ) = @_; for( @$list ) { my $match = $_; $match =~ s/\./\\./g; $match =~ s/\*/.*/g; $match =~ s/\?/./g; return 1 if $item =~ /^$match$/; } return 0; } sub contains { use integer; #Check membership in a sorted list? Pointless to re-implement but I'm feeling this way out. #Actually, I never use it anyway. Oh well. my ( $list, $item ) = @_; my $top = @$list; my $bot = 0; while( $top > $bot ) { my $idx = $bot + (($top - $bot) / 2); my $cmp = $list->[$idx] cmp $item; if( !$cmp ) { return \$list->[$idx] } elsif( $cmp == 1 ) { $bot = $idx + 1 } else { $top = $idx } } return undef; } sub wgrab { require HTTP::Request; require LWP::UserAgent; my $r = HTTP::Request->new(GET => $_[0]); my $ua = LWP::UserAgent->new( env_proxy => 1 ); my $res = $ua->request($r); $res->is_success or die $res->status_line; #If encoding is GZip or BZip2 then unpack it. my $dc; for($res->headers->{"content-type"}) { /\/x-gzip$/ and $dc = unz($res->content), last; /\/x-bzip2$/ and $dc = unbz2($res->content), last; $dc = $res->decoded_content; } split("\n", $dc); } #Naive decompression routines. sub unz { require IO::Uncompress::Gunzip; my $buf; IO::Uncompress::Gunzip::gunzip(\$_[0] => \$buf, Transparent => 0); $buf; } sub unbz2 { require IO::Uncompress::Bunzip2; my $buf; IO::Uncompress::Bunzip2::bunzip2(\$_[0] => \$buf, Transparent => 0); $buf; }
environmentalomics/build-bio-linux
package_scripts/make_package_list.perl
Perl
mit
6,398
=pod =head1 NAME i2d_ECPrivateKey, d2i_ECPrivate_key - Encode and decode functions for saving and reading EC_KEY structures =head1 SYNOPSIS #include <openssl/ec.h> EC_KEY *d2i_ECPrivateKey(EC_KEY **key, const unsigned char **in, long len); int i2d_ECPrivateKey(EC_KEY *key, unsigned char **out); unsigned int EC_KEY_get_enc_flags(const EC_KEY *key); void EC_KEY_set_enc_flags(EC_KEY *eckey, unsigned int flags); =head1 DESCRIPTION The ECPrivateKey encode and decode routines encode and parse an B<EC_KEY> structure into a binary format (ASN.1 DER) and back again. These functions are similar to the d2i_X509() functions, and you should refer to that page for a detailed description (see L<d2i_X509(3)>). The format of the external representation of the public key written by i2d_ECPrivateKey (such as whether it is stored in a compressed form or not) is described by the point_conversion_form. See L<EC_GROUP_copy(3)> for a description of point_conversion_form. When reading a private key encoded without an associated public key (e.g. if EC_PKEY_NO_PUBKEY has been used - see below), then d2i_ECPrivateKey generates the missing public key automatically. Private keys encoded without parameters (e.g. if EC_PKEY_NO_PARAMETERS has been used - see below) cannot be loaded using d2i_ECPrivateKey. The functions EC_KEY_get_enc_flags and EC_KEY_set_enc_flags get and set the value of the encoding flags for the B<key>. There are two encoding flags currently defined - EC_PKEY_NO_PARAMETERS and EC_PKEY_NO_PUBKEY. These flags define the behaviour of how the B<key> is converted into ASN1 in a call to i2d_ECPrivateKey. If EC_PKEY_NO_PARAMETERS is set then the public parameters for the curve are not encoded along with the private key. If EC_PKEY_NO_PUBKEY is set then the public key is not encoded along with the private key. =head1 RETURN VALUES d2i_ECPrivateKey() returns a valid B<EC_KEY> structure or B<NULL> if an error occurs. The error code that can be obtained by L<ERR_get_error(3)>. i2d_ECPrivateKey() returns the number of bytes successfully encoded or a negative value if an error occurs. The error code can be obtained by L<ERR_get_error(3)>. EC_KEY_get_enc_flags returns the value of the current encoding flags for the EC_KEY. =head1 SEE ALSO L<crypto(3)>, L<ec(3)>, L<EC_GROUP_new(3)>, L<EC_GROUP_copy(3)>, L<EC_POINT_new(3)>, L<EC_POINT_add(3)>, L<EC_GFp_simple_method(3)>, L<d2i_ECPKParameters(3)>, L<d2i_ECPrivateKey(3)> =cut
vbloodv/blood
extern/openssl.orig/doc/crypto/d2i_ECPrivateKey.pod
Perl
mit
2,465
package WebService::Slack::WebApi::Generator; use strict; use warnings; use utf8; use feature qw/state/; sub import { my ($class, %rules) = @_; my $caller = caller; while (my ($method_name, $rule) = each %rules) { (my $path = $method_name) =~ s/_([a-z])/\u$1/g; my $method = sprintf '%s::%s', $caller, $method_name; no strict 'refs'; *$method = sub { state $v = Data::Validator->new(%$rule)->with('Method', 'AllowExtra'); my ($self, $args, %extra) = $v->validate(@_); return $self->request($path, {%$args, %extra}); }; } } 1;
mihyaeru21/p5-WebService-Slack-WebApi
lib/WebService/Slack/WebApi/Generator.pm
Perl
mit
623
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 12.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. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V824 0 567 592 856 861 880 884 886 890 891 894 895 900 907 908 909 910 930 931 975 976 1020 1024 1159 1160 1231 1232 1270 1272 1274 1280 1296 1329 1367 1369 1376 1377 1416 1417 1419 1425 1442 1443 1466 1467 1477 1488 1515 1520 1525 1536 1540 1548 1558 1563 1564 1567 1568 1569 1595 1600 1625 1632 1806 1807 1867 1869 1872 1920 1970 2305 2362 2364 2382 2384 2389 2392 2417 2433 2436 2437 2445 2447 2449 2451 2473 2474 2481 2482 2483 2486 2490 2492 2501 2503 2505 2507 2510 2519 2520 2524 2526 2527 2532 2534 2555 2561 2564 2565 2571 2575 2577 2579 2601 2602 2609 2610 2612 2613 2615 2616 2618 2620 2621 2622 2627 2631 2633 2635 2638 2649 2653 2654 2655 2662 2677 2689 2692 2693 2702 2703 2706 2707 2729 2730 2737 2738 2740 2741 2746 2748 2758 2759 2762 2763 2766 2768 2769 2784 2788 2790 2800 2801 2802 2817 2820 2821 2829 2831 2833 2835 2857 2858 2865 2866 2868 2869 2874 2876 2884 2887 2889 2891 2894 2902 2904 2908 2910 2911 2914 2918 2930 2946 2948 2949 2955 2958 2961 2962 2966 2969 2971 2972 2973 2974 2976 2979 2981 2984 2987 2990 2998 2999 3002 3006 3011 3014 3017 3018 3022 3031 3032 3047 3067 3073 3076 3077 3085 3086 3089 3090 3113 3114 3124 3125 3130 3134 3141 3142 3145 3146 3150 3157 3159 3168 3170 3174 3184 3202 3204 3205 3213 3214 3217 3218 3241 3242 3252 3253 3258 3260 3269 3270 3273 3274 3278 3285 3287 3294 3295 3296 3298 3302 3312 3330 3332 3333 3341 3342 3345 3346 3369 3370 3386 3390 3396 3398 3401 3402 3406 3415 3416 3424 3426 3430 3440 3458 3460 3461 3479 3482 3506 3507 3516 3517 3518 3520 3527 3530 3531 3535 3541 3542 3543 3544 3552 3570 3573 3585 3643 3647 3676 3713 3715 3716 3717 3719 3721 3722 3723 3725 3726 3732 3736 3737 3744 3745 3748 3749 3750 3751 3752 3754 3756 3757 3770 3771 3774 3776 3781 3782 3783 3784 3790 3792 3802 3804 3806 3840 3912 3913 3947 3953 3980 3984 3992 3993 4029 4030 4045 4047 4048 4096 4130 4131 4136 4137 4139 4140 4147 4150 4154 4160 4186 4256 4294 4304 4345 4347 4348 4352 4442 4447 4515 4520 4602 4608 4615 4616 4679 4680 4681 4682 4686 4688 4695 4696 4697 4698 4702 4704 4743 4744 4745 4746 4750 4752 4783 4784 4785 4786 4790 4792 4799 4800 4801 4802 4806 4808 4815 4816 4823 4824 4847 4848 4879 4880 4881 4882 4886 4888 4895 4896 4935 4936 4955 4961 4989 5024 5109 5121 5751 5760 5789 5792 5873 5888 5901 5902 5909 5920 5943 5952 5972 5984 5997 5998 6001 6002 6004 6016 6110 6112 6122 6128 6138 6144 6159 6160 6170 6176 6264 6272 6314 6400 6429 6432 6444 6448 6460 6464 6465 6468 6510 6512 6517 6624 6656 7424 7532 7680 7836 7840 7930 7936 7958 7960 7966 7968 8006 8008 8014 8016 8024 8025 8026 8027 8028 8029 8030 8031 8062 8064 8117 8118 8133 8134 8148 8150 8156 8157 8176 8178 8181 8182 8191 8192 8277 8279 8280 8287 8292 8298 8306 8308 8335 8352 8370 8400 8427 8448 8508 8509 8524 8531 8580 8592 9169 9216 9255 9280 9291 9312 9752 9753 9854 9856 9874 9888 9890 9985 9989 9990 9994 9996 10024 10025 10060 10061 10062 10063 10067 10070 10071 10072 10079 10081 10133 10136 10160 10161 10175 10192 10220 10224 11022 11904 11930 11931 12020 12032 12246 12272 12284 12288 12352 12353 12439 12441 12544 12549 12589 12593 12687 12688 12728 12784 12831 12832 12868 12880 12926 12927 13055 13056 19894 19904 40870 40960 42125 42128 42183 44032 55204 55296 64046 64048 64107 64256 64263 64275 64280 64285 64311 64312 64317 64318 64319 64320 64322 64323 64325 64326 64434 64467 64832 64848 64912 64914 64968 64976 65022 65024 65040 65056 65060 65072 65107 65108 65127 65128 65132 65136 65141 65142 65277 65279 65280 65281 65471 65474 65480 65482 65488 65490 65496 65498 65501 65504 65511 65512 65519 65529 65548 65549 65575 65576 65595 65596 65598 65599 65614 65616 65630 65664 65787 65792 65795 65799 65844 65847 65856 66304 66335 66336 66340 66352 66379 66432 66462 66463 66464 66560 66718 66720 66730 67584 67590 67592 67593 67594 67638 67639 67641 67644 67645 67647 67648 118784 119030 119040 119079 119082 119262 119552 119639 119808 119893 119894 119965 119966 119968 119970 119971 119973 119975 119977 119981 119982 119994 119995 119996 119997 120004 120005 120070 120071 120075 120077 120085 120086 120093 120094 120122 120123 120127 120128 120133 120134 120135 120138 120145 120146 120484 120488 120778 120782 120832 131070 173783 194560 195102 196606 196608 262142 262144 327678 327680 393214 393216 458750 458752 524286 524288 589822 589824 655358 655360 720894 720896 786430 786432 851966 851968 917502 917504 917505 917506 917536 917632 917760 918000 983038 1114112 END
operepo/ope
client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/In/4_0.pl
Perl
mit
4,925
hasShape(X,user) :- node(X), nodeShape(X,knows,user), cardinality(X,knows,1,star). noHasShape(X,user):- node(X), not nodeShape(X,knows,user) . noHasShape(X,user):- node(X), not cardinality(X,knows,1,star) . cardinality(X,P,Min,star):- integer(Min), countProperty(X,P,C), Min <= C . cardinality(X,P,Min,Max):- integer(Min), integer(Max), countProperty(X,P,C), Min <= C, C <= Max . #show nodeShape/3 . nodeShape(X,P,S):- countShapeProperty(X,P,S,CS), countProperty(X,P,C), C = CS . #show countProperty/3 . countProperty(X,P,C):- node(X), property(P), C = #count { V: arc(X,P,V) } . #show countShapeProperty/4 . countShapeProperty(X,P,S,C):- node(X), property(P), shape(S), C = #count { 1: shapeValue(X,P,S) } . #show shapeValue/3 . shapeValue(X,P,S):- shape(S), arc(X,P,V), hasShape(V,S) . hasShape(X,A) | not hasShape(X,A) :- node(X), shape(A) . -hasShape(X,S) :- noHasShape(X,S). integerAge(X,A) :- arc(X,age,A), integer(A) . % arc(alice,age,12) . % arc(alice,name,"Alice"). arc(alice,knows,alice). arc(bob,knows,carol). -hasShape(carol,user). % Domain declarations... integer(0..100). string("Alice";"Bob";"Carol") . node(alice;bob;carol). property(knows). shape(user). #show hasShape/2 . #show noHasShape/2 .
labra/asptests
ACorunnaWorkshop/count.pl
Perl
mit
1,370
:- module(detlogentypes,[ denotes_a/1, denotes_v/1, 'denotes_.'/3, 'denotes_[]'/1]). denotes_a([static]). 'denotes_.'(_,[list,nonvar],[list,nonvar]). 'denotes_.'(_,[var],[nonvar]). 'denotes_.'(_,[nonvar],[nonvar]). 'denotes_.'([list,static],[list,static],[list,static]). 'denotes_.'([list,nonvar],[list,static],[list,nonvar]). 'denotes_.'([list,nonvar],[static],[nonvar]). 'denotes_.'([list,static],[static],[static]). 'denotes_.'([nonvar],[list,static],[list,nonvar]). 'denotes_.'([nonvar],[static],[nonvar]). 'denotes_.'([static],[list,static],[list,static]). 'denotes_.'([static],[static],[static]). 'denotes_.'([var],[list,static],[list,nonvar]). 'denotes_.'([var],[static],[nonvar]). 'denotes_[]'([list,static]). denotes_v([var]).
leuschel/logen
old_logen/filter_prop/detlogentypes.pl
Perl
apache-2.0
743
#!/usr/bin/env perl # 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. =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 <helpdesk.org>. =cut use strict; use Getopt::Long; my ($start, $end, $chr, $output_dir, $input_dir, $target_file, $run, $parse, $split, $rerun, $ssahabuild, $ssaha2); GetOptions('start=i' => \$start, 'end=i' => \$end, 'output_dir=s' => \$output_dir, 'input_dir=s' => \$input_dir, 'target_file=s' => \$target_file, 'run' => \$run, 'parse' => \$parse, 'ssahabuild=s' => \$ssahabuild, # location of ssahaBuild binary 'ssaha2=s' => \$ssaha2, # location of ssaha2 binary 'split' => \$split, #option to split reads in groups to reduce run time 'rerun=i' => \$rerun, #to rerun it if some jobs failed i is the split start number ); $output_dir ||="."; my $seed; ###kmer is always set to 12, so ajust seed for different species $seed = 2 if $input_dir =~ /zfish/; my $skip = 3; ##if input from array, this is short sequence, run it in turing (big mem) or use exonerate(small memory 1024 MB) ##[exonerate_bin_dir]/exonerate-1.4.0 --query [ssaha_input_dir]/1_query_seq --target [blast_db_dir]/softmasked_dusted.fa --showalignment no --showvulgar yes ##nathan's affy array parameters to ensure one mismatch : --bestn 100 --dnahspthreshold 116 --fsmmemory 256 --dnawordlen 25 --dnawordthreshold 11 ##my affy parameters to ensure full match : [exonerate_bin_dir]/exonerate-1.4.0 --query [ssaha_input_dir]/1_query_seq --target [blast_db_dir]/softmasked_dusted.fa --showalignment yes --showvulgar no --ryo "vulgar: %S %V %pi\n" --dnahspthreshold 156 ##dnahspthreshold 116 for 25 mer 156 for 33 mer for exact match test it for each run $seed = "2 -kmer 6 -ckmer 6 -cmatch 10 -tags 1 -score 12 -skip 1 -sense 1" if $input_dir =~ /array/; $seed = 5 if $input_dir !~ /zfish|array/; print "seed is $seed\n"; my $output_file = "ssaha2_output"; my $queue_long = "-q long -M10000000 -R'select[mem>10000] rusage[mem=10000]'";## for watson reads my $queue_normal = "-q normal -M6000000 -R'select[mem>6000] rusage[mem=6000]'"; ##for new farm abi reads #my $queue = $queue_long; my $queue = $queue_normal; my (@chr_names, %snp_pos, %input_length, %done); run_ssaha2() if $run; parse_ssaha2() if $parse; sub run_ssaha2 { my ($subj_dir,$tar_file) = $target_file =~ /^(.*)\/(.*)$/; my ($subname) = $tar_file =~ /^(.*)\.*.*$/; my $subject = "$subj_dir/$subname"; print "tar_file is $tar_file and subject is $subject and target_file is $target_file\n"; if (! -f "$subject\.body") { print "Submitting ssaha2Build job...\n"; my $ssaha2build = "bsub $queue_long -J 'ssaha2build' -o $target_file\_out $ssahabuild -kmer 12 -skip $skip -save $subject $target_file"; system("$ssaha2build"); my $call = "bsub -q normal -K -w 'done('ssaha2build')' -J waiting_process sleep 1"; #waits until all variation features have finished to continue system($call); } if ($start and $end) { #input name will change to \\\$LSB_JOBINDEX\_query_seq for flanking sequence mapping #my $input = "$input_dir/Watson_\\\$LSB_JOBINDEX\.fastq" if $input_dir; my $input = "$input_dir/\\\$LSB_JOBINDEX\.query_seq" if $input_dir;#need a dot in input, not a '_' after LSB_JOBINDEX #next if (-z "$input"); print "input is $input and split $split\n"; if (! $split) {#mainly for flanking_sequence mapping print "Submitting ssaha2 job array...\n"; bsub_ssaha_job_array($start,$end,$input,$queue,$target_file); } else { my $input; my @files = glob("$input_dir/*fastq") ; #mainly for sequencing reads $input = $files[0]; my ($input_file) = $input =~ /^.*\/(.*)$/; my $num = `grep "^\@" $input |grep -v -c "[?%*]"`; $num =~ s/^\s+|\s+$//g; print "number of sequence entries in file is $num \n"; my $n; #my $size = $num;#this is run whole file in one go my $size = 50000; #this is to split file in this size my $count; $input = "$input_dir/Watson_\\\$LSB_JOBINDEX\.fastq"; if (!$rerun) { for ($n = 1;$n<=$num;$n+=$size) { my $e = $n+$size-1; $e = $num if ($e > $num); $count++; if (! -e "$output_dir/ssaha_out_$input_file\:$n") { #check for ssaha2_output is exists or not print "Submitting ssaha2 job $count ...\n"; bsub_ssaha_job ($start,$end,$n,$e,$queue,$input,$target_file); } } } else { $n = $rerun; my $e = $n+$size-1; $e = $num if ($e > $num); bsub_ssaha_job ($start,$end,$n,$e,$queue,$input,$target_file); } } } } my $call = "bsub -K -w 'done(ssaha_out*)' -J waiting_process sleep 1"; #waits until all ssaha jobs have finished to continue #system($call); sub parse_ssaha2 { foreach my $num ($start..$end) { my $input = "$input_dir/$num\.query_seq" if $input_dir; my $out_file = "$output_dir/ssaha.$num\.out"; print "input is $input and out_file is $out_file\n"; next if (-z "$out_file"); parse_ssaha2_out ($num, $input,"$out_file"); } } sub bsub_ssaha_job_array { my ($start,$end, $input_file, $queue, $target_file) = @_ ; my ($subj_dir,$tar_file) = $target_file =~ /^(.*)\/(.*)$/; my ($subname) = $tar_file =~ /^(.*)\.*.*$/; my $subject = "$subj_dir/$subname"; #for 454 reads #my $ssaha_command = "$ssaha2 -rtype 454 -best 1 -output cigar -name -save $subject $input_file"; #for watson for comparison #my $ssaha_command = "$ssaha2 -seeds 5 -cut 5000 -memory 300 -best 1 -output cigar -name -save $subject $input_file"; #for normal flanking mapping my $ssaha_command = "$ssaha2 -align 0 -kmer 12 -skip $skip -seeds $seed -cut 5000 -output vulgar -depth 5 -best 1 -tags 1 -name -save $subject $input_file"; my $call = "bsub -J'ssaha_out_[$start-$end]%50' $queue -e $output_dir/ssaha.%I.err -o $output_dir/ssaha.%I.out "; $call .= " $ssaha_command"; print "$call\n"; system ($call); } sub bsub_ssaha_job { my ($start, $end, $n, $e, $queue, $input_file, $target_file) = @_ ; my ($subj_dir,$tar_file) = $target_file =~ /^(.*)\/(.*)$/; my ($subname) = $tar_file =~ /^(.*)\.*.*$/; my $subject = "$subj_dir/$subname"; my ($ssaha_command, $count); print "target_file is $target_file\n"; #for normal mapping with long sequence (more than 2 kb) #$ssaha_command = "$ssaha2 -align 0 -kmer 12 -seeds $seed -cut 5000 -output vulgar -depth 5 -best 1 -tags 1 -save $subject $input_file"; #for abi reads #$ssaha_command = "$ssaha2 -start $n -end $end -seeds 5 -score 250 -tags 1 -best 1 -output cigar -name -memory 300 -cut 5000 -save $subject $input_file"; #for 454 reads -454 = "-skip 5 -seeds 2 -score 30 -sense 1 -cmatch 10 -ckmer 6" (use skip 5 instead of skip 3 to save memory) $ssaha_command = "$ssaha2 -start $n -end $e -skip 5 -seeds 2 -score 30 -sense 1 -cmatch 10 -ckmer 6 -best 1 -output cigar -name -save $subject $input_file"; #for watson reads #$ssaha_command = "$ssaha2 -start $n -end $e -seeds 5 -cut 5000 -memory 300 -best 1 -output cigar -name -save $subject $input_file"; #for sam output #$ssaha_command = "$ssaha2 -start $n -end $end -seeds 15 -score 250 -tags 1 -best 1 -output sam -name -memory 300 -cut 5000 -save $subject $input_file"; print "job_num is ", ++$count, " and start is $start and out is ssaha_out_$start\n"; #my $call = "bsub -J $input_dir\_ssaha_job_$start $queue -e $output_dir/error_ssaha_$start -o $output_dir/ssaha_out_$start "; my $call = "bsub -J'ssaha_out_[$start-$end]%50' $queue -e $output_dir/ssaha.%I:$n.err -o $output_dir/ssaha.%I:$n.out "; $call .= " $ssaha_command"; system ($call); print "$call\n"; } sub parse_ssaha2_out { my ($start, $input_file, $ssaha2_output) = @_; print "input_file is $input_file ssaha2_output is $ssaha2_output\n"; open INPUT, "$input_file" or die "can't open $input_file : $!\n"; open OUT, ">$output_dir/mapping_file_$start" or die "can't open output_file : $!\n"; open OUT1, ">$output_dir/out_mapping_$start" or die "can't open out_mapping file : $!\n"; my ($name,%rec_seq,%rec_find); while (<INPUT>) { if (/^\>/) { s/^\>|\n//g; $name = $_; } else { s/\n//; $rec_seq{$name} .= $_; } } foreach my $name (keys %rec_seq) { my ($fseq,$lseq) = split /[W\-\_]+/,$rec_seq{$name}; my $snp_posf = length($fseq)+1; my $snp_posl = length($lseq)+1; #my $tot_length = $snp_posf + $snp_posl-2; my $tot_length = length($rec_seq{$name}); $snp_pos{$name} = "$snp_posf\_$snp_posl"; $snp_pos{$name} = "$snp_posf\_$snp_posl"; $input_length{$name} = $tot_length; #print "$name: ".$snp_pos{$name}.' > '.$rec_seq{$name}."\n"; } open SSAHA, "$ssaha2_output" or die "can't open $output_file : $!\n"; open MAP, ">>$output_dir/THREE_MAPPINGS"; while (<SSAHA>) { #print ; if (/^vulgar\:\s+(\S+)\s+(\d+)\s+(\d+)\s+(\+|\-)\s+(\S+)\s+(\d+)\s+(\d+)\s+(\+|\-)\s+(\d+)\s+(.*)$/) { #print "q_id is $1 and q_start is $2 and q_end is $3 and q_strand is $4 and t_id is $5 and t_start is $6 and t_end is $7 and t_strand is $8 and score is $9 and match is $10\n"; #next unless $1 eq "rs31190187"; my $h={}; $h->{'q_id'} = $1; $h->{'q_start'} = $2; $h->{'q_end'} = $3; $h->{'q_strand'} = $4; $h->{'t_id'} = $5; $h->{'t_start'} = $6; $h->{'t_end'} = $7; $h->{'t_strand'} = $8; $h->{'score'} = $9; $h->{'match'} = $10; push @{$rec_find{$h->{'q_id'}}}, $h if $h->{'q_id'}; } } foreach my $q_id (keys %rec_find) { my @h = sort {$b->{'score'}<=>$a->{'score'}} @{$rec_find{$q_id}}; #print "There are ",scalar @h," hits and q_id is $q_id\n"; # Get rid of mappings that score less than the best scoring mapping my @mappings = grep {$_->{'score'} == $h[0]->{'score'}} @h; find_results(@mappings); # Comment out the old code checking number of mappings etc. This should be done by the post-processing scripts =head if (scalar @h==1) { find_results($h[0]); } elsif ($h[0]->{'score'} > $h[1]->{'score'} and @h=>2) { find_results($h[0]); } elsif ($h[0]->{'score'} == $h[1]->{'score'} and @h==2) { find_results($h[0],$h[1]); } elsif ($h[1]->{'score'} > $h[2]->{'score'} and @h=>3) { find_results($h[0],$h[1]); } elsif ($h[1]->{'score'} == $h[2]->{'score'} and @h==3) { find_results($h[0],$h[1],$h[2]); } elsif ($h[2]->{'score'} > $h[3]->{'score'} and @h=>4) { find_results($h[0],$h[1],$h[2]); } #for MHC region elsif (($h[3]->{'t_id'}=~/6|MHC/ and $h[3]->{'score'} <= $h[2]->{'score'} and @h==4) or ($h[4] and $h[4]->{'t_id'}=~/6|MHC/ and $h[4]->{'score'} <= $h[2]->{'score'} and @h==5) or ($h[5] and $h[5]->{'t_id'}=~/6|MHC/ and $h[5]->{'score'} <= $h[2]->{'score'} and @h==6) or ($h[6] and $h[6]->{'t_id'}=~/6|MHC/ and $h[6]->{'score'} <= $h[2]->{'score'} and @h==7) or ($h[7] and $h[7]->{'t_id'}=~/6|MHC/ and $h[7]->{'score'} <= $h[2]->{'score'} and @h ==8)) { find_results(@h); } else { #needs to be written to the failed_variation table print MAP "$q_id\n"; } =cut } my ($total_seq,$no); $total_seq = keys %rec_seq; foreach my $q_id (keys %rec_seq) { if (!$done{$q_id}) { $no++; } } print OUT1 "$no out of $total_seq are not mapped\n"; close OUT; close OUT1; close MAP; } sub find_results { my (@h) = @_; LINE : foreach my $h (@h) { my $q_id = $h->{'q_id'}; my $q_start = $h->{'q_start'}; my $q_end = $h->{'q_end'}; my $q_strand = $h->{'q_strand'}; my $t_id = $h->{'t_id'}; my $t_start = $h->{'t_start'}; my $t_end = $h->{'t_end'}; my $t_strand = $h->{'t_strand'}; my $score = $h->{'score'}; my $match = $h->{'match'}; my @match_components = split /\s+/, $match; my ($new_q_start, $new_q_end, $new_t_start, $new_t_end); #print "$q_id,$q_start,$q_end,$q_strand,$t_id,$t_start,$t_end,$t_strand,$score,@match_components\n"; while (@match_components) { my $type = shift @match_components; my $query_match_length = shift @match_components; my $target_match_length = shift @match_components; #print "type is $type and query_match_length is $query_match_length and target_match_length is $target_match_length\n"; next LINE if (! defined $query_match_length or ! defined $target_match_length); my ($snp_q_pos, $snp_t_start, $snp_t_end, $snp_strand, $pre_target_match_length); my ($snp_posf,$snp_posl) = split /\_/, $snp_pos{$q_id}; $snp_q_pos = $snp_posf; if ($q_strand eq '+') { $new_q_start = $q_start + $query_match_length - 1 if ($type eq 'M'); $new_q_start = $q_start + $query_match_length + 1 if ($type eq 'G'); $new_t_start = $t_start + $target_match_length -1 if ($type eq 'M'); $new_t_start = $t_start + $target_match_length +1 if ($type eq 'G'); } elsif ($q_strand eq '-') { $new_q_start = $q_start - $query_match_length + 1 if ($type eq 'M'); $new_q_start = $q_start - $query_match_length - 1 if ($type eq 'G'); $new_t_start = $t_start + $target_match_length -1 if ($type eq 'M'); $new_t_start = $t_start + $target_match_length +1 if ($type eq 'G'); } #print "$q_id: [$snp_q_pos:$q_start,$new_q_start],$new_t_start and $t_start ; ".$snp_pos{$q_id}."\n"; if (($snp_q_pos >= $q_start and $snp_q_pos <= $new_q_start) or ($snp_q_pos >= $new_q_start and $snp_q_pos <= $q_start)) { if ($type eq 'M') { $snp_t_start = $t_start + abs($snp_q_pos-$q_start); $snp_t_end = $snp_t_start; #print "$q_id: $snp_q_pos,$q_start => $snp_t_start\n"; #print "abs is ",abs($snp_q_pos-$q_start),"\n"; #print "$snp_t_start and $snp_t_end\n"; } elsif ($type eq 'G') { if ($target_match_length ==0) { $snp_t_start = $t_start+1; $snp_t_end = $snp_t_start -1; } elsif ($query_match_length ==0) { $snp_t_start = $t_start+1; $snp_t_end = $snp_t_start + $target_match_length; } } } #print "$snp_t_start && $snp_t_end && $q_strand\n"; if ($snp_t_start && $snp_t_end && $q_strand ) { #print "$snp_t_start && $snp_t_end && $q_strand\n"; my $final_score = $score/$input_length{$q_id}; #print OUT "MORE_HITS\t" if ($h[2]); print OUT "$q_id\t$t_id\t$snp_t_start\t$snp_t_end\t$q_strand\t$final_score\n"; $done{$q_id}=1; last; } $q_start = $new_q_start; $t_start = $new_t_start; } } }
willmclaren/ensembl-variation
scripts/import/run_ssaha2.pl
Perl
apache-2.0
15,493
# # 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 apps::protocols::dhcp::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} = '1.0'; %{$self->{modes}} = ( 'connection' => 'apps::protocols::dhcp::mode::connection', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check a DHCP server. =cut
Sims24/centreon-plugins
apps/protocols/dhcp/plugin.pm
Perl
apache-2.0
1,267
package Paws::SQS::DeleteMessageBatchResultEntry; use Moose; has Id => (is => 'ro', isa => 'Str', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::SQS::DeleteMessageBatchResultEntry =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::SQS::DeleteMessageBatchResultEntry object: $service_obj->Method(Att1 => { Id => $value, ..., Id => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::SQS::DeleteMessageBatchResultEntry object: $result = $service_obj->Method(...); $result->Att1->Id =head1 DESCRIPTION Encloses the C<Id> of an entry in C< DeleteMessageBatch.> =head1 ATTRIBUTES =head2 B<REQUIRED> Id => Str Represents a successfully deleted message. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::SQS> =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/SQS/DeleteMessageBatchResultEntry.pm
Perl
apache-2.0
1,338
#!/usr/bin/env perl use strict; use warnings; use Pod::Usage; use Getopt::Long; use Scalar::Util qw(looks_like_number); use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater; my @OPTIONS = qw( registry|reg_conf=s compara=s species=s@ replace die_if_no_core verbose help man ); sub run { my $options = _parse_options(); _load_registry($options); my $dba = _compara_dba($options); my $genome_db_ids = _genome_db_ids($options, $dba); my $runnable = _build_runnable($options, $dba, $genome_db_ids); $runnable->run_without_hive(); return; } sub _parse_options { my $hash = {}; GetOptions( $hash, @OPTIONS) or pod2usage(1); pod2usage( -exitstatus => 0, -verbose => 1 ) if $hash->{help}; pod2usage( -exitstatus => 0, -verbose => 2 ) if $hash->{man}; return $hash; } sub _load_registry { my ($options) = @_; Bio::EnsEMBL::Registry->load_all($options->{registry}); return; } sub _compara_dba { my ($options) = @_; my $synonym = $options->{compara}; my $dba = Bio::EnsEMBL::Registry->get_DBAdaptor($synonym, 'compara'); if(! defined $dba) { my $reg = $options->{registry} || q{-}; print STDERR "Cannot find a compara DBAdaptor instance for the synonym ${synonym}. Check your registry (location ${reg}) to see if you have defined it\n"; pod2usage( -exitstatus => 1, -verbose => 1 ); } return $dba; } sub _genome_db_ids { my ($options, $dba) = @_; my $species = $options->{species}; if(! defined $species) { print STDOUT 'Working with all available GenomeDBs', "\n" if $options->{verbose}; return; } my @genome_dbs; foreach my $s (@{$species}) { if(looks_like_number($s)) { push(@genome_dbs, $s); } else { my $gdb = $dba->get_GenomeDBAdaptor()->fetch_by_registry_name($s); if(! defined $gdb) { print STDERR "$s does not have a valid GenomeDB\n"; pod2usage( -exitstatus => 1, -verbose => 1 ); } push(@genome_dbs, $gdb->dbID()); } } return \@genome_dbs; } sub _build_runnable { my ($options, $dba, $genome_db_ids) = @_; my %args = ( -DB_ADAPTOR => $dba, -REPLACE => $options->{replace}, -DIE_IF_NO_CORE_ADAPTOR => $options->{die_if_no_core}, -DEBUG => $options->{verbose} ); $args{-GENOME_DB_IDS} = $genome_db_ids if defined $genome_db_ids; return Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater->new_without_hive(%args); } #Only execute method run(); exit 0; __END__ =pod =head1 NAME populate_member_display_label.pl =head1 SYNOPSIS ./populate_member_display_label.pl --reg_conf my.reg --compara my_compara --species 'homo_sapiens' --replace ./populate_member_display_label.pl --reg_conf my.reg --compara my_compara --species 90 --species 91 ./populate_member_display_label.pl --registry my.reg --compara my_compara =head1 DESCRIPTION This is a thin wrapper script to call out to the module C<Bio::EnsEMBL::Compara::RunnableDB::MemberDisplayLabelUpdater>. The aim is to upate the field C<member.display_label> in the specified compara database. Pipelines sometimes will not load this data because it does not exist when you run the pipeline (true for Ensembl Compara because some display labels will depend on the projections from generated from Compara). Options are available to force errors to appear as & when we miss out on a core adaptor as well as forcing the replacement of existing display labels. You can specify the GenomeDBs to update or giving no values causes an update of all GenomeDBs =head1 OPTIONS =over 8 =item B<--registry | --reg_conf> Specify a location of the registry file to load =item B<--compara> Compara database to use e.g. multi =item B<--species> Specify a registry alias to find a GenomeDB by; supports GenomeDB IDs & you can specify multiple options on the command line =item B<--replace> Replace any existing display labels =item B<--die_if_no_core> Cause the script to die if we encounter any GenomeDB without a Core DBAdaptor =item B<--verbose> Prints messages to STDOUT =item B<--help> Help output =item B<--man> Manual page =back =cut
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-compara/scripts/pipeline/populate_member_display_labels.pl
Perl
apache-2.0
4,157
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =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::DBAdaptor =head1 SYNOPSIS $db = Bio::EnsEMBL::DBSQL::DBAdaptor->new( -user => 'root', -dbname => 'pog', -host => 'caldy', -driver => 'mysql' ); $gene_adaptor = $db->get_GeneAdaptor(); $gene = $gene_adaptor->fetch_by_stable_id($stable_id); $slice = $db->get_SliceAdaptor()->fetch_by_chr_start_end( 'X', 1, 10000 ); =head1 DESCRIPTION Formerly this class provided database connectivity and a means to retrieve object adaptors. This class is now provided for convenience and backwards compatibility, and delegates its connection responsibilities to the DBConnection class (no longer inherited from) and its object adaptor retrieval to the static Bio::EnsEMBL::Registry. Please use Bio::EnsEMBL::Registry to retrieve object adaptors. =head1 METHODS =cut package Bio::EnsEMBL::DBSQL::DBAdaptor; use strict; use Bio::EnsEMBL::DBSQL::DBConnection; use Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor; use Bio::EnsEMBL::Utils::SeqRegionCache; use Bio::EnsEMBL::Utils::Exception qw(throw warning deprecate); use Bio::EnsEMBL::Utils::Argument qw(rearrange); use Bio::EnsEMBL::Utils::Scalar qw(check_ref scope_guard); use Bio::EnsEMBL::Utils::ConfigRegistry; my $REGISTRY = "Bio::EnsEMBL::Registry"; require Bio::EnsEMBL::Registry; =head2 new Arg [-DNADB]: (optional) Bio::EnsEMBL::DBSQL::DBAdaptor DNADB All sequence, assembly, contig information etc, will be retrieved from this database instead. Arg [-NO_CACHE]: (optional) int 1 This option will turn off caching for slice features, so, every time a set of features is retrieved, they will come from the database instead of the cache. This option is only recommended for advanced users, specially if you need to store and retrieve features. It might reduce performance when querying the database if not used properly. If in doubt, do not use it or ask in the developer mailing list. Arg [-ADD_ALIASES]: (optional) boolean Used to automatically load aliases for this species into the Registry upon loading. Arg [-ADD_SPECIES_ID]: (optional) boolean Used to automatically load the species id based on the species if none is defined. Arg [..] : Other args are passed to superclass Bio::EnsEMBL::DBSQL::DBConnection Example : $db = new Bio::EnsEMBL::DBSQL::DBAdaptor( -user => 'root', -dbname => 'pog', -host => 'caldy', -driver => 'mysql' ); $db = new Bio::EnsEMBL::DBSQL::DBAdaptor( -species => 'Homo_sapiens', -group => 'core', -user => 'root', -dbname => 'pog', -host => 'caldy', -driver => 'mysql' ); $db = new Bio::EnsEMBL::DBSQL::DBAdaptor( -species => 'staphylococcus_aureus', -group => 'core', -user => 'root', -dbname => 'staphylococcus_collection_1_52_1a', -multispecies_db => 1, -host => 'caldy', -driver => 'mysql' ); Description: Constructor for DBAdaptor. Returntype : Bio::EnsEMBL::DBSQL::DBAdaptor Exceptions : none Caller : general Status : Stable =cut sub new { my ( $class, @args ) = @_; my $self = bless {}, $class; my ( $is_multispecies, $species, $species_id, $group, $con, $dnadb, $no_cache, $dbname, $add_aliases, $add_species_id ) = rearrange( [ 'MULTISPECIES_DB', 'SPECIES', 'SPECIES_ID', 'GROUP', 'DBCONN', 'DNADB', 'NO_CACHE', 'DBNAME', 'ADD_ALIASES', 'ADD_SPECIES_ID' ], @args ); if ( defined($con) ) { $self->dbc($con) } else { if(! defined $dbname) { throw "-DBNAME is a required parameter when creating a DBAdaptor"; } $self->dbc( new Bio::EnsEMBL::DBSQL::DBConnection(@args) ); } if ( defined($species) ) { $self->species($species); } if ( defined($group) ) { $self->group($group) } $self = Bio::EnsEMBL::Utils::ConfigRegistry::gen_load($self); if (defined $species_id) { $self->species_id($species_id); } elsif ($add_species_id and defined $species) { $self->find_and_add_species_id(); } else { $self->species_id(1); } $self->is_multispecies( defined($is_multispecies) && $is_multispecies == 1 ); if ( defined($dnadb) ) { $self->dnadb($dnadb) } if ( $no_cache ) { $self->no_cache($no_cache) } if ( $add_aliases ) { $self->find_and_add_aliases($add_aliases) } return $self; } ## end sub new =head2 clear_caches Example : $dba->clear_caches(); Description : Loops through all linked adaptors and clears their caches if C<clear_cache()> is implemented. Not all caches are cleared & the DBAdaptor instance should be removed from the registry to clear these remaining essential caches. Returntype : None Exceptions : None =cut sub clear_caches { my ($self) = @_; my $adaptors = $REGISTRY->get_all_adaptors( $self->species(), $self->group()); foreach my $adaptor (@{$adaptors}) { if($adaptor->can('clear_cache')) { $adaptor->clear_cache(); } } return; } =head2 find_and_add_aliases Example : $dba->find_and_add_aliases(); Description : When executed we delegate to the find_and_add_aliases method in Bio::EnsEMBL::Registry which scans the database's MetaContainer for species.alias entries indicating alternative names for this species. This is best executed on a core DBAdaptor instance. Returntype : None Exceptions : None =cut sub find_and_add_aliases { my ($self) = @_; $REGISTRY->find_and_add_aliases(-ADAPTOR => $self); return; } =head2 find_and_add_species_id Description : Returntype : None Exceptions : None =cut sub find_and_add_species_id { my ($self) = @_; my $species = $self->species; defined $species or throw "Undefined species"; my $dbc = $self->dbc; my $sth = $dbc->prepare(sprintf "SELECT DISTINCT species_id FROM %s.meta " . "WHERE meta_key='species.alias' AND meta_value LIKE '%%s%'", $dbc->db_handle->quote_identifier($dbc->dbname), $species); $sth->execute() or throw "Error querying for species_id: perhaps the DB doesn't have a meta table?\n" . "$DBI::err .... $DBI::errstr\n"; my $species_id; $sth->bind_columns(\$species_id); $sth->fetch; throw "Undefined species_id" unless defined $species_id; throw "Something wrong retrieving the species_id" unless $species_id >= 1; $self->species_id($species_id); return; } =head2 dbc Arg[1] : (optional) Bio::EnsEMBL::DBSQL::DBConnection Example : $dbc = $dba->dbc(); Description: Getter/Setter for DBConnection. Returntype : Bio::EnsEMBL::DBSQL::DBConnection Exceptions : throws if argument not a Bio::EnsEMBL::DBSQL::DBConnection Caller : general Status : Stable =cut sub dbc{ my $self = shift; if(@_){ my $arg = shift; if(defined($arg)){ if(!$arg->isa('Bio::EnsEMBL::DBSQL::DBConnection')){ throw("$arg is no a DBConnection\n"); } } $self->{_dbc} = $arg; } return $self->{_dbc}; } =head2 add_db_adaptor Arg [1] : string $name the name of the database to attach to this database Arg [2] : Bio::EnsEMBL::DBSQL::DBConnection the db adaptor to attach to this database Example : $db->add_db_adaptor('lite', $lite_db_adaptor); Description: Attaches another database instance to this database so that it can be used in instances where it is required. Returntype : none Exceptions : none Caller : EnsWeb Status : At Risk : may get deprecated, please use add_db from the registry instead =cut sub add_db_adaptor { my ($self, $name, $adaptor) = @_; unless($name && $adaptor && ref $adaptor) { throw('adaptor and name arguments are required'); } $REGISTRY->add_db($self, $name, $adaptor); } =head2 remove_db_adaptor Arg [1] : string $name the name of the database to detach from this database. Example : $lite_db = $db->remove_db_adaptor('lite'); Description: Detaches a database instance from this database and returns it. Returntype : none Exceptions : none Caller : ? Status : At Risk : mey get deprecated, use remove_db instead from the Registry =cut sub remove_db_adaptor { my ($self, $name) = @_; return $REGISTRY->remove_db($self, $name); } =head2 get_all_db_adaptors Arg [1] : none Example : @attached_dbs = values %{$db->get_all_db_adaptors()}; Description: returns all of the attached databases as a hash reference of key/value pairs where the keys are database names and the values are the attached databases Returntype : hash reference with Bio::EnsEMBL::DBSQL::DBConnection values Exceptions : none Caller : Bio::EnsEMBL::DBSQL::ProxyAdaptor Status : At Risk : may get deprecated soon : please use Bio::EnsEMBL::Registry->get_all_db_adaptors =cut sub get_all_db_adaptors { my ($self) = @_; return $REGISTRY->get_all_db_adaptors($self); } =head2 get_db_adaptor Arg [1] : string $name the name of the attached database to retrieve Example : $lite_db = $db->get_db_adaptor('lite'); Description: returns an attached db adaptor of name $name or undef if no such attached database exists Returntype : Bio::EnsEMBL::DBSQL::DBConnection Exceptions : none Caller : ? Status : At Risk : may get deprecated soon : please use Bio::EnsEMBL::Registry->get_db_adaptors =cut sub get_db_adaptor { my ($self, $name) = @_; return $REGISTRY->get_db($self, $name); } =head2 get_available_adaptors Example : my %pairs = %{$dba->get_available_adaptors()}; Description: gets a hash of the available adaptors ReturnType : reference to a hash Exceptions : none Caller : Bio::EnsEMBL::Utils::ConfigRegistry Status : Stable =cut sub get_available_adaptors { my $adaptors = { # Firstly those that just have an adaptor named after there object # in the main DBSQL directory. AltAlleleGroup => 'Bio::EnsEMBL::DBSQL::AltAlleleGroupAdaptor', Analysis => 'Bio::EnsEMBL::DBSQL::AnalysisAdaptor', ArchiveStableId => 'Bio::EnsEMBL::DBSQL::ArchiveStableIdAdaptor', AssemblyExceptionFeature => 'Bio::EnsEMBL::DBSQL::AssemblyExceptionFeatureAdaptor', AssemblyMapper => 'Bio::EnsEMBL::DBSQL::AssemblyMapperAdaptor', AssemblySlice => 'Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor', Attribute => 'Bio::EnsEMBL::DBSQL::AttributeAdaptor', CoordSystem => 'Bio::EnsEMBL::DBSQL::CoordSystemAdaptor', DataFile => 'Bio::EnsEMBL::DBSQL::DataFileAdaptor', DBEntry => 'Bio::EnsEMBL::DBSQL::DBEntryAdaptor', DensityFeature => 'Bio::EnsEMBL::DBSQL::DensityFeatureAdaptor', DensityType => 'Bio::EnsEMBL::DBSQL::DensityTypeAdaptor', DnaAlignFeature => 'Bio::EnsEMBL::DBSQL::DnaAlignFeatureAdaptor', Exon => 'Bio::EnsEMBL::DBSQL::ExonAdaptor', Gene => 'Bio::EnsEMBL::DBSQL::GeneAdaptor', IntronSupportingEvidence => 'Bio::EnsEMBL::DBSQL::IntronSupportingEvidenceAdaptor', KaryotypeBand => 'Bio::EnsEMBL::DBSQL::KaryotypeBandAdaptor', MiscFeature => 'Bio::EnsEMBL::DBSQL::MiscFeatureAdaptor', MiscSet => 'Bio::EnsEMBL::DBSQL::MiscSetAdaptor', Operon => 'Bio::EnsEMBL::DBSQL::OperonAdaptor', OperonTranscript => 'Bio::EnsEMBL::DBSQL::OperonTranscriptAdaptor', PredictionExon => 'Bio::EnsEMBL::DBSQL::PredictionExonAdaptor', PredictionTranscript => 'Bio::EnsEMBL::DBSQL::PredictionTranscriptAdaptor', ProteinAlignFeature => 'Bio::EnsEMBL::DBSQL::ProteinAlignFeatureAdaptor', ProteinFeature => 'Bio::EnsEMBL::DBSQL::ProteinFeatureAdaptor', RepeatConsensus => 'Bio::EnsEMBL::DBSQL::RepeatConsensusAdaptor', RepeatFeature => 'Bio::EnsEMBL::DBSQL::RepeatFeatureAdaptor', SeqRegionSynonym => 'Bio::EnsEMBL::DBSQL::SeqRegionSynonymAdaptor', Sequence => 'Bio::EnsEMBL::DBSQL::SequenceAdaptor', SimpleFeature => 'Bio::EnsEMBL::DBSQL::SimpleFeatureAdaptor', Slice => 'Bio::EnsEMBL::DBSQL::SliceAdaptor', SupportingFeature => 'Bio::EnsEMBL::DBSQL::SupportingFeatureAdaptor', Transcript => 'Bio::EnsEMBL::DBSQL::TranscriptAdaptor', TranscriptSupportingFeature => 'Bio::EnsEMBL::DBSQL::TranscriptSupportingFeatureAdaptor', Translation => 'Bio::EnsEMBL::DBSQL::TranslationAdaptor', UnmappedObject => 'Bio::EnsEMBL::DBSQL::UnmappedObjectAdaptor', # Those whose adaptors are in Map::DBSQL Ditag => 'Bio::EnsEMBL::Map::DBSQL::DitagAdaptor', DitagFeature => 'Bio::EnsEMBL::Map::DBSQL::DitagFeatureAdaptor', Marker => 'Bio::EnsEMBL::Map::DBSQL::MarkerAdaptor', MarkerFeature => 'Bio::EnsEMBL::Map::DBSQL::MarkerFeatureAdaptor', # Finally the exceptions... those that have non-standard mapping # between object / adaptor .... GenomeContainer => 'Bio::EnsEMBL::DBSQL::GenomeContainer', MetaContainer => 'Bio::EnsEMBL::DBSQL::MetaContainer', MetaCoordContainer => 'Bio::EnsEMBL::DBSQL::MetaCoordContainer', }; return $adaptors; } ## end sub get_available_adaptors ########################################################### # # Support for DAS # ########################################################### =head2 add_DASFeatureFactory Arg [1] : Bio::EnsEMBL::ExternalFeatureFactory $value Example : none Description: Attaches a DAS Feature Factory to this method. ExternalFeatureFactory objects are not really used right now. They may be reintroduced or taken out completely. The fate of this function is unknown (although it is presently needed). Returntype : none Exceptions : none Caller : EnsWeb Status : At Risk : with the new web code this may not be needed/supported =cut sub add_DASFeatureFactory{ my ($self,$value) = @_; push(@{$self->{'_das_ff'}},$value); } sub remove_all_DASFeatureFactories { $_[0]->{'_das_ff'} = []; } =head2 _each_DASFeatureFactory Args : none Example : none Description: Not sure if this is used, or if it should be removed. It does not seem to be used at the moment Returntype : Bio::EnsEMBL::ExternalFeatureFactory Exceptions : none Caller : ?? Status : At Risk : with the new web code this may not be needed/supported =cut sub _each_DASFeatureFactory{ my ($self) = @_; return @{$self->{'_das_ff'}||[]} } ################################################################## # # SUPPORT FOR EXTERNAL FEATURE FACTORIES # ################################################################## =head2 add_ExternalFeatureAdaptor Arg [1] : Bio::EnsEMBL::External::ExternalFeatureAdaptor Example : $db_adaptor->add_ExternalFeatureAdaptor($xfa); Description: Adds an external feature adaptor to this database adaptor. Adding the external adaptor in this way allows external features to be obtained from Slices and from RawContigs. The external feature adaptor which is passed to this method will have its db attribuite set to this DBAdaptor object via the db accessor method. ExternalFeatureAdaptors passed to this method are stored internally in a hash keyed on the string returned by the ExternalFeatureAdaptors track_name method. If the track name method is not implemented then the a default key named 'External features' is assigned. In the event of duplicate key names, a number is appended to the key name, and incremented for each subsequent adaptor with the same track name. For example, if no track_names are specified then the the external feature adaptors will be stored under the keys 'External features', 'External features2' 'External features3' etc. Returntype : none Exceptions : none Caller : general =cut sub add_ExternalFeatureAdaptor { my ($self, $adaptor) = @_; unless($adaptor && ref $adaptor && $adaptor->isa('Bio::EnsEMBL::External::ExternalFeatureAdaptor')) { throw("[$adaptor] is not a " . "Bio::EnsEMBL::External::ExternalFeatureAdaptor"); } unless(exists $self->{'_xf_adaptors'}) { $self->{'_xf_adaptors'} = {}; } my $track_name = $adaptor->{'_track_name'}; if(!$track_name) { $track_name = $adaptor->track_name(); } #use a generic track name if one hasn't been defined unless(defined $track_name) { $track_name = "External features"; } #if the track name exists add numbers to the end until a free name is found if(exists $self->{'_xf_adaptors'}->{"$track_name"}) { my $num = 2; $num++ while(exists $self->{'_xf_adaptors'}->{"$track_name$num"}); $self->{'_xf_adaptors'}->{"$track_name$num"} = $adaptor; } else { $self->{'_xf_adaptors'}->{"$track_name"} = $adaptor; } $adaptor->ensembl_db($self); } =head2 get_ExternalFeatureAdaptors Arg [1] : none Example : @xfas = values %{$db_adaptor->get_ExternalFeatureAdaptors}; Description: Retrieves all of the ExternalFeatureAdaptors which have been added to this DBAdaptor. The ExternalFeatureAdaptors are returned in a reference to a hash keyed on the track names of the external adaptors Returntype : Reference to a hash of ExternalFeatureAdaptors keyed on their track names. Exceptions : none Caller : general =cut sub get_ExternalFeatureAdaptors { my $self = shift; return $self->{'_xf_adaptors'}; } =head2 add_ExternalFeatureFactory Arg [1] : Bio::EnsEMBL::DB::ExternalFeatureFactoryI $value Example : $db_adaptor->add_ExternalFeatureFactory Description: It is recommended that add_ExternalFeatureAdaptor be used instead. See documentation for Bio::EnsEMBL::External::ExternalFeatureAdaptor Adds an external feature factory to the core database so that features from external sources can be displayed in ensembl. This method is still available mainly for legacy support for external EnsEMBL installations. Returntype : none Exceptions : none Caller : external =cut sub add_ExternalFeatureFactory{ my ($self,$value) = @_; $self->add_ExternalFeatureAdaptor($value); } # # OVERWRITABLE STANDARD ADAPTORS # =head2 get_adaptor Arg [1] : Canonical data type for which an adaptor is required. Example : $db_adaptor->get_adaptor("Protein") Description: Gets an adaptor object for a standard data type. Returntype : Adaptor Object of arbitrary type or undef Exceptions : none Caller : external Status : Medium Risk : please use the Registry method, as at some time this : may no longer be supprted. =cut sub get_adaptor { my ($self, $canonical_name, @other_args) = @_; return $REGISTRY->get_adaptor($self->species(),$self->group(),$canonical_name); } =head2 set_adaptor Arg [1] : Canonical data type for new adaptor. Arg [2] : Object defining the adaptor for arg1. Example : $aa = Bio::EnsEMBL::DBSQL::GeneAdaptor->new($db_adaptor); : $db_adaptor->set_adaptor("Gene", $ga) Description: Stores the object which represents the adaptor for the arg1 data type. Returntype : none Exceptions : none Caller : external Status : Medium Risk : please use the Registry method, as at some time this : may no longer be supprted. =cut sub set_adaptor { my ($self, $canonical_name, $module) = @_; $REGISTRY->add_adaptor($self->species(),$self->group(),$canonical_name,$module); return $module; } # # GENERIC FEATURE ADAPTORS # =head2 get_GenericFeatureAdaptors Arg [1] : List of names of feature adaptors to get. If no adaptor names are given, all the defined adaptors are returned. Example : $db->get_GenericFeature("SomeFeature", "SomeOtherFeature") Description: Returns a hash containing the named feature adaptors (or all feature adaptors). Returntype : reference to a Hash containing the named feature adaptors (or all feature adaptors). Exceptions : If any of the the named generic feature adaptors do not exist. Caller : external =cut sub get_GenericFeatureAdaptors { my ($self, @names) = @_; my %adaptors = (); if (!@names) { %adaptors = %{$self->{'generic_feature_adaptors'}}; } else { foreach my $name (@names) { if (!exists($self->{'generic_feature_adaptors'}->{$name})) { throw("No generic feature adaptor has been defined for $name" ); } $adaptors{$name} = $self->{'generic_feature_adaptors'}->{$name}; } } return \%adaptors; } =head2 add_GenericFeatureAdaptor Arg [1] : The name of the feature. Arg [2] : Adaptor object for a generic feature. Example : $db->add_GenericFeatureAdaptor("SomeFeature", "Bio::EnsEMBL::DBSQL::SomeFeatureAdaptor") Description: Stores the object which represents the adaptor for the named feature type. Returntype : none Exceptions : Caller : external =cut sub add_GenericFeatureAdaptor { my ($self, $name, $adaptor_obj) = @_; # check that $adaptor is an object that subclasses BaseFeatureAdaptor if (!$adaptor_obj->isa("Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor")) { throw("$name is a " . ref($adaptor_obj) . "which is not a " . "subclass of Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor" ); } $self->{'generic_feature_adaptors'}->{$name} = $adaptor_obj; } =head2 species Arg [1] : (optional) string $arg The new value of the species used by this DBAdaptor. Example : $species = $dba->species() Description: Getter/Setter for the species of to use for this connection. There is currently no point in setting this value after the connection has already been established by the constructor. Returntype : string Exceptions : none Caller : new Status : Stable =cut sub species { my ( $self, $arg ) = @_; if ( defined($arg) ) { $self->{_species} = $arg; } $self->{_species}; } =head2 all_species Args : NONE Example : @all_species = @{$dba->all_species()}; Description: Returns the names of all species contained in the database to which this DBAdaptor is connected. Returntype : array reference Exceptions : none Caller : general Status : Stable =cut sub all_species { my ($self) = @_; if ( !$self->is_multispecies() ) { return [ $self->species() ] } return $self->{'_all_species'} if exists $self->{_all_species}; my $sql = "SELECT meta_value FROM meta WHERE meta_key = 'species.db_name'"; $self->{_all_species} = $self->dbc->sql_helper()->execute_simple(-SQL => $sql); return $self->{'_all_species'}; } ## end sub all_species =head2 is_multispecies Arg [1] : (optional) boolean $arg Example : if ($dba->is_multispecies()) { } Description: Getter/Setter for the is_multispecies boolean of to use for this connection. There is currently no point in setting this value after the connection has already been established by the constructor. Returntype : boolean Exceptions : none Caller : new Status : Stable =cut sub is_multispecies { my ( $self, $arg ) = @_; if ( defined($arg) ) { $self->{_is_multispecies} = $arg; } return $self->{_is_multispecies}; } =head2 species_id Arg [1] : (optional) string $arg The new value of the species_id used by this DBAdaptor when dealing with multi-species databases. Example : $species_id = $dba->species_id() Description: Getter/Setter for the species_id of to use for this connection. There is currently no point in setting this value after the connection has already been established by the constructor. Returntype : string Exceptions : none Caller : new Status : Stable =cut sub species_id { my ( $self, $arg ) = @_; if ( defined($arg) ) { $self->{_species_id} = $arg; } return $self->{_species_id}; } =head2 no_cache Arg [1] : (optional) int $arg The new value of the no cache attribute used by this DBAdaptor. Example : $no_cache = $dba->no_cache(); Description: Getter/Setter for the no_cache to use for this connection. There is currently no point in setting this value after the connection has already been established by the constructor. Returntype : int Exceptions : none Caller : new Status : Stable =cut sub no_cache { my ($self, $arg ) = @_; if ( defined $arg ){ if ($arg != 1 && $arg != 0){ throw("$arg is not allowed for this attribute. Only value 1|0 is allowed"); } $self->{_no_cache} = $arg; } $self->{_no_cache}; } =head2 group Arg [1] : (optional) string $arg The new value of the group used by this DBAdaptor. Example : $group = $dba->group() Description: Getter/Setter for the group of to use for this connection. There is currently no point in setting this value after the connection has already been established by the constructor. Returntype : string Exceptions : none Caller : new Status : Stable =cut sub group { my ($self, $arg ) = @_; ( defined $arg ) && ( $self->{_group} = $arg ); $self->{_group}; } =head2 get_SeqRegionCache Arg [1] : none Example : my $srcache = $dba->get_SeqRegionCache(); Description: Retrieves a seq_region cache for this database Returntype : Bio::EnsEMBL::Utils::SeqRegionCache Exceptions : none Caller : SliceAdaptor, AssemblyMapperAdaptor Status : Stable =cut sub get_SeqRegionCache { my $self = shift; # use the cache from the database where seq_regions are stored if($self != $self->dnadb()) { return $self->dnadb()->get_SeqRegionCache(); } if(!$self->{'seq_region_cache'}) { $self->{'seq_region_cache'} = Bio::EnsEMBL::Utils::SeqRegionCache->new(); } return $self->{'seq_region_cache'}; } #convenient method to retrieve the schema_build version for the database being used sub _get_schema_build{ my ($self) = @_; #avoided using dnadb by default to avoid obfuscation of behaviour my @dbname = split/_/, $self->dbc->dbname(); #warn "dbname is $schema_build"; my $schema_build = pop @dbname; $schema_build = pop(@dbname).'_'.$schema_build; return $schema_build; } =head2 dnadb Title : dnadb Usage : my $dnadb = $db->dnadb(); Function: returns the database adaptor where the dna lives Useful if you only want to keep one copy of the dna on disk but have other databases with genes and features in Returns : dna database adaptor Args : Bio::EnsEMBL::DBSQL::BaseAdaptor Status : Medium Risk. : Use the Registry method add_DNAAdaptor/get_DNAAdaptor instead =cut sub dnadb { my $self = shift; if(@_) { my $arg = shift; $REGISTRY->add_DNAAdaptor($self->species(),$self->group(),$arg->species(),$arg->group()); } # return $self->{'dnadb'} || $self; return $REGISTRY->get_DNAAdaptor($self->species(),$self->group()) || $self; } use vars '$AUTOLOAD'; sub AUTOLOAD { my ( $self, @args ) = @_; my $type; if ( $AUTOLOAD =~ /^.*::get_(\w+)Adaptor$/ ) { $type = $1; } elsif ( $AUTOLOAD =~ /^.*::get_(\w+)$/ ) { $type = $1; } else { throw( sprintf( "Could not work out type for %s\n", $AUTOLOAD ) ); } my $ret = $REGISTRY->get_adaptor( $self->species(), $self->group(), $type ); return $ret if $ret; warning( sprintf( "Could not find %s adaptor in the registry for %s %s\n", $type, $self->species(), $self->group() ) ); throw( sprintf( "Could not get adaptor %s for %s %s\n", $type, $self->species(), $self->group() ) ); } ## end sub AUTOLOAD sub DESTROY { } # required due to AUTOLOAD =head2 to_hash Example : my $hash = $dba->to_hash(); my $new_dba = $dba->new(%{$hash}); Description: Provides a hash which is compatible with the parameters for DBAdaptor's new() method. This can be useful during serialisation but be aware that Registry Returntype : Hash Exceptions : none Caller : general Status : New =cut sub to_hash { my ($self) = @_; my $hash = $self->dbc()->to_hash(); $hash->{-SPECIES} = $self->species(); $hash->{-GROUP} = $self->group(); $hash->{-SPECIES_ID} = $self->species_id(); $hash->{-MULTISPECIES_DB} = $self->is_multispecies(); return $hash; } ######################### # Switchable adaptor methods ######################### =head2 switch_adaptor Arg [1] : String name of the adaptor type to switch out Arg [2] : Reference The switchable adaptor implementation Arg [3] : (optional) CodeRef Provide a subroutine reference as a callback. The adaptor will be switched before your codeblock is executed and the adaptor switched back to the original once your code has finished running Arg [4] : (optional) Boolean override any existing switchable adaptor Example : $dba->switch_adaptor("sequence", $my_replacement_sequence_adaptor); $dba->switch_adaptor("sequence", $my_other_replacement_sequence_adaptor, 1); $dba->switch_adaptor("sequence", $my_replacement_sequence_adaptor, sub { #Make calls as normal without having to do manual cleanup }); Returntype : None Description : Provides a wrapper around the Registry add_switchable_adaptor() method defaulting both species and group to the current DBAdaptor. Callbacks are also available providing automatic resource cleanup. The method also remembers the last switch you did. It will not remember multiple switches though. Exceptions : Thrown if no switchable adaptor instance was given =cut sub switch_adaptor { my ($self, $adaptor_name, $instance, $callback, $force) = @_; my ($species, $group) = ($self->species(), $self->group()); $REGISTRY->add_switchable_adaptor($species, $group, $adaptor_name, $instance, $force); $self->{_last_switchable_adaptor} = $adaptor_name; if(check_ref($callback, 'CODE')) { #Scope guard will reset the adaptor once it falls out of scope. They #are implemented as callback DESTROYS so are neigh on impossible #to stop executing my $guard = scope_guard(sub { $REGISTRY->remove_switchable_adaptor($species, $group, $adaptor_name); } ); $callback->(); } return; } =head2 has_switched_adaptor Arg [1] : String name of the adaptor type to switch back in Example : $dba->has_switchable_adaptor("sequence"); #explicit switching back Returntype : Boolean indicating if the given adaptor is being activly switched Description : Provides a wrapper around the Registry has_switchable_adaptor() method defaulting both species and group to the current DBAdaptor. This will inform if the specified adaptor is being switched out Exceptions : None =cut sub has_switched_adaptor { my ($self, $adaptor_name) = @_; return $REGISTRY->has_switchable_adaptor($self->species, $self->group, $adaptor_name); } =head2 revert_adaptor Arg [1] : (optional) String name of the adaptor type to switch back in Example : $dba->revert_adaptor(); #implicit switching back whatever was the last switch_adaptor() call $dba->revert_adaptor("sequence"); #explicit switching back Returntype : The removed adaptor Description : Provides a wrapper around the Registry remove_switchable_adaptor() method defaulting both species and group to the current DBAdaptor. This will remove a switchable adaptor. You can also remove the last adaptor you switched in without having to specify any parameter. Exceptions : Thrown if no switchable adaptor name was given or could be found in the internal last adaptor variable =cut sub revert_adaptor { my ($self, $adaptor_name) = @_; $adaptor_name ||= $self->{_last_switchable_adaptor}; throw "Not given an adaptor name to remove and cannot find the name of the last switched adaptor" if ! $adaptor_name; my $deleted_adaptor = $REGISTRY->remove_switchable_adaptor($self->species, $self->group, $adaptor_name); delete $self->{last_switch}; return $deleted_adaptor; } 1;
danstaines/ensembl
modules/Bio/EnsEMBL/DBSQL/DBAdaptor.pm
Perl
apache-2.0
35,453
# 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::YoutubeVideoAsset; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { youtubeVideoId => $args->{youtubeVideoId}, youtubeVideoTitle => $args->{youtubeVideoTitle}}; # 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/YoutubeVideoAsset.pm
Perl
apache-2.0
1,095