hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 163
values | lang
stringclasses 53
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
112
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
113
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
float64 1
116k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
113
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 3
1.05M
| avg_line_length
float64 1
966k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed7a677385455340459550e40d63d48f05a022db | 1,962 | pm | Perl | auto-lib/Paws/SES/DescribeConfigurationSet.pm | agimenez/aws-sdk-perl | 9c4dff7d1af2ff0210c28ca44fb9e92bc625712b | [
"Apache-2.0"
]
| null | null | null | auto-lib/Paws/SES/DescribeConfigurationSet.pm | agimenez/aws-sdk-perl | 9c4dff7d1af2ff0210c28ca44fb9e92bc625712b | [
"Apache-2.0"
]
| null | null | null | auto-lib/Paws/SES/DescribeConfigurationSet.pm | agimenez/aws-sdk-perl | 9c4dff7d1af2ff0210c28ca44fb9e92bc625712b | [
"Apache-2.0"
]
| null | null | null |
package Paws::SES::DescribeConfigurationSet;
use Moose;
has ConfigurationSetAttributeNames => (is => 'ro', isa => 'ArrayRef[Str|Undef]');
has ConfigurationSetName => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeConfigurationSet');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::SES::DescribeConfigurationSetResponse');
class_has _result_key => (isa => 'Str', is => 'ro', default => 'DescribeConfigurationSetResult');
1;
### main pod documentation begin ###
=head1 NAME
Paws::SES::DescribeConfigurationSet - Arguments for method DescribeConfigurationSet on Paws::SES
=head1 DESCRIPTION
This class represents the parameters used for calling the method DescribeConfigurationSet on the
Amazon Simple Email Service service. Use the attributes of this class
as arguments to method DescribeConfigurationSet.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeConfigurationSet.
As an example:
$service_obj->DescribeConfigurationSet(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 ConfigurationSetAttributeNames => ArrayRef[Str|Undef]
A list of configuration set attributes to return.
=head2 B<REQUIRED> ConfigurationSetName => Str
The name of the configuration set to describe.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method DescribeConfigurationSet in L<Paws::SES>
=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
| 31.645161 | 249 | 0.750255 |
ed5ce81b54613ce395196ccc73f521e2e6737c87 | 88 | pl | Perl | Task/Sum-digits-of-an-integer/Perl/sum-digits-of-an-integer-2.pl | mullikine/RosettaCodeData | 4f0027c6ce83daa36118ee8b67915a13cd23ab67 | [
"Info-ZIP"
]
| 1 | 2018-11-09T22:08:38.000Z | 2018-11-09T22:08:38.000Z | Task/Sum-digits-of-an-integer/Perl/sum-digits-of-an-integer-2.pl | mullikine/RosettaCodeData | 4f0027c6ce83daa36118ee8b67915a13cd23ab67 | [
"Info-ZIP"
]
| null | null | null | Task/Sum-digits-of-an-integer/Perl/sum-digits-of-an-integer-2.pl | mullikine/RosettaCodeData | 4f0027c6ce83daa36118ee8b67915a13cd23ab67 | [
"Info-ZIP"
]
| 1 | 2018-11-09T22:08:40.000Z | 2018-11-09T22:08:40.000Z | use ntheory "sumdigits";
say sumdigits($_,36) for (qw/1 1234 1020304 fe f0e DEADBEEF/);
| 29.333333 | 62 | 0.727273 |
ed43c94e72f199df30dd938cc0a4a196b0d859cb | 871 | pl | Perl | windows10/git-bash-zsh/usr/share/perl5/core_perl/unicore/lib/Age/V50.pl | Allen-LPL/dotfiles | 9bc894fc6c9d32b1a0c84812c66fb5133484eff4 | [
"MIT"
]
| 1,318 | 2019-07-11T10:34:39.000Z | 2022-03-29T15:05:19.000Z | windows10/git-bash-zsh/usr/share/perl5/core_perl/unicore/lib/Age/V50.pl | Allen-LPL/dotfiles | 9bc894fc6c9d32b1a0c84812c66fb5133484eff4 | [
"MIT"
]
| 387 | 2019-09-05T16:33:09.000Z | 2022-03-31T10:43:39.000Z | windows10/git-bash-zsh/usr/share/perl5/core_perl/unicore/lib/Age/V50.pl | Allen-LPL/dotfiles | 9bc894fc6c9d32b1a0c84812c66fb5133484eff4 | [
"MIT"
]
| 66 | 2019-11-11T15:33:12.000Z | 2022-03-01T07:55:55.000Z | # !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 13.0.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly. Use Unicode::UCD to access the Unicode character data
# base.
return <<'END';
V70
578
592
891
894
1231
1232
1274
1280
1296
1300
1466
1467
1984
2043
2427
2429
2430
2432
3298
3300
3313
3315
6912
6988
6992
7037
7620
7627
7678
7680
8428
8432
8525
8527
8580
8581
9180
9192
9906
9907
10183
10187
11028
11035
11040
11044
11360
11373
11380
11384
42775
42779
42784
42786
43072
43128
67840
67866
67871
67872
73728
74607
74752
74851
74864
74868
119648
119666
120778
120780
END
| 10.247059 | 77 | 0.741676 |
ed4aaf8af6666c7b1c69e799f28fae19f7e14af8 | 46,788 | pm | Perl | src/WebApplication/WebApplication.pm | paczian/MG-RAST | f6f3dea9ec21fa1fa7e561f755ddc91e98c79ada | [
"BSD-2-Clause"
]
| 23 | 2015-01-28T10:36:41.000Z | 2020-12-20T14:54:52.000Z | src/WebApplication/WebApplication.pm | paczian/MG-RAST | f6f3dea9ec21fa1fa7e561f755ddc91e98c79ada | [
"BSD-2-Clause"
]
| 19 | 2015-03-12T14:51:34.000Z | 2022-02-22T17:58:20.000Z | src/WebApplication/WebApplication.pm | paczian/MG-RAST | f6f3dea9ec21fa1fa7e561f755ddc91e98c79ada | [
"BSD-2-Clause"
]
| 17 | 2015-01-14T17:13:05.000Z | 2021-12-16T10:18:00.000Z | package WebApplication;
# WebApplication - framework to develop application-like web sites
use strict;
use warnings;
use FreezeThaw qw( freeze thaw );
use CGI;
use CGI::Cookie;
use HTML::Strip;
use DBMaster;
use Scalar::Util qw/reftype/;
# include default WebPages
use WebMenu;
use WebConfig;
use WebPage::Error;
use WebApplicationDBHandle;
use Conf;
$CGI::LIST_CONTEXT_WARN = 0;
$CGI::Application::LIST_CONTEXT_WARN = 0;
1;
=pod
=head1 WebApplication
=head2 DESCRIPTION
The WebApplication is a framework to support fast, comprehesible and componentalized
creation of applications on the web. Main features include:
=over 4
=item * menus
=item * user authentication
=item * page oriented structure
=item * session management
=item * action management
=item * reusable components
=back
For setup and usage, please refer to the WebApplication Tutorial.
=head2 METHODS
=head3 B<new> ($params)
B<Returns:> a reference to a WebApplication object
Creates a new instance of the WebApplication object.
$params is a hash which supports the following values:
=over 4
=item dbmaster
An instance of the PPO DBMaster which points to the user database.
If this parameter is omitted, a dbmaster will be created with the following settings in
WebConfig, located in FIGdisk/config/WebApplication/$appname.cfg:
=over 8
=item * DBNAME
=item * DBHOST
=item * DBUSER
=item * DBPWD
=back
If the configuration file is not present, these values will default to the ones set in
WebConfig
=item menu
An instance of WebMenu which will represent the current structure of the navigation menu.
If this is omitted it will default to an empty menu.
=item default
The name of the page to be displayed when no $cgi->param('page') is present.
=item layout
An instance of WebLayout which represents the layout of the page.
=item id
A string representing the name of the application. This is used to identify the application
in the database. If this does not yet exist in the database, it will be created.
=item cgi
An instance of the CGI object. If omitted, this will default to CGI->new()
=item noTrace
If TRUE, tracing will not be activated. This is useful when you want to activate
tracing before constructing the WebApplication object.
=back
=cut
sub new {
my ($class, $params) = @_;
my $dbmaster = $params->{'dbmaster'};
my $menu = $params->{'menu'} || WebMenu->new();
my $default = $params->{'default'};
my $layout = $params->{'layout'};
my $backend_name = $params->{'id'};
my $cgi = $params->{'cgi'} || CGI->new();
my $hs = HTML::Strip->new();
my @cgi_params = $cgi->param;
foreach my $p (@cgi_params) {
my @plist = $cgi->param($p);
foreach my $p1 (@plist) {
if ($p1 && defined(reftype($p1)) && (reftype($p1) eq "")) {
$p1 = $hs->parse($p1);
}
}
$cgi->param($p, @plist);
}
$hs->eof;
my $self = { cgi => $cgi,
menu => $menu,
menu_backup => freeze($menu),
layout => $layout,
backend => undef,
page => undef,
default => $default,
error => undef,
redirect => undef,
show_login_user_info => 0,
fancy_login => 0,
messages => {},
components => {},
component_index => {},
data_handlers => {},
actions => {},
time => time,
page_title_prefix => '',
test_bot => $cgi->param('test_bot') || 0,
no_bot => 0,
bot_no_follow => 0,
metatags => [],
strict_browser => 0,
anonymous_mode => $Conf::anonymous_mode || 0,
transmitted => 0,
require_terms_of_service => $Conf::require_terms_of_service || 0,
in_request => 0,
js_init_functions => [],
};
bless $self, $class;
# Generate an event if we're tracking this user.
# read in local configuration into global WebConfig
&WebConfig::import_local_config($backend_name);
# create a dbmaster
unless (defined($dbmaster) || $WebConfig::NODB) {
my $error;
($dbmaster, $error) = WebApplicationDBHandle->new();
if ($error) {
print STDERR $@;
}
}
$self->{dbmaster} = $dbmaster;
if ($dbmaster && !$self->anonymous_mode()) {
$self->{session} = $dbmaster->UserSession->create($cgi);
# check if application is registered
my $backend = $dbmaster->Backend->init({ 'name' => $backend_name });
if (ref $backend and $backend->isa('WebServerBackend::Backend')) {
$self->{'backend'} = $backend;
}
else {
$self->{'backend'} = $dbmaster->Backend->create({ 'name' => $backend_name });
}
unless ($self->backend) {
}
} else {
# create a backend stub
my $backend = Backend->new( $backend_name );
{
package Backend;
sub new {
my $self = { name => $_[1] };
bless $self, 'Backend';
}
sub name {
return $_[0]->{name};
}
sub init {
return undef;
}
}
$self->{backend} = $backend;
# create a session stub
my $session = UserSession->new();
{
package UserSession;
sub new {
my $self = { user => undef };
bless $self, 'UserSession';
}
sub add_entry { return undef; }
sub get_entry { return undef; }
sub user { return $_[0]->{user}; }
sub cookie {
my ($self) = @_;
my $uname = '0';
if (defined($self->user)) {
$uname = $self->user->login;
}
return CGI::Cookie->new( -name => 'AnonWebSession',
-value => $uname,
-expires => '+2h' );
}
}
$self->{session} = $session;
}
return $self;
}
#******************************************************************************
#* ACCESSOR METHODS
#******************************************************************************
=pod
=head3 B<default> ()
B<Returns:> a scalar string
Getter for the default attribute. The default attribute determines the initial page
to be displayed if no $cgi->param('page') is given.
=cut
sub default {
return $_[0]->{default};
}
=pod
=head3 B<dbmaster> ()
B<Returns:> a reference to a DBMaster object
Getter for the dbmaster attribute. See above description for details.
=cut
sub dbmaster {
return $_[0]->{dbmaster};
}
=pod
=head3 B<session> ()
B<Returns:> a reference to a WebServerBackend::Session object
Getter for the session attribute. This is an instance of the Session object, which
stores the current user and a history of three last visited pages.
=cut
sub session {
return $_[0]->{session};
}
=pod
=head3 B<cgi> ()
B<Returns:> a reference to a CGI object
Getter for the cgi attribute. This the instance of the CGI object used throughout the
WebApplication.
=cut
sub cgi {
my ($self, $cgi) = @_;
if (defined($cgi)) {
$self->{cgi} = $cgi;
}
return $self->{cgi};
}
=pod
=head3 B<menu> ()
B<Returns:> a reference to a WebMenu object
Getter for the menu attribute. This is an instance of the WebMenu object which stores
the structure of the menu.
=cut
sub menu {
return $_[0]->{menu};
}
=pod
=head3 B<layout> ()
B<Returns:> a reference to a WebLayout object
Getter for the layout attribute. This is an instance of the WebLayout object which
stores required javascript, css and the html template.
=cut
sub layout {
return $_[0]->{layout};
}
=pod
=head3 B<backend> ()
B<Returns:> a reference to a WebServerBackend object
Getter for the backend attribute. This is an instance of the WebServerBackend object
which is used to identify the current application.
=cut
sub backend {
return $_[0]->{'backend'};
}
=pod
=head3 B<url> (I<url>)
B<Returns:> a scalar string
Getter / setter for the url attribute. This will return the name of the cgi script of
this application (e.g. index.cgi).
=cut
sub url {
my ($self, $url) = @_;
if (defined($url)) {
$self->{url} = $url;
}
unless (defined($self->{url})) {
my $cgi = $_[0]->{'cgi'};
$url = $cgi->url(-relative=>1);
$url =~ s/\.cgi.*$/\.cgi/;
$self->{url} = $url
}
return $self->{url};
}
=pod
=head3 B<error> (I<error>)
B<Returns:> a scalar string
Getter / setter for the current error status. If the optional parameter I<error> is
given, the error status is stored in the application. Setting this parameter will cause
the application to not display the current page, but an error page stating this
error message instead.
=cut
sub error {
my ($self, $message) = @_;
if (defined $message) {
$self->{error} = $message;
}
return $self->{error};
}
=pod
=head3 B<page> (I<page>)
B<Returns:> a reference to a WebPage object
Returns a reference to the current WebPage object. If the optional parameter I<page> is
given, the page object is stored in the application.
=cut
sub page {
if ($_[1]) {
$_[0]->{'page'} = $_[1];
}
return $_[0]->{'page'};
}
=pod
=head3 B<show_login_user_info> (I<BOOL>)
B<Returns:> a scalar boolean
Get/set the flag if the login box should be inserted into the user info template. The
default value is false.
=cut
sub show_login_user_info {
if (scalar(@_) > 1) {
$_[0]->{show_login_user_info} = $_[1];
}
return $_[0]->{show_login_user_info};
}
=pod
=head3 B<fancy_login> (I<BOOL>)
B<Returns:> a scalar boolean
Get/set the flag if the fancy login box should be inserted into the user info template. The
default value is false.
=cut
sub fancy_login {
if (scalar(@_) > 1) {
$_[0]->{fancy_login} = $_[1];
}
return $_[0]->{fancy_login};
}
=pod
=head3 B<rights> ()
B<Returns:> a reference to an array of Right objects
Returns a reference to an array of Rights objects this application supports.
=cut
sub rights {
my ($self) = @_;
# check if the rights have been loaded
unless (defined($self->{'rights'})) {
# set the rights
{
no strict;
my $rights_method = $self->backend->name()."::MyAppRights::rights()";
my $rights_module = "require " .$self->backend->name()."::MyAppRights;";
eval($rights_module);
$self->{'rights'} = eval($rights_method);
}
}
return $self->{'rights'};
}
#******************************************************************************
#* WEB COMPONENTS
#******************************************************************************
=pod
=head3 B<register_component> (I<component_name>, I<identifier>)
B<Returns:> a reference to a WebComponent object
Register a web component of the name I<component_name> where I<component_name>
is a module in the WebComponent directory. Web components are re-usable html
blocks to include into web pages like default dialogs, tables, charts and so on.
This method returns a reference to a WebComponent object.
I<identifier> is a unique name which is used to later reference that component.
=cut
sub register_component {
my ($self, $component, $id) = @_;
# require web component
$component = 'WebComponent::'.$component;
{
no strict;
eval "require $component;";
}
# init internal component cache if necessary
unless ($self->{'components'}->{$component}) {
$self->{'components'}->{$component} = [];
}
# check for singleton
my $web_component;
if (scalar(@{$self->{'components'}->{$component}}) && $self->{'components'}->{$component}->[0]->{singleton}) {
# get the existing component
$web_component = $self->{'components'}->{$component}->[0];
} else {
# init new web component
$web_component = $component->new($self, scalar(@{$self->{'components'}->{$component}}), $component);
$web_component->{_id} = $id;
push @{$self->{'components'}->{$component}}, $web_component;
}
# update index
$self->{'component_index'}->{$id} = $web_component;
return $web_component;
}
=pod
=head3 B<component> (I<identifier>)
B<Returns:> a reference to a WebComponent object
Retrieve the web component registered with the unique name I<identifier> from
the component repository of the WebApplication. The method confesses if called
with an unknown identifier.
=cut
sub component {
my ($self, $id) = @_;
unless ($self->{'component_index'}->{$id}) {
return undef;
}
return $self->{'component_index'}->{$id};
}
#******************************************************************************
#* DATA HANDLING
#******************************************************************************
=pod
=head3 B<data_handle> (I<type>, I<options>)
B<Returns:> a reference to an object
Request the DataHandler of the given type I<type>. Some DataHandlers may accept
additional parameters, those can be passed by providing the optional parameter
I<options>.
=cut
sub data_handle {
my ($self, $type, $options) = @_;
# get from internal data cache if possible
unless ($self->{'data_handlers'}->{$type}) {
# require the data handler package
my $package = $self->backend->name().'::DataHandler::'.$type;
{
no strict;
eval "require $package";
my $error = "";
if ($@) {
$error = $@;
$package = 'DataHandler::'.$type;
eval "require $package";
if ($@) {
return undef;
}
}
}
my $data = $package->new($self);
$self->{'data_handlers'}->{$type} = $data;
}
if ($options) {
return $self->{'data_handlers'}->{$type}->handle($options);
}
return $self->{'data_handlers'}->{$type}->handle;
}
#******************************************************************************
#* ACTION MANAGEMENT
#******************************************************************************
=pod
=head3 B<register_action> (I<object>, I<method>, I<trigger>)
B<Returns:> a reference to a WebApplication object
Registers an action with the web application framework. If the WebApplication is
called with the cgi parameter I<action>, it will check if the action has been registered.
If not, it will throw an error. If the action is registered, it's method will be
executed in between WebPage->init and WebPage->output.
=cut
sub register_action {
my ($self, $object, $method, $trigger) = @_;
$self->{'actions'}->{$trigger} = [ $object, $method ];
return $self;
}
=pod
=head3 B<execute_action> ()
Checks if a cgi param parameter 'action' is present and if it is registered as a trigger,
then executes the action (invokes the method on the WebPage or WebComponent object).
=cut
sub execute_action {
my ($self) = @_;
return unless ($self->cgi->param('action'));
my $action = $self->cgi->param('action');
if ($self->{'actions'}->{$action}) {
my ($object, $method) = @{$self->{'actions'}->{$action}};
if (ref $object and $method) {
my $result = $object->$method();
push @{$self->{'actions'}->{$action}}, $result;
}
}
else {
$self->error("This page was called with an unregistered action parameter '".
$self->cgi->param('action')."'.");
}
}
=pod
=head3 B<get_action_result> (I<trigger>)
B<Returns:> whatever the according action method returns
Return the result of an action registered with the trigger I<trigger>. If the
action has not been executed this will return undef.
=cut
sub get_action_result {
my ($self, $trigger) = @_;
if ($self->{'actions'}->{$trigger}) {
return $self->{'actions'}->{$trigger}->[2];
}
}
#******************************************************************************
#* APPLICATION MESSAGES
#******************************************************************************
=pod
=head3 B<add_message> (I<msg_type>, I<message>)
B<Returns:> a reference to a WebApplication object
Adds a message with the content of I<message> to the output of the page. The
message type I<msg_type> determines the css formatting and position of the
html output.
The following message type are recognised: 'warning', 'info'.
=cut
sub add_message {
my ($self, $type, $msg, $fadetimer) = @_;
# check type
# check msg
unless ($msg) {
print STDERR "Empty message in method add_message.";
$msg = '';
}
# init message type if necessary
unless ($self->{'messages'}->{$type}) {
$self->{'messages'}->{$type} = [];
}
my $fade_flag = 1;
foreach(@{$self->{'messages'}->{$type}}){
if($_ =~ /onload/){
$fade_flag = 0;
}
}
if($fadetimer && $fade_flag){
my $div_id;
if ($type eq 'warning'){
$div_id = 'warning';
} else {
$div_id = 'info';
}
$msg .= "<img src=\"$Conf::cgi_url/Html/clear.gif\" onload='fade(\"" . $div_id . "\", ". $fadetimer . ");'>";
}
push @{$self->{'messages'}->{$type}}, $msg;
return $self;
}
=pod
=head3 B<get_messages> (I<msg_type>)
B<Returns:> a scalar string
Returns an array reference to all message of the type I<msg_type>.
The following message type are recognised: 'warning', 'info'.
=cut
sub get_messages {
my ($self, $type) = @_;
my $msg = [];
# get messages of that type
if ($self->{'messages'}->{$type}) {
$msg = $self->{'messages'}->{$type};
}
return $msg;
}
#******************************************************************************
#* PAGE REDIRECTION
#******************************************************************************
=pod
=head3 B<redirect> (I<page>)
B<Returns:> a scalar string
Request a redirect to another WebApplication page. I<params> is mandatory
and expects either the name of a page module or a hash containing the page
module name and the frozen cgi parameters
=cut
sub redirect {
my ($self, $params) = @_;
if ($params) {
if (ref($params) eq 'HASH') {
$self->{redirect} = $params;
unless (defined($params->{page}) && length($params->{page})) {
$self->{redirect}->{page} = $self->default;
}
} else {
$self->{redirect} = { page => $params };
}
}
return $self->{redirect};
}
=pod
=head3 B<do_redirect> ()
Executes the actual redirect to another WebPage available in the current WebApplication.
If the page redirected from is omitted from the session, the redirect will flush all
CGI parameters before the redirect.
If the redirect is with frozen CGI parameters, tose CGI parameters are restored.
=cut
sub do_redirect {
my ($self) = @_;
# check if we have at least a page to redirect to
unless ($self->redirect->{page}) {
die "redirect called without page to redirect to.\n";
}
# check for recursive call of redirect
if ($self->{last_redirect} && ($self->{last_redirect} eq $self->redirect->{page})) {
die "recursive call of redirect.\n";
}
# clear cgi params from omitted pages
$self->cgi->delete_all() if ($self->page->omit_from_session);
# set up new cgi data
if ($self->redirect->{parameters}) {
$self->cgi->delete_all();
my @t = thaw($self->redirect->{parameters});
my $params = $t[0];
foreach my $p (keys(%$params)) {
$self->cgi->param( -name => $p, -values => $params->{$p});
}
}
# set the page parameter
$self->cgi->param('page', $self->redirect->{page});
# reset application and re-run
$self->{last_redirect} = $self->redirect->{page};
$self->reset_application;
$self->run;
}
=pod
=head3 B<reset_application> ()
Resets all internal variables of the WebApplication except for already generated
messages. This will also restore the default menu from the backup copy.
=cut
sub reset_application {
my $self = shift;
my ( $menu ) = thaw( $self->{'menu_backup'} );
$self->{'menu'} = $menu;
$self->{'error'} = undef;
$self->{'redirect'} = undef;
$self->{'components'} = {};
$self->{'component_index'} = {};
$self->{'actions'} = {};
}
#******************************************************************************
#* CONTENT GENERATION
#******************************************************************************
=pod
=head3 B<check_for_maintenance> (I<read_maintenance_msg_flag>)
B<Returns:> an array of $flag and $msg or a scalar string
Returns true if the server is locked down for maintenance. The method checks
for the presence of a I<Backend_name>.disabled file at the location of the
script running the WebApplication.
If the optional parameter I<read_maintenance_msg_flag> is provided and true,
the method will read out the content of the file and return it. This is used
by the Maintenance page to disabled a non default maintenance notification.
=cut
sub check_for_maintenance {
my $disabled = $_[0]->backend->name.".disabled";
my $flag = (-e $disabled);
my $msg;
if ($flag and $_[1]) {
open(MSG, "$disabled");
$msg = <MSG>;
close(MSG);
return ($flag, $msg);
}
return $flag;
}
=pod
=head3 B<check_for_silent_login> ()
This method checks for the presence of the CGI parameter I<silent_login>
to allow authenticating as a user from an URL. If present, this CGI param
will be read as loginname:password and the WebApplication tries to login
as that user.
=cut
sub check_for_silent_login {
if ($_[0]->cgi->param('silent_login')) {
$_[0]->cgi->param('silent_login') =~ /^([^:.]+)\:(.+)$/ ;
my $user = $_[0]->dbmaster->User->init( { login => $1 } );
if (ref $user and $user->active and
crypt($2, $user->password) eq $user->password) {
$_[0]->session->user($user);
warn "Silent authentication successful: $1\n";
}
else {
warn "Silent authentication failed: $1\n";
}
}
}
=pod
=head3 B<check_for_anonymous_login> ()
This method checks for the presence of the CGI parameter I<anonymous_login>
to keep the chosen name of the current user if the application is running in
anonymous mode.
=cut
sub check_for_anonymous_login {
my ($self) = @_;
return undef unless $self->anonymous_mode;
my $cgi = $self->cgi;
my $cookie = $cgi->cookie('AnonWebSession');
my $uname = $cgi->param('anonymous_login') || $cookie;
if ($uname) {
if ($uname eq 'logout') {
$self->session->{user} = undef;
} else {
$self->session->{user} = User->new( $uname );
{
package User;
sub new {
my $self = { firstname => $_[1] };
bless $self, 'User';
}
sub has_right { return 1; }
sub firstname { return $_[0]->{firstname}; }
sub lastname { return ''; }
sub login { return $_[0]->{firstname}; }
sub has_right_to { return []; }
sub get_user_scope { return {} };
sub is_admin { return 0; }
sub _id { return undef; }
}
}
}
# create a dbmaster stub
my $dbmaster = Local::DBMaster->new( $self );
{
package Local::DBMaster;
sub new {
my $self = { application => $_[1],
session => $_[1]->session };
bless $self, 'Local::DBMaster';
}
sub Preferences {
return Preferences->new( $_[0]->{session} );
}
sub Rights {
return Rights->new();
}
sub Backend {
return $_[0]->{application}->{backend};
}
package Preferences;
sub new {
my $self = { session => $_[1] };
bless $self, 'Preferences';
}
sub get_objects {
if ($_[1]->{name} && $_[1]->{name} eq 'SeedUser') {
return [ Preference->new( $_[0]->{session} ) ];
} else {
return [];
}
}
sub create {
return undef;
}
package Preference;
sub new {
my $self = { session => $_[1] };
bless $self, 'Preference';
}
sub name {
my $name = '';
if ($_[0]->value) {
$name = 'SeedUser';
}
return $name;
}
sub value {
my ($self) = @_;
my $user = 0;
if ($self->{session}->user) {
$user = $self->{session}->user->login;
}
return $user;
}
package Rights;
sub new {
my $self = {};
bless $self, 'Rights';
}
sub get_objects {
return [];
}
sub create {
return Right->new;
}
package Right;
sub new {
my $self = {};
bless $self, 'Right';
}
}
$self->{dbmaster} = $dbmaster;
return;
}
=pod
=head3 B<check_rights> ()
This method takes a rights array and checks if the user has all the necessary
rights to proceed. If no user is logged in, the method redirects to the login
page, if the user is missing a right an error page will be shown. If everything
is fine, it will return true.
The run method automatically calls this method with the page required rights
as input.
=cut
sub check_rights {
my ($self, $rights) = @_;
if(scalar(@$rights)) {
unless ($self->session->user) {
$self->redirect('Login');
$self->do_redirect();
die 'cgi_exit';
}
else {
my $loginName = $self->session->user->login;
foreach my $right (@$rights) {
unless ($self->session->user->has_right($self, $right->[0], $right->[1], $right->[2], $right->[3])) {
$self->error( "Sorry, but you are lacking the rights required for this page." );
last;
}
}
}
}
return $self;
}
=pod
=head3 B<check_requirements> ()
This method queries the WebPage and WebComponents for javascript and/or css
requirements and adds those files to the page output.
=cut
sub check_requirements {
my ($self) = @_;
# build a hash over all required css and javascript files
# to make sure to include each file only once
my $css = {};
my $js = {};
my $orderedCSS = [];
my $orderedJS = [];
my $addedCSS = {};
my $addedJS = {};
# include IE compatibility script and style
my $user_agent = $ENV{HTTP_USER_AGENT};
if ($user_agent && $user_agent =~ /MSIE/) {
$self->layout->add_css_reverse("$Conf::cgi_url/Html/ie7-css.css");
$js->{"$Conf::cgi_url/Html/ie7-standard-p.js"} = 1;
}
# include message fade script
$js->{"$Conf::cgi_url/Html/fade.js"} = 1;
# Depth-first addition of ordered JS and CSS files
my $obj = $self->page();
my $tail = [];
do {
while ( defined($obj->{'childComponents'}) &&
@{$obj->{'childComponents'}} > 0 ) {
push(@$tail, $obj);
$obj = shift @{$obj->{'childComponents'}};
} # bottoming out at deepest component, add CSS, JS
foreach my $cssFile (@{$obj->{'_orderedCSS'}}) {
unless(defined($addedCSS->{$cssFile})) {
push(@$orderedCSS, $cssFile);
$addedCSS->{$cssFile} = 1;
}
}
foreach my $jsFile (@{$obj->{'_orderedJS'}}) {
unless(defined($addedJS->{$jsFile})) {
push(@$orderedJS, $jsFile);
$addedJS->{$jsFile} = 1;
}
}
$obj = pop(@$tail); # then begin climbing back up
} while ( defined($obj) ); # until we reach the top
# check page requirements
foreach (@{$self->page->require_css}) {
$css->{$_} = 1;
}
foreach (@{$self->page->require_javascript}) {
$js->{$_} = 1;
}
# check components requirements
foreach my $type (keys %{$self->{'components'}}) {
foreach my $component (@{$self->{'components'}->{$type}}) {
if ($component->require_css) {
$css->{$component->require_css} = 1;
}
foreach (@{$component->require_javascript}) {
$js->{$_} = 1;
}
}
}
# generate css / js head block
foreach (keys %$css) {
$self->layout->add_css($_);
}
foreach (@$orderedCSS) {
$self->layout->add_css($_);
}
foreach (keys %$js) {
$self->layout->add_javascript($_);
}
foreach (@$orderedJS) {
$self->layout->add_javascript($_);
}
}
# checks whether the current browser is supported
sub check_browser {
my $user_agent = $ENV{HTTP_USER_AGENT};
# check for each of the supported browsers
if ($user_agent &&
(
(($user_agent =~ /Firefox\/(\d+)/) && $1 > 1) ||
(($user_agent =~ /Chrome\/(\d+\.\d+)/) && $1 > 0.2) ||
($user_agent =~ /Safari/) ||
(($user_agent =~ /MSIE (\d+\.\d+)/) && $1 > 5))) {
return (1, '');
} else {
return (0, "You are using an unsupported browser. Some of the features of this application may not be available. We are currently developing for Firefox 2.x, Safari 2.x, MS InternetExplorer 6.x, Chrome 0.2, and higher versions.");
}
}
sub check_browser_strict {
my ($self) = @_;
my $user_agent = $ENV{HTTP_USER_AGENT};
my $ua = '';
if ($user_agent =~ /Chrome\/(\d+\.\d+)/) {
$ua = "Chrome";
} elsif ($user_agent =~ /MSIE (\d+\.\d+)/) {
$ua = "Microsoft Internet Explorer";
} elsif ($user_agent =~ /Safari/) {
$ua = "Safari";
} else {
$ua = "an unknown browser";
}
# check for each of the supported browsers
if ($user_agent =~ /Firefox\/(\d+)/) {
return (1, '');
} else {
my $popup = "<img src='./Html/clear.gif' onload='if (! confirm(\"This application has been optimized for the Firefox browser. Since you are using $ua, many features will not be available and / or behave incorrectly. Click OK to continue or CANCEL to download Firefox.\")){window.top.location=\"http://www.mozilla.org/firefox/\";}'>";
if ($self->session->user && scalar(@{$self->dbmaster->Preferences->get_objects( { user => $self->session->user, name => 'confirm_proceed_non_ff_browser', value => 1 } )})) {
$popup = "";
}
return (0, "$popup This application has been optimized for the Firefox browser. Since you are using $ua, many features will not be available and / or behave incorrectly.<br><br>Firefox is freely available <a href='http://www.mozilla.org/firefox/'>here</a>.");
}
}
=pod
=head3 B<get_user_info> ()
B<Returns:> a scalar string
Return the content of the user info template. This will display a link to the user
management page, a logout button and the full name of the user if a user is logged
in, otherwise a login and password form.
=cut
sub get_user_info {
my ($self) = @_;
my $session = $self->session;
my $info = '';
if ($session->user) {
if ($self->fancy_login) {
$info .= "<div id='user'>";
$info .= "<div style='float:left; padding-top:4px; color: #8FBC3F; font-size: 1.4em;'>".$session->user->firstname . " " . $session->user->lastname."</div><div style='float:left;'>";
if ($session->user->has_right($self, 'edit', 'user', $session->user->_id) && ! $self->anonymous_mode ) {
$info .= "<a href='".$self->url."?page=AccountManagement'><img class='imglink' style='padding-left: 10px; height:20px;' src='".IMAGES.
"mg-account.png' title='Account Management' /></a>\n";
}
if ($self->anonymous_mode) {
$info .= "<a href='".$self->url."?anonymous_login=logout'></a>";
} else {
$info .= "<a href='".$self->url."?page=Logout'><img class='imglink' style='height:20px;' src='".IMAGES."mg-logout.png' title='Logout' /></a>\n";
}
$info .= "</div></div>";
} elsif (0) { # compact
my $username = $session->user->firstname . " " . $session->user->lastname;
$info .= "<div id='menu'><ul id='nav'><li><div>$username</div>";
$info .= "<ul>";
if ($session->user->has_right($self, 'edit', 'user', $session->user->_id) && ! $self->anonymous_mode ) {
$info .= "<li><a href='".$self->url."?page=AccountManagement'>Manage Account</a></li>";
}
$info .= "<li>";
if ($self->anonymous_mode) {
$info .= "<a href='".$self->url."?anonymous_login=logout'>Log out</a>\n";
} else {
$info .= "<a href='".$self->url."?page=Logout'>Log out</a>\n";
}
$info .= "</li></ul></div>\n";
} else {
$info .= "<div id='user'>";
if ($session->user->has_right($self, 'edit', 'user', $session->user->_id) && ! $self->anonymous_mode ) {
$info .= "<a href='".$self->url."?page=AccountManagement'><img class='imglink' src='".IMAGES.
"wac_people.png' title='Account Management' /></a>\n";
}
if ($self->anonymous_mode) {
$info .= "<a href='".$self->url."?anonymous_login=logout'><img class='imglink' src='".IMAGES."wac_logout.png' title='Logout' /></a>\n";
} else {
$info .= "<a href='".$self->url."?page=Logout'><img class='imglink' src='".IMAGES."wac_logout.png' title='Logout' /></a>\n";
}
$info .= $session->user->firstname . " " . $session->user->lastname;
$info .= "</div>";
}
}
else {
if ($self->show_login_user_info) {
$info .= "<div id='login'>";
if ($self->anonymous_mode) {
$info .= $self->page->start_form('login_form', { page => $self->default });
$info .= "<input type='text' title='Enter your login name here.' name='anonymous_login'>";
$info .= "<input type='submit' value='login' style='width:40px;cursor: pointer;' title='Click here to login!'>\n" .$self->page->end_form();
} elsif ($self->fancy_login) {
my $formstart = undef;
eval {
use Conf;
if ($Conf::secure_url) {
$formstart = "<form method='post' id='login_form' enctype='multipart/form-data' action='".$Conf::secure_url.$self->url()."' style='margin: 0px; padding: 0px;'>\n".$self->cgi->hidden(-name=>'action', -id=>'action', -value=>'perform_login', -override=>1).$self->cgi->hidden(-name=>'page', -id=>'page', -value=>'Login', -override=>1);
}
};
if (! $formstart) {
$formstart = $self->page->start_form('login_form', { action => 'perform_login', 'page' => 'Login' });
}
$info .= $formstart;
$info .= "<div id='login_box'><div id='login_left_txt'>EXISTING USERS »</div>";
$info .= "<div id='login_input_box'><div id='login_input_header'>LOGIN<a class='forgot' href='?page=Register' style='margin-left:32px;' title='click to register a new account'>REGISTER</a></div><div id='login_input_box'><input type='text' title='Enter your login name here.' name='login'></div></div>";
$info .= "<div id='login_input_box'>";
$info .= "<div>";
$info .= "<div style='float: left;' id='login_input_header'>PASSWORD</div><div id='login_input_header_forgot'><a class='forgot' href='?page=RequestNewPassword'>FORGOT?</a></div>";
$info .= "</div>";
$info .= "<div id='login_input_box'><input type='password' title='Enter your password.' name='password'></div></div>";
$info .= "<div id='login_submit'><input type='submit' value='login' style='margin-right: 0; width:45px;cursor: pointer;' title='Click here to login!'></div>";
# $info .= "<img src='./Html/google_login.jpg' style='cursor: pointer; width: 22px; height: 22px; margin-left: 5px; margin-top: 13px;' title='login via your google account' onclick='window.top.location=\"test.cgi\"'>";
$info .= "</div>" .$self->page->end_form();
} else {
$info .= $self->page->start_form('login_form', { page => 'Login', action => 'perform_login' });
$info .= "<input type='text' title='Enter your login name here.' name='login'> ".
"<input type='password' title='Enter your password.' name='password'>\n";
$info .= "<input type='submit' value='login' style='width:40px;cursor: pointer;' title='Click here to login!'>\n" .$self->page->end_form();
}
$info .= "</div>";
}
}
return $info;
}
=pod
=head3 B<page_title_prefix> ()
B<Returns:> a scalar string
Gets / sets the prefix for the title of every displayed page.
=cut
sub page_title_prefix {
my ($self, $prefix) = @_;
if (defined($prefix)) {
$self->{page_title_prefix} = $prefix;
}
return $self->{page_title_prefix};
}
=pod
=head3 B<run> ()
B<Returns:> 1
Produces the web page output.
Note that unless the caller has set the C<no_site_meter> member, the tracking code will be
added to the content.
=cut
sub run {
my $self = shift;
# sanity check on cgi param 'page'
my $page = $self->default;
if ( $self->cgi->param('page') and
$self->cgi->param('page') =~ /^\w+$/ ) {
$page = $self->cgi->param('page');
}
# immediate redirect to maintenance page if
# file 'application_backend_name.disabled' is present in apache doc root
$page = "Maintenance" if $self->check_for_maintenance();
# check for silent login
$self->check_for_silent_login();
# check for anonymous login
$self->check_for_anonymous_login();
# check for terms of service
if ($self->require_terms_of_service && $self->session->user && $page ne "TermsofService" && $page ne "Logout") {
my $pref = $self->dbmaster->Preferences->get_objects( { user => $self->session->user,
name => 'AgreeTermsOfService' } );
unless (scalar(@$pref) && $pref->[0]->value && $self->require_terms_of_service <= $pref->[0]->value) {
$page = "TermsofService";
}
}
# require the web page package
my $package = $self->backend->name().'::WebPage::'.$page;
{
no strict;
eval "require $package";
if ($@) {
my $possible_error = $@;
my $last_error = $!;
$package = 'WebPage::'.$page;
eval "require $package";
if ($@) {
print STDERR "Loading package '$package' failed: $possible_error \n";
print STDERR "Fallback to default failed: $@ \n";
print STDERR "Last errors: $! \n";
print STDERR "$last_error \n";
if ($Conf::developer_mode)
{
$self->error("<h2>Error loading page module for $page.</h2>\n$@");
}
else
{
$self->error( "Sorry, but the page '$page' was not found.");
}
}
}
}
my $content;
unless ($self->error) {
# init the requested web page object
$self->page($package->new($self));
unless (ref $self->page) {
$self->error( "Sorry, unable to initialize page object '$package'.\n" );
}
# initialize the page
$self->page->init;
# write to session
unless ($self->page->omit_from_session) {
$self->session->add_entry();
}
# check for required rights
$self->check_rights($self->page->required_rights);
unless ($self->error) {
# execute actions
$self->execute_action();
# if either the page init or the executed actions
# require a redirect, do it now
if ($self->redirect) {
$self->do_redirect();
return;
}
else {
# if this is the default page and there is a message of the day
# file, add an info box with the content of the motd
my $motd_file = $self->backend->name.".motd";
if (($self->page->name eq $self->default) && -f $motd_file) {
if (open(FILE, $motd_file)) {
my $msg = "";
while (<FILE>) {
$msg .= $_;
}
close FILE;
$self->add_message('info', $msg);
} else {
print STDERR "Could not open message of the day file: $@\n";
}
}
# check for browser support
if ($self->page->name eq $self->default) {
my ($supported, $msg);
if ($self->strict_browser) {
($supported, $msg) = $self->check_browser_strict();
} else {
($supported, $msg) = $self->check_browser();
}
unless ($supported) {
$self->add_message('warning', $msg);
}
}
# generate the page content;
# this is done here to allow the page to change the
# application and session during runtime
eval { $content = $self->page->output; };
if ($@) {
my $error = $@;
if ($Conf::developer_mode) {
$self->error("<h2>Error generating page output for $page.</h2>\n$error");
}
}
# checking for any js calls via the JSCaller Web Component
if (defined($self->{components}->{'WebComponent::JSCaller'})) {
# then append the calls to the content (this only adds hidden info)
$content .= $self->{components}->{'WebComponent::JSCaller'}->[0]->generate_html();
}
}
}
}
# load error page if necessary
if ($self->error) {
$self->page( WebPage::Error->new($self) );
$content = $self->page->output;
}
# check the requirements
$self->check_requirements();
# diable cacheing
$self->layout->add_metatag( '<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">' );
$self->layout->add_metatag( '<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">' );
# check if we are a robot
if ($self->bot) {
if ($self->no_bot) {
$self->layout->add_metatag( '<meta name="robots" content="noindex,nofollow" />' );
}
if ($self->bot_no_follow) {
$self->layout->add_metatag( '<meta name="robots" content="nofollow" />' );
}
foreach my $tag (@{$self->metatags}) {
$self->layout->add_metatag( '<meta name="'.$tag->{key}.'" content="'.$tag->{value}.'" />' );
}
} else {
# Not a bot, so we want site meter code in. Check for the site meter override.
# add no-robot to the header, since this is not one of our recognized robots
$self->layout->add_metatag( '<meta name="robots" content="noindex,nofollow" />' );
}
$self->layout->set_page($page);
# fill the layout
my $initialize_all = qq~<script>function initialize_all () {
~;
foreach my $call (@{$self->js_init_functions()}) {
$initialize_all .= $call."\n";
}
$initialize_all .= qq~
}</script>~;
$self->layout->set_content( { title => $self->page_title_prefix . $self->page->title,
pagetitle => ($self->page->{icon}||"").$self->page->title,
content => $initialize_all.$content,
warnings => $self->get_messages('warning'),
info => $self->get_messages('info'),
menu => $self->menu->output($self),
user => $self->get_user_info(),
} );
# Print the output. We only do this once. If we hit this code a second
# time, it means a redirect took place, and we only want the redirect's
# output, not ours.
unless ($self->{transmitted}) {
$self->{transmitted} = 1;
print $self->cgi->header( -cookie => [ $self->session->cookie ], -charset => 'UTF-8' );
my $output = $self->layout->output;
print $output;
}
}
sub metatags {
my ($self, $key, $value) = @_;
if ($key && $value) {
push(@{$self->{metatags}}, { key => $key, value => $value } );
}
return $self->{metatags};
}
=pod
=head3 B<bot> ()
B<Returns:> boolean
Finds out whether the user agent is a robot / spider
=cut
sub bot {
my ($self) = @_;
my $agent = $ENV{HTTP_USER_AGENT};
my $allowed_bots = ['Google','msnbot','Rambler','Yahoo','AbachoBOT','accoona','AcoiRobot','ASPSeek','CrocCrawler','Dumbot','FAST-WebCrawler','GeonaBot','Gigabot','Lycos','MSRBOT','Scooter','AltaVista','IDBot','eStyle','Scrubby'];
foreach my $bot (@$allowed_bots) {
if ($agent =~ /$bot/i) {
return 1;
}
}
if ($self->test_bot) {
return 1;
}
return 0;
}
=pod
=head3 B<bot_no_follow> ()
B<Returns:> boolean
Gets / sets whether a bot should follow the links on this page
=cut
sub bot_no_follow {
my ($self, $no_follow) = @_;
if (defined($no_follow)) {
$self->{bot_no_follow} = $no_follow;
}
return $self->{bot_no_follow};
}
=pod
=head3 B<test_bot> ()
B<Returns:> boolean
Sets test_bot status. If set to true, any user agent will be interpreted as being a robot.
This can be used to test pages for robot compliance. Also returns the current status of the
variable.
=cut
sub test_bot {
my ($self, $test) = @_;
if (defined($test)) {
$self->{test_bot} = $test;
}
return $self->{test_bot};
}
=pod
=head3 B<no_bot> ()
B<Returns:> boolean
Sets no_bot status. If set to true, the metatag to exclude robots from this page will be set.
Also returns the current status of the
variable.
=cut
sub no_bot {
my ($self, $no_bot) = @_;
if (defined($no_bot)) {
$self->{no_bot} = $no_bot;
}
return $self->{no_bot};
}
=pod
=head3 B<button> ($value, %options)
Returns the html for a submit button. The position parameter is the button value
(default C<Submit>). Any other properties can be added as part of the options hash.
No leading C<-> is necessary on the option name. Thus,
$page->button('OK', name => 'frog')
will generate a button with a value of C<OK> and a name of C<frog>. Use this method
instead of CGI methods or raw literals in order to automatically include the button
style class.
To generate a pure button (as opposed to a submit button), specify
type => 'button'
in the options.
=cut
sub button {
my ($self, $value, %options) = @_;
my $realValue = $value || "Submit";
my $retVal;
my $type = $options{type} || "";
if ($type eq 'button') {
delete $options{type};
$retVal = CGI::button({ class => 'button', value => $value, %options });
} else {
$retVal = CGI::submit({ class => 'button', value => $value, %options });
}
return $retVal;
}
=head3 createAttributeList
my @list = $app->createAttributeList(\@counts, @valuesAndDefaults);
Create an attribute list for a web component or page. The attribute list
is a list of [name, value] pairs. We only want to include attributes that
have a nonzero count, and this method performs the necessary checks.
For example
my @list = $app->createAttributeList([$apples, $oranges],
Apples => 1, Oranges = 0);
will return a list of zero, one, or two elements. If both I<$apples> and
I<$oranges> are nonzero, then it will return
[Apples, 1], [Oranges, 0]
If I<$oranges> is nonzero and I<$apples> is zero, it will return
[Organges, 0]
=over 4
=item counts
A reference to a list of counts. For each value, the number of objects with that
value is placed in this list, in the order
=item valuesAndDefaults
A list of value names and default values. The list order must match the order of
the I<counts> list.
=item RETURN
Returns a list of 2-tuples, each one containing a value name and a default for
a value with a nonzero count.
=back
=cut
sub createAttributeList {
# Get the parameters.
my ($self, $counts, @valuesAndDefaults) = @_;
# Declare the return variable.
my @retVal = ();
# Stack the counts. We will pop them off to get them in the desired order.
my @stack = reverse @$counts;
# Loop through the list of counts.
for (my $i = 0; $i <= $#valuesAndDefaults; $i += 2) {
my $count = pop @stack;
if ($count) {
push @retVal, [$valuesAndDefaults[$i], $valuesAndDefaults[$i+1]];
}
}
# Return the result.
return @retVal;
}
=pod
=head3 B<anonymous_mode> ($value)
Getter / setter for the anonymous mode. In this mode the user only needs to register with a login name and without a password. The user will have all possible rights. This mode should be used with extreme care!
=cut
sub anonymous_mode {
my ($self, $value) = @_;
if (defined $value) {
$self->{anonymous_mode} = $value;
}
return $self->{anonymous_mode};
}
=pod
=head3 B<require_terms_of_service> ($value)
Getter / setter for whether the current application requires the user to agree to the terms of service for parts of the application that require a login.
=cut
sub require_terms_of_service {
my ($self, $require) = @_;
if (defined($require)) {
$self->{require_terms_of_service} = $require;
}
return $self->{require_terms_of_service};
}
#******************************************************************************
#* DEBUG AND TESTING
#******************************************************************************
sub _dump {
my $self = shift;
require Data::Dumper;
my $layout = $self->layout;
$self->{layout} = undef;
my $dump = '<p><pre>'.Data::Dumper->Dump([ $self ]).'</pre></p>';
$self->{layout} = $layout;
return $dump;
}
sub strict_browser {
my ($self, $strict) = @_;
if (defined($strict)) {
$self->{strict_browser} = $strict;
}
return $self->{strict_browser};
}
sub js_init_functions {
my ($self) = @_;
return $self->{js_init_functions};
}
| 24.847584 | 338 | 0.605177 |
ed3ef5135f32427b6d1f531be8f15b61fab6077f | 11,543 | pm | Perl | assets/PortableGit/usr/share/perl5/core_perl/TAP/Parser/Scheduler.pm | ther3tyle/git-it-electron | d808d9ce9f95ffebe39911e57907d72f4653ff6e | [
"BSD-2-Clause"
]
| 4,499 | 2015-05-08T04:02:28.000Z | 2022-03-31T20:07:15.000Z | assets/PortableGit/usr/share/perl5/core_perl/TAP/Parser/Scheduler.pm | enterstudio/git-it-electron | b101d208e9a393e16fc4368e205275e5dfc6f63e | [
"BSD-2-Clause"
]
| 261 | 2015-05-09T03:09:24.000Z | 2022-03-25T18:35:53.000Z | assets/PortableGit/usr/share/perl5/core_perl/TAP/Parser/Scheduler.pm | enterstudio/git-it-electron | b101d208e9a393e16fc4368e205275e5dfc6f63e | [
"BSD-2-Clause"
]
| 1,318 | 2015-05-09T02:16:45.000Z | 2022-03-28T11:10:01.000Z | package TAP::Parser::Scheduler;
use strict;
use warnings;
use Carp;
use TAP::Parser::Scheduler::Job;
use TAP::Parser::Scheduler::Spinner;
=head1 NAME
TAP::Parser::Scheduler - Schedule tests during parallel testing
=head1 VERSION
Version 3.35
=cut
our $VERSION = '3.35';
=head1 SYNOPSIS
use TAP::Parser::Scheduler;
=head1 DESCRIPTION
=head1 METHODS
=head2 Class Methods
=head3 C<new>
my $sched = TAP::Parser::Scheduler->new(tests => \@tests);
my $sched = TAP::Parser::Scheduler->new(
tests => [ ['t/test_name.t','Test Description'], ... ],
rules => \%rules,
);
Given 'tests' and optional 'rules' as input, returns a new
C<TAP::Parser::Scheduler> object. Each member of C<@tests> should be either a
a test file name, or a two element arrayref, where the first element is a test
file name, and the second element is a test description. By default, we'll use
the test name as the description.
The optional C<rules> attribute provides direction on which tests should be run
in parallel and which should be run sequentially. If no rule data structure is
provided, a default data structure is used which makes every test eligible to
be run in parallel:
{ par => '**' },
The rules data structure is documented more in the next section.
=head2 Rules data structure
The "C<rules>" data structure is the the heart of the scheduler. It allows you
to express simple rules like "run all tests in sequence" or "run all tests in
parallel except these five tests.". However, the rules structure also supports
glob-style pattern matching and recursive definitions, so you can also express
arbitarily complicated patterns.
The rule must only have one top level key: either 'par' for "parallel" or 'seq'
for "sequence".
Values must be either strings with possible glob-style matching, or arrayrefs
of strings or hashrefs which follow this pattern recursively.
Every element in an arrayref directly below a 'par' key is eligible to be run
in parallel, while vavalues directly below a 'seq' key must be run in sequence.
=head3 Rules examples
Here are some examples:
# All tests be run in parallel (the default rule)
{ par => '**' },
# Run all tests in sequence, except those starting with "p"
{ par => 't/p*.t' },
# Run all tests in parallel, except those starting with "p"
{
seq => [
{ seq => 't/p*.t' },
{ par => '**' },
],
}
# Run some startup tests in sequence, then some parallel tests than some
# teardown tests in sequence.
{
seq => [
{ seq => 't/startup/*.t' },
{ par => ['t/a/*.t','t/b/*.t','t/c/*.t'], }
{ seq => 't/shutdown/*.t' },
],
},
=head3 Rules resolution
=over 4
=item * By default, all tests are eligible to be run in parallel. Specifying any of your own rules removes this one.
=item * "First match wins". The first rule that matches a test will be the one that applies.
=item * Any test which does not match a rule will be run in sequence at the end of the run.
=item * The existence of a rule does not imply selecting a test. You must still specify the tests to run.
=item * Specifying a rule to allow tests to run in parallel does not make the run in parallel. You still need specify the number of parallel C<jobs> in your Harness object.
=back
=head3 Glob-style pattern matching for rules
We implement our own glob-style pattern matching. Here are the patterns it supports:
** is any number of characters, including /, within a pathname
* is zero or more characters within a filename/directory name
? is exactly one character within a filename/directory name
{foo,bar,baz} is any of foo, bar or baz.
\ is an escape character
=cut
sub new {
my $class = shift;
croak "Need a number of key, value pairs" if @_ % 2;
my %args = @_;
my $tests = delete $args{tests} || croak "Need a 'tests' argument";
my $rules = delete $args{rules} || { par => '**' };
croak "Unknown arg(s): ", join ', ', sort keys %args
if keys %args;
# Turn any simple names into a name, description pair. TODO: Maybe
# construct jobs here?
my $self = bless {}, $class;
$self->_set_rules( $rules, $tests );
return $self;
}
# Build the scheduler data structure.
#
# SCHEDULER-DATA ::= JOB
# || ARRAY OF ARRAY OF SCHEDULER-DATA
#
# The nested arrays are the key to scheduling. The outer array contains
# a list of things that may be executed in parallel. Whenever an
# eligible job is sought any element of the outer array that is ready to
# execute can be selected. The inner arrays represent sequential
# execution. They can only proceed when the first job is ready to run.
sub _set_rules {
my ( $self, $rules, $tests ) = @_;
# Convert all incoming tests to job objects.
# If no test description is provided use the file name as the description.
my @tests = map { TAP::Parser::Scheduler::Job->new(@$_) }
map { 'ARRAY' eq ref $_ ? $_ : [ $_, $_ ] } @$tests;
my $schedule = $self->_rule_clause( $rules, \@tests );
# If any tests are left add them as a sequential block at the end of
# the run.
$schedule = [ [ $schedule, @tests ] ] if @tests;
$self->{schedule} = $schedule;
}
sub _rule_clause {
my ( $self, $rule, $tests ) = @_;
croak 'Rule clause must be a hash'
unless 'HASH' eq ref $rule;
my @type = keys %$rule;
croak 'Rule clause must have exactly one key'
unless @type == 1;
my %handlers = (
par => sub {
[ map { [$_] } @_ ];
},
seq => sub { [ [@_] ] },
);
my $handler = $handlers{ $type[0] }
|| croak 'Unknown scheduler type: ', $type[0];
my $val = $rule->{ $type[0] };
return $handler->(
map {
'HASH' eq ref $_
? $self->_rule_clause( $_, $tests )
: $self->_expand( $_, $tests )
} 'ARRAY' eq ref $val ? @$val : $val
);
}
sub _glob_to_regexp {
my ( $self, $glob ) = @_;
my $nesting;
my $pattern;
while (1) {
if ( $glob =~ /\G\*\*/gc ) {
# ** is any number of characters, including /, within a pathname
$pattern .= '.*?';
}
elsif ( $glob =~ /\G\*/gc ) {
# * is zero or more characters within a filename/directory name
$pattern .= '[^/]*';
}
elsif ( $glob =~ /\G\?/gc ) {
# ? is exactly one character within a filename/directory name
$pattern .= '[^/]';
}
elsif ( $glob =~ /\G\{/gc ) {
# {foo,bar,baz} is any of foo, bar or baz.
$pattern .= '(?:';
++$nesting;
}
elsif ( $nesting and $glob =~ /\G,/gc ) {
# , is only special inside {}
$pattern .= '|';
}
elsif ( $nesting and $glob =~ /\G\}/gc ) {
# } that matches { is special. But unbalanced } are not.
$pattern .= ')';
--$nesting;
}
elsif ( $glob =~ /\G(\\.)/gc ) {
# A quoted literal
$pattern .= $1;
}
elsif ( $glob =~ /\G([\},])/gc ) {
# Sometimes meta characters
$pattern .= '\\' . $1;
}
else {
# Eat everything that is not a meta character.
$glob =~ /\G([^{?*\\\},]*)/gc;
$pattern .= quotemeta $1;
}
return $pattern if pos $glob == length $glob;
}
}
sub _expand {
my ( $self, $name, $tests ) = @_;
my $pattern = $self->_glob_to_regexp($name);
$pattern = qr/^ $pattern $/x;
my @match = ();
for ( my $ti = 0; $ti < @$tests; $ti++ ) {
if ( $tests->[$ti]->filename =~ $pattern ) {
push @match, splice @$tests, $ti, 1;
$ti--;
}
}
return @match;
}
=head2 Instance Methods
=head3 C<get_all>
Get a list of all remaining tests.
=cut
sub get_all {
my $self = shift;
my @all = $self->_gather( $self->{schedule} );
$self->{count} = @all;
@all;
}
sub _gather {
my ( $self, $rule ) = @_;
return unless defined $rule;
return $rule unless 'ARRAY' eq ref $rule;
return map { defined() ? $self->_gather($_) : () } map {@$_} @$rule;
}
=head3 C<get_job>
Return the next available job as L<TAP::Parser::Scheduler::Job> object or
C<undef> if none are available. Returns a L<TAP::Parser::Scheduler::Spinner> if
the scheduler still has pending jobs but none are available to run right now.
=cut
sub get_job {
my $self = shift;
$self->{count} ||= $self->get_all;
my @jobs = $self->_find_next_job( $self->{schedule} );
if (@jobs) {
--$self->{count};
return $jobs[0];
}
return TAP::Parser::Scheduler::Spinner->new
if $self->{count};
return;
}
sub _not_empty {
my $ar = shift;
return 1 unless 'ARRAY' eq ref $ar;
for (@$ar) {
return 1 if _not_empty($_);
}
return;
}
sub _is_empty { !_not_empty(@_) }
sub _find_next_job {
my ( $self, $rule ) = @_;
my @queue = ();
my $index = 0;
while ( $index < @$rule ) {
my $seq = $rule->[$index];
# Prune any exhausted items.
shift @$seq while @$seq && _is_empty( $seq->[0] );
if (@$seq) {
if ( defined $seq->[0] ) {
if ( 'ARRAY' eq ref $seq->[0] ) {
push @queue, $seq;
}
else {
my $job = splice @$seq, 0, 1, undef;
$job->on_finish( sub { shift @$seq } );
return $job;
}
}
++$index;
}
else {
# Remove the empty sub-array from the array
splice @$rule, $index, 1;
}
}
for my $seq (@queue) {
if ( my @jobs = $self->_find_next_job( $seq->[0] ) ) {
return @jobs;
}
}
return;
}
=head3 C<as_string>
Return a human readable representation of the scheduling tree.
For example:
my @tests = (qw{
t/startup/foo.t
t/shutdown/foo.t
t/a/foo.t t/b/foo.t t/c/foo.t t/d/foo.t
});
my $sched = TAP::Parser::Scheduler->new(
tests => \@tests,
rules => {
seq => [
{ seq => 't/startup/*.t' },
{ par => ['t/a/*.t','t/b/*.t','t/c/*.t'] },
{ seq => 't/shutdown/*.t' },
],
},
);
Produces:
par:
seq:
par:
seq:
par:
seq:
't/startup/foo.t'
par:
seq:
't/a/foo.t'
seq:
't/b/foo.t'
seq:
't/c/foo.t'
par:
seq:
't/shutdown/foo.t'
't/d/foo.t'
=cut
sub as_string {
my $self = shift;
return $self->_as_string( $self->{schedule} );
}
sub _as_string {
my ( $self, $rule, $depth ) = ( shift, shift, shift || 0 );
my $pad = ' ' x 2;
my $indent = $pad x $depth;
if ( !defined $rule ) {
return "$indent(undef)\n";
}
elsif ( 'ARRAY' eq ref $rule ) {
return unless @$rule;
my $type = ( 'par', 'seq' )[ $depth % 2 ];
return join(
'', "$indent$type:\n",
map { $self->_as_string( $_, $depth + 1 ) } @$rule
);
}
else {
return "$indent'" . $rule->filename . "'\n";
}
}
1;
| 25.708241 | 172 | 0.5431 |
ed67fed7e5378dd2a57ab495c1e50cb3677b30f1 | 1,856 | t | Perl | t/HexToASCII.t | kablamo/zeroclickinfo-goodies | d6b03c53d5bbd19bd7c06ea9f859a3e6ba2495ae | [
"Apache-2.0"
]
| 1 | 2020-02-22T14:02:31.000Z | 2020-02-22T14:02:31.000Z | t/HexToASCII.t | danny0838/zeroclickinfo-goodies | d9501cffd587d6ac260afba22f45f4a1ba9ac6ef | [
"Apache-2.0"
]
| null | null | null | t/HexToASCII.t | danny0838/zeroclickinfo-goodies | d9501cffd587d6ac260afba22f45f4a1ba9ac6ef | [
"Apache-2.0"
]
| 1 | 2021-02-03T16:57:25.000Z | 2021-02-03T16:57:25.000Z | #!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Test::Deep;
use DDG::Test::Goodie;
zci answer_type => 'ascii';
zci is_cached => 1;
sub build_structured_answer {
my ($word, $response) = @_;
return $response,
structured_answer => {
data => {
title => $response,
subtitle => "Hex to ASCII: $word",
},
templates => {
group => 'text',
},
},
}
sub build_test { test_zci(build_structured_answer(@_)) }
ddg_goodie_test(
[qw( DDG::Goodie::HexToASCII )],
'ascii 0x7465ff7374' => undef,
'ascii 0x7465007374' => build_test('0x7465007374', 'te<code title="null">[NUL]</code>st'),
'ascii 0x74657374' => build_test('0x74657374', 'test'),
'0x74657374 hex to ascii' => build_test('0x74657374', 'test'),
'0x74657374 to ascii' => build_test('0x74657374', 'test'),
'ascii 0x5468697320697320612074657374' => build_test('0x5468697320697320612074657374', 'This is a test'),
'ascii 0x466f7220736f6d6520726561736f6e2c2049206465636964656420746f2061736b20612073656172636820656e67696e6520746f20636f6e766572742068657820746f2041534349492e0d0a436f6f6c2c20746869732073656172636820656e67696e6520646f65732069742c20756e74696c20492072756e206f7574206f662073706163652e' => build_test('0x466f7220736f6d6520726561736f6e2c2049206465636964656420746f2061736b20612073656172636820656e67696e6520746f20636f6e766572742068657820746f2041534349492e0d0a436f6f6c2c20746869732073656172636820656e67696e6520646f65732069742c20756e74696c20492072756e206f7574206f662073706163652e', 'For some reason, I decided to ask a search engine to convert hex to ASCII.<code title="carriage return">[CR]</code><code title="linefeed">[LF]</code>Cool, this search engine does it, until I run out of …'),
);
done_testing;
| 46.4 | 789 | 0.719289 |
ed4e396d08690c194ef80d11242672801e5c7754 | 2,362 | pl | Perl | Source/GUI/Cocoa/_i18n/_update_file_in_stringsdb.pl | dabrain34/MediaInfo | d999229d20ac3b45b36b5db7e116ebb93edbe62a | [
"BSD-2-Clause"
]
| 1 | 2017-12-16T20:49:14.000Z | 2017-12-16T20:49:14.000Z | Source/GUI/Cocoa/_i18n/_update_file_in_stringsdb.pl | dabrain34/MediaInfo | d999229d20ac3b45b36b5db7e116ebb93edbe62a | [
"BSD-2-Clause"
]
| null | null | null | Source/GUI/Cocoa/_i18n/_update_file_in_stringsdb.pl | dabrain34/MediaInfo | d999229d20ac3b45b36b5db7e116ebb93edbe62a | [
"BSD-2-Clause"
]
| null | null | null | #!/usr/bin/perl -w
#tested on Perl v5.12.3
#Author: Max Pozdeev
use Encode qw/encode decode/;
use File::Basename;
use Data::Dumper;
my $stringsdb = "./stringsdb.txt";
if(int @ARGV == 0) {
die "Usage: $0 <filename>";
}
my $filename = $ARGV[0];
my %db;
if(-f $stringsdb) {
#print "Loading db\n";
open(my $in, '<:raw', $stringsdb) || die "Couldn't open db file: $!";
my $text = do { local $/; <$in> };
close $in;
my $content = decode('UTF-16', $text);
my @lines = split /\n/, $content;
foreach(@lines) {
if($_ =~ /^([^=]+)\s*=\s*(.+)/) {
my $fileparam = $1;
my $value = $2;
my($file,$param)=split /\//, $fileparam, 2;
$db{$file}{$param} = $value;
}
}
}
#open .strings file
addStringsFromFile($filename);
#print Dumper(\%db);
#save stringsdb
my $output_str = "";
foreach(sort keys %db) {
my $fileIndex = $_;
my $fileHash = \%{$db{$fileIndex}};
foreach(sort keys %$fileHash) {
my $param = $_;
my $value = $fileHash->{$param};
#print "$param $value\n";
$output_str .= "$fileIndex/$param=$value\n";
}
}
open my $out, '>:raw', $stringsdb;
print $out encode("UTF-16", $output_str);
close $out;
sub addStringsFromFile
{
my ($filename) = @_;
my $fileIndex = basename($filename);
open(my $in, '<:raw', $filename) || die "Couldn't open $filename: $!";
my $text = do { local $/; <$in> };
close $in;
my $content = decode('UTF-16', $text);
my @lines = split /\n/, $content;
foreach(@lines) {
if($_ =~ /^"(.+?)"\s*=\s*"(.+)"/) {
my $param = $1;
my $value = $2;
#print "found $param $value\n";
if(!defined $db{$fileIndex}{$param}) {
$db{$fileIndex}{$param} = "csv/$param//$value";
print "Added $param from $fileIndex: ". encode('utf-8',$value) ."\n";
}
else {
my @dbValue = split(/\//, $db{$fileIndex}{$param}, 4);
if($dbValue[3] ne $value) {
$db{$fileIndex}{$param} = "$dbValue[0]/$dbValue[1]/$dbValue[2]/$value";
print "Replaced $param in $fileIndex: ". encode('utf-8',$value) ."\n";
}
}
}
}
print "Parsed $filename\n";
} | 25.673913 | 91 | 0.482642 |
ed60a8d73402c1b4ee9a22f9cdc47ba2aa093d22 | 207 | pm | Perl | obselete/HydraVdt/Nodes/InitNode.pm | acj/hydra | e6d3879db2d7889632a2b0a8f1b30e8323b06030 | [
"AFL-3.0"
]
| null | null | null | obselete/HydraVdt/Nodes/InitNode.pm | acj/hydra | e6d3879db2d7889632a2b0a8f1b30e8323b06030 | [
"AFL-3.0"
]
| null | null | null | obselete/HydraVdt/Nodes/InitNode.pm | acj/hydra | e6d3879db2d7889632a2b0a8f1b30e8323b06030 | [
"AFL-3.0"
]
| null | null | null | #!/usr/bin/perl
package InitNode;
use AbstractNode;
our @ISA=("AbstractNode");
sub Accept
{
my $self=shift();
my $visitor=shift();
$visitor->visitInitNode($self);
}
return 1;
| 12.9375 | 36 | 0.594203 |
ed1acf263ae0924b0eaf6412815bf51328586fd7 | 4,660 | pm | Perl | modules/Bio/EnsEMBL/Mapper/Coordinate.pm | msmanoj/ensembl | f357e3331a6b529fa82a08d0cee0be8ea1d90887 | [
"Apache-2.0"
]
| null | null | null | modules/Bio/EnsEMBL/Mapper/Coordinate.pm | msmanoj/ensembl | f357e3331a6b529fa82a08d0cee0be8ea1d90887 | [
"Apache-2.0"
]
| null | null | null | modules/Bio/EnsEMBL/Mapper/Coordinate.pm | msmanoj/ensembl | f357e3331a6b529fa82a08d0cee0be8ea1d90887 | [
"Apache-2.0"
]
| null | null | null | =head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2021] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::Mapper::Coordinate
=head1 SYNOPSIS
=head1 DESCRIPTION
Representation of a mapped region in a sequence; returned from Mapper.pm
when the target region maps on to valid sequence.
=head1 METHODS
=cut
package Bio::EnsEMBL::Mapper::Coordinate;
use strict;
=head2 new
Arg [1] char|int id of object in mapped region
Arg [2] int start of region
Arg [3] int end of region
Arg [4] int strand if region
Arg [5] Bio::EnsEMBL::CoordSystem coordsytem of the region
Function creates a new Coordinate object
Returntype Bio::EnsEMBL::Mapper::Coordinate
Exceptions none
Status Stable
=cut
sub new {
my ( $proto, $id, $start, $end, $strand, $coord_system, $rank ) = @_;
my $class = ref($proto) || $proto;
return
bless( { 'id' => $id,
'start' => $start,
'end' => $end,
'strand' => $strand,
'coord_system' => $coord_system,
'rank' => $rank || 0
},
$class );
}
=head2 start
Arg 1 int $start
start coordinate of object in mapped region
Function getter/setter method
Returntype int
Exceptions none
Caller Bio::EnsEMBL::Mapper::Coordinate
Status Stable
=cut
sub start {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'start'} = $value;
}
return $self->{'start'};
}
=head2 end
Arg 1 int $end
end coordinate of object in mapped region
Function getter/setter method
Returntype int
Exceptions none
Caller Bio::EnsEMBL::Mapper::Coordinate
Status Stable
=cut
sub end {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'end'} = $value;
}
return $self->{'end'};
}
=head2 strand
Arg 1 int $strand
strand of object in mapped region
Function getter/setter method
Returntype int
Exceptions none
Caller Bio::EnsEMBL::Mapper::Coordinate
Status Stable
=cut
sub strand {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'strand'} = $value;
}
return $self->{'strand'};
}
=head2 id
Arg 1 char|int $id
id of object in mapped region
e.g. seq_region_id
Function getter/setter method
Returntype char|int
Exceptions none
Caller Bio::EnsEMBL::Mapper::Coordinate
Status Stable
=cut
sub id {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'id'} = $value;
}
return $self->{'id'};
}
=head2 name
Arg 1 char name
name of object in mapped region
e.g. seq_region_name
Function getter/setter method
Returntype char
Exceptions none
Caller Bio::EnsEMBL::Mapper::Coordinate
Status Stable
=cut
sub name {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'name'} = $value;
}
return $self->{'name'};
}
=head2 coord_system
Arg 1 Bio::EnsEMBL::CoordSystem
Function getter/setter method
Returntype Bio::EnsEMBL::CoordSystem
Exceptions none
Caller Bio::EnsEMBL::Mapper::Coordinate
Status Stable
=cut
sub coord_system {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'coord_system'} = $value;
}
return $self->{'coord_system'};
}
=head2 length
Function getter method
Returntype int
Exceptions none
Caller ?
Status Stable
=cut
sub length {
my ($self) = @_;
return $self->{'end'} - $self->{'start'} + 1;
}
sub rank {
my ( $self, $value ) = @_;
if ( defined($value) ) {
$self->{'rank'} = $value;
}
return $self->{'rank'};
}
1;
| 19.256198 | 100 | 0.619742 |
ed22472be13fb84de15ba06fb4ad7496b449ac3b | 2,110 | t | Perl | test/050-stream.t | iriscouch/erlang-request | abd5e34b651a62e1c28b8fec6e7855cb0df6af9b | [
"Apache-2.0"
]
| 6 | 2015-05-05T13:27:51.000Z | 2016-12-01T11:35:25.000Z | test/050-stream.t | iriscouch/erlang-request | abd5e34b651a62e1c28b8fec6e7855cb0df6af9b | [
"Apache-2.0"
]
| null | null | null | test/050-stream.t | iriscouch/erlang-request | abd5e34b651a62e1c28b8fec6e7855cb0df6af9b | [
"Apache-2.0"
]
| null | null | null | #! /usr/bin/env escript
-define(TIMEOUT, 3000).
-define(PORT, 12345).
-define(HOST, "http://localhost:12345").
main([]) -> ok
, code:add_pathz("test")
, code:add_pathz("ebin")
, code:add_pathz("deps/ejson/ebin")
, request:start()
, http_server:run(stream, ?PORT)
, etap:plan(16)
, test()
, etap:end_tests()
.
test() -> ok
, test_normal()
, test_streaming_body()
.
test_normal() -> ok
, {Res, Body} = request:get(?HOST ++ "/normal")
, etap:isnt(Res, error, "Stream server response")
, etap:is(Body, <<"GET\r\n/normal\r\nGoodbye\r\n">>, "Got the streaming response")
.
test_streaming_body() -> ok
, Opts = {[ {url,?HOST++"/streaming/post"}, {onResponse,true} ]}
, {Res, Body} = request:post(Opts)
, etap:isnt(Res, error, "Stream server response to POST")
, etap:is(Res:headers("transfer-encoding"), "chunked", "Streamer is a chunked encoding")
, etap:is(Body(), <<"POST\r\n">>, "First streamer line")
, etap:is(Body(), <<"/streaming/post\r\n">>, "Second streamer line")
, etap:is(Body(), <<"Goodbye\r\n">>, "Third streamer line")
, etap:is(Body(), 'end', "Streamer end")
, Me = self()
, Check_body = fun(Resp, Get_body) -> ok
, etap:isnt(Resp, error, "Good response for async onRequest")
, etap:is(Res:headers("transfer-encoding"), "chunked", "Async stream is a chunked encoding")
, etap:is(Get_body(), <<"POST\r\n">>, "First async streamer line")
, etap:is(Get_body(), <<"/streaming/async\r\n">>, "Second async streamer line")
, etap:is(Get_body(), <<"Goodbye\r\n">>, "Third async streamer line")
, etap:is(Get_body(), 'end', "Async streamer end")
, Me ! done
end
, Pid = request:request({[ {method,post}, {url,?HOST++"/streaming/async"}, {onResponse,Check_body} ]})
, etap:ok(is_pid(Pid), "Request with onResponse is async")
, Done = receive
done -> true
after 1000 -> false
end
, etap:ok(Done, "Body check finished")
.
%dot(Obj, Key) -> request:dot(Obj, Key).
% vim: sts=4 sw=4 et
| 33.492063 | 106 | 0.585782 |
ed369519135b67be11cbbfb952aa5bfd1a8ce6ba | 343 | pm | Perl | auto-lib/Azure/RecoveryServices/AddVCenterRequestProperties.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Azure/RecoveryServices/AddVCenterRequestProperties.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Azure/RecoveryServices/AddVCenterRequestProperties.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| 1 | 2021-04-08T15:26:39.000Z | 2021-04-08T15:26:39.000Z | package Azure::RecoveryServices::AddVCenterRequestProperties;
use Moose;
has 'friendlyName' => (is => 'ro', isa => 'Str' );
has 'ipAddress' => (is => 'ro', isa => 'Str' );
has 'port' => (is => 'ro', isa => 'Str' );
has 'processServerId' => (is => 'ro', isa => 'Str' );
has 'runAsAccountId' => (is => 'ro', isa => 'Str' );
1;
| 34.3 | 61 | 0.533528 |
ed07c7f5d2adb25d56f64bf8bac97d926a1a81d9 | 3,453 | pl | Perl | scripts/arachnoserver/prepare_submission_fasta.pl | BRAEMBL/ena-tools | 96ab52ee77793e3ec61ef819bc5c983e90448a26 | [
"Unlicense"
]
| 6 | 2015-02-15T19:26:25.000Z | 2018-07-30T10:05:37.000Z | scripts/arachnoserver/prepare_submission_fasta.pl | BRAEMBL/ena-tools | 96ab52ee77793e3ec61ef819bc5c983e90448a26 | [
"Unlicense"
]
| null | null | null | scripts/arachnoserver/prepare_submission_fasta.pl | BRAEMBL/ena-tools | 96ab52ee77793e3ec61ef819bc5c983e90448a26 | [
"Unlicense"
]
| null | null | null | #!/usr/bin/env perl
=head1 prepare_submission_fasta.pl
=head2 SYNOPSIS
=head2 How to run this script
=over
export PERL5LIB=$PWD/lib:$PWD/project_lib
color()(set -o pipefail;"$@" 2>&1>&3|sed $'s,.*,\e[31m&\e[m,'>&2)3>&1
# Redirect 2>/dev/null to suppress warnings that are irrelevant for this.
#
./scripts/arachnoserver/prepare_submission_fasta.pl \
--features "/home/michael/spider_toxin_devel/qfab_package/245/245coordinatesAllForward.tsv" \
--assembly "/home/michael/spider_toxin_devel/qfab_package/245/245_reverse_complement_Assembly.fa" \
--organism "Hadronyche infensa" \
--assembly_name HI \
--assembly_method MIRA \
--sequencing_technology "454 GS" \
--sra_study_accession ERP005525 \
--sra_sample_accession ERS431088 \
=back
=head2 Parameters
=head3 -features
=cut
=head3 -assembly
=cut
use strict;
use Carp;
use Data::Dumper;
use Getopt::Long;
use List::MoreUtils qw{ zip };
use Hash::Util qw(lock_keys);
my $feature_file;
my $fasta_file;
my $organism;
my $assembly_name;
my $assembly_method;
my $sequencing_technology;
my $sra_study_accession;
my $sra_sample_accession;
my $help;
# Mapping of command line parameters to variables
my %config_hash = (
"features" => \$feature_file,
"organism" => \$organism,
"assembly_name" => \$assembly_name,
"assembly_method" => \$assembly_method,
"sequencing_technology" => \$sequencing_technology,
"sra_study_accession" => \$sra_study_accession,
"sra_sample_accession" => \$sra_sample_accession,
"help" => \$help,
);
# Loading command line parameters into variables and into a hash.
my $result = GetOptions(
\%config_hash,
'features=s',
'organism=s',
'assembly_name=s',
'assembly_method=s',
'sequencing_technology=s',
'sra_study_accession=s',
'sra_sample_accession=s',
'help',
);
if ($help) {
system('perldoc', $0);
exit;
}
die "Missing mandatory parameter --feature!" unless($feature_file);
die "Can't find file $feature_file!" unless(-f $feature_file);
use Bio::Seq;
use Bio::SeqIO;
my $seq_out = Bio::SeqIO->new(
-fh => \*STDOUT,
-format => 'Fasta'
);
open my $IN, $feature_file;
my @genelist = parse_tsv($IN);
foreach my $current_gene (@genelist) {
my $header = join '',
"[Organism=$organism]",
"[Name for the assembly=$assembly_name]",
"[Assembly method=$assembly_method]",
"[Sequencing technology=$sequencing_technology]",
"[SRA Study Accession=$sra_study_accession]",
"[SRA Sample Accession=$sra_sample_accession]",
'[Contig/Isotig name=' . $current_gene->{seq_name} . ']',
'[product=' . $current_gene->{product} . ']',
'[5\' CDS location='. $current_gene->{start} .']',
'[3\' CDS location='. $current_gene->{end} .']',
"[partial at 5' ? (yes/no)=no]",
"[partial at 3' ? (yes/no)=no]",
"[Translation table=1]";
my $seq_obj = Bio::Seq->new(
-id => $header,
-seq => $current_gene->{nt_seq},
);
$seq_out->write_seq($seq_obj);
}
exit;
sub parse_tsv {
my $fh = shift;
my @header = qw(
seq_name
product
aa_seq_1
aa_seq_2
aa_seq_3
nt_seq
start
end
);
my @genelist;
open my $fh, $feature_file;
while (my $current_line = <$IN>) {
chomp($current_line);
my @f = split "\t", $current_line;
my %hash = zip @header, @f;
lock_keys(%hash);
push @genelist, \%hash;
}
return @genelist;
}
| 23.331081 | 105 | 0.648132 |
ed2d56cd9faf35de0a89d601e05ea5e404c5780f | 94 | pm | Perl | lib/perl/GUS/Study/ProtocolAppNode.pm | EuPathDB/ebi2gus | d82037894ba7dbe44cb4dc493a394f92330d7f75 | [
"Apache-2.0"
]
| null | null | null | lib/perl/GUS/Study/ProtocolAppNode.pm | EuPathDB/ebi2gus | d82037894ba7dbe44cb4dc493a394f92330d7f75 | [
"Apache-2.0"
]
| null | null | null | lib/perl/GUS/Study/ProtocolAppNode.pm | EuPathDB/ebi2gus | d82037894ba7dbe44cb4dc493a394f92330d7f75 | [
"Apache-2.0"
]
| null | null | null | package GUS::Study::ProtocolAppNode;
use base qw(GUSRow);
use strict;
sub init {
#TODO
}
1; | 9.4 | 36 | 0.702128 |
ed6d3fa283c174e05945d1c7d7bb9b129c075bd6 | 3,696 | pl | Perl | examples/ppa_1998/chap7/multibus.pl | peterlharding/PDQ | b6ff8dd958dbae85b4402745539898b711760713 | [
"MIT"
]
| 5 | 2015-08-12T16:22:11.000Z | 2019-06-05T05:57:35.000Z | examples/ppa_1998/chap7/multibus.pl | peterlharding/PDQ | b6ff8dd958dbae85b4402745539898b711760713 | [
"MIT"
]
| null | null | null | examples/ppa_1998/chap7/multibus.pl | peterlharding/PDQ | b6ff8dd958dbae85b4402745539898b711760713 | [
"MIT"
]
| 3 | 2018-03-12T12:25:28.000Z | 2019-06-05T05:57:44.000Z | #!/usr/bin/perl
###############################################################################
# Copyright (C) 1994 - 1996, Performance Dynamics Company #
# #
# 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 http://www.perfdynamics.com/Tools/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. #
###############################################################################
#
# multibus.pl
#
# Created by NJG: 13:03:53 07-19-96 Updated by NJG: 19:31:12 07-31-96
#
# $Id: multibus.pl,v 4.3 2009/03/26 02:55:32 pfeller Exp $
#
#---------------------------------------------------------------------
use pdq;
#---------------------------------------------------------------------
# System parameters
$BUSES = 9;
$CPUS = 64;
$STIME = 1.0;
$COMPT = 10.0;
# submodel throughput characteristic
@sm_x = ();
@pq = ();
#---------------------------------------------------------------------
sub multiserver
{
my ($m, $stime) = @_;
$work = "reqs";
$node = "bus";
$x = 0.0;
for ($i = 1; $i <= $CPUS; $i++) {
if ($i <= $m) {
pdq::Init("multibus");
$streams = pdq::CreateClosed($work, $pdq::TERM, $i, 0.0);
$nodes = pdq::CreateNode($node, $pdq::CEN, $pdq::ISRV);
pdq::SetDemand($node, $work, $stime);
pdq::Solve($pdq::EXACT);
$x = pdq::GetThruput($pdq::TERM, $work);
$sm_x[$i] = $x;
} else {
$sm_x[$i] = $x;
}
# printf "*>> %f\n", $x;
}
} # multiserver #
#----- Multibus submodel ---------------------------------------------
multiserver($BUSES, $STIME);
#----- Composite model -----------------------------------------------
$pq[0][0] = 1.0;
for ($n = 1; $n <= $CPUS; $n++) {
$R = 0.0; # reset
for ($j = 1; $j <= $n; $j++) {
$h = ($j / $sm_x[$j]) * $pq[$j - 1][$n - 1];
$R += $h;
# printf "%2d sm_x[%02d] %f pq[%02d][%02d] %f h %f R %f\n",
# $j, $sm_x[$j], $j, $n, $pq[$j - 1][$n - 1], $h, $R;
}
$xn = $n / ($COMPT + $R);
# printf("xn %f n %d COMPT+R %f\n", $xn, $n, ($COMPT + $R));
$qlength = $xn * $R;
# printf("qlngth %f\n", $qlength);
for ($j = 1; $j <= $n; $j++) {
$pq[$j][$n] = ($xn / $sm_x[$j]) * $pq[$j - 1][$n - 1];
# printf("pq[%d][%d] %f\n", $j, $n, $pq[$j][$n]);
}
$pq[0][$n] = 1.0;
for ($j = 1; $j <= $n; $j++) {
$pq[0][$n] -= $pq[$j][$n];
# printf("%2d %2d pq[00][%02d] %f pq[%02d][%02d] %f\n", $j, $n, $n, $pq[0][$n], $j, $n, $pq[$j][$n]);
}
}
#----- Processing Power ----------------------------------------------
printf("Buses:%2d, CPUs:%2d\n", $BUSES, $CPUS);
printf("Load %3.4f\n", ($STIME / $COMPT));
printf("X at FESC: %3.4f\n", $xn);
printf("P %3.4f\n", $xn * $COMPT);
#---------------------------------------------------------------------
| 30.295082 | 110 | 0.353896 |
ed33c6681c8dbfb48a98a026e870a7e9a677b8e9 | 2,682 | pm | Perl | modules/EnsEMBL/Web/ExtIndex/WEBSRS.pm | amonida/ensembl-webcode | 284a8c633fdcf72575f18c11ac0657ee0919e270 | [
"Apache-2.0",
"MIT"
]
| null | null | null | modules/EnsEMBL/Web/ExtIndex/WEBSRS.pm | amonida/ensembl-webcode | 284a8c633fdcf72575f18c11ac0657ee0919e270 | [
"Apache-2.0",
"MIT"
]
| null | null | null | modules/EnsEMBL/Web/ExtIndex/WEBSRS.pm | amonida/ensembl-webcode | 284a8c633fdcf72575f18c11ac0657ee0919e270 | [
"Apache-2.0",
"MIT"
]
| null | null | null | #!/usr/local/bin/perl -w
=head1 LICENSE
Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::Web::ExtIndex::WEBSRS;
require LWP::UserAgent;
use strict;
sub new {
my $class = shift;
my $self = {
'options' => {
'id' => '+-f+id',
'acc' => '+-f+acc',
'seq' => '+-f+seq',
'desc' => '+-f+des',
'all' => '-e',
}
};
bless $self, $class;
return $self;
}
sub get_seq_by_id { my ($self, $args)=@_; return $self->query_server( "id", $args); }
sub get_seq_by_acc { my ($self, $args)=@_; return $self->query_server( "acc", $args); }
sub query_server {
my ($self, $type, $args) = @_;
my $db = lc($args->{'DB'});
$db = '{embl_SP_emblnew}' if $db eq 'emblnew' || $db eq 'embl';
$db = '{swissprot_SP_swissnew}' if $db eq 'swissnew' || $db eq 'swissprot';
$db = '{sptrembl_SP_tremblnew}' if $db eq 'tremblnew' || $db eq 'sptrembl';
$db = "$db-type";
my $query = "$args->{'EXE'}?[$db:$args->{'ID'}]".
( $self->{'options'}{$args->{'OPTIONS'}} || $self->{'options'}{'all'} );
print STDERR "$query\n";
my $ua = LWP::UserAgent->new;
my $request = HTTP::Request->new('GET', $query);
my $response = $ua->request($request); # or
my $str = $response->as_string;
print STDERR "$str\n";
my @lines = split(/\n/,$str);
my @output;
my $foundseq = 0;
foreach my $line (@lines) {
$line =~ s/<.*?>//g;
chomp;
if( $line =~ s/^DE\s+//) { push @output, $line ; }
elsif( $args->{'OPTIONS'} eq 'all' ) { push @output, $line ; }
elsif( $args->{'OPTIONS'} eq 'id' && $line =~ s/^ID\s+//) { push @output, $line ; }
elsif( $args->{'OPTIONS'} eq 'acc' && $line =~ s/^AC\s+//) { push @output, $line ; }
elsif( $args->{'OPTIONS'} eq 'seq' && $line =~ /^>/) { $foundseq = 1; }
elsif( $args->{'OPTIONS'} eq 'seq' && $foundseq == 1) { push @output, $line ; }
elsif( $args->{'OPTIONS'} eq 'seq' && $line =~ /^</) { $foundseq = 0; }
}
return \@output;
}
1;
| 33.525 | 100 | 0.559657 |
ed394ffb13429b006e228b4e02700b5272d674ee | 1,113 | ph | Perl | pop/lib/include/xveddefs.ph | nickpapadonis/poplog-x64 | c4af8c97e68823fe162fbedde0bc0af183c3a1ca | [
"MIT"
]
| null | null | null | pop/lib/include/xveddefs.ph | nickpapadonis/poplog-x64 | c4af8c97e68823fe162fbedde0bc0af183c3a1ca | [
"MIT"
]
| null | null | null | pop/lib/include/xveddefs.ph | nickpapadonis/poplog-x64 | c4af8c97e68823fe162fbedde0bc0af183c3a1ca | [
"MIT"
]
| null | null | null | /* --- Copyright University of Sussex 1993. All rights reserved. ----------
> File: C.all/lib/include/xveddefs.ph
> Purpose: Defines location of XVED
> Author: Jonathan Meyer, Apr 1 1991 (see revisions)
> Documentation:
> Related Files:
*/
#_TERMIN_IF DEF XVEDDEFS_INCLUDED
section;
iconstant macro (
XVED = '$usepop/pop/x/ved/',
XVEDSRC = XVED dir_>< 'src/',
XVEDLIB = XVED dir_>< 'lib/',
XVEDAUTO = XVED dir_>< 'auto/',
XVEDHELP = XVED dir_>< 'help/',
XVEDREF = XVED dir_>< 'ref/',
XVEDTEACH = XVED dir_>< 'teach/',
XVEDSYSDOC = XVED dir_>< 'sysdoc/',
XVEDXRDB = XVED dir_>< 'xrdb/',
XVEDBITMAPS = XVED dir_>< 'bitmaps/',
);
iconstant XVEDDEFS_INCLUDED = true;
endsection;
/* --- Revision History ---------------------------------------------------
--- John Gibson, Jun 28 1993
Removed XVEDI*NCLUDE -- now just uses standard X include dir
--- John Gibson, Oct 31 1991
Uses dir_>< instead of sys_>< etc
--- Jonathan Meyer, Jun 17 1991
Removed XVED_LOAD_OPTIONS (now in XVEDSRC/xved.p)
--- Jonathan Meyer, May 30 1991
Removed xvedhome
*/
| 24.733333 | 75 | 0.617251 |
ed63c52b59a96d6cb3aba4682f8c29237bbd9e99 | 5,740 | pm | Perl | posda/posdatools/FileDist/include/DicomLookup/Application.pm | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
]
| 6 | 2019-01-17T15:47:44.000Z | 2022-02-02T16:47:25.000Z | posda/posdatools/FileDist/include/DicomLookup/Application.pm | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
]
| 23 | 2016-06-08T21:51:36.000Z | 2022-03-02T08:11:44.000Z | posda/posdatools/FileDist/include/DicomLookup/Application.pm | UAMS-DBMI/PosdaTools | 7d33605da1b88e4787a1368dbecaffda1df95e5b | [
"Apache-2.0"
]
| null | null | null | #!/usr/bin/perl -w
#
use strict;
use Posda::HttpApp::GenericMfWindow;
use Posda::HttpApp::HttpObj;
use Posda::HttpApp::SubController;
use Posda::HttpApp::WindowButtons;
use Dispatch::LineReader;
my $header = <<EOF;
<table style="width:100%" summary="window header">
<tr>
<td valign="top" align="left" width="160">
<?dyn="Logo"?>
</td>
<td valign="top">
<h2><?dyn="title"?></h2>
<p>
Enter search value:
<?dyn="InputChangeNoReload" op="SetSearchString" field="SearchString"?>
</p>
<p>Note: Search is in the format: (xxxx,xxxx)</p>
</td>
<td valign="top" align="right" width="180" height="120">
<?dyn="iframe" height="0" width="0" style="visibility:hidden;display:none" child_path="Controller"?>
<?dyn="iframe" frameborder="0" height="100%" child_path="WindowButtons"?>
</td>
</tr>
</table><hr>
<?dyn="iframe" height="350" child_path="Content"?>
<hr>
EOF
my $bad_config = <<EOF;
<table style="width:100%" summary="window header">
<tr>
<td valign="top" align="left" width="160">
<?dyn="Logo"?>
</td>
<td valign="top">
<h2><?dyn="title"?></h2>
</td>
<td valign="top" align="right" width="180" height="120">
<?dyn="iframe" height="0" width="0" style="visibility:hidden;display:none" child_path="Controller"?>
<?dyn="iframe" frameborder="0" height="100%" child_path="WindowButtons"?>
</td>
</tr>
</table>
<table border="1"><hr><th colspan="2">Bad Configuration Files</th></tr>
<?dyn="BadConfigReport"?>
</table>
EOF
{
package DicomLookup::Application;
use vars qw( @ISA );
@ISA = ( "Posda::HttpApp::GenericMfWindow" );
sub new {
my($class, $sess, $path) = @_;
my $this = Posda::HttpApp::GenericMfWindow->new($sess, $path);
$this->{title} = "Dicom Element Lookup Application";
bless $this, $class;
$this->{w} = 800;
$this->{h} = 500;
$this->{RoutesBelow}->{ExpertModeChanged} = 1;
Posda::HttpApp::Controller->new($this->{session},
$this->child_path("Controller"));
Posda::HttpApp::WindowButtons->new($this->{session},
$this->child_path("WindowButtons"));
DicomLookup::Application::Content->new(
$this->{session}, $this->child_path("Content"));
Posda::HttpApp::DebugWindow->new($sess, "Debug");
$this->SetInitialExpertAndDebug;
$this->ReOpenFile();
if(exists $main::HTTP_APP_CONFIG->{BadJson}){
$this->{BadConfigFiles} = $main::HTTP_APP_CONFIG->{BadJson};
}
my $session = $main::HTTP_APP_SINGLETON->GetSession($this->{session});
$session->{Privileges}->{capability}->{CanDebug} = 1;
return $this;
}
sub BadConfigReport{
my($this, $http, $dyn) = @_;
for my $i (keys %{$this->{BadConfigFiles}}){
$http->queue(
"<tr><td>$i</td><td>$this->{BadConfigFiles}->{$i}</td></tr>");
}
}
sub Logo{
my($this, $http, $dyn) = @_;
my $image = $main::HTTP_APP_CONFIG->{config}->{Identity}->{LogoImage};
my $height = $main::HTTP_APP_CONFIG->{config}->{Identity}->{LogoHeight};
my $width = $main::HTTP_APP_CONFIG->{config}->{Identity}->{LogoWidth};
my $alt = $main::HTTP_APP_CONFIG->{config}->{Identity}->{LogoAlt};
$http->queue("<img src=\"$image\" height=\"$height\" width=\"$width\" " ,
"alt=\"$alt\">");
}
sub Content {
my($this, $http, $dyn) = @_;
if($this->{BadConfigFiles}){
return $this->RefreshEngine($http, $dyn, $bad_config);
}
$this->RefreshEngine($http, $dyn, $header);
}
sub SetSearchString{
my($this, $http, $dyn) = @_;
$this->{SearchString} = $dyn->{value};
$this->SearchText;
}
sub SearchText{
my($this, $http, $dyn) = @_;
my $obj = $this->child("Content");
$obj->SearchText($this->{SearchString});
}
sub CleanUp{
my($this) = @_;
$this->delete_descendants;
}
sub DESTROY{
my($this) = @_;
}
}
{
package DicomLookup::Application::Content;
use File::Path qw (remove_tree);
use Posda::HttpApp::GenericIframe;
use vars qw( @ISA );
@ISA = ( "Posda::HttpApp::GenericIframe" );
sub new{
my($class, $sess, $path) = @_;
my $this = Posda::HttpApp::GenericIframe->new($sess, $path);
bless $this, $class;
$this->{SearchesInProgress} = 0;
$this->{Operation} = "Idle";
$this->AutoRefresh;
return $this;
}
sub Content{
my($this, $http, $dyn) = @_;
if($this->{Operation} eq "SearchString"){
$this->RefreshEngine($http, $dyn,
"<small>Search for elements matching: \"$this->{SearchString}\"<br>" .
'<pre><?dyn="SearchStringResults"?><pre></small>');
} else {
$http->queue("Enter Search Above");
}
}
sub SearchText{
my($this, $text_string) = @_;
$this->{SearchString} = $text_string;
$this->{Operation} = "SearchString";
$this->StartTextSearch;
$this->AutoRefresh;
}
sub SearchStringResults{
my($this, $http, $dyn) = @_;
for my $l (@{$this->{SearchResults}}){ $http->queue("$l\n") }
}
sub StartTextSearch{
my($this) = @_;
my $str = $this->{SearchString};
$str =~ s/\"/\\\"/g;
my $cmd = "SearchElementsByName.pl \"$str\"";
$this->{SearchResults} = [];
if($this->{SearchesInProgress} > 0){
push(@{$this->{SearchResults}},
"Attempting to start new search when one in progress");
return;
}
$this->{SearchesInProgress} += 1;
Dispatch::LineReader->new_cmd($cmd,
$this->SearchLine, $this->EndSearch);
}
sub SearchLine{
my($this) = @_;
my $sub = sub {
my($line) = @_;
push(@{$this->{SearchResults}}, $line);
};
return $sub;
}
sub EndSearch{
my($this, $line) = @_;
my $sub = sub {
$this->{SearchesInProgress} -= 1;
$this->AutoRefresh;
};
return $sub;
}
}
1;
| 30.37037 | 100 | 0.587979 |
ed703cb01434c5b35c254cf99ae5b4de391b5a40 | 446 | pl | Perl | silk-src/src/rwcount/tests/rwcount-legacy-1.pl | mjschultz/netsa-pkg | 07bf4ff29a73ebc0f58e4aa27d3ad6b1dee7fc83 | [
"Apache-2.0"
]
| 3 | 2018-06-01T06:55:14.000Z | 2021-11-14T22:51:04.000Z | silk-src/src/rwcount/tests/rwcount-legacy-1.pl | mjschultz/netsa-pkg | 07bf4ff29a73ebc0f58e4aa27d3ad6b1dee7fc83 | [
"Apache-2.0"
]
| 3 | 2017-07-02T17:03:34.000Z | 2021-09-09T17:05:31.000Z | silk-src/src/rwcount/tests/rwcount-legacy-1.pl | mjschultz/netsa-pkg | 07bf4ff29a73ebc0f58e4aa27d3ad6b1dee7fc83 | [
"Apache-2.0"
]
| 4 | 2017-08-14T15:42:31.000Z | 2022-01-24T16:24:27.000Z | #! /usr/bin/perl -w
# MD5: 42225c369e5eab1756000cb6582cf354
# TEST: ./rwcount --bin-size=3600 --load-scheme=1 --timestamp-format=m/d/y ../../tests/data.rwf
use strict;
use SiLKTests;
my $rwcount = check_silk_app('rwcount');
my %file;
$file{data} = get_data_or_exit77('data');
my $cmd = "$rwcount --bin-size=3600 --load-scheme=1 --timestamp-format=m/d/y $file{data}";
my $md5 = "42225c369e5eab1756000cb6582cf354";
check_md5_output($md5, $cmd);
| 29.733333 | 95 | 0.706278 |
ed3edd991d68f4533e34a349bf798654197e2f6c | 3,616 | pm | Perl | lib/perl/Bio/EnsEMBL/EGPipeline/RNAFeatures/DeleteGenes.pm | manuelcarbajo/ensembl-production-imported | 3e3d28f8698415954b79fa67e6e9c71d9bc22cb0 | [
"Apache-2.0"
]
| null | null | null | lib/perl/Bio/EnsEMBL/EGPipeline/RNAFeatures/DeleteGenes.pm | manuelcarbajo/ensembl-production-imported | 3e3d28f8698415954b79fa67e6e9c71d9bc22cb0 | [
"Apache-2.0"
]
| 5 | 2021-05-26T13:41:58.000Z | 2022-01-25T15:03:50.000Z | lib/perl/Bio/EnsEMBL/EGPipeline/RNAFeatures/DeleteGenes.pm | manuelcarbajo/ensembl-production-imported | 3e3d28f8698415954b79fa67e6e9c71d9bc22cb0 | [
"Apache-2.0"
]
| 3 | 2021-05-13T16:13:04.000Z | 2021-07-01T11:57:42.000Z | =head1 LICENSE
See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=pod
=head1 NAME
Bio::EnsEMBL::EGPipeline::RNAFeatures::DeleteGenes
=head1 Author
James Allen
=cut
package Bio::EnsEMBL::EGPipeline::RNAFeatures::DeleteGenes;
use strict;
use warnings;
use base ('Bio::EnsEMBL::EGPipeline::Common::RunnableDB::Base');
sub run {
my ($self) = @_;
my $logic_name = $self->param_required('logic_name');
my $dba = $self->core_dba();
my $ga = $dba->get_adaptor('Gene');
my $dbea = $dba->get_adaptor('DBEntry');
my $aa = $dba->get_adaptor('Attribute');
my @genes = @{ $ga->fetch_all_by_logic_name($logic_name) };
# Unfortunately can't just do $ga->remove, because that also
# deletes all of the dna_align_features...
foreach my $gene (@genes) {
$self->remove_gene($dba, $dbea, $aa, $gene);
}
}
sub remove_gene {
my ($self, $dba, $dbea, $aa, $gene) = @_;
# Remove object xrefs
foreach my $dbe (@{ $gene->get_all_DBEntries() }) {
$dbea->remove_from_object($dbe, $gene, 'Gene');
}
# Remove attributes
$aa->remove_from_Gene($gene);
# Remove transcripts
foreach my $transcript (@{ $gene->get_all_Transcripts() }) {
$self->remove_transcript($dba, $dbea, $aa, $transcript);
}
my $sth = $dba->dbc->prepare("DELETE FROM gene WHERE gene_id = ? ");
$sth->execute($gene->dbID);
}
sub remove_transcript {
my ($self, $dba, $dbea, $aa, $transcript) = @_;
# Remove object xrefs
foreach my $dbe (@{ $transcript->get_all_DBEntries() }) {
$dbea->remove_from_object($dbe, $transcript, 'Transcript');
}
# Remove attributes
$aa->remove_from_Transcript($transcript);
# Remove the translation if it exists
if (defined $transcript->translation) {
my $ta = $dba->get_adaptor('Translation');
$ta->remove($transcript->translation);
}
# Remove exons
foreach my $exon (@{ $transcript->get_all_Exons() }) {
# Only remove the exon if this is the last transcript to reference it
my $sth = $dba->dbc->prepare("SELECT count(*) FROM exon_transcript WHERE exon_id = ?" );
$sth->execute($exon->dbID);
my ($count) = $sth->fetchrow_array();
if ($count == 1) {
$self->remove_exon($dba, $exon);
}
}
# Remove exon/transcript links
my $sth = $dba->dbc->prepare("DELETE FROM exon_transcript WHERE transcript_id = ?");
$sth->execute($transcript->dbID);
# Remove supporting feature links
$sth = $dba->dbc->prepare("DELETE FROM transcript_supporting_feature WHERE transcript_id = ?");
$sth->execute($transcript->dbID);
# Remove transcript
$sth = $dba->dbc->prepare( "DELETE FROM transcript WHERE transcript_id = ?" );
$sth->execute($transcript->dbID);
}
sub remove_exon {
my ($self, $dba, $exon) = @_;
# Remove supporting feature links
my $sth = $dba->dbc->prepare("DELETE FROM supporting_feature WHERE exon_id = ?");
$sth->execute($exon->dbID);
# Remove exon
$sth = $dba->dbc->prepare("DELETE FROM exon WHERE exon_id = ?");
$sth->execute($exon->dbID);
}
1;
| 26.985075 | 97 | 0.670631 |
ed6efb884585e1ac9dbc98d5d33173d815e0eaa1 | 345 | pl | Perl | PhD-Code/DTI_Morten/AAL/run_qsub_scripts.pl | joaodornas/random-code | 8db8cbccab674c4b77efaed86086dc6a99e5b9a1 | [
"Apache-2.0"
]
| 1 | 2021-01-13T05:01:59.000Z | 2021-01-13T05:01:59.000Z | PhD-Code/DTI_Morten/AAL/run_qsub_scripts.pl | joaodornas/random-code | 8db8cbccab674c4b77efaed86086dc6a99e5b9a1 | [
"Apache-2.0"
]
| null | null | null | PhD-Code/DTI_Morten/AAL/run_qsub_scripts.pl | joaodornas/random-code | 8db8cbccab674c4b77efaed86086dc6a99e5b9a1 | [
"Apache-2.0"
]
| null | null | null | #!/usr/bin/perl
# script to run qsub shell scripts
use Cwd qw();
my $path = Cwd::cwd();
print "$path\n";
$dir=$path;
$script='fdt_script.sh';
for ($t=1; $t<91; $t++) {
# create dir
$regiondir=$t."_all";
print ("qsub -V -cwd -e e$t -o i$t $regiondir/$script\n");
system ("qsub -V -cwd -e e$t -o i$t $regiondir/$script");
};
| 19.166667 | 62 | 0.562319 |
73f4eb80f6d2a8e503d9743821457f7e792d498f | 2,900 | pm | Perl | auto-lib/Paws/LicenseManager/ListResourceInventory.pm | meis/aws-sdk-perl | 6d61ffcf351e446f06d7e84e53caa08d98573959 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Paws/LicenseManager/ListResourceInventory.pm | meis/aws-sdk-perl | 6d61ffcf351e446f06d7e84e53caa08d98573959 | [
"Apache-2.0"
]
| 1 | 2021-05-26T19:13:58.000Z | 2021-05-26T19:13:58.000Z | auto-lib/Paws/LicenseManager/ListResourceInventory.pm | meis/aws-sdk-perl | 6d61ffcf351e446f06d7e84e53caa08d98573959 | [
"Apache-2.0"
]
| null | null | null |
package Paws::LicenseManager::ListResourceInventory;
use Moose;
has Filters => (is => 'ro', isa => 'ArrayRef[Paws::LicenseManager::InventoryFilter]');
has MaxResults => (is => 'ro', isa => 'Int');
has NextToken => (is => 'ro', isa => 'Str');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListResourceInventory');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::LicenseManager::ListResourceInventoryResponse');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::LicenseManager::ListResourceInventory - Arguments for method ListResourceInventory on L<Paws::LicenseManager>
=head1 DESCRIPTION
This class represents the parameters used for calling the method ListResourceInventory on the
L<AWS License Manager|Paws::LicenseManager> service. Use the attributes of this class
as arguments to method ListResourceInventory.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListResourceInventory.
=head1 SYNOPSIS
my $license-manager = Paws->service('LicenseManager');
my $ListResourceInventoryResponse =
$license -manager->ListResourceInventory(
Filters => [
{
Condition =>
'EQUALS', # values: EQUALS, NOT_EQUALS, BEGINS_WITH, CONTAINS
Name => 'MyString',
Value => 'MyString',
},
...
], # OPTIONAL
MaxResults => 1, # OPTIONAL
NextToken => 'MyString', # OPTIONAL
);
# Results:
my $NextToken = $ListResourceInventoryResponse->NextToken;
my $ResourceInventoryList =
$ListResourceInventoryResponse->ResourceInventoryList;
# Returns a L<Paws::LicenseManager::ListResourceInventoryResponse> object.
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.
For the AWS API documentation, see L<https://docs.aws.amazon.com/goto/WebAPI/license-manager/ListResourceInventory>
=head1 ATTRIBUTES
=head2 Filters => ArrayRef[L<Paws::LicenseManager::InventoryFilter>]
One or more filters.
=head2 MaxResults => Int
Maximum number of results to return in a single call. To retrieve the
remaining results, make another call with the returned C<NextToken>
value.
=head2 NextToken => Str
Token for the next set of results.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method ListResourceInventory in L<Paws::LicenseManager>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: L<https://github.com/pplu/aws-sdk-perl>
Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues>
=cut
| 31.182796 | 249 | 0.705172 |
ed4fd1f61e93f5d0aef67f93852fc45742e09368 | 4,022 | pm | Perl | featclass/Subs/ImageLinksWordsOverlapSub.pm | accurat-toolkit/workflow-docalignment | c7c817e8726bc6bfb84e2cba65d805a3c40631b4 | [
"Apache-2.0"
]
| null | null | null | featclass/Subs/ImageLinksWordsOverlapSub.pm | accurat-toolkit/workflow-docalignment | c7c817e8726bc6bfb84e2cba65d805a3c40631b4 | [
"Apache-2.0"
]
| null | null | null | featclass/Subs/ImageLinksWordsOverlapSub.pm | accurat-toolkit/workflow-docalignment | c7c817e8726bc6bfb84e2cba65d805a3c40631b4 | [
"Apache-2.0"
]
| null | null | null | #!/usr/bin/perl/
# Written by M. Paramita (m.paramita@sheffield.ac.uk)
# Last update 16 August 2011
use strict;
use warnings;
use utf8;
use File::Find;
#open folder
my ($directory, $input1, $input2, $output, $pairFile, $status, $HTMLstatus);
my (@url1, @url2);
sub ImageLinksWordsOverlapSub {
$_ = shift;
my @args = split("\t");
my $source = $args[0];
my $target = $args[1];
my $path = "";
$pairFile = $args[2];
my $outputPath = $args[3];
$directory = $path;
mkdir $outputPath. "$source-$target-output/" unless (-d $outputPath. "$source-$target-output/");
$output = $outputPath . "$source-$target-output/$source-$target-ImageLinksWordOverlap.txt";
open OUTPUT, "> $output" or die "Couldn't open file $output: $!\n";
open INPUT, $pairFile or die "Couldn't open file $pairFile: $!\n";
print OUTPUT "Comparability Level\tDocName_1\tDocName_2\tLinksOut_1\tLinksOut_2\tImageLinkWordsOverlap\n";
while (<INPUT>) {
if (/DocName_1/) {
}
else
{
@url1 = ();
@url2 = ();
$HTMLstatus = "ok";
my @data = split("\t");
my ($comparabilityLevel, $initDocName1, $docName1, $folder1, $domain1, $genre1, $url1, $initDocName2, $docName2, $folder2, $domain2, $genre2, $url2);
$comparabilityLevel = "null";
print OUTPUT "$comparabilityLevel\t";
$initDocName1 = $data[0];
print OUTPUT "$initDocName1\t";
$docName1 = $data[2];
if (-e $docName1) {
open INPUT1, $docName1 or die "Couldn't open file $docName1: $!\n";
while (<INPUT1>) {
my $sentence = $_;
chomp ($sentence);
while ($sentence =~ /&/) {
$sentence =~ s/&/&/g;
}
$sentence =~ s/"/\"/g;
$sentence =~ s/&\#039;/\'/g;
$sentence =~ s/</</g;
$sentence =~ s/>/>/g;
$_ = $sentence;
while ( /<img [^>]*src=[\"\']+([^( )]+)[\"\']+[>]*/gi) {
#print "-- url1: $1\n";
my @url1temp = split(/[ \t\":;\-_\',&*\+?!\.\(\)\/]+/, $1);
push(@url1, @url1temp);
}
}
close INPUT1;
}
$initDocName2 = $data[4];
print OUTPUT "$initDocName2\t";
$docName2 = $data[6];
if (-e $docName2) {
open INPUT2, $docName2 or die "Couldn't open file $docName2: $!\n";
while (<INPUT2>) {
my $sentence = $_;
chomp ($sentence);
while ($sentence =~ /&/) {
$sentence =~ s/&/&/g;
}
$sentence =~ s/"/\"/g;
$sentence =~ s/&\#039;/\'/g;
$sentence =~ s/</</g;
$sentence =~ s/>/>/g;
$_ = $sentence;
while ( /<img [^>]*src=[\"\']+([^( )]+)[\"\']+[>]*/gi) {
my @url2temp = split(/[ \t\":;\-_\',&*\+?!\.\(\)\/]+/, $1);
#print "-- url2: $1\n";
push(@url2, @url2temp);
}
}
close INPUT2;
}
if ((-e $docName1) && (-e $docName2))
{
my $url1size = scalar @url1;
my $url2size = scalar @url2;
print OUTPUT "$url1size\t$url2size\t";
my $overlap = 0;
for(my $i = 0; $i < $url1size; $i++) {
for (my $j = 0; $j < $url2size; $j++) {
#This is where we match every combination of url 1 and url 2
# if URL words equals jpg, png, gif, jpeg, www, http, ignore them all.
if (($url1[$i] eq "jpg") || ($url1[$i] eq "jpeg") || ($url1[$i] eq "png") || ($url1[$i] eq "gif") || ($url1[$i] eq "www") || ($url1[$i] eq "http")) {
}
elsif (($url1[$i] eq $url2[$j]) && ($url1[$i] ne "")) {
$url1[$i] = "";
$url2[$j] = "";
$overlap++;
#print "It's the same";
}
}
}
my $normOverlap = "null";
if ($overlap != 0) {
$normOverlap = $overlap/($url1size*$url2size);
}
elsif ($url1size*$url2size > 0) {
$normOverlap = $overlap/($url1size*$url2size);
}
print OUTPUT "$normOverlap";
@url1 = ();
@url2 = ();
}
else {
print OUTPUT "null\tnull\tnull";
@url1 = ();
@url2 = ();
}
print OUTPUT "\n";
}
}
}
1; | 25.455696 | 156 | 0.496768 |
ed7987d4c1c6960e68858e7a5cc0a569c0b21a6c | 1,068 | pm | Perl | lib/EnsEMBL/REST/View/SeqXML.pm | nuno-agostinho/ensembl-rest | 365c592c56656485c4a6d471d62be2953bccec29 | [
"Apache-2.0"
]
| null | null | null | lib/EnsEMBL/REST/View/SeqXML.pm | nuno-agostinho/ensembl-rest | 365c592c56656485c4a6d471d62be2953bccec29 | [
"Apache-2.0"
]
| null | null | null | lib/EnsEMBL/REST/View/SeqXML.pm | nuno-agostinho/ensembl-rest | 365c592c56656485c4a6d471d62be2953bccec29 | [
"Apache-2.0"
]
| null | null | null | =head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::REST::View::SeqXML;
use Moose;
use namespace::autoclean;
extends 'Catalyst::View';
sub process {
my ($self, $c, $stash_key) = @_;
$stash_key ||= 'rest';
$c->res->body(${$self->encode_seq($c, $stash_key)});
$c->res->headers->header('Content-Type' => 'text/x-seqxml+xml');
return 1;
}
with 'EnsEMBL::REST::Role::Sequence';
1;
| 28.864865 | 101 | 0.743446 |
ed5fc8b586c3dba685c89f25f607c3d58ea941bb | 9,056 | pm | Perl | lib/Template/Plugin.pm | plicease-pr/Template | 464a896a6ffc02e16c03a5bf4dc627e8526739a7 | [
"BSD-Source-Code"
]
| 84 | 2015-01-06T15:02:47.000Z | 2022-03-04T12:56:32.000Z | lib/Template/Plugin.pm | plicease-pr/Template | 464a896a6ffc02e16c03a5bf4dc627e8526739a7 | [
"BSD-Source-Code"
]
| 193 | 2015-01-01T22:22:06.000Z | 2022-03-03T06:39:40.000Z | lib/Template/Plugin.pm | plicease-pr/Template | 464a896a6ffc02e16c03a5bf4dc627e8526739a7 | [
"BSD-Source-Code"
]
| 65 | 2015-01-01T21:25:26.000Z | 2022-01-17T16:19:27.000Z | #============================================================= -*-Perl-*-
#
# Template::Plugin
#
# DESCRIPTION
#
# Module defining a base class for a plugin object which can be loaded
# and instantiated via the USE directive.
#
# AUTHOR
# Andy Wardley <abw@wardley.org>
#
# COPYRIGHT
# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
#
# This module is free software; you can redistribute it an/or
# modify it under the same terms as Perl itself.
#
#============================================================================
package Template::Plugin;
use strict;
use warnings;
use base 'Template::Base';
our $VERSION = '3.009';
our $DEBUG = 0 unless defined $DEBUG;
our $ERROR = '';
our $AUTOLOAD;
#========================================================================
# ----- CLASS METHODS -----
#========================================================================
#------------------------------------------------------------------------
# load()
#
# Class method called when the plugin module is first loaded. It
# returns the name of a class (by default, its own class) or a prototype
# object which will be used to instantiate new objects. The new()
# method is then called against the class name (class method) or
# prototype object (object method) to create a new instances of the
# object.
#------------------------------------------------------------------------
sub load {
return $_[0];
}
#------------------------------------------------------------------------
# new($context, $delegate, @params)
#
# Object constructor which is called by the Template::Context to
# instantiate a new Plugin object. This base class constructor is
# used as a general mechanism to load and delegate to other Perl
# modules. The context is passed as the first parameter, followed by
# a reference to a delegate object or the name of the module which
# should be loaded and instantiated. Any additional parameters passed
# to the USE directive are forwarded to the new() constructor.
#
# A plugin object is returned which has an AUTOLOAD method to delegate
# requests to the underlying object.
#------------------------------------------------------------------------
sub new {
my $class = shift;
bless {
}, $class;
}
#------------------------------------------------------------------------
# fail($error)
#
# Version 1 error reporting function, now replaced by error() inherited
# from Template::Base. Raises a "deprecated function" warning and then
# calls error().
#------------------------------------------------------------------------
sub fail {
my $class = shift;
my ($pkg, $file, $line) = caller();
warn "Template::Plugin::fail() is deprecated at $file line $line. Please use error()\n";
$class->error(@_);
}
1;
__END__
=head1 NAME
Template::Plugin - Base class for Template Toolkit plugins
=head1 SYNOPSIS
package MyOrg::Template::Plugin::MyPlugin;
use base qw( Template::Plugin );
use Template::Plugin;
use MyModule;
sub new {
my $class = shift;
my $context = shift;
bless {
...
}, $class;
}
=head1 DESCRIPTION
A "plugin" for the Template Toolkit is simply a Perl module which
exists in a known package location (e.g. C<Template::Plugin::*>) and
conforms to a regular standard, allowing it to be loaded and used
automatically.
The C<Template::Plugin> module defines a base class from which other
plugin modules can be derived. A plugin does not have to be derived
from Template::Plugin but should at least conform to its object-oriented
interface.
It is recommended that you create plugins in your own package namespace
to avoid conflict with toolkit plugins. e.g.
package MyOrg::Template::Plugin::FooBar;
Use the L<PLUGIN_BASE|Template::Manual::Config#PLUGIN_BASE> option to specify
the namespace that you use. e.g.
use Template;
my $template = Template->new({
PLUGIN_BASE => 'MyOrg::Template::Plugin',
});
=head1 METHODS
The following methods form the basic interface between the Template
Toolkit and plugin modules.
=head2 load($context)
This method is called by the Template Toolkit when the plugin module
is first loaded. It is called as a package method and thus implicitly
receives the package name as the first parameter. A reference to the
L<Template::Context> object loading the plugin is also passed. The
default behaviour for the C<load()> method is to simply return the class
name. The calling context then uses this class name to call the C<new()>
package method.
package MyPlugin;
sub load { # called as MyPlugin->load($context)
my ($class, $context) = @_;
return $class; # returns 'MyPlugin'
}
=head2 new($context, @params)
This method is called to instantiate a new plugin object for the C<USE>
directive. It is called as a package method against the class name returned by
L<load()>. A reference to the L<Template::Context> object creating the plugin
is passed, along with any additional parameters specified in the C<USE>
directive.
sub new { # called as MyPlugin->new($context)
my ($class, $context, @params) = @_;
bless {
_CONTEXT => $context,
}, $class; # returns blessed MyPlugin object
}
=head2 error($error)
This method, inherited from the L<Template::Base> module, is used for
reporting and returning errors. It can be called as a package method
to set/return the C<$ERROR> package variable, or as an object method to
set/return the object C<_ERROR> member. When called with an argument, it
sets the relevant variable and returns C<undef.> When called without an
argument, it returns the value of the variable.
package MyPlugin;
use base 'Template::Plugin';
sub new {
my ($class, $context, $dsn) = @_;
return $class->error('No data source specified')
unless $dsn;
bless {
_DSN => $dsn,
}, $class;
}
package main;
my $something = MyPlugin->new()
|| die MyPlugin->error(), "\n";
$something->do_something()
|| die $something->error(), "\n";
=head1 DEEPER MAGIC
The L<Template::Context> object that handles the loading and use of plugins
calls the L<new()> and L<error()> methods against the package name returned by
the L<load()> method. In pseudo-code terms looks something like this:
$class = MyPlugin->load($context); # returns 'MyPlugin'
$object = $class->new($context, @params) # MyPlugin->new(...)
|| die $class->error(); # MyPlugin->error()
The L<load()> method may alternately return a blessed reference to an
object instance. In this case, L<new()> and L<error()> are then called as
I<object> methods against that prototype instance.
package YourPlugin;
sub load {
my ($class, $context) = @_;
bless {
_CONTEXT => $context,
}, $class;
}
sub new {
my ($self, $context, @params) = @_;
return $self;
}
In this example, we have implemented a 'Singleton' plugin. One object
gets created when L<load()> is called and this simply returns itself for
each call to L<new().>
Another implementation might require individual objects to be created
for every call to L<new(),> but with each object sharing a reference to
some other object to maintain cached data, database handles, etc.
This pseudo-code example demonstrates the principle.
package MyServer;
sub load {
my ($class, $context) = @_;
bless {
_CONTEXT => $context,
_CACHE => { },
}, $class;
}
sub new {
my ($self, $context, @params) = @_;
MyClient->new($self, @params);
}
sub add_to_cache { ... }
sub get_from_cache { ... }
package MyClient;
sub new {
my ($class, $server, $blah) = @_;
bless {
_SERVER => $server,
_BLAH => $blah,
}, $class;
}
sub get {
my $self = shift;
$self->{ _SERVER }->get_from_cache(@_);
}
sub put {
my $self = shift;
$self->{ _SERVER }->add_to_cache(@_);
}
When the plugin is loaded, a C<MyServer> instance is created. The L<new()>
method is called against this object which instantiates and returns a C<MyClient>
object, primed to communicate with the creating C<MyServer>.
=head1 AUTHOR
Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
=head1 COPYRIGHT
Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=head1 SEE ALSO
L<Template>, L<Template::Plugins>, L<Template::Context>
=cut
# Local Variables:
# mode: perl
# perl-indent-level: 4
# indent-tabs-mode: nil
# End:
#
# vim: expandtab shiftwidth=4:
| 29.212903 | 93 | 0.602142 |
ed0c3ca98cbbd185938c1673af8a1d98a3c05225 | 4,831 | pl | Perl | webapp/perl/local/lib/perl5/auto/share/dist/DateTime-Locale/sv-FI.pl | tomoyanp/isucon9-qualify-20210912 | f84b5d1c82f9d41bbba02422c1a6acd358d9c41a | [
"MIT"
]
| null | null | null | webapp/perl/local/lib/perl5/auto/share/dist/DateTime-Locale/sv-FI.pl | tomoyanp/isucon9-qualify-20210912 | f84b5d1c82f9d41bbba02422c1a6acd358d9c41a | [
"MIT"
]
| 5 | 2021-05-20T04:16:14.000Z | 2022-02-12T01:40:02.000Z | webapp/perl/local/lib/perl5/auto/share/dist/DateTime-Locale/sv-FI.pl | matsubara0507/isucon9-kansousen | 77b19085d76add98a3ce7370063a8636cde62499 | [
"MIT"
]
| null | null | null | {
am_pm_abbreviated => [
"fm",
"em",
],
available_formats => {
Bh => "h B",
Bhm => "h:mm B",
Bhms => "h:mm:ss B",
E => "ccc",
EBhm => "E h:mm B",
EBhms => "E h:mm:ss B",
EHm => "E HH:mm",
EHms => "E HH:mm:ss",
Ed => "E d",
Ehm => "E h:mm a",
Ehms => "E h:mm:ss a",
Gy => "y G",
GyMMM => "MMM y G",
GyMMMEd => "E d MMM y G",
GyMMMd => "d MMM y G",
H => "HH",
Hm => "HH:mm",
Hms => "HH:mm:ss",
Hmsv => "HH:mm:ss v",
Hmv => "HH:mm v",
M => "L",
MEd => "E d/M",
MMM => "LLL",
MMMEd => "E d MMM",
MMMMEd => "E d MMMM",
"MMMMW-count-one" => "'vecka' W 'i' MMMM",
"MMMMW-count-other" => "'vecka' W 'i' MMMM",
MMMMd => "d MMMM",
MMMd => "d MMM",
MMd => "d/M",
MMdd => "dd/MM",
Md => "d/M",
d => "d",
h => "h a",
hm => "h:mm a",
hms => "h:mm:ss a",
hmsv => "h:mm:ss a v",
hmv => "h:mm a v",
ms => "mm:ss",
y => "y",
yM => "y-MM",
yMEd => "E, y-MM-dd",
yMM => "y-MM",
yMMM => "MMM y",
yMMMEd => "E d MMM y",
yMMMM => "MMMM y",
yMMMd => "d MMM y",
yMd => "y-MM-dd",
yQQQ => "QQQ y",
yQQQQ => "QQQQ y",
"yw-count-one" => "'vecka' w, Y",
"yw-count-other" => "'vecka' w, Y",
},
code => "sv-FI",
date_format_full => "EEEE d MMMM y",
date_format_long => "d MMMM y",
date_format_medium => "d MMM y",
date_format_short => "dd-MM-y",
datetime_format_full => "{1} {0}",
datetime_format_long => "{1} {0}",
datetime_format_medium => "{1} {0}",
datetime_format_short => "{1} {0}",
day_format_abbreviated => [
"m\N{U+00e5}n",
"tis",
"ons",
"tors",
"fre",
"l\N{U+00f6}r",
"s\N{U+00f6}n",
],
day_format_narrow => [
"M",
"T",
"O",
"T",
"F",
"L",
"S",
],
day_format_wide => [
"m\N{U+00e5}ndag",
"tisdag",
"onsdag",
"torsdag",
"fredag",
"l\N{U+00f6}rdag",
"s\N{U+00f6}ndag",
],
day_stand_alone_abbreviated => [
"m\N{U+00e5}n",
"tis",
"ons",
"tors",
"fre",
"l\N{U+00f6}r",
"s\N{U+00f6}n",
],
day_stand_alone_narrow => [
"M",
"T",
"O",
"T",
"F",
"L",
"S",
],
day_stand_alone_wide => [
"m\N{U+00e5}ndag",
"tisdag",
"onsdag",
"torsdag",
"fredag",
"l\N{U+00f6}rdag",
"s\N{U+00f6}ndag",
],
era_abbreviated => [
"f.Kr.",
"e.Kr.",
],
era_narrow => [
"f.Kr.",
"e.Kr.",
],
era_wide => [
"f\N{U+00f6}re Kristus",
"efter Kristus",
],
first_day_of_week => 1,
glibc_date_1_format => "%a %-d.%-m.%Y %H.%M.%S %z",
glibc_date_format => "%d.%m.%Y",
glibc_datetime_format => "%a %e. %B %Y %H.%M.%S",
glibc_time_12_format => "%I:%M:%S %p",
glibc_time_format => "%H.%M.%S",
language => "Swedish",
month_format_abbreviated => [
"jan.",
"feb.",
"mars",
"apr.",
"maj",
"juni",
"juli",
"aug.",
"sep.",
"okt.",
"nov.",
"dec.",
],
month_format_narrow => [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
],
month_format_wide => [
"januari",
"februari",
"mars",
"april",
"maj",
"juni",
"juli",
"augusti",
"september",
"oktober",
"november",
"december",
],
month_stand_alone_abbreviated => [
"jan.",
"feb.",
"mars",
"apr.",
"maj",
"juni",
"juli",
"aug.",
"sep.",
"okt.",
"nov.",
"dec.",
],
month_stand_alone_narrow => [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
],
month_stand_alone_wide => [
"januari",
"februari",
"mars",
"april",
"maj",
"juni",
"juli",
"augusti",
"september",
"oktober",
"november",
"december",
],
name => "Swedish Finland",
native_language => "svenska",
native_name => "svenska Finland",
native_script => undef,
native_territory => "Finland",
native_variant => undef,
quarter_format_abbreviated => [
"Q1",
"Q2",
"Q3",
"Q4",
],
quarter_format_narrow => [
1,
2,
3,
4,
],
quarter_format_wide => [
"1:a kvartalet",
"2:a kvartalet",
"3:e kvartalet",
"4:e kvartalet",
],
quarter_stand_alone_abbreviated => [
"Q1",
"Q2",
"Q3",
"Q4",
],
quarter_stand_alone_narrow => [
1,
2,
3,
4,
],
quarter_stand_alone_wide => [
"1:a kvartalet",
"2:a kvartalet",
"3:e kvartalet",
"4:e kvartalet",
],
script => undef,
territory => "Finland",
time_format_full => "'kl'. HH:mm:ss zzzz",
time_format_long => "HH:mm:ss z",
time_format_medium => "HH:mm:ss",
time_format_short => "HH:mm",
variant => undef,
version => 35,
}
| 17.440433 | 53 | 0.445249 |
ed09f29297138b7cd9e8677778818c70cf2218ca | 2,599 | t | Perl | external/sbml/bindings/perl/t/03__DowncastSBase.t | dchandran/evolvenetworks | 072f9e1292552f691a86457ffd16a5743724fb5e | [
"BSD-3-Clause"
]
| 1 | 2019-08-22T17:17:41.000Z | 2019-08-22T17:17:41.000Z | external/sbml/bindings/perl/t/03__DowncastSBase.t | dchandran/evolvenetworks | 072f9e1292552f691a86457ffd16a5743724fb5e | [
"BSD-3-Clause"
]
| null | null | null | external/sbml/bindings/perl/t/03__DowncastSBase.t | dchandran/evolvenetworks | 072f9e1292552f691a86457ffd16a5743724fb5e | [
"BSD-3-Clause"
]
| null | null | null | # Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl GRN-Models.t'
#########################
# change 'tests => 1' to 'tests => last_test_to_print';
use Test;
BEGIN { plan tests => 390 };
use LibSBML;
use strict;
use Data::Dumper;
#########################
# Insert your test code below, the Test::More module is use()ed here so read
# its man page ( perldoc Test::More ) for help writing this test script.
my @SBaseClassList = (
"FunctionDefinition",
"UnitDefinition",
"CompartmentType",
"SpeciesType",
"Compartment",
"Species",
"Parameter",
"InitialAssignment",
"AssignmentRule",
"AlgebraicRule",
"RateRule",
"Constraint",
"Reaction",
"SpeciesReference",
"ModifierSpeciesReference",
"Event",
"EventAssignment",
"Unit",
"UnitDefinition",
"Trigger",
"Delay",
"ListOf",
"ListOfCompartments",
"ListOfCompartmentTypes",
"ListOfConstraints",
"ListOfEvents",
"ListOfEventAssignments",
"ListOfFunctionDefinitions",
"ListOfInitialAssignments",
"ListOfParameters",
"ListOfReactions",
"ListOfRules",
"ListOfSpecies",
"ListOfSpeciesReferences",
"ListOfSpeciesTypes",
"ListOfUnits",
"ListOfUnitDefinitions",
"StoichiometryMath",
);
my @MiscClassList = (
"XMLToken",
"XMLNode",
"XMLTriple",
"CVTerm",
"Date",
"ModelCreator",
"XMLAttributes",
"XMLNamespaces",
);
#########################
my $lo = new LibSBML::ListOf;
my $level = LibSBML::SBMLDocument::getDefaultLevel();
my $version = LibSBML::SBMLDocument::getDefaultVersion();
foreach my $class ( map { "LibSBML::" . $_ } @SBaseClassList )
{
my $obj = ($class !~ /ListOf/) ? new $class($level,$version) : new $class;
ok(&isOwned($obj), 1);
ok(ref $obj, $class);
my $clone = &checkClone($obj,ref($obj));
$lo->append($clone);
ok(ref $lo->get(0), $class);
ok(&isOwned($lo->get(0)), undef);
ok(&isOwned($lo->remove(0)), 1);
}
foreach my $class ( map { "LibSBML::" . $_ } @MiscClassList )
{
my $obj = new $class;
ok(&isOwned($obj), 1);
ok(ref $obj, $class);
my $clone = &checkClone($obj,ref($obj));
}
#########################
sub checkClone {
my($obj,$class) = @_;
ok(&isOwned($obj), 1);
ok(ref($obj), $class);
my $clone = $obj->clone();
ok(&isOwned($clone), 1);
ok(ref($clone), $class);
$clone;
}
#
# ownership check code for SBase derived classes.
#
no strict 'refs';
sub isOwned {
my $self = shift;
my $ptr = tied(%$self);
my $class = ref($self);
return ${"${class}::OWNER"}{$ptr};
}
| 19.839695 | 77 | 0.60908 |
ed69282af0dcc8b872a01b94bc71a72c80b6a7cd | 4,222 | t | Perl | t/55_statistics_info.t | HaraldJoerg/DBD-SQLite | 711f90b8c75b2995eca43952aac7775c19ad8d28 | [
"Artistic-1.0"
]
| 16 | 2015-01-12T20:06:58.000Z | 2022-03-14T11:05:55.000Z | t/55_statistics_info.t | HaraldJoerg/DBD-SQLite | 711f90b8c75b2995eca43952aac7775c19ad8d28 | [
"Artistic-1.0"
]
| 88 | 2015-01-06T12:44:31.000Z | 2022-03-12T02:53:37.000Z | t/55_statistics_info.t | HaraldJoerg/DBD-SQLite | 711f90b8c75b2995eca43952aac7775c19ad8d28 | [
"Artistic-1.0"
]
| 29 | 2015-04-15T22:30:37.000Z | 2021-12-14T21:17:31.000Z | use strict;
use warnings;
use lib "t/lib";
use SQLiteTest;
use Test::More;
BEGIN {
use DBD::SQLite;
unless ($DBD::SQLite::sqlite_version_number && $DBD::SQLite::sqlite_version_number >= 3006019) {
plan skip_all => "this test requires SQLite 3.6.19 and newer";
exit;
}
}
use if -d ".git", "Test::FailWarnings";
my @sql_statements = split /\n\n/, <<__EOSQL__;
CREATE TABLE a (
id INTEGER,
fname TEXT,
lname TEXT,
UNIQUE(id)
);
CREATE INDEX "a_fn" ON "a" ( "fname" );
CREATE INDEX "a_ln" ON "a" ( "lname" );
CREATE UNIQUE INDEX "a_an" ON "a" ( "fname", "lname" );
ATTACH DATABASE ':memory:' AS remote;
CREATE TABLE remote.b (
id INTEGER,
fname TEXT,
lname TEXT,
PRIMARY KEY(id),
UNIQUE(fname, lname)
);
__EOSQL__
my $dbh = connect_ok( RaiseError => 1, PrintError => 0, AutoCommit => 1 );
my $sth;
my $stats_data;
my $R = \%DBD::SQLite::db::DBI_code_for_rule;
ok ($dbh->do($_), $_) foreach @sql_statements;
for my $table_name ('a', 'A') {
$sth = $dbh->statistics_info(undef, undef, $table_name, 0, 0);
$stats_data = $sth->fetchall_hashref([ 'INDEX_NAME', 'ORDINAL_POSITION' ]);
for ($stats_data->{a_fn}->{1}) {
is($_->{TABLE_NAME}, "a" , "table name");
is($_->{COLUMN_NAME}, "fname", "column name");
is($_->{TYPE}, "btree", "type");
is($_->{ORDINAL_POSITION}, 1, "ordinal position");
is($_->{NON_UNIQUE}, 1, "non unique");
is($_->{INDEX_NAME}, "a_fn", "index name");
is($_->{TABLE_SCHEM}, "main", "table schema");
}
ok(not(exists $stats_data->{a_fn}->{2}), "only one index in a_fn index");
for ($stats_data->{a_ln}->{1}) {
is($_->{TABLE_NAME}, "a" , "table name");
is($_->{COLUMN_NAME}, "lname", "column name");
is($_->{TYPE}, "btree", "type");
is($_->{ORDINAL_POSITION}, 1, "ordinal position");
is($_->{NON_UNIQUE}, 1, "non unique");
is($_->{INDEX_NAME}, "a_ln", "index name");
is($_->{TABLE_SCHEM}, "main", "table schema");
}
ok(not(exists $stats_data->{a_ln}->{2}), "only one index in a_ln index");
for ($stats_data->{a_an}->{1}) {
is($_->{TABLE_NAME}, "a" , "table name");
is($_->{COLUMN_NAME}, "fname", "column name");
is($_->{TYPE}, "btree", "type");
is($_->{ORDINAL_POSITION}, 1, "ordinal position");
is($_->{NON_UNIQUE}, 0, "non unique");
is($_->{INDEX_NAME}, "a_an", "index name");
is($_->{TABLE_SCHEM}, "main", "table schema");
}
for ($stats_data->{a_an}->{2}) {
is($_->{TABLE_NAME}, "a" , "table name");
is($_->{COLUMN_NAME}, "lname", "column name");
is($_->{TYPE}, "btree", "type");
is($_->{ORDINAL_POSITION}, 2, "ordinal position");
is($_->{NON_UNIQUE}, 0, "non unique");
is($_->{INDEX_NAME}, "a_an", "index name");
is($_->{TABLE_SCHEM}, "main", "table schema");
}
ok(not(exists $stats_data->{a_ln}->{3}), "only two indexes in a_an index");
$sth = $dbh->statistics_info(undef, undef, $table_name, 'unique only', 0);
$stats_data = $sth->fetchall_hashref([ 'INDEX_NAME', 'ORDINAL_POSITION' ]);
for ($stats_data->{a_an}->{1}) {
is($_->{TABLE_NAME}, "a" , "table name");
is($_->{COLUMN_NAME}, "fname", "column name");
is($_->{TYPE}, "btree", "type");
is($_->{ORDINAL_POSITION}, 1, "ordinal position");
is($_->{NON_UNIQUE}, 0, "non unique");
is($_->{INDEX_NAME}, "a_an", "index name");
is($_->{TABLE_SCHEM}, "main", "table schema");
}
for ($stats_data->{a_an}->{2}) {
is($_->{TABLE_NAME}, "a" , "table name");
is($_->{COLUMN_NAME}, "lname", "column name");
is($_->{TYPE}, "btree", "type");
is($_->{ORDINAL_POSITION}, 2, "ordinal position");
is($_->{NON_UNIQUE}, 0, "non unique");
is($_->{INDEX_NAME}, "a_an", "index name");
is($_->{TABLE_SCHEM}, "main", "table schema");
}
ok(not(exists $stats_data->{a_ln}->{3}), "only two indexes in a_an index");
}
done_testing;
| 35.478992 | 100 | 0.531028 |
ed6ca22b4a4ca6620c90ceec2769069447abfc14 | 11,537 | pl | Perl | util/filter_fasta_by_rsem_values.pl | chenx-bob/trinityrnaseq | 5cc19070ceb461af107de79d568aed0b0e24d580 | [
"BSD-3-Clause"
]
| 1 | 2017-12-29T10:55:27.000Z | 2017-12-29T10:55:27.000Z | util/filter_fasta_by_rsem_values.pl | binlu1981/trinityrnaseq | 5cc19070ceb461af107de79d568aed0b0e24d580 | [
"BSD-3-Clause"
]
| null | null | null | util/filter_fasta_by_rsem_values.pl | binlu1981/trinityrnaseq | 5cc19070ceb461af107de79d568aed0b0e24d580 | [
"BSD-3-Clause"
]
| 1 | 2020-06-21T01:02:04.000Z | 2020-06-21T01:02:04.000Z | #!/usr/bin/env perl
=head1 NAME
filter_fasta_by_rsem_values.pl - Use RSEM relative abundance values to filter a
transcript assembly FASTA file
=head1 SYNOPSIS
USAGE: filter_fasta_by_rsem_values.pl
--rsem_output=/path/to/RSEM.isoforms.results[,...]
--fasta=/path/to/Trinity.fasta
--output=/path/to/output.fasta
[ --tpm_cutoff=1.0
--fpkm_cutoff=0.5
--isopct_cutoff=0.05
]
=head1 OPTIONS
B<--rsem_output,-r>
This file is the RSEM output file, usually from util/RSEM_util/run_RSEM.pl
Provide a comma-separated list for multiple RSEM output files, or specify
parameter like so:
-r RSEM.isoforms.A -r RSEM.isoforms.B -r RSEM.isoforms.C ...
B<--fasta,-f>
The FASTA file representing transcript assemblies from the primary Trinity run.
B<--output,-o>
The output FASTA file to be created. These are the sequences whose scores are
greater or equal to the user-specified cutoffs.
B<--filtered_output,-e>
Optional. Pass this if you want a FASTA file created of those sequences which
do NOT meet the user-specified cutoffs.
B<--tpm_cutoff,-t>
Optional. Will filter transcripts, keeping those with TPM values equal to or
greater than this. See the INPUT section for more detail here.
B<--fpkm_cutoff,-c>
Optional. Will filter transcripts, keeping those with FPKM values equal to or
greater than this. See the INPUT section for more detail here.
B<--isopct_cutoff,-i>
Optional. Will filter transcripts, keeping those with isoform percentage values
equal to or greater than this. See the INPUT section for more detail here.
B<--log,-l>
Log file
B<--help,-h>
This help message
=head1 DESCRIPTION
Trinity contains a pipeline for read alignment, visualization and relative abundance
estimation here:
http://trinityrnaseq.sourceforge.net/analysis/align_visualize_quantify.html
Among the products of this is the file 'RSEM.isoforms.results', which contains calculated
values such as TPM, FPKM and IsoPct. See INPUT for more on this.
The user can use this RSEM file to filter the source transcript assembly FASTA file
based on any combination of these cutoffs.
=head1 INPUT
The input RSEM file looks like this:
transcript_id gene_id length effective_length expected_count TPM FPKM IsoPct
comp100579_c0_seq1 comp100579_c0 204 10.71 0.00 0.00 0.00 0.00
comp100585_c0_seq1 comp100585_c0 301 85.75 0.00 0.00 0.00 0.00
comp100592_c0_seq1 comp100592_c0 439 222.65 9.00 0.39 0.31 100.00
comp100599_c0_seq1 comp100599_c0 268 54.93 0.00 0.00 0.00 0.00
comp100606_c0_seq1 comp100606_c0 807 590.56 36.65 0.60 0.47 16.24
comp100606_c0_seq2 comp100606_c0 783 566.56 181.35 3.10 2.44 83.76
The corresponding input FASTA has headers like:
>comp100579_c0_seq1 len=204 path=[1:0-203]
>comp100585_c0_seq1 len=301 path=[1:0-88 90:89-300]
>comp100592_c0_seq1 len=439 path=[1:0-438]
>comp100599_c0_seq1 len=268 path=[1:0-267]
>comp100606_c0_seq1 len=807 path=[1:0-285 784:286-309 287:310-806]
>comp100606_c0_seq2 len=783 path=[1:0-285 287:286-782]
To do the actual filtering, you need to pass at least one of the cutoff parameters.
They are additive - if more than one are passed, each will be applied to futher filter
the input set.
There are filters for TPM, FPKM, and PctIso. From the RSEM documentation, they are:
'TPM' stands for Transcripts Per Million. It is a relative measure of transcript abundance. The
sum of all transcripts' TPM is 1 million. 'FPKM' stands for Fragments Per Kilobase of transcript
per Million mapped reads. It is another relative measure of transcript abundance. 'IsoPct' stands
for isoform percentage. It is the percentage of this transcript's abandunce over its parent gene's
abandunce. If its parent gene has only one isoform or the gene information is not provided, this
field will be set to 100.
=head1 OUTPUT
The output is a FASTA file with the same headers and sequence, only filtered based
on the parameters passed.
=head1 CONTACT
Joshua Orvis
jorvis@gmail.com
=cut
use warnings;
use strict;
use Getopt::Long qw(:config no_ignore_case no_auto_abbrev pass_through);
use Pod::Usage;
my %options = ();
my $results = GetOptions (\%options,
'rsem_output|r=s@',
'fasta|f=s',
'output|o=s',
'tpm_cutoff|t=s',
'fpkm_cutoff|c=s',
'isopct_cutoff|i=s',
'filtered_output|e=s',
'log|l=s',
'help|h') || pod2usage();
## display documentation
if( $options{'help'} ){
pod2usage( {-exitval => 0, -verbose => 2, -output => \*STDERR} );
}
if (@ARGV) {
die "Error, did not recognize parameters: @ARGV ";
}
## make sure everything passed was peachy
&check_parameters(\%options);
## open the log if requested
my $logfh;
if (defined $options{log}) {
open($logfh, ">$options{log}") || die "can't create log file: $!";
}
_log( "INFO: cutoffs: fpkm_cutoff=(" . ($options{fpkm_cutoff} || '') . "), perc_comp_fpkm_cutoff=(" . ($options{perc_comp_fpkm_cutoff} || '') . ")");
_log( "INFO: Opening RSEM file ($options{rsem_output})" );
my $rsem = load_rsem_output( $options{rsem_output} );
_log( "INFO: creating output file: ($options{output})" );
open(my $ofh, ">$options{output}") || logdie("ERROR: failed to create output file: $!");
open (my $rsem_ofh, ">$options{output}.rsem") or logdie $!;
print $rsem_ofh join("\t", "transcript_id", "gene_id", "length", "effective_length",
"expected_count", "TPM", "FPKM", "IsoPct", "iso_per_gene", "rsem_filename") . "\n"; # header line
my $filtered_ofh;
if ( $options{filtered_output} ) {
_log( "INFO: creating optional filtered output file: ($options{filtered_output})" );
open($filtered_ofh, ">$options{filtered_output}") || logdie("ERROR: failed to create filtered output file: $!");
}
_log( "INFO: reading input FASTA file: ($options{fasta})" );
open( my $ifh, $options{fasta} ) || logdie("ERROR: failed to read input FASTA file: $!");
my $keep = 0;
while ( my $line = <$ifh> ) {
if ( $line =~ /^\>(\S+)/ ) {
my $seq_id = $1;
## make sure we have cutoffs for this
if ( ! exists $$rsem{$seq_id} ) {
logdie("ERROR: found a transcript ID ($seq_id) in the FASTA that wasn't in the RSEM file");
}
my $gene_id = $$rsem{iso_to_gene}->{$seq_id} or logdie("ERROR, cannot determine gene_id for $seq_id");
my $num_iso_per_gene = $$rsem{iso_count_per_gene}->{$gene_id} or logdie("ERROR, cannot determine number of isoforms for gene: $gene_id");
$keep = 1; ## optimism first. just keep swimming
my @rsem_entries = @{$$rsem{$seq_id}}; # this is why people hate or love perl.
my @rsem_entries_meet_requirements;
foreach my $rsem_entry (@rsem_entries) {
## if any individual rsem entry for this transcript meets all specified filtering criteria, then we keep it.
my $local_keep = 1;
$local_keep = 0 if ( defined $options{fpkm_cutoff} && $rsem_entry->{fpkm} < $options{fpkm_cutoff} );
$local_keep = 0 if ( defined $options{tpm_cutoff} && $rsem_entry->{tpm} < $options{tpm_cutoff} );
$local_keep = 0 if ( defined $options{isopct_cutoff} && $rsem_entry->{isopct} < $options{isopct_cutoff}
&& $num_iso_per_gene > 1);
if ($local_keep) {
push (@rsem_entries_meet_requirements, $rsem_entry);
}
}
if (@rsem_entries_meet_requirements) {
foreach my $rsem_entry (@rsem_entries_meet_requirements) {
print $rsem_ofh $rsem_entry->{line} . "\t$num_iso_per_gene\t" . $rsem_entry->{file} . "\n";
}
}
else {
$keep = 0;
}
}
print $ofh $line if $keep;
if ( $keep == 0 && $options{filtered_output} ) {
print $filtered_ofh $line;
}
}
close $ofh;
close $rsem_ofh;
exit(0);
sub load_rsem_output {
my $files_aref = shift;
my @files = split(/,/,join(',', @$files_aref));
## relative abundance data. looks like:
# $rel{'comp3119_c0_seq1'} = { fpkm => 63.55,
# tpm => 10324,
# isopct => 31.43
# }
my %rel = ();
foreach my $file (@files) {
open(my $ifh, $file) || logdie("ERROR: failed to read rsem_output file: $!");
while (my $line = <$ifh>) {
chomp $line;
next if $line =~ /^\s*$/;
my @cols = split("\t", $line);
if ( scalar @cols == 8 && $cols[3] ne 'effective length' ) {
if ( exists $rel{$cols[0]} && grep { $_->{file} eq $file } @{$rel{$cols[0]}} ) {
logdie("ERROR: found more than one entry in the RSEM file for $cols[0]");
} else {
my $struct = { fpkm => $cols[6],
tpm => $cols[5],
isopct => $cols[7],
line => $line,
file => $file,
trans => $cols[0],
gene => $cols[1],
};
push (@{$rel{$cols[0]}}, $struct);
}
}
}
}
_log("INFO: Loaded RSEM values for " . scalar(keys %rel) . " transcripts");
my %trans_to_gene;
my %gene_to_iso;
## generate trans to gene mapping and count isoforms per gene.
foreach my $trans_id (keys %rel) {
my @rsem_entries = @{$rel{$trans_id}};
foreach my $rsem_entry (@rsem_entries) {
my $gene_id = $rsem_entry->{gene};
$gene_to_iso{$gene_id}->{$trans_id} = 1;
$trans_to_gene{$trans_id} = $gene_id;
}
}
$rel{iso_to_gene} = \%trans_to_gene;
foreach my $gene_id (keys %gene_to_iso) {
my @trans = keys %{$gene_to_iso{$gene_id}};
my $num_trans = scalar(@trans);
$rel{iso_count_per_gene}->{$gene_id} = $num_trans;
}
return \%rel;
}
sub _log {
my $msg = shift;
print $logfh "$msg\n" if $logfh;
}
sub logdie {
my $msg = shift;
print STDERR "$msg\n";
print $logfh "$msg\n" if $logfh;
exit(1);
}
sub check_parameters {
my $options = shift;
## make sure required arguments were passed
my @required = qw( rsem_output fasta output );
for my $option ( @required ) {
unless ( defined $$options{$option} ) {
logdie("ERROR: --$option is a required option");
}
}
## at least one of the cutoffs must be defined
if ( ! defined $$options{fpkm_cutoff} &&
! defined $$options{tpm_cutoff} &&
! defined $$options{isopct_cutoff}) {
logdie("ERROR: You must define at least one cutoff for filtering. See the PERLDOC");
}
}
| 33.932353 | 149 | 0.584987 |
ed3c8a7d1f3a8805633ff04070b6c55e2b811515 | 2,153 | pm | Perl | lib/AndroidRank.pm | someanon/android-rank-app | f2e69c92edf8375ade41aacd2a6348db473d8f4e | [
"Apache-2.0"
]
| null | null | null | lib/AndroidRank.pm | someanon/android-rank-app | f2e69c92edf8375ade41aacd2a6348db473d8f4e | [
"Apache-2.0"
]
| null | null | null | lib/AndroidRank.pm | someanon/android-rank-app | f2e69c92edf8375ade41aacd2a6348db473d8f4e | [
"Apache-2.0"
]
| null | null | null | package AndroidRank;
use Mojo::Base -base;
use Mojo::UserAgent;
use Mojo::Util qw/url_escape trim/;
use Mojo::JSON qw/decode_json/;
sub suggest {
my ($self, %args) = @_;
my $q = url_escape($args{q});
my $url = $self->_url("searchjson?name_startsWith=$q");
my $res = Mojo::UserAgent->new->get($url)->res->body;
$res = substr $res, 1, -2;
$res = decode_json($res);
return [ map {
{ title => $_->{name}, ext_id => $_->{appid} };
} @{$res->{geonames}} ];
}
sub get_app_details {
my ($self, %args) = @_;
my $url = $self->_url("details?id=$args{ext_id}");
my $dom = Mojo::UserAgent->new->max_redirects(5)->get($url)->res->dom;
my $details = {};
$details->{title} = $dom->at('[itemprop="name"]')->text;
($details->{artist_id}) = $dom->at('h1')->next->at('a')->attr('href') =~ /id=([^&]+)/;
$details->{artist_name} = $dom->at('h1')->next->at('a')->text;
$details->{short_text} = trim $dom->at('#content')->children->[0]->children->[1]->all_text;
$details->{icon} = eval { $dom->at('[itemprop="image"]')->attr('src') };
$details->{app_info} = {
@{$dom->find('table.appstat')->[0]->find('tbody tr')->map(sub {
$_->at('th')->all_text => $_->at('td')->all_text;
})->to_array}
};
$details->{app_installs} = {
@{$dom->find('table.appstat')->[2]->find('tbody tr')->map(sub {
$_->at('th')->all_text => $_->at('td')->all_text;
})->to_array},
# + бага в вёрстке
$dom->find('table.appstat')->[2]->find('tbody > th')->first->all_text,
$dom->find('table.appstat')->[2]->find('tbody > td')->first->all_text,
};
$details->{rating_values} = {
@{$dom->find('table.appstat')->[3]->find('tbody tr')->map(sub {
$_->at('th')->all_text => $_->at('td')->all_text;
})->to_array},
};
$details->{rating_scores} = {
@{$dom->find('table[itemprop="aggregateRating"] tbody tr')->map(sub {
$_->at('th')->all_text => $_->at('td')->all_text;
})->to_array},
};
$details->{country_ratings} = {
# не понятно откуда брать, на странице нет такой инфы.
};
return $details;
}
sub _url {
my ($self, $path) = @_;
return "http://www.androidrank.org/$path";
}
1;
| 32.621212 | 93 | 0.560149 |
73ec39a6d45f96ece2b91d6c71363f87bc220046 | 15,678 | al | Perl | Apps/CZ/CoreLocalizationPack/app/Src/Codeunits/VATStatementDPHDP3.Codeunit.al | MiguelMercadoActual/ALAppExtensions | 97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b | [
"MIT"
]
| 337 | 2019-05-07T06:04:40.000Z | 2022-03-31T10:07:42.000Z | Apps/CZ/CoreLocalizationPack/app/Src/Codeunits/VATStatementDPHDP3.Codeunit.al | MiguelMercadoActual/ALAppExtensions | 97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b | [
"MIT"
]
| 14,850 | 2019-05-07T06:04:27.000Z | 2022-03-31T19:53:28.000Z | Apps/CZ/CoreLocalizationPack/app/Src/Codeunits/VATStatementDPHDP3.Codeunit.al | MiguelMercadoActual/ALAppExtensions | 97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b | [
"MIT"
]
| 374 | 2019-05-09T10:08:14.000Z | 2022-03-31T17:48:32.000Z | codeunit 11788 "VAT Statement DPHDP3 CZL" implements "VAT Statement Export CZL"
{
var
VATStmtXMLExportHelperCZL: codeunit "VAT Stmt XML Export Helper CZL";
procedure ExportToXMLFile(VATStatementName: Record "VAT Statement Name"): Text
var
FileManagement: Codeunit "File Management";
TempBlob: Codeunit "Temp Blob";
ClientFileNameLbl: Label 'VAT Statement %1 %2.xml', Comment = '%1 = VAT Statement Template Nam, %2 = VAT Statement Name';
begin
ExportToXMLBlob(VATStatementName, TempBlob);
if TempBlob.HasValue() then
exit(FileManagement.BLOBExport(TempBlob, StrSubstNo(ClientFileNameLbl, VATStatementName."Statement Template Name", VATStatementName.Name), true));
end;
procedure ExportToXMLBlob(VATStatementName: Record "VAT Statement Name"; var TempBlob: Codeunit "Temp Blob")
var
VATStatementAttachmentCZL: Record "VAT Statement Attachment CZL";
ExportVATStmtDialogCZL: Report "Export VAT Stmt. Dialog CZL";
VATStatementDPHDP3CZL: XMLport "VAT Statement DPHDP3 CZL";
XmlParams: Text;
DocumentOutStream: OutStream;
AttachmentXPathTxt: Label 'DPHDP3/Prilohy/ObecnaPriloha', Locked = true;
AttachmentNodeNameTok: Label 'jm_souboru', Locked = true;
begin
XmlParams := VATStmtXMLExportHelperCZL.GetReportRequestPageParameters(Report::"Export VAT Stmt. Dialog CZL");
VATStmtXMLExportHelperCZL.UpdateParamsVATStatementName(XmlParams, VATStatementName);
XmlParams := ExportVATStmtDialogCZL.RunRequestPage(XmlParams);
if XmlParams = '' then
exit;
VATStmtXMLExportHelperCZL.SaveReportRequestPageParameters(Report::"Export VAT Stmt. Dialog CZL", XmlParams);
VATStatementDPHDP3CZL.ClearVariables();
VATStatementDPHDP3CZL.SetXMLParams(XmlParams);
TempBlob.CreateOutStream(DocumentOutStream, TextEncoding::UTF8);
VATStatementDPHDP3CZL.SetDestination(DocumentOutStream);
VATStatementDPHDP3CZL.Export();
VATStatementDPHDP3CZL.CopyAttachmentFilter(VATStatementAttachmentCZL);
VATStmtXMLExportHelperCZL.EncodeAttachmentsToXML(TempBlob, AttachmentXPathTxt, AttachmentNodeNameTok, VATStatementAttachmentCZL);
end;
procedure InitVATAttributes(VATStatementTemplateName: Code[10])
var
L001T_XMLTok: Label 'DAN23', Locked = true;
L001B_XMLTok: Label 'OBRAT23', Locked = true;
L002T_XMLTok: Label 'DAN5', Locked = true;
L002B_XMLTok: Label 'OBRAT5', Locked = true;
L003T_XMLTok: Label 'DAN_PZB23', Locked = true;
L003B_XMLTok: Label 'P_ZB23', Locked = true;
L004T_XMLTok: Label 'DAN_PZB5', Locked = true;
L004B_XMLTok: Label 'P_ZB5', Locked = true;
L005T_XMLTok: Label 'DAN_PSL23_E', Locked = true;
L005B_XMLTok: Label 'P_SL23_E', Locked = true;
L006T_XMLTok: Label 'DAN_PSL5_E', Locked = true;
L006B_XMLTok: Label 'P_SL5_E', Locked = true;
L007T_XMLTok: Label 'DAN_DZB23', Locked = true;
L007B_XMLTok: Label 'DOV_ZB23', Locked = true;
L008T_XMLTok: Label 'DAN_DZB5', Locked = true;
L008B_XMLTok: Label 'DOV_ZB5', Locked = true;
L009T_XMLTok: Label 'DAN_PDOP_NRG', Locked = true;
L009B_XMLTok: Label 'P_DOP_NRG', Locked = true;
L010T_XMLTok: Label 'DAN_RPREN23', Locked = true;
L010B_XMLTok: Label 'REZ_PREN23', Locked = true;
L011T_XMLTok: Label 'DAN_RPREN5', Locked = true;
L011B_XMLTok: Label 'REZ_PREN5', Locked = true;
L012T_XMLTok: Label 'DAN_PSL23_Z', Locked = true;
L012B_XMLTok: Label 'P_SL23_Z', Locked = true;
L013T_XMLTok: Label 'DAN_PSL5_Z', Locked = true;
L013B_XMLTok: Label 'P_SL5_Z', Locked = true;
L020B_XMLTok: Label 'DOD_ZB', Locked = true;
L021B_XMLTok: Label 'PLN_SLUZBY', Locked = true;
L022B_XMLTok: Label 'PLN_VYVOZ', Locked = true;
L023B_XMLTok: Label 'DOD_DOP_NRG', Locked = true;
L024B_XMLTok: Label 'PLN_ZASLANI', Locked = true;
L025B_XMLTok: Label 'PLN_REZ_PREN', Locked = true;
L026B_XMLTok: Label 'PLN_OST', Locked = true;
L030B_XMLTok: Label 'TRI_POZB', Locked = true;
L031B_XMLTok: Label 'TRI_DOZB', Locked = true;
L032B_XMLTok: Label 'DOV_OSV', Locked = true;
L033T_XMLTok: Label 'OPR_VERIT', Locked = true;
L034T_XMLTok: Label 'OPR_DLUZ', Locked = true;
L040T_XMLTok: Label 'ODP_TUZ23_NAR', Locked = true;
L040C_XMLTok: Label 'ODP_TUZ23', Locked = true;
L040B_XMLTok: Label 'PLN23', Locked = true;
L041T_XMLTok: Label 'ODP_TUZ5_NAR', Locked = true;
L041C_XMLTok: Label 'ODP_TUZ5', Locked = true;
L041B_XMLTok: Label 'PLN5', Locked = true;
L042T_XMLTok: Label 'ODP_CU_NAR', Locked = true;
L042C_XMLTok: Label 'ODP_CU', Locked = true;
L042B_XMLTok: Label 'DOV_CU', Locked = true;
L043T_XMLTok: Label 'OD_ZDP23', Locked = true;
L043C_XMLTok: Label 'ODKR_ZDP23', Locked = true;
L043B_XMLTok: Label 'NAR_ZDP23', Locked = true;
L044T_XMLTok: Label 'OD_ZDP5', Locked = true;
L044C_XMLTok: Label 'ODKR_ZDP5', Locked = true;
L044B_XMLTok: Label 'NAR_ZDP5', Locked = true;
L045T_XMLTok: Label 'ODP_REZ_NAR', Locked = true;
L045C_XMLTok: Label 'ODP_REZIM', Locked = true;
L046T_XMLTok: Label 'ODP_SUM_NAR', Locked = true;
L046C_XMLTok: Label 'ODP_SUM_KR', Locked = true;
L047T_XMLTok: Label 'OD_MAJ', Locked = true;
L047C_XMLTok: Label 'ODKR_MAJ', Locked = true;
L047B_XMLTok: Label 'NAR_MAJ', Locked = true;
L050B_XMLTok: Label 'PLNOSV_KF', Locked = true;
L051W_XMLTok: Label 'PLNOSV_NKF', Locked = true;
L051D_XMLTok: Label 'PLN_NKF', Locked = true;
L052T_XMLTok: Label 'ODP_UPRAV_KF', Locked = true;
L052C_XMLTok: Label 'KOEF_P20_NOV', Locked = true;
L053T_XMLTok: Label 'VYPOR_ODP', Locked = true;
L053C_XMLTok: Label 'KOEF_P20_VYPOR', Locked = true;
L060T_XMLTok: Label 'UPRAV_ODP', Locked = true;
L061T_XMLTok: Label 'DAN_VRAC', Locked = true;
L062T_XMLTok: Label 'DAN_ZOCELK', Locked = true;
L063T_XMLTok: Label 'ODP_ZOCELK', Locked = true;
L064T_XMLTok: Label 'DANO_DA', Locked = true;
L065T_XMLTok: Label 'DANO_NO', Locked = true;
L066T_XMLTok: Label 'DANO', Locked = true;
TTok: Label 'D', Locked = true;
BTok: Label 'Z', Locked = true;
CTok: Label 'K', Locked = true;
WTok: Label 'B', Locked = true;
DTok: Label 'S', Locked = true;
XOutputtaxTxt: Label 'l. %1 - Output tax', Comment = '%1 = line number';
XTaxbaseTxt: Label 'l. %1 - Tax base', Comment = '%1 = line number';
XAcquisitionofgoodstaxbaseTxt: Label 'l. %1 - Acquisition of goods, tax base', Comment = '%1 = line number';
XDeliveryOfGoodsTaxBaseTxt: Label 'l. %1 - Delivery of goods, tax base', Comment = '%1 = line number';
XGoodsImportTaxBaseTxt: Label 'l. %1 - Goods import, tax base', Comment = '%1 = line number';
XCreditorTaxTxt: Label 'l. %1 - Creditor, tax', Comment = '%1 = line number';
XDebtorTaxTxt: Label 'l. %1 - Debtor, tax', Comment = '%1 = line number';
XInfullTxt: Label 'l. %1 - In full', Comment = '%1 = line number';
XReducedDeductionTxt: Label 'l. %1 - Reduced deduction', Comment = '%1 = line number';
XWithoutClaimOnDeductionTxt: Label 'l. %1 - Without claim on deduction', Comment = '%1 = line number';
XWithClaimOnDeductionTxt: Label 'l. %1 - With claim on deduction', Comment = '%1 = line number';
XDeductionTxt: Label 'l. %1 - Deduction', Comment = '%1 = line number';
XCoefficientTxt: Label 'l. %1 - Coefficient %', Comment = '%1 = line number';
XDeducationChangeTxt: Label 'l. %1 - Deducation change', Comment = '%1 = line number';
XSettlementCoefficientTxt: Label 'l. %1 - Settlement coefficient', Comment = '%1 = line number';
XTaxTxt: Label 'l. %1 - Tax', Comment = '%1 = line number';
begin
InsertData(VATStatementTemplateName, 01, TTok, XOutputtaxTxt, L001T_XMLTok);
InsertData(VATStatementTemplateName, 01, BTok, XTaxbaseTxt, L001B_XMLTok);
InsertData(VATStatementTemplateName, 02, TTok, XOutputtaxTxt, L002T_XMLTok);
InsertData(VATStatementTemplateName, 02, BTok, XTaxbaseTxt, L002B_XMLTok);
InsertData(VATStatementTemplateName, 03, TTok, XOutputtaxTxt, L003T_XMLTok);
InsertData(VATStatementTemplateName, 03, BTok, XTaxbaseTxt, L003B_XMLTok);
InsertData(VATStatementTemplateName, 04, TTok, XOutputtaxTxt, L004T_XMLTok);
InsertData(VATStatementTemplateName, 04, BTok, XTaxbaseTxt, L004B_XMLTok);
InsertData(VATStatementTemplateName, 05, TTok, XOutputtaxTxt, L005T_XMLTok);
InsertData(VATStatementTemplateName, 05, BTok, XTaxbaseTxt, L005B_XMLTok);
InsertData(VATStatementTemplateName, 06, TTok, XOutputtaxTxt, L006T_XMLTok);
InsertData(VATStatementTemplateName, 06, BTok, XTaxbaseTxt, L006B_XMLTok);
InsertData(VATStatementTemplateName, 07, TTok, XOutputtaxTxt, L007T_XMLTok);
InsertData(VATStatementTemplateName, 07, BTok, XTaxbaseTxt, L007B_XMLTok);
InsertData(VATStatementTemplateName, 08, TTok, XOutputtaxTxt, L008T_XMLTok);
InsertData(VATStatementTemplateName, 08, BTok, XTaxbaseTxt, L008B_XMLTok);
InsertData(VATStatementTemplateName, 09, TTok, XOutputtaxTxt, L009T_XMLTok);
InsertData(VATStatementTemplateName, 09, BTok, XTaxbaseTxt, L009B_XMLTok);
InsertData(VATStatementTemplateName, 10, TTok, XOutputtaxTxt, L010T_XMLTok);
InsertData(VATStatementTemplateName, 10, BTok, XTaxbaseTxt, L010B_XMLTok);
InsertData(VATStatementTemplateName, 11, TTok, XOutputtaxTxt, L011T_XMLTok);
InsertData(VATStatementTemplateName, 11, BTok, XTaxbaseTxt, L011B_XMLTok);
InsertData(VATStatementTemplateName, 12, TTok, XOutputtaxTxt, L012T_XMLTok);
InsertData(VATStatementTemplateName, 12, BTok, XTaxbaseTxt, L012B_XMLTok);
InsertData(VATStatementTemplateName, 13, TTok, XOutputtaxTxt, L013T_XMLTok);
InsertData(VATStatementTemplateName, 13, BTok, XTaxbaseTxt, L013B_XMLTok);
InsertData(VATStatementTemplateName, 20, BTok, XTaxbaseTxt, L020B_XMLTok);
InsertData(VATStatementTemplateName, 21, BTok, XTaxbaseTxt, L021B_XMLTok);
InsertData(VATStatementTemplateName, 22, BTok, XTaxbaseTxt, L022B_XMLTok);
InsertData(VATStatementTemplateName, 23, BTok, XTaxbaseTxt, L023B_XMLTok);
InsertData(VATStatementTemplateName, 24, BTok, XTaxbaseTxt, L024B_XMLTok);
InsertData(VATStatementTemplateName, 25, BTok, XTaxbaseTxt, L025B_XMLTok);
InsertData(VATStatementTemplateName, 26, BTok, XTaxbaseTxt, L026B_XMLTok);
InsertData(VATStatementTemplateName, 30, BTok, XAcquisitionofgoodstaxbaseTxt, L030B_XMLTok);
InsertData(VATStatementTemplateName, 31, BTok, XDeliveryOfGoodsTaxBaseTxt, L031B_XMLTok);
InsertData(VATStatementTemplateName, 32, BTok, XGoodsImportTaxBaseTxt, L032B_XMLTok);
InsertData(VATStatementTemplateName, 33, TTok, XCreditorTaxTxt, L033T_XMLTok);
InsertData(VATStatementTemplateName, 34, TTok, XDebtorTaxTxt, L034T_XMLTok);
InsertData(VATStatementTemplateName, 40, TTok, XInfullTxt, L040T_XMLTok);
InsertData(VATStatementTemplateName, 40, CTok, XReducedDeductionTxt, L040C_XMLTok);
InsertData(VATStatementTemplateName, 40, BTok, XTaxbaseTxt, L040B_XMLTok);
InsertData(VATStatementTemplateName, 41, TTok, XInfullTxt, L041T_XMLTok);
InsertData(VATStatementTemplateName, 41, CTok, XReducedDeductionTxt, L041C_XMLTok);
InsertData(VATStatementTemplateName, 41, BTok, XTaxbaseTxt, L041B_XMLTok);
InsertData(VATStatementTemplateName, 42, TTok, XInfullTxt, L042T_XMLTok);
InsertData(VATStatementTemplateName, 42, CTok, XReducedDeductionTxt, L042C_XMLTok);
InsertData(VATStatementTemplateName, 42, BTok, XTaxbaseTxt, L042B_XMLTok);
InsertData(VATStatementTemplateName, 43, TTok, XInfullTxt, L043T_XMLTok);
InsertData(VATStatementTemplateName, 43, CTok, XReducedDeductionTxt, L043C_XMLTok);
InsertData(VATStatementTemplateName, 43, BTok, XTaxbaseTxt, L043B_XMLTok);
InsertData(VATStatementTemplateName, 44, TTok, XInfullTxt, L044T_XMLTok);
InsertData(VATStatementTemplateName, 44, CTok, XReducedDeductionTxt, L044C_XMLTok);
InsertData(VATStatementTemplateName, 44, BTok, XTaxbaseTxt, L044B_XMLTok);
InsertData(VATStatementTemplateName, 45, TTok, XInfullTxt, L045T_XMLTok);
InsertData(VATStatementTemplateName, 45, CTok, XReducedDeductionTxt, L045C_XMLTok);
InsertData(VATStatementTemplateName, 46, TTok, XInfullTxt, L046T_XMLTok);
InsertData(VATStatementTemplateName, 46, CTok, XReducedDeductionTxt, L046C_XMLTok);
InsertData(VATStatementTemplateName, 47, TTok, XInfullTxt, L047T_XMLTok);
InsertData(VATStatementTemplateName, 47, CTok, XReducedDeductionTxt, L047C_XMLTok);
InsertData(VATStatementTemplateName, 47, BTok, XTaxbaseTxt, L047B_XMLTok);
InsertData(VATStatementTemplateName, 50, BTok, XTaxbaseTxt, L050B_XMLTok);
InsertData(VATStatementTemplateName, 51, WTok, XWithoutClaimOnDeductionTxt, L051W_XMLTok);
InsertData(VATStatementTemplateName, 51, DTok, XWithClaimOnDeductionTxt, L051D_XMLTok);
InsertData(VATStatementTemplateName, 52, TTok, XDeductionTxt, L052T_XMLTok);
InsertData(VATStatementTemplateName, 52, CTok, XCoefficientTxt, L052C_XMLTok);
InsertData(VATStatementTemplateName, 53, TTok, XDeducationChangeTxt, L053T_XMLTok);
InsertData(VATStatementTemplateName, 53, CTok, XSettlementCoefficientTxt, L053C_XMLTok);
InsertData(VATStatementTemplateName, 60, TTok, XTaxTxt, L060T_XMLTok);
InsertData(VATStatementTemplateName, 61, TTok, XTaxTxt, L061T_XMLTok);
InsertData(VATStatementTemplateName, 62, TTok, XTaxTxt, L062T_XMLTok);
InsertData(VATStatementTemplateName, 63, TTok, XTaxTxt, L063T_XMLTok);
InsertData(VATStatementTemplateName, 64, TTok, XTaxTxt, L064T_XMLTok);
InsertData(VATStatementTemplateName, 65, TTok, XTaxTxt, L065T_XMLTok);
InsertData(VATStatementTemplateName, 66, TTok, XTaxTxt, L066T_XMLTok);
end;
local procedure InsertData(VATStatementTemplateName: Code[10]; LineNo: Integer; Apendix: Code[1]; Description: Text[100]; XmlCode: Code[20])
var
VATAttributeCodeCZL: Record "VAT Attribute Code CZL";
AttributeCode: Code[20];
XTagFormatLbl: Label 'DP3-%1%2', Comment = '%1 = line number with a fixed length of two characters, %2 = abbreviation specifying value on a line', Locked = true;
begin
AttributeCode := StrSubstNo(XTagFormatLbl, LeftPadCode(Format(LineNo), 2, '0'), Apendix);
if VATAttributeCodeCZL.Get(VATStatementTemplateName, AttributeCode) then
exit;
VATAttributeCodeCZL.Init();
VATAttributeCodeCZL.Validate("VAT Statement Template Name", VATStatementTemplateName);
VATAttributeCodeCZL.Validate(Code, AttributeCode);
VATAttributeCodeCZL.Validate(Description, StrSubstNo(Description, LeftPadCode(Format(LineNo), 3, '0')));
VATAttributeCodeCZL.Validate("XML Code", XmlCode);
VATAttributeCodeCZL.Insert();
end;
local procedure LeftPadCode(String: Text; Length: Integer; FillCharacter: Text): Text;
begin
exit(PadStr('', Length - StrLen(String), FillCharacter) + String);
end;
} | 65.598326 | 169 | 0.706021 |
ed10c337a7113f5be80608994c65bf304131e1fb | 21,480 | pl | Perl | BarBIQ_code_1_0_0.0/BarBIQ_sub_shift.pl | Shiroguchi-Lab/BarBIQ | 25a3219c67a4ad7f1c1dbcc03b0f207106f8eee5 | [
"Artistic-1.0-Perl"
]
| 1 | 2022-02-24T03:32:56.000Z | 2022-02-24T03:32:56.000Z | BarBIQ_code_1_0_0.0/BarBIQ_sub_shift.pl | Shiroguchi-Lab/BarBIQ | 25a3219c67a4ad7f1c1dbcc03b0f207106f8eee5 | [
"Artistic-1.0-Perl"
]
| null | null | null | BarBIQ_code_1_0_0.0/BarBIQ_sub_shift.pl | Shiroguchi-Lab/BarBIQ | 25a3219c67a4ad7f1c1dbcc03b0f207106f8eee5 | [
"Artistic-1.0-Perl"
]
| null | null | null | #! /usr/bin/env perl
##########################################################################################################################################
######Description of this code#####
## This code is used to romove the shifted RepSeqs generated by insertion or deletion errors at amplification primer sites (5’ end of the I1 and R2 reads).
## The inputfile file of this code is the output file from BarBIQ_sub_clustering_step_two.pl
##########################################################################################################################################
######how to run this code #####
###command##
## BarBIQ_sub_shift.pl --in inputfile --out outputfile
###explaination##
## --in: the inputfile which is generated from BarBIQ_sub_clustering_step_two.pl.
## --out: outputfile, please set a name for your outputfile
##########################################################################################################################################
#####Install#####
## None
##########################################################################################################################################
#####code#####
use strict;
use warnings;
print "Now you are runing $0\n";
print "The parameters are: @ARGV\n";
##read command##
my ($i,$inputfile,$outputfile);
my $single_end = "No"; # this is a pair end data
my $shiftcon=7; # how many bases should be considered as a shift.
for($i=0; $i<=$#ARGV; $i=$i+2)
{
if ($ARGV[$i] eq "--in") {$inputfile = $ARGV[$i+1];}
elsif ($ARGV[$i] eq "--out") {$outputfile = $ARGV[$i+1];}
else {die "Your input is wrong!!!\n Please input \"--in inputfile --out outputfile\"\n $!";}
}
if(!$inputfile) {die "Your input is wrong!!!\n Please input \"--in: inputfile\"\n $!";}
if(!$outputfile) {die "Your input is wrong!!!\n Please input \"--out: outputfile\"\n $!";}
if(-e $outputfile){die "Your output file $outputfile is already existed!!! please check!!!\n $!";}
my $outputfile_I1="$outputfile"."_statistic_I1"; ### save the statistics of shift sequences of I1
my $outputfile_R2="$outputfile"."_statistic_R2"; ### save the statistics of shift sequences of R2
unlink $outputfile_I1;
unlink $outputfile_R2;
##read command##
##check the inputfile##
if(!(-e $inputfile)) {die "Your input file $inputfile is not existed!!! please check!!!\n $!";}
open (FILE,$inputfile) or die "Could not open file '$inputfile' $!"; # open inputfile
print "Your inputfile is:\n$inputfile\n";
my $gi=<FILE>;
chomp $gi;
my @info=split(/\s+/,$gi);
if(!(($#info == 3) && ($info[0] =~ /\Acluster_/)))
{
die "Your input file $inputfile is wrong!!! please check!!!\n $!";
}
if ($info[3] eq "No")
{
print "This is a single end data!!!please use another code!!!\n";
die;
}
close FILE;
print "Inputfile is OK!\nStart to calculating:\n";
##check the inputfile##
##sorting the inputfile by cluster ID##
print "Sorting by cluster ID...\n";
my $inputfile_sort="$inputfile"."_sort"; ## a file for sorted inputfile by cluster ID
unlink $inputfile_sort;
my (@out,$out,$string);
open(IN, $inputfile) || die "canot open input file '$inputfile' $!";
@out = sort {$a->[0] cmp $b->[0]}
map [(split)], <IN>;
open(SORT, '>>', $inputfile_sort) or die "Could not open file '$inputfile_sort' $!";
for $out(@out)
{
$string=join("\t",@$out);
print SORT ("$string\n");
}
close SORT;
close IN;
print "File sorting finished!!!\n";
##sorting the inputfile by cluster ID##
##Get one cluster's data and find the possible shifts##
open (FILE,$inputfile_sort) or die "Could not open file '$inputfile_sort' $!";
chomp($gi=<FILE>); @info=split(/\s+/,$gi);
my ($cluster_name, $cluster_name_next);
if($info[0] =~ m{\Acluster_([0-9]*)}){$cluster_name = "cluster_"."$1";}
my @sequence;
push @sequence, [@info];
my (%shift, %shift_pair, %shift_I1, %shift_R2, %shift_I1_count, %shift_R2_count, %correct);
while($gi=<FILE>)
{
chomp $gi;@info=split(/\s+/,$gi);
if($info[0] =~ m{\Acluster_([0-9]*)}){$cluster_name_next = "cluster_"."$1";}
if ($cluster_name_next eq $cluster_name) {push @sequence, [@info];}
else {
&Find_shift($cluster_name, \@sequence);
undef @sequence;
$cluster_name = $cluster_name_next;
push @sequence, [@info];
}
}
&Find_shift($cluster_name, \@sequence);
undef @sequence;
close FILE;
##Get one cluster's data and find the possible shifts##
##To review all the sequences and statistic all cases##
my (%pair_A_B_I1, %pair_B_A_I1, %pair_A_B_R2, %pair_B_A_R2);
open (FILE,$inputfile_sort) or die "Could not open file '$inputfile_sort' $!";
chomp($gi=<FILE>); @info=split(/\s+/,$gi);
if($info[0] =~ m{\Acluster_([0-9]*)}){$cluster_name = "cluster_"."$1";}
push @sequence, [@info];
while($gi=<FILE>)
{
chomp $gi;
@info=split(/\s+/,$gi);
if($info[0] =~ m{\Acluster_([0-9]*)}){$cluster_name_next = "cluster_"."$1";}
if($cluster_name_next eq $cluster_name) {push @sequence, [@info];}
else{
&Review_shift($cluster_name, \@sequence);
undef @sequence;
$cluster_name = $cluster_name_next;
push @sequence, [@info];
}
}
&Review_shift($cluster_name, \@sequence);
undef @sequence;
close FILE;
## save the statistic shifts informations into files ##
my (%possible_pair_A_B_I1, %possible_pair_A_B_R2, %possible_pair_B_A_I1, %possible_pair_B_A_R2);
open (OUTFI1,'>>', $outputfile_I1) or die "Could not open file '$outputfile_I1' $!";
foreach my $key (keys %pair_A_B_I1)
{
my @keys = split(/\s+/,$key);
print OUTFI1 ("$pair_A_B_I1{$key}\t$pair_B_A_I1{$key}\t$shift_I1_count{$keys[0]}\t$shift_I1_count{$keys[1]}\t$shift_I1{$key}\t$keys[0]\t$keys[1]\n");
# if ($keys[0] eq "GTTTGCTCCCCACGCTTTCGAGCCTCAGCGTCAGTTATCGTCCAGTAAGCCGCCTTCGCCACTGGTGTTCCTCCTAATATCTACGCATTTCACCGCTACACTAGGAATTCCGCTTACCCCTCCGACACTCTAGTACGACAGTTTCCAATGCAGTGCCGGGGTTGAGCCCCGGGCTTTCACATCAGACTTGCCGCACCGCCTGCGCTCCCT") {print "yes2\n$pair_A_B_I1{$key}\t$pair_B_A_I1{$key}\t$shift_I1_count{$keys[0]}\t$shift_I1_count{$keys[1]}\t$shift_I1{$key}\n";}
# if(($shift_I1_count{$keys[0]} < $shift_I1_count{$keys[1]})) ## this step include M>=S
# {
# print OUTFI1 ("$pair_A_B_I1{$key}\t$pair_B_A_I1{$key}\t$shift_I1_count{$keys[0]}\t$shift_I1_count{$keys[1]}\t$shift_I1{$key}\t$keys[0]\t$keys[1]\n");
# $possible_pair_A_B_I1{$key}=$pair_A_B_I1{$key}; $possible_pair_B_A_I1{$key}=$pair_B_A_I1{$key};
# }
}
close OUTFI1;
open (OUTFR2,'>>', $outputfile_R2) or die "Could not open file '$outputfile_R2' $!";
foreach my $key (keys %pair_A_B_R2)
{
my @keys = split(/\s+/,$key);
print OUTFR2 ("$pair_A_B_R2{$key}\t$pair_B_A_R2{$key}\t$shift_R2_count{$keys[0]}\t$shift_R2_count{$keys[1]}\t$shift_R2{$key}\t$keys[0]\t$keys[1]\n");
# print "$pair_A_B{$key}\t$pair_B_A{$key}\t$pair_seq{$keys[0]}\t$pair_seq{$keys[1]}\n";
#if(($shift_R2_count{$keys[0]} < $shift_R2_count{$keys[1]})) ## this step include the threhold M>S
# {
# print OUTFR2 ("$pair_A_B_R2{$key}\t$pair_B_A_R2{$key}\t$shift_R2_count{$keys[0]}\t$shift_R2_count{$keys[1]}\t$shift_R2{$key}\t$keys[0]\t$keys[1]\n");
# $possible_pair_A_B_R2{$key}=$pair_A_B_R2{$key}; $possible_pair_B_A_R2{$key}=$pair_B_A_R2{$key};
# }
}
close OUTFR2;
##To review all the sequences and statistic all cases##
## Use threshold to delete all the real shifts###
my %delete_I1;
my %delete_R2;
my %delete_I1_ratio;
my %delete_R2_ratio;
# my $threshold_1=0.9; # to delete the high populational shifts
open (FILEI1, $outputfile_I1) or die "Could not open file '$outputfile_I1' $!";
while($gi=<FILEI1>)
{
chomp $gi;
@info=split(/\s+/,$gi);
# my $ratio = ($info[0]+$info[1])/$info[2];
# my $threshold_2 = ($info[2]-2)/$info[2]; # to delete the low populational shifts
if($info[2]<$info[3] && ($info[0]>=$info[1]))
{
if ($info[0]<$info[1]) {print "$info[5]\t$info[6]\n";}
if(exists $delete_I1{$info[5]})
{
if ($delete_I1_ratio{$info[5]} > ($info[2]/$info[3])) ## if one shift has more than one possible mothers, using S/M (lowest) to choose one mother
{
$delete_I1{$info[5]} = $info[6]; $delete_I1_ratio{$info[5]} = $info[2]/$info[3];
}
}
else{ $delete_I1{$info[5]} = $info[6]; $delete_I1_ratio{$info[5]} = $info[2]/$info[3];}
}
}
close FILEI1;
open (FILER2, $outputfile_R2) or die "Could not open file '$outputfile_R2' $!";
while($gi=<FILER2>)
{
chomp $gi;
@info=split(/\s+/,$gi);
# my $ratio = ($info[0]+$info[1])/$info[2];
# my $threshold_2 = ($info[2]-2)/$info[2]; # to delete the low populational shifts
if($info[2]<$info[3] && ($info[0]>=$info[1]))
{
if ($info[0]<$info[1]) {print "$info[5]\t$info[6]\n";}
if(exists $delete_R2{$info[5]} )
{
if ($delete_R2_ratio{$info[5]} > ($info[2]/$info[3]))
{
$delete_R2{$info[5]} = $info[6]; $delete_R2_ratio{$info[5]} = $info[2]/$info[3];
}
}
else{ $delete_R2{$info[5]} = $info[6]; $delete_R2_ratio{$info[5]} = $info[2]/$info[3];}
}
}
close FILER2;
my $delete_no=0;
foreach my $key (keys %delete_I1)
{ $delete_no++}
print "Totally found $delete_no shifts of I1, and start to delete them.....\n";
$delete_no=0;
foreach my $key (keys %delete_R2)
{ $delete_no++}
print "Totally found $delete_no shifts of R2, and start to delete them.....\n";
open (FILE,$inputfile_sort) or die "Could not open file '$inputfile_sort' $!";
chomp($gi=<FILE>);@info=split(/\s+/,$gi);if($info[0] =~ m{\Acluster_([0-9]*)}){$cluster_name = "cluster_"."$1";}
push @sequence, [@info];
while($gi=<FILE>)
{
chomp $gi;
@info=split(/\s+/,$gi);
if($info[0] =~ m{\Acluster_([0-9]*)}){$cluster_name_next = "cluster_"."$1";}
if ($cluster_name_next eq $cluster_name){push @sequence, [@info];}
else {
&Delete_shift($cluster_name, \@sequence);
undef @sequence;$cluster_name = $cluster_name_next;
push @sequence, [@info];
}
}
&Delete_shift($cluster_name, \@sequence);
undef @sequence;
close FILE;
## Use threshold to delete all the real shifts###
#Find the shift sequence#
sub Find_shift
{
my ($k, $j, $m, $seqseq, $cluster_name, $I1_del, $R2_del);
($cluster_name, $seqseq)=@_;
if($#$seqseq>0)
{
for ($k=0; $k<$#$seqseq; $k++)
{
for ($j=($k+1); $j<=$#$seqseq; $j++)
{
$I1_del=10000; $R2_del=10000; ## they are not shifted sequences
my $lI1=length($$seqseq[$k][2]); # print "$lI1\n";
my $lR2=length($$seqseq[$k][3]); # print "$lR2\n"; die;
for ($m=0; $m<=$shiftcon; $m++)
{
if(substr($$seqseq[$k][2], $m) eq substr($$seqseq[$j][2], 0, ($lI1-$m)))
{
$I1_del=$m; last;
}
elsif(substr($$seqseq[$k][2], 0, ($lI1-$m)) eq substr($$seqseq[$j][2], $m))
{
$I1_del=$m; last;
}
}
for ($m=0; $m<=$shiftcon; $m++)
{
if(substr($$seqseq[$k][3], $m) eq substr($$seqseq[$j][3], 0, ($lR2-$m)))
{
$R2_del=$m; last;
}
elsif(substr($$seqseq[$k][3], 0, ($lR2-$m)) eq substr($$seqseq[$j][3], $m))
{
$R2_del=$m;last;
}
}
# print "$I1_del\t$R2_del\n";
if ($I1_del<=$shiftcon && $R2_del<=$shiftcon)
{
my $seqs_s="$$seqseq[$k][2]"."$$seqseq[$k][3]";
# print "$seqs_s\n";
my $seqs_m="$$seqseq[$j][2]"."$$seqseq[$j][3]";
my $seqs_pair="$seqs_s\t$seqs_m";
my $seqs_pair_r="$seqs_m\t$seqs_s";
$shift{$seqs_s} = $seqs_m;
$shift{$seqs_m} = $seqs_s;
$shift_pair{$seqs_pair} = $seqs_pair_r;
$shift_pair{$seqs_pair_r} = $seqs_pair;
if($$seqseq[$k][2] ne $$seqseq[$j][2])
{
my $pairs_I1="$$seqseq[$k][2]\t$$seqseq[$j][2]";
if(!(exists $shift_I1{$pairs_I1}))
{
$shift_I1{$pairs_I1}="$I1_del";
my $pairs_I1_r="$$seqseq[$j][2]\t$$seqseq[$k][2]";
$shift_I1{$pairs_I1_r}="$I1_del";
$shift_I1_count{$$seqseq[$k][2]}=0; #if ($$seqseq[$k][2] eq "GTTTGCTCCCCACGCTTTCGAGCCTCAGCGTCAGTTATCGTCCAGTAAGCCGCCTTCGCCACTGGTGTTCCTCCTAATATCTACGCATTTCACCGCTACACTAGGAATTCCGCTTACCCCTCCGACACTCTAGTACGACAGTTTCCAATGCAGTGCCGGGGTTGAGCCCCGGGCTTTCACATCAGACTTGCCGCACCGCCTGCGCTCCCT") {print "yes\n";}
$shift_I1_count{$$seqseq[$j][2]}=0;
}
}
if($$seqseq[$k][3] ne $$seqseq[$j][3])
{
my $pairs_R2="$$seqseq[$k][3]\t$$seqseq[$j][3]";
if(!(exists $shift_R2{$pairs_R2}))
{
$shift_R2{$pairs_R2}="$R2_del";
my $pairs_R2_r="$$seqseq[$j][3]\t$$seqseq[$k][3]";
$shift_R2{$pairs_R2_r}="$R2_del";
$shift_R2_count{$$seqseq[$k][3]}=0;
$shift_R2_count{$$seqseq[$j][3]}=0;
}
}
}
}
}
}
}
## review shifts
sub Review_shift
{
my ($cluster, $seq)=@_;
my ($i, $j, %possible, %group, %group_I1, %group_R2);
undef %possible;
# print "$#$seq\n";
for($i=0; $i<=$#$seq; $i++)
{
my $repseq="$$seq[$i][2]"."$$seq[$i][3]";
# print "$repseq\n";
if(exists $shift{$repseq})
{
$possible{$repseq}=\@{$$seq[$i]}; # print "$$seq[$i][0]\n";
}
}
while(%possible)
{
undef %group;
undef %group_I1;
undef %group_R2;
my @keykey=(keys %possible); # print "$#keykey\n";
my $seed = $keykey[0];
$group{$seed} = $possible{$seed};
delete $possible{$seed};
if(%possible)
{
foreach my $key (keys %possible)
{
my $pairs_seqs="$seed\t$key"; if(exists $shift_pair{$pairs_seqs}) {$group{$key} = $possible{$key}; delete $possible{$key};}
}
}
foreach my $key (keys %group)
{
if(exists $group_I1{${$group{$key}}[2]})
{
$group_I1{${$group{$key}}[2]}=$group_I1{${$group{$key}}[2]}+${$group{$key}}[1]; # print "${$group{$key}}[0]\t${$group{$key}}[1]\t${$group{$key}}[2]\n"; die;
}
else{
$group_I1{${$group{$key}}[2]}=${$group{$key}}[1];
}
if(exists $group_R2{${$group{$key}}[3]})
{
$group_R2{${$group{$key}}[3]}=$group_R2{${$group{$key}}[3]}+${$group{$key}}[1];
}
else{
$group_R2{${$group{$key}}[3]}=${$group{$key}}[1];
}
}
my @keys=(keys %group_I1); # print "$#keys\n";
if ($#keys>0)
{
for($i=0; $i<=($#keys-1); $i++)
{
for($j=$i+1; $j<=$#keys; $j++)
{
my $pairpair="$keys[$i]\t$keys[$j]";
my $pairpair_r="$keys[$j]\t$keys[$i]";
if (exists $shift_I1{$pairpair})
{
if($group_I1{$keys[$i]} >= $group_I1{$keys[$j]})
{
if (exists $pair_A_B_I1{$pairpair})
{
$pair_B_A_I1{$pairpair}++; $pair_A_B_I1{$pairpair_r}++;
}
else{
$pair_A_B_I1{$pairpair}=0; $pair_B_A_I1{$pairpair}=1;
$pair_A_B_I1{$pairpair_r}=1; $pair_B_A_I1{$pairpair_r}=0;
}
}
else {
if (exists $pair_A_B_I1{$pairpair})
{
$pair_A_B_I1{$pairpair}++; $pair_B_A_I1{$pairpair_r}++;
}
else{
$pair_A_B_I1{$pairpair}=1; $pair_B_A_I1{$pairpair}=0;
$pair_A_B_I1{$pairpair_r}=0; $pair_B_A_I1{$pairpair_r}=1;
}
}
if(!(exists $shift_I1{$pairpair_r})) {print "Somthing is wrong!!\n";}
}
}
}
}
foreach my $key (keys %group_I1)
{
$shift_I1_count{$key}++;
}
@keys=(keys %group_R2);
if ($#keys>0)
{
for($i=0; $i<=($#keys-1); $i++)
{
for($j=$i+1; $j<=$#keys; $j++)
{
my $pairpair="$keys[$i]\t$keys[$j]";
my $pairpair_r="$keys[$j]\t$keys[$i]";
if (exists $shift_R2{$pairpair})
{
if($group_R2{$keys[$i]} >= $group_R2{$keys[$j]})
{
if (exists $pair_A_B_R2{$pairpair})
{
$pair_B_A_R2{$pairpair}++; $pair_A_B_R2{$pairpair_r}++;
}
else{
$pair_A_B_R2{$pairpair}=0; $pair_B_A_R2{$pairpair}=1;
$pair_A_B_R2{$pairpair_r}=1; $pair_B_A_R2{$pairpair_r}=0;
}
}
else {
if (exists $pair_A_B_R2{$pairpair})
{
$pair_A_B_R2{$pairpair}++; $pair_B_A_R2{$pairpair_r}++;
}
else{
$pair_A_B_R2{$pairpair}=1; $pair_B_A_R2{$pairpair}=0;
$pair_A_B_R2{$pairpair_r}=0; $pair_B_A_R2{$pairpair_r}=1;
}
}
if(!(exists $shift_R2{$pairpair_r})) {print "Somthing is wrong!!\n";}
}
}
}
}
foreach my $key (keys %group_R2)
{
$shift_R2_count{$key}++;
}
}
}
sub Delete_shift {
my ($cluster, $seq)=@_;
my %correct;
my %correct_reads;
my %correct_cluster;
for(my $i=0; $i<=$#$seq; $i++)
{
if(exists $delete_I1{$$seq[$i][2]})
{
$$seq[$i][2] = $delete_I1{$$seq[$i][2]};
}
if(exists $delete_R2{$$seq[$i][3]})
{
$$seq[$i][3] = $delete_R2{$$seq[$i][3]};
}
my $seqseq="$$seq[$i][2]"."$$seq[$i][3]";
if($correct{$seqseq})
{
$correct_reads{$seqseq}=$correct_reads{$seqseq}+$$seq[$i][1];
}
else{
$correct{$seqseq}="$$seq[$i][2]\t$$seq[$i][3]";
$correct_reads{$seqseq}=$$seq[$i][1];
$correct_cluster{$seqseq}=$$seq[$i][0];
}
}
open (OUTF,'>>', $outputfile) or die "Could not open file '$outputfile' $!";
foreach my $key (keys %correct)
{
print OUTF ("$correct_cluster{$key}\t$correct_reads{$key}\t$correct{$key}\n");
}
close OUTF;
}
# unlink $inputfile_sort;
print "Done!!!\n";
##Get one cluster's data and find the shift##
##end##
#####Author#####
#Jianshi Frank Jin
#####Version#####
#V1.001
#2018.10.03
| 43.046092 | 366 | 0.454004 |
ed50cc5e3c8eecef11900f6f83908976e9b49ce7 | 452 | al | Perl | sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al | Michal-Gagala/sympy | 3cc756c2af73b5506102abaeefd1b654e286e2c8 | [
"MIT"
]
| null | null | null | sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al | Michal-Gagala/sympy | 3cc756c2af73b5506102abaeefd1b654e286e2c8 | [
"MIT"
]
| null | null | null | sympy/parsing/autolev/test-examples/pydy-example-repo/double_pendulum.al | Michal-Gagala/sympy | 3cc756c2af73b5506102abaeefd1b654e286e2c8 | [
"MIT"
]
| null | null | null | MOTIONVARIABLES' Q{2}', U{2}'
CONSTANTS L,M,G
NEWTONIAN N
FRAMES A,B
SIMPROT(N, A, 3, Q1)
SIMPROT(N, B, 3, Q2)
W_A_N>=U1*N3>
W_B_N>=U2*N3>
POINT O
PARTICLES P,R
P_O_P> = L*A1>
P_P_R> = L*B1>
V_O_N> = 0>
V2PTS(N, A, O, P)
V2PTS(N, B, P, R)
MASS P=M, R=M
Q1' = U1
Q2' = U2
GRAVITY(G*N1>)
ZERO = FR() + FRSTAR()
KANE()
INPUT M=1,G=9.81,L=1
INPUT Q1=.1,Q2=.2,U1=0,U2=0
INPUT TFINAL=10, INTEGSTP=.01
CODE DYNAMICS() some_filename.c
| 17.384615 | 32 | 0.595133 |
ed79533b44b6f66dfb353537150551b2e8197796 | 30,663 | pm | Perl | lib/Blast/IPS/Data/S1x7.pm | shancock9/blast-ips | e96b2e950d70bf955fba6777e872c2d2f0ddd8d2 | [
"MIT"
]
| null | null | null | lib/Blast/IPS/Data/S1x7.pm | shancock9/blast-ips | e96b2e950d70bf955fba6777e872c2d2f0ddd8d2 | [
"MIT"
]
| null | null | null | lib/Blast/IPS/Data/S1x7.pm | shancock9/blast-ips | e96b2e950d70bf955fba6777e872c2d2f0ddd8d2 | [
"MIT"
]
| null | null | null | package Blast::IPS::Data;
use strict;
use warnings;
# Blast data for symmetry='S', gamma=1.7
# For data definitions see the README file in Blast::IPS::Data.
our $rBlastData;
$rBlastData->{'S1x7'} = {
table_name => 'S1x7',
symmetry => 2,
gamma => 1.7,
data_source => 'S8000_G1x7/moc2_from_moc_r100/',
shock_table_info => [ 2, 1.7, 7.95e-07, 8000, 2.15e-07, 10, 1.18e-07, 1.77e-07, 5e-07, 1660.1, -0.7098 ],
shock_table => [
[ -4.45766881, 12.00017658, -2.99997679, -4.45878196, 0.99832936 ],
[ -4.08624728, 10.88592596, -2.99992928, -4.08819126, 0.99708126 ],
[ -3.51606987, 9.17548694, -2.99965798, -3.52064792, 0.99311795 ],
[ -3.18339174, 8.17764784, -2.99907239, -3.19094274, 0.98863406 ],
[ -2.91521128, 7.37348831, -2.99792893, -2.92652075, 0.98295099 ],
[ -2.69350051, 6.70900764, -2.99597973, -2.70930241, 0.97614011 ],
[ -2.50224697, 6.13628379, -2.99288736, -2.52334425, 0.96809192 ],
[ -2.33215674, 5.62758753, -2.98821073, -2.35944879, 0.9586576 ],
[ -2.18008429, 5.17363397, -2.98152603, -2.21445195, 0.94786877 ],
[ -2.04123512, 4.76025276, -2.97225433, -2.08366454, 0.93557696 ],
[ -1.91257569, 4.3786019, -2.95972745, -1.96416138, 0.92164185 ],
[ -1.79141859, 4.02096189, -2.94310625, -1.85342638, 0.90584707 ],
[ -1.67530037, 3.68041627, -2.9213, -1.74925576, 0.8878741 ],
[ -1.56151255, 3.34955673, -2.89275413, -1.64937232, 0.86720086 ],
[ -1.44617816, 3.01801313, -2.85485859, -1.55072545, 0.84282526 ],
[ -1.32090088, 2.66355998, -2.80159876, -1.44701233, 0.81217274 ],
[ -1.19870997, 2.32508835, -2.73616443, -1.34981686, 0.77801334 ],
[ -1.08718274, 2.02382063, -2.66457519, -1.26495093, 0.74334897 ],
[ -0.98282191, 1.74965923, -2.58811777, -1.18918399, 0.70828952 ],
[ -0.88392992, 1.49759433, -2.50868235, -1.12086073, 0.6732375 ],
[ -0.78841512, 1.26183507, -2.42732521, -1.05822058, 0.63826155 ],
[ -0.69303521, 1.03430074, -2.3435353, -0.99903095, 0.60284127 ],
[ -0.59796831, 0.81550747, -2.2594614, -0.94339675, 0.56764752 ],
[ -0.50220354, 0.60314295, -2.17600844, -0.89070881, 0.5328701 ],
[ -0.40478517, 0.39518655, -2.09391675, -0.84047416, 0.49868438 ],
[ -0.30494243, 0.19015694, -2.01390858, -0.79236582, 0.46530561 ],
[ -0.2017563, -0.01360581, -1.93644618, -0.74604477, 0.43287942 ],
[ -0.09448412, -0.21728404, -1.86202035, -0.70130952, 0.40159274 ],
[ 0.01780405, -0.42230956, -1.79090445, -0.65792747, 0.37156156 ],
[ 0.13604979, -0.63000866, -1.72332084, -0.61571618, 0.34289238 ],
[ 0.261238, -0.84167033, -1.65943583, -0.57452626, 0.31567365 ],
[ 0.39437644, -1.05852168, -1.59937892, -0.53424379, 0.28997937 ],
[ 0.53667491, -1.28202043, -1.54317542, -0.49473608, 0.26583713 ],
[ 0.689409, -1.51362106, -1.49083066, -0.45589852, 0.2432623 ],
[ 0.84834472, -1.74674101, -1.44385198, -0.41889129, 0.22291824 ],
[ 1.01407915, -1.98245722, -1.40171982, -0.38350189, 0.2045934 ],
[ 1.18785647, -2.22266633, -1.36381705, -0.34942326, 0.188029 ],
[ 1.3708764, -2.46906361, -1.32964838, -0.31641863, 0.17301553 ],
[ 1.56444681, -2.72337824, -1.2987883, -0.28428202, 0.15937145 ],
[ 1.76978631, -2.98713036, -1.27089859, -0.25286452, 0.14695199 ],
[ 1.98823675, -3.26192896, -1.24567868, -0.22203155, 0.13562807 ],
[ 2.22109009, -3.54926156, -1.22287887, -0.1916846, 0.1252928 ],
[ 2.46993505, -3.85093135, -1.20225835, -0.16171251, 0.11584295 ],
[ 2.73625067, -4.16855953, -1.18362097, -0.13204329, 0.10719546 ],
[ 3.02194201, -4.50423369, -1.16676968, -0.10258071, 0.09926682 ],
[ 3.32888288, -4.85995795, -1.15153974, -0.07325797, 0.09198854 ],
[ 3.65913912, -5.23792247, -1.13777943, -0.0440119, 0.0852984 ],
[ 4.01516884, -5.64072662, -1.12534338, -0.01476869, 0.07913724 ],
[ 4.39962182, -6.07114314, -1.11410235, 0.01453466, 0.07345366 ],
[ 4.81534012, -6.53212042, -1.10394054, 0.04395066, 0.06820288 ],
[ 5.26555853, -7.02700359, -1.09474974, 0.07353438, 0.06334377 ],
[ 5.75410512, -7.55974553, -1.08642753, 0.10335123, 0.05883768 ],
[ 6.28500172, -8.13446357, -1.07888552, 0.13344801, 0.05465277 ],
[ 6.86286486, -8.75587441, -1.0720418, 0.16387559, 0.05075984 ],
[ 7.49270651, -9.42907351, -1.0658241, 0.19467448, 0.04713402 ],
[ 8.18053505, -10.16017218, -1.06016422, 0.22590071, 0.0437514 ],
[ 8.93215597, -10.95501743, -1.05500827, 0.25756771, 0.040595 ],
[ 9.75457275, -11.82068102, -1.05030411, 0.28970955, 0.03764734 ],
[ 10.65518744, -12.76460714, -1.04600766, 0.32234259, 0.03489419 ],
[ 11.64160115, -13.7944088, -1.0420819, 0.35546131, 0.03232416 ],
[ 12.72261446, -14.91891428, -1.03849187, 0.38907289, 0.02992552 ],
[ 13.90722762, -16.14712203, -1.03520836, 0.4231625, 0.02768879 ],
[ 15.20544075, -17.48903463, -1.03220446, 0.45771892, 0.02560459 ],
[ 16.62785388, -18.95524269, -1.02945645, 0.49272179, 0.02366445 ],
[ 18.18626704, -20.55754329, -1.02694228, 0.52815626, 0.02185986 ],
[ 19.81472585, -22.22803141, -1.02473939, 0.56241259, 0.02025428 ],
[ 21.66461938, -24.12169022, -1.0226397, 0.59840534, 0.01870158 ],
[ 23.63314764, -26.13288835, -1.02076665, 0.63380062, 0.01729717 ],
[ 25.71119677, -28.25231179, -1.01910046, 0.66839603, 0.01603179 ],
[ 28.06264378, -30.64675079, -1.01751218, 0.70461952, 0.01481082 ],
[ 30.53364963, -33.15924354, -1.01610617, 0.73983075, 0.01371733 ],
[ 33.33060459, -35.99931727, -1.01476549, 0.77668291, 0.01266306 ],
[ 36.25233049, -38.96241149, -1.01358514, 0.81227468, 0.01172506 ],
[ 39.55826742, -42.31134465, -1.01245899, 0.84950212, 0.01082118 ],
[ 42.98505303, -45.77908992, -1.01147373, 0.88518048, 0.01002285 ],
[ 46.85776445, -49.69436196, -1.01053293, 0.9224663, 0.00925367 ],
[ 51.2559696, -54.13686217, -1.00963608, 0.961493, 0.00851389 ],
[ 55.79240473, -58.71519736, -1.00885846, 0.99860923, 0.00786705 ],
[ 60.9343866, -63.90076562, -1.00811638, 1.03741708, 0.00724483 ],
[ 66.17130656, -69.17847463, -1.00747856, 1.07390994, 0.00670603 ],
[ 72.08769574, -75.13725526, -1.00686893, 1.11200944, 0.0061874 ],
[ 78.80484194, -81.89852972, -1.00628724, 1.15184995, 0.00568907 ],
[ 85.56794665, -88.70244015, -1.0057934, 1.18884785, 0.00526322 ],
[ 93.21009609, -96.38700827, -1.00532123, 1.22746197, 0.00485355 ],
[ 101.888755, -105.1098349, -1.00487054, 1.26782837, 0.00446012 ],
[ 110.48442432, -113.74570647, -1.00449366, 1.30470711, 0.00412925 ],
[ 120.18107659, -123.48413451, -1.00413295, 1.34316179, 0.0038109 ],
[ 131.17321504, -134.51975357, -1.00378828, 1.38332373, 0.00350511 ],
[ 141.80604941, -145.19132607, -1.00350554, 1.41921919, 0.00325304 ],
[ 153.74925444, -157.17473599, -1.00323442, 1.45658313, 0.00301024 ],
[ 167.22546426, -170.69273561, -1.00297484, 1.49553371, 0.00277674 ],
[ 182.50652193, -186.01730113, -1.00272672, 1.53620403, 0.00255257 ],
[ 196.85861308, -200.40706934, -1.00252865, 1.57151776, 0.00237289 ],
[ 212.93075014, -216.51827893, -1.00233845, 1.60822812, 0.00219971 ]
],
energy_table => [
[ -4.45766881, 0.0068126, 0.00839934, 0.0068126, 0.00839934, 5.5394336, -1.5990578 ],
[ -4.08624728, 0.01076544, 0.01324929, 0.01076544, 0.01324929, 4.9413565, -1.6253972 ],
[ -3.51606987, 0.02167618, 0.02650896, 0.02167618, 0.02650896, 4.0013232, -1.6802043 ],
[ -3.18339174, 0.03251236, 0.03944972, 0.03251236, 0.03944972, 3.4362346, -1.7260078 ],
[ -2.91521128, 0.04494502, 0.05396142, 0.04494502, 0.05396142, 2.9674287, -1.7739584 ],
[ -2.69350051, 0.05855584, 0.06937634, 0.05855584, 0.06937634, 2.5693831, -1.8240732 ],
[ -2.50224697, 0.0733208, 0.08546994, 0.0733208, 0.08546994, 2.2157818, -1.8776466 ],
[ -2.33215674, 0.08923549, 0.10200147, 0.08923549, 0.10200147, 1.8920582, -1.9342076 ],
[ -2.18008429, 0.10597544, 0.1183822, 0.10597544, 0.1183822, 1.5937089, -1.9898353 ],
[ -2.04123512, 0.12351124, 0.13432441, 0.12351124, 0.13432441, 1.313879, -2.0425396 ],
[ -1.91257569, 0.14176708, 0.14947423, 0.14176708, 0.14947423, 1.0478458, -2.1010411 ],
[ -1.79141859, 0.16073271, 0.16350941, 0.16073271, 0.16350941, 0.78948944, -2.1553008 ],
[ -1.67530037, 0.18046208, 0.17610766, 0.18046208, 0.17610766, 0.53667197, -2.1980097 ],
[ -1.56151255, 0.20113476, 0.18693418, 0.20113476, 0.18693418, 0.28424956, -2.231961 ],
[ -1.44617816, 0.22322045, 0.19559814, 0.22322045, 0.19559814, 0.02523777, -2.2429074 ],
[ -1.32090088, 0.24813603, 0.20148654, 0.24813603, 0.20148654, -0.25536124, -2.2172738 ],
[ -1.19870997, 0.27289156, 0.20295847, 0.27289156, 0.20295847, -0.52360445, -2.1496906 ],
[ -1.08718274, 0.29541366, 0.2002794, 0.29541366, 0.2002794, -0.7587128, -2.0561639 ],
[ -0.98282191, 0.31603264, 0.1943344, 0.31603264, 0.1943344, -0.96822588, -1.9595552 ],
[ -0.88392992, 0.33485582, 0.18593449, 0.33485582, 0.18593449, -1.1575095, -1.8773572 ],
[ -0.78841512, 0.35214189, 0.17572159, 0.35214189, 0.17572159, -1.3334404, -1.8197378 ],
[ -0.69303521, 0.36835354, 0.16401411, 0.36835354, 0.16401411, -1.5048938, -1.7883734 ],
[ -0.59796831, 0.38335247, 0.15142545, 0.38335247, 0.15142545, -1.6740362, -1.7800543 ],
[ -0.50220354, 0.39722977, 0.13837712, 0.39722977, 0.13837712, -1.8445857, -1.7883982 ],
[ -0.40478517, 0.41006691, 0.12522685, 0.41006691, 0.12522685, -2.0195495, -1.8071994 ],
[ -0.30494243, 0.42191824, 0.11229311, 0.42191824, 0.11229311, -2.2011308, -1.8314499 ],
[ -0.2017563, 0.43285282, 0.09981582, 0.43285282, 0.09981582, -2.3914736, -1.8575575 ],
[ -0.09448412, 0.44291555, 0.08800206, 0.44291555, 0.08800206, -2.5921768, -1.883096 ],
[ 0.01780405, 0.4521657, 0.07698695, 0.4521657, 0.07698695, -2.8050513, -1.9066444 ],
[ 0.13604979, 0.46065596, 0.06686255, 0.46065596, 0.06686255, -3.0318557, -1.9274435 ],
[ 0.261238, 0.46843592, 0.05767999, 0.46843592, 0.05767999, -3.2743903, -1.9451761 ],
[ 0.39437644, 0.47555149, 0.04945639, 0.47555149, 0.04945639, -3.5344748, -1.9598253 ],
[ 0.53667491, 0.48205384, 0.04217093, 0.48205384, 0.04217093, -3.8143187, -1.9715811 ],
[ 0.689409, 0.48798994, 0.03578278, 0.48798994, 0.03578278, -4.1162632, -1.9807013 ],
[ 0.84834472, 0.49323443, 0.03040438, 0.49323443, 0.03040438, -4.4316912, -1.9874432 ],
[ 1.01407915, 0.49788548, 0.02588607, 0.49788548, 0.02588607, -4.7615659, -1.9922671 ],
[ 1.18785647, 0.50204115, 0.02208126, 0.50204115, 0.02208126, -5.1081204, -1.9955527 ],
[ 1.3708764, 0.5057778, 0.01887122, 0.5057778, 0.01887122, -5.4735984, -1.9977868 ],
[ 1.56444681, 0.5091582, 0.01615725, 0.5091582, 0.01615725, -5.8604862, -1.9992311 ],
[ 1.76978631, 0.51223115, 0.01385974, 0.51223115, 0.01385974, -6.2711246, -2.0000986 ],
[ 1.98823675, 0.51503798, 0.0119117, 0.51503798, 0.0119117, -6.7081158, -2.0005623 ],
[ 2.22109009, 0.51761183, 0.01025819, 0.51761183, 0.01025819, -7.1739903, -2.0007577 ],
[ 2.46993505, 0.51998288, 0.00885178, 0.51998288, 0.00885178, -7.6718786, -2.0007869 ],
[ 2.73625067, 0.5221747, 0.00765408, 0.5221747, 0.00765408, -8.2047165, -2.0007475 ],
[ 3.02194201, 0.52420979, 0.00663157, 0.52420979, 0.00663157, -8.776304, -2.0006395 ],
[ 3.32888288, 0.52610598, 0.00575704, 0.52610598, 0.00575704, -9.3903564, -2.0005033 ],
[ 3.65913912, 0.52787883, 0.00500751, 0.52787883, 0.00500751, -10.051016, -2.000394 ],
[ 4.01516884, 0.52954267, 0.00436339, 0.52954267, 0.00436339, -10.763196, -2.0002879 ],
[ 4.39962182, 0.5311095, 0.00380843, 0.5311095, 0.00380843, -11.532192, -2.0001986 ],
[ 4.81534012, 0.53258939, 0.00332914, 0.53258939, 0.00332914, -12.363695, -2.0001328 ],
[ 5.26555853, 0.53399134, 0.00291414, 0.53399134, 0.00291414, -13.264179, -2.0000857 ],
[ 5.75410512, 0.53532373, 0.00255369, 0.53532373, 0.00255369, -14.241304, -2.0000527 ],
[ 6.28500172, 0.5365931, 0.00224, 0.5365931, 0.00224, -15.303117, -2.0000304 ],
[ 6.86286486, 0.53780541, 0.00196492, 0.53780541, 0.00196492, -16.458857, -2.0000173 ],
[ 7.49270651, 0.53896545, 0.00172657, 0.53896545, 0.00172657, -17.718547, -2.0000092 ],
[ 8.18053505, 0.5400781, 0.00151638, 0.54010808, 0.0016146501, -19.094209, -2.0000046 ],
[ 8.93215597, 0.54114601, 0.00133197, 0.54131148, 0.0015873817, -20.597453, -2.0000022 ],
[ 9.75457275, 0.54217236, 0.0011699, 0.54258316, 0.001517015, -22.242287, -2.000001 ],
[ 10.65518744, 0.54315945, 0.00102735, 0.54391727, 0.0014401765, -24.043517, -2.0000004 ],
[ 11.64160115, 0.54410874, 0.00090196, 0.545299, 0.0013580303, -26.016345, -2.0000002 ],
[ 12.72261446, 0.54502196, 0.00079163, 0.54672205, 0.0012719434, -28.178372, -2.0000001 ],
[ 13.90722762, 0.54590015, 0.00069458, 0.54816991, 0.0011733973, -30.547598, -2 ],
[ 15.20544075, 0.54674443, 0.00060924, 0.54963144, 0.0010773463, -33.144024, -2 ],
[ 16.62785388, 0.54755572, 0.00053423, 0.55115207, 0.0010923403, -35.988851, -2 ],
[ 18.18626704, 0.54833503, 0.00046833, 0.55274436, 0.00095620677, -39.105677, -2 ],
[ 19.81472585, 0.54905092, 0.00041286, 0.5542051, 0.00084188614, -42.362595, -2 ],
[ 21.66461938, 0.54976594, 0.00036206, 0.55566232, 0.00073744226, -46.062382, -2 ],
[ 23.63314764, 0.5504343, 0.00031856, 0.55702297, 0.00064817534, -49.999438, -2 ],
[ 25.71119677, 0.55105629, 0.00028137, 0.55828801, 0.00057200688, -54.155536, -2 ],
[ 28.06264378, 0.55167644, 0.00024733, 0.55954822, 0.00050237319, -58.85843, -2 ],
[ 30.53364963, 0.55225056, 0.00021838, 0.56071401, 0.0004432625, -63.800442, -2 ],
[ 33.33060459, 0.55282296, 0.00019188, 0.56187547, 0.00038921568, -69.394352, -2 ],
[ 36.25233049, 0.55334973, 0.00016949, 0.56294369, 0.00034359003, -75.237804, -2 ],
[ 39.55826742, 0.55387491, 0.00014898, 0.56400808, 0.00030184657, -81.849678, -2 ],
[ 42.98505303, 0.55435489, 0.00013175, 0.56498037, 0.00026682068, -88.703249, -2 ],
[ 46.85776445, 0.55483345, 0.00011596, 0.56594935, 0.00023473628, -96.448672, -2 ],
[ 51.2559696, 0.55531054, 0.00010153, 0.56691496, 0.0002054444, -105.24508, -2 ],
[ 55.79240473, 0.55574296, 8.954e-05, 0.56778983, 0.00018111532, -114.31795, -2 ],
[ 60.9343866, 0.55617411, 7.856e-05, 0.56866183, 0.00015886565, -124.60192, -2 ],
[ 66.17130656, 0.55656102, 6.952e-05, 0.56944415, 0.00014053068, -135.07576, -2 ],
[ 72.08769574, 0.55694686, 6.121e-05, 0.57022409, 0.00012371771, -146.90853, -2 ],
[ 78.80484194, 0.55733159, 5.362e-05, 0.57100161, 0.00010835231, -160.34283, -2 ],
[ 85.56794665, 0.55767264, 4.745e-05, 0.57169069, 9.584952e-05, -173.86904, -2 ],
[ 93.21009609, 0.55801278, 4.178e-05, 0.57237781, 8.438131e-05, -189.15334, -2 ],
[ 101.888755, 0.55835199, 3.659e-05, 0.57306296, 7.3897466e-05, -206.51065, -2 ],
[ 110.48442432, 0.55864804, 3.244e-05, 0.57366082, 6.549272e-05, -223.70199, -2 ],
[ 120.18107659, 0.55894336, 2.862e-05, 0.57425714, 5.7771013e-05, -243.0953, -2 ],
[ 131.17321504, 0.55923795, 2.512e-05, 0.57485189, 5.0700065e-05, -265.07957, -2 ],
[ 141.80604941, 0.55948985, 2.236e-05, 0.57536043, 4.5133354e-05, -286.34524, -2 ],
[ 153.74925444, 0.5597412, 1.982e-05, 0.57586779, 4.000169e-05, -310.23165, -2 ],
[ 167.22546426, 0.55999199, 1.748e-05, 0.57637398, 3.5285515e-05, -337.18407, -2 ],
[ 182.50652193, 0.5602422, 1.535e-05, 0.57687897, 3.0965505e-05, -367.74619, -2 ],
[ 196.85861308, 0.56045027, 1.371e-05, 0.57729889, 2.7654347e-05, -396.45037, -2 ],
[ 212.93075014, 0.56065794, 1.219e-05, 0.57771796, 2.4594262e-05, -428.59464, -2 ]
],
impulse_table => [
[
-5.0625585, 13.814839, -5.0630076, 0.026559356, -0.0010125631, -0.15249032,
-1.733542, -0.22812839, -0.0016236587, -0.37523928, 0.28889653, 0.99450877,
-2.5260158
],
[
-4.9618449, 13.512699, -4.9623672, 0.027731709, -0.0011198542, -0.15181966,
-1.7328713, -0.2784863, -0.0017957015, -0.37456862, 0.28889646, 0.99378194,
-2.4893872
],
[
-4.6051699, 12.442677, -4.606062, 0.03219861, -0.0015997917, -0.14881966,
-1.7298713, -0.45682851, -0.0025652878, -0.37156862, 0.28889588, 0.99034439,
-2.3624137
],
[
-4.1997048, 11.226292, -4.201344, 0.037839289, -0.0023996876, -0.14381966,
-1.7248713, -0.65957684, -0.0038479317, -0.36656862, 0.28889375, 0.98408426,
-2.2244666
],
[
-3.9120227, 10.363266, -3.914545, 0.042140161, -0.0031995834, -0.13881966,
-1.7198713, -0.80344819, -0.0051305756, -0.36156862, 0.28888973, 0.97732464,
-2.1319138
],
[
-3.5065576, 9.1469535, -3.5112016, 0.04842339, -0.0047993751, -0.12881966,
-1.7098713, -1.006305, -0.0076958633, -0.35156861, 0.28887341, 0.962718,
-2.0114045
],
[
-2.995732, 7.6149019, -3.0057486, 0.056011323, -0.0079989558, -0.10881986,
-1.6898714, -1.2623591, -0.012826436, -0.33156861, 0.28878923, 0.93063884,
-1.8827097
],
[
-2.3025848, 5.5392359, -2.3311273, 0.062638717, -0.015997483, -0.058835811,
-1.6398796, -1.6146719, -0.025652359, -0.2815686, 0.28804182, 0.84298835,
-1.7758277
],
[
-1.8971197, 4.3328704, -1.9499308, 0.062111892, -0.023988558, -0.0090261587,
-1.5899773, -1.8330714, -0.038469367, -0.23171778, 0.28605098, 0.75458717,
-1.7747534
],
[
-1.6094376, 3.4885091, -1.6911533, 0.059160449, -0.031928653, 0.039932159,
-1.540516, -2.0076764, -0.051225107, -0.18246448, 0.28232357, 0.67192953,
-1.8178386
],
[
-1.3862941, 2.8477493, -1.5006707, 0.056036905, -0.039662212, 0.086274889,
-1.4924645, -2.17035, -0.063727916, -0.13501198, 0.27656573, 0.59807916,
-1.8848072
],
[
-1.2039725, 2.3394958, -1.3539153, 0.05392205, -0.046824328, 0.12704319,
-1.4477556, -2.3376817, -0.075493555, -0.092277863, 0.26874058, 0.53403981,
-1.9653908
],
[
-1.0498219, 1.9247595, -1.2374074, 0.05314594, -0.052880838, 0.15958018,
-1.4090228, -2.5186354, -0.085687235, -0.057490186, 0.25906033, 0.47954713,
-2.0531944
],
[
-0.91629046, 1.5792094, -1.1428357, 0.053444345, -0.057447521, 0.1835355,
-1.3780899, -2.7151311, -0.093491271, -0.033097547, 0.24791844, 0.43365828,
-2.1439388
],
[
-0.79850743, 1.2863766, -1.064681, 0.054360807, -0.060572513, 0.20058985,
-1.3546355, -2.9225455, -0.098745427, -0.018583643, 0.2357966, 0.39516877,
-2.2347746
],
[
-0.69314691, 1.0345625, -0.99909829, 0.055521319, -0.062611351, 0.21284183,
-1.3369359, -3.1332947, -0.10198732, -0.011133899, 0.22318195, 0.36286592,
-2.3238835
],
[
-0.59783673, 0.81521018, -0.94332206, 0.056702133, -0.063941718, 0.22192617,
-1.3232478, -3.3408522, -0.10391905, -0.0080837579, 0.21051127, 0.33565538,
-2.4101799
],
[
-0.51082535, 0.62193611, -0.89531644, 0.057796021, -0.064833979, 0.22891775,
-1.3123176, -3.5411862, -0.10506741, -0.0077353711, 0.19814257, 0.31260603,
-2.4930795
],
[
-0.43078265, 0.44990292, -0.85355526, 0.058763966, -0.065454888, 0.23448675,
-1.3033357, -3.7323475, -0.10575528, -0.0087932755, 0.18634683, 0.29295133,
-2.5723267
],
[
-0.35667467, 0.29539286, -0.81687637, 0.059601014, -0.065903203, 0.23905176,
-1.2957816, -3.9136875, -0.10616852, -0.01070341, 0.175312, 0.27607144,
-2.647873
],
[
-0.2876818, 0.15551103, -0.78438259, 0.06031697, -0.066237837, 0.24288111,
-1.2893121, -4.0852705, -0.10641372, -0.013079551, 0.16515322, 0.26146931,
-2.7197954
],
[
-0.22314328, 0.027975267, -0.75537251, 0.060926724, -0.066494917, 0.24615305,
-1.2836941, -4.2475172, -0.10655345, -0.015633089, 0.15592537, 0.24874748,
-2.7882416
],
[
-0.16251866, -0.089036104, -0.72929097, 0.061445756, -0.066697324, 0.24899026,
-1.27876, -4.4010063, -0.10662536, -0.018453607, 0.14763594, 0.23758775,
-2.8533965
],
[
-0.10536025, -0.19699307, -0.70569389, 0.061888314, -0.066860076, 0.2514803,
-1.2743882, -4.5463682, -0.10665297, -0.021281486, 0.14025559, 0.22773451,
-2.9154603
],
[
-0.051293024, -0.29709469, -0.68422233, 0.062266768, -0.066993312, 0.2536874,
-1.2704854, -4.6842295, -0.10665121, -0.024442072, 0.13370812, 0.21898142,
-2.9746354
],
[
2.6993029e-07, -0.39032867, -0.6645833, 0.062591582, -0.067104099, 0.25566013,
-1.266981, -4.8151861, -0.10662992, -0.027088747, 0.12788682, 0.21116098,
-3.0311186
],
[
0.013212177, -0.41407959, -0.65963633, 0.062670097, -0.067130469, 0.25615039,
-1.2661082, -4.8489284, -0.10662187, -0.027965416, 0.1264476, 0.20921983,
-3.0457136
],
[
0.18232183, -0.70917952, -0.60009263, 0.063507516, -0.067405447, 0.26184836,
-1.2559474, -5.280338, -0.10645291, -0.03812142, 0.11005042, 0.18680591,
-3.233701
],
[
0.26236453, -0.84353944, -0.57417077, 0.063809483, -0.067504127, 0.26421428,
-1.2517469, -5.4837249, -0.10634519, -0.043472618, 0.10347104, 0.17761849,
-3.3231343
],
[
0.40546538, -1.0762312, -0.53103932, 0.064229688, -0.067645562, 0.26799451,
-1.2451199, -5.8452177, -0.10613255, -0.053098964, 0.093294345, 0.16313073,
-3.4831782
],
[
0.53062852, -1.2726831, -0.49634633, 0.064496834, -0.067741979, 0.27088627,
-1.2401717, -6.1586992, -0.10593918, -0.062032949, 0.085803227, 0.15221665,
-3.6229428
],
[
0.69314745, -1.5191922, -0.45499005, 0.064740016, -0.06784045, 0.27414566,
-1.2347983, -6.5615398, -0.10569256, -0.073590433, 0.077662102, 0.14007639,
-3.8036667
],
[
0.99325204, -1.9532122, -0.38778534, 0.064986908, -0.067970648, 0.27895498,
-1.22749, -7.292447, -0.10527984, -0.096499682, 0.066168413, 0.12235366,
-4.1341635
],
[
1.0986126, -2.1001295, -0.36656466, 0.065033618, -0.068005622, 0.28033491,
-1.2255851, -7.5451359, -0.10515195, -0.10481337, 0.062958332, 0.117263,
-4.2490694
],
[
1.2089606, -2.2514039, -0.34547461, 0.065068069, -0.068037933, 0.28163524,
-1.2238914, -7.8077051, -0.10502789, -0.11332738, 0.059954944, 0.11243734,
-4.3687725
],
[
1.3862946, -2.4895441, -0.31376002, 0.065101004, -0.068082328, 0.28345101,
-1.2217164, -8.2254249, -0.10484923, -0.12710009, 0.0557727, 0.10560834,
-4.5597954
],
[
1.6094382, -2.7816656, -0.27717691, 0.06511704, -0.068127836, 0.28532867,
-1.2197425, -8.7441718, -0.10465858, -0.14473466, 0.051415694, 0.098345801,
-4.7979298
],
[
1.7917597, -3.0150264, -0.2496489, 0.065117848, -0.06815825, 0.28658378, -1.2186062, -9.1628559,
-0.10452835, -0.16007232, 0.048443014, 0.093295159, -4.9908084
],
[
1.9459104, -3.2091079, -0.22781549, 0.065113866, -0.068180275, 0.28748262,
-1.217896, -9.5135724, -0.10443361, -0.17286649, 0.046258745, 0.089530311,
-5.1528127
],
[
2.0794418, -3.375109, -0.2098568, 0.065108292, -0.068196857, 0.28815748,
-1.2174219, -9.8151551, -0.10436199, -0.18292569, 0.044570213, 0.086586714,
-5.2924258
],
[
2.3027872, -3.6488725, -0.18158301, 0.065097005, -0.068221579, 0.2891056,
-1.2169687, -10.315401, -0.10426087, -0.20158771, 0.042096888, 0.08130624,
-5.5341381
],
[
2.9958252, -4.4737429, -0.10518201, 0.065062699, -0.068269161, 0.291003,
-1.216133, -11.84035, -0.10405422, -0.25848398, 0.036409359, 0.071548916,
-6.2409696
],
[
3.9122115, -5.5246924, -0.023002342, 0.065035117, -0.068302509, 0.29214836,
-1.2161584, -13.811732, -0.10393104, -0.33396458, 0.031598017, 0.062740593,
-7.1674214
],
[
4.605397, -6.2998491, 0.0293681, 0.065024953, -0.068312238, 0.29253022,
-1.2161093, -15.280733, -0.10388881, -0.39111969, 0.029066323, 0.057917041,
-7.8645128
],
[
5.2983708, -7.0629149, 0.075607497, 0.065019762, -0.068317363, 0.29272117,
-1.2161145, -16.736415, -0.10386782, -0.44827195, 0.027097683, 0.054091782,
-8.5596411
],
[
6.2147916, -8.0586828, 0.12959279, 0.065016655, -0.068320431, 0.29283585,
-1.2161192, -18.647485, -0.10385522, -0.52385498, 0.025053238, 0.050066627,
-9.4774781
],
[
6.9078686, -8.8041094, 0.16615371, 0.065015636, -0.068321451, 0.29287407,
-1.2161209, -20.085013, -0.10385101, -0.58101575, 0.023797075, 0.047574666,
-10.171068
],
[
7.6009119, -9.5443493, 0.19974381, 0.065015135, -0.068321957, 0.29289319,
-1.2161219, -21.517352, -0.10384891, -0.63817209, 0.022720776, 0.045431985,
-10.864383
],
[
8.5173454, -10.516833, 0.24038523, 0.06501484, -0.068322273, 0.29290466,
-1.2161224, -23.405146, -0.10384765, -0.71374986, 0.021506072, 0.043008392,
-11.780989
],
[
9.2103622, -11.24829, 0.26871426, 0.065014744, -0.068322363, 0.29290848,
-1.2161226, -24.828882, -0.10384723, -0.77090168, 0.020710216, 0.041418581,
-12.474067
],
[
10.81979, -12.936724, 0.32804845, 0.065014667, -0.068322453, 0.29291154,
-1.2161228, -28.125361, -0.10362119, -0.88342141, 0.019163335, 0.038326307,
-14.083546
],
[
11.512999, -13.660365, 0.3512844, 0.065014656, -0.068322461, 0.29291193,
-1.2161228, -29.541735, -0.10289501, -0.91512123, 0.018597811, 0.037195442,
-14.776763
],
[
13.122419, -15.333871, 0.40087688, 0.065014646, -0.068322457, 0.29291223,
-1.2161228, -32.823758, -0.10022161, -0.98521344, 0.01745908, 0.034918124,
-16.386188
],
[
13.815627, -16.052285, 0.42061887, 0.065014644, -0.068322466, 0.29291227,
-1.2161228, -34.235061, -0.098870256, -1.0140794, 0.017029918, 0.034059818,
-17.079396
],
[
16.118249, -18.430393, 0.48049619, 0.065014638, -0.068322461, 0.29291238,
-1.2161227, -38.914947, -0.094199687, -1.1051797, 0.015805079, 0.031610157,
-19.38202
],
[
18.420869, -20.798426, 0.53325557, 0.065014633, -0.068322479, 0.29291318,
-1.2161219, -43.584985, -0.089707434, -1.1901382, 0.014813396, 0.029626792,
-21.684639
]
],
tail_shock_table => [
[ 7.4150606, -0.7098, -0.041725186, -0.041725186 ],
[ 7.6003012, -0.72021983, -0.050479603, -0.032258871 ],
[ 8.517091, -0.76987601, -0.058578616, -0.019289613 ],
[ 9.2102313, -0.80556634, -0.060393556, -0.01435554 ],
[ 10.819762, -0.88341927, -0.060953711, -0.0078729789 ],
[ 11.512985, -0.91512016, -0.060526519, -0.0061762592 ],
[ 13.122416, -0.98521322, -0.058953897, -0.003532175 ],
[ 13.815625, -1.0140793, -0.058158978, -0.0027573305 ],
[ 16.118249, -1.1052264, -0.055415415, -0.001076967 ]
],
blast_info => [
0.15881964, 1.7398709, 0.38153901, -0.25652876, 2.1021692, 0.0016689518, 3.6785756, -0.15997913,
0.49615741, 0.39113763, 0.65870966, -0.17834545, 0.2998678, 0.28889676, 0.038243904, -0.040189676,
1660.1, -0.7098, 26316.098, -0.85069485
],
};
1;
| 59.655642 | 112 | 0.558589 |
ed6fe1bc4eab5199b7dc94d789dcd44de29dccca | 1,918 | pm | Perl | modules/Bio/EnsEMBL/Compara/RunnableDB/DumpMultiAlign/MkDirConstrainedElements.pm | manuelcarbajo/ensembl-compara | 0ffe653215a20e6921c5f4983ea9e4755593a491 | [
"Apache-2.0"
]
| null | null | null | modules/Bio/EnsEMBL/Compara/RunnableDB/DumpMultiAlign/MkDirConstrainedElements.pm | manuelcarbajo/ensembl-compara | 0ffe653215a20e6921c5f4983ea9e4755593a491 | [
"Apache-2.0"
]
| null | null | null | modules/Bio/EnsEMBL/Compara/RunnableDB/DumpMultiAlign/MkDirConstrainedElements.pm | manuelcarbajo/ensembl-compara | 0ffe653215a20e6921c5f4983ea9e4755593a491 | [
"Apache-2.0"
]
| null | null | null | =head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2020] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 NAME
Bio::EnsEMBL::Compara::RunnableDB::DumpMultiAlign::MkDirConstrainedElements
=head1 SYNOPSIS
Find the best directory name to dump some constrained elements, and creates it
=cut
package Bio::EnsEMBL::Compara::RunnableDB::DumpMultiAlign::MkDirConstrainedElements;
use strict;
use warnings;
use File::Path qw(make_path remove_tree);
use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');
sub write_output {
my $self = shift;
my $mlss = $self->compara_dba->get_MethodLinkSpeciesSetAdaptor->fetch_by_dbID($self->param_required('mlss_id'));
my $dirname = $mlss->filename;
my $work_dir = $self->param_required('work_dir').'/'.$dirname;
make_path($work_dir) unless -d $work_dir;
my $output_dir = $self->param_required('export_dir').'/bed/ensembl-compara/'.$dirname;
# remove_tree($output_dir);
make_path($output_dir) unless -d $output_dir;
$self->dataflow_output_id( {'dirname' => $dirname} );
}
1;
| 28.626866 | 116 | 0.755996 |
ed67baa92a8fb775937561230dda0500af7964f8 | 634 | pl | Perl | src/process_fasta.pl | stajichlab/FGMP | 20e8dcbfcc0221e19f03fa8e8bff31b6cbbeb592 | [
"MIT"
]
| 17 | 2016-10-06T12:10:29.000Z | 2021-12-23T18:54:45.000Z | src/process_fasta.pl | stajichlab/FGMP | 20e8dcbfcc0221e19f03fa8e8bff31b6cbbeb592 | [
"MIT"
]
| 17 | 2017-02-28T21:53:19.000Z | 2021-08-30T09:55:21.000Z | src/process_fasta.pl | stajichlab/FGMP | 20e8dcbfcc0221e19f03fa8e8bff31b6cbbeb592 | [
"MIT"
]
| 5 | 2016-10-07T02:26:58.000Z | 2021-04-27T09:54:31.000Z | #!/usr/bin/env perl
use strict;
use warnings;
use Bio::SeqIO;
my $in_file = $ARGV[0];
my $start_pos = $ARGV[1];
my $end_pos = $ARGV[2];
my $in = Bio::SeqIO->new( -file => $in_file, -format => 'fasta' );
my $out = Bio::SeqIO->new( -file => ">$in_file.out", -format => 'fasta' );
while ( my $seq = $in->next_seq() ) {
$seq->display_id( $seq->display_id() . "_$start_pos-$end_pos" );
if ( ( $seq->length ) > $end_pos ) {
$out->write_seq( $seq->trunc( $start_pos, $end_pos ) );
}
else {
$out->write_seq( $seq->trunc( $start_pos, $seq->length ) );
}
}
| 28.818182 | 75 | 0.512618 |
ed5cd1c486bc246a4a138fd6d7ed70937cd651d5 | 5,611 | t | Perl | t/52_app_status.t | Ch4p34uN0iR/Seccubus | 94ed4b161565a119d5052cdcaf484d3dfefa7940 | [
"Apache-2.0"
]
| null | null | null | t/52_app_status.t | Ch4p34uN0iR/Seccubus | 94ed4b161565a119d5052cdcaf484d3dfefa7940 | [
"Apache-2.0"
]
| null | null | null | t/52_app_status.t | Ch4p34uN0iR/Seccubus | 94ed4b161565a119d5052cdcaf484d3dfefa7940 | [
"Apache-2.0"
]
| null | null | null | #!/usr/bin/env perl
# Copyright 2017 Frank Breedijk
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
use Mojo::Base -strict;
use strict;
use Test::More;
use Test::Mojo;
use lib "lib";
my $db_version = 0;
foreach my $data_file (glob "db/data_v*.mysql") {
$data_file =~ /^db\/data_v(\d+)\.mysql$/;
$db_version = $1 if $1 > $db_version;
}
ok($db_version > 0, "DB version = $db_version");
`mysql -h 127.0.0.1 -u root -e "drop database seccubus"`;
is($?,0,"Database dropped ok");
`mysql -h 127.0.0.1 -u root -e "create database seccubus"`;
is($?,0,"Database created ok");
`mysql -h 127.0.0.1 -u root -e "grant all privileges on seccubus.* to seccubus\@localhost identified by 'seccubus';"`;
is($?,0,"Privileges granted ok");
`mysql -h 127.0.0.1 -u root -e "flush privileges;"`;
is($?,0,"Privileges flushed ok");
`mysql -h 127.0.0.1 -u root seccubus < db/structure_v$db_version.mysql`;
is($?,0,"Database structure created ok");
`mysql -h 127.0.0.1 -u root seccubus < db/data_v$db_version.mysql`;
is($?,0,"Database data imported ok");
my $t = Test::Mojo->new('Seccubus');
$t->ua->inactivity_timeout(40);
$t->get_ok('/api/appstatus')
->status_is(200)
->json_is("/0/name","Configuration file")
->json_is("/0/result","OK")
->json_is("/1/name","Path modules")
->json_is("/1/result","OK")
->json_is("/2/name","Path scanners")
->json_is("/2/result","OK")
->json_is("/3/name","Path bindir")
->json_is("/3/result","OK")
->json_is("/4/name","Path configdir")
->json_is("/4/result","OK")
->json_is("/5/name","Path dbdir")
->json_is("/5/result","OK")
->json_is("/6/name","Database login")
->json_is("/6/result","OK")
->json_is("/7/name","Database structure")
->json_is("/7/result","OK")
->json_is("/8/name","Database version")
->json_is("/8/result","OK")
->json_is("/9/name","Authentication")
->json_is("/9/result","Warn")
->json_is("/10/name","SMTP configuration")
->json_is("/10/result","OK")
->json_hasnt("/11")
;
pass("Creating empty database");
`mysql -h 127.0.0.1 -u root -e "drop database seccubus"`;
`mysql -h 127.0.0.1 -u root -e "create database seccubus"`;
`mysql -h 127.0.0.1 -u root -e "grant all privileges on seccubus.* to seccubus\@localhost identified by 'seccubus';"`;
`mysql -h 127.0.0.1 -u root -e "flush privileges;"`;
# Error without code
$t->get_ok('/api/appstatus')
->status_is(200)
->json_is("/0/name","Configuration file")
->json_is("/0/result","OK")
->json_is("/1/name","Path modules")
->json_is("/1/result","OK")
->json_is("/2/name","Path scanners")
->json_is("/2/result","OK")
->json_is("/3/name","Path bindir")
->json_is("/3/result","OK")
->json_is("/4/name","Path configdir")
->json_is("/4/result","OK")
->json_is("/5/name","Path dbdir")
->json_is("/5/result","OK")
->json_is("/6/name","Database login")
->json_is("/6/result","OK")
->json_is("/7/name","Database structure")
->json_is("/7/result","Error")
->json_hasnt("/8")
;
# Error with code 500
$t->get_ok('/api/appstatus/500')
->status_is(500)
->json_is("/0/name","Configuration file")
->json_is("/0/result","OK")
->json_is("/1/name","Path modules")
->json_is("/1/result","OK")
->json_is("/2/name","Path scanners")
->json_is("/2/result","OK")
->json_is("/3/name","Path bindir")
->json_is("/3/result","OK")
->json_is("/4/name","Path configdir")
->json_is("/4/result","OK")
->json_is("/5/name","Path dbdir")
->json_is("/5/result","OK")
->json_is("/6/name","Database login")
->json_is("/6/result","OK")
->json_is("/7/name","Database structure")
->json_is("/7/result","Error")
->json_hasnt("/8")
;
# Error with non numeric code
$t->get_ok('/api/appstatus/bla')
->status_is(200)
->json_is("/0/name","Configuration file")
->json_is("/0/result","OK")
->json_is("/1/name","Path modules")
->json_is("/1/result","OK")
->json_is("/2/name","Path scanners")
->json_is("/2/result","OK")
->json_is("/3/name","Path bindir")
->json_is("/3/result","OK")
->json_is("/4/name","Path configdir")
->json_is("/4/result","OK")
->json_is("/5/name","Path dbdir")
->json_is("/5/result","OK")
->json_is("/6/name","Database login")
->json_is("/6/result","OK")
->json_is("/7/name","Database structure")
->json_is("/7/result","Error")
->json_hasnt("/8")
;
pass("Creating outdated database");
$db_version = sprintf("%02d", $db_version-1);
`mysql -h 127.0.0.1 -u root seccubus < db/structure_v$db_version.mysql`;
`mysql -h 127.0.0.1 -u root seccubus < db/data_v$db_version.mysql`;
$t->get_ok('/api/appstatus/500')
->status_is(500)
->json_is("/0/name","Configuration file")
->json_is("/0/result","OK")
->json_is("/1/name","Path modules")
->json_is("/1/result","OK")
->json_is("/2/name","Path scanners")
->json_is("/2/result","OK")
->json_is("/3/name","Path bindir")
->json_is("/3/result","OK")
->json_is("/4/name","Path configdir")
->json_is("/4/result","OK")
->json_is("/5/name","Path dbdir")
->json_is("/5/result","OK")
->json_is("/6/name","Database login")
->json_is("/6/result","OK")
->json_is("/7/name","Database structure")
->json_is("/7/result","OK")
->json_is("/8/name","Database version")
->json_is("/8/result","Error")
->json_hasnt("/9")
;
done_testing();
| 31.880682 | 118 | 0.642666 |
73ff5ef659bffd576d3edf79b8a814706c4fb90e | 67,650 | pm | Perl | Git/usr/share/perl5/core_perl/Text/Balanced.pm | DalalBassam/myrecipeswebsite | 1ac6e97b6bac19b6d8a06d8ebf36e1f1b79a18f4 | [
"MIT"
]
| 16 | 2020-09-20T22:32:54.000Z | 2021-04-02T17:14:25.000Z | Git/usr/share/perl5/core_perl/Text/Balanced.pm | DalalBassam/myrecipeswebsite | 1ac6e97b6bac19b6d8a06d8ebf36e1f1b79a18f4 | [
"MIT"
]
| 98 | 2017-11-02T19:00:44.000Z | 2022-03-22T16:15:39.000Z | Git/usr/share/perl5/core_perl/Text/Balanced.pm | DalalBassam/myrecipeswebsite | 1ac6e97b6bac19b6d8a06d8ebf36e1f1b79a18f4 | [
"MIT"
]
| 9 | 2016-10-21T08:18:57.000Z | 2021-05-23T14:19:21.000Z | package Text::Balanced;
# EXTRACT VARIOUSLY DELIMITED TEXT SEQUENCES FROM STRINGS.
# FOR FULL DOCUMENTATION SEE Balanced.pod
use 5.005;
use strict;
use Exporter ();
use SelfLoader;
use vars qw { $VERSION @ISA %EXPORT_TAGS };
BEGIN {
$VERSION = '2.03';
@ISA = 'Exporter';
%EXPORT_TAGS = (
ALL => [ qw{
&extract_delimited
&extract_bracketed
&extract_quotelike
&extract_codeblock
&extract_variable
&extract_tagged
&extract_multiple
&gen_delimited_pat
&gen_extract_tagged
&delimited_pat
} ],
);
}
Exporter::export_ok_tags('ALL');
# PROTOTYPES
sub _match_bracketed($$$$$$);
sub _match_variable($$);
sub _match_codeblock($$$$$$$);
sub _match_quotelike($$$$);
# HANDLE RETURN VALUES IN VARIOUS CONTEXTS
sub _failmsg {
my ($message, $pos) = @_;
$@ = bless {
error => $message,
pos => $pos,
}, 'Text::Balanced::ErrorMsg';
}
sub _fail {
my ($wantarray, $textref, $message, $pos) = @_;
_failmsg $message, $pos if $message;
return (undef, $$textref, undef) if $wantarray;
return undef;
}
sub _succeed {
$@ = undef;
my ($wantarray,$textref) = splice @_, 0, 2;
my ($extrapos, $extralen) = @_ > 18
? splice(@_, -2, 2)
: (0, 0);
my ($startlen, $oppos) = @_[5,6];
my $remainderpos = $_[2];
if ( $wantarray ) {
my @res;
while (my ($from, $len) = splice @_, 0, 2) {
push @res, substr($$textref, $from, $len);
}
if ( $extralen ) { # CORRECT FILLET
my $extra = substr($res[0], $extrapos-$oppos, $extralen, "\n");
$res[1] = "$extra$res[1]";
eval { substr($$textref,$remainderpos,0) = $extra;
substr($$textref,$extrapos,$extralen,"\n")} ;
#REARRANGE HERE DOC AND FILLET IF POSSIBLE
pos($$textref) = $remainderpos-$extralen+1; # RESET \G
} else {
pos($$textref) = $remainderpos; # RESET \G
}
return @res;
} else {
my $match = substr($$textref,$_[0],$_[1]);
substr($match,$extrapos-$_[0]-$startlen,$extralen,"") if $extralen;
my $extra = $extralen
? substr($$textref, $extrapos, $extralen)."\n" : "";
eval {substr($$textref,$_[4],$_[1]+$_[5])=$extra} ; #CHOP OUT PREFIX & MATCH, IF POSSIBLE
pos($$textref) = $_[4]; # RESET \G
return $match;
}
}
# BUILD A PATTERN MATCHING A SIMPLE DELIMITED STRING
sub gen_delimited_pat($;$) # ($delimiters;$escapes)
{
my ($dels, $escs) = @_;
return "" unless $dels =~ /\S/;
$escs = '\\' unless $escs;
$escs .= substr($escs,-1) x (length($dels)-length($escs));
my @pat = ();
my $i;
for ($i=0; $i<length $dels; $i++)
{
my $del = quotemeta substr($dels,$i,1);
my $esc = quotemeta substr($escs,$i,1);
if ($del eq $esc)
{
push @pat, "$del(?:[^$del]*(?:(?:$del$del)[^$del]*)*)$del";
}
else
{
push @pat, "$del(?:[^$esc$del]*(?:$esc.[^$esc$del]*)*)$del";
}
}
my $pat = join '|', @pat;
return "(?:$pat)";
}
*delimited_pat = \&gen_delimited_pat;
# THE EXTRACTION FUNCTIONS
sub extract_delimited (;$$$$)
{
my $textref = defined $_[0] ? \$_[0] : \$_;
my $wantarray = wantarray;
my $del = defined $_[1] ? $_[1] : qq{\'\"\`};
my $pre = defined $_[2] ? $_[2] : '\s*';
my $esc = defined $_[3] ? $_[3] : qq{\\};
my $pat = gen_delimited_pat($del, $esc);
my $startpos = pos $$textref || 0;
return _fail($wantarray, $textref, "Not a delimited pattern", 0)
unless $$textref =~ m/\G($pre)($pat)/gc;
my $prelen = length($1);
my $matchpos = $startpos+$prelen;
my $endpos = pos $$textref;
return _succeed $wantarray, $textref,
$matchpos, $endpos-$matchpos, # MATCH
$endpos, length($$textref)-$endpos, # REMAINDER
$startpos, $prelen; # PREFIX
}
sub extract_bracketed (;$$$)
{
my $textref = defined $_[0] ? \$_[0] : \$_;
my $ldel = defined $_[1] ? $_[1] : '{([<';
my $pre = defined $_[2] ? $_[2] : '\s*';
my $wantarray = wantarray;
my $qdel = "";
my $quotelike;
$ldel =~ s/'//g and $qdel .= q{'};
$ldel =~ s/"//g and $qdel .= q{"};
$ldel =~ s/`//g and $qdel .= q{`};
$ldel =~ s/q//g and $quotelike = 1;
$ldel =~ tr/[](){}<>\0-\377/[[(({{<</ds;
my $rdel = $ldel;
unless ($rdel =~ tr/[({</])}>/)
{
return _fail $wantarray, $textref,
"Did not find a suitable bracket in delimiter: \"$_[1]\"",
0;
}
my $posbug = pos;
$ldel = join('|', map { quotemeta $_ } split('', $ldel));
$rdel = join('|', map { quotemeta $_ } split('', $rdel));
pos = $posbug;
my $startpos = pos $$textref || 0;
my @match = _match_bracketed($textref,$pre, $ldel, $qdel, $quotelike, $rdel);
return _fail ($wantarray, $textref) unless @match;
return _succeed ( $wantarray, $textref,
$match[2], $match[5]+2, # MATCH
@match[8,9], # REMAINDER
@match[0,1], # PREFIX
);
}
sub _match_bracketed($$$$$$) # $textref, $pre, $ldel, $qdel, $quotelike, $rdel
{
my ($textref, $pre, $ldel, $qdel, $quotelike, $rdel) = @_;
my ($startpos, $ldelpos, $endpos) = (pos $$textref = pos $$textref||0);
unless ($$textref =~ m/\G$pre/gc)
{
_failmsg "Did not find prefix: /$pre/", $startpos;
return;
}
$ldelpos = pos $$textref;
unless ($$textref =~ m/\G($ldel)/gc)
{
_failmsg "Did not find opening bracket after prefix: \"$pre\"",
pos $$textref;
pos $$textref = $startpos;
return;
}
my @nesting = ( $1 );
my $textlen = length $$textref;
while (pos $$textref < $textlen)
{
next if $$textref =~ m/\G\\./gcs;
if ($$textref =~ m/\G($ldel)/gc)
{
push @nesting, $1;
}
elsif ($$textref =~ m/\G($rdel)/gc)
{
my ($found, $brackettype) = ($1, $1);
if ($#nesting < 0)
{
_failmsg "Unmatched closing bracket: \"$found\"",
pos $$textref;
pos $$textref = $startpos;
return;
}
my $expected = pop(@nesting);
$expected =~ tr/({[</)}]>/;
if ($expected ne $brackettype)
{
_failmsg qq{Mismatched closing bracket: expected "$expected" but found "$found"},
pos $$textref;
pos $$textref = $startpos;
return;
}
last if $#nesting < 0;
}
elsif ($qdel && $$textref =~ m/\G([$qdel])/gc)
{
$$textref =~ m/\G[^\\$1]*(?:\\.[^\\$1]*)*(\Q$1\E)/gsc and next;
_failmsg "Unmatched embedded quote ($1)",
pos $$textref;
pos $$textref = $startpos;
return;
}
elsif ($quotelike && _match_quotelike($textref,"",1,0))
{
next;
}
else { $$textref =~ m/\G(?:[a-zA-Z0-9]+|.)/gcs }
}
if ($#nesting>=0)
{
_failmsg "Unmatched opening bracket(s): "
. join("..",@nesting)."..",
pos $$textref;
pos $$textref = $startpos;
return;
}
$endpos = pos $$textref;
return (
$startpos, $ldelpos-$startpos, # PREFIX
$ldelpos, 1, # OPENING BRACKET
$ldelpos+1, $endpos-$ldelpos-2, # CONTENTS
$endpos-1, 1, # CLOSING BRACKET
$endpos, length($$textref)-$endpos, # REMAINDER
);
}
sub _revbracket($)
{
my $brack = reverse $_[0];
$brack =~ tr/[({</])}>/;
return $brack;
}
my $XMLNAME = q{[a-zA-Z_:][a-zA-Z0-9_:.-]*};
sub extract_tagged (;$$$$$) # ($text, $opentag, $closetag, $pre, \%options)
{
my $textref = defined $_[0] ? \$_[0] : \$_;
my $ldel = $_[1];
my $rdel = $_[2];
my $pre = defined $_[3] ? $_[3] : '\s*';
my %options = defined $_[4] ? %{$_[4]} : ();
my $omode = defined $options{fail} ? $options{fail} : '';
my $bad = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}})
: defined($options{reject}) ? $options{reject}
: ''
;
my $ignore = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}})
: defined($options{ignore}) ? $options{ignore}
: ''
;
if (!defined $ldel) { $ldel = '<\w+(?:' . gen_delimited_pat(q{'"}) . '|[^>])*>'; }
$@ = undef;
my @match = _match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore);
return _fail(wantarray, $textref) unless @match;
return _succeed wantarray, $textref,
$match[2], $match[3]+$match[5]+$match[7], # MATCH
@match[8..9,0..1,2..7]; # REM, PRE, BITS
}
sub _match_tagged # ($$$$$$$)
{
my ($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore) = @_;
my $rdelspec;
my ($startpos, $opentagpos, $textpos, $parapos, $closetagpos, $endpos) = ( pos($$textref) = pos($$textref)||0 );
unless ($$textref =~ m/\G($pre)/gc)
{
_failmsg "Did not find prefix: /$pre/", pos $$textref;
goto failed;
}
$opentagpos = pos($$textref);
unless ($$textref =~ m/\G$ldel/gc)
{
_failmsg "Did not find opening tag: /$ldel/", pos $$textref;
goto failed;
}
$textpos = pos($$textref);
if (!defined $rdel)
{
$rdelspec = substr($$textref, $-[0], $+[0] - $-[0]);
unless ($rdelspec =~ s/\A([[(<{]+)($XMLNAME).*/ quotemeta "$1\/$2". _revbracket($1) /oes)
{
_failmsg "Unable to construct closing tag to match: $rdel",
pos $$textref;
goto failed;
}
}
else
{
$rdelspec = eval "qq{$rdel}" || do {
my $del;
for (qw,~ ! ^ & * ) _ + - = } ] : " ; ' > . ? / | ',)
{ next if $rdel =~ /\Q$_/; $del = $_; last }
unless ($del) {
use Carp;
croak "Can't interpolate right delimiter $rdel"
}
eval "qq$del$rdel$del";
};
}
while (pos($$textref) < length($$textref))
{
next if $$textref =~ m/\G\\./gc;
if ($$textref =~ m/\G(\n[ \t]*\n)/gc )
{
$parapos = pos($$textref) - length($1)
unless defined $parapos;
}
elsif ($$textref =~ m/\G($rdelspec)/gc )
{
$closetagpos = pos($$textref)-length($1);
goto matched;
}
elsif ($ignore && $$textref =~ m/\G(?:$ignore)/gc)
{
next;
}
elsif ($bad && $$textref =~ m/\G($bad)/gcs)
{
pos($$textref) -= length($1); # CUT OFF WHATEVER CAUSED THE SHORTNESS
goto short if ($omode eq 'PARA' || $omode eq 'MAX');
_failmsg "Found invalid nested tag: $1", pos $$textref;
goto failed;
}
elsif ($$textref =~ m/\G($ldel)/gc)
{
my $tag = $1;
pos($$textref) -= length($tag); # REWIND TO NESTED TAG
unless (_match_tagged(@_)) # MATCH NESTED TAG
{
goto short if $omode eq 'PARA' || $omode eq 'MAX';
_failmsg "Found unbalanced nested tag: $tag",
pos $$textref;
goto failed;
}
}
else { $$textref =~ m/./gcs }
}
short:
$closetagpos = pos($$textref);
goto matched if $omode eq 'MAX';
goto failed unless $omode eq 'PARA';
if (defined $parapos) { pos($$textref) = $parapos }
else { $parapos = pos($$textref) }
return (
$startpos, $opentagpos-$startpos, # PREFIX
$opentagpos, $textpos-$opentagpos, # OPENING TAG
$textpos, $parapos-$textpos, # TEXT
$parapos, 0, # NO CLOSING TAG
$parapos, length($$textref)-$parapos, # REMAINDER
);
matched:
$endpos = pos($$textref);
return (
$startpos, $opentagpos-$startpos, # PREFIX
$opentagpos, $textpos-$opentagpos, # OPENING TAG
$textpos, $closetagpos-$textpos, # TEXT
$closetagpos, $endpos-$closetagpos, # CLOSING TAG
$endpos, length($$textref)-$endpos, # REMAINDER
);
failed:
_failmsg "Did not find closing tag", pos $$textref unless $@;
pos($$textref) = $startpos;
return;
}
sub extract_variable (;$$)
{
my $textref = defined $_[0] ? \$_[0] : \$_;
return ("","","") unless defined $$textref;
my $pre = defined $_[1] ? $_[1] : '\s*';
my @match = _match_variable($textref,$pre);
return _fail wantarray, $textref unless @match;
return _succeed wantarray, $textref,
@match[2..3,4..5,0..1]; # MATCH, REMAINDER, PREFIX
}
sub _match_variable($$)
{
# $#
# $^
# $$
my ($textref, $pre) = @_;
my $startpos = pos($$textref) = pos($$textref)||0;
unless ($$textref =~ m/\G($pre)/gc)
{
_failmsg "Did not find prefix: /$pre/", pos $$textref;
return;
}
my $varpos = pos($$textref);
unless ($$textref =~ m{\G\$\s*(?!::)(\d+|[][&`'+*./|,";%=~:?!\@<>()-]|\^[a-z]?)}gci)
{
unless ($$textref =~ m/\G((\$#?|[*\@\%]|\\&)+)/gc)
{
_failmsg "Did not find leading dereferencer", pos $$textref;
pos $$textref = $startpos;
return;
}
my $deref = $1;
unless ($$textref =~ m/\G\s*(?:::|')?(?:[_a-z]\w*(?:::|'))*[_a-z]\w*/gci
or _match_codeblock($textref, "", '\{', '\}', '\{', '\}', 0)
or $deref eq '$#' or $deref eq '$$' )
{
_failmsg "Bad identifier after dereferencer", pos $$textref;
pos $$textref = $startpos;
return;
}
}
while (1)
{
next if $$textref =~ m/\G\s*(?:->)?\s*[{]\w+[}]/gc;
next if _match_codeblock($textref,
qr/\s*->\s*(?:[_a-zA-Z]\w+\s*)?/,
qr/[({[]/, qr/[)}\]]/,
qr/[({[]/, qr/[)}\]]/, 0);
next if _match_codeblock($textref,
qr/\s*/, qr/[{[]/, qr/[}\]]/,
qr/[{[]/, qr/[}\]]/, 0);
next if _match_variable($textref,'\s*->\s*');
next if $$textref =~ m/\G\s*->\s*\w+(?![{([])/gc;
last;
}
my $endpos = pos($$textref);
return ($startpos, $varpos-$startpos,
$varpos, $endpos-$varpos,
$endpos, length($$textref)-$endpos
);
}
sub extract_codeblock (;$$$$$)
{
my $textref = defined $_[0] ? \$_[0] : \$_;
my $wantarray = wantarray;
my $ldel_inner = defined $_[1] ? $_[1] : '{';
my $pre = defined $_[2] ? $_[2] : '\s*';
my $ldel_outer = defined $_[3] ? $_[3] : $ldel_inner;
my $rd = $_[4];
my $rdel_inner = $ldel_inner;
my $rdel_outer = $ldel_outer;
my $posbug = pos;
for ($ldel_inner, $ldel_outer) { tr/[]()<>{}\0-\377/[[((<<{{/ds }
for ($rdel_inner, $rdel_outer) { tr/[]()<>{}\0-\377/]]))>>}}/ds }
for ($ldel_inner, $ldel_outer, $rdel_inner, $rdel_outer)
{
$_ = '('.join('|',map { quotemeta $_ } split('',$_)).')'
}
pos = $posbug;
my @match = _match_codeblock($textref, $pre,
$ldel_outer, $rdel_outer,
$ldel_inner, $rdel_inner,
$rd);
return _fail($wantarray, $textref) unless @match;
return _succeed($wantarray, $textref,
@match[2..3,4..5,0..1] # MATCH, REMAINDER, PREFIX
);
}
sub _match_codeblock($$$$$$$)
{
my ($textref, $pre, $ldel_outer, $rdel_outer, $ldel_inner, $rdel_inner, $rd) = @_;
my $startpos = pos($$textref) = pos($$textref) || 0;
unless ($$textref =~ m/\G($pre)/gc)
{
_failmsg qq{Did not match prefix /$pre/ at"} .
substr($$textref,pos($$textref),20) .
q{..."},
pos $$textref;
return;
}
my $codepos = pos($$textref);
unless ($$textref =~ m/\G($ldel_outer)/gc) # OUTERMOST DELIMITER
{
_failmsg qq{Did not find expected opening bracket at "} .
substr($$textref,pos($$textref),20) .
q{..."},
pos $$textref;
pos $$textref = $startpos;
return;
}
my $closing = $1;
$closing =~ tr/([<{/)]>}/;
my $matched;
my $patvalid = 1;
while (pos($$textref) < length($$textref))
{
$matched = '';
if ($rd && $$textref =~ m#\G(\Q(?)\E|\Q(s?)\E|\Q(s)\E)#gc)
{
$patvalid = 0;
next;
}
if ($$textref =~ m/\G\s*#.*/gc)
{
next;
}
if ($$textref =~ m/\G\s*($rdel_outer)/gc)
{
unless ($matched = ($closing && $1 eq $closing) )
{
next if $1 eq '>'; # MIGHT BE A "LESS THAN"
_failmsg q{Mismatched closing bracket at "} .
substr($$textref,pos($$textref),20) .
qq{...". Expected '$closing'},
pos $$textref;
}
last;
}
if (_match_variable($textref,'\s*') ||
_match_quotelike($textref,'\s*',$patvalid,$patvalid) )
{
$patvalid = 0;
next;
}
# NEED TO COVER MANY MORE CASES HERE!!!
if ($$textref =~ m#\G\s*(?!$ldel_inner)
( [-+*x/%^&|.]=?
| [!=]~
| =(?!>)
| (\*\*|&&|\|\||<<|>>)=?
| split|grep|map|return
| [([]
)#gcx)
{
$patvalid = 1;
next;
}
if ( _match_codeblock($textref, '\s*', $ldel_inner, $rdel_inner, $ldel_inner, $rdel_inner, $rd) )
{
$patvalid = 1;
next;
}
if ($$textref =~ m/\G\s*$ldel_outer/gc)
{
_failmsg q{Improperly nested codeblock at "} .
substr($$textref,pos($$textref),20) .
q{..."},
pos $$textref;
last;
}
$patvalid = 0;
$$textref =~ m/\G\s*(\w+|[-=>]>|.|\Z)/gc;
}
continue { $@ = undef }
unless ($matched)
{
_failmsg 'No match found for opening bracket', pos $$textref
unless $@;
return;
}
my $endpos = pos($$textref);
return ( $startpos, $codepos-$startpos,
$codepos, $endpos-$codepos,
$endpos, length($$textref)-$endpos,
);
}
my %mods = (
'none' => '[cgimsox]*',
'm' => '[cgimsox]*',
's' => '[cegimsox]*',
'tr' => '[cds]*',
'y' => '[cds]*',
'qq' => '',
'qx' => '',
'qw' => '',
'qr' => '[imsx]*',
'q' => '',
);
sub extract_quotelike (;$$)
{
my $textref = $_[0] ? \$_[0] : \$_;
my $wantarray = wantarray;
my $pre = defined $_[1] ? $_[1] : '\s*';
my @match = _match_quotelike($textref,$pre,1,0);
return _fail($wantarray, $textref) unless @match;
return _succeed($wantarray, $textref,
$match[2], $match[18]-$match[2], # MATCH
@match[18,19], # REMAINDER
@match[0,1], # PREFIX
@match[2..17], # THE BITS
@match[20,21], # ANY FILLET?
);
};
sub _match_quotelike($$$$) # ($textref, $prepat, $allow_raw_match)
{
my ($textref, $pre, $rawmatch, $qmark) = @_;
my ($textlen,$startpos,
$oppos,
$preld1pos,$ld1pos,$str1pos,$rd1pos,
$preld2pos,$ld2pos,$str2pos,$rd2pos,
$modpos) = ( length($$textref), pos($$textref) = pos($$textref) || 0 );
unless ($$textref =~ m/\G($pre)/gc)
{
_failmsg qq{Did not find prefix /$pre/ at "} .
substr($$textref, pos($$textref), 20) .
q{..."},
pos $$textref;
return;
}
$oppos = pos($$textref);
my $initial = substr($$textref,$oppos,1);
if ($initial && $initial =~ m|^[\"\'\`]|
|| $rawmatch && $initial =~ m|^/|
|| $qmark && $initial =~ m|^\?|)
{
unless ($$textref =~ m/ \Q$initial\E [^\\$initial]* (\\.[^\\$initial]*)* \Q$initial\E /gcsx)
{
_failmsg qq{Did not find closing delimiter to match '$initial' at "} .
substr($$textref, $oppos, 20) .
q{..."},
pos $$textref;
pos $$textref = $startpos;
return;
}
$modpos= pos($$textref);
$rd1pos = $modpos-1;
if ($initial eq '/' || $initial eq '?')
{
$$textref =~ m/\G$mods{none}/gc
}
my $endpos = pos($$textref);
return (
$startpos, $oppos-$startpos, # PREFIX
$oppos, 0, # NO OPERATOR
$oppos, 1, # LEFT DEL
$oppos+1, $rd1pos-$oppos-1, # STR/PAT
$rd1pos, 1, # RIGHT DEL
$modpos, 0, # NO 2ND LDEL
$modpos, 0, # NO 2ND STR
$modpos, 0, # NO 2ND RDEL
$modpos, $endpos-$modpos, # MODIFIERS
$endpos, $textlen-$endpos, # REMAINDER
);
}
unless ($$textref =~ m{\G(\b(?:m|s|qq|qx|qw|q|qr|tr|y)\b(?=\s*\S)|<<)}gc)
{
_failmsg q{No quotelike operator found after prefix at "} .
substr($$textref, pos($$textref), 20) .
q{..."},
pos $$textref;
pos $$textref = $startpos;
return;
}
my $op = $1;
$preld1pos = pos($$textref);
if ($op eq '<<') {
$ld1pos = pos($$textref);
my $label;
if ($$textref =~ m{\G([A-Za-z_]\w*)}gc) {
$label = $1;
}
elsif ($$textref =~ m{ \G ' ([^'\\]* (?:\\.[^'\\]*)*) '
| \G " ([^"\\]* (?:\\.[^"\\]*)*) "
| \G ` ([^`\\]* (?:\\.[^`\\]*)*) `
}gcsx) {
$label = $+;
}
else {
$label = "";
}
my $extrapos = pos($$textref);
$$textref =~ m{.*\n}gc;
$str1pos = pos($$textref)--;
unless ($$textref =~ m{.*?\n(?=\Q$label\E\n)}gc) {
_failmsg qq{Missing here doc terminator ('$label') after "} .
substr($$textref, $startpos, 20) .
q{..."},
pos $$textref;
pos $$textref = $startpos;
return;
}
$rd1pos = pos($$textref);
$$textref =~ m{\Q$label\E\n}gc;
$ld2pos = pos($$textref);
return (
$startpos, $oppos-$startpos, # PREFIX
$oppos, length($op), # OPERATOR
$ld1pos, $extrapos-$ld1pos, # LEFT DEL
$str1pos, $rd1pos-$str1pos, # STR/PAT
$rd1pos, $ld2pos-$rd1pos, # RIGHT DEL
$ld2pos, 0, # NO 2ND LDEL
$ld2pos, 0, # NO 2ND STR
$ld2pos, 0, # NO 2ND RDEL
$ld2pos, 0, # NO MODIFIERS
$ld2pos, $textlen-$ld2pos, # REMAINDER
$extrapos, $str1pos-$extrapos, # FILLETED BIT
);
}
$$textref =~ m/\G\s*/gc;
$ld1pos = pos($$textref);
$str1pos = $ld1pos+1;
unless ($$textref =~ m/\G(\S)/gc) # SHOULD USE LOOKAHEAD
{
_failmsg "No block delimiter found after quotelike $op",
pos $$textref;
pos $$textref = $startpos;
return;
}
pos($$textref) = $ld1pos; # HAVE TO DO THIS BECAUSE LOOKAHEAD BROKEN
my ($ldel1, $rdel1) = ("\Q$1","\Q$1");
if ($ldel1 =~ /[[(<{]/)
{
$rdel1 =~ tr/[({</])}>/;
defined(_match_bracketed($textref,"",$ldel1,"","",$rdel1))
|| do { pos $$textref = $startpos; return };
$ld2pos = pos($$textref);
$rd1pos = $ld2pos-1;
}
else
{
$$textref =~ /\G$ldel1[^\\$ldel1]*(\\.[^\\$ldel1]*)*$ldel1/gcs
|| do { pos $$textref = $startpos; return };
$ld2pos = $rd1pos = pos($$textref)-1;
}
my $second_arg = $op =~ /s|tr|y/ ? 1 : 0;
if ($second_arg)
{
my ($ldel2, $rdel2);
if ($ldel1 =~ /[[(<{]/)
{
unless ($$textref =~ /\G\s*(\S)/gc) # SHOULD USE LOOKAHEAD
{
_failmsg "Missing second block for quotelike $op",
pos $$textref;
pos $$textref = $startpos;
return;
}
$ldel2 = $rdel2 = "\Q$1";
$rdel2 =~ tr/[({</])}>/;
}
else
{
$ldel2 = $rdel2 = $ldel1;
}
$str2pos = $ld2pos+1;
if ($ldel2 =~ /[[(<{]/)
{
pos($$textref)--; # OVERCOME BROKEN LOOKAHEAD
defined(_match_bracketed($textref,"",$ldel2,"","",$rdel2))
|| do { pos $$textref = $startpos; return };
}
else
{
$$textref =~ /[^\\$ldel2]*(\\.[^\\$ldel2]*)*$ldel2/gcs
|| do { pos $$textref = $startpos; return };
}
$rd2pos = pos($$textref)-1;
}
else
{
$ld2pos = $str2pos = $rd2pos = $rd1pos;
}
$modpos = pos $$textref;
$$textref =~ m/\G($mods{$op})/gc;
my $endpos = pos $$textref;
return (
$startpos, $oppos-$startpos, # PREFIX
$oppos, length($op), # OPERATOR
$ld1pos, 1, # LEFT DEL
$str1pos, $rd1pos-$str1pos, # STR/PAT
$rd1pos, 1, # RIGHT DEL
$ld2pos, $second_arg, # 2ND LDEL (MAYBE)
$str2pos, $rd2pos-$str2pos, # 2ND STR (MAYBE)
$rd2pos, $second_arg, # 2ND RDEL (MAYBE)
$modpos, $endpos-$modpos, # MODIFIERS
$endpos, $textlen-$endpos, # REMAINDER
);
}
my $def_func = [
sub { extract_variable($_[0], '') },
sub { extract_quotelike($_[0],'') },
sub { extract_codeblock($_[0],'{}','') },
];
sub extract_multiple (;$$$$) # ($text, $functions_ref, $max_fields, $ignoreunknown)
{
my $textref = defined($_[0]) ? \$_[0] : \$_;
my $posbug = pos;
my ($lastpos, $firstpos);
my @fields = ();
#for ($$textref)
{
my @func = defined $_[1] ? @{$_[1]} : @{$def_func};
my $max = defined $_[2] && $_[2]>0 ? $_[2] : 1_000_000_000;
my $igunk = $_[3];
pos $$textref ||= 0;
unless (wantarray)
{
use Carp;
carp "extract_multiple reset maximal count to 1 in scalar context"
if $^W && defined($_[2]) && $max > 1;
$max = 1
}
my $unkpos;
my $func;
my $class;
my @class;
foreach $func ( @func )
{
if (ref($func) eq 'HASH')
{
push @class, (keys %$func)[0];
$func = (values %$func)[0];
}
else
{
push @class, undef;
}
}
FIELD: while (pos($$textref) < length($$textref))
{
my ($field, $rem);
my @bits;
foreach my $i ( 0..$#func )
{
my $pref;
$func = $func[$i];
$class = $class[$i];
$lastpos = pos $$textref;
if (ref($func) eq 'CODE')
{ ($field,$rem,$pref) = @bits = $func->($$textref) }
elsif (ref($func) eq 'Text::Balanced::Extractor')
{ @bits = $field = $func->extract($$textref) }
elsif( $$textref =~ m/\G$func/gc )
{ @bits = $field = defined($1)
? $1
: substr($$textref, $-[0], $+[0] - $-[0])
}
$pref ||= "";
if (defined($field) && length($field))
{
if (!$igunk) {
$unkpos = $lastpos
if length($pref) && !defined($unkpos);
if (defined $unkpos)
{
push @fields, substr($$textref, $unkpos, $lastpos-$unkpos).$pref;
$firstpos = $unkpos unless defined $firstpos;
undef $unkpos;
last FIELD if @fields == $max;
}
}
push @fields, $class
? bless (\$field, $class)
: $field;
$firstpos = $lastpos unless defined $firstpos;
$lastpos = pos $$textref;
last FIELD if @fields == $max;
next FIELD;
}
}
if ($$textref =~ /\G(.)/gcs)
{
$unkpos = pos($$textref)-1
unless $igunk || defined $unkpos;
}
}
if (defined $unkpos)
{
push @fields, substr($$textref, $unkpos);
$firstpos = $unkpos unless defined $firstpos;
$lastpos = length $$textref;
}
last;
}
pos $$textref = $lastpos;
return @fields if wantarray;
$firstpos ||= 0;
eval { substr($$textref,$firstpos,$lastpos-$firstpos)="";
pos $$textref = $firstpos };
return $fields[0];
}
sub gen_extract_tagged # ($opentag, $closetag, $pre, \%options)
{
my $ldel = $_[0];
my $rdel = $_[1];
my $pre = defined $_[2] ? $_[2] : '\s*';
my %options = defined $_[3] ? %{$_[3]} : ();
my $omode = defined $options{fail} ? $options{fail} : '';
my $bad = ref($options{reject}) eq 'ARRAY' ? join('|', @{$options{reject}})
: defined($options{reject}) ? $options{reject}
: ''
;
my $ignore = ref($options{ignore}) eq 'ARRAY' ? join('|', @{$options{ignore}})
: defined($options{ignore}) ? $options{ignore}
: ''
;
if (!defined $ldel) { $ldel = '<\w+(?:' . gen_delimited_pat(q{'"}) . '|[^>])*>'; }
my $posbug = pos;
for ($ldel, $pre, $bad, $ignore) { $_ = qr/$_/ if $_ }
pos = $posbug;
my $closure = sub
{
my $textref = defined $_[0] ? \$_[0] : \$_;
my @match = Text::Balanced::_match_tagged($textref, $pre, $ldel, $rdel, $omode, $bad, $ignore);
return _fail(wantarray, $textref) unless @match;
return _succeed wantarray, $textref,
$match[2], $match[3]+$match[5]+$match[7], # MATCH
@match[8..9,0..1,2..7]; # REM, PRE, BITS
};
bless $closure, 'Text::Balanced::Extractor';
}
package Text::Balanced::Extractor;
sub extract($$) # ($self, $text)
{
&{$_[0]}($_[1]);
}
package Text::Balanced::ErrorMsg;
use overload '""' => sub { "$_[0]->{error}, detected at offset $_[0]->{pos}" };
1;
__END__
=pod
=head1 NAME
Text::Balanced - Extract delimited text sequences from strings.
=head1 SYNOPSIS
use Text::Balanced qw (
extract_delimited
extract_bracketed
extract_quotelike
extract_codeblock
extract_variable
extract_tagged
extract_multiple
gen_delimited_pat
gen_extract_tagged
);
# Extract the initial substring of $text that is delimited by
# two (unescaped) instances of the first character in $delim.
($extracted, $remainder) = extract_delimited($text,$delim);
# Extract the initial substring of $text that is bracketed
# with a delimiter(s) specified by $delim (where the string
# in $delim contains one or more of '(){}[]<>').
($extracted, $remainder) = extract_bracketed($text,$delim);
# Extract the initial substring of $text that is bounded by
# an XML tag.
($extracted, $remainder) = extract_tagged($text);
# Extract the initial substring of $text that is bounded by
# a C<BEGIN>...C<END> pair. Don't allow nested C<BEGIN> tags
($extracted, $remainder) =
extract_tagged($text,"BEGIN","END",undef,{bad=>["BEGIN"]});
# Extract the initial substring of $text that represents a
# Perl "quote or quote-like operation"
($extracted, $remainder) = extract_quotelike($text);
# Extract the initial substring of $text that represents a block
# of Perl code, bracketed by any of character(s) specified by $delim
# (where the string $delim contains one or more of '(){}[]<>').
($extracted, $remainder) = extract_codeblock($text,$delim);
# Extract the initial substrings of $text that would be extracted by
# one or more sequential applications of the specified functions
# or regular expressions
@extracted = extract_multiple($text,
[ \&extract_bracketed,
\&extract_quotelike,
\&some_other_extractor_sub,
qr/[xyz]*/,
'literal',
]);
# Create a string representing an optimized pattern (a la Friedl)
# that matches a substring delimited by any of the specified characters
# (in this case: any type of quote or a slash)
$patstring = gen_delimited_pat(q{'"`/});
# Generate a reference to an anonymous sub that is just like extract_tagged
# but pre-compiled and optimized for a specific pair of tags, and consequently
# much faster (i.e. 3 times faster). It uses qr// for better performance on
# repeated calls, so it only works under Perl 5.005 or later.
$extract_head = gen_extract_tagged('<HEAD>','</HEAD>');
($extracted, $remainder) = $extract_head->($text);
=head1 DESCRIPTION
The various C<extract_...> subroutines may be used to
extract a delimited substring, possibly after skipping a
specified prefix string. By default, that prefix is
optional whitespace (C</\s*/>), but you can change it to whatever
you wish (see below).
The substring to be extracted must appear at the
current C<pos> location of the string's variable
(or at index zero, if no C<pos> position is defined).
In other words, the C<extract_...> subroutines I<don't>
extract the first occurrence of a substring anywhere
in a string (like an unanchored regex would). Rather,
they extract an occurrence of the substring appearing
immediately at the current matching position in the
string (like a C<\G>-anchored regex would).
=head2 General behaviour in list contexts
In a list context, all the subroutines return a list, the first three
elements of which are always:
=over 4
=item [0]
The extracted string, including the specified delimiters.
If the extraction fails C<undef> is returned.
=item [1]
The remainder of the input string (i.e. the characters after the
extracted string). On failure, the entire string is returned.
=item [2]
The skipped prefix (i.e. the characters before the extracted string).
On failure, C<undef> is returned.
=back
Note that in a list context, the contents of the original input text (the first
argument) are not modified in any way.
However, if the input text was passed in a variable, that variable's
C<pos> value is updated to point at the first character after the
extracted text. That means that in a list context the various
subroutines can be used much like regular expressions. For example:
while ( $next = (extract_quotelike($text))[0] )
{
# process next quote-like (in $next)
}
=head2 General behaviour in scalar and void contexts
In a scalar context, the extracted string is returned, having first been
removed from the input text. Thus, the following code also processes
each quote-like operation, but actually removes them from $text:
while ( $next = extract_quotelike($text) )
{
# process next quote-like (in $next)
}
Note that if the input text is a read-only string (i.e. a literal),
no attempt is made to remove the extracted text.
In a void context the behaviour of the extraction subroutines is
exactly the same as in a scalar context, except (of course) that the
extracted substring is not returned.
=head2 A note about prefixes
Prefix patterns are matched without any trailing modifiers (C</gimsox> etc.)
This can bite you if you're expecting a prefix specification like
'.*?(?=<H1>)' to skip everything up to the first <H1> tag. Such a prefix
pattern will only succeed if the <H1> tag is on the current line, since
. normally doesn't match newlines.
To overcome this limitation, you need to turn on /s matching within
the prefix pattern, using the C<(?s)> directive: '(?s).*?(?=<H1>)'
=head2 C<extract_delimited>
The C<extract_delimited> function formalizes the common idiom
of extracting a single-character-delimited substring from the start of
a string. For example, to extract a single-quote delimited string, the
following code is typically used:
($remainder = $text) =~ s/\A('(\\.|[^'])*')//s;
$extracted = $1;
but with C<extract_delimited> it can be simplified to:
($extracted,$remainder) = extract_delimited($text, "'");
C<extract_delimited> takes up to four scalars (the input text, the
delimiters, a prefix pattern to be skipped, and any escape characters)
and extracts the initial substring of the text that
is appropriately delimited. If the delimiter string has multiple
characters, the first one encountered in the text is taken to delimit
the substring.
The third argument specifies a prefix pattern that is to be skipped
(but must be present!) before the substring is extracted.
The final argument specifies the escape character to be used for each
delimiter.
All arguments are optional. If the escape characters are not specified,
every delimiter is escaped with a backslash (C<\>).
If the prefix is not specified, the
pattern C<'\s*'> - optional whitespace - is used. If the delimiter set
is also not specified, the set C</["'`]/> is used. If the text to be processed
is not specified either, C<$_> is used.
In list context, C<extract_delimited> returns a array of three
elements, the extracted substring (I<including the surrounding
delimiters>), the remainder of the text, and the skipped prefix (if
any). If a suitable delimited substring is not found, the first
element of the array is the empty string, the second is the complete
original text, and the prefix returned in the third element is an
empty string.
In a scalar context, just the extracted substring is returned. In
a void context, the extracted substring (and any prefix) are simply
removed from the beginning of the first argument.
Examples:
# Remove a single-quoted substring from the very beginning of $text:
$substring = extract_delimited($text, "'", '');
# Remove a single-quoted Pascalish substring (i.e. one in which
# doubling the quote character escapes it) from the very
# beginning of $text:
$substring = extract_delimited($text, "'", '', "'");
# Extract a single- or double- quoted substring from the
# beginning of $text, optionally after some whitespace
# (note the list context to protect $text from modification):
($substring) = extract_delimited $text, q{"'};
# Delete the substring delimited by the first '/' in $text:
$text = join '', (extract_delimited($text,'/','[^/]*')[2,1];
Note that this last example is I<not> the same as deleting the first
quote-like pattern. For instance, if C<$text> contained the string:
"if ('./cmd' =~ m/$UNIXCMD/s) { $cmd = $1; }"
then after the deletion it would contain:
"if ('.$UNIXCMD/s) { $cmd = $1; }"
not:
"if ('./cmd' =~ ms) { $cmd = $1; }"
See L<"extract_quotelike"> for a (partial) solution to this problem.
=head2 C<extract_bracketed>
Like C<"extract_delimited">, the C<extract_bracketed> function takes
up to three optional scalar arguments: a string to extract from, a delimiter
specifier, and a prefix pattern. As before, a missing prefix defaults to
optional whitespace and a missing text defaults to C<$_>. However, a missing
delimiter specifier defaults to C<'{}()[]E<lt>E<gt>'> (see below).
C<extract_bracketed> extracts a balanced-bracket-delimited
substring (using any one (or more) of the user-specified delimiter
brackets: '(..)', '{..}', '[..]', or '<..>'). Optionally it will also
respect quoted unbalanced brackets (see below).
A "delimiter bracket" is a bracket in list of delimiters passed as
C<extract_bracketed>'s second argument. Delimiter brackets are
specified by giving either the left or right (or both!) versions
of the required bracket(s). Note that the order in which
two or more delimiter brackets are specified is not significant.
A "balanced-bracket-delimited substring" is a substring bounded by
matched brackets, such that any other (left or right) delimiter
bracket I<within> the substring is also matched by an opposite
(right or left) delimiter bracket I<at the same level of nesting>. Any
type of bracket not in the delimiter list is treated as an ordinary
character.
In other words, each type of bracket specified as a delimiter must be
balanced and correctly nested within the substring, and any other kind of
("non-delimiter") bracket in the substring is ignored.
For example, given the string:
$text = "{ an '[irregularly :-(] {} parenthesized >:-)' string }";
then a call to C<extract_bracketed> in a list context:
@result = extract_bracketed( $text, '{}' );
would return:
( "{ an '[irregularly :-(] {} parenthesized >:-)' string }" , "" , "" )
since both sets of C<'{..}'> brackets are properly nested and evenly balanced.
(In a scalar context just the first element of the array would be returned. In
a void context, C<$text> would be replaced by an empty string.)
Likewise the call in:
@result = extract_bracketed( $text, '{[' );
would return the same result, since all sets of both types of specified
delimiter brackets are correctly nested and balanced.
However, the call in:
@result = extract_bracketed( $text, '{([<' );
would fail, returning:
( undef , "{ an '[irregularly :-(] {} parenthesized >:-)' string }" );
because the embedded pairs of C<'(..)'>s and C<'[..]'>s are "cross-nested" and
the embedded C<'E<gt>'> is unbalanced. (In a scalar context, this call would
return an empty string. In a void context, C<$text> would be unchanged.)
Note that the embedded single-quotes in the string don't help in this
case, since they have not been specified as acceptable delimiters and are
therefore treated as non-delimiter characters (and ignored).
However, if a particular species of quote character is included in the
delimiter specification, then that type of quote will be correctly handled.
for example, if C<$text> is:
$text = '<A HREF=">>>>">link</A>';
then
@result = extract_bracketed( $text, '<">' );
returns:
( '<A HREF=">>>>">', 'link</A>', "" )
as expected. Without the specification of C<"> as an embedded quoter:
@result = extract_bracketed( $text, '<>' );
the result would be:
( '<A HREF=">', '>>>">link</A>', "" )
In addition to the quote delimiters C<'>, C<">, and C<`>, full Perl quote-like
quoting (i.e. q{string}, qq{string}, etc) can be specified by including the
letter 'q' as a delimiter. Hence:
@result = extract_bracketed( $text, '<q>' );
would correctly match something like this:
$text = '<leftop: conj /and/ conj>';
See also: C<"extract_quotelike"> and C<"extract_codeblock">.
=head2 C<extract_variable>
C<extract_variable> extracts any valid Perl variable or
variable-involved expression, including scalars, arrays, hashes, array
accesses, hash look-ups, method calls through objects, subroutine calls
through subroutine references, etc.
The subroutine takes up to two optional arguments:
=over 4
=item 1.
A string to be processed (C<$_> if the string is omitted or C<undef>)
=item 2.
A string specifying a pattern to be matched as a prefix (which is to be
skipped). If omitted, optional whitespace is skipped.
=back
On success in a list context, an array of 3 elements is returned. The
elements are:
=over 4
=item [0]
the extracted variable, or variablish expression
=item [1]
the remainder of the input text,
=item [2]
the prefix substring (if any),
=back
On failure, all of these values (except the remaining text) are C<undef>.
In a scalar context, C<extract_variable> returns just the complete
substring that matched a variablish expression. C<undef> is returned on
failure. In addition, the original input text has the returned substring
(and any prefix) removed from it.
In a void context, the input text just has the matched substring (and
any specified prefix) removed.
=head2 C<extract_tagged>
C<extract_tagged> extracts and segments text between (balanced)
specified tags.
The subroutine takes up to five optional arguments:
=over 4
=item 1.
A string to be processed (C<$_> if the string is omitted or C<undef>)
=item 2.
A string specifying a pattern to be matched as the opening tag.
If the pattern string is omitted (or C<undef>) then a pattern
that matches any standard XML tag is used.
=item 3.
A string specifying a pattern to be matched at the closing tag.
If the pattern string is omitted (or C<undef>) then the closing
tag is constructed by inserting a C</> after any leading bracket
characters in the actual opening tag that was matched (I<not> the pattern
that matched the tag). For example, if the opening tag pattern
is specified as C<'{{\w+}}'> and actually matched the opening tag
C<"{{DATA}}">, then the constructed closing tag would be C<"{{/DATA}}">.
=item 4.
A string specifying a pattern to be matched as a prefix (which is to be
skipped). If omitted, optional whitespace is skipped.
=item 5.
A hash reference containing various parsing options (see below)
=back
The various options that can be specified are:
=over 4
=item C<reject =E<gt> $listref>
The list reference contains one or more strings specifying patterns
that must I<not> appear within the tagged text.
For example, to extract
an HTML link (which should not contain nested links) use:
extract_tagged($text, '<A>', '</A>', undef, {reject => ['<A>']} );
=item C<ignore =E<gt> $listref>
The list reference contains one or more strings specifying patterns
that are I<not> be be treated as nested tags within the tagged text
(even if they would match the start tag pattern).
For example, to extract an arbitrary XML tag, but ignore "empty" elements:
extract_tagged($text, undef, undef, undef, {ignore => ['<[^>]*/>']} );
(also see L<"gen_delimited_pat"> below).
=item C<fail =E<gt> $str>
The C<fail> option indicates the action to be taken if a matching end
tag is not encountered (i.e. before the end of the string or some
C<reject> pattern matches). By default, a failure to match a closing
tag causes C<extract_tagged> to immediately fail.
However, if the string value associated with <reject> is "MAX", then
C<extract_tagged> returns the complete text up to the point of failure.
If the string is "PARA", C<extract_tagged> returns only the first paragraph
after the tag (up to the first line that is either empty or contains
only whitespace characters).
If the string is "", the the default behaviour (i.e. failure) is reinstated.
For example, suppose the start tag "/para" introduces a paragraph, which then
continues until the next "/endpara" tag or until another "/para" tag is
encountered:
$text = "/para line 1\n\nline 3\n/para line 4";
extract_tagged($text, '/para', '/endpara', undef,
{reject => '/para', fail => MAX );
# EXTRACTED: "/para line 1\n\nline 3\n"
Suppose instead, that if no matching "/endpara" tag is found, the "/para"
tag refers only to the immediately following paragraph:
$text = "/para line 1\n\nline 3\n/para line 4";
extract_tagged($text, '/para', '/endpara', undef,
{reject => '/para', fail => MAX );
# EXTRACTED: "/para line 1\n"
Note that the specified C<fail> behaviour applies to nested tags as well.
=back
On success in a list context, an array of 6 elements is returned. The elements are:
=over 4
=item [0]
the extracted tagged substring (including the outermost tags),
=item [1]
the remainder of the input text,
=item [2]
the prefix substring (if any),
=item [3]
the opening tag
=item [4]
the text between the opening and closing tags
=item [5]
the closing tag (or "" if no closing tag was found)
=back
On failure, all of these values (except the remaining text) are C<undef>.
In a scalar context, C<extract_tagged> returns just the complete
substring that matched a tagged text (including the start and end
tags). C<undef> is returned on failure. In addition, the original input
text has the returned substring (and any prefix) removed from it.
In a void context, the input text just has the matched substring (and
any specified prefix) removed.
=head2 C<gen_extract_tagged>
(Note: This subroutine is only available under Perl5.005)
C<gen_extract_tagged> generates a new anonymous subroutine which
extracts text between (balanced) specified tags. In other words,
it generates a function identical in function to C<extract_tagged>.
The difference between C<extract_tagged> and the anonymous
subroutines generated by
C<gen_extract_tagged>, is that those generated subroutines:
=over 4
=item *
do not have to reparse tag specification or parsing options every time
they are called (whereas C<extract_tagged> has to effectively rebuild
its tag parser on every call);
=item *
make use of the new qr// construct to pre-compile the regexes they use
(whereas C<extract_tagged> uses standard string variable interpolation
to create tag-matching patterns).
=back
The subroutine takes up to four optional arguments (the same set as
C<extract_tagged> except for the string to be processed). It returns
a reference to a subroutine which in turn takes a single argument (the text to
be extracted from).
In other words, the implementation of C<extract_tagged> is exactly
equivalent to:
sub extract_tagged
{
my $text = shift;
$extractor = gen_extract_tagged(@_);
return $extractor->($text);
}
(although C<extract_tagged> is not currently implemented that way, in order
to preserve pre-5.005 compatibility).
Using C<gen_extract_tagged> to create extraction functions for specific tags
is a good idea if those functions are going to be called more than once, since
their performance is typically twice as good as the more general-purpose
C<extract_tagged>.
=head2 C<extract_quotelike>
C<extract_quotelike> attempts to recognize, extract, and segment any
one of the various Perl quotes and quotelike operators (see
L<perlop(3)>) Nested backslashed delimiters, embedded balanced bracket
delimiters (for the quotelike operators), and trailing modifiers are
all caught. For example, in:
extract_quotelike 'q # an octothorpe: \# (not the end of the q!) #'
extract_quotelike ' "You said, \"Use sed\"." '
extract_quotelike ' s{([A-Z]{1,8}\.[A-Z]{3})} /\L$1\E/; '
extract_quotelike ' tr/\\\/\\\\/\\\//ds; '
the full Perl quotelike operations are all extracted correctly.
Note too that, when using the /x modifier on a regex, any comment
containing the current pattern delimiter will cause the regex to be
immediately terminated. In other words:
'm /
(?i) # CASE INSENSITIVE
[a-z_] # LEADING ALPHABETIC/UNDERSCORE
[a-z0-9]* # FOLLOWED BY ANY NUMBER OF ALPHANUMERICS
/x'
will be extracted as if it were:
'm /
(?i) # CASE INSENSITIVE
[a-z_] # LEADING ALPHABETIC/'
This behaviour is identical to that of the actual compiler.
C<extract_quotelike> takes two arguments: the text to be processed and
a prefix to be matched at the very beginning of the text. If no prefix
is specified, optional whitespace is the default. If no text is given,
C<$_> is used.
In a list context, an array of 11 elements is returned. The elements are:
=over 4
=item [0]
the extracted quotelike substring (including trailing modifiers),
=item [1]
the remainder of the input text,
=item [2]
the prefix substring (if any),
=item [3]
the name of the quotelike operator (if any),
=item [4]
the left delimiter of the first block of the operation,
=item [5]
the text of the first block of the operation
(that is, the contents of
a quote, the regex of a match or substitution or the target list of a
translation),
=item [6]
the right delimiter of the first block of the operation,
=item [7]
the left delimiter of the second block of the operation
(that is, if it is a C<s>, C<tr>, or C<y>),
=item [8]
the text of the second block of the operation
(that is, the replacement of a substitution or the translation list
of a translation),
=item [9]
the right delimiter of the second block of the operation (if any),
=item [10]
the trailing modifiers on the operation (if any).
=back
For each of the fields marked "(if any)" the default value on success is
an empty string.
On failure, all of these values (except the remaining text) are C<undef>.
In a scalar context, C<extract_quotelike> returns just the complete substring
that matched a quotelike operation (or C<undef> on failure). In a scalar or
void context, the input text has the same substring (and any specified
prefix) removed.
Examples:
# Remove the first quotelike literal that appears in text
$quotelike = extract_quotelike($text,'.*?');
# Replace one or more leading whitespace-separated quotelike
# literals in $_ with "<QLL>"
do { $_ = join '<QLL>', (extract_quotelike)[2,1] } until $@;
# Isolate the search pattern in a quotelike operation from $text
($op,$pat) = (extract_quotelike $text)[3,5];
if ($op =~ /[ms]/)
{
print "search pattern: $pat\n";
}
else
{
print "$op is not a pattern matching operation\n";
}
=head2 C<extract_quotelike> and "here documents"
C<extract_quotelike> can successfully extract "here documents" from an input
string, but with an important caveat in list contexts.
Unlike other types of quote-like literals, a here document is rarely
a contiguous substring. For example, a typical piece of code using
here document might look like this:
<<'EOMSG' || die;
This is the message.
EOMSG
exit;
Given this as an input string in a scalar context, C<extract_quotelike>
would correctly return the string "<<'EOMSG'\nThis is the message.\nEOMSG",
leaving the string " || die;\nexit;" in the original variable. In other words,
the two separate pieces of the here document are successfully extracted and
concatenated.
In a list context, C<extract_quotelike> would return the list
=over 4
=item [0]
"<<'EOMSG'\nThis is the message.\nEOMSG\n" (i.e. the full extracted here document,
including fore and aft delimiters),
=item [1]
" || die;\nexit;" (i.e. the remainder of the input text, concatenated),
=item [2]
"" (i.e. the prefix substring -- trivial in this case),
=item [3]
"<<" (i.e. the "name" of the quotelike operator)
=item [4]
"'EOMSG'" (i.e. the left delimiter of the here document, including any quotes),
=item [5]
"This is the message.\n" (i.e. the text of the here document),
=item [6]
"EOMSG" (i.e. the right delimiter of the here document),
=item [7..10]
"" (a here document has no second left delimiter, second text, second right
delimiter, or trailing modifiers).
=back
However, the matching position of the input variable would be set to
"exit;" (i.e. I<after> the closing delimiter of the here document),
which would cause the earlier " || die;\nexit;" to be skipped in any
sequence of code fragment extractions.
To avoid this problem, when it encounters a here document whilst
extracting from a modifiable string, C<extract_quotelike> silently
rearranges the string to an equivalent piece of Perl:
<<'EOMSG'
This is the message.
EOMSG
|| die;
exit;
in which the here document I<is> contiguous. It still leaves the
matching position after the here document, but now the rest of the line
on which the here document starts is not skipped.
To prevent <extract_quotelike> from mucking about with the input in this way
(this is the only case where a list-context C<extract_quotelike> does so),
you can pass the input variable as an interpolated literal:
$quotelike = extract_quotelike("$var");
=head2 C<extract_codeblock>
C<extract_codeblock> attempts to recognize and extract a balanced
bracket delimited substring that may contain unbalanced brackets
inside Perl quotes or quotelike operations. That is, C<extract_codeblock>
is like a combination of C<"extract_bracketed"> and
C<"extract_quotelike">.
C<extract_codeblock> takes the same initial three parameters as C<extract_bracketed>:
a text to process, a set of delimiter brackets to look for, and a prefix to
match first. It also takes an optional fourth parameter, which allows the
outermost delimiter brackets to be specified separately (see below).
Omitting the first argument (input text) means process C<$_> instead.
Omitting the second argument (delimiter brackets) indicates that only C<'{'> is to be used.
Omitting the third argument (prefix argument) implies optional whitespace at the start.
Omitting the fourth argument (outermost delimiter brackets) indicates that the
value of the second argument is to be used for the outermost delimiters.
Once the prefix an dthe outermost opening delimiter bracket have been
recognized, code blocks are extracted by stepping through the input text and
trying the following alternatives in sequence:
=over 4
=item 1.
Try and match a closing delimiter bracket. If the bracket was the same
species as the last opening bracket, return the substring to that
point. If the bracket was mismatched, return an error.
=item 2.
Try to match a quote or quotelike operator. If found, call
C<extract_quotelike> to eat it. If C<extract_quotelike> fails, return
the error it returned. Otherwise go back to step 1.
=item 3.
Try to match an opening delimiter bracket. If found, call
C<extract_codeblock> recursively to eat the embedded block. If the
recursive call fails, return an error. Otherwise, go back to step 1.
=item 4.
Unconditionally match a bareword or any other single character, and
then go back to step 1.
=back
Examples:
# Find a while loop in the text
if ($text =~ s/.*?while\s*\{/{/)
{
$loop = "while " . extract_codeblock($text);
}
# Remove the first round-bracketed list (which may include
# round- or curly-bracketed code blocks or quotelike operators)
extract_codeblock $text, "(){}", '[^(]*';
The ability to specify a different outermost delimiter bracket is useful
in some circumstances. For example, in the Parse::RecDescent module,
parser actions which are to be performed only on a successful parse
are specified using a C<E<lt>defer:...E<gt>> directive. For example:
sentence: subject verb object
<defer: {$::theVerb = $item{verb}} >
Parse::RecDescent uses C<extract_codeblock($text, '{}E<lt>E<gt>')> to extract the code
within the C<E<lt>defer:...E<gt>> directive, but there's a problem.
A deferred action like this:
<defer: {if ($count>10) {$count--}} >
will be incorrectly parsed as:
<defer: {if ($count>
because the "less than" operator is interpreted as a closing delimiter.
But, by extracting the directive using
S<C<extract_codeblock($text, '{}', undef, 'E<lt>E<gt>')>>
the '>' character is only treated as a delimited at the outermost
level of the code block, so the directive is parsed correctly.
=head2 C<extract_multiple>
The C<extract_multiple> subroutine takes a string to be processed and a
list of extractors (subroutines or regular expressions) to apply to that string.
In an array context C<extract_multiple> returns an array of substrings
of the original string, as extracted by the specified extractors.
In a scalar context, C<extract_multiple> returns the first
substring successfully extracted from the original string. In both
scalar and void contexts the original string has the first successfully
extracted substring removed from it. In all contexts
C<extract_multiple> starts at the current C<pos> of the string, and
sets that C<pos> appropriately after it matches.
Hence, the aim of of a call to C<extract_multiple> in a list context
is to split the processed string into as many non-overlapping fields as
possible, by repeatedly applying each of the specified extractors
to the remainder of the string. Thus C<extract_multiple> is
a generalized form of Perl's C<split> subroutine.
The subroutine takes up to four optional arguments:
=over 4
=item 1.
A string to be processed (C<$_> if the string is omitted or C<undef>)
=item 2.
A reference to a list of subroutine references and/or qr// objects and/or
literal strings and/or hash references, specifying the extractors
to be used to split the string. If this argument is omitted (or
C<undef>) the list:
[
sub { extract_variable($_[0], '') },
sub { extract_quotelike($_[0],'') },
sub { extract_codeblock($_[0],'{}','') },
]
is used.
=item 3.
An number specifying the maximum number of fields to return. If this
argument is omitted (or C<undef>), split continues as long as possible.
If the third argument is I<N>, then extraction continues until I<N> fields
have been successfully extracted, or until the string has been completely
processed.
Note that in scalar and void contexts the value of this argument is
automatically reset to 1 (under C<-w>, a warning is issued if the argument
has to be reset).
=item 4.
A value indicating whether unmatched substrings (see below) within the
text should be skipped or returned as fields. If the value is true,
such substrings are skipped. Otherwise, they are returned.
=back
The extraction process works by applying each extractor in
sequence to the text string.
If the extractor is a subroutine it is called in a list context and is
expected to return a list of a single element, namely the extracted
text. It may optionally also return two further arguments: a string
representing the text left after extraction (like $' for a pattern
match), and a string representing any prefix skipped before the
extraction (like $` in a pattern match). Note that this is designed
to facilitate the use of other Text::Balanced subroutines with
C<extract_multiple>. Note too that the value returned by an extractor
subroutine need not bear any relationship to the corresponding substring
of the original text (see examples below).
If the extractor is a precompiled regular expression or a string,
it is matched against the text in a scalar context with a leading
'\G' and the gc modifiers enabled. The extracted value is either
$1 if that variable is defined after the match, or else the
complete match (i.e. $&).
If the extractor is a hash reference, it must contain exactly one element.
The value of that element is one of the
above extractor types (subroutine reference, regular expression, or string).
The key of that element is the name of a class into which the successful
return value of the extractor will be blessed.
If an extractor returns a defined value, that value is immediately
treated as the next extracted field and pushed onto the list of fields.
If the extractor was specified in a hash reference, the field is also
blessed into the appropriate class,
If the extractor fails to match (in the case of a regex extractor), or returns an empty list or an undefined value (in the case of a subroutine extractor), it is
assumed to have failed to extract.
If none of the extractor subroutines succeeds, then one
character is extracted from the start of the text and the extraction
subroutines reapplied. Characters which are thus removed are accumulated and
eventually become the next field (unless the fourth argument is true, in which
case they are discarded).
For example, the following extracts substrings that are valid Perl variables:
@fields = extract_multiple($text,
[ sub { extract_variable($_[0]) } ],
undef, 1);
This example separates a text into fields which are quote delimited,
curly bracketed, and anything else. The delimited and bracketed
parts are also blessed to identify them (the "anything else" is unblessed):
@fields = extract_multiple($text,
[
{ Delim => sub { extract_delimited($_[0],q{'"}) } },
{ Brack => sub { extract_bracketed($_[0],'{}') } },
]);
This call extracts the next single substring that is a valid Perl quotelike
operator (and removes it from $text):
$quotelike = extract_multiple($text,
[
sub { extract_quotelike($_[0]) },
], undef, 1);
Finally, here is yet another way to do comma-separated value parsing:
@fields = extract_multiple($csv_text,
[
sub { extract_delimited($_[0],q{'"}) },
qr/([^,]+)(.*)/,
],
undef,1);
The list in the second argument means:
I<"Try and extract a ' or " delimited string, otherwise extract anything up to a comma...">.
The undef third argument means:
I<"...as many times as possible...">,
and the true value in the fourth argument means
I<"...discarding anything else that appears (i.e. the commas)">.
If you wanted the commas preserved as separate fields (i.e. like split
does if your split pattern has capturing parentheses), you would
just make the last parameter undefined (or remove it).
=head2 C<gen_delimited_pat>
The C<gen_delimited_pat> subroutine takes a single (string) argument and
> builds a Friedl-style optimized regex that matches a string delimited
by any one of the characters in the single argument. For example:
gen_delimited_pat(q{'"})
returns the regex:
(?:\"(?:\\\"|(?!\").)*\"|\'(?:\\\'|(?!\').)*\')
Note that the specified delimiters are automatically quotemeta'd.
A typical use of C<gen_delimited_pat> would be to build special purpose tags
for C<extract_tagged>. For example, to properly ignore "empty" XML elements
(which might contain quoted strings):
my $empty_tag = '<(' . gen_delimited_pat(q{'"}) . '|.)+/>';
extract_tagged($text, undef, undef, undef, {ignore => [$empty_tag]} );
C<gen_delimited_pat> may also be called with an optional second argument,
which specifies the "escape" character(s) to be used for each delimiter.
For example to match a Pascal-style string (where ' is the delimiter
and '' is a literal ' within the string):
gen_delimited_pat(q{'},q{'});
Different escape characters can be specified for different delimiters.
For example, to specify that '/' is the escape for single quotes
and '%' is the escape for double quotes:
gen_delimited_pat(q{'"},q{/%});
If more delimiters than escape chars are specified, the last escape char
is used for the remaining delimiters.
If no escape char is specified for a given specified delimiter, '\' is used.
=head2 C<delimited_pat>
Note that C<gen_delimited_pat> was previously called C<delimited_pat>.
That name may still be used, but is now deprecated.
=head1 DIAGNOSTICS
In a list context, all the functions return C<(undef,$original_text)>
on failure. In a scalar context, failure is indicated by returning C<undef>
(in this case the input text is not modified in any way).
In addition, on failure in I<any> context, the C<$@> variable is set.
Accessing C<$@-E<gt>{error}> returns one of the error diagnostics listed
below.
Accessing C<$@-E<gt>{pos}> returns the offset into the original string at
which the error was detected (although not necessarily where it occurred!)
Printing C<$@> directly produces the error message, with the offset appended.
On success, the C<$@> variable is guaranteed to be C<undef>.
The available diagnostics are:
=over 4
=item C<Did not find a suitable bracket: "%s">
The delimiter provided to C<extract_bracketed> was not one of
C<'()[]E<lt>E<gt>{}'>.
=item C<Did not find prefix: /%s/>
A non-optional prefix was specified but wasn't found at the start of the text.
=item C<Did not find opening bracket after prefix: "%s">
C<extract_bracketed> or C<extract_codeblock> was expecting a
particular kind of bracket at the start of the text, and didn't find it.
=item C<No quotelike operator found after prefix: "%s">
C<extract_quotelike> didn't find one of the quotelike operators C<q>,
C<qq>, C<qw>, C<qx>, C<s>, C<tr> or C<y> at the start of the substring
it was extracting.
=item C<Unmatched closing bracket: "%c">
C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> encountered
a closing bracket where none was expected.
=item C<Unmatched opening bracket(s): "%s">
C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> ran
out of characters in the text before closing one or more levels of nested
brackets.
=item C<Unmatched embedded quote (%s)>
C<extract_bracketed> attempted to match an embedded quoted substring, but
failed to find a closing quote to match it.
=item C<Did not find closing delimiter to match '%s'>
C<extract_quotelike> was unable to find a closing delimiter to match the
one that opened the quote-like operation.
=item C<Mismatched closing bracket: expected "%c" but found "%s">
C<extract_bracketed>, C<extract_quotelike> or C<extract_codeblock> found
a valid bracket delimiter, but it was the wrong species. This usually
indicates a nesting error, but may indicate incorrect quoting or escaping.
=item C<No block delimiter found after quotelike "%s">
C<extract_quotelike> or C<extract_codeblock> found one of the
quotelike operators C<q>, C<qq>, C<qw>, C<qx>, C<s>, C<tr> or C<y>
without a suitable block after it.
=item C<Did not find leading dereferencer>
C<extract_variable> was expecting one of '$', '@', or '%' at the start of
a variable, but didn't find any of them.
=item C<Bad identifier after dereferencer>
C<extract_variable> found a '$', '@', or '%' indicating a variable, but that
character was not followed by a legal Perl identifier.
=item C<Did not find expected opening bracket at %s>
C<extract_codeblock> failed to find any of the outermost opening brackets
that were specified.
=item C<Improperly nested codeblock at %s>
A nested code block was found that started with a delimiter that was specified
as being only to be used as an outermost bracket.
=item C<Missing second block for quotelike "%s">
C<extract_codeblock> or C<extract_quotelike> found one of the
quotelike operators C<s>, C<tr> or C<y> followed by only one block.
=item C<No match found for opening bracket>
C<extract_codeblock> failed to find a closing bracket to match the outermost
opening bracket.
=item C<Did not find opening tag: /%s/>
C<extract_tagged> did not find a suitable opening tag (after any specified
prefix was removed).
=item C<Unable to construct closing tag to match: /%s/>
C<extract_tagged> matched the specified opening tag and tried to
modify the matched text to produce a matching closing tag (because
none was specified). It failed to generate the closing tag, almost
certainly because the opening tag did not start with a
bracket of some kind.
=item C<Found invalid nested tag: %s>
C<extract_tagged> found a nested tag that appeared in the "reject" list
(and the failure mode was not "MAX" or "PARA").
=item C<Found unbalanced nested tag: %s>
C<extract_tagged> found a nested opening tag that was not matched by a
corresponding nested closing tag (and the failure mode was not "MAX" or "PARA").
=item C<Did not find closing tag>
C<extract_tagged> reached the end of the text without finding a closing tag
to match the original opening tag (and the failure mode was not
"MAX" or "PARA").
=back
=head1 AUTHOR
Damian Conway (damian@conway.org)
=head1 BUGS AND IRRITATIONS
There are undoubtedly serious bugs lurking somewhere in this code, if
only because parts of it give the impression of understanding a great deal
more about Perl than they really do.
Bug reports and other feedback are most welcome.
=head1 COPYRIGHT
Copyright 1997 - 2001 Damian Conway. All Rights Reserved.
Some (minor) parts copyright 2009 Adam Kennedy.
This module is free software. It may be used, redistributed
and/or modified under the same terms as Perl itself.
=cut
| 29.645048 | 161 | 0.64918 |
73f0d81b5a9f3b95bc7b0ac24ad4ac322c43db8c | 561 | pm | Perl | lib/VMOMI/DistributedVirtualSwitchHostMemberPnicSpec.pm | stumpr/p5-vmomi | e2571d72a1f552ddd0258ad289ec229d8d12a147 | [
"Apache-2.0"
]
| 1 | 2017-06-22T21:26:24.000Z | 2017-06-22T21:26:24.000Z | lib/VMOMI/DistributedVirtualSwitchHostMemberPnicSpec.pm | restump/p5-vmomi | e2571d72a1f552ddd0258ad289ec229d8d12a147 | [
"Apache-2.0"
]
| null | null | null | lib/VMOMI/DistributedVirtualSwitchHostMemberPnicSpec.pm | restump/p5-vmomi | e2571d72a1f552ddd0258ad289ec229d8d12a147 | [
"Apache-2.0"
]
| 1 | 2016-07-19T19:56:09.000Z | 2016-07-19T19:56:09.000Z | package VMOMI::DistributedVirtualSwitchHostMemberPnicSpec;
use parent 'VMOMI::DynamicData';
use strict;
use warnings;
our @class_ancestors = (
'DynamicData',
);
our @class_members = (
['pnicDevice', undef, 0, ],
['uplinkPortKey', undef, 0, 1],
['uplinkPortgroupKey', undef, 0, 1],
['connectionCookie', undef, 0, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| 19.344828 | 59 | 0.673797 |
ed558829c2318817d05ae702b57dcffb5d7ff2a7 | 3,880 | pm | Perl | perl/vendor/lib/Crypt/Mac/HMAC.pm | ifleeyo180/VspriteMoodleWebsite | 38baa924829c83808d2c87d44740ff365927a646 | [
"Apache-2.0"
]
| 2 | 2021-11-19T22:37:28.000Z | 2021-11-22T18:04:55.000Z | perl/vendor/lib/Crypt/Mac/HMAC.pm | ifleeyo180/VspriteMoodleWebsite | 38baa924829c83808d2c87d44740ff365927a646 | [
"Apache-2.0"
]
| 6 | 2021-11-18T00:39:48.000Z | 2021-11-20T00:31:40.000Z | perl/vendor/lib/Crypt/Mac/HMAC.pm | ifleeyo180/VspriteMoodleWebsite | 38baa924829c83808d2c87d44740ff365927a646 | [
"Apache-2.0"
]
| null | null | null | package Crypt::Mac::HMAC;
### BEWARE - GENERATED FILE, DO NOT EDIT MANUALLY!
use strict;
use warnings;
our $VERSION = '0.069';
use base qw(Crypt::Mac Exporter);
our %EXPORT_TAGS = ( all => [qw( hmac hmac_hex hmac_b64 hmac_b64u )] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw();
1;
=pod
=head1 NAME
Crypt::Mac::HMAC - Message authentication code HMAC
=head1 SYNOPSIS
### Functional interface:
use Crypt::Mac::HMAC qw( hmac hmac_hex );
# calculate MAC from string/buffer
$hmac_raw = hmac('SHA256', $key, 'data buffer');
$hmac_hex = hmac_hex('SHA256', $key, 'data buffer');
$hmac_b64 = hmac_b64('SHA256', $key, 'data buffer');
$hmac_b64u = hmac_b64u('SHA256', $key, 'data buffer');
### OO interface:
use Crypt::Mac::HMAC;
$d = Crypt::Mac::HMAC->new('SHA256', $key);
$d->add('any data');
$d->addfile('filename.dat');
$d->addfile(*FILEHANDLE);
$result_raw = $d->mac; # raw bytes
$result_hex = $d->hexmac; # hexadecimal form
$result_b64 = $d->b64mac; # Base64 form
$result_b64u = $d->b64umac; # Base64 URL Safe form
=head1 DESCRIPTION
Provides an interface to the HMAC message authentication code (MAC) algorithm.
=head1 EXPORT
Nothing is exported by default.
You can export selected functions:
use Crypt::Mac::HMAC qw(hmac hmac_hex );
Or all of them at once:
use Crypt::Mac::HMAC ':all';
=head1 FUNCTIONS
=head2 hmac
Logically joins all arguments into a single string, and returns its HMAC message authentication code encoded as a binary string.
$hmac_raw = hmac($hash_name, $key, 'data buffer');
#or
$hmac_raw = hmac($hash_name, $key, 'any data', 'more data', 'even more data');
# $hash_name ... any <NAME> for which there exists Crypt::Digest::<NAME>
# $key ......... the key (octets/bytes)
=head2 hmac_hex
Logically joins all arguments into a single string, and returns its HMAC message authentication code encoded as a hexadecimal string.
$hmac_hex = hmac_hex($hash_name, $key, 'data buffer');
#or
$hmac_hex = hmac_hex($hash_name, $key, 'any data', 'more data', 'even more data');
# $hash_name ... any <NAME> for which there exists Crypt::Digest::<NAME>
# $key ......... the key (octets/bytes, not hex!)
=head2 hmac_b64
Logically joins all arguments into a single string, and returns its HMAC message authentication code encoded as a Base64 string.
$hmac_b64 = hmac_b64($hash_name, $key, 'data buffer');
#or
$hmac_b64 = hmac_b64($hash_name, $key, 'any data', 'more data', 'even more data');
# $hash_name ... any <NAME> for which there exists Crypt::Digest::<NAME>
# $key ......... the key (octets/bytes, not Base64!)
=head2 hmac_b64u
Logically joins all arguments into a single string, and returns its HMAC message authentication code encoded as a Base64 URL Safe string (see RFC 4648 section 5).
$hmac_b64url = hmac_b64u($hash_name, $key, 'data buffer');
#or
$hmac_b64url = hmac_b64u($hash_name, $key, 'any data', 'more data', 'even more data');
# $hash_name ... any <NAME> for which there exists Crypt::Digest::<NAME>
# $key ......... the key (octets/bytes, not Base64url!)
=head1 METHODS
=head2 new
$d = Crypt::Mac::HMAC->new($hash_name, $key);
# $hash_name ... any <NAME> for which there exists Crypt::Digest::<NAME>
# $key ......... the key (octets/bytes)
=head2 clone
$d->clone();
=head2 reset
$d->reset();
=head2 add
$d->add('any data');
#or
$d->add('any data', 'more data', 'even more data');
=head2 addfile
$d->addfile('filename.dat');
#or
$d->addfile(*FILEHANDLE);
=head2 mac
$result_raw = $d->mac();
=head2 hexmac
$result_hex = $d->hexmac();
=head2 b64mac
$result_b64 = $d->b64mac();
=head2 b64umac
$result_b64url = $d->b64umac();
=head1 SEE ALSO
=over
=item * L<CryptX|CryptX>
=item * L<https://en.wikipedia.org/wiki/Hmac>
=item * L<https://tools.ietf.org/html/rfc2104>
=back
=cut
| 23.515152 | 162 | 0.665979 |
73ee757fbb82fc21055b816b558fe71f72b94f62 | 2,164 | pm | Perl | modules/Bio/EnsEMBL/EGPipeline/LoadGFF3/ConstructFilenames.pm | dbolser-ebi/copy-of-eg-pipelines | ff2bd80571fd5584e1338c96f77f6489e761a44e | [
"Apache-2.0"
]
| null | null | null | modules/Bio/EnsEMBL/EGPipeline/LoadGFF3/ConstructFilenames.pm | dbolser-ebi/copy-of-eg-pipelines | ff2bd80571fd5584e1338c96f77f6489e761a44e | [
"Apache-2.0"
]
| null | null | null | modules/Bio/EnsEMBL/EGPipeline/LoadGFF3/ConstructFilenames.pm | dbolser-ebi/copy-of-eg-pipelines | ff2bd80571fd5584e1338c96f77f6489e761a44e | [
"Apache-2.0"
]
| null | null | null | =head1 LICENSE
Copyright [1999-2014] EMBL-European Bioinformatics Institute
and Wellcome Trust Sanger 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
=pod
=head1 NAME
Bio::EnsEMBL::EGPipeline::LoadGFF3::ConstructFilenames
=head1 Author
James Allen
=cut
package Bio::EnsEMBL::EGPipeline::LoadGFF3::ConstructFilenames;
use strict;
use warnings;
use base ('Bio::EnsEMBL::EGPipeline::Common::RunnableDB::Base');
use File::Spec::Functions qw(catdir);
sub write_output {
my ($self) = @_;
my $species = $self->param_required('species');
my $source_dir = $self->param_required('source_dir');
my $gff3_filename = $self->param_required('gff3_filename');
my $gff3_tidy_filename = $self->param_required('gff3_tidy_filename');
my $fasta_filename = $self->param('fasta_filename');
my $genbank_filename = $self->param('genbank_filename');
my $protein_fasta_filename = $self->param('protein_fasta_filename');
my $output_ids = {
gff3_file => catdir($source_dir, $species, $gff3_filename),
gff3_tidy_file => catdir($source_dir, $species, $gff3_tidy_filename),
};
if (defined $fasta_filename) {
$$output_ids{fasta_file} = catdir($source_dir, $species, $fasta_filename);
} else {
$$output_ids{fasta_file} = catdir($source_dir, $species, "genome.fa");
}
if (defined $genbank_filename) {
$$output_ids{genbank_file} = catdir($source_dir, $species, $genbank_filename);
}
if (defined $protein_fasta_filename) {
$$output_ids{protein_fasta_file} = catdir($source_dir, $species, $protein_fasta_filename);
}
$self->dataflow_output_id($output_ids, 1);
}
1;
| 28.853333 | 94 | 0.716266 |
ed40883246d1b9b1132280ef5667b5747c4532f8 | 6,557 | pm | Perl | lib/Tephra/Hel/HelSearch.pm | sestaton/tephra | 606d45266211fc28e8619a68ce483e482eea48fc | [
"MIT"
]
| 24 | 2016-01-12T21:03:11.000Z | 2021-05-27T01:24:51.000Z | lib/Tephra/Hel/HelSearch.pm | sestaton/tephra | 606d45266211fc28e8619a68ce483e482eea48fc | [
"MIT"
]
| 50 | 2016-01-06T02:51:59.000Z | 2022-02-04T23:07:38.000Z | lib/Tephra/Hel/HelSearch.pm | sestaton/tephra | 606d45266211fc28e8619a68ce483e482eea48fc | [
"MIT"
]
| 3 | 2017-11-10T09:19:28.000Z | 2019-11-01T14:47:48.000Z | package Tephra::Hel::HelSearch;
use 5.014;
use Moose;
use File::Spec;
use File::Find;
use File::Basename;
use File::Temp qw(tempfile);
use IPC::System::Simple qw(system EXIT_ANY);
use Log::Any qw($log);
use Cwd qw(abs_path);
use Path::Class::File;
use Bio::DB::HTS::Kseq;
use Sort::Naturally;
use Try::Tiny;
use namespace::autoclean;
#use Data::Dump::Color;
with 'Tephra::Role::Run::HelitronScanner',
'Tephra::Role::Util';
=head1 NAME
Tephra::Hel::HelSearch - Find Helitrons in a reference genome
=head1 VERSION
Version 0.13.2
=cut
our $VERSION = '0.13.2';
$VERSION = eval $VERSION;
sub find_helitrons {
my $self = shift;
my $genome = $self->genome->absolute->resolve;
my $jar = $self->helitronscanner;
my (%scanh_cmd, %scant_cmd, %pair_cmd, %draw_cmd);
my ($name, $path, $suffix) = fileparse($genome, qr/\.[^.]*/);
if ($name =~ /(\.fa.*)/) {
$name =~ s/$1//;
}
my $g_headlcvs = File::Spec->catfile($path, $name.'_hscan_head.lcvs');
my $g_taillcvs = File::Spec->catfile($path, $name.'_hscan_tail.lcvs');
my $g_paired = File::Spec->catfile($path, $name.'_hscan_paired.txt');
my $g_helname = File::Spec->catfile($path, $name.'_tephra_hscan_helitrons');
my $full_hels = $g_helname.'.hel.fa';
my $exte_hels = $g_helname.'.ext.hel.fa';
my $flan_hels = $g_helname.'.flanking.fa';
#my $jar = File::Spec->catfile($hscan_dir, "HelitronScanner.jar");
my $parent = $jar->parent->parent; # unfortunately, the dist does not unpack in a separate dir
my $lcvs = File::Spec->catfile($parent, 'TrainingSet', 'head.lcvs');
my $rcvs = File::Spec->catfile($parent, 'TrainingSet', 'tail.lcvs');
my @scanh_opts = qw(-g -lf -o -tl -buffer_size);
my @scanh_args = ($genome, $lcvs, $g_headlcvs, '10', '1000000');
@scanh_cmd{@scanh_opts} = @scanh_args;
my @scant_opts = qw(-g -lf -o -tl -buffer_size);
my @scant_args = ($genome, $rcvs, $g_taillcvs, '10', '1000000');
@scant_cmd{@scant_opts} = @scant_args;
my @pair_opts = qw(-hs -ts -o);
my @pair_args = ($g_headlcvs, $g_taillcvs, $g_paired);
@pair_cmd{@pair_opts} = @pair_args;
my @draw_opts = qw(-p -g -o -ext5 -ext3);
my @draw_args = ($g_paired, $genome, $g_helname, '100', '100');
@draw_cmd{@draw_opts} = @draw_args;
$self->run_hscan_headtail(\%scanh_cmd, $jar, 'scanHead');
$self->run_hscan_headtail(\%scant_cmd, $jar, 'scanTail');
$self->run_hscan_pair(\%pair_cmd, $jar);
$self->run_hscan_draw(\%draw_cmd, $jar);
return { full_helitrons => $full_hels,
extended_seqs => $exte_hels,
flanking_seqs => $flan_hels,
head => $g_headlcvs,
tail => $g_taillcvs,
paired => $g_paired
};
}
sub make_hscan_outfiles {
my $self = shift;
my ($helitrons) = @_;
#my $gff = $self->gff;
my $genome = $self->genome->absolute->resolve;
my ($full, $exte, $flank, $head, $tail, $paired) =
@{$helitrons}{qw(full_helitrons extended_seqs flanking_seqs head tail paired)};
my ($gname, $gpath, $gsuffix) = fileparse($genome, qr/\.[^.]*/);
my $tmpfname = $gname.'_tephra_helsearch_fas_XXXX';
my $tmpgname = $gname.'_tephra_helsearch_gff_XXXX';
my ($outf, $ffilename) = tempfile( TEMPLATE => $tmpfname, DIR => $gpath, UNLINK => 0, SUFFIX => '.fasta' );
my ($outg, $gfilename) = tempfile( TEMPLATE => $tmpgname, DIR => $gpath, UNLINK => 0, SUFFIX => '.gff3' );
my %refs;
my $gkseq = Bio::DB::HTS::Kseq->new($genome);
my $giter = $gkseq->iterator;
while (my $gseqs = $giter->next_seq) {
my $name = $gseqs->name;
my $seq = $gseqs->seq;
$refs{$name} = length($seq);
}
my $header = '##gff-version 3';
say $outg $header;
for my $ref (nsort keys %refs) {
say $outg join q{ }, '##sequence-region', $ref, '1', $refs{$ref};
}
my %strand = ( forward => '+', reverse => '-' );
my ($name, $seq, %hel, %sfmap);
my $helct = 0;
open my $hin, '<', $full or die "\n[ERROR]: Could not open file: $full\n";
while (($name, $seq) = $self->read_seq(\*$hin)) {
$helct++;
my ($ref, $start, $stop) = ($name =~ /(^\S+)_\#SUB_(\d+)-(\d+)/);
my ($str) = ($name =~ /\[(forward|reverse)\]/);
my $strand = $strand{$str};
#my $id = "DHH_helitron$helct";
my $id = "helitron$helct";
# seqid source type start end score strand phase attribs
my $gff_str;
if ($start > $stop && $strand eq '-') {
$gff_str = join "||", $ref, 'HelitronScanner', 'helitron', $stop, $start, '.',
$strand, '.', "ID=$id;Ontology_term=SO:0000544";
$id .= "_$ref"."_$stop"."_$start"; #."_$strand";
say $outf join "\n", ">".$id, $seq;
}
else {
$gff_str = join "||", $ref, 'HelitronScanner', 'helitron', $start, $stop, '.',
$strand, '.', "ID=$id;Ontology_term=SO:0000544";
$id .= "_$ref"."_$start"."_$stop"; #."_$strand";
say $outf join "\n", ">".$id, $seq;
}
push @{$hel{$ref}}, $gff_str;
$sfmap{$id} = 'DHH';
}
close $hin;
close $outf;
#dd \%hel;
for my $ref (nsort keys %hel) {
for my $feature (@{$hel{$ref}}) {
my @feats = split /\|\|/, $feature;
say $outg join "\t", @feats;
}
}
close $outg;
unlink $full, $exte, $flank, $head, $tail, $paired; #TODO: optionally keep intermediate files
return (\%sfmap,
{ fasta => $ffilename, gff => $gfilename });
}
sub read_seq {
my $self = shift;
my ($fh) = @_;
local $/ = "\n>";
return unless my $entry = $fh->getline;
chomp $entry;
my ($id, $seq) = split /\n/, $entry, 2;
defined $id && $id =~ s/>//g;
defined $seq && $seq =~ s/>//g;
$seq =~ s/\s+|\n//g;
$seq =~ s/.{60}\K/\n/g;
return ($id, $seq);
}
=head1 AUTHOR
S. Evan Staton, C<< <evan at evanstaton.com> >>
=head1 BUGS
Please report any bugs or feature requests through the project site at
L<https://github.com/sestaton/tephra/issues>. I will be notified,
and there will be a record of the issue. Alternatively, I can also be
reached at the email address listed above to resolve any questions.
=head1 SUPPORT
You can find documentation for this module with the perldoc command.
perldoc Tephra::Hel::HelSearch
=head1 LICENSE AND COPYRIGHT
Copyright (C) 2015- S. Evan Staton
This program is distributed under the MIT (X11) License, which should be distributed with the package.
If not, it can be found here: L<http://www.opensource.org/licenses/mit-license.php>
=cut
__PACKAGE__->meta->make_immutable;
1;
| 30.21659 | 111 | 0.591582 |
ed5dacd22a08d87a2b017e711281a13973ad5443 | 4,855 | pm | Perl | lib/RokuUI.pm | eouthwaite/perl-RokuUI | ba3614af43d7b33ea716f35aa59ef1edc4d366cc | [
"Unlicense"
]
| 1 | 2015-06-19T17:49:31.000Z | 2015-06-19T17:49:31.000Z | lib/RokuUI.pm | eouthwaite/perl-RokuUI | ba3614af43d7b33ea716f35aa59ef1edc4d366cc | [
"Unlicense"
]
| null | null | null | lib/RokuUI.pm | eouthwaite/perl-RokuUI | ba3614af43d7b33ea716f35aa59ef1edc4d366cc | [
"Unlicense"
]
| null | null | null | # RokuUI.pm version 0.1
#
# Copyright Michael Polymenakos 2007 mpoly@panix.com
#
# Released under the GPL. http://www.gnu.org/licenses/gpl.txt
#
use strict;
use Net::Telnet;
package RokuUI;
sub RokuDisplay {
sub new {
my $class = shift;
my $self = {@_};
bless ($self, $class);
return $self;
}
sub DESTROY {
my $self = shift;
if (defined($self->{connection})) {
$self->close()
}
}
sub open() {
my $self = shift;
$self->{port} = 4444 if !$self->{port};
$self->{connection} = Net::Telnet->new(
Port => $self->{port},
Prompt => '/SoundBridge> $/',
Timeout => 15,
Errmode => 'return'
);
if ($self->{connection}->open($self->{host})) {
return 1;
} else {
return 0;
}
}
sub close() {
my $self = shift;
if(defined($self->{connection})) {
$self->{connection}->cmd("sketch -c clear");
$self->{connection}->cmd("sketch -c exit");
$self->{connection}->cmd("irman off");
$self->{connection}->cmd("exit");
$self->{connection}->close();
}
}
sub msg() {
#
# text - default none - can be ommited to just set font and encoding
# x,y location - default 0,0
# font -
# encoding - default is latin1
# duration - in seconds, default 5. 0 means exit and leave text displayed
# mode - default 'text'. Any abbreviation of "marquee" results in a marquee
# keygrab - determines what happens when a user hits a key
# keygrab=0 - (default) the routine is interrupted, and the keypress is passed on to the roku
# keygrab=1 - the routine is interrupted, and the keypress is returned to the caller
# keygrab=2 - the routine is not interrupted, and the keypress is discarded
# clear - 0/1 force the display to clear first (default 0)
#
my $self = shift;
return 0 if !($self->{connection});
my %args = @_;
my $x = $args{'x'} || 0;
my $y = $args{'y'} || 0;
my $text = $args{'text'} || "";
my $font = $args{'font'} || $self->{'font'};
my $encoding = $args{'encoding'} || $self->{'encoding'};
my $keygrab = $args{'keygrab'};
my $clear = $args{'clear'} || 0;
my $duration = $args{'duration'};
if ($keygrab eq '') { # 0 is a valid value
$keygrab = 1;
}
if ($duration eq '') { # 0 is a valid value
$duration = $self->{'duration'} || 5 ;
}
my $marquee = $args{'mode'} =~ /^m(a(r(q(u(ee?)?)?)?)?)?$/i ? 1 : 0;
if ($encoding) {
$self->{connection}->cmd("sketch -c encoding $encoding");
}
if ($font) {
$self->{connection}->cmd("sketch -c font $font");
}
return 1 if !$text;
# preemptive strike - apparently text after marquee is appended to the marquee
if ($self->{marquee} && (!$marquee)) {
$self->{marquee} = 0;
$self->{connection}->cmd("sketch -c marquee -stop");
$self->{connection}->cmd("sketch -c clear");
} elsif ($clear) {
$self->{connection}->cmd("sketch -c clear");
}
#Escape quotes
$text =~ s/"/\\"/;
if ($marquee) {
$self->{marquee} = 1;
$self->{connection}->cmd("sketch -c marquee -start \"$text\"");
} else {
$self->{connection}->cmd("sketch -c text $x $y \"$text\"");
}
if ($duration) {
if ($keygrab == 2) {
sleep($duration);
#$self->{connection}->cmd("sketch -c exit");
return "TIMEOUT"; # for consistency...
}
$self->{connection}->cmd("irman intercept");
my ($p, $m) = $self->{connection}->waitfor(Match => '/irman: .*/',
Timeout => $duration);
$self->{connection}->cmd("irman off");
if ($m) {
$m =~ s/^irman: //;
if (!$keygrab) {
$self->{connection}->cmd("sketch -c exit");
$self->{connection}->cmd("irman dispatch $m");
}
return $m;
} else {
return "TIMEOUT";
}
} else {
return 1;
}
}
sub ison() {
my $self = shift;
return 0 if !($self->{connection});
my @ps = $self->{connection}->cmd("ps");
for my $ps (@ps) {
return 0 if $ps =~ / StandbyApp\n/;
}
return 1;
}
sub cmd() {
my $self = shift;
return 0 if !($self->{connection});
return $self->{connection}->cmd(shift);
}
sub clear() {
my $self = shift;
return 0 if !($self->{connection});
if ($self->{inmarquis}) {
$self->{inmarquis} = 0;
$self->{connection}->cmd("sketch -c marquee -stop");
}
$self->{connection}->cmd("sketch -c clear");
return 1
}
}
;1;
| 24.897436 | 101 | 0.497013 |
ed74a8c5316e55368db781df97ce5fbf17a20fb1 | 644 | pm | Perl | lib/Moose/Meta/Method/Accessor/Native/Array/push.pm | RsrchBoy/moose | 6bdea4fe2cf00478e26c3949994825ed66964da0 | [
"Artistic-1.0"
]
| null | null | null | lib/Moose/Meta/Method/Accessor/Native/Array/push.pm | RsrchBoy/moose | 6bdea4fe2cf00478e26c3949994825ed66964da0 | [
"Artistic-1.0"
]
| null | null | null | lib/Moose/Meta/Method/Accessor/Native/Array/push.pm | RsrchBoy/moose | 6bdea4fe2cf00478e26c3949994825ed66964da0 | [
"Artistic-1.0"
]
| null | null | null | package Moose::Meta::Method::Accessor::Native::Array::push;
our $VERSION = '2.2007';
use strict;
use warnings;
use Moose::Role;
with 'Moose::Meta::Method::Accessor::Native::Array::Writer';
sub _adds_members { 1 }
sub _potential_value {
my $self = shift;
my ($slot_access) = @_;
return '[ @{ (' . $slot_access . ') }, @_ ]';
}
sub _inline_optimized_set_new_value {
my $self = shift;
my ($inv, $new, $slot_access) = @_;
return 'push @{ (' . $slot_access . ') }, @_;';
}
sub _return_value {
my $self = shift;
my ($slot_access) = @_;
return 'scalar @{ (' . $slot_access . ') }';
}
no Moose::Role;
1;
| 17.405405 | 60 | 0.586957 |
ed81d0c1c7308924c2b7e1f6c54f8595943af224 | 1,649 | pl | Perl | samples/grapher-no-x.pl | a-little-srdjan/yagat | 63d8536dd0cddc8d5203f20069e4e11e38082ba9 | [
"MIT"
]
| 7 | 2016-11-28T18:15:03.000Z | 2018-07-20T16:53:00.000Z | samples/grapher-no-x.pl | a-little-srdjan/yagat | 63d8536dd0cddc8d5203f20069e4e11e38082ba9 | [
"MIT"
]
| null | null | null | samples/grapher-no-x.pl | a-little-srdjan/yagat | 63d8536dd0cddc8d5203f20069e4e11e38082ba9 | [
"MIT"
]
| 1 | 2019-04-11T00:54:48.000Z | 2019-04-11T00:54:48.000Z | :- discontiguous dir/2.
:- discontiguous direct_nested/2.
:- discontiguous pkg/1.
:- discontiguous imports/2.
nested(X, Y) :- direct_nested(X, Y), dir(X, _), dir(Y, _).
nested(X, Y) :- direct_nested(Z, Y), nested(X, Z).
pkg_dir(X) :- dir(X), pkg(X).
dependency(X, Y) :- imports(X, Y), pkg(X), pkg(Y).
dependency(X, Y) :- imports(Z, Y), dependency(X, Z).
p_label(M, D, Y) :- mark(M, Y), dir(Y, D).
p_label(M, D, Y) :- mark(M, Z), nested(Z, Y), dir(Z, D).
d_label(M, Y) :- p_label(M, D, Y), p_label(M2, D2, Y), M \== M2, D2 > D.
label(M, Y) :- p_label(M, _, Y), \+ d_label(M, Y).
violation(X, Y) :- dependency(X, Y), label(M, X), label(M2, Y), M \== M2, M < M2.
pkg("github.com/a-little-srdjan/grapher/printers").
imports("github.com/a-little-srdjan/grapher/printers","github.com/a-little-srdjan/grapher/pkg_graph").
dir("github.com",0).
dir("github.com/a-little-srdjan",1).
direct_nested("github.com","github.com/a-little-srdjan").
dir("github.com/a-little-srdjan/grapher",2).
direct_nested("github.com/a-little-srdjan","github.com/a-little-srdjan/grapher").
dir("github.com/a-little-srdjan/grapher/printers",3).
direct_nested("github.com/a-little-srdjan/grapher","github.com/a-little-srdjan/grapher/printers").
pkg("github.com/a-little-srdjan/grapher").
imports("github.com/a-little-srdjan/grapher","github.com/a-little-srdjan/grapher/pkg_graph").
imports("github.com/a-little-srdjan/grapher","github.com/a-little-srdjan/grapher/printers").
pkg("github.com/a-little-srdjan/grapher/pkg_graph").
dir("github.com/a-little-srdjan/grapher/pkg_graph",3).
direct_nested("github.com/a-little-srdjan/grapher","github.com/a-little-srdjan/grapher/pkg_graph").
| 54.966667 | 102 | 0.69436 |
73ecf8be33353e70869558888d514ee2bfb1621c | 487 | t | Perl | t/admin/plugins.t | wangxiaochuang/apisix | 4efc1202dc7a97e928411f883ea42a5ab446ce03 | [
"ECL-2.0",
"Apache-2.0"
]
| 1 | 2019-10-29T02:04:21.000Z | 2019-10-29T02:04:21.000Z | t/admin/plugins.t | wangxiaochuang/apisix | 4efc1202dc7a97e928411f883ea42a5ab446ce03 | [
"ECL-2.0",
"Apache-2.0"
]
| null | null | null | t/admin/plugins.t | wangxiaochuang/apisix | 4efc1202dc7a97e928411f883ea42a5ab446ce03 | [
"ECL-2.0",
"Apache-2.0"
]
| null | null | null | use t::APISIX 'no_plan';
repeat_each(1);
no_long_string();
no_root_location();
no_shuffle();
log_level("info");
run_tests;
__DATA__
=== TEST 1: get plugins' name
--- request
GET /apisix/admin/plugins/list
--- response_body_like eval
qr/\["limit-req","limit-count","limit-conn","key-auth","prometheus","node-status","jwt-auth","zipkin","ip-restriction","grpc-transcode","serverless-pre-function","serverless-post-function","openid-connect","proxy-rewrite"\]/
--- no_error_log
[error]
| 24.35 | 224 | 0.722793 |
ed2f2c94aa0a6fc04b185e045ccca5b55ed2792e | 2,887 | pm | Perl | lib/FAST/Bio/Seq/LargeSeqI.pm | tlawrence3/FAST | 54a7987c04fa151e1fc8657caa13423069a33743 | [
"Artistic-2.0",
"Unlicense"
]
| 32 | 2015-02-12T05:54:00.000Z | 2021-02-17T08:09:33.000Z | lib/FAST/Bio/Seq/LargeSeqI.pm | tlawrence3/FAST | 54a7987c04fa151e1fc8657caa13423069a33743 | [
"Artistic-2.0",
"Unlicense"
]
| 42 | 2015-02-12T05:53:50.000Z | 2019-10-18T12:43:24.000Z | lib/FAST/Bio/Seq/LargeSeqI.pm | tlawrence3/FAST | 54a7987c04fa151e1fc8657caa13423069a33743 | [
"Artistic-2.0",
"Unlicense"
]
| 13 | 2015-04-14T06:18:43.000Z | 2021-10-11T07:47:52.000Z | #
# BioPerl module for FAST::Bio::Seq::LargeSeqI
#
# Please direct questions and support issues to <bioperl-l@bioperl.org>
#
# Cared for by Albert Vilella
#
# Copyright Albert Vilella
#
# You may distribute this module under the same terms as perl itself
# POD documentation - main docs before the code
=head1 NAME
FAST::Bio::Seq::LargeSeqI - Interface class for sequences that cache their
residues in a temporary file
=head1 SYNOPSIS
#
=head1 DESCRIPTION
The interface class defines a group of sequence classes that do not
keep their sequence information in memory but store it in a file. This
makes it possible to work with very large files even with limited RAM.
The most important consequence of file caching for sequences is that
you do not want to inspect the sequence unless absolutely
necessary. These sequences typically override the length() method not
to check the sequence.
The seq() method is not resetable, if you want to add to the end of the
sequence you have to use add_sequence_as_string(), for any other sequence changes you'll
have to create a new object.
=head1 FEEDBACK
=head2 Mailing Lists
User feedback is an integral part of the evolution of this and other
Bioperl modules. Send your comments and suggestions preferably to
the Bioperl mailing list. Your participation is much appreciated.
bioperl-l@bioperl.org - General discussion
http://bioperl.org/wiki/Mailing_lists - About the mailing lists
=head2 Support
Please direct usage questions or support issues to the mailing list:
I<bioperl-l@bioperl.org>
rather than to the module maintainer directly. Many experienced and
reponsive experts will be able look at the problem and quickly
address it. Please include a thorough description of the problem
with code and data examples if at all possible.
=head2 Reporting Bugs
Report bugs to the Bioperl bug tracking system to help us keep track
of the bugs and their resolution. Bug reports can be submitted via
email or the web:
https://redmine.open-bio.org/projects/bioperl/
=head1 AUTHOR - Albert Vilella
Email avilella-AT-gmail-DOT-com
=head1 CONTRIBUTORS
Heikki Lehvaslaiho, heikki-at-bioperl-dot-org
=head1 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _
=cut
# Let the code begin...
package FAST::Bio::Seq::LargeSeqI;
use strict;
use base qw(FAST::Bio::Root::RootI);
=head2 add_sequence_as_string
Title : add_sequence_as_string
Usage : $seq->add_sequence_as_string("CATGAT");
Function: Appends additional residues to an existing object.
This allows one to build up a large sequence without
storing entire object in memory.
Returns : Current length of sequence
Args : string to append
=cut
sub add_sequence_as_string {
my ($self) = @_;
$self->throw_not_implemented();
}
1;
| 25.548673 | 88 | 0.765154 |
ed847c0652b23dc8a26570498788baf17f015b89 | 550 | pl | Perl | tools/parse_csr.pl | FGasper/p5-comodo-dcv | 9a5a9477739c6b808f7a829d80f9c46b005154c7 | [
"Artistic-1.0-cl8"
]
| 1 | 2017-03-15T22:18:58.000Z | 2017-03-15T22:18:58.000Z | tools/parse_csr.pl | FGasper/p5-comodo-dcv | 9a5a9477739c6b808f7a829d80f9c46b005154c7 | [
"Artistic-1.0-cl8"
]
| 1 | 2017-11-06T22:38:08.000Z | 2017-11-06T22:38:08.000Z | tools/parse_csr.pl | FGasper/p5-Comodo-DCV | 9a5a9477739c6b808f7a829d80f9c46b005154c7 | [
"Artistic-1.0-cl8"
]
| null | null | null | #!/usr/bin/env perl
use strict;
use warnings;
use Comodo::DCV ();
use Crypt::Format ();
my $stdin = do { local $/; <STDIN> };
if (!length $stdin) {
die "Need a CSR!";
}
if ($stdin =~ m<\A----->) {
print "Parsing PEM …$/";
$stdin = Crypt::Format::pem2der($stdin);
}
else {
print "Didn’t receive PEM; assuming that this is DER …$/";
}
my ($fname, $content) = Comodo::DCV::get_filename_and_contents($stdin);
print "$/Path (relative to document root):$/.well-known/pki-validation/$fname$/";
print $/;
print "Content:$/$content$/";
| 19.642857 | 81 | 0.607273 |
ed50c4a6bd6a658678ba64aa747f222b09f3ca9a | 4,133 | pm | Perl | tools/intogen/external/lib/perl/Bio/EnsEMBL/Pipeline/FASTA/SpeciesFactory.pm | globusgenomics/galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
]
| 1 | 2021-02-05T13:19:58.000Z | 2021-02-05T13:19:58.000Z | tools/intogen/external/lib/perl/Bio/EnsEMBL/Pipeline/FASTA/SpeciesFactory.pm | globusgenomics/genomics-galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
]
| null | null | null | tools/intogen/external/lib/perl/Bio/EnsEMBL/Pipeline/FASTA/SpeciesFactory.pm | globusgenomics/genomics-galaxy | 7caf74d9700057587b3e3434c64e82c5b16540f1 | [
"CC-BY-3.0"
]
| null | null | null | =pod
=head1 LICENSE
Copyright (c) 1999-2012 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>.
=head1 NAME
Bio::EnsEMBL::Pipeline::FASTA::SpeciesFactory
=head1 DESCRIPTION
A module which generates dump jobs for each species it finds in the Ensembl
Registry. The type of dump performed is controlled by the I<sequence_type_list>
parameter. The species we run the code on can be controlled by specifying
the I<species> parameter or by reducing the number of DBAdaptors loaded into
the registry.
Allowed parameters are:
=over 8
=item sequence_type_list - The type of dump to perform. Should be an array and
can contain I<dna>, I<cdna> and I<ncrna>. Defaults
to all of these.
=item species - Can be an array of species to perform dumps for or a single
species name. If specified only jobs will be created for
those species. Defaults to nothing so all species are processed
item db_types - Specify the types of database to dump. Defaults to core and
should be an array.
=back
The code flows to two outputs. Please take note if you are reusing this module
=over 8
=item 2 - Perform DNA dumps
=item 3 - Perform Gene dumps
=back
Multiple types of DB can be specifed with the I<db_types> method call but
be aware that this is flowed as 1 job per species for all types.
=cut
package Bio::EnsEMBL::Pipeline::FASTA::SpeciesFactory;
use strict;
use warnings;
use base qw/Bio::EnsEMBL::Pipeline::SpeciesFactory Bio::EnsEMBL::Pipeline::FASTA::Base/;
use Bio::EnsEMBL::Registry;
sub param_defaults {
my ($self) = @_;
return {
%{$self->SUPER::param_defaults()},
sequence_type_list => [qw/dna cdna ncrna/],
};
}
sub fetch_input {
my ($self) = @_;
$self->SUPER::fetch_input();
$self->reset_empty_array_param('sequence_type_list');
my %sequence_types = map { $_ => 1 } @{ $self->param('sequence_type_list') };
$self->param('sequence_types', \%sequence_types);
return;
}
sub run {
my ($self) = @_;
my @dna;
my @genes;
my @species;
foreach my $dba (@{$self->param('dbas')}) {
if(!$self->process_dba($dba)) {
$self->fine('Skipping %s', $dba->species());
next;
}
my $dna_flow = $self->dna_flow($dba);
if($dna_flow) {
push(@dna, [$self->input_id($dba, 'dna'), $dna_flow]);
}
my $genes_flow = $self->genes_flow($dba);
if($genes_flow) {
push(@genes, [$self->input_id($dba, 'genes'), $genes_flow]);
}
push(@species, [ { species => $dba->species() }, 5 ]);
}
$self->param('dna', \@dna);
$self->param('genes', \@genes);
$self->param('species', \@species);
return;
}
sub write_output {
my ($self) = @_;
$self->do_flow('dna');
$self->do_flow('genes');
$self->do_flow('species');
return;
}
# return 0 if we do not want to do any flowing otherwise return 2
sub dna_flow {
my ($self, $dba) = @_;
return 0 unless $self->param('sequence_types')->{dna};
return 2;
}
# return 0 if we do not want to do any flowing otherwise return 3
sub genes_flow {
my ($self, $dba) = @_;
my $types = $self->param('sequence_types');
return 0 if ! $types->{cdna} && ! $types->{ncrna};
return 3;
}
sub input_id {
my ($self, $dba, $type) = @_;
my $mc = $dba->get_MetaContainer();
my $input_id = {
db_types => $self->db_types($dba),
species => $mc->get_production_name(),
};
if($type eq 'dna') {
$input_id->{sequence_type_list} = ['dna'];
}
else {
my $types = $self->param('sequence_types');
my @types;
push(@types, 'cdna') if $types->{cdna};
push(@types, 'ncrna') if $types->{ncrna};
$input_id->{sequence_type_list} = \@types;
}
return $input_id;
}
1;
| 24.748503 | 88 | 0.648923 |
ed7c4419851e750b0b8c4e3be29e1fc1bba87ee3 | 848 | pm | Perl | t/lib/SongsToTheSiren/Test/Forms/Fields/Render/WithValue.pm | djstevenson/songs-to-the-siren | 1387f2dcb5a90206723746e514e2b8e10dedc18f | [
"MIT"
]
| null | null | null | t/lib/SongsToTheSiren/Test/Forms/Fields/Render/WithValue.pm | djstevenson/songs-to-the-siren | 1387f2dcb5a90206723746e514e2b8e10dedc18f | [
"MIT"
]
| 78 | 2020-02-16T01:35:12.000Z | 2021-01-26T18:40:30.000Z | t/lib/SongsToTheSiren/Test/Forms/Fields/Render/WithValue.pm | djstevenson/songs-to-the-siren | 1387f2dcb5a90206723746e514e2b8e10dedc18f | [
"MIT"
]
| null | null | null | package SongsToTheSiren::Test::Forms::Fields::Render::WithValue;
use utf8;
use Moose;
use namespace::autoclean;
use Test::More;
use Test::Exception;
extends 'SongsToTheSiren::Test::Forms::Fields::Render::Base';
with 'SongsToTheSiren::Test::Role';
has '+user_base' => (default => 'form_field_render5');
sub run {
my $self = shift;
$self->_run_test('Input::Text', {
field_args => {name => 'your-name', value => 'xyzzy'},
field_type => 'input',
exp_label_attrs => {for => 'test-form-your-name'},
exp_label => 'Your name',
exp_input_attrs => {
type => 'text',
name => 'your-name',
class => 'form-control',
value => 'xyzzy',
id => 'test-form-your-name',
},
});
done_testing;
}
__PACKAGE__->meta->make_immutable;
1;
| 23.555556 | 67 | 0.570755 |
ed6fa8f284c6df8103d0a4ee925704ea2ea60c14 | 11,680 | pl | Perl | modules/treex-gate-plugin/treex_online/treex_online.pl | datlowe/czsem-gate-tools | 5e4bfc72b35adf05a82e0c368728d60a8fbd0318 | [
"Apache-2.0"
]
| 1 | 2016-12-05T15:49:35.000Z | 2016-12-05T15:49:35.000Z | modules/treex-gate-plugin/treex_online/treex_online.pl | datlowe/czsem-gate-tools | 5e4bfc72b35adf05a82e0c368728d60a8fbd0318 | [
"Apache-2.0"
]
| null | null | null | modules/treex-gate-plugin/treex_online/treex_online.pl | datlowe/czsem-gate-tools | 5e4bfc72b35adf05a82e0c368728d60a8fbd0318 | [
"Apache-2.0"
]
| null | null | null | #!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use Error ':try';
use Set::Light;
use Treex::Core;
use Treex::Block::CzsemRpcReader;
use Treex::CzsemScenario;
use RPC::XML::Server;
use RPC::XML;
use Net::Address::IP::Local;
use Sys::Hostname;
use Treex::Core::Log;
sub debugPrint {
#print STDERR @_;
}
debugPrint "treex online start\n";
Treex::Core::Log::log_set_error_level('INFO');
our $stringAttrs;
our $hashAttrs;
my $port_number = shift(@ARGV);
my $handshake_hash = shift(@ARGV);
$port_number = 9090 unless defined $port_number;
$handshake_hash = '#default' unless defined $handshake_hash;
my $scenario = undef;
my @scenarioSetup = (
'Util::SetGlobal language=cs',
'CzsemRpcReader',
'W2A::CS::Segment',
'devel\analysis\cs\s_w2t.scen');
$RPC::XML::ENCODING = "UTF-8";
$RPC::XML::FORCE_STRING_ENCODING = 1;
sub get_local_ipv4_address {
my $socket = IO::Socket::INET->new(
Proto => 'udp',
PeerAddr => '198.41.0.4', # a.root-servers.net
PeerPort => '53', # DNS
);
if (! $socket) {
return '127.0.0.1'
}
# A side-effect of making a socket connection is that our IP address
# is available from the 'sockhost' method
my $local_ip_address = $socket->sockhost;
return $local_ip_address;
}
sub startServer
{
my $srv = RPC::XML::Server->new(port => $port_number); #server object
$srv->add_method(
{
"name" => "treex.handshake",
"signature" => ['string'],
"code" => \&handshake
}
);
$srv->add_method(
{
"name" => "treex.isScenarioInitialized",
"signature" => ['boolean'],
"code" => \&isScenarioInitialized
}
);
$srv->add_method(
{
"name" => "treex.initScenario",
"signature" => ['string string string'],
"code" => \&initScenarioSrv
}
);
$srv->add_method(
{
"name" => "treex.analyzeText",
"signature" => ['array string'],
"code" => \&analyzeTextSrv
}
);
$srv->add_method(
{
"name" => "treex.analyzePreprocessedDoc",
"signature" => ['array string array'],
"code" => \&analyzePreprocessedDocSrv
}
);
$srv->add_method(
{
"name" => "treex.encodeDoc",
"signature" => ['array string'],
"code" => \&encodeDocSrv
}
);
$srv->add_method(
{
"name" => "treex.terminate",
"signature" => ['string'], #what are the return type and call parameters beware of the spaces!
"code" => \&terminate
}
);
try {
print STDERR "Starting Treex RPC server at: \n";
print STDERR " http://localhost:$port_number \n";
my $host = hostname;
print STDERR " http://$host:$port_number \n";
my $ipv4 = Net::Address::IP::Local->public_ipv4;
if (! $ipv4) {
$ipv4 = get_local_ipv4_address();
}
print STDERR " http://$ipv4:$port_number \n";
}
catch Net::Address::IP::Local::Error with {
my $ex = shift;
my $errMsg = $ex->stringify;
print STDERR "WARNING network error registered:\n $errMsg";
};
### IPv6 ###
try {
my $ipv6 = Net::Address::IP::Local->public_ipv6;
print STDERR " http://[$ipv6]:$port_number \n";
}
catch Net::Address::IP::Local::Error with {
my $ex = shift;
my $errMsg = $ex->stringify;
print STDERR "INFO IPv6 not available:\n $errMsg";
};
print STDERR "\nHandshake hash: $handshake_hash\n";
$srv->server_loop; # Just work
}
sub isScenarioInitialized
{
return defined $scenario;
}
sub handshake
{
return $handshake_hash;
}
sub terminate
{
exit;
}
sub initScenario
{
my $lang = shift;
my $scenStrParam = shift;
my $scenStr = "Util::SetGlobal language=$lang CzsemRpcReader " . $scenStrParam;
debugPrint "init scenario: $scenStr \n";
$scenario = Treex::CzsemScenario->new(from_string => $scenStr);
$scenario->init;
$scenario->start;
}
sub analyzeText
{
return analyzePreprocessedDoc(shift, []);
}
#this function is no more used, it was too slow, now replaced with encodeNode
sub processNode
{
my $node = shift;
my $schema = shift;
my $ret = {};
if ($node->parent) {
debugPrint "parent: ";
debugPrint $node->parent->id;
$ret->{"parent_id"} = $node->parent->id;
}
debugPrint "\ntype: ";
debugPrint $node->get_pml_type_name . "\n";
$ret->{"pml_type_name"} = $node->get_pml_type_name;
#debugPrint $schema->get_type_names;
my $nodeType = $schema->get_type_by_name($node->get_pml_type_name);
debugPrint $nodeType . "\n";
my $nodePaths = $schema->get_paths_to_atoms([$nodeType]);
debugPrint "nodePaths: $nodePaths\n";
# foreach my $path ( $node->attribute_paths ) {
foreach my $path ( $schema->get_paths_to_atoms([$nodeType]) ) {
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#this is the most costly line !!!!!
my $value = $node->attr($path);
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#my $valueAll = $node->all($path);
if ($value) {
if (UNIVERSAL::isa($value,'ARRAY'))
{
my @arr_value = $value->values;
my $finall_value = [];
#debugPrint "$path = @arr_value ($valueAll)\n";
foreach my $v (@arr_value)
{
push(@$finall_value, $v);
}
$ret->{$path} = $finall_value;
} else {
#debugPrint "$path = $value ($valueAll)\n";
#utf8::encode($value);
$ret->{$path} = $value;
}
}
}
return $ret;
}
sub encodeDoc
{
my $filename = shift;
my $doc = Treex::Core::Document->new( { filename => $filename } );
return encodeLoadedDoc($doc);
}
sub encodeLoadedDoc
{
my $doc = shift;
my $zones = [];
debugPrint "-------------encodeLoadedDoc-$doc---------\n";
foreach my $bundle ( $doc->get_bundles ) {
foreach my $bundlezone ( $bundle->get_all_zones ) {
my $nodes = [];
my $roots = [];
my $sentence = $bundlezone->sentence;
my $language = $bundlezone->language;
my $selector = $bundlezone->selector;
#utf8::encode($sentence);
debugPrint "-----------sentence--------\n";
debugPrint $bundlezone->sentence . "\n";
foreach my $root ( $bundlezone->get_all_trees ) {
debugPrint "--root--\n";
debugPrint $root->id;
debugPrint "\n";
push(@$roots, encodeNode($root));
foreach my $node ( $root->get_descendants({}) ) {
debugPrint "----node------\n";
push(@$nodes, encodeNode($node));
}
}
my $zone = {
language => $language,
selector => $selector,
roots => $roots,
nodes => $nodes,
sentence => $sentence };
push (@$zones, $zone);
}
}
log_info 'Document ready for network transfer.';
return $zones;
}
sub debugPrintPreprocessedDoc
{
my $zones = shift;
foreach my $zone ( @$zones ) {
debugPrint "--- ZONE ---\n";
debugPrint $zone->{'sentence'};
debugPrint "\n";
my $tocs = $zone->{'tokens'};
foreach my $toc ( @$tocs ) {
debugPrint $toc->{'lemma'};
debugPrint " ";
}
debugPrint "\n";
}
}
sub analyzePreprocessedDoc
{
my $text = shift;
my $zones = shift;
debugPrintPreprocessedDoc($zones);
my $doc = Treex::Core::Document->new;
my $docParams = {
doc => $doc,
text => $text,
zones => $zones
};
$Treex::Block::CzsemRpcReader::dataQueue->enqueue($docParams);
$Treex::Block::CzsemRpcReader::dataQueue->enqueue(undef);
$scenario->run;
# DEBUG !!!!!!!!!!!!!!!!!!!!!!!!!!!!
#$doc->save('treex_online_debug.treex');
# DEBUG !!!!!!!!!!!!!!!!!!!!!!!!!!!!
return encodeLoadedDoc($doc);
}
sub analyzeTextSrv
{
shift; #server context
return analyzeText(@_);
}
sub encodeDocSrv
{
shift; #server context
return encodeDoc(@_);
}
sub initScenarioSrv
{
shift; #server context
return initScenario(@_);
}
sub analyzePreprocessedDocSrv
{
shift; #server context
return analyzePreprocessedDoc(@_);
}
sub printPathsForType
{
my $schema = shift;
my $typename = shift;
my $nodeType = $schema->get_type_by_name($typename);
print "------ $typename ------\n";
foreach my $path ( $schema->get_paths_to_atoms([$nodeType]) ) {
print "$path\n";
}
}
sub printPaths
{
my $doc = Treex::Core::Document->new;
my $bundle = $doc->create_bundle;
my $schema = $bundle->type->schema;
foreach my $typeName ( $schema->get_type_names ) {
printPathsForType($schema, $typeName);
}
foreach my $typeName ( $schema->get_type_names ) {
print "$typeName\n";
}
printPathsForType($schema, 'a-node.type');
printPathsForType($schema, 't-node.type');
printPathsForType($schema, 'n-node.type');
printPathsForType($schema, 'p-terminal.type');
printPathsForType($schema, 'p-nonterminal.type');
}
sub testDoc {
my $document = Treex::Core::Document->new( { filename => 'C:\workspace\czsem_git\src\czsem\treex-gate-plugin\src\test\resources\czsem\gate\treex\demo_en.treex' } );
encodeLoadedDoc($document);
foreach my $bundle ($document->get_bundles())
{
foreach my $root ($bundle->get_all_trees())
{
foreach my $node ($root->get_descendants({}))
{
print "------\n";
foreach my $attr (keys %{$node}) {
print "attr $attr = xxx$node->{$attr}xxx\n";
}
}
}
}
}
sub buildAttrSets
{
$stringAttrs = Set::Light->new;
$hashAttrs = Set::Light->new;
my $doc = Treex::Core::Document->new;
my $bundle = $doc->create_bundle;
my $schema = $bundle->type->schema;
foreach my $typeName ( $schema->get_type_names ) {
my $nodeType = $schema->get_type_by_name($typeName);
foreach my $path ( $schema->get_paths_to_atoms([$nodeType]) ) {
my @parts = split(/\//, $path);
$stringAttrs->insert(pop @parts);
$hashAttrs->insert(@parts);
}
}
#Attributes having origin and needed back in GATE:
$stringAttrs->insert("origForm"); #because of spell checker
$stringAttrs->insert("origFormToken"); #because of correction highlighter
}
sub encodeSubNode
{
my $node = shift;
my $ret = shift;
my $attrPrefix = shift;
foreach my $key (keys %{$node}) {
my $outKey = $attrPrefix . $key;
my $value = $node->{$key};
#skip empty values
next if !defined $value or $value eq '';
if ($stringAttrs->contains($key)) {
$ret->{$outKey} = $value;
} else {
if ($hashAttrs->contains($key))
{
encodeSubNode($value, $ret, $outKey . '/');
}
}
}
}
sub encodeNode
{
my $node = shift;
my $ret = {};
if ($node->parent) {
debugPrint "parent: ";
debugPrint $node->parent->id;
$ret->{"parent_id"} = $node->parent->id;
}
debugPrint "\ntype: ";
debugPrint $node->get_pml_type_name . "\n";
$ret->{"pml_type_name"} = $node->get_pml_type_name;
encodeSubNode($node, $ret, '');
return $ret;
}
sub printAttrSets
{
print "-str-\n";
foreach my $elem (keys %{$stringAttrs} ) {
print "$elem\n";
}
print "-hash-\n";
foreach my $elem (keys %{ $hashAttrs} ) {
print "$elem\n";
if ($stringAttrs->contains($elem)) {
print "WARNING duplicit!!!\n";
}
}
}
#initScenario(@scenarioSetup);
#printPaths;
buildAttrSets;
#printAttrSets;
#testDoc;
startServer;
| 21.007194 | 166 | 0.563699 |
ed5cfe44edbdb587ad1dc1235d3dcdcd61b1c608 | 2,258 | t | Perl | src/z80asm/t2/defines.t | iratahack/z88dk | 7917edb01695b53311ce60f7a3d70916e0ef7483 | [
"ClArtistic"
]
| null | null | null | src/z80asm/t2/defines.t | iratahack/z88dk | 7917edb01695b53311ce60f7a3d70916e0ef7483 | [
"ClArtistic"
]
| null | null | null | src/z80asm/t2/defines.t | iratahack/z88dk | 7917edb01695b53311ce60f7a3d70916e0ef7483 | [
"ClArtistic"
]
| null | null | null | #!/usr/bin/env perl
BEGIN { use lib 't2'; require 'testlib.pl'; }
z80asm_ok("", "", "",
'nop' => bytes(0));
z80asm_nok("", "", "#define", <<END_ERR);
Error at file '$test.asm' line 1: syntax error
END_ERR
z80asm_nok("", "", "#undef", <<END_ERR);
Error at file '$test.asm' line 1: syntax error
END_ERR
z80asm_ok("", "", "",
'#ignored', "");
z80asm_ok("", "", "",
'#define nil nop', => "",
'nil' => bytes(0));
z80asm_ok("", "", "",
'#define nil 0' => "",
'#undef nil' => "",
'#UNDEF nil ; ignored' => "",
'#DEFINE nil nop' => "",
'nil' => bytes(0));
z80asm_ok("", "", "",
'#define label here' => "",
'.label jp here' => bytes(0xc3, 0, 0));
z80asm_nok("", "", <<END_ASM, <<END_ERR);
#define nil nop
#define nil nop
END_ASM
Error at file '$test.asm' line 2: symbol 'nil' already defined
END_ERR
z80asm_nok("", "", <<END_ASM, <<END_ERR);
#define .3 nop
#define 3 nop
END_ASM
Error at file '$test.asm' line 1: syntax error
Error at file '$test.asm' line 2: syntax error
END_ERR
z80asm_nok("", "", <<END_ASM, <<END_ERR);
#define abc(a,b,a) a+b+a
END_ASM
Error at file '$test.asm' line 1: symbol 'a' already defined
END_ERR
z80asm_nok("", "", <<END_ASM, <<END_ERR);
#define abc(a,b a+b
END_ASM
Error at file '$test.asm' line 1: syntax error
END_ERR
z80asm_ok("", "", "",
'#define abc(a,b) a+b' => "",
'defb abc(1,2); comment'=> bytes(3),
'defb abc 1,2 ; comment'=> bytes(3));
z80asm_ok("", "", "",
'#define abc defb' => "",
'abc 1,2' => bytes(1,2));
z80asm_ok("", "", "",
'#define pusha \\' => "",
'push bc \\ \\' => "",
'push de \\ \\' => "",
'push hl' => "",
'pusha' => bytes(0xc5, 0xd5, 0xe5));
z80asm_ok("", "", "",
'#define COMMA ,' => "",
'#define LOAD(x) ld x' => "",
'LOAD a COMMA b' => bytes(0x78),
'LOAD(a COMMA b)' => bytes(0x78));
z80asm_ok("", "", "",
'#define ret nop' => "",
'ret' => bytes(0));
path("$test.1.asm")->spew(<<END);
#define ret nop
END
path("$test.2.asm")->spew(<<END);
ret
END
run_ok("./z88dk-z80asm -b $test.1.asm $test.2.asm");
check_bin_file("$test.1.bin", bytes(0xc9));
z80asm_ok("", "", "",
'#define cat(a, b) a ## b' => "",
'cat(aa,bb): jp aabb' => bytes(0xc3, 0, 0));
unlink_testfiles();
done_testing();
| 21.92233 | 62 | 0.540301 |
73fa8c42da0c1d53367f7062894fda17da90e238 | 312 | al | Perl | Git/usr/lib/perl5/vendor_perl/auto/Net/SSLeay/want_write.al | DalalBassam/myrecipeswebsite | 1ac6e97b6bac19b6d8a06d8ebf36e1f1b79a18f4 | [
"MIT"
]
| 12 | 2016-05-06T23:44:19.000Z | 2018-04-27T21:46:36.000Z | Git/usr/lib/perl5/vendor_perl/auto/Net/SSLeay/want_write.al | DalalBassam/myrecipeswebsite | 1ac6e97b6bac19b6d8a06d8ebf36e1f1b79a18f4 | [
"MIT"
]
| 5 | 2020-03-23T07:56:06.000Z | 2020-03-24T02:05:11.000Z | Git/usr/lib/perl5/vendor_perl/auto/Net/SSLeay/want_write.al | DalalBassam/myrecipeswebsite | 1ac6e97b6bac19b6d8a06d8ebf36e1f1b79a18f4 | [
"MIT"
]
| 9 | 2016-10-21T08:18:57.000Z | 2021-05-23T14:19:21.000Z | # NOTE: Derived from blib/lib/Net/SSLeay.pm.
# Changes made here will be lost when autosplit is run again.
# See AutoSplit.pm.
package Net::SSLeay;
#line 502 "blib/lib/Net/SSLeay.pm (autosplit into blib/lib/auto/Net/SSLeay/want_write.al)"
sub want_write { want(shift) == 3 }
# end of Net::SSLeay::want_write
1;
| 31.2 | 90 | 0.733974 |
ed6002dc1123427a9c0e0d320f55a1e970abdb8b | 177 | al | Perl | Apps/W1/OnPrem Permissions/app/Permissions/Inventory/invtitembomedit.permissionset.al | MiguelMercadoActual/ALAppExtensions | 97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b | [
"MIT"
]
| 1 | 2021-06-22T10:28:10.000Z | 2021-06-22T10:28:10.000Z | Apps/W1/OnPrem Permissions/app/Permissions/Inventory/invtitembomedit.permissionset.al | MiguelMercadoActual/ALAppExtensions | 97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b | [
"MIT"
]
| null | null | null | Apps/W1/OnPrem Permissions/app/Permissions/Inventory/invtitembomedit.permissionset.al | MiguelMercadoActual/ALAppExtensions | 97ee3823053eb32fa7e38dc3d1e7a89bdcca8d7b | [
"MIT"
]
| null | null | null | permissionset 8563 "INVT-ITEM/BOM, EDIT"
{
Access = Public;
Assignable = true;
Caption = 'Edit items/BOMs/SKUs';
IncludedPermissionSets = "Inventory - Edit";
}
| 19.666667 | 48 | 0.661017 |
73e9a2d77a46e191241328076d3af4ce5d4f6a30 | 8,407 | pl | Perl | pus.pl | mdclyburn/pus | 9010560f3bbecdad5fb6d72adc8446c8ed6d3e29 | [
"MIT"
]
| null | null | null | pus.pl | mdclyburn/pus | 9010560f3bbecdad5fb6d72adc8446c8ed6d3e29 | [
"MIT"
]
| null | null | null | pus.pl | mdclyburn/pus | 9010560f3bbecdad5fb6d72adc8446c8ed6d3e29 | [
"MIT"
]
| null | null | null | #!/usr/bin/perl
# PUS - the Project Utility Script
#
# This nifty script can handle your project test-compiling and
# submission needs so you don't have to manually type that handin
# command or 'scp' that file to the lab machine to test it.
#
# Subcommands:
# ltest <archive> - Extracts the specified tar GZ archive to a
# local directory and issues the 'make' command.
# This test succeeds as long as the compile is
# successful.
#
# rtest <archive> - Sends the archive to the configured machine and
# issues the 'make' command. This test succeeds as
# long as the compile is successful.
#
# submit <archive> - Turns in the specified archive to handin.
#
use Term::ANSIColor;
use File::Copy;
use File::Path;
# read the configuration file
read_configuration() if (-e ".pus.conf");
# first argument is the subcommand
if ($ARGV[0] eq "ltest") {
die "You need to specify an archive like this: pus.pl ltest proj.tgz\n" if !defined $ARGV[1];
print colored("Let's see if this thing compiles on your machine...\n", "yellow");
local_compile($ARGV[1]);
}
elsif ($ARGV[0] eq "rtest") {
die "You need to specify an archive like this: pus.pl rtest proj.tgz\n" if !defined $ARGV[1];
print colored("Running compile test remotely...\n", "yellow");
remote_compile($ARGV[1]);
}
elsif ($ARGV[0] eq "submit") {
die "You need to specify an archive like this: pus.pl submit proj.tgz\n" if !defined $ARGV[1];
print colored("Submitting...\n", "yellow");
submit($ARGV[1]);
}
else {
die "Usage: pus.pl <ltest | rtest | submit> archive\n";
}
# Read the configuration file.
sub read_configuration {
open(CONFIG, ".pus.conf") || die "Failed to open configuration file.\n";
while(<CONFIG>) {
chomp;
next if /^(#|$)/; # comment or empty line
my ($opt, $setting) = $_ =~ /([A-Za-z0-9_.]+)\s*=\s*(\S+)/;
$config{$opt} = $setting unless (!defined $setting);
}
# set the archive if it has been specified in configuration
# but don't ignore the user's command
if(!defined $ARGV[1] && defined $config{"default_archive"}) {
$ARGV[1] = $config{"default_archive"};
}
close(CONFIG);
return;
}
# Compile the specified archive on the local machine.
sub local_compile {
my ($archive_file) = @_;
# make sure this thing exists
die colored("I don't see any $archive_file around here...\n", "red") if ! -f $archive_file;
# get things into place
mkdir "pus_test";
copy $archive_file, "pus_test/";
chdir "pus_test";
my $output = `tar -zxf $archive_file 2>&1`;
if($? != 0) { # clean up even if you fail; not nice to leave things around
print colored("Extraction failed. Here is what tar said:\n", "red");
print $output;
chdir "..";
rmtree "pus_test";
die colored("Failed. Do not submit this... whatever it is...\nIs this even a gzipped tar?\n", "red");
}
# the simple make; what pretty much any instructor or TA will do
if(`uname -a` =~ /BSD/) {
print colored("This looks like a BSD; I'm using gmake instead.\n", "blue");
$output = `gmake 2>&1`;
}
else {
$output = `make 2>&1`;
}
if($? != 0) { # compilation failed and we still have to clean up
print colored("Make failed. Here is what it said:\n", "red");
print $output;
chdir "..";
rmtree "pus_test";
die colored("Failed. Do not submit this archive.\n", "red");
}
# congrats; getting here means success
print colored("Congratulations! Compile test met with success!\n", "green");
chdir "..";
rmtree "pus_test";
return;
}
# Compile the specified archive on the configured remote
# machine. The configuration file must be in place with
# the right options in order for this to work.
sub remote_compile {
die "You need to specify a remote machine in your configuration to do this.\n" if !defined $config{"remote_machine"};
die "You need to specify a user name in your configuration to do this.\n" if !defined $config{"user_name"};
die "You need to specify a directory in your configuration to do this.\n" if !defined $config{"remote_directory"};
my ($archive_file) = @_;
die colored("I don't see any $archive_file around here...\n", "red") if ! -f $archive_file;
$remote_machine = $config{"remote_machine"};
print colored("Let's see if this thing compiles on $remote_machine...\n", "yellow");
my $addr = $config{"user_name"} . "\@" . $config{"remote_machine"};
my $directory = $config{"remote_directory"};
# make the directory
print " - creating $directory...\n";
my $output = `ssh $addr "mkdir $directory" 2>&1`;
die(colored("Directory creation failed. Here is what ssh said:\n", "red"), $output) if $? != 0;
# send over the archive
print " - transferring archive...\n";
$output = `scp $archive_file $addr:$directory 2>&1`;
if ($? != 0) { # clean up
print colored("Send failed. Here is what scp said:\n", "red");
print $output;
`ssh $addr "rm -rf $directory"`;
exit 1;
}
# extract it
print " - unarchiving files...\n";
$output = `ssh $addr "tar -zx -C $directory -f $directory/$archive_file" 2>&1`;
if ($? != 0) { # clean up
print colored("Extraction failed. Here is what tar said:\n", "red");
print $output;
`ssh $addr "rm -rf $directory"`;
exit 1;
}
# run the only command that should have to be run
print " - issuing the command (hold your breath)!...\n";
$output = `ssh $addr "cd $directory && make" 2>&1`;
if ($? != 0) { # clean up
print colored("Failed. Do not submit this archive. Check this:\n", "red");
print $output;
`ssh $addr "rm -rf $directory"`;
exit 1;
}
print colored("Congratulations: the remote machine compiled successfully!\n", "green");
`ssh $addr "rm -rf $directory"`;
if ($? != 0) {
print colored("Hmm... I couldn't clean up after myself... this is embarrassing...\n", "yellow");
print colored("The directory is still on the remote computer. I couldn't be rid of it.\n", "yellow");
}
return;
}
sub submit {
die "You need to specify a remote machine in your configuration to do this.\n" if !defined $config{"remote_machine"};
die "You need to specify a user name in your configuration to do this.\n" if !defined $config{"user_name"};
die "You need to specify a directory in your configuration to do this.\n" if !defined $config{"remote_directory"};
die "You need to specify a handin repository in your configuration to do this.\n" if !defined $config{"handin_repo"};
my ($archive_file) = @_;
die colored("I don't see any $archive_file around here...\n", "red") if ! -f $archive_file;
my $remote_machine = $config{"remote_machine"};
# ensure that it compiles first
print "Running a compilation test on $remote_machine... ";
my $output = `$0 rtest $archive_file`;
die colored("ERROR\nCompile test failed. Refusing to submit because of this:\n", "red"), $output if $? != 0;
print colored("OK!\n", "green");
my $addr = $config{"user_name"} . "\@" . $remote_machine;
my $repo_url = $config{"handin_repo"};
# create the repo and copy the archive over
print " - creating temporary repository...\n";
my $remote_dir = ".pus_submit_" . time; # reduce chance of file conflicts
$output = `ssh $addr "hg clone $repo_url $remote_dir" 2>&1`;
if ($? != 0) {
die colored("Repository creation failed. Here is what ssh said:\n", "red"), $output;
}
print " - transferring archive...\n";
$output = `scp $archive_file $addr:$remote_dir/`;
if ($? != 0) {
print colored("Send failed. Here is what scp said:\n", "red");
print $output;
`ssh $addr "rm -rf $remote_dir"`;
exit 1;
}
# these Mercurial commands will be issued in order
my @hg_commands = ( "ssh $addr \"hg add --cwd $remote_dir $archive_file\" 2>&1",
"ssh $addr \"hg --cwd $remote_dir commit -m \'New submission.\' 2>&1\"",
"ssh $addr \"hg --cwd $remote_dir push 2>&1\"");
# submit!
print " - issuing Hg commands...\n";
foreach $cmd (@hg_commands) {
$output = `$cmd`;
if ($? != 0) {
print " - removing remote directory... ";
`ssh $addr "rm -rf $remote_dir"`;
print " ok...\n" if ($? == 0);
print " couldn't even do that...\n" if ($? != 0);
die colored("Submission failed. Here's what Hg said:\n", "red"), $output;
}
}
print colored("Congratulations: the submission made it to handin!\n", "green");
# clean up
`ssh $addr "rm -rf $remote_dir"`;
die colored("I couldn't clean up after myself. You'll have to manually remove $remote_dir.\n", "yellow") if $? != 0;
return;
}
exit;
| 34.174797 | 118 | 0.654574 |
ed4b4040ee7f008bd1af2ba673de93053dffc528 | 237 | pm | Perl | lib/Templ/Parser/Return.pm | kilna/perl-Templ | 57e968aea2958a9bcc444985b13c808976f99942 | [
"Artistic-2.0"
]
| null | null | null | lib/Templ/Parser/Return.pm | kilna/perl-Templ | 57e968aea2958a9bcc444985b13c808976f99942 | [
"Artistic-2.0"
]
| null | null | null | lib/Templ/Parser/Return.pm | kilna/perl-Templ | 57e968aea2958a9bcc444985b13c808976f99942 | [
"Artistic-2.0"
]
| null | null | null |
package Templ::Parser::Return;
use base 'Templ::Parser';
use strict;
use warnings;
sub header { return 'my $templ_out = '; }
sub append { return '$templ_out .= '; }
sub footer { return ";\nreturn \$templ_out;\n" }
1;
| 18.230769 | 48 | 0.611814 |
ed590eff69ad009cd00b34ef6101dd5be9d07d90 | 2,653 | t | Perl | t/get_read_group.t | BuildJet/MIP | f1f63117a7324e37dbcaa16c0298f4b4c857d44c | [
"MIT"
]
| null | null | null | t/get_read_group.t | BuildJet/MIP | f1f63117a7324e37dbcaa16c0298f4b4c857d44c | [
"MIT"
]
| null | null | null | t/get_read_group.t | BuildJet/MIP | f1f63117a7324e37dbcaa16c0298f4b4c857d44c | [
"MIT"
]
| null | null | null | #!/usr/bin/env perl
use 5.026;
use Carp;
use charnames qw{ :full :short };
use English qw{ -no_match_vars };
use File::Basename qw{ dirname };
use File::Spec::Functions qw{ catdir };
use FindBin qw{ $Bin };
use open qw{ :encoding(UTF-8) :std };
use Params::Check qw{ allow check last_error };
use Test::More;
use utf8;
use warnings qw{ FATAL utf8 };
## CPANM
use autodie qw { :all };
use Modern::Perl qw{ 2018 };
use Readonly;
## MIPs lib/
use lib catdir( dirname($Bin), q{lib} );
use MIP::Test::Fixtures qw{ test_standard_cli };
my $VERBOSE = 1;
our $VERSION = 1.02;
$VERBOSE = test_standard_cli(
{
verbose => $VERBOSE,
version => $VERSION,
}
);
## Constants
Readonly my $COMMA => q{,};
Readonly my $SPACE => q{ };
BEGIN {
use MIP::Test::Fixtures qw{ test_import };
### Check all internal dependency modules and imports
## Modules with import
my %perl_module = (
q{MIP::Sample_info} => [qw{ get_read_group }],
q{MIP::Test::Fixtures} => [qw{ test_standard_cli }],
);
test_import( { perl_module_href => \%perl_module, } );
}
use MIP::Sample_info qw{ get_read_group };
diag( q{Test get_read_group from Sample_info.pm v}
. $MIP::Sample_info::VERSION
. $COMMA
. $SPACE . q{Perl}
. $SPACE
. $PERL_VERSION
. $SPACE
. $EXECUTABLE_NAME );
## Given input parameters
my %sample_info = (
sample => {
ADM1059A1 => {
file => {
ADM1059A1_161011_TestFilev2_GAGATTCC_lane1 => {
read_direction_file => {
ADM1059A1_161011_TestFilev2_GAGATTCC_lane1_1 => {
flowcell => q{TestFilev2},
lane => q{1},
sample_barcode => q{GAGATTC},
},
},
},
},
},
},
);
my %active_parameter = ( platform => q{ILLUMINA}, );
my $infile_prefix = q{ADM1059A1_161011_TestFilev2_GAGATTCC_lane1};
## When the subroutine is executed
my %read_group = get_read_group(
{
infile_prefix => $infile_prefix,
platform => $active_parameter{platform},
sample_id => q{ADM1059A1},
sample_info_href => \%sample_info,
}
);
## Then return expected read group hash
my %expected_read_group = (
id => q{ADM1059A1_161011_TestFilev2_GAGATTCC_lane1},
lane => 1,
lb => q{ADM1059A1},
pl => q{ILLUMINA},
pu => q{TestFilev2.1.GAGATTC},
sm => q{ADM1059A1},
);
is_deeply( \%read_group, \%expected_read_group, q{Get read group} );
done_testing();
| 24.564815 | 73 | 0.570298 |
ed7cf20a86a7cfb9af62a7fb56f6b0bf635aaec6 | 410 | pl | Perl | bin/fr/basic-tokenizer.pl | AghilasSini/irisa-text-normalizer | 62905e87ae3a07f93f2bffa96a47bf446cfcd792 | [
"MIT"
]
| 1 | 2019-06-04T05:21:05.000Z | 2019-06-04T05:21:05.000Z | bin/fr/basic-tokenizer.pl | AghilasSini/irisa-text-normalizer | 62905e87ae3a07f93f2bffa96a47bf446cfcd792 | [
"MIT"
]
| null | null | null | bin/fr/basic-tokenizer.pl | AghilasSini/irisa-text-normalizer | 62905e87ae3a07f93f2bffa96a47bf446cfcd792 | [
"MIT"
]
| null | null | null | #!/usr/bin/perl
# Tokenize a text for the French language
#
use strict;
use Cwd 'abs_path';
use File::Basename;
use lib dirname( abs_path(__FILE__) )."/../../lib";
use basicTokenizerFr;
basicTokenizerFr::initAbbr();
foreach my $f (@ARGV) {
open(F, $f);
while (my $t = <F>) {
chomp;
#$t = remove_diacritics($t);
$t = &basicTokenizerFr::tok($t)."\n";
print $t;
}
close(F);
}
| 16.4 | 51 | 0.592683 |
ed6f6298e550ada937188b7cf59ef63341655ad4 | 3,137 | al | Perl | Modules/System/Camera and Media Interaction/src/CameraImpl.Codeunit.al | waldo1001/ALAppExtensions | 935155845bf45b631d1c34b6bcd5aec54308d50f | [
"MIT"
]
| null | null | null | Modules/System/Camera and Media Interaction/src/CameraImpl.Codeunit.al | waldo1001/ALAppExtensions | 935155845bf45b631d1c34b6bcd5aec54308d50f | [
"MIT"
]
| null | null | null | Modules/System/Camera and Media Interaction/src/CameraImpl.Codeunit.al | waldo1001/ALAppExtensions | 935155845bf45b631d1c34b6bcd5aec54308d50f | [
"MIT"
]
| null | null | null | // ------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// ------------------------------------------------------------------------------------------------
codeunit 1922 "Camera Impl."
{
Access = Internal;
var
Camera: Page Camera;
PictureFileNameTok: Label 'Picture_%1.jpeg', Comment = '%1 = String generated from current datetime to make sure file names are unique ';
OverrideImageQst: Label 'The existing picture will be replaced. Do you want to continue?';
UnsupportedFieldTypeErr: Label 'The field type %1 is not supported.', Comment = '%1 - The type of the field', Locked = true;
procedure GetPicture(PictureStream: InStream; var PictureName: Text): Boolean
var
WasPictureTaken: Boolean;
begin
if not IsAvailable() then
exit(false);
Clear(Camera);
Camera.SetQuality(100); // 100%
Camera.RunModal();
if Camera.HasPicture() then begin
Camera.GetPicture(PictureStream);
PictureName := StrSubstNo(PictureFileNameTok, Format(CurrentDateTime(), 0, '<Day,2>_<Month,2>_<Year4>_<Hours24>_<Minutes,2>_<Seconds,2>'));
WasPictureTaken := true;
end;
exit(WasPictureTaken);
end;
#if not CLEAN20
procedure AddPicture(RecordVariant: Variant; FieldNo: Integer): Boolean
var
#pragma warning disable AA0073
TempMedia: Record "Temp Media" temporary;
#pragma warning restore AA0073
RecordWithMediaRef: RecordRef;
MediaFieldRef: FieldRef;
PictureInStream: InStream;
PictureName: Text;
begin
if not IsAvailable() then
exit(false);
RecordWithMediaRef.GetTable(RecordVariant);
MediaFieldRef := RecordWithMediaRef.Field(FieldNo);
if not (MediaFieldRef.Type in [FieldType::Media, FieldType::MediaSet]) then
Error(UnsupportedFieldTypeErr, MediaFieldRef.Type);
if not GetPicture(PictureInStream, PictureName) then
exit(false);
if not IsNullGuid(MediaFieldRef.Value) then
if not Confirm(OverrideImageQst) then
exit(false);
case MediaFieldRef.Type of
FieldType::Media:
begin
TempMedia.Media.ImportStream(PictureInStream, PictureName, 'image/jpeg');
MediaFieldRef.Value := TempMedia.Media;
end;
FieldType::MediaSet:
begin
TempMedia.MediaSet.ImportStream(PictureInStream, PictureName, 'image/jpeg');
MediaFieldRef.Value := TempMedia.MediaSet;
end;
end;
if not RecordWithMediaRef.Modify(true) then
RecordWithMediaRef.Insert(true);
exit(true);
end;
#endif
procedure IsAvailable(): Boolean
begin
if GuiAllowed() then
exit(Camera.IsAvailable());
exit(false);
end;
} | 35.247191 | 151 | 0.58846 |
ed69bc1f5cf31e9f2a2923284287c2550d852829 | 7,828 | pm | Perl | lib/VertRes/Utils/GTypeCheck.pm | sanger-pathogens/vr-codebase | a85c4e29938cd13b36fa0a1bde1db0abd7201912 | [
"BSD-Source-Code"
]
| 7 | 2015-11-20T11:38:02.000Z | 2020-11-02T18:08:18.000Z | lib/VertRes/Utils/GTypeCheck.pm | sanger-pathogens/vr-codebase | a85c4e29938cd13b36fa0a1bde1db0abd7201912 | [
"BSD-Source-Code"
]
| 11 | 2015-05-12T11:09:51.000Z | 2022-03-22T11:11:20.000Z | lib/VertRes/Utils/GTypeCheck.pm | sanger-pathogens/vr-codebase | a85c4e29938cd13b36fa0a1bde1db0abd7201912 | [
"BSD-Source-Code"
]
| 14 | 2015-06-26T09:28:41.000Z | 2021-07-23T11:25:28.000Z | package VertRes::Utils::GTypeCheck;
use base qw(VertRes::Base);
use strict;
use warnings;
use Carp;
use VertRes::LSF;
use Utils;
sub new
{
my ($class, @args) = @_;
my $self = $class->SUPER::new(@args);
return $self;
}
sub check_genotype
{
my ($self) = @_;
if ( !exists($$self{'bam'}) ) { $self->throw("Expected the \"bam\" option.\n") }
if ( !exists($$self{'fa_ref'}) ) { $self->throw("Expected the \"fa_ref\" option.\n") }
if ( !exists($$self{'glf'}) ) { $self->throw("Expected the \"glf\" option.\n") }
if ( !exists($$self{'snps'}) ) { $self->throw("Expected the \"snps\" option.\n") }
if ( !exists($$self{'samtools'}) ) { $self->throw("Expected the \"samtools\" option.\n") }
if ( !exists($$self{'min_glf_ratio'}) ) { $self->throw("Expected the \"min_glf_ratio\" option.\n") }
if ( !exists($$self{'lock_file'}) ) { $self->throw("Expected the \"lock_file\" option.\n") }
my $bam = $$self{'bam'};
my $fa_ref = $$self{'fa_ref'};
my $glf = $$self{'glf'};
my $snps = $$self{'snps'};
my $samtools = $$self{'samtools'};
my $genotype = exists($$self{'genotype'}) ? $$self{'genotype'} : '';
my $ratio = $$self{'min_glf_ratio'};
my $lock_file = $$self{'lock_file'};
my $prefix = exists($$self{'prefix'}) ? $$self{'prefix'} : '_';
# Splits e.g. '/path/to/file.bam' to '/path/to' and 'file'
my ($dir,$name,$suff) = Utils::basename($bam);
if ( !$dir ) { $dir = '.'; }
my $pileup_out = "$name.bcf";
my $pileup_cmd = "bin2hapmap -l $snps > $name.tmp.sites && $samtools mpileup -ugDI -d 1000 -l $name.tmp.sites -f $fa_ref $bam > $name.tmp.pileup && mv $name.tmp.pileup $pileup_out";
my $checkGenotype_cmd = "$glf checkGenotype -s - $snps $pileup_out > $name.gtypey";
if (exists $self->{'snp_sites'} ) {
my $snp_sites_string;
open my $f, $self->{'snp_sites'} or $self->throw("Error opening file ". $self->{'snp_sites'});
while (<$f>) {
chomp;
my @a = split /\t/;
$snp_sites_string .= "$a[0]:$a[1]-$a[1] ";
}
close $f;
my $gtype_bam = "$name.gtype.tmp.sort";
$pileup_out = "$name.bcf";
$pileup_cmd = "$samtools view -bh $bam $snp_sites_string > $name.gtype.tmp.bam && $samtools sort $name.gtype.tmp.bam $gtype_bam && $samtools index $gtype_bam.bam && $samtools mpileup -ugDI -d 1000 -l " . $self->{'snp_sites'} . " -f $fa_ref $gtype_bam.bam > $name.gtype.tmp.pileup && mv $name.gtype.tmp.pileup $pileup_out && rm $name.gtype.tmp.bam";
$checkGenotype_cmd = "$glf checkGenotype -s - $snps $pileup_out > $name.gtypey";
}
# Dynamic script to be run by LSF.
open(my $fh, '>', "$dir/${prefix}genotype.pl") or $self->throw("$dir/${prefix}genotype.pl: $!");
print $fh
qq{
use Utils;
use VertRes::Utils::GTypeCheck;
\$base = VertRes::Base->new();
if ( ! -e "$bam.bai" || Utils::file_newer("$bam","$bam.bai") )
{
Utils::CMD("$samtools index $bam");
}
if ( ! -e "$pileup_out" || Utils::file_newer("$bam","$pileup_out") )
{
Utils::CMD(q[$pileup_cmd]);
}
if ( ! -e "$name.gtypex" || Utils::file_newer(q[$pileup_out],"$name.gtypex") )
{
Utils::CMD(q[$checkGenotype_cmd]);
if ( ! -s "$name.gtypey" )
{
\$base->throw("FIXME: this should not happen, what's wrong with:\n\t$checkGenotype_cmd\n???\n");
}
rename("$name.gtypey", "$name.gtypex") or Utils::CMD("rename $name.gtypey $name.gtypex: \$!");
if ( ! -s "$name.gtypex" )
{
\$base->throw("FIXME: this should not happen, what's wrong with:\n\trename $name.gtypey $name.gtypex\n???\n");
}
}
if ( -s "$name.gtypex" )
{
my \$gtc = VertRes::Utils::GTypeCheck->new();
open (my \$fh,'>',"$name.gtype") or Utils::error("$name.gtype: \$!");
print \$fh \$gtc->is_genotype_ok("$name.gtypex",'$genotype',$ratio);
close \$fh;
}
};
close $fh;
VertRes::LSF::run($lock_file,$dir,"$prefix${name}_glf",$self, qq{perl -w ${prefix}genotype.pl});
return $$self{'No'};
}
sub is_genotype_ok
{
my ($self,$gtype_file,$expected,$min_ratio) = @_;
open (my $fh,'<',$gtype_file) or $self->throw("$gtype_file; $!");
# Reading the first two lines would be enough, but we must see if there were
# data for the expected genotype.
#
# entropy 16.7
# sample C57BL_6J likelihood 9863 over 2583 sites, avg depth 1.05
# sample C57BLKS_J likelihood 16203 over 2469 sites, avg depth 1.05
# We also need to take account of examples where the top 2 records have an equal likelihood
# and one of them is the expected sample, but as it is listed second it is recorded as unconfirmed
# e.g. sample UK10K_CIL5062115 lane 6436_7#5:
# entropy 0.1, hets included 1
# sample UK10K_CIL5002407 likelihood 0 over 26 sites, score 0.000000, avg depth 30.192308
# sample UK10K_CIL5062115 likelihood 0 over 26 sites, score 0.000000, avg depth 30.192308
my $has_data = 0;
my ($hit1,$hit2,$gtype1,$lhood1,$gtype2,$lhood2);
my $entrp = <$fh>;
while (my $line=<$fh>)
{
if ( $has_data && defined($hit1) && defined($hit2) ) { last; }
# The regex matches both lines:
# sample NA12717 likelihood 104917 over 13788 sites, score 1.222, avg depth 0.026506
# sample xx/NA12717.snp likelihood 104917 over 13788 sites, score 1.222, avg depth 0.026506
#
if ( !($line =~ m{sample\s+(?:.*/)?(\S+?)(?:\.snp)?\s+likelihood \d+ over \d+ sites, score (\S+),} ) )
{
$self->throw("Could not parse $gtype_file: $hit1")
}
if ( $expected && $1 eq $expected ) { $has_data = 1; }
if ( !defined $hit1 )
{
$hit1 = $line;
$gtype1 = $1;
$lhood1 = $2;
}
elsif ( !defined $hit2 )
{
$hit2 = $line;
$gtype2 = $1;
$lhood2 = $2;
}
}
close $fh;
# need to take account of special circumstance above where the 'correct' sample is listed second, but has
# the same likelihood as that reported first-> $expected eq $gtype2 and $lhood1==$lhood2
my $expected_gtype1 = ($expected eq $gtype1 && $lhood1 == $lhood2) ? 1 : 0;
my $expected_gtype2 = ($expected eq $gtype2 && $lhood1 == $lhood2) ? 1 : 0;
if ( $expected && !$has_data ) { $expected = 0; }
my $ratio = $lhood1!=0 ? $lhood2/$lhood1 : $lhood2/1e-6;
if ( $expected_gtype1 ) { return "status=confirmed expected=$expected found=$gtype1 ratio=$ratio\n"; }
if ( $expected_gtype2 ) { return "status=confirmed expected=$expected found=$gtype2 ratio=$ratio\n"; }
if ( $ratio<$min_ratio )
{
if ( $expected ) { return "status=unconfirmed expected=$expected found=$gtype1 ratio=$ratio\n"; }
return "status=unknown expected=none found=$gtype1 ratio=$ratio\n";
}
if ( !$expected ) { return "status=candidate expected=none found=$gtype1 ratio=$ratio\n"; }
if ( $expected eq $gtype1 ) { return "status=confirmed expected=$expected found=$gtype1 ratio=$ratio\n"; }
return "status=wrong expected=$expected found=$gtype1 ratio=$ratio\n";
}
sub get_status
{
my ($gtype_file) = @_;
my %info = ( status=>'', expected=>'', found=>'', ratio=>'' );
open(my $fh,'<',$gtype_file) or croak "$gtype_file: $!";
my (@lines) = <$fh>;
close($fh) or croak "$gtype_file: $!";
if ( !scalar @lines ) { croak "Could not read $gtype_file\n"; }
# status=confirmed expected=NA19107 found=NA19107 ratio=1.28724761001092
if ( !($lines[0]=~/status=(\S+)\s+expected=(\S+)\s+found=(\S+)\s+ratio=(\S+)/) ) { croak "Could not parse $gtype_file: $lines[0]"; }
$info{status} = $1;
$info{expected} = $2;
$info{found} = $3;
$info{ratio} = $4;
return \%info;
}
1;
| 36.924528 | 356 | 0.580225 |
ed7ebd45588ef9a37cb2f6fd81a91216e07f294a | 215 | pm | Perl | author/lib/SampleAniki/DB.pm | GeJ/Aniki | 7e2074eea74dc14757d9ef5b742dc419a30af697 | [
"Artistic-1.0"
]
| 32 | 2015-02-10T21:42:43.000Z | 2021-01-18T00:34:33.000Z | author/lib/SampleAniki/DB.pm | GeJ/Aniki | 7e2074eea74dc14757d9ef5b742dc419a30af697 | [
"Artistic-1.0"
]
| 25 | 2015-01-13T04:24:24.000Z | 2019-12-07T11:35:38.000Z | author/lib/SampleAniki/DB.pm | GeJ/Aniki | 7e2074eea74dc14757d9ef5b742dc419a30af697 | [
"Artistic-1.0"
]
| 14 | 2015-06-03T05:05:31.000Z | 2021-01-15T12:59:16.000Z | use 5.014002;
package SampleAniki::DB {
use Mouse v2.4.5;
extends qw/Aniki/;
__PACKAGE__->setup(
schema => 'SampleAniki::DB::Schema',
filter => 'SampleAniki::DB::Filter',
);
};
1;
| 15.357143 | 44 | 0.572093 |
ed3811c13bea6aa9e4c8af264358e5a133ea20ea | 2,950 | pm | Perl | lib/Crawl/Bot/Plugin/Logging.pm | crawl/cheibriados | 3c88ea7ca070f98c08d358d2c28ba3f5218a7c8d | [
"MIT"
]
| null | null | null | lib/Crawl/Bot/Plugin/Logging.pm | crawl/cheibriados | 3c88ea7ca070f98c08d358d2c28ba3f5218a7c8d | [
"MIT"
]
| null | null | null | lib/Crawl/Bot/Plugin/Logging.pm | crawl/cheibriados | 3c88ea7ca070f98c08d358d2c28ba3f5218a7c8d | [
"MIT"
]
| null | null | null | package Crawl::Bot::Plugin::Logging;
use Moose;
extends 'Crawl::Bot::Plugin';
use autodie;
# XXX: only supports one channel at the moment
# XXX: should strip out mirc color codes from the logs
has date => (
is => 'ro',
isa => 'Str',
lazy => 1,
clearer => 'clear_date',
builder => '_build_date',
);
sub _build_date {
my ($year, $month, $day) = (localtime)[5, 4, 3];
$year += 1900;
$month++;
return sprintf '%04d%02d%02d', $year, $month, $day;
}
has logfile => (
is => 'ro',
isa => 'FileHandle',
lazy => 1,
clearer => 'clear_logfile',
default => sub {
my $self = shift;
my $filepath = File::Spec->catfile($self->logfilepath, ($self->bot->channels)[0] . '-' . $self->date . '.lg');
open my $fh, '>>', $filepath;
$fh->autoflush(1);
return $fh;
}
);
has logfilepath => (
is => 'ro',
isa => 'Str',
lazy => 1,
default => sub {
my $self = shift;
my $path = File::Spec->catdir($self->data_dir, 'log');
mkdir $path unless -d $path;
return $path;
},
);
before logfile => sub {
my $self = shift;
if ($self->date ne $self->_build_date) {
$self->clear_date;
$self->clear_logfile;
}
};
sub log_message {
my $self = shift;
my ($message) = @_;
my $timestamp = sprintf '%02d:%02d:%02d', (localtime)[2, 1, 0];
$self->logfile->print("$timestamp $message\n");
}
sub said {
my $self = shift;
my ($args) = @_;
# Only log the first channel
if ($args->{channel} eq $self->bot->{channels}[0]) {
$self->log_message("<$args->{who}> $args->{body}");
}
return;
}
sub emoted {
my $self = shift;
my ($args) = @_;
if ($args->{channel} eq $self->bot->{channels}[0]) {
$self->log_message("* $args->{who} $args->{body}");
}
return;
}
sub nick_change {
my $self = shift;
# bleh... uses different arg format
my ($old, $new) = @_;
# I guess we get nick changes everywhere *sigh*
$self->log_message("-!- $old is now known as $new");
return;
}
sub kicked {
my $self = shift;
my ($args) = @_;
if ($args->{channel} eq $self->bot->{channels}[0]) {
$self->log_message("-!- $args->{kicked} was kicked from $args->{channel} by $args->{who} [$args->{reason}]");
}
return;
}
sub topic {
my $self = shift;
my ($args) = @_;
# Might as well log this for ##crawl as well.
if (defined($args->{who})) {
$self->log_message("-!- $args->{who} changed the topic of $args->{channel} to: $args->{topic}");
}
else {
$self->log_message("-!- The topic of $args->{channel} is: $args->{topic}");
}
return;
}
sub sent {
my $self = shift;
my ($args) = @_;
if ($args->{channel} eq $self->bot->{channels}[0]) {
$self->log_message("<$args->{who}> $args->{body}");
}
return;
}
1;
| 22.180451 | 118 | 0.518983 |
ed32f0c469969005f3b4cf14985b3f71b5e125be | 373 | pm | Perl | lib/Moose/Exception/MustSupplyAnAttributeToConstructWith.pm | cv-library/Moose | 7d6242635c5700b2c28142778e959a6379e1ed3f | [
"Artistic-1.0"
]
| 2 | 2021-10-20T00:25:39.000Z | 2021-11-08T12:52:42.000Z | external/win_perl/lib/Moose/Exception/MustSupplyAnAttributeToConstructWith.pm | Brute-f0rce/l0phtcrack | 25f681c07828e5e68e0dd788d84cc13c154aed3d | [
"Apache-2.0",
"MIT"
]
| null | null | null | external/win_perl/lib/Moose/Exception/MustSupplyAnAttributeToConstructWith.pm | Brute-f0rce/l0phtcrack | 25f681c07828e5e68e0dd788d84cc13c154aed3d | [
"Apache-2.0",
"MIT"
]
| 1 | 2022-03-14T06:41:16.000Z | 2022-03-14T06:41:16.000Z | package Moose::Exception::MustSupplyAnAttributeToConstructWith;
our $VERSION = '2.2009';
use Moose;
extends 'Moose::Exception';
with 'Moose::Exception::Role::ParamsHash';
has 'class' => (
is => 'ro',
isa => 'Str',
required => 1
);
sub _build_message {
"You must supply an attribute to construct with";
}
__PACKAGE__->meta->make_immutable;
1;
| 18.65 | 63 | 0.659517 |
73e6566407a6322b4739230399434e76752f54e3 | 4,182 | pm | Perl | lib/Mojolicious/Plugin/ShareDir.pm | adherzog/p5-Mojolicious-Plugin-ShareDir | f39de1ec973c346ed0156c22e8be4e9926d8711f | [
"Artistic-1.0"
]
| null | null | null | lib/Mojolicious/Plugin/ShareDir.pm | adherzog/p5-Mojolicious-Plugin-ShareDir | f39de1ec973c346ed0156c22e8be4e9926d8711f | [
"Artistic-1.0"
]
| null | null | null | lib/Mojolicious/Plugin/ShareDir.pm | adherzog/p5-Mojolicious-Plugin-ShareDir | f39de1ec973c346ed0156c22e8be4e9926d8711f | [
"Artistic-1.0"
]
| null | null | null | package Mojolicious::Plugin::ShareDir;
use Mojo::Base 'Mojolicious::Plugin';
our $VERSION = '0.01';
use File::ShareDir;
use Mojo::File;
sub register {
my ( $self, $app ) = @_;
$app->helper(
sharedir => sub {
state $sharedir = $self->_build_sharedir($app);
return $sharedir;
}
);
if ( my $sharedir = $app->sharedir ) {
my $templates = $sharedir->child('templates');
$app->renderer->paths->[0] = $templates if ( -d $templates );
my $public = $sharedir->child('public');
$app->static->paths->[0] = $public if ( -d $public );
}
}
sub _build_sharedir {
my ( $self, $app ) = @_;
my $local = $app->home->child('share');
return $local if ( -d $local );
my $distname = ref $app;
$distname =~ s/::/-/g;
my $distdir;
eval { $distdir = Mojo::File->new( File::ShareDir::dist_dir($distname) ) };
return $distdir if ( defined $distdir && -d $distdir );
return;
}
1;
__END__
=encoding utf-8
=head1 NAME
Mojolicious::Plugin::ShareDir - Use File::ShareDir paths automatically
=head1 SYNOPSIS
# MyApp.pm
package MyApp;
use Mojo::Base 'Mojolicious';
sub startup {
my $app = shift;
$app->plugin( 'ShareDir' );
# $app->renderer->paths is now set to [ "$share/templates" ]
# $app->status->paths is now set to [ "$share/public" ]
my $sharedir = $app->sharedir; # Returns a Mojo::File obj
}
=head1 DESCRIPTION
This L<Mojolicious> plugin integrates L<File::ShareDir> with your Mojolicious
app, automatically setting the path to your C<templates> and C<public>
directories, and making it easy to access additonal shared directories and data.
This works seamlessly during development and after installation.
Since this module modifies your renderer and static paths, make sure to load it
early!
This plugin is heavily inspired by and very similar to
L<Mojolicious::Plugin::InstallablePaths>, but supports a slightly different
directory structure.
=head1 DIRECTORY STRUCTURE
This script assumes a fairly standard Mojolicious application layout. If your
app starts out like this:
my_app
|- Makefile.PL
|- lib/
|- myapp.conf
|- public/
|- script/
|- t/
+- templates/
Create a new C<share/> directory, and move your C<templates> and C<public>
directories into it. You should now have a structure like this:
my_app
|- Makefile.PL
|- lib/
|- myapp.conf
|- script/
|- share/
| |- public/
| +- templates/
+- t/
=head1 BUILD SCRIPTS
You'll need to modify your build system to have your new C<share/> directory
installed along with your application.
=head2 ExtUtils::MakeMaker
This is the default if you used C<mojo generate makefile>).
Use L<File::ShareDir::Install> in your C<Makefile.PL>:
use ExtUtils::MakeMaker;
use File::ShareDir::Install;
install_share 'share';
WriteMakefile( ... );
package MY;
use File::ShareDir::Install qw(postamble);
=head2 Other build systems
If you're using L<Module::Install>, take a look at L<Module::Install::Share>.
If you're using L<Dist::Zilla>, take a look at L<Dist::Zill::Plugin::ShareDir>.
If you're using something else, check your build system's documentation and/or
search CPAN for how to have the share directory installed along with your
application.
=head1 CONFIGURATION
None.
=head1 HELPERS
=head2 sharedir
my $dir = $app->sharedir;
my $subdir = $app->sharedir->child('data');
Returns a L<Mojo::File> object pointing at your share directory.
=head1 METHODS
L<Mojolicious::Plugin::ShareDir> inherits all methods from
L<Mojolicious::Plugin> and implements the following new ones.
=head2 register
$plugin->register(Mojolicious->new);
Register plugin in L<Mojolicious> application, updates paths, and adds helpers.
=head1 AUTHOR
Adam Herzog E<lt>adam@adamherzog.comE<gt>
=head1 COPYRIGHT
Copyright 2019 Adam Herzog
=head1 LICENSE
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<File::ShareDir>.
| 22.978022 | 80 | 0.670493 |
ed73de7215013f44f956533c948d54e8994c3cda | 348 | pm | Perl | t/lib/Storage/MySQL.pm | Ovid/DBIx-Class-ParseError | 1845153069289068be2025aa511874e1bca9a458 | [
"Artistic-1.0"
]
| null | null | null | t/lib/Storage/MySQL.pm | Ovid/DBIx-Class-ParseError | 1845153069289068be2025aa511874e1bca9a458 | [
"Artistic-1.0"
]
| null | null | null | t/lib/Storage/MySQL.pm | Ovid/DBIx-Class-ParseError | 1845153069289068be2025aa511874e1bca9a458 | [
"Artistic-1.0"
]
| null | null | null | package Storage::MySQL;
use strict;
use warnings;
use Moo::Role;
use Test::mysqld;
has _mysqld => (
is => 'lazy',
);
sub _build__mysqld {
Test::mysqld->new(
my_cnf => {
'skip-networking' => '',
'sql-mode' => 'TRADITIONAL',
}
)
}
sub connect_info { shift->_mysqld->dsn(dbname => 'test') }
1;
| 14.5 | 58 | 0.537356 |
ed26a0eb07eb9aa87f7e7458dc24fdd9d974890c | 381 | t | Perl | t/04_multiple_tests.t | tokuhirom/Test-Snippet | ee2e88eb6436b981594ddecce0093c18bb5cae0f | [
"Artistic-1.0"
]
| 1 | 2015-11-09T01:24:30.000Z | 2015-11-09T01:24:30.000Z | t/04_multiple_tests.t | tokuhirom/Test-Snippet | ee2e88eb6436b981594ddecce0093c18bb5cae0f | [
"Artistic-1.0"
]
| null | null | null | t/04_multiple_tests.t | tokuhirom/Test-Snippet | ee2e88eb6436b981594ddecce0093c18bb5cae0f | [
"Artistic-1.0"
]
| null | null | null | use strict;
use warnings;
use Test::Snippet tests => 2;
my $pod = join '', <DATA>;
test_snippet_in_pod( $pod );
__DATA__
=head1 NAME
Acme::Test - testing acme
=head1 SYNOPSIS
=begin snippet label1
$ 3+2
5
=end snippet
=begin snippet label2
$ [2,5,5,{foo => 'bar'}]
$ARRAY1 = [
2,
( 5 ) x 2,
{ foo => 'bar' }
];
=end snippet
| 11.545455 | 29 | 0.545932 |
ed3964d2ddd80cca07962fa397aad5e7659bebe5 | 17,173 | pm | Perl | lib/SNMP/Info/Layer1/Bayhub.pm | semirke/snmp-info | 26320033e9e27e05a5ee835f7ee821e8f5265b52 | [
"BSD-3-Clause"
]
| 1 | 2019-05-28T13:20:18.000Z | 2019-05-28T13:20:18.000Z | lib/SNMP/Info/Layer1/Bayhub.pm | semirke/snmp-info | 26320033e9e27e05a5ee835f7ee821e8f5265b52 | [
"BSD-3-Clause"
]
| null | null | null | lib/SNMP/Info/Layer1/Bayhub.pm | semirke/snmp-info | 26320033e9e27e05a5ee835f7ee821e8f5265b52 | [
"BSD-3-Clause"
]
| null | null | null | # SNMP::Info::Layer1::Bayhub
# $Id$
#
# Copyright (c) 2008 Eric Miller, Max Baker
# 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 University of California, Santa Cruz 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.
package SNMP::Info::Layer1::Bayhub;
use strict;
use Exporter;
use SNMP::Info::SONMP;
use SNMP::Info::NortelStack;
use SNMP::Info::Layer2;
@SNMP::Info::Layer1::Bayhub::ISA
= qw/SNMP::Info::SONMP SNMP::Info::NortelStack SNMP::Info::Layer2 Exporter/;
@SNMP::Info::Layer1::Bayhub::EXPORT_OK = qw//;
our ($VERSION, %FUNCS, %GLOBALS, %MIBS, %MUNGE);
$VERSION = '3.67';
%MIBS = (
%SNMP::Info::Layer2::MIBS,
%SNMP::Info::NortelStack::MIBS,
%SNMP::Info::SONMP::MIBS,
'S5-ETHERNET-COMMON-MIB' => 's5EnPortTable',
'S5-COMMON-STATS-MIB' => 's5CmStat',
);
%GLOBALS = (
%SNMP::Info::Layer2::GLOBALS, %SNMP::Info::NortelStack::GLOBALS,
%SNMP::Info::SONMP::GLOBALS,
);
%FUNCS = (
%SNMP::Info::Layer2::FUNCS,
%SNMP::Info::NortelStack::FUNCS,
%SNMP::Info::SONMP::FUNCS,
# S5-ETHERNET-COMMON-MIB::s5EnPortTable
'bayhub_pb_index' => 's5EnPortBrdIndx',
'bayhub_pp_index' => 's5EnPortIndx',
'bayhub_up_admin' => 's5EnPortPartStatus',
'bayhub_up' => 's5EnPortLinkStatus',
# S5-ETHERNET-COMMON-MIB::s5EnPortExtTable
'bayhub_p_speed' => 's5EnPortExtActiveSpeed',
'bayhub_p_cap' => 's5EnPortExtHwCapability',
'bayhub_p_adv' => 's5EnPortExtAutoNegAdv',
# S5-COMMON-STATS-MIB::s5CmSNodeTable
'bayhub_nb_index' => 's5CmSNodeBrdIndx',
'bayhub_np_index' => 's5CmSNodePortIndx',
'fw_mac' => 's5CmSNodeMacAddr',
);
%MUNGE = (
%SNMP::Info::Layer2::MUNGE, %SNMP::Info::NortelStack::MUNGE,
%SNMP::Info::SONMP::MUNGE,
);
sub layers {
return '00000011';
}
sub os {
return 'bay_hub';
}
sub vendor {
return 'avaya';
}
sub model {
my $bayhub = shift;
my $id = $bayhub->id();
return unless defined $id;
my $model = &SNMP::translateObj($id);
return $id unless defined $model;
$model =~ s/^sreg-//i;
return 'Baystack Hub' if ( $model =~ /BayStack/ );
return '5000' if ( $model =~ /5000/ );
return '5005' if ( $model =~ /5005/ );
return $model;
}
# Hubs do not support ifMIB requirements for get MAC
# and port status
sub i_index {
my $bayhub = shift;
my $partial = shift;
my $b_index = $bayhub->bayhub_pb_index($partial) || {};
my $p_index = $bayhub->bayhub_pp_index($partial) || {};
my $model = $bayhub->model() || 'Baystack Hub';
my %i_index;
foreach my $iid ( keys %$b_index ) {
my $board = $b_index->{$iid};
next unless defined $board;
my $port = $p_index->{$iid} || 0;
if ( $model eq 'Baystack Hub' ) {
my $comidx = $board;
if ( !( $comidx % 5 ) ) {
$board = ( $board / 5 );
}
elsif ( $comidx =~ /[16]$/ ) {
$board = int( $board / 5 );
$port = 25;
}
elsif ( $comidx =~ /[27]$/ ) {
$board = int( $board / 5 );
$port = 26;
}
}
my $index = ( $board * 256 ) + $port;
$i_index{$iid} = $index;
}
return \%i_index;
}
# Partials don't really help in this class, but implemented
# for consistency
sub interfaces {
my $bayhub = shift;
my $partial = shift;
my $i_index = $bayhub->i_index() || {};
my %if;
foreach my $iid ( keys %$i_index ) {
my $index = $i_index->{$iid};
next unless defined $index;
next if ( defined $partial and $index !~ /^$partial$/ );
# Index numbers are deterministic slot * 256 + port
my $port = $index % 256;
my $slot = int( $index / 256 );
my $slotport = "$slot.$port";
$if{$index} = $slotport;
}
return \%if;
}
sub i_duplex {
my $bayhub = shift;
my $partial = shift;
my $port_index = $bayhub->i_index() || {};
my %i_duplex;
foreach my $iid ( keys %$port_index ) {
my $index = $port_index->{$iid};
next unless defined $index;
next if ( defined $partial and $index !~ /^$partial$/ );
my $duplex = 'half';
$i_duplex{$index} = $duplex;
}
return \%i_duplex;
}
sub i_duplex_admin {
my $bayhub = shift;
my $partial = shift;
my $port_index = $bayhub->i_index() || {};
my %i_duplex_admin;
foreach my $iid ( keys %$port_index ) {
my $index = $port_index->{$iid};
next unless defined $index;
next if ( defined $partial and $index !~ /^$partial$/ );
my $duplex = 'half';
$i_duplex_admin{$index} = $duplex;
}
return \%i_duplex_admin;
}
sub i_speed {
my $bayhub = shift;
my $partial = shift;
my $port_index = $bayhub->i_index() || {};
my $port_speed = $bayhub->bayhub_p_speed() || {};
my %i_speed;
foreach my $iid ( keys %$port_index ) {
my $index = $port_index->{$iid};
next unless defined $index;
next if ( defined $partial and $index !~ /^$partial$/ );
my $speed = $port_speed->{$iid} || '10 Mbps';
$speed = '10 Mbps' if $speed =~ /bps10M/i;
$speed = '100 Mbps' if $speed =~ /bps100M/i;
$i_speed{$index} = $speed;
}
return \%i_speed;
}
sub i_up {
my $bayhub = shift;
my $partial = shift;
my $port_index = $bayhub->i_index() || {};
my $link_stat = $bayhub->bayhub_up() || {};
my %i_up;
foreach my $iid ( keys %$port_index ) {
my $index = $port_index->{$iid};
next unless defined $index;
next if ( defined $partial and $index !~ /^$partial$/ );
my $link_stat = $link_stat->{$iid};
next unless defined $link_stat;
$link_stat = 'up' if $link_stat =~ /on/i;
$link_stat = 'down' if $link_stat =~ /off/i;
$i_up{$index} = $link_stat;
}
return \%i_up;
}
sub i_up_admin {
my $bayhub = shift;
my $partial = shift;
my $i_index = $bayhub->i_index() || {};
my $link_stat = $bayhub->bayhub_up_admin() || {};
my %i_up_admin;
foreach my $iid ( keys %$i_index ) {
my $index = $i_index->{$iid};
next unless defined $index;
next if ( defined $partial and $index !~ /^$partial$/ );
my $link_stat = $link_stat->{$iid};
next unless defined $link_stat;
$i_up_admin{$index} = $link_stat;
}
return \%i_up_admin;
}
sub set_i_up_admin {
# map setting to those the hub will understand
my %setting = qw/up 2 down 3/;
my $bayhub = shift;
my ( $setting, $iid ) = @_;
my $i_index = $bayhub->i_index() || {};
my %reverse_i_index = reverse %$i_index;
$setting = lc($setting);
return 0 unless defined $setting{$setting};
$iid = $reverse_i_index{$iid};
return $bayhub->set_bayhub_up_admin( $setting{$setting}, $iid );
}
# Hubs do not support the standard Bridge MIB
sub bp_index {
my $bayhub = shift;
my $partial = shift;
my $b_index = $bayhub->bayhub_nb_index() || {};
my $p_index = $bayhub->bayhub_np_index() || {};
my $model = $bayhub->model() || 'Baystack Hub';
my %bp_index;
foreach my $iid ( keys %$b_index ) {
my $board = $b_index->{$iid};
next unless defined $board;
my $port = $p_index->{$iid} || 0;
if ( $model eq 'Baystack Hub' ) {
my $comidx = $board;
if ( !( $comidx % 5 ) ) {
$board = ( $board / 5 );
}
elsif ( $comidx =~ /[16]$/ ) {
$board = int( $board / 5 );
$port = 25;
}
elsif ( $comidx =~ /[27]$/ ) {
$board = int( $board / 5 );
$port = 26;
}
}
my $index = ( $board * 256 ) + $port;
next if ( defined $partial and $index !~ /^$partial$/ );
$bp_index{$index} = $index;
}
return \%bp_index;
}
sub fw_mac {
my $bayhub = shift;
my $partial = shift;
return $bayhub->SUPER::fw_mac($partial);
}
sub fw_port {
my $bayhub = shift;
my $partial = shift;
my $b_index = $bayhub->bayhub_nb_index($partial) || {};
my $p_index = $bayhub->bayhub_np_index($partial) || {};
my $model = $bayhub->model() || 'Baystack Hub';
my %fw_port;
foreach my $iid ( keys %$b_index ) {
my $board = $b_index->{$iid};
next unless defined $board;
my $port = $p_index->{$iid} || 0;
if ( $model eq 'Baystack Hub' ) {
my $comidx = $board;
if ( !( $comidx % 5 ) ) {
$board = ( $board / 5 );
}
elsif ( $comidx =~ /[16]$/ ) {
$board = int( $board / 5 );
$port = 25;
}
elsif ( $comidx =~ /[27]$/ ) {
$board = int( $board / 5 );
$port = 26;
}
}
my $index = ( $board * 256 ) + $port;
$fw_port{$iid} = $index;
}
return \%fw_port;
}
sub index_factor {
return 256;
}
sub slot_offset {
return 0;
}
# Devices do not support ENTITY-MIB use proprietary methods.
sub e_index {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_index($partial);
}
sub e_class {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_class($partial);
}
sub e_descr {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_descr($partial);
}
sub e_name {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_name($partial);
}
sub e_fwver {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_fwver($partial);
}
sub e_hwver {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_hwver($partial);
}
sub e_parent {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_parent($partial);
}
sub e_pos {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_pos($partial);
}
sub e_serial {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_serial($partial);
}
sub e_swver {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_swver($partial);
}
sub e_type {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_type($partial);
}
sub e_vendor {
my $stack = shift;
my $partial = shift;
return $stack->ns_e_vendor($partial);
}
1;
__END__
=head1 NAME
SNMP::Info::Layer1::Bayhub - SNMP Interface to Bay/Nortel/Avaya Hubs
=head1 AUTHOR
Eric Miller
=head1 SYNOPSIS
#Let SNMP::Info determine the correct subclass for you.
my $bayhub = new SNMP::Info(
AutoSpecify => 1,
Debug => 1,
DestHost => 'myswitch',
Community => 'public',
Version => 2
)
or die "Can't connect to DestHost.\n";
my $class = $bayhub->class();
print "SNMP::Info determined this device to fall under subclass : $class\n";
=head1 DESCRIPTION
Provides abstraction to the configuration information obtainable from a
Bay hub device through SNMP. Also provides device MAC to port mapping through
the proprietary MIB.
For speed or debugging purposes you can call the subclass directly, but not
after determining a more specific class using the method above.
my $bayhub = new SNMP::Info::Layer1::Bayhub(...);
=head2 Inherited Classes
=over
=item SNMP::Info::Layer2
=item SNMP::Info::NortelStack
=item SNMP::Info::SONMP
=back
=head2 Required MIBs
=over
=item F<S5-ETHERNET-COMMON-MIB>
=item F<S5-COMMON-STATS-MIB>
=back
=head2 Inherited MIBs
See L<SNMP::Info::Layer2/"Required MIBs"> for its MIB requirements.
See L<SNMP::Info::NortelStack/"Required MIBs"> for its MIB requirements.
See L<SNMP::Info::SONMP/"Required MIBs"> for its MIB requirements.
=head1 GLOBALS
These are methods that return scalar value from SNMP
=over
=item $bayhub->vendor()
Returns 'avaya'
=item $bayhub->os()
Returns 'bay_hub'
=item $bayhub->model()
Cross references $bayhub->id() to the F<SYNOPTICS-MIB> and returns
the results.
Removes either Baystack Hub, 5000, or 5005 depending on the model.
=back
=head2 Overrides
=over
=item $bayhub->layers()
Returns 00000011. Class emulates Layer 2 functionality through proprietary
MIBs.
=item $bayhub->index_factor()
Required by SNMP::Info::SONMP. Number representing the number of ports
reserved per slot within the device MIB. Returns 256.
=item $bayhub->slot_offset()
Required by SNMP::Info::SONMP. Offset if slot numbering does not
start at 0. Returns 0.
=back
=head2 Globals imported from SNMP::Info::Layer2
See L<SNMP::Info::Layer2/"GLOBALS"> for details.
=head2 Global Methods imported from SNMP::Info::NortelStack
See L<SNMP::Info::NortelStack/"GLOBALS"> for details.
=head2 Global Methods imported from SNMP::Info::SONMP
See L<SNMP::Info::SONMP/"GLOBALS"> for details.
=head1 TABLE METHODS
These are methods that return tables of information in the form of a reference
to a hash.
=head2 Overrides
=over
=item $bayhub->i_index()
Returns reference to map of IIDs to Interface index.
Since hubs do not support C<ifIndex>, the interface index is created using the
formula (board * 256 + port).
=item $bayhub->interfaces()
Returns reference to map of IIDs to physical ports.
=item $bayhub->i_duplex()
Returns half, hubs do not support full duplex.
=item $bayhub->i_duplex_admin()
Returns half, hubs do not support full duplex.
=item $bayhub->i_speed()
Returns interface speed.
=item $bayhub->i_up()
Returns (C<s5EnPortLinkStatus>) for each port. Translates on/off to up/down.
=item $bayhub->i_up_admin()
Returns (C<s5EnPortPartStatus>) for each port.
=item $bayhub->set_i_up_admin(state, ifIndex)
Sets port state, must be supplied with state and port C<ifIndex>
State choices are 'up' or 'down'
Example:
my %if_map = reverse %{$bayhub->interfaces()};
$bayhub->set_i_up_admin('down', $if_map{'1.1'})
or die "Couldn't change port state. ",$bayhub->error(1);
=item $bayhub->bp_index()
Simulates bridge MIB by returning reference to a hash containing the index for
both the keys and values.
=item $bayhub->fw_port()
Returns reference to map of IIDs of the C<S5-COMMON-STATS-MIB::s5CmSNodeTable>
to the Interface index.
=item $bayhub->fw_mac()
(C<s5CmSNodeMacAddr>)
=back
=head2 Pseudo F<ENTITY-MIB> Information
These devices do not support F<ENTITY-MIB>. These methods emulate Physical
Table methods using F<S5-CHASSIS-MIB>. See
L<SNMP::Info::NortelStack/"TABLE METHODS"> for details.
=over
=item $bayhub->e_index()
Returns ns_e_index().
=item $bayhub->e_class()
Returns ns_e_class().
=item $bayhub->e_descr()
Returns ns_e_descr().
=item $bayhub->e_name()
Returns ns_e_name().
=item $bayhub->e_fwver()
Returns ns_e_fwver().
=item $bayhub->e_hwver()
Returns ns_e_hwver().
=item $bayhub->e_parent()
Returns ns_e_parent().
=item $bayhub->e_pos()
Returns ns_e_pos().
=item $bayhub->e_serial()
Returns ns_e_serial().
=item $bayhub->e_swver()
Returns ns_e_swver().
=item $bayhub->e_type()
Returns ns_e_type().
=item $bayhub->e_vendor()
Returns ns_e_vendor().
=back
=head2 Table Methods imported from SNMP::Info::Layer2
See L<SNMP::Info::Layer2/"TABLE METHODS"> for details.
=head2 Table Methods imported from SNMP::Info::NortelStack
See L<SNMP::Info::NortelStack/"TABLE METHODS"> for details.
=head2 Table Methods imported from SNMP::Info::SONMP
See L<SNMP::Info::SONMP/"TABLE METHODS"> for details.
=cut
| 23.301221 | 81 | 0.604903 |
ed3024fa307c883fa9e2f19b82e43717e30a1ea7 | 5,637 | pm | Perl | os/linux/local/mode/memory.pm | nribault/centreon-plugins | e99276ba80ba202392791e78d72b00f1306d1a99 | [
"Apache-2.0"
]
| null | null | null | os/linux/local/mode/memory.pm | nribault/centreon-plugins | e99276ba80ba202392791e78d72b00f1306d1a99 | [
"Apache-2.0"
]
| null | null | null | os/linux/local/mode/memory.pm | nribault/centreon-plugins | e99276ba80ba202392791e78d72b00f1306d1a99 | [
"Apache-2.0"
]
| null | null | null | #
# Copyright 2020 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package os::linux::local::mode::memory;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {
'warning:s' => { name => 'warning' },
'critical:s' => { name => 'critical' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'.");
$self->{output}->option_exit();
}
}
sub check_rhel_version {
my ($self, %options) = @_;
$self->{rhel_71} = 0;
return if ($options{stdout} !~ /(?:Redhat|CentOS|Red[ \-]Hat).*?release\s+(\d+)\.(\d+)/mi);
$self->{rhel_71} = 1 if ($1 >= 8 || ($1 == 7 && $2 >= 1));
}
sub run {
my ($self, %options) = @_;
my ($stdout) = $options{custom}->execute_command(
command => 'cat',
command_options => '/proc/meminfo /etc/redhat-release 2>&1',
no_quit => 1
);
# Buffer can be missing. In Openvz container for example.
my $buffer_used = 0;
my ($cached_used, $free, $total_size, $slab_used);
foreach (split(/\n/, $stdout)) {
if (/^MemTotal:\s+(\d+)/i) {
$total_size = $1 * 1024;
} elsif (/^Cached:\s+(\d+)/i) {
$cached_used = $1 * 1024;
} elsif (/^Buffers:\s+(\d+)/i) {
$buffer_used = $1 * 1024;
} elsif (/^Slab:\s+(\d+)/i) {
$slab_used = $1 * 1024;
} elsif (/^MemFree:\s+(\d+)/i) {
$free = $1 * 1024;
}
}
if (!defined($total_size) || !defined($cached_used) || !defined($free)) {
$self->{output}->add_option_msg(short_msg => 'Some informations missing.');
$self->{output}->option_exit();
}
$self->check_rhel_version(stdout => $stdout);
my $physical_used = $total_size - $free;
my $nobuf_used = $physical_used - $buffer_used - $cached_used;
my ($slab_value, $slab_unit);
($slab_value, $slab_unit) = $self->{perfdata}->change_bytes(value => $slab_used) if (defined($slab_used));
if ($self->{rhel_71} == 1) {
$nobuf_used -= $slab_used;
}
my $prct_used = $nobuf_used * 100 / $total_size;
my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]);
my ($nobuf_value, $nobuf_unit) = $self->{perfdata}->change_bytes(value => $nobuf_used);
my ($buffer_value, $buffer_unit) = $self->{perfdata}->change_bytes(value => $buffer_used);
my ($cached_value, $cached_unit) = $self->{perfdata}->change_bytes(value => $cached_used);
$self->{output}->output_add(
severity => $exit,
short_msg => sprintf(
'Ram used (-buffers/cache%s) %s (%.2f%%), Buffer: %s, Cached: %s%s',
($self->{rhel_71} == 1 && defined($slab_used)) ? '/slab' : '',
$nobuf_value . " " . $nobuf_unit,
$prct_used,
$buffer_value . " " . $buffer_unit,
$cached_value . " " . $cached_unit,
(defined($slab_used)) ? ', Slab: ' . $slab_value . ' ' . $slab_unit : '',
)
);
$self->{output}->perfdata_add(
label => 'cached', unit => 'B',
value => $cached_used,
min => 0
);
$self->{output}->perfdata_add(
label => 'buffer', unit => 'B',
value => $buffer_used,
min => 0
);
$self->{output}->perfdata_add(
label => 'used', unit => 'B',
value => $nobuf_used,
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size),
min => 0, max => $total_size
);
$self->{output}->perfdata_add(
label => 'slab', unit => 'B',
value => $slab_used,
min => 0
) if (defined($slab_used));
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check physical memory (need '/proc/meminfo' file).
Command used: cat /proc/meminfo /etc/redhat-release 2>&1
=over 8
=item B<--warning>
Threshold warning in percent.
=item B<--critical>
Threshold critical in percent.
=back
=cut
| 32.211429 | 196 | 0.580451 |
ed7a020d4ba63f3cdfe92eb35328885c8a4b7d1b | 8,130 | pm | Perl | lib/Chart/Plotly/Trace/Sankey/Link.pm | hstejas/p5-Chart-Plotly | c1666613369ff44d0ec984935b02b4024638aacf | [
"MIT"
]
| 11 | 2017-01-08T12:08:24.000Z | 2021-12-14T15:27:56.000Z | lib/Chart/Plotly/Trace/Sankey/Link.pm | hstejas/p5-Chart-Plotly | c1666613369ff44d0ec984935b02b4024638aacf | [
"MIT"
]
| 28 | 2016-11-21T20:25:21.000Z | 2021-04-20T16:58:38.000Z | lib/Chart/Plotly/Trace/Sankey/Link.pm | hstejas/p5-Chart-Plotly | c1666613369ff44d0ec984935b02b4024638aacf | [
"MIT"
]
| 3 | 2016-12-14T15:59:41.000Z | 2020-07-30T04:39:43.000Z | package Chart::Plotly::Trace::Sankey::Link;
use Moose;
use MooseX::ExtraArgs;
use Moose::Util::TypeConstraints qw(enum union);
if (!defined Moose::Util::TypeConstraints::find_type_constraint('PDL')) {
Moose::Util::TypeConstraints::type('PDL');
}
use Chart::Plotly::Trace::Sankey::Link::Concentrationscales;
use Chart::Plotly::Trace::Sankey::Link::Hoverlabel;
use Chart::Plotly::Trace::Sankey::Link::Line;
# VERSION
# ABSTRACT: This attribute is one of the possible options for the trace sankey.
=encoding utf-8
=head1 SYNOPSIS
# EXAMPLE: examples/traces/sankey.pl
=head1 DESCRIPTION
This attribute is part of the possible options for the trace sankey.
This file has been autogenerated from the official plotly.js source.
If you like Plotly, please support them: L<https://plot.ly/>
Open source announcement: L<https://plot.ly/javascript/open-source-announcement/>
Full reference: L<https://plot.ly/javascript/reference/#sankey>
=head1 DISCLAIMER
This is an unofficial Plotly Perl module. Currently I'm not affiliated in any way with Plotly.
But I think plotly.js is a great library and I want to use it with perl.
=head1 METHODS
=cut
=head2 TO_JSON
Serialize the trace to JSON. This method should be called only by L<JSON> serializer.
=cut
sub TO_JSON {
my $self = shift;
my $extra_args = $self->extra_args // {};
my $meta = $self->meta;
my %hash = %$self;
for my $name (sort keys %hash) {
my $attr = $meta->get_attribute($name);
if (defined $attr) {
my $value = $hash{$name};
my $type = $attr->type_constraint;
if ($type && $type->equals('Bool')) {
$hash{$name} = $value ? \1 : \ 0;
}
}
}
%hash = (%hash, %$extra_args);
delete $hash{'extra_args'};
if ($self->can('type') && (!defined $hash{'type'})) {
$hash{type} = $self->type();
}
return \%hash;
}
=head1 ATTRIBUTES
=over
=cut
=item * color
Sets the `link` color. It can be a single value, or an array for specifying color for each `link`. If `link.color` is omitted, then by default, a translucent grey link will be used.
=cut
has color => (
is => "rw",
isa => "Str|ArrayRef[Str]",
documentation => "Sets the `link` color. It can be a single value, or an array for specifying color for each `link`. If `link.color` is omitted, then by default, a translucent grey link will be used.",
);
=item * colorscales
=cut
has colorscales => (
is => "rw",
isa => "ArrayRef|ArrayRef[Chart::Plotly::Trace::Sankey::Link::Concentrationscales]",
);
=item * colorsrc
Sets the source reference on plot.ly for color .
=cut
has colorsrc => (
is => "rw",
isa => "Str",
documentation => "Sets the source reference on plot.ly for color .",
);
=item * description
=cut
has description => (
is => "ro",
default => "The links of the Sankey plot.",
);
=item * hoverinfo
Determines which trace information appear when hovering links. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired.
=cut
has hoverinfo => (
is => "rw",
isa => enum(["all","none","skip"]),
documentation => "Determines which trace information appear when hovering links. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired.",
);
=item * hoverlabel
=cut
has hoverlabel => (
is => "rw",
isa => "Maybe[HashRef]|Chart::Plotly::Trace::Sankey::Link::Hoverlabel",
);
=item * hovertemplate
Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plot.ly/javascript/plotlyjs-events/#event-data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `value` and `label`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`.
=cut
has hovertemplate => (
is => "rw",
isa => "Str|ArrayRef[Str]",
documentation => "Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example \"y: %{y}\". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example \"Price: %{y:\$.2f}\". https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example \"Day: %{2019-01-01|%A}\". https://github.com/d3/d3-3.x-api-reference/blob/master/Time-Formatting.md#format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plot.ly/javascript/plotlyjs-events/#event-data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `value` and `label`. Anything contained in tag `<extra>` is displayed in the secondary box, for example \"<extra>{fullData.name}</extra>\". To hide the secondary box completely, use an empty tag `<extra></extra>`.",
);
=item * hovertemplatesrc
Sets the source reference on plot.ly for hovertemplate .
=cut
has hovertemplatesrc => (
is => "rw",
isa => "Str",
documentation => "Sets the source reference on plot.ly for hovertemplate .",
);
=item * label
The shown name of the link.
=cut
has label => (
is => "rw",
isa => "ArrayRef|PDL",
documentation => "The shown name of the link.",
);
=item * labelsrc
Sets the source reference on plot.ly for label .
=cut
has labelsrc => (
is => "rw",
isa => "Str",
documentation => "Sets the source reference on plot.ly for label .",
);
=item * line
=cut
has line => (
is => "rw",
isa => "Maybe[HashRef]|Chart::Plotly::Trace::Sankey::Link::Line",
);
=item * source
An integer number `[0..nodes.length - 1]` that represents the source node.
=cut
has source => (
is => "rw",
isa => "ArrayRef|PDL",
documentation => "An integer number `[0..nodes.length - 1]` that represents the source node.",
);
=item * sourcesrc
Sets the source reference on plot.ly for source .
=cut
has sourcesrc => (
is => "rw",
isa => "Str",
documentation => "Sets the source reference on plot.ly for source .",
);
=item * target
An integer number `[0..nodes.length - 1]` that represents the target node.
=cut
has target => (
is => "rw",
isa => "ArrayRef|PDL",
documentation => "An integer number `[0..nodes.length - 1]` that represents the target node.",
);
=item * targetsrc
Sets the source reference on plot.ly for target .
=cut
has targetsrc => (
is => "rw",
isa => "Str",
documentation => "Sets the source reference on plot.ly for target .",
);
=item * value
A numeric value representing the flow volume value.
=cut
has value => (
is => "rw",
isa => "ArrayRef|PDL",
documentation => "A numeric value representing the flow volume value.",
);
=item * valuesrc
Sets the source reference on plot.ly for value .
=cut
has valuesrc => (
is => "rw",
isa => "Str",
documentation => "Sets the source reference on plot.ly for value .",
);
=pod
=back
=cut
__PACKAGE__->meta->make_immutable();
1;
| 28.626761 | 1,167 | 0.675892 |
73d517ef88fbbd10494573cb49e8ae629312c133 | 483 | pm | Perl | auto-lib/Azure/ADHybridHealthService/AlertFeedback.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Azure/ADHybridHealthService/AlertFeedback.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Azure/ADHybridHealthService/AlertFeedback.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| 1 | 2021-04-08T15:26:39.000Z | 2021-04-08T15:26:39.000Z | package Azure::ADHybridHealthService::AlertFeedback;
use Moose;
has 'comment' => (is => 'ro', isa => 'Str' );
has 'consentedToShare' => (is => 'ro', isa => 'Bool' );
has 'createdDate' => (is => 'ro', isa => 'Str' );
has 'feedback' => (is => 'ro', isa => 'Str' );
has 'level' => (is => 'ro', isa => 'Str' );
has 'serviceMemberId' => (is => 'ro', isa => 'Str' );
has 'shortName' => (is => 'ro', isa => 'Str' );
has 'state' => (is => 'ro', isa => 'Str' );
1;
| 37.153846 | 58 | 0.488613 |
73eaa28944b0d26939793df8d522474be367d3c5 | 4,895 | pl | Perl | perl/vendor/lib/auto/share/dist/DateTime-Locale/fr-DZ.pl | luiscarlosg27/xampp | c295dbdd435c9c62fbd4cc6fc42097bea7a900a0 | [
"Apache-2.0"
]
| 2 | 2021-07-24T12:46:49.000Z | 2021-08-02T08:37:53.000Z | perl/vendor/lib/auto/share/dist/DateTime-Locale/fr-DZ.pl | luiscarlosg27/xampp | c295dbdd435c9c62fbd4cc6fc42097bea7a900a0 | [
"Apache-2.0"
]
| null | null | null | perl/vendor/lib/auto/share/dist/DateTime-Locale/fr-DZ.pl | luiscarlosg27/xampp | c295dbdd435c9c62fbd4cc6fc42097bea7a900a0 | [
"Apache-2.0"
]
| null | null | null | {
am_pm_abbreviated => [
"AM",
"PM",
],
available_formats => {
Bh => "h B",
Bhm => "h:mm B",
Bhms => "h:mm:ss B",
E => "E",
EBhm => "E h:mm B",
EBhms => "E h:mm:ss B",
EHm => "E HH:mm",
EHms => "E HH:mm:ss",
Ed => "E d",
Ehm => "E h:mm a",
Ehms => "E h:mm:ss a",
Gy => "y G",
GyMMM => "MMM y G",
GyMMMEd => "E d MMM y G",
GyMMMd => "d MMM y G",
H => "HH 'h'",
Hm => "HH:mm",
Hms => "HH:mm:ss",
Hmsv => "HH:mm:ss v",
Hmv => "HH:mm v",
M => "L",
MEd => "E dd/MM",
MMM => "LLL",
MMMEd => "E d MMM",
"MMMMW-count-one" => "'semaine' W (MMMM)",
"MMMMW-count-other" => "'semaine' W (MMMM)",
MMMMd => "d MMMM",
MMMd => "d MMM",
Md => "dd/MM",
d => "d",
h => "h a",
hm => "h:mm a",
hms => "h:mm:ss a",
hmsv => "h:mm:ss a v",
hmv => "h:mm a v",
ms => "mm:ss",
y => "y",
yM => "MM/y",
yMEd => "E dd/MM/y",
yMMM => "MMM y",
yMMMEd => "E d MMM y",
yMMMM => "MMMM y",
yMMMd => "d MMM y",
yMd => "dd/MM/y",
yQQQ => "QQQ y",
yQQQQ => "QQQQ y",
"yw-count-one" => "'semaine' w 'de' Y",
"yw-count-other" => "'semaine' w 'de' Y",
},
code => "fr-DZ",
date_format_full => "EEEE d MMMM y",
date_format_long => "d MMMM y",
date_format_medium => "d MMM y",
date_format_short => "dd/MM/y",
datetime_format_full => "{1} '\N{U+00e0}' {0}",
datetime_format_long => "{1} '\N{U+00e0}' {0}",
datetime_format_medium => "{1} '\N{U+00e0}' {0}",
datetime_format_short => "{1} {0}",
day_format_abbreviated => [
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam.",
"dim.",
],
day_format_narrow => [
"L",
"M",
"M",
"J",
"V",
"S",
"D",
],
day_format_wide => [
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi",
"dimanche",
],
day_stand_alone_abbreviated => [
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam.",
"dim.",
],
day_stand_alone_narrow => [
"L",
"M",
"M",
"J",
"V",
"S",
"D",
],
day_stand_alone_wide => [
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi",
"dimanche",
],
era_abbreviated => [
"av. J.-C.",
"ap. J.-C.",
],
era_narrow => [
"av. J.-C.",
"ap. J.-C.",
],
era_wide => [
"avant J\N{U+00e9}sus-Christ",
"apr\N{U+00e8}s J\N{U+00e9}sus-Christ",
],
first_day_of_week => 6,
glibc_date_1_format => "%a %b %e %H:%M:%S %Z %Y",
glibc_date_format => "%m/%d/%y",
glibc_datetime_format => "%a %b %e %H:%M:%S %Y",
glibc_time_12_format => "%I:%M:%S %p",
glibc_time_format => "%H:%M:%S",
language => "French",
month_format_abbreviated => [
"janv.",
"f\N{U+00e9}vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\N{U+00fb}t",
"sept.",
"oct.",
"nov.",
"d\N{U+00e9}c.",
],
month_format_narrow => [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
],
month_format_wide => [
"janvier",
"f\N{U+00e9}vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\N{U+00fb}t",
"septembre",
"octobre",
"novembre",
"d\N{U+00e9}cembre",
],
month_stand_alone_abbreviated => [
"janv.",
"f\N{U+00e9}vr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"ao\N{U+00fb}t",
"sept.",
"oct.",
"nov.",
"d\N{U+00e9}c.",
],
month_stand_alone_narrow => [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D",
],
month_stand_alone_wide => [
"janvier",
"f\N{U+00e9}vrier",
"mars",
"avril",
"mai",
"juin",
"juillet",
"ao\N{U+00fb}t",
"septembre",
"octobre",
"novembre",
"d\N{U+00e9}cembre",
],
name => "French Algeria",
native_language => "fran\N{U+00e7}ais",
native_name => "fran\N{U+00e7}ais Alg\N{U+00e9}rie",
native_script => undef,
native_territory => "Alg\N{U+00e9}rie",
native_variant => undef,
quarter_format_abbreviated => [
"T1",
"T2",
"T3",
"T4",
],
quarter_format_narrow => [
1,
2,
3,
4,
],
quarter_format_wide => [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre",
],
quarter_stand_alone_abbreviated => [
"T1",
"T2",
"T3",
"T4",
],
quarter_stand_alone_narrow => [
1,
2,
3,
4,
],
quarter_stand_alone_wide => [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre",
],
script => undef,
territory => "Algeria",
time_format_full => "h:mm:ss a zzzz",
time_format_long => "h:mm:ss a z",
time_format_medium => "h:mm:ss a",
time_format_short => "h:mm a",
variant => undef,
version => 37,
}
| 17.930403 | 54 | 0.449847 |
ed73b3082f97cbcac1b3e4141f420e794bbca1b3 | 852 | pm | Perl | local/lib/perl5/Date/Manip/Offset/off150.pm | jkb78/extrajnm | 6890e38e15f85ea9c09a141aa14affad0b8e91e7 | [
"MIT"
]
| null | null | null | local/lib/perl5/Date/Manip/Offset/off150.pm | jkb78/extrajnm | 6890e38e15f85ea9c09a141aa14affad0b8e91e7 | [
"MIT"
]
| null | null | null | local/lib/perl5/Date/Manip/Offset/off150.pm | jkb78/extrajnm | 6890e38e15f85ea9c09a141aa14affad0b8e91e7 | [
"MIT"
]
| null | null | null | package #
Date::Manip::Offset::off150;
# Copyright (c) 2008-2015 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
# This file was automatically generated. Any changes to this file will
# be lost the next time 'tzdata' is run.
# Generated on: Wed Nov 25 11:44:43 EST 2015
# Data version: tzdata2015g
# Code version: tzcode2015g
# This module contains data from the zoneinfo time zone database. The original
# data was obtained from the URL:
# ftp://ftp.iana.org/tz
use strict;
use warnings;
require 5.010000;
our ($VERSION);
$VERSION='6.52';
END { undef $VERSION; }
our ($Offset,%Offset);
END {
undef $Offset;
undef %Offset;
}
$Offset = '+08:05:43';
%Offset = (
0 => [
'asia/shanghai',
],
);
1;
| 21.3 | 79 | 0.666667 |
ed40b86d8bc07e8c14ddd1eb76ccc44b653c2682 | 3,431 | pl | Perl | capstone_final_package/capstone_adat/external/CSV_script/test_script.pl | korenmiklos/106 | 9925a2bda18915eb43d7bdd2b54d4d7aa113bc66 | [
"MIT"
]
| 1 | 2018-04-07T20:44:45.000Z | 2018-04-07T20:44:45.000Z | capstone_final_package/capstone_adat/external/CSV_script/test_script.pl | korenmiklos/106 | 9925a2bda18915eb43d7bdd2b54d4d7aa113bc66 | [
"MIT"
]
| null | null | null | capstone_final_package/capstone_adat/external/CSV_script/test_script.pl | korenmiklos/106 | 9925a2bda18915eb43d7bdd2b54d4d7aa113bc66 | [
"MIT"
]
| null | null | null | use Text::CSV;
use strict;
use warnings;
use utf8;
use File::Copy;
binmode STDOUT, ':utf8';
use open qw/:std :utf8/;
my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary attribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();
my $filename = 'test_csv_1APR.csv';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
my $row = $csv->getline( $fh );
my $columns = $row;
# new becsles oldal
open my $topfh, '<:encoding(UTF-8)', 'mandatumbecsles.md' or die "Can't open file $!";
read $topfh, my $top_file_content, -s $topfh;
my $new_top_file_content = $top_file_content;
while ($row = $csv->getline( $fh )) {
chomp $row;
my $mdfilename = "$row->[0].md";
#print "$mdfilename\n"; - commented out
open my $mdfh, '<:encoding(UTF-8)', $mdfilename or die "Can't open file $!";
read $mdfh, my $file_content, -s $mdfh;
#print "$file_content\n";
my $new_file_content = $file_content =~ s/id="id_fidesz">xx%/id="id_fidesz">$row->[1]/gr;
$new_file_content = $new_file_content =~ s/id="id_jobbik">xx%/id="id_jobbik">$row->[2]/gr;
$new_file_content = $new_file_content =~ s/id="id_baloldal">xx%/id="id_baloldal">$row->[3]/gr;
$new_file_content = $new_file_content =~ s/id="id_lmp">xx%/id="id_lmp">$row->[4]/gr;
$new_file_content = $new_file_content =~ s/id="id_momentum">xx%/id="id_momentum">$row->[5]/gr;
$new_file_content = $new_file_content =~ s/id="id_egyutt">xx%/id="id_egyutt">$row->[6]/gr;
$new_file_content = $new_file_content =~ s/id="id_mkkp">xx%/id="id_mkkp">$row->[7]/gr;
#$new_file_content = $new_file_content =~ s/id="esely">xx/id="esely">$row->[10]/gr;
#$new_file_content = $new_file_content =~ s/id="esely2">xx/id="esely2">$row->[11]/gr;
$new_file_content = $new_file_content =~ s/id="gyoztes">xx/id="gyoztes">$row->[21]/gr;
$new_file_content = $new_file_content =~ s/id="masodik">xx/id="masodik">$row->[23]/gr;
#$new_file_content = $new_file_content =~ s/id="profil">xx/id="profil">$row->[24]/gr;
$new_file_content = $new_file_content =~ s/id="biztos_jelolt">xx/id="biztos_jelolt">$row->[24]/gr;
$new_file_content = $new_file_content =~ s/id="id_fidesz2">xx%/id="id_fidesz2">$row->[8]/gr;
$new_file_content = $new_file_content =~ s/id="id_jobbik2">xx%/id="id_jobbik2">$row->[9]/gr;
$new_file_content = $new_file_content =~ s/id="id_baloldal2">xx%/id="id_baloldal2">$row->[10]/gr;
$new_file_content = $new_file_content =~ s/id="id_lmp2">xx%/id="id_lmp2">$row->[12]/gr;
$new_file_content = $new_file_content =~ s/id="id_momentum2">xx%/id="id_momentum2">$row->[13]/gr;
$new_file_content = $new_file_content =~ s/id="id_egyutt2">xx%/id="id_egyutt2">$row->[14]/gr;
$new_file_content = $new_file_content =~ s/id="id_mkkp2">xx%/id="id_mkkp2">$row->[15]/gr;
#print $new_file_content; - commented out
open my $ofh, '>', "test_output/$mdfilename";
print {$ofh} $new_file_content;
close $ofh;
$new_top_file_content = $new_top_file_content =~ s/id="gyoztes_$row->[0]">Győztes/id="gyoztes_$row->[0]">$row->[21]/gr;
$new_top_file_content = $new_top_file_content =~ s/id="masodik_$row->[0]">Második/id="masodik_$row->[0]">$row->[22]/gr;
$new_top_file_content = $new_top_file_content =~ s/id="kulonbseg_$row->[0]">Különbség/id="kulonbseg_$row->[0]">$row->[20]/gr;
};
open my $topofh, '>', "test_output/mandatumbecsles.md";
print {$topofh} $new_top_file_content;
close $topofh;
print "$columns\n";
| 50.455882 | 127 | 0.666861 |
ed659cabfa180362e263aec35c74906caa7b89e9 | 1,968 | pm | Perl | auto-lib/Paws/AppStream/ApplicationSettingsResponse.pm | meis/aws-sdk-perl | 6d61ffcf351e446f06d7e84e53caa08d98573959 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Paws/AppStream/ApplicationSettingsResponse.pm | meis/aws-sdk-perl | 6d61ffcf351e446f06d7e84e53caa08d98573959 | [
"Apache-2.0"
]
| 1 | 2021-05-26T19:13:58.000Z | 2021-05-26T19:13:58.000Z | auto-lib/Paws/AppStream/ApplicationSettingsResponse.pm | meis/aws-sdk-perl | 6d61ffcf351e446f06d7e84e53caa08d98573959 | [
"Apache-2.0"
]
| null | null | null | package Paws::AppStream::ApplicationSettingsResponse;
use Moose;
has Enabled => (is => 'ro', isa => 'Bool');
has S3BucketName => (is => 'ro', isa => 'Str');
has SettingsGroup => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::AppStream::ApplicationSettingsResponse
=head1 USAGE
This class represents one of two things:
=head3 Arguments in a call to a service
Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.
As an example, if Att1 is expected to be a Paws::AppStream::ApplicationSettingsResponse object:
$service_obj->Method(Att1 => { Enabled => $value, ..., SettingsGroup => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::AppStream::ApplicationSettingsResponse object:
$result = $service_obj->Method(...);
$result->Att1->Enabled
=head1 DESCRIPTION
Describes the persistent application settings for users of a stack.
=head1 ATTRIBUTES
=head2 Enabled => Bool
Specifies whether persistent application settings are enabled for users
during their streaming sessions.
=head2 S3BucketName => Str
The S3 bucket where usersE<rsquo> persistent application settings are
stored. When persistent application settings are enabled for the first
time for an account in an AWS Region, an S3 bucket is created. The
bucket is unique to the AWS account and the Region.
=head2 SettingsGroup => Str
The path prefix for the S3 bucket where usersE<rsquo> persistent
application settings are stored.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::AppStream>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: L<https://github.com/pplu/aws-sdk-perl>
Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues>
=cut
| 26.594595 | 115 | 0.747967 |
ed2f2155f61488e8453b7c653bc93d8ae1cb2c64 | 324 | t | Perl | t/data/object/integer/detract.t | gitpan/Data-Object | 1d7fafd23016ebb81ab3eabd44255088435e047c | [
"Artistic-1.0"
]
| null | null | null | t/data/object/integer/detract.t | gitpan/Data-Object | 1d7fafd23016ebb81ab3eabd44255088435e047c | [
"Artistic-1.0"
]
| null | null | null | t/data/object/integer/detract.t | gitpan/Data-Object | 1d7fafd23016ebb81ab3eabd44255088435e047c | [
"Artistic-1.0"
]
| null | null | null | use Test::More;
use_ok 'Data::Object::Number';
can_ok 'Data::Object::Number', 'detract';
subtest 'test the detract method' => sub {
my $integer = Data::Object::Number->new(99999);
is $integer->detract, 99999;
$integer = Data::Object::Number->new('99999');
is "$integer", 99999;
};
ok 1 and done_testing;
| 21.6 | 51 | 0.645062 |
ed7f43ff2af2ef2cfbee774b350a58bbbd9cf2b9 | 905 | pm | Perl | t/TestChecks/DbCheck_3.pm | MatBarba/ensembl-datacheck | 74b93d57ba4e53ba720c12df2d21d8499de46253 | [
"Apache-2.0"
]
| null | null | null | t/TestChecks/DbCheck_3.pm | MatBarba/ensembl-datacheck | 74b93d57ba4e53ba720c12df2d21d8499de46253 | [
"Apache-2.0"
]
| null | null | null | t/TestChecks/DbCheck_3.pm | MatBarba/ensembl-datacheck | 74b93d57ba4e53ba720c12df2d21d8499de46253 | [
"Apache-2.0"
]
| null | null | null | =head1 LICENSE
# Copyright [2018] EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
=cut
package TestChecks::DbCheck_3;
use warnings;
use strict;
use Moose;
use Test::More;
extends 'Bio::EnsEMBL::DataCheck::DbCheck';
use constant {
NAME => 'DbCheck_3',
DESCRIPTION => 'Skipping DbCheck example.',
DB_TYPES => ['variation'],
};
sub tests {
}
1;
| 23.205128 | 74 | 0.729282 |
ed27afa1516351bdb696c1d52b2b3bf0740d8a93 | 7,522 | pm | Perl | network/kemp/snmp/mode/vsstatus.pm | dalfo77/centreon-plugins | 3cb2011c46a45b5e4a785ca6bab439142f882d45 | [
"Apache-2.0"
]
| null | null | null | network/kemp/snmp/mode/vsstatus.pm | dalfo77/centreon-plugins | 3cb2011c46a45b5e4a785ca6bab439142f882d45 | [
"Apache-2.0"
]
| null | null | null | network/kemp/snmp/mode/vsstatus.pm | dalfo77/centreon-plugins | 3cb2011c46a45b5e4a785ca6bab439142f882d45 | [
"Apache-2.0"
]
| null | null | null | #
# Copyright 2020 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::kemp::snmp::mode::vsstatus;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
sub custom_status_output {
my ($self, %options) = @_;
my $msg = 'status : ' . $self->{result_values}->{status};
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_status'};
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'vs', type => 1, cb_prefix_output => 'prefix_vs_output', message_multiple => 'All virtual servers are ok' }
];
$self->{maps_counters}->{vs} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'status' }, { name => 'display' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
{ label => 'active', set => {
key_values => [ { name => 'vSActivConns' }, { name => 'display' } ],
output_template => 'Active connections : %s',
perfdatas => [
{ label => 'active', template => '%s', min => 0, label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'in-traffic', set => {
key_values => [ { name => 'vSInBytes', per_second => 1 }, { name => 'display' } ],
output_template => 'Traffic In : %s %s/s',
output_change_bytes => 2,
perfdatas => [
{ label => 'traffic_in', template => '%.2f', min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'out-traffic', set => {
key_values => [ { name => 'vSOutBytes', per_second => 1 }, { name => 'display' } ],
output_template => 'Traffic Out : %s %s/s',
output_change_bytes => 2,
perfdatas => [
{ label => 'traffic_out', template => '%.2f', min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display' },
]
}
}
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
'filter-name:s' => { name => 'filter_name' },
'warning-status:s' => { name => 'warning_status', default => '' },
'critical-status:s' => { name => 'critical_status', default => '%{status} !~ /inService|disabled|redirect/i' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$self->change_macros(macros => ['warning_status', 'critical_status']);
}
sub prefix_vs_output {
my ($self, %options) = @_;
return "Virtual server '" . $options{instance_value}->{display} . "' ";
}
my %map_state = (
1 => 'inService',
2 => 'outOfService',
4 => 'disabled',
5 => 'sorry',
6 => 'redirect',
7 => 'errormsg',
);
my $mapping = {
vSname => { oid => '.1.3.6.1.4.1.12196.13.1.1.13' },
vSstate => { oid => '.1.3.6.1.4.1.12196.13.1.1.14', map => \%map_state },
vSInBytes => { oid => '.1.3.6.1.4.1.12196.13.1.1.19' },
vSOutBytes => { oid => '.1.3.6.1.4.1.12196.13.1.1.20' },
vSActivConns => { oid => '.1.3.6.1.4.1.12196.13.1.1.21' },
};
my $oid_vsEntry = '.1.3.6.1.4.1.12196.13.1.1';
sub manage_selection {
my ($self, %options) = @_;
$self->{vs} = {};
my $snmp_result = $options{snmp}->get_table(oid => $oid_vsEntry,
nothing_quit => 1);
foreach my $oid (keys %{$snmp_result}) {
next if ($oid !~ /^$mapping->{vSstate}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $instance);
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$result->{vSname} !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "skipping '" . $result->{vSname} . "': no matching filter.", debug => 1);
next;
}
$self->{vs}->{$instance} = { display => $result->{vSname},
status => $result->{vSstate},
vSInBytes => defined($result->{vSInBytes}) ? $result->{vSInBytes} * 8 : undef,
vSOutBytes => defined($result->{vSOutBytes}) ? $result->{vSOutBytes} * 8 : undef,
vSActivConns => $result->{vSActivConns} };
}
if (scalar(keys %{$self->{vs}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No virtual server found.");
$self->{output}->option_exit();
}
$self->{cache_name} = "kemp_" . $self->{mode} . '_' . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all'));
}
1;
__END__
=head1 MODE
Check virtual server status.
=over 8
=item B<--filter-counters>
Only display some counters (regexp can be used).
Example: --filter-counters='^status$'
=item B<--filter-name>
Filter virtual server name (can be a regexp).
=item B<--warning-status>
Set warning threshold for status.
Can used special variables like: %{status}, %{display}
=item B<--critical-status>
Set critical threshold for status (Default: '%{status} !~ /inService|disabled|redirect/i').
Can used special variables like: %{status}, %{display}
=item B<--warning-*>
Threshold warning.
Can be: 'active', 'in-traffic' (b/s), 'out-traffic' (b/s).
=item B<--critical-*>
Threshold critical.
Can be: 'active', 'in-traffic' (b/s), 'out-traffic' (b/s).
=back
=cut
| 35.481132 | 148 | 0.539218 |
ed84f8bd3f99708eba4c449b60be60cb2d36e565 | 16,330 | pm | Perl | lib/Mojo/Template.pm | wudangt/mojo | fbbafd9f93c647e8a3d7c7c8948f49fd58ad0e70 | [
"Artistic-2.0"
]
| 1 | 2015-11-06T03:32:24.000Z | 2015-11-06T03:32:24.000Z | lib/Mojo/Template.pm | wudangt/mojo | fbbafd9f93c647e8a3d7c7c8948f49fd58ad0e70 | [
"Artistic-2.0"
]
| null | null | null | lib/Mojo/Template.pm | wudangt/mojo | fbbafd9f93c647e8a3d7c7c8948f49fd58ad0e70 | [
"Artistic-2.0"
]
| null | null | null | package Mojo::Template;
use Mojo::Base -base;
use Carp 'croak';
use Mojo::ByteStream;
use Mojo::Exception;
use Mojo::Util qw(decode encode monkey_patch slurp);
use constant DEBUG => $ENV{MOJO_TEMPLATE_DEBUG} || 0;
has [qw(auto_escape compiled)];
has [qw(append code prepend template)] => '';
has capture_end => 'end';
has capture_start => 'begin';
has comment_mark => '#';
has encoding => 'UTF-8';
has escape => sub { \&Mojo::Util::xml_escape };
has [qw(escape_mark expression_mark trim_mark)] => '=';
has [qw(line_start replace_mark)] => '%';
has name => 'template';
has namespace => 'Mojo::Template::SandBox';
has tag_start => '<%';
has tag_end => '%>';
has tree => sub { [] };
sub build {
my $self = shift;
my (@lines, $cpst, $multi);
my $escape = $self->auto_escape;
for my $line (@{$self->tree}) {
push @lines, '';
for (my $j = 0; $j < @{$line}; $j += 2) {
my ($op, $value) = @$line[$j, $j + 1];
my $newline = chomp($value //= '');
# Capture end
if ($op eq 'cpen') {
$lines[-1] .= 'return Mojo::ByteStream->new($_M) }';
# No following code
my $next = $line->[$j + 3];
$lines[-1] .= ';' if !defined $next || $next =~ /^\s*$/;
}
# Text (quote and fix line ending)
if ($op eq 'text') {
$value = $newline ? quotemeta($value) . '\n' : quotemeta $value;
$lines[-1] .= "\$_M .= \"" . $value . "\";" if length $value;
}
# Code or multiline expression
if ($op eq 'code' || $multi) { $lines[-1] .= "$value" }
# Expression
if ($op eq 'expr' || $op eq 'escp') {
# Start
unless ($multi) {
# Escaped
if ($op eq 'escp' && !$escape || $op eq 'expr' && $escape) {
$lines[-1] .= "\$_M .= _escape";
$lines[-1] .= " scalar $value" if length $value;
}
# Raw
else { $lines[-1] .= "\$_M .= scalar $value" }
}
# Multiline
$multi = !(($line->[$j + 2] // '') eq 'text'
&& ($line->[$j + 3] // '') eq '');
# Append semicolon
$lines[-1] .= ';' unless $multi || $cpst;
}
# Capture start
if ($cpst) {
$lines[-1] .= $cpst;
$cpst = undef;
}
$cpst = " sub { my \$_M = ''; " if $op eq 'cpst';
}
}
return $self->code(join "\n", @lines)->tree([]);
}
sub compile {
my $self = shift;
# Compile with line directive
return undef unless my $code = $self->code;
my $compiled = eval $self->_wrap($code);
$self->compiled($compiled) and return undef unless $@;
# Use local stacktrace for compile exceptions
return Mojo::Exception->new($@, [$self->template, $code])->trace->verbose(1);
}
sub interpret {
my $self = shift;
# Stacktrace
local $SIG{__DIE__} = sub {
CORE::die($_[0]) if ref $_[0];
Mojo::Exception->throw(shift, [$self->template, $self->code]);
};
return undef unless my $compiled = $self->compiled;
my $output;
return $output if eval { $output = $compiled->(@_); 1 };
# Exception with template context
return Mojo::Exception->new($@, [$self->template])->verbose(1);
}
sub parse {
my ($self, $template) = @_;
# Clean start
my $tree = $self->template($template)->tree([])->tree;
my $tag = $self->tag_start;
my $replace = $self->replace_mark;
my $expr = $self->expression_mark;
my $escp = $self->escape_mark;
my $cpen = $self->capture_end;
my $cmnt = $self->comment_mark;
my $cpst = $self->capture_start;
my $trim = $self->trim_mark;
my $end = $self->tag_end;
my $start = $self->line_start;
my $token_re = qr/
(
\Q$tag\E(?:\Q$replace\E|\Q$cmnt\E) # Replace
|
\Q$tag$expr\E(?:\Q$escp\E)?(?:\s*\Q$cpen\E(?!\w))? # Expression
|
\Q$tag\E(?:\s*\Q$cpen\E(?!\w))? # Code
|
(?:(?<!\w)\Q$cpst\E\s*)?(?:\Q$trim\E)?\Q$end\E # End
)
/x;
my $cpen_re = qr/^(\Q$tag\E)(?:\Q$expr\E)?(?:\Q$escp\E)?\s*\Q$cpen\E/;
my $end_re = qr/^(?:(\Q$cpst\E)\s*)?(\Q$trim\E)?\Q$end\E$/;
# Split lines
my $state = 'text';
my ($trimming, @capture_token);
for my $line (split "\n", $template) {
$trimming = 0 if $state eq 'text';
# Turn Perl line into mixed line
if ($state eq 'text' && $line !~ s/^(\s*)\Q$start$replace\E/$1$start/) {
if ($line =~ s/^(\s*)\Q$start\E(?:(\Q$cmnt\E)|(\Q$expr\E))?//) {
# Comment
if ($2) { $line = "$tag$2 $trim$end" }
# Expression or code
else { $line = $3 ? "$1$tag$3$line $end" : "$tag$line $trim$end" }
}
}
# Escaped line ending
$line .= "\n" unless $line =~ s/\\\\$/\\\n/ || $line =~ s/\\$//;
# Mixed line
my @token;
for my $token (split $token_re, $line) {
# Capture end
@capture_token = ('cpen', undef) if $token =~ s/$cpen_re/$1/;
# End
if ($state ne 'text' && $token =~ $end_re) {
$state = 'text';
# Capture start
splice @token, -2, 0, 'cpst', undef if $1;
# Trim left side
if ($2) {
$trimming = 1;
$self->_trim(\@token);
}
# Hint at end
push @token, 'text', '';
}
# Code
elsif ($token =~ /^\Q$tag\E$/) { $state = 'code' }
# Expression
elsif ($token =~ /^\Q$tag$expr\E$/) { $state = 'expr' }
# Expression that needs to be escaped
elsif ($token =~ /^\Q$tag$expr$escp\E$/) { $state = 'escp' }
# Comment
elsif ($token =~ /^\Q$tag$cmnt\E$/) { $state = 'cmnt' }
# Text
else {
# Replace
$token = $tag if $token eq "$tag$replace";
# Trim right side (convert whitespace to line noise)
if ($trimming && $token =~ s/^(\s+)//) {
push @token, 'code', $1;
$trimming = 0;
}
# Comments are ignored
next if $state eq 'cmnt';
push @token, @capture_token, $state, $token;
@capture_token = ();
}
}
push @$tree, \@token;
}
return $self;
}
sub render {
my $self = shift;
return $self->parse(shift)->build->compile || $self->interpret(@_);
}
sub render_file {
my ($self, $path) = (shift, shift);
$self->name($path) unless defined $self->{name};
my $template = slurp $path;
my $encoding = $self->encoding;
croak qq{Template "$path" has invalid encoding}
if $encoding && !defined($template = decode $encoding, $template);
return $self->render($template, @_);
}
sub _line {
my $name = shift->name;
$name =~ y/"//d;
return qq{#line @{[shift]} "$name"};
}
sub _trim {
my ($self, $line) = @_;
# Walk line backwards
for (my $j = @$line - 4; $j >= 0; $j -= 2) {
# Skip captures
next if $line->[$j] eq 'cpst' || $line->[$j] eq 'cpen';
# Only trim text
return unless $line->[$j] eq 'text';
# Convert whitespace text to line noise
splice @$line, $j, 0, 'code', $1 if $line->[$j + 1] =~ s/(\s+)$//;
# Text left
return if length $line->[$j + 1];
}
}
sub _wrap {
my ($self, $code) = @_;
# Escape function
my $escape = $self->escape;
monkey_patch $self->namespace, _escape => sub {
no warnings 'uninitialized';
ref $_[0] eq 'Mojo::ByteStream' ? $_[0] : $escape->("$_[0]");
};
# Wrap lines
my $num = () = $code =~ /\n/g;
my $head = $self->_line(1);
$head .= "\npackage @{[$self->namespace]}; use Mojo::Base -strict;";
$code = "$head sub { my \$_M = ''; @{[$self->prepend]}; do { $code\n";
$code .= $self->_line($num + 1) . "\n@{[$self->append]}; \$_M } };";
warn "-- Code for @{[$self->name]}\n@{[encode 'UTF-8', $code]}\n\n" if DEBUG;
return $code;
}
1;
=encoding utf8
=head1 NAME
Mojo::Template - Perl-ish templates!
=head1 SYNOPSIS
use Mojo::Template;
# Simple
my $mt = Mojo::Template->new;
my $output = $mt->render(<<'EOF');
% use Time::Piece;
<!DOCTYPE html>
<html>
<head><title>Simple</title></head>
% my $now = localtime;
<body>Time: <%= $now->hms %></body>
</html>
EOF
say $output;
# More advanced
my $output = $mt->render(<<'EOF', 23, 'foo bar');
% my ($num, $text) = @_;
%= 5 * 5
<!DOCTYPE html>
<html>
<head><title>More advanced</title></head>
<body>
test 123
foo <% my $i = $num + 2; %>
% for (1 .. 23) {
* some text <%= $i++ %>
% }
</body>
</html>
EOF
say $output;
=head1 DESCRIPTION
L<Mojo::Template> is a minimalistic and very Perl-ish template engine,
designed specifically for all those small tasks that come up during big
projects. Like preprocessing a configuration file, generating text from
heredocs and stuff like that.
See L<Mojolicious::Guides::Rendering> for information on how to generate
content with the L<Mojolicious> renderer.
=head1 SYNTAX
For all templates L<strict>, L<warnings>, L<utf8> and Perl 5.10 features are
automatically enabled.
<% Perl code %>
<%= Perl expression, replaced with result %>
<%== Perl expression, replaced with XML escaped result %>
<%# Comment, useful for debugging %>
<%% Replaced with "<%", useful for generating templates %>
% Perl code line, treated as "<% line =%>"
%= Perl expression line, treated as "<%= line %>"
%== Perl expression line, treated as "<%== line %>"
%# Comment line, useful for debugging
%% Replaced with "%", useful for generating templates
Escaping behavior can be reversed with the L</"auto_escape"> attribute, this
is the default in L<Mojolicious> C<.ep> templates for example.
<%= Perl expression, replaced with XML escaped result %>
<%== Perl expression, replaced with result %>
L<Mojo::ByteStream> objects are always excluded from automatic escaping.
% use Mojo::ByteStream 'b';
<%= b('<div>excluded!</div>') %>
Whitespace characters around tags can be trimmed by adding an additional equal
sign to the end of a tag.
<%= All whitespace characters around this expression will be trimmed =%>
Newline characters can be escaped with a backslash.
This is <%= 1 + 1 %> a\
single line
And a backslash in front of a newline character can be escaped with another
backslash.
This will <%= 1 + 1 %> result\\
in multiple\\
lines
You can capture whole template blocks for reuse later with the C<begin> and
C<end> keywords.
<% my $block = begin %>
<% my $name = shift; =%>
Hello <%= $name %>.
<% end %>
<%= $block->('Baerbel') %>
<%= $block->('Wolfgang') %>
Perl lines can also be indented freely.
% my $block = begin
% my $name = shift;
Hello <%= $name %>.
% end
%= $block->('Baerbel')
%= $block->('Wolfgang')
L<Mojo::Template> templates get compiled to a Perl subroutine, that means you
can access arguments simply via C<@_>.
% my ($foo, $bar) = @_;
% my $x = shift;
test 123 <%= $foo %>
The compilation of templates to Perl code can make debugging a bit tricky, but
L<Mojo::Template> will return L<Mojo::Exception> objects that stringify to
error messages with context.
Bareword "xx" not allowed while "strict subs" in use at template line 4.
2: </head>
3: <body>
4: % my $i = 2; xx
5: %= $i * 2
6: </body>
=head1 ATTRIBUTES
L<Mojo::Template> implements the following attributes.
=head2 auto_escape
my $bool = $mt->auto_escape;
$mt = $mt->auto_escape($bool);
Activate automatic escaping.
=head2 append
my $code = $mt->append;
$mt = $mt->append('warn "Processed template"');
Append Perl code to compiled template. Note that this code should not contain
newline characters, or line numbers in error messages might end up being
wrong.
=head2 capture_end
my $end = $mt->capture_end;
$mt = $mt->capture_end('end');
Keyword indicating the end of a capture block, defaults to C<end>.
<% my $block = begin %>
Some data!
<% end %>
=head2 capture_start
my $start = $mt->capture_start;
$mt = $mt->capture_start('begin');
Keyword indicating the start of a capture block, defaults to C<begin>.
<% my $block = begin %>
Some data!
<% end %>
=head2 code
my $code = $mt->code;
$mt = $mt->code($code);
Perl code for template.
=head2 comment_mark
my $mark = $mt->comment_mark;
$mt = $mt->comment_mark('#');
Character indicating the start of a comment, defaults to C<#>.
<%# This is a comment %>
=head2 compiled
my $compiled = $mt->compiled;
$mt = $mt->compiled($compiled);
Compiled template code.
=head2 encoding
my $encoding = $mt->encoding;
$mt = $mt->encoding('UTF-8');
Encoding used for template files.
=head2 escape
my $cb = $mt->escape;
$mt = $mt->escape(sub {...});
A callback used to escape the results of escaped expressions, defaults to
L<Mojo::Util/"xml_escape">.
$mt->escape(sub {
my $str = shift;
return reverse $str;
});
=head2 escape_mark
my $mark = $mt->escape_mark;
$mt = $mt->escape_mark('=');
Character indicating the start of an escaped expression, defaults to C<=>.
<%== $foo %>
=head2 expression_mark
my $mark = $mt->expression_mark;
$mt = $mt->expression_mark('=');
Character indicating the start of an expression, defaults to C<=>.
<%= $foo %>
=head2 line_start
my $start = $mt->line_start;
$mt = $mt->line_start('%');
Character indicating the start of a code line, defaults to C<%>.
% $foo = 23;
=head2 name
my $name = $mt->name;
$mt = $mt->name('foo.mt');
Name of template currently being processed, defaults to C<template>. Note that
this value should not contain quotes or newline characters, or error messages
might end up being wrong.
=head2 namespace
my $namespace = $mt->namespace;
$mt = $mt->namespace('main');
Namespace used to compile templates, defaults to C<Mojo::Template::SandBox>.
Note that namespaces should only be shared very carefully between templates,
since functions and global variables will not be cleared automatically.
=head2 prepend
my $code = $mt->prepend;
$mt = $mt->prepend('my $self = shift;');
Prepend Perl code to compiled template. Note that this code should not contain
newline characters, or line numbers in error messages might end up being
wrong.
=head2 replace_mark
my $mark = $mt->replace_mark;
$mt = $mt->replace_mark('%');
Character used for escaping the start of a tag or line, defaults to C<%>.
<%% my $foo = 23; %>
=head2 tag_start
my $start = $mt->tag_start;
$mt = $mt->tag_start('<%');
Characters indicating the start of a tag, defaults to C<E<lt>%>.
<% $foo = 23; %>
=head2 tag_end
my $end = $mt->tag_end;
$mt = $mt->tag_end('%>');
Characters indicating the end of a tag, defaults to C<%E<gt>>.
<%= $foo %>
=head2 template
my $template = $mt->template;
$mt = $mt->template($template);
Raw unparsed template.
=head2 tree
my $tree = $mt->tree;
$mt = $mt->tree([['text', 'foo']]);
Template in parsed form. Note that this structure should only be used very
carefully since it is very dynamic.
=head2 trim_mark
my $mark = $mt->trim_mark;
$mt = $mt->trim_mark('-');
Character activating automatic whitespace trimming, defaults to C<=>.
<%= $foo =%>
=head1 METHODS
L<Mojo::Template> inherits all methods from L<Mojo::Base> and implements the
following new ones.
=head2 build
$mt = $mt->build;
Build Perl L</"code"> from L</"tree">.
=head2 compile
my $exception = $mt->compile;
Compile Perl L</"code"> for template.
=head2 interpret
my $output = $mt->interpret;
my $output = $mt->interpret(@args);
Interpret L</"compiled"> template code.
# Reuse template
say $mt->render('Hello <%= $_[0] %>!', 'Bender');
say $mt->interpret('Fry');
say $mt->interpret('Leela');
=head2 parse
$mt = $mt->parse($template);
Parse template into L</"tree">.
=head2 render
my $output = $mt->render($template);
my $output = $mt->render($template, @args);
Render template.
say $mt->render('Hello <%= $_[0] %>!', 'Bender');
=head2 render_file
my $output = $mt->render_file('/tmp/foo.mt');
my $output = $mt->render_file('/tmp/foo.mt', @args);
Render template file.
=head1 DEBUGGING
You can set the C<MOJO_TEMPLATE_DEBUG> environment variable to get some
advanced diagnostics information printed to C<STDERR>.
MOJO_TEMPLATE_DEBUG=1
=head1 SEE ALSO
L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicio.us>.
=cut
| 23.909224 | 79 | 0.581935 |
ed7b1d2b8912453f26797a8497463aba2dd5a953 | 7,283 | al | Perl | benchmark/benchmarks/FASP-benchmarks/data/planar-triangulations-2/triangulation-0390-390-1569.al | krzysg/FaspHeuristic | 1929c40e3fbc49e68b04acfc5522539a18758031 | [
"MIT"
]
| null | null | null | benchmark/benchmarks/FASP-benchmarks/data/planar-triangulations-2/triangulation-0390-390-1569.al | krzysg/FaspHeuristic | 1929c40e3fbc49e68b04acfc5522539a18758031 | [
"MIT"
]
| null | null | null | benchmark/benchmarks/FASP-benchmarks/data/planar-triangulations-2/triangulation-0390-390-1569.al | krzysg/FaspHeuristic | 1929c40e3fbc49e68b04acfc5522539a18758031 | [
"MIT"
]
| null | null | null | 1 86 354
2 43 45 48 193 220 251 322 340 382
3 11 66 79 109 208 242
4 138 238 240 273
5 27 38 87 96 132 194
6 195
7 15 289 334
8 130 172 237 318 351
9 6 176 252 291 365
10 33 163 227 341
11 242 244 383
12 94 154 174 279 311
13 256 286 298 337
14 53 162 224 313 381
15 7 196 244
16 42 46 108 137 330
17 59 117
18 27 65 154 245
19 52 105 184 249 302
20 189 318 346
21 78 187 304
22 208 280 367
23 125 202 210
24 213 275
25 33 75 157 271 310 376
26 47 54 144 216 323
27 5 18 65 194
28 119 261 270 272
29 160 264 386 388
30 150 228 352 361 368
31 67 170
32 49 253 268
33 10 110 226 271
34 336 338 387
35 88 133 212 377
36 185 228 338
37 20 24 164 275 292 318
38 165 194 335
39 49 120 129 156 222 359
40 181 196 288 313 334 381
41 27 158 194 343
42 16 94 100 108 137 170 191 308 342
43 2 26 45 54 322
44 53 288
45 2 54 251
46 16 137 192 330 347
47 26 55 144 189 193
48 28 74 111 220 382
49 110 129
50 122 123 352
51 209 302 315
52 19 70 209 302 344
53 155 224 234
54 26 63 177 216 389
55 85 189 193 333 346
56 11 79 80 163 266 383
57 32 268
58 1 86 125 265 309
59 71 238 337
60 350
61 67 97 142 366
62 192 201 206 225
63 54 100 137 177 192 201
64 57 129 216 247 389
65 27 88 91 132
66 3 148 214
67 31 61 76 97 170 366
68 60 61 81 142 186 350
69 207 213 275 339
70 143 167 259 282 344 388
71 40 59 107 181 250 256
72 146 373
73 209 300 344
74 111 178 179 217
75 25 157 273 376
76 320 342 366
77 141 162 223 236
78 36 187 352
79 3 11 80 208
80 79 266 329
81 68 198
82 199 254 282 390
83 237 249 367
84 127 128 165 180
85 55 111 179 333
86 1 41 173 343 354
87 5 96
88 132 174 212
89 126 215 255
90 236 306
91 18 65 88 154 174
92 133 294 295 296
93 72 364 373
94 42 170 279 311 379
95 119 139 204 297 305
96 5 38 87 165 180
97 31 60 68 106
98 124 372 387
99 83 237 276
100 297 305 308
101 109 152 196 242 349
102 341
103 228 290 312 320 366 369
104 84 127 168 319
105 83 99
106 31 60 212
107 250 301
108 16 42 330 342
109 101 148 152 214 242
110 49 157 359
111 74 85 179 193 382
112 161 296 303 336
113 11 15 244
114 95 204
115 75 123 138 221 240 287
116 110 115 157 211 287 345 359
117 17 147 197 238 286 337
118 309 373
119 28 114 139 220
120 39 64 129 222 389
121 63 100 114 177 204 220 297
122 150 211 361
123 115 211 221 304 352
124 6 90 236 306 358 365
125 23 58 210 265 300
126 215 255 321 331
127 84 239 319 362
128 84 104 146 183 203
129 32 49 57 120
130 8 37 292 318
131 134 139 153 270 272 299
132 5 27 35 88 231
133 231 295 303 377
134 178 188 248 299
135 10 102 163 341
136 175 298 375
137 16 100 192
138 4 115 117 197 238 240
139 95 119 153 272 384
140 95 384
141 90 236 260 298 301
142 68 81 198 290
143 70 184 249 386
144 47 164 189 323
145 173 248 299 324
146 72 84 118 128 165 203 243 373
147 136 175 197 304 375 380
148 3
149 29 143 160 249 367 386
150 30 353 361 369
151 271 277 289 317 376
152 109 214 349
153 131 139 299 384
154 12 18 245
155 44 199
156 39 89 222 255 258 348 359
157 75 116 287 310
158 154 159 190 245 311 343
159 153 158 190 232 299 384
160 29 66 214 367
161 34 81 186 336
162 313 374
163 33 102 135 271
164 20 24 37 189
165 38 96 335
166 255 284 316 353 369
167 70 259 370
168 104 267 314 327 390
169 152 199 214 264 293
170 31 67 76 94 279
171 24 144 164 323
172 69 275 280 351 355
173 58 86 145 248 265
174 88 154 212 279
175 147 262 306 372
176 9 239 252 291 326
177 45 54 251
178 74 134 261 270 278
179 74 111 202 333
180 165 239
181 334 385
182 26 216 247 268 281
183 93 203 267 314
184 52 70 143
185 34 36 78 187 338 387
186 68 81 161 303 328 350
187 21 78 262 371
188 134 178 210 248 265 278
189 20 47 55 164 346
190 159 324
191 42 308 379
192 46 62 137 206
193 2 47 85 322 382
194 86 325 354
195 229 263 326 356
196 101 242 334
197 115 147 221 304
198 36 81 142 228 338
199 82 155 264 293
200 10 182 227 268
201 63 120 192 222 389
202 23 51 179 217 278 300 302 315
203 72 93 146
204 95
205 180 239 360
206 46 192 215 331 347
207 102 172 339 341 355
208 22 66 280 329 367
209 52 302 315 344
210 23 125 188 265 278
211 50 115 123 345
212 60 279 377
213 24 171 218 275 339
214 29 66 148 264
215 89 331
216 54 247 389
217 74 178 179 202
218 171 213 281 339
219 93 167 183 259 267
220 2 28 48 114
221 115 304
222 39 62 120 201
223 40 71 162 250 313
224 14 53 229 319
225 62 89 156 206 215 222
226 10 33 49 110
227 10 182 269 281
228 142 150 198 290 368
229 14 195 263 285 326
230 73 167 300 309 344 370
231 5 35 87 295
232 140 159 191 305 308 384
233 101 196 288 349
234 155 199 390
235 34 98 124 387
236 77 141 356
237 22 276 318 351 367
238 17 59 117 138 289
239 84 127 180 205 291
240 75 273
241 158 159 232
242 11 15 109 113 196
243 1 58 118 146 354
244 7 15 113 383
245 27 41 154 158
246 127 176 239 362
247 57 182 216 268
248 134 188
249 19 105 149 184
250 71 223
251 2 45 177 340
252 6 176 195 326
253 10 32 49 200 226
254 82 267 390
255 89 126 156 166 316 348
256 59 107 337
257 82 199 234 390
258 316 345 348 359
259 70 267 282
260 90 141 298 306 307
261 28 48 74
262 175 185 187 371 380
263 14 162
264 82 388
265 125 173 188 248
266 56 163 329 355
267 168 219 274 314 390
268 32 247 253
269 218 281 341
270 28 134 178 261
271 33 56 151 163 277
272 28 119 139 270
273 75 240 289 376
274 254 259 282
275 8 24 37 69 213
276 20 99 283 318
277 56 271 317 383
278 23 188 202 217
279 31 106 174
280 22 329
281 26 227 323
282 254 259 274 388
283 19 20 99 105 276 302
284 103 126 166 255 321 369
285 224
286 13 147 337 375
287 75 116
288 53 196 233 381
289 4 7 238 317 383
290 61
291 176 205
292 8 130 275
293 44 155 349
294 296
295 87 96 133 180 205 231 294 360
296 303 336
297 204 305
298 13 136 141 363 375
299 134 159 190 248 324
300 23 230
301 13 77 223 250 256 298
302 19 52 202 209
303 92 112 186 296 377
304 21 197
305 95 140 232 297
306 98 260 307 363 372
307 260 298 306 363
308 305
309 125 243 300 370 378
310 25 33 110 157
311 154 158 241
312 284 320 321
313 40 162 381
314 104 128 168 183 267
315 73 202 209 300
316 258 348 353
317 383
318 8 20
319 104 168 224 285 362
320 76 312 321 342 366
321 284 320 331 342
322 26 43 47 193
323 26 144 218 281
324 86 173 190 299 343
325 38 194 335 354
326 195 246 252 285 362
327 53 224 319 390
328 112 161 303
329 79 80 266 355
330 108 321 331 342 347
331 126 321 330 347
332 370 373 378
333 20 55 179 202 283 302 346
334 7 15 181 196 385
335 325
336 112 124 235
337 13 17 256 286
338 81 161 185 198
339 213 218 269 341
340 2 121 177 220
341 10 207 227 269
342 42 108 170 320 330
343 41 86 190 324
344 73 167 209
345 211 316 353 359
346 20 55 189 333
347 46 206 331
348 258 316
349 44 101 169 233 288 293
350 68 186 212 377
351 22 237 280
352 21 30 50 78 123 304 361 368
353 122 150 166 211 316
354 86 243 325 357
355 102 163 266 280 329
356 6 124 195 236
357 146 165 243 325 335 354
358 294 296 336 365
359 49 116 156
360 205 291 294 358 365
361 30 50 122 352
362 285 319 326
363 136 175
364 93 167 219 370
365 6 9 124 291 358
366 61 76 290 320
367 22 66 83 149 208 249
368 30 36 78 352
369 166 228 353
370 167 309 373 378
371 21 147 262 304 380
372 98 175 185 262 387
373 93 118 146 332 364 378
374 77 195 236 263 356
375 13 136 147 286 298
376 25 151 271 273 289
377 35 186 303
378 118 332 373
379 42 94 232 241 311
380 175 262 371
381 14 40 53 313
382 48 193
383 7 56 317
384 95 139 159 232
385 7 59 71 181 238 289
386 70 388
387 98 185 235 372
388 82 386
389 54 63 120 201
390 53 168 234 267 | 18.674359 | 36 | 0.731155 |
ed80e6ee07bf49ab901fba773158d2f3f943ce6a | 6,117 | pm | Perl | perun-cli/Perun/beans/Publication.pm | ondrejvelisek/perun | 585dba97fb6aaacd9478084578a4217911205a55 | [
"BSD-2-Clause"
]
| null | null | null | perun-cli/Perun/beans/Publication.pm | ondrejvelisek/perun | 585dba97fb6aaacd9478084578a4217911205a55 | [
"BSD-2-Clause"
]
| null | null | null | perun-cli/Perun/beans/Publication.pm | ondrejvelisek/perun | 585dba97fb6aaacd9478084578a4217911205a55 | [
"BSD-2-Clause"
]
| null | null | null | package Perun::beans::Publication;
use strict;
use warnings;
use Perun::Common;
use overload
'""' => \&toString;
sub toString {
my $self = shift;
my @authors = $self->{_authors};
my $rank = $self->{_rank};
my $id = $self->{_id};
my $externalId = $self->{_externalId};
my $publicationSystemId = $self->{publicationSystemId};
my $title = $self->{_title};
my $year = $self->{_year};
my $main = $self->{_main};
my $isbn = $self->{_isbn};
my $categoryId = $self->{_categoryId};
my $createdBy = $self->{_createdBy};
my $createdDate = $self->{_createdDate};
my $doi = $self->{_doi};
my $locked = $self->{_locked};
my $str = 'Publication (';
$str .= "authors: @authors, " if (@authors);
$str .= "rank: $rank, " if ($rank);
$str .= "id: $id" if ($id);
$str .= "externalId: $externalId" if ($externalId);
$str .= "publicationSystemId: $publicationSystemId" if ($publicationSystemId);
$str .= "title: $title" if ($title);
$str .= "year: $year" if ($year);
$str .= "main: $main" if ($main);
$str .= "isbn: $isbn" if ($isbn);
$str .= "categoryId: $categoryId" if ($categoryId);
$str .= "createdBy: $createdBy" if ($createdBy);
$str .= "createdDate: $createdDate" if ($createdDate);
$str .= "doi: $doi" if ($doi);
$str .= "locked: $locked" if ($locked);
$str .= ')';
return $str;
}
sub new
{
bless({});
}
sub fromHash
{
my $publication = Perun::Common::fromHash(@_);
for my $author (@{$publication->{_authors}}) {
$author = Perun::beans::Author::fromHash("Perun::beans::Author", $author);
}
return $publication;
}
sub TO_JSON
{
my $self = shift;
my $id;
if (defined($self->{_id})) {
$id = $self->{_id} * 1;
} else {
$id = 0;
}
my $title;
if (defined($self->{_title})) {
$title = "$self->{_title}";
} else {
$title = undef;
}
my $rank;
if (defined($self->{_rank})) {
$rank = $self->{_rank} * 1;
} else {
$rank = undef;
}
my $externalId;
if (defined($self->{_externalId})) {
$externalId = $self->{_externalId} * 1;
} else {
$externalId = undef;
}
my $publicationSystemId;
if (defined($self->{_publicationSystemId})) {
$publicationSystemId = $self->{_publicationSystemId} * 1;
} else {
$publicationSystemId = undef;
}
my $year;
if (defined($self->{_year})) {
$year = $self->{_year} * 1;
} else {
$year = undef;
}
my $categoryId;
if (defined($self->{_categoryId})) {
$categoryId = $self->{_categoryId} * 1;
} else {
$categoryId = undef;
}
my $main;
if (defined($self->{_main})) {
$main = "$self->{_main}";
} else {
$main = undef;
}
my $isbn;
if (defined($self->{_isbn})) {
$isbn = "$self->{_isbn}";
} else {
$isbn = undef;
}
my $createdBy;
if (defined($self->{_createdBy})) {
$createdBy = "$self->{_createdBy}";
} else {
$createdBy = undef;
}
my $createdDate;
if (defined($self->{_createdDate})) {
$createdDate = "$self->{_createdDate}";
} else {
$createdDate = undef;
}
my $doi;
if (defined($self->{_doi})) {
$doi = "$self->{_doi}";
} else {
$doi = undef;
}
my $locked;
if (defined($self->{_locked})) {
$locked = $self->{_locked} * 1;
} else {
$locked = undef;
}
my @authors;
if (defined($self->{_authors})) {
@authors = $self->{_authors} * 1;
} else {
@authors = undef;
}
return { id => $id, title => $title, rank => $rank, externalId => $externalId,
publicationSystemId => $publicationSystemId, year => $year, isbn => $isbn, main => $main, categoryId =>
$categoryId, createdBy => $createdBy, createdDate => $createdDate, doi => $doi, locked => $locked, authors
=> \@authors };
}
sub getId
{
my $self = shift;
return $self->{_id};
}
sub setId
{
my $self = shift;
$self->{_id} = shift;
return;
}
sub getTitle
{
my $self = shift;
return $self->{_title};
}
sub setTitle
{
my $self = shift;
$self->{_title} = shift;
return;
}
sub getRank
{
my $self = shift;
return $self->{_rank};
}
sub setRank
{
my $self = shift;
$self->{_rank} = shift;
return;
}
sub getExternalId
{
my $self = shift;
return $self->{_externalId};
}
sub setExternalId
{
my $self = shift;
$self->{_externalId} = shift;
return;
}
sub getPublicationSystemId
{
my $self = shift;
return $self->{_publicationSystemId};
}
sub setPublicationSystemId
{
my $self = shift;
$self->{_publicationSystemId} = shift;
return;
}
sub getYear
{
my $self = shift;
return $self->{_year};
}
sub setYear
{
my $self = shift;
$self->{_year} = shift;
return;
}
sub getMain
{
my $self = shift;
return $self->{_main};
}
sub setMain
{
my $self = shift;
$self->{_main} = shift;
return;
}
sub getIsbn
{
my $self = shift;
return $self->{_isbn};
}
sub setIsbn
{
my $self = shift;
$self->{_isbn} = shift;
return;
}
sub getCategoryId
{
my $self = shift;
return $self->{_categoryId};
}
sub setCategoryId
{
my $self = shift;
$self->{_categoryId} = shift;
return;
}
sub getCreatedBy
{
my $self = shift;
return $self->{_createdBy};
}
sub setCreatedBy
{
my $self = shift;
$self->{_createdBy} = shift;
return;
}
sub getCreatedDate
{
my $self = shift;
return $self->{_createdDate};
}
sub setCreatedDate
{
my $self = shift;
$self->{_createdDate} = shift;
return;
}
sub getDoi
{
my $self = shift;
return $self->{_doi};
}
sub setDoi
{
my $self = shift;
$self->{_doi} = shift;
return;
}
sub getLocked
{
my $self = shift;
return $self->{_locked};
}
sub setLocked
{
my $self = shift;
$self->{_locked} = shift;
return;
}
sub getAuthors
{
my $self = shift;
return @{$self->{_authors}};
}
#return '["' . join('", "', @$value) . '"]'
sub printAuthors
{
my $self = shift;
my @authors = $self->getAuthors;
my @result;
foreach my $author (@authors) {
push @result, $author->getFirstName.' '.$author->getLastName;
}
return '['.join(', ', @result).']';
}
sub getCommonArrayRepresentation {
my $self = shift;
return ($self->getId, $self->getTitle, $self->getRank, $self->getYear, $self->getCategoryId, $self->getLocked,
$self->printAuthors);
}
sub getCommonArrayRepresentationHeading {
return ('ID', 'Name', 'Rank', 'Year', 'Category ID', 'Locked', 'Authors');
}
1;
| 15.44697 | 112 | 0.597025 |
ed20f6d721654d55f71291718c00ecc0da55b245 | 209 | pm | Perl | auto-lib/Azure/ServiceFabricData/ServicePlacementRequireDomainDistributionPolicyDescription.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Azure/ServiceFabricData/ServicePlacementRequireDomainDistributionPolicyDescription.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| null | null | null | auto-lib/Azure/ServiceFabricData/ServicePlacementRequireDomainDistributionPolicyDescription.pm | pplu/azure-sdk-perl | 26cbef2d926f571bc1617c26338c106856f95568 | [
"Apache-2.0"
]
| 1 | 2021-04-08T15:26:39.000Z | 2021-04-08T15:26:39.000Z | package Azure::ServiceFabricData::ServicePlacementRequireDomainDistributionPolicyDescription;
use Moose;
has 'Type' => (is => 'ro', isa => 'Str' );
has 'DomainName' => (is => 'ro', isa => 'Str' );
1;
| 29.857143 | 93 | 0.650718 |
ed80516d48f1c3571a4b5184d6284184d41b9e29 | 776 | pl | Perl | Perl/InlineCPP/Hash/UseMacro/main.pl | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
]
| null | null | null | Perl/InlineCPP/Hash/UseMacro/main.pl | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
]
| null | null | null | Perl/InlineCPP/Hash/UseMacro/main.pl | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
]
| null | null | null | use Inline CPP => Config => LIBS => '-L/lib/gcc/i686-pc-cygwin/3.4.4 /cygdrive/d/PersonalTool/xyzzy/laboratory/Perl/InlineCPP/Include/ -lmylib -lstdc++ -lMacro',
INC => '-I/cygdrive/d/PersonalTool/xyzzy/laboratory/Perl/InlineCPP/Include';
# INC => '-I/D:/PersonalTool/xyzzy/laboratory/Perl/InlineCPP/Include/';
use Inline CPP => <<'END_OF_CPP';
#include <iostream>
#include "Macro.hpp"
HV* convertHash() {
Test test;
test.integer = 10;
// {HV* hash = newHV();
// hv_store(hash, "key", strlen("key"), newSViv(test.integer), 0);
// return hash;};
createHash(test);
}
int getBiger() {
getBig(1, 2);
}
END_OF_CPP
print convertHash->{'key'};
#print getBiger();
| 28.740741 | 162 | 0.585052 |
ed4995f4b0a5a0be7ba84c8307fcad4c33b3138d | 3,304 | pm | Perl | cloud/google/gcp/compute/computeengine/mode/discovery.pm | petneli/centreon-plugins | d131e60a1859fdd0e959623de56e6e7512c669af | [
"Apache-2.0"
]
| 316 | 2015-01-18T20:37:21.000Z | 2022-03-27T00:20:35.000Z | cloud/google/gcp/compute/computeengine/mode/discovery.pm | petneli/centreon-plugins | d131e60a1859fdd0e959623de56e6e7512c669af | [
"Apache-2.0"
]
| 2,333 | 2015-04-26T19:10:19.000Z | 2022-03-31T15:35:21.000Z | cloud/google/gcp/compute/computeengine/mode/discovery.pm | petneli/centreon-plugins | d131e60a1859fdd0e959623de56e6e7512c669af | [
"Apache-2.0"
]
| 371 | 2015-01-18T20:37:23.000Z | 2022-03-22T10:10:16.000Z | #
# 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::google::gcp::compute::computeengine::mode::discovery;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use JSON::XS;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {
'prettify' => { name => 'prettify' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
}
sub run {
my ($self, %options) = @_;
my $disco_data;
my $disco_stats;
$disco_stats->{start_time} = time();
my $instances = $options{custom}->gcp_list_compute_engine_instances();
foreach my $instance (@$instances) {
my $item = {};
$item->{id} = $instance->{id};
$item->{name} = $instance->{name};
$item->{description} = $instance->{description};
$item->{status} = $instance->{status};
$item->{cpu_platform} = $instance->{cpuPlatform};
if ($instance->{machineType} =~ /machineTypes\/(.*?)$/) {
$item->{machine_type} = $1;
}
if ($instance->{zone} =~ /zones\/(.*?)$/) {
$item->{zone} = $1;
}
$item->{network_interfaces} = [];
foreach (@{$instance->{networkInterfaces}}) {
push @{$item->{network_interfaces}}, { name => $_->{name}, ip => $_->{networkIP} };
}
$item->{tags} = [];
if (defined($instance->{tags}->{items})) {
push @{$item->{tags}}, @{$instance->{tags}->{items}};
}
push @$disco_data, $item;
}
$disco_stats->{end_time} = time();
$disco_stats->{duration} = $disco_stats->{end_time} - $disco_stats->{start_time};
$disco_stats->{discovered_items} = scalar(@$disco_data);
$disco_stats->{results} = $disco_data;
my $encoded_data;
eval {
if (defined($self->{option_results}->{prettify})) {
$encoded_data = JSON::XS->new->utf8->pretty->encode($disco_stats);
} else {
$encoded_data = JSON::XS->new->utf8->encode($disco_stats);
}
};
if ($@) {
$encoded_data = '{"code":"encode_error","message":"Cannot encode discovered data into JSON format"}';
}
$self->{output}->output_add(short_msg => $encoded_data);
$self->{output}->display(nolabel => 1, force_ignore_perfdata => 1);
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Compute engine discovery.
=over 8
=item B<--prettify>
Prettify JSON output.
=back
=cut
| 27.764706 | 109 | 0.603511 |
ed6af2de3263768e40389c61ff1e20d93e6b3fe9 | 27,692 | pm | Perl | test/lib/pgBackRestTest/Env/Host/HostDbSyntheticTest.pm | jreidthompson/pgbackrest | 8babd558bc3a5b930fd096ffb306551773f1f14d | [
"MIT"
]
| null | null | null | test/lib/pgBackRestTest/Env/Host/HostDbSyntheticTest.pm | jreidthompson/pgbackrest | 8babd558bc3a5b930fd096ffb306551773f1f14d | [
"MIT"
]
| null | null | null | test/lib/pgBackRestTest/Env/Host/HostDbSyntheticTest.pm | jreidthompson/pgbackrest | 8babd558bc3a5b930fd096ffb306551773f1f14d | [
"MIT"
]
| null | null | null | ####################################################################################################################################
# HostDbTest.pm - Database host
####################################################################################################################################
package pgBackRestTest::Env::Host::HostDbSyntheticTest;
use parent 'pgBackRestTest::Env::Host::HostDbCommonTest';
####################################################################################################################################
# Perl includes
####################################################################################################################################
use strict;
use warnings FATAL => qw(all);
use Carp qw(confess);
use Exporter qw(import);
our @EXPORT = qw();
use Fcntl ':mode';
use File::Basename qw(basename dirname);
use File::stat;
use pgBackRestDoc::Common::Exception;
use pgBackRestDoc::Common::Log;
use pgBackRestDoc::Common::String;
use pgBackRestDoc::ProjectInfo;
use pgBackRestTest::Common::ContainerTest;
use pgBackRestTest::Common::DbVersion;
use pgBackRestTest::Common::FileTest;
use pgBackRestTest::Common::RunTest;
use pgBackRestTest::Common::StorageRepo;
use pgBackRestTest::Common::Wait;
use pgBackRestTest::Env::Host::HostBackupTest;
use pgBackRestTest::Env::Host::HostBaseTest;
use pgBackRestTest::Env::Host::HostDbCommonTest;
use pgBackRestTest::Env::Manifest;
####################################################################################################################################
# new
####################################################################################################################################
sub new
{
my $class = shift; # Class name
# Assign function parameters, defaults, and log debug info
my
(
$strOperation,
$oParam,
) =
logDebugParam
(
__PACKAGE__ . '->new', \@_,
{name => 'oParam', required => false, trace => true},
);
my $self = $class->SUPER::new(
{
strImage => containerRepo() . ':' . testRunGet()->vm() . "-test",
bTls => $oParam->{bTls},
strBackupDestination => $$oParam{strBackupDestination},
bSynthetic => true,
bStandby => $$oParam{bStandby},
bRepoLocal => $oParam->{bRepoLocal},
bRepoEncrypt => $oParam->{bRepoEncrypt},
});
bless $self, $class;
# Return from function and log return values if any
return logDebugReturn
(
$strOperation,
{name => 'self', value => $self, trace => true}
);
}
####################################################################################################################################
# dbFileCreate
#
# Create a file specifying content, mode, and time.
####################################################################################################################################
sub dbFileCreate
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strFile = shift;
my $strContent = shift;
my $lTime = shift;
my $strMode = shift;
# Check that strTarget is a valid
my $strPath = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_PATH};
if (!defined($strPath))
{
confess &log(ERROR, "${strTarget} not a valid target: \n" . Dumper(${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}));
}
# Get tablespace path if this is a tablespace
my $strPgPath;
if (index($strTarget, DB_PATH_PGTBLSPC . '/') == 0)
{
my $iCatalog = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_CATALOG};
$strPgPath = 'PG_' . ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_DB_VERSION} . "_${iCatalog}";
}
# Create actual file location
my $strPathFile = $strPath .
(defined($strPgPath) ? "/${strPgPath}" : '') . "/${strFile}";
if (index($strPathFile, '/') != 0)
{
$strPathFile = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{&MANIFEST_TARGET_PGDATA}{&MANIFEST_SUBKEY_PATH} . '/' .
(defined(dirname($strPathFile)) ? dirname($strPathFile) : '') . "/${strPathFile}";
}
# Create the file
testFileCreate($strPathFile, $strContent, $lTime, $strMode);
# Return path to created file
return $strPathFile;
}
####################################################################################################################################
# dbFileRemove
####################################################################################################################################
sub dbFileRemove
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strFile = shift;
my $bIgnoreMissing = shift;
# Get actual path location
my $strDbFile = $self->manifestDbPathGet($oManifestRef, $strTarget, $strFile);
# Remove the file
if (!(defined($bIgnoreMissing) && $bIgnoreMissing && !(-e $strDbFile)))
{
testFileRemove($strDbFile);
}
return $strDbFile;
}
####################################################################################################################################
# dbLinkCreate
#
# Create a file specifying content, mode, and time.
####################################################################################################################################
sub dbLinkCreate
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strFile = shift;
my $strDestination = shift;
# Create actual file location
my $strDbFile = $self->manifestDbPathGet($oManifestRef, $strTarget, $strFile);
# Create the file
testLinkCreate($strDbFile, $strDestination);
# Return path to created file
return $strDbFile;
}
####################################################################################################################################
# manifestDbPathGet
#
# Get the db path based on the target and file passed.
####################################################################################################################################
sub manifestDbPathGet
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strFile = shift;
# Determine the manifest key
my $strDbPath = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_PATH};
# If target is a tablespace
if (defined(${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_TABLESPACE_ID}))
{
my $iCatalog = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_CATALOG};
$strDbPath .= '/PG_' . ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_DB_VERSION} . "_${iCatalog}";
}
$strDbPath .= defined($strFile) ? "/${strFile}" : '';
return $strDbPath;
}
####################################################################################################################################
# manifestFileCreate
#
# Create a file specifying content, mode, and time and add it to the manifest.
####################################################################################################################################
sub manifestFileCreate
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strFile = shift;
my $strContent = shift;
my $strChecksum = shift;
my $lTime = shift;
my $strMode = shift;
my $bPrimary = shift;
my $strChecksumPageError = shift;
# Determine the manifest key
my $strManifestKey = $self->manifestKeyGet($oManifestRef, $strTarget, $strFile);
# Create the file
my $strPathFile = $self->dbFileCreate($oManifestRef, $strTarget, $strFile, $strContent, $lTime, $strMode);
# Stat the file
my $oStat = lstat($strPathFile);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_GROUP} = getgrgid($oStat->gid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_USER} = getpwuid($oStat->uid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_MODE} =
sprintf('%04o', S_IMODE($oStat->mode));
${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_TIMESTAMP} = $oStat->mtime;
${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_SIZE} = $oStat->size;
delete(${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_REFERENCE});
my $bChecksumPage = defined($strChecksumPageError) ? false : (isChecksumPage($strManifestKey) ? true : undef);
if (defined($bChecksumPage))
{
$oManifestRef->{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_CHECKSUM_PAGE} =
$bChecksumPage ? JSON::PP::true : JSON::PP::false;
if (!$bChecksumPage && $strChecksumPageError ne '0')
{
my @iyChecksumPageError = eval($strChecksumPageError);
$oManifestRef->{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_CHECKSUM_PAGE_ERROR} =
\@iyChecksumPageError;
}
else
{
delete($oManifestRef->{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{&MANIFEST_SUBKEY_CHECKSUM_PAGE_ERROR});
}
}
if (defined($strChecksum))
{
${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey}{checksum} = $strChecksum;
}
}
####################################################################################################################################
# manifestFileRemove
#
# Remove a file from disk and (optionally) the manifest.
####################################################################################################################################
sub manifestFileRemove
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strFile = shift;
# Determine the manifest key
my $strManifestKey = $self->manifestKeyGet($oManifestRef, $strTarget, $strFile);
# Remove the file
$self->dbFileRemove($oManifestRef, $strTarget, $strFile, true);
# Remove from manifest
delete(${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey});
}
####################################################################################################################################
# manifestKeyGet
#
# Get the manifest key based on the target and file/path/link passed.
####################################################################################################################################
sub manifestKeyGet
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strFile = shift;
# Determine the manifest key
my $strManifestKey = $strTarget;
# If target is a tablespace
if (defined(${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_TABLESPACE_ID}))
{
my $iCatalog = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_CATALOG};
$strManifestKey .= '/PG_' . ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_DB_VERSION} . "_${iCatalog}";
}
$strManifestKey .= (defined($strFile) ? "/$strFile" : '');
return $strManifestKey;
}
####################################################################################################################################
# manifestLinkCreate
#
# Create a link and add it to the manifest.
####################################################################################################################################
sub manifestLinkCreate
{
my $self = shift;
my $oManifestRef = shift;
my $strPath = shift;
my $strFile = shift;
my $strDestination = shift;
my $bPrimary = shift;
# Determine the manifest key
my $strManifestKey = $self->manifestKeyGet($oManifestRef, $strPath, $strFile);
# Load target
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strManifestKey}{&MANIFEST_SUBKEY_PATH} = $strDestination;
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strManifestKey}{&MANIFEST_SUBKEY_TYPE} = MANIFEST_VALUE_LINK;
# Create the link
my $strDbFile = $self->dbLinkCreate($oManifestRef, $strPath, $strFile, $strDestination);
# Stat the link
my $oStat = lstat($strDbFile);
# Check for errors in stat
if (!defined($oStat))
{
confess 'unable to stat ${strDbFile}';
}
# Load file into manifest
${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{$strManifestKey}{&MANIFEST_SUBKEY_GROUP} = getgrgid($oStat->gid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{$strManifestKey}{&MANIFEST_SUBKEY_USER} = getpwuid($oStat->uid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{$strManifestKey}{&MANIFEST_SUBKEY_DESTINATION} = $strDestination;
# Stat what the link is pointing to
my $strDestinationFile = $strDestination;
if (index($strDestinationFile, '/') != 0)
{
$strDestinationFile = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{&MANIFEST_TARGET_PGDATA}{&MANIFEST_SUBKEY_PATH} . '/' .
(defined(dirname($strPath)) ? dirname($strPath) : '') . "/${strDestination}";
}
$oStat = lstat($strDestinationFile);
my $strSection = MANIFEST_SECTION_TARGET_PATH;
if (S_ISREG($oStat->mode))
{
$strSection = MANIFEST_SECTION_TARGET_FILE;
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_SIZE} = $oStat->size;
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_TIMESTAMP} = $oStat->mtime;
(${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_CHECKSUM}) = storageTest()->hashSize($strDestinationFile);
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strManifestKey}{&MANIFEST_SUBKEY_FILE} =
basename(${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strManifestKey}{&MANIFEST_SUBKEY_PATH});
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strManifestKey}{&MANIFEST_SUBKEY_PATH} =
dirname(${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strManifestKey}{&MANIFEST_SUBKEY_PATH});
}
# Allow a link to a link to be created to test that backrest errors out correctly
elsif (S_ISLNK($oStat->mode))
{
$strSection = MANIFEST_SECTION_TARGET_LINK;
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_DESTINATION} = $strDestination;
}
elsif (!S_ISDIR($oStat->mode))
{
confess &log(ASSERT, "unrecognized file type for file $strDestinationFile");
}
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_GROUP} = getgrgid($oStat->gid);
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_USER} = getpwuid($oStat->uid);
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_MODE} = sprintf('%04o', S_IMODE($oStat->mode));
}
####################################################################################################################################
# manifestLinkMap
#
# Remap links to new directories/files
####################################################################################################################################
sub manifestLinkMap
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strDestination = shift;
if ($$oManifestRef{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_TYPE} ne MANIFEST_VALUE_LINK)
{
confess "cannot map target ${strTarget} because it is not a link";
}
if (defined($$oManifestRef{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_TABLESPACE_ID}))
{
confess "tablespace ${strTarget} cannot be remapped with this function";
}
if (defined($strDestination))
{
confess "GENERAL LINK REMAP NOT IMPLEMENTED";
}
else
{
delete($$oManifestRef{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget});
delete($$oManifestRef{&MANIFEST_SECTION_TARGET_LINK}{$strTarget});
}
}
####################################################################################################################################
# manifestLinkRemove
#
# Create a link and add it to the manifest.
####################################################################################################################################
sub manifestLinkRemove
{
my $self = shift;
my $oManifestRef = shift;
my $strPath = shift;
my $strFile = shift;
# Delete the link
my $strDbFile = $self->dbFileRemove($oManifestRef, $strPath, $strFile);
# Determine the manifest key
my $strManifestKey = $self->manifestKeyGet($oManifestRef, $strPath, $strFile);
# Delete from manifest
delete(${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strManifestKey});
delete(${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{$strManifestKey});
delete(${$oManifestRef}{&MANIFEST_SECTION_TARGET_FILE}{$strManifestKey});
delete(${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strManifestKey});
}
####################################################################################################################################
# manifestPathCreate
#
# Create a path specifying mode and add it to the manifest.
####################################################################################################################################
sub manifestPathCreate
{
my $self = shift;
my $oManifestRef = shift;
my $strPath = shift;
my $strSubPath = shift;
my $strMode = shift;
# Determine the manifest key
my $strManifestKey = $self->manifestKeyGet($oManifestRef, $strPath, $strSubPath);
# Create the db path
my $strDbPath = $self->dbPathCreate($oManifestRef, $strPath, $strSubPath, defined($strMode) ? $strMode : '0700');
# Stat the file
my $oStat = lstat($strDbPath);
# Check for errors in stat
if (!defined($oStat))
{
confess 'unable to stat ${strSubPath}';
}
# Load file into manifest
my $strSection = MANIFEST_SECTION_TARGET_PATH;
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_GROUP} = getgrgid($oStat->gid);
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_USER} = getpwuid($oStat->uid);
${$oManifestRef}{$strSection}{$strManifestKey}{&MANIFEST_SUBKEY_MODE} = sprintf('%04o', S_IMODE($oStat->mode));
}
####################################################################################################################################
# manifestReference
#
# Update all files that do not have a reference with the supplied reference.
####################################################################################################################################
sub manifestReference
{
my $self = shift;
my $oManifestRef = shift;
my $strReference = shift;
my $bClear = shift;
# Set prior backup
if (defined($strReference))
{
${$oManifestRef}{&MANIFEST_SECTION_BACKUP}{&MANIFEST_KEY_PRIOR} = $strReference;
}
else
{
delete(${$oManifestRef}{&MANIFEST_SECTION_BACKUP}{&MANIFEST_KEY_PRIOR});
}
# Find all file sections
foreach my $strSectionFile (sort(keys(%$oManifestRef)))
{
# Skip non-file sections
if ($strSectionFile !~ /\:file$/)
{
next;
}
foreach my $strFile (sort(keys(%{${$oManifestRef}{$strSectionFile}})))
{
if (!defined($strReference))
{
delete(${$oManifestRef}{$strSectionFile}{$strFile}{&MANIFEST_SUBKEY_REFERENCE});
}
elsif (defined($bClear) && $bClear)
{
if (defined(${$oManifestRef}{$strSectionFile}{$strFile}{&MANIFEST_SUBKEY_REFERENCE}) &&
${$oManifestRef}{$strSectionFile}{$strFile}{&MANIFEST_SUBKEY_REFERENCE} ne $strReference)
{
delete(${$oManifestRef}{$strSectionFile}{$strFile}{&MANIFEST_SUBKEY_REFERENCE});
}
}
elsif (!defined(${$oManifestRef}{$strSectionFile}{$strFile}{&MANIFEST_SUBKEY_REFERENCE}))
{
${$oManifestRef}{$strSectionFile}{$strFile}{&MANIFEST_SUBKEY_REFERENCE} = $strReference;
}
}
}
}
####################################################################################################################################
# manifestTablespaceCreate
#
# Create a tablespace specifying mode and add it to the manifest.
####################################################################################################################################
sub manifestTablespaceCreate
{
my $self = shift;
my $oManifestRef = shift;
my $iOid = shift;
my $strMode = shift;
# Load linked path into manifest
my $strLinkPath = $self->tablespacePath($iOid);
my $strTarget = MANIFEST_TARGET_PGTBLSPC . "/${iOid}";
my $oStat = lstat($strLinkPath);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strTarget}{&MANIFEST_SUBKEY_GROUP} = getgrgid($oStat->gid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strTarget}{&MANIFEST_SUBKEY_USER} = getpwuid($oStat->uid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strTarget}{&MANIFEST_SUBKEY_MODE} =
sprintf('%04o', S_IMODE($oStat->mode));
# Create the tablespace path if it does not exist
my $strTablespacePath = $strLinkPath;
my $strPathTarget = $strTarget;
my $iCatalog = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_CATALOG};
my $strTablespaceId = 'PG_' . ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_DB_VERSION} . "_${iCatalog}";
$strTablespacePath .= "/${strTablespaceId}";
$strPathTarget .= "/${strTablespaceId}";
if (!-e $strTablespacePath)
{
storageTest()->pathCreate($strTablespacePath, {strMode => defined($strMode) ? $strMode : '0700'});
}
# Load tablespace path into manifest
$oStat = lstat($strTablespacePath);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{&MANIFEST_TARGET_PGTBLSPC} =
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{&MANIFEST_TARGET_PGDATA};
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strPathTarget}{&MANIFEST_SUBKEY_GROUP} = getgrgid($oStat->gid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strPathTarget}{&MANIFEST_SUBKEY_USER} = getpwuid($oStat->uid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strPathTarget}{&MANIFEST_SUBKEY_MODE} =
sprintf('%04o', S_IMODE($oStat->mode));
# Create the link in DB_PATH_PGTBLSPC
my $strLink = $self->dbBasePath() . '/' . DB_PATH_PGTBLSPC . "/${iOid}";
symlink($strLinkPath, $strLink)
or confess "unable to link ${strLink} to ${strLinkPath}";
# Load link into the manifest
$oStat = lstat($strLink);
my $strLinkTarget = MANIFEST_TARGET_PGDATA . "/${strTarget}";
${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{$strLinkTarget}{&MANIFEST_SUBKEY_GROUP} = getgrgid($oStat->gid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{$strLinkTarget}{&MANIFEST_SUBKEY_USER} = getpwuid($oStat->uid);
${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{$strLinkTarget}{&MANIFEST_SUBKEY_DESTINATION} = $strLinkPath;
# Load tablespace target into the manifest
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_PATH} = $strLinkPath;
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_TYPE} = MANIFEST_VALUE_LINK;
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_TABLESPACE_ID} = $iOid;
${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_TABLESPACE_NAME} = "ts${iOid}";
}
####################################################################################################################################
# manifestTablespaceDrop
#
# Drop a tablespace add remove it from the manifest.
####################################################################################################################################
sub manifestTablespaceDrop
{
my $self = shift;
my $oManifestRef = shift;
my $iOid = shift;
my $iIndex = shift;
# Remove tablespace path/file/link from manifest
my $strTarget = DB_PATH_PGTBLSPC . "/${iOid}";
# Remove manifest path, link, target
delete(${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget});
delete(${$oManifestRef}{&MANIFEST_SECTION_TARGET_LINK}{&MANIFEST_TARGET_PGDATA . "/${strTarget}"});
delete(${$oManifestRef}{&MANIFEST_SECTION_TARGET_PATH}{$strTarget});
# Remove nested manifest files and paths
foreach my $strSection (&MANIFEST_SECTION_TARGET_PATH, &MANIFEST_SECTION_TARGET_FILE)
{
foreach my $strFile (keys(%{${$oManifestRef}{$strSection}}))
{
if (index($strFile, "${strTarget}/") == 0)
{
delete($$oManifestRef{$strSection}{$strFile});
}
}
}
# Drop the link in DB_PATH_PGTBLSPC
testFileRemove($self->dbBasePath($iIndex) . "/${strTarget}");
}
####################################################################################################################################
# dbPathCreate
#
# Create a path specifying mode.
####################################################################################################################################
sub dbPathCreate
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strSubPath = shift;
my $strMode = shift;
# Create final file location
my $strFinalPath = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_TARGET}{$strTarget}{&MANIFEST_SUBKEY_PATH};
# Get tablespace path if this is a tablespace
if (index($strTarget, DB_PATH_PGTBLSPC . '/') == 0)
{
my $iCatalog = ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_CATALOG};
$strFinalPath .= '/PG_' . ${$oManifestRef}{&MANIFEST_SECTION_BACKUP_DB}{&MANIFEST_KEY_DB_VERSION} . "_${iCatalog}";
}
$strFinalPath .= (defined($strSubPath) ? "/${strSubPath}" : '');
# Create the path
if (!(-e $strFinalPath))
{
storageTest()->pathCreate($strFinalPath, {strMode => $strMode});
}
return $strFinalPath;
}
####################################################################################################################################
# dbPathMode
#
# Change the mode of a path.
####################################################################################################################################
sub dbPathMode
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strPath = shift;
my $strMode = shift;
# Get the db path
my $strDbPath = $self->manifestDbPathGet($oManifestRef, $strTarget, $strPath);
testPathMode($strDbPath, $strMode);
return $strDbPath;
}
####################################################################################################################################
# dbPathRemove
#
# Remove a path.
####################################################################################################################################
sub dbPathRemove
{
my $self = shift;
my $oManifestRef = shift;
my $strTarget = shift;
my $strPath = shift;
# Get the db path
my $strDbPath = $self->manifestDbPathGet($oManifestRef, $strTarget, $strPath);
# Create the path
testPathRemove($strDbPath);
return $strDbPath;
}
1;
| 38.568245 | 135 | 0.539867 |
ed751a226a758e6277b238ed514e3030a6775040 | 6,267 | pm | Perl | tools/adobe/Codex2.pm | brycelelbach/asl | df0d271f6c67fbb944039a9455c4eb69ae6df141 | [
"MIT"
]
| 4 | 2015-10-02T17:31:56.000Z | 2019-04-17T00:54:15.000Z | tools/adobe/Codex2.pm | brycelelbach/asl | df0d271f6c67fbb944039a9455c4eb69ae6df141 | [
"MIT"
]
| null | null | null | tools/adobe/Codex2.pm | brycelelbach/asl | df0d271f6c67fbb944039a9455c4eb69ae6df141 | [
"MIT"
]
| null | null | null | # =========================================================================
# Formatting: Expand tabs, 4 spaces per indent level.
# =========================================================================
=pod
=head1 NAME
Adobe::Codex2 - Perl interface to Codex 2.0 system.
=head1 SYNOPSIS
use Adobe::Codex2;
my $Codex = Adobe::Codex2->new();
my @productlist = $Codex->GetProducts();
...
=head1 DESCRIPTION
Adobe::Codex2 is the main module to use for working with the Codex 2.0 system.
This is the only Adobe::Codex2 module you'll need to include in your scripts;
the rest of the files in the Adobe/Codex/... tree are used indirectly by the
main module.
However, you will want to look at the POD for the other modules in the tree,
since all the methods are documented in those modules.
=head2 CALLING CONVENTIONS
There is a 1:1 mapping between the methods in the Codex WSDL and the methods
in the Perl module. This includes the arguments; the names of the attributes
and elements in the WSDL are used as the argument names for the Perl methods.
For example, here is the XML for the GetContacts request and response:
<xs:element name="GetContactsRequest">
<xs:complexType>
<xs:sequence maxOccurs="1" minOccurs="1">
<xs:element ref="schemas:versionname"/>
<xs:element ref="schemas:productname"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="GetContactsResponse">
<xs:complexType>
<xs:sequence maxOccurs="1" minOccurs="1">
<xs:element ref="schemas:contactlist"/>
<xs:element minOccurs="0" ref="schemas:performancedata"/>
</xs:sequence>
</xs:complexType>
</xs:element>
And here is the Perl method:
my @contactlist = $Codex->GetContacts(productname => $ProductName,
versionname => $VersionName);
Remember that named arguments can be put in the call in any order.
In general, all arguments are required for all methods. If you want to
use an empty value for an argument, pass in an empty string ("").
=head2 RETURN DATA
In general, return data will be one of the following:
"operationresult" = boolean value, expressed as the string "true"
or "false". This is most often returned from "delete" methods that
remove an item from the Codex DB.
ID value = integer. This is most often returned from "add" methods
that insert a new item in the Codex DB.
Data = hash. This is what you'll mostly get from Codex methods.
The hash keys will map to the return data names in the WSDL.
List = array of data hash references. This is what you'll get when
you call most of the "Get" methods that work on an entire set of
items (e.g., "GetProducts").
All the Codex calls also return "performancedata" with data about how long
the call took to run. This data is currently discarded by the Perl module.
=head1 VARIABLES/CONFIGURATION
$DEBUG = 1/0 (on/off), default is 0 (off).
Print debugging information. Currently this just prints the SOAP
request and response XML. This needs to be set before you create
the Codex2 object.
$TIMEOUT = 180
Sets timeout for LWP::UserAgent calls to Codex. Default is 180
seconds, the same as the internal default in LWP::UserAgent.
=head1 DEPENDENCIES
In an attempt to placate those who don't want to install any extra modules in
their Perl distribution, this module depends on very few other modules. With
the exception of XML::Parser, all of these should be included in a base Perl
distribution:
HTTP::Headers;
HTTP::Request;
LWP::UserAgent;
XML::Parser
And of course, it also depends on the entire Adobe::Codex2::* module tree.
=head1 SUBROUTINES/METHODS
=cut
# -------------------------------------------------------------------------
# Module setup.
# -------------------------------------------------------------------------
package Adobe::Codex2;
require 5.8.0;
use strict;
use warnings;
use base qw(Exporter);
our $VERSION = "0.2.0";
our @ISA = qw(Adobe::Codex2::Build
Adobe::Codex2::Metadata);
our @EXPORT = qw();
our @EXPORT_OK = qw($DEBUG
$TIMEOUT);
our %EXPORT_TAGS = ();
# Get Perl modules.
# None.
# Get Codex modules.
use Adobe::Codex2::Build;
use Adobe::Codex2::Metadata;
use Adobe::Codex2::SOAP;
# -------------------------------------------------------------------------
# Module variables.
# -------------------------------------------------------------------------
our $DEBUG = 0;
our $TIMEOUT = 180;
# -------------------------------------------------------------------------
=pod
=head2 new
Create new Codex object.
Usage:
my $Codex = Adobe::Codex2->new($Server);
Input:
$Server = FQDN for Codex server (optional).
Output:
success = Codex object.
failure = undef or die() with error text.
Notes:
* Default $Server value is "codex.corp.adobe.com:8080".
=cut
# -------------------------------------------------------------------------
sub new
{
# Get arguments.
my $Class = shift;
my $Server = shift;
# Check arguments.
$Server = "codex.corp.adobe.com:8080" unless (defined $Server);
# Service endpoint.
my $Service = "http://$Server/codex/services";
# Set up object.
my $Self = {};
bless $Self, ref($Class) || $Class;
# Set values in SOAP module.
$Adobe::Codex2::SOAP::DEBUG = $DEBUG;
$Adobe::Codex2::SOAP::SERVICE = $Service;
$Adobe::Codex2::SOAP::TIMEOUT = $TIMEOUT;
# Return object.
return $Self;
}
# -------------------------------------------------------------------------
=pod
=head2 DESTROY
Object destructor.
Called automatically when object goes out of scope; should not be
called directly by user.
=cut
# -------------------------------------------------------------------------
sub DESTROY
{
# Get arguments.
my $Self = shift;
# Check arguments.
# TODO
# Return something.
return 1;
}
1;
__END__
=pod
=head1 AUTHOR
Dave Foglesong (fogleson@adobe.com)
=head1 COPYRIGHT
Copyright 2008 Adobe Systems Incorporated. All rights reserved.
=cut
| 26.782051 | 78 | 0.589596 |
ed4a54003da2b7fb4cce17ab53371fe1a092c9a9 | 6,677 | pm | Perl | Mojoqq/perl/vendor/lib/DateTime/TimeZone/Australia/Lindeman.pm | ghuan/Mojo-webqq-for-windows | ad44014da4578f99aa3efad0b55f0fc3bc3af322 | [
"Unlicense"
]
| null | null | null | Mojoqq/perl/vendor/lib/DateTime/TimeZone/Australia/Lindeman.pm | ghuan/Mojo-webqq-for-windows | ad44014da4578f99aa3efad0b55f0fc3bc3af322 | [
"Unlicense"
]
| null | null | null | Mojoqq/perl/vendor/lib/DateTime/TimeZone/Australia/Lindeman.pm | ghuan/Mojo-webqq-for-windows | ad44014da4578f99aa3efad0b55f0fc3bc3af322 | [
"Unlicense"
]
| null | null | null | # This file is auto-generated by the Perl DateTime Suite time zone
# code generator (0.07) This code generator comes with the
# DateTime::TimeZone module distribution in the tools/ directory
#
# Generated from /tmp/JvovdcV6u5/australasia. Olson data version 2016d
#
# Do not edit this file directly.
#
package DateTime::TimeZone::Australia::Lindeman;
$DateTime::TimeZone::Australia::Lindeman::VERSION = '1.98';
use strict;
use Class::Singleton 1.03;
use DateTime::TimeZone;
use DateTime::TimeZone::OlsonDB;
@DateTime::TimeZone::Australia::Lindeman::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' );
my $spans =
[
[
DateTime::TimeZone::NEG_INFINITY, # utc_start
59768892244, # utc_end 1894-12-31 14:04:04 (Mon)
DateTime::TimeZone::NEG_INFINITY, # local_start
59768928000, # local_end 1895-01-01 00:00:00 (Tue)
35756,
0,
'LMT',
],
[
59768892244, # utc_start 1894-12-31 14:04:04 (Mon)
60463116060, # utc_end 1916-12-31 14:01:00 (Sun)
59768928244, # local_start 1895-01-01 00:04:04 (Tue)
60463152060, # local_end 1917-01-01 00:01:00 (Mon)
36000,
0,
'AEST',
],
[
60463116060, # utc_start 1916-12-31 14:01:00 (Sun)
60470290800, # utc_end 1917-03-24 15:00:00 (Sat)
60463155660, # local_start 1917-01-01 01:01:00 (Mon)
60470330400, # local_end 1917-03-25 02:00:00 (Sun)
39600,
1,
'AEDT',
],
[
60470290800, # utc_start 1917-03-24 15:00:00 (Sat)
61252041600, # utc_end 1941-12-31 16:00:00 (Wed)
60470326800, # local_start 1917-03-25 01:00:00 (Sun)
61252077600, # local_end 1942-01-01 02:00:00 (Thu)
36000,
0,
'AEST',
],
[
61252041600, # utc_start 1941-12-31 16:00:00 (Wed)
61259554800, # utc_end 1942-03-28 15:00:00 (Sat)
61252081200, # local_start 1942-01-01 03:00:00 (Thu)
61259594400, # local_end 1942-03-29 02:00:00 (Sun)
39600,
1,
'AEDT',
],
[
61259554800, # utc_start 1942-03-28 15:00:00 (Sat)
61275283200, # utc_end 1942-09-26 16:00:00 (Sat)
61259590800, # local_start 1942-03-29 01:00:00 (Sun)
61275319200, # local_end 1942-09-27 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
61275283200, # utc_start 1942-09-26 16:00:00 (Sat)
61291004400, # utc_end 1943-03-27 15:00:00 (Sat)
61275322800, # local_start 1942-09-27 03:00:00 (Sun)
61291044000, # local_end 1943-03-28 02:00:00 (Sun)
39600,
1,
'AEDT',
],
[
61291004400, # utc_start 1943-03-27 15:00:00 (Sat)
61307337600, # utc_end 1943-10-02 16:00:00 (Sat)
61291040400, # local_start 1943-03-28 01:00:00 (Sun)
61307373600, # local_end 1943-10-03 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
61307337600, # utc_start 1943-10-02 16:00:00 (Sat)
61322454000, # utc_end 1944-03-25 15:00:00 (Sat)
61307377200, # local_start 1943-10-03 03:00:00 (Sun)
61322493600, # local_end 1944-03-26 02:00:00 (Sun)
39600,
1,
'AEDT',
],
[
61322454000, # utc_start 1944-03-25 15:00:00 (Sat)
62167183200, # utc_end 1970-12-31 14:00:00 (Thu)
61322490000, # local_start 1944-03-26 01:00:00 (Sun)
62167219200, # local_end 1971-01-01 00:00:00 (Fri)
36000,
0,
'AEST',
],
[
62167183200, # utc_start 1970-12-31 14:00:00 (Thu)
62193369600, # utc_end 1971-10-30 16:00:00 (Sat)
62167219200, # local_start 1971-01-01 00:00:00 (Fri)
62193405600, # local_end 1971-10-31 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
62193369600, # utc_start 1971-10-30 16:00:00 (Sat)
62203651200, # utc_end 1972-02-26 16:00:00 (Sat)
62193409200, # local_start 1971-10-31 03:00:00 (Sun)
62203690800, # local_end 1972-02-27 03:00:00 (Sun)
39600,
1,
'AEDT',
],
[
62203651200, # utc_start 1972-02-26 16:00:00 (Sat)
62761276800, # utc_end 1989-10-28 16:00:00 (Sat)
62203687200, # local_start 1972-02-27 02:00:00 (Sun)
62761312800, # local_end 1989-10-29 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
62761276800, # utc_start 1989-10-28 16:00:00 (Sat)
62772163200, # utc_end 1990-03-03 16:00:00 (Sat)
62761316400, # local_start 1989-10-29 03:00:00 (Sun)
62772202800, # local_end 1990-03-04 03:00:00 (Sun)
39600,
1,
'AEDT',
],
[
62772163200, # utc_start 1990-03-03 16:00:00 (Sat)
62792726400, # utc_end 1990-10-27 16:00:00 (Sat)
62772199200, # local_start 1990-03-04 02:00:00 (Sun)
62792762400, # local_end 1990-10-28 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
62792726400, # utc_start 1990-10-27 16:00:00 (Sat)
62803612800, # utc_end 1991-03-02 16:00:00 (Sat)
62792766000, # local_start 1990-10-28 03:00:00 (Sun)
62803652400, # local_end 1991-03-03 03:00:00 (Sun)
39600,
1,
'AEDT',
],
[
62803612800, # utc_start 1991-03-02 16:00:00 (Sat)
62824176000, # utc_end 1991-10-26 16:00:00 (Sat)
62803648800, # local_start 1991-03-03 02:00:00 (Sun)
62824212000, # local_end 1991-10-27 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
62824176000, # utc_start 1991-10-26 16:00:00 (Sat)
62835062400, # utc_end 1992-02-29 16:00:00 (Sat)
62824215600, # local_start 1991-10-27 03:00:00 (Sun)
62835102000, # local_end 1992-03-01 03:00:00 (Sun)
39600,
1,
'AEDT',
],
[
62835062400, # utc_start 1992-02-29 16:00:00 (Sat)
62845596000, # utc_end 1992-06-30 14:00:00 (Tue)
62835098400, # local_start 1992-03-01 02:00:00 (Sun)
62845632000, # local_end 1992-07-01 00:00:00 (Wed)
36000,
0,
'AEST',
],
[
62845596000, # utc_start 1992-06-30 14:00:00 (Tue)
62855625600, # utc_end 1992-10-24 16:00:00 (Sat)
62845632000, # local_start 1992-07-01 00:00:00 (Wed)
62855661600, # local_end 1992-10-25 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
62855625600, # utc_start 1992-10-24 16:00:00 (Sat)
62867116800, # utc_end 1993-03-06 16:00:00 (Sat)
62855665200, # local_start 1992-10-25 03:00:00 (Sun)
62867156400, # local_end 1993-03-07 03:00:00 (Sun)
39600,
1,
'AEDT',
],
[
62867116800, # utc_start 1993-03-06 16:00:00 (Sat)
62887680000, # utc_end 1993-10-30 16:00:00 (Sat)
62867152800, # local_start 1993-03-07 02:00:00 (Sun)
62887716000, # local_end 1993-10-31 02:00:00 (Sun)
36000,
0,
'AEST',
],
[
62887680000, # utc_start 1993-10-30 16:00:00 (Sat)
62898566400, # utc_end 1994-03-05 16:00:00 (Sat)
62887719600, # local_start 1993-10-31 03:00:00 (Sun)
62898606000, # local_end 1994-03-06 03:00:00 (Sun)
39600,
1,
'AEDT',
],
[
62898566400, # utc_start 1994-03-05 16:00:00 (Sat)
DateTime::TimeZone::INFINITY, # utc_end
62898602400, # local_start 1994-03-06 02:00:00 (Sun)
DateTime::TimeZone::INFINITY, # local_end
36000,
0,
'AEST',
],
];
sub olson_version {'2016d'}
sub has_dst_changes {10}
sub _max_year {2026}
sub _new_instance {
return shift->_init( @_, spans => $spans );
}
1;
| 26.287402 | 93 | 0.651191 |
ed547be07d00f8681c9ef9d4430fad629f551170 | 2,808 | pm | Perl | src/perl/qto/lib/Qto/Controller/Export.pm | Diverdi/qto | 5f0783daefca45395d16362cd44bf12748f74186 | [
"Artistic-1.0-Perl",
"MIT"
]
| 6 | 2020-02-12T11:19:42.000Z | 2022-02-13T00:07:19.000Z | src/perl/qto/lib/Qto/Controller/Export.pm | Diverdi/qto | 5f0783daefca45395d16362cd44bf12748f74186 | [
"Artistic-1.0-Perl",
"MIT"
]
| 5 | 2020-03-31T19:46:00.000Z | 2020-06-25T11:59:56.000Z | src/perl/qto/lib/Qto/Controller/Export.pm | Diverdi/qto | 5f0783daefca45395d16362cd44bf12748f74186 | [
"Artistic-1.0-Perl",
"MIT"
]
| 13 | 2020-02-12T11:20:38.000Z | 2020-06-30T16:15:38.000Z | package Qto::Controller::Export ;
use strict ; use warnings ;
require Exporter;
our @ISA = qw(Exporter Mojo::Base Qto::Controller::BaseController);
our $AUTOLOAD =();
our $ModuleDebug = 0 ;
use AutoLoader;
use parent qw(Qto::Controller::BaseController);
use Carp qw /cluck confess shortmess croak carp/ ;
use Data::Printer ;
use Qto::App::Utils::Logger;
use Qto::App::IO::In::CnrUrlPrms ;
use Qto::App::IO::WtrExportFactory ;
use Qto::App::Utils::Timer ;
use Qto::App::Cnvr::CnrDbName qw(toPlainName toEnvName);
our $config = {};
our $objLogger = {} ;
# --------------------------------------------------------
# Export all the items according to the "as" url param output type
# --------------------------------------------------------
sub doExportItems {
my $self = shift;
my $db = $self->stash('db');
my $item = $self->stash('item');
my $table = $item ;
my $ret = 1 ;
my $msg = 0 ;
my $msr2 = {} ;
my $file_to_export = '/tmp/non-existent-file-to-export.tmp' ;
my $http_method = 'GET' ;
my $met = '' ;
my $cnt = '' ;
my $dat = '' ;
$config = $self->app->config ;
$db = toEnvName ( $db , $config) ;
my $objModel = 'Qto::App::Mdl::Model'->new ( \$config , $db , $item ) ;
$self->SUPER::doReloadProjDbMeta( \$objModel , $db , $item) ;
my $as = 'xls' ; # the default form of the Export control
$as = $self->req->query_params->param('as') || $as ; # decide which type of list page to build
my $md_dialect = 'github' ; # the default type of mark-down dialect ( because of Microsoft ... )
$md_dialect = $self->req->query_params->param('type') || $md_dialect ; # decide which type of list page to build
my $objCnrUrlPrms = 'Qto::App::IO::In::CnrUrlPrms'->new(\$config , \$objModel , $self->req->query_params);
my $pg_size = $self->req->query_params->param('pg-size') || 100000 ;
$objModel->set('select.web-action.pg-size' , $pg_size );
return $self->SUPER::doRenderJSON($objCnrUrlPrms->get('http_code'),$objCnrUrlPrms->get('msg'),$http_method,$met,$cnt,$dat)
unless $objCnrUrlPrms->doValidateAndSetHiSelect();
my $objExportFactory = 'Qto::App::IO::WtrExportFactory'->new(\$config, \$objModel , $as );
my $objExporter = $objExportFactory->doSpawn( $as );
$objExporter->doExport( $db , $table ) ;
($ret , $msg , $file_to_export ) = $objExporter->doExport( $db , $table , $md_dialect) ;
unless ( $ret == 0 ) {
$self->render('text' => "$msg" );
} else {
$self->render_file('filepath' => "$file_to_export" );
}
}
1;
__END__
| 38.465753 | 126 | 0.543091 |
ed498c13b096fa1d65b8ae408416aa86d3fb1411 | 2,263 | pl | Perl | tools/mirrorbrain-ci-asn.pl | openSUSE/mirrorbrain | c5fcf05bad171d6c59f5ca47e988372d1ab4f0c2 | [
"Apache-2.0"
]
| 24 | 2017-10-13T13:00:45.000Z | 2022-03-28T01:46:12.000Z | tools/mirrorbrain-ci-asn.pl | seccer22/mirrorbrain | c5fcf05bad171d6c59f5ca47e988372d1ab4f0c2 | [
"Apache-2.0"
]
| 46 | 2017-08-03T15:13:53.000Z | 2022-03-29T09:32:06.000Z | tools/mirrorbrain-ci-asn.pl | seccer22/mirrorbrain | c5fcf05bad171d6c59f5ca47e988372d1ab4f0c2 | [
"Apache-2.0"
]
| 16 | 2018-02-08T04:43:09.000Z | 2022-03-20T19:22:52.000Z | #!/usr/bin/env perl
use strict;
use warnings;
use feature qw( say );
use MaxMind::DB::Writer::Tree;
my $filename = 'mirrorbrain-ci-asn.mmdb';
# Your top level data structure will always be a map (hash). The MMDB format
# is strongly typed. Describe your data types here.
# See https://metacpan.org/pod/MaxMind::DB::Writer::Tree#DATA-TYPES
my %types = (
'autonomous_system_number' => 'uint64',
'autonomous_system_organization' => 'utf8_string',
'prefix_len' => 'uint16',
);
my $tree = MaxMind::DB::Writer::Tree->new(
# "database_type" is some arbitrary string describing the database. At
# MaxMind we use strings like 'GeoIP2-City', 'GeoIP2-Country', etc.
database_type => 'GeoLite2-ASN',
languages => ['en'],
# "description" is a hashref where the keys are language names and the
# values are descriptions of the database in that language.
description =>
{ en => 'MirrorBrain CI ASN DB' },
# "ip_version" can be either 4 or 6
ip_version => 6,
# add a callback to validate data going in to the database
map_key_type_callback => sub { $types{ $_[0] } },
# "record_size" is the record size in bits. Either 24, 28 or 32.
record_size => 24,
remove_reserved_networks => 0,
);
# {'autonomous_system_number': 3680, 'autonomous_system_organization': 'Novell, Inc.', 'ip_address': '130.57.72.10', 'prefix_len': 20}
$tree->insert_network(
'127.0.0.1/32',
{
'autonomous_system_number' => 1231,
'autonomous_system_organization' => 'ACME Master Inc',
'prefix_len' => 32,
},
);
$tree->insert_network(
'127.0.0.2/32',
{
'autonomous_system_number' => 1232,
'autonomous_system_organization' => 'ACME Inc',
'prefix_len' => 32,
},
);
$tree->insert_network(
'127.0.0.3/32',
{
'autonomous_system_number' => 1233,
'autonomous_system_organization' => 'ACME GmbH',
'prefix_len' => 32,
},
);
$tree->insert_network(
'127.0.0.4/32',
{
'autonomous_system_number' => 1234,
'autonomous_system_organization' => 'ACME Asia Inc',
'prefix_len' => 32,
},
);
# Write the database to disk.
open my $fh, '>:raw', $filename;
$tree->write_tree( $fh );
close $fh;
say "$filename has now been created";
| 25.426966 | 134 | 0.642952 |
ed73f142ab9c99c04ef3b392b99918671bd4fb5b | 3,102 | t | Perl | t/node/remote-addr-ipv6.t | mohanwang/apisix2.0_read | 24a197c4a40a37302dd860bb318d60841b3c9a28 | [
"Apache-2.0"
]
| 1 | 2021-01-06T08:33:43.000Z | 2021-01-06T08:33:43.000Z | t/node/remote-addr-ipv6.t | mohanwang/apisix2.0_read | 24a197c4a40a37302dd860bb318d60841b3c9a28 | [
"Apache-2.0"
]
| null | null | null | t/node/remote-addr-ipv6.t | mohanwang/apisix2.0_read | 24a197c4a40a37302dd860bb318d60841b3c9a28 | [
"Apache-2.0"
]
| null | null | null | #
# 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 t::APISIX;
no_root_location();
my $travis_os_name = $ENV{TRAVIS_OS_NAME};
if ((defined $travis_os_name) && $travis_os_name eq "linux") {
plan(skip_all =>
"skip under Travis CI inux environment which doesn't work well with IPv6");
} else {
plan 'no_plan';
}
run_tests();
__DATA__
=== TEST 1: set route: remote addr = ::1
--- config
location /t {
content_by_lua_block {
local t = require("lib.test_admin").test
local code, body = t('/apisix/admin/routes/1',
ngx.HTTP_PUT,
[[{
"remote_addr": "::1",
"upstream": {
"nodes": {
"127.0.0.1:1980": 1
},
"type": "roundrobin"
},
"uri": "/hello"
}]]
)
if code >= 300 then
ngx.status = code
end
ngx.say(body)
}
}
--- request
GET /t
--- response_body
passed
--- no_error_log
[error]
=== TEST 2: IPv6 /not_found
--- listen_ipv6
--- config
location /t {
content_by_lua_block {
ngx.sleep(0.2)
local t = require("lib.test_admin").test_ipv6
t('/not_found')
}
}
--- request
GET /t
--- response_body eval
qr/"error_msg":"404 Route Not Found"/
--- no_error_log
[error]
=== TEST 3: IPv4 /not_found
--- listen_ipv6
--- request
GET /not_found
--- error_code: 404
--- response_body eval
qr/"error_msg":"404 Route Not Found"/
--- no_error_log
[error]
=== TEST 4: IPv6 /hello
--- listen_ipv6
--- config
location /t {
content_by_lua_block {
ngx.sleep(0.2)
local t = require("lib.test_admin").test_ipv6
t('/hello')
}
}
--- request
GET /t
--- response_body eval
qr{connected: 1
request sent: 59
received: HTTP/1.1 200 OK
received: Content-Type: text/plain
received: Connection: close
received: Server: APISIX/\d\.\d+(\.\d+)?
received: Server: \w+
received:
received: hello world
failed to receive a line: closed \[\]
close: 1 nil}
--- no_error_log
[error]
=== TEST 5: IPv4 /hello
--- listen_ipv6
--- request
GET /hello
--- error_code: 404
--- response_body
{"error_msg":"404 Route Not Found"}
--- no_error_log
[error]
| 22.642336 | 81 | 0.599613 |
73f439b987bd5034fce895b034578820ab4b254e | 3,729 | pm | Perl | framework/core/Project/Math.pm | dericp/defects4j | 252f7b0e259678dfd1074679c7974c6eb384ad02 | [
"MIT"
]
| null | null | null | framework/core/Project/Math.pm | dericp/defects4j | 252f7b0e259678dfd1074679c7974c6eb384ad02 | [
"MIT"
]
| null | null | null | framework/core/Project/Math.pm | dericp/defects4j | 252f7b0e259678dfd1074679c7974c6eb384ad02 | [
"MIT"
]
| null | null | null | #-------------------------------------------------------------------------------
# Copyright (c) 2014-2015 René Just, Darioush Jalali, and Defects4J 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.
#-------------------------------------------------------------------------------
=pod
=head1 NAME
Project::Math.pm -- L<Project> submodule for Commons-math.
=head1 DESCRIPTION
This module provides all project-specific configurations and subroutines for the
Commons-math project.
=cut
package Project::Math;
use strict;
use warnings;
use Constants;
use Vcs::Git;
our @ISA = qw(Project);
my $PID = "Math";
sub new {
my $class = shift;
my $name = "commons-math";
my $src = "src/main/java";
my $test = "src/test";
my $vcs = Vcs::Git->new($PID,
"$REPO_DIR/$name.git",
"$SCRIPT_DIR/projects/$PID/commit-db");
return $class->SUPER::new($PID, $name, $vcs, $src, $test);
}
sub src_dir {
@_ == 2 or die $ARG_ERROR;
my ($self, $vid) = @_;
Utils::check_vid($vid);
# Init dir_map if necessary
$self->_build_dir_map();
# Get revision hash
my $revision_id = $self->lookup($vid);
# Get src directory from lookup table
my $src = $self->{_dir_map}->{$revision_id}->{src};
return $src if defined $src;
# Get default src dir if not listed in _dir_map
return $self->SUPER::src_dir($vid);
}
sub test_dir {
@_ == 2 or die $ARG_ERROR;
my ($self, $vid) = @_;
Utils::check_vid($vid);
# Init dir_map if necessary
$self->_build_dir_map();
# Get revision hash
my $revision_id = $self->lookup($vid);
# Get test directory from lookup table
my $test = $self->{_dir_map}->{$revision_id}->{test};
return $test if defined $test;
# Get default test dir if not listed in _dir_map
return $self->SUPER::test_dir($vid);
}
sub _build_dir_map {
my $self = shift;
return if defined $self->{_dir_map};
my $map_file = "$SCRIPT_DIR/projects/$PID/dir_map.csv";
open (IN, "<$map_file") or die "Cannot open directory map $map_file: $!";
my $cache = {};
while (<IN>) {
chomp;
/([^,]+),([^,]+),(.+)/ or next;
$cache->{$1} = {src=>$2, test=>$3};
}
close IN;
$self->{_dir_map}=$cache;
}
#
# Remove loopoing tests in addition to the broken ones
#
sub fix_tests {
@_ == 2 or die $ARG_ERROR;
my ($self, $vid) = @_;
Utils::check_vid($vid);
$self->SUPER::fix_tests($vid);
my $dir = $self->test_dir($vid);
# TODO: make this more precise
my $file = "$SCRIPT_DIR/projects/$PID/broken_tests";
if (-e $file) {
$self->exclude_tests_in_file($file, $dir);
}
}
1;
| 27.828358 | 81 | 0.620005 |
ed8500fb89989ac62ab5bcfef0bc7dadd0dba088 | 2,901 | pl | Perl | src/main/webapp/assets/filetree/jqueryFileTree.pl | yousef1876/CRM_Accounting_HR | c76225e6f6694c9021530b5a39dd31010cc200a9 | [
"MIT"
]
| 19 | 2015-03-06T13:47:24.000Z | 2020-09-20T14:39:08.000Z | src/main/webapp/assets/filetree/jqueryFileTree.pl | yousef1876/CRM_Accounting_HR | c76225e6f6694c9021530b5a39dd31010cc200a9 | [
"MIT"
]
| 5 | 2016-07-05T06:06:31.000Z | 2016-07-27T05:21:36.000Z | src/main/webapp/assets/filetree/jqueryFileTree.pl | yousef1876/CRM_Accounting_HR | c76225e6f6694c9021530b5a39dd31010cc200a9 | [
"MIT"
]
| 7 | 2015-04-19T14:08:55.000Z | 2022-03-10T15:35:30.000Z | #!/usr/bin/perl
use strict;
use HTML::Entities ();
#-----------------------------------------------------------
# jQuery File Tree Perl Connector
#
# Version 1.0
#
# Oleg Burlaca
# http://www.burlaca.com/2009/02/jquery-file-tree-connector/
# 12 February 2009
#-----------------------------------------------------------
# for security reasons, specify a root folder
# to prevent the whole filesystem to be shown
# for ex: the root folder of your webbrowser
my $root = "/var/www/html/";
#----------------------------------------------------------
my $params = &getCGIParams();
print "Content-type: text/html\n\n";
my $dir = $params->{dir};
my $fullDir = $root . $dir;
exit if ! -e $fullDir;
opendir(BIN, $fullDir) or die "Can't open $dir: $!";
my (@folders, @files);
my $total = 0;
while( defined (my $file = readdir BIN) ) {
next if $file eq '.' or $file eq '..';
$total++;
if (-d "$fullDir/$file") {
push (@folders, $file);
} else {
push (@files, $file);
}
}
closedir(BIN);
return if $total == 0;
print "<ul class=\"jqueryFileTree\" style=\"display: none;\">";
# print Folders
foreach my $file (sort @folders) {
next if ! -e $fullDir . $file;
print '<li class="directory collapsed"><a href="#" rel="' .
&HTML::Entities::encode($dir . $file) . '/">' .
&HTML::Entities::encode($file) . '</a></li>';
}
# print Files
foreach my $file (sort @files) {
next if ! -e $fullDir . $file;
$file =~ /\.(.+)$/;
my $ext = $1;
print '<li class="file ext_' . $ext . '"><a href="#" rel="' .
&HTML::Entities::encode($dir . $file) . '/">' .
&HTML::Entities::encode($file) . '</a></li>';
}
print "</ul>\n";
#--------------------------------------------------------------------------------------------------
sub getCGIParams {
my $line;
if ($ENV{'REQUEST_METHOD'} eq "POST") {
read(STDIN, $line, $ENV{'CONTENT_LENGTH'});
} else {
$line = $ENV{'QUERY_STRING'};
}
my (@pairs) = split(/&/, $line);
my ($name, $value, %F);
foreach (@pairs) {
($name, $value) = split(/=/);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
if (! exists $F{$name}) {
$F{$name} = $value;
} elsif (exists $F{$name} and ref($F{$name}) ne 'ARRAY') {
my $prev_value = $F{$name};
delete $F{$name};
$F{$name} = [ $prev_value, $value ];
} else { push @{ $F{$name} }, $value }
}
return \%F;
}
#--------------------------------------------------------------------------------------------------
| 28.441176 | 188 | 0.408135 |
ed85ad6b564c396e161abd8797375e6608faf93f | 5,685 | pm | Perl | misc-scripts/cloud/EnsCloud/Describer.pm | arnaudxk/ensembl | 2baa0f180dde74e9d89b7ac0495d15c79bc63ff3 | [
"Apache-2.0"
]
| null | null | null | misc-scripts/cloud/EnsCloud/Describer.pm | arnaudxk/ensembl | 2baa0f180dde74e9d89b7ac0495d15c79bc63ff3 | [
"Apache-2.0"
]
| null | null | null | misc-scripts/cloud/EnsCloud/Describer.pm | arnaudxk/ensembl | 2baa0f180dde74e9d89b7ac0495d15c79bc63ff3 | [
"Apache-2.0"
]
| 1 | 2016-02-17T09:50:07.000Z | 2016-02-17T09:50:07.000Z | =head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsCloud::Describer;
use Moose::Role;
requires 'region_alias';
use Net::Amazon::EC2;
use Text::SimpleTable;
our $col_widths_headings = {
tags => [ 22, 'Tag' ],
instance_id => [ 10, 'Instance' ],
ip_address => [ 14, 'Ip Address' ],
dns_name => [ 57, 'DNS Name' ],
instance_type => [ 9, 'Type' ],
launch_time => [ 16, 'Launch' ],
image_id => [ 12, 'Ami id' ],
name => [ 45, 'Name' ],
description => [ 45, 'Description' ],
image_state => [ 7, 'State' ],
# snap_creation => [ 23, 'Snap Creation' ],
# [ 13, 'Vol Creation' ]
size => [ 5, 'Size' ],
create_time => [ 20, 'Create Time' ],
# [ 20, 'Attach Time' ],
# [ 13, 'Volume Id' ],
# [ 10, 'Device' ],
# [ 10, 'Vol. status' ],
# [ 8, 'Attach status' ],
# zone => [ 10, 'Zone' ]
# [ 13, 'Snapshot Id' ],
# [ 19, 'Start Time' ],
# [ 8, 'Progress' ],
# status => [ 10, 'Status' ],
# [ 12, 'owner' ],
# [ 11, 'owner alias' ],
};
has ec2_wanted_version => (
is => 'rw',
default => '2011-02-28'
);
#has 'ec2' => (
# is => 'ro',
# isa => 'Net::Amazon::EC2',
#lazy_
#);
# has 'region_alias' => (
# is => 'rw',
# isa => 'Str',
# required =>1
# );
sub ec2 {
my $self = shift;
my $region_lookup = {
'eu' => 'eu-west-1',
'useast' => 'us-east-1',
'uswest' => 'us-west-1',
'asia' => 'ap-southeast-1',
};
return Net::Amazon::EC2->new(
AWSAccessKeyId => $ENV{AWS_ACCESS_KEY_ID},
SecretAccessKey => $ENV{AWS_ACCESS_KEY_SECRET},
debug => 0,
region => $region_lookup->{ $self->region_alias },
version => $self->ec2_wanted_version
);
}
sub list_volumes {
my $self = shift;
my $volumes = $self->ec2->describe_volumes;
my @sorted_volumes = sort { $a->{size} <=> $b->{size} } @$volumes;
my $instances = $self->ec2->describe_instances;
my $instance2ip;
foreach my $instance (@$instances) {
# print dump $instance->instances_set;
my $instance_set = $instance->instances_set->[0];
$instance2ip->{ $instance_set->{instance_id} } =
$instance_set->{ip_address};
}
# die dump $volumes;
my $table = Text::SimpleTable->new(
[ 5, 'Size' ],
[ 20, 'Create Time' ],
[ 20, 'Attach Time' ],
[ 13, 'Volume Id' ],
[ 13, 'Instance Id' ],
[ 15, 'Ip Address' ],
[ 10, 'Device' ],
[ 10, 'Vol. status' ],
[ 8, 'Attach status' ],
[ 13, 'Snapshot Id' ],
[ 10, 'Zone' ]
);
foreach my $volume (@sorted_volumes) {
# print dump $instance->instances_set;
my $attachments = $volume->attachments;
print
"Volume [$volume->{volume_id}] is attached to multiple instances: this not handled by this script\n"
and exit
if @$attachments > 1;
$volume->{create_time} =~ s/.000Z$//;
$attachments->[0]->{attach_time} =~ s/.000Z$//;
# die dump $instance_set;
$table->row(
$volume->{size},
$volume->{create_time},
$attachments->[0]->{attach_time} || '',
$volume->{volume_id},
$attachments->[0]->{instance_id} || '',
$instance2ip->{ $attachments->[0]->{instance_id} } || '',
$attachments->[0]->{device} || '',
$volume->{status},
$attachments->[0]->{status} || '',
$volume->{snapshot_id} || 'no snapshot',
$volume->{zone}
);
}
print $table->draw;
}
sub list_instances {
my ($self) = @_;
my $instances = $self->ec2->describe_instances;
my $table = Text::SimpleTable->new(
$col_widths_headings->{tags},
$col_widths_headings->{instance_id},
$col_widths_headings->{ip_address},
$col_widths_headings->{dns_name},
$col_widths_headings->{instance_type},
$col_widths_headings->{launch_time},
$col_widths_headings->{image_state},
$col_widths_headings->{image_id}
);
foreach my $instance (@$instances) {
# print dump $instance->instances_set;
my $instance_set = $instance->instances_set->[0];
$instance_set->{launch_time} =~ s/:\d+\.000Z$//;
#die dump $instance_set;
$table->row(
$instance_set->{tags} || '',
$instance_set->{instance_id},
$instance_set->{ip_address} || '',
$instance_set->{dns_name} || '',
$instance_set->{instance_type},
$instance_set->{launch_time},
$instance_set->{instance_state}->name,
$instance_set->{image_id},
);
}
return $table->draw;
}
# __PACKAGE__->meta->make_immutable;
1;
__END__
| 28.004926 | 100 | 0.523483 |
ed1a47c30cd16135a1a4cefcff477ea30a03e8b2 | 102,049 | pl | Perl | deps/src/node-v10.15.3/deps/openssl/openssl/crypto/aes/asm/aesni-x86.pl | Mstronach/turicreate | c5e0e58d44adc1c1414eac486f3dc17a721a296e | [
"BSD-3-Clause"
]
| 2,757 | 2018-04-28T21:41:36.000Z | 2022-03-29T06:33:36.000Z | deps/src/node-v10.15.3/deps/openssl/openssl/crypto/aes/asm/aesni-x86.pl | Mstronach/turicreate | c5e0e58d44adc1c1414eac486f3dc17a721a296e | [
"BSD-3-Clause"
]
| 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | deps/src/node-v10.15.3/deps/openssl/openssl/crypto/aes/asm/aesni-x86.pl | Mstronach/turicreate | c5e0e58d44adc1c1414eac486f3dc17a721a296e | [
"BSD-3-Clause"
]
| 449 | 2018-05-09T05:54:05.000Z | 2022-03-30T14:54:18.000Z | #! /usr/bin/env perl
# Copyright 2009-2016 The OpenSSL Project Authors. All Rights Reserved.
#
# Licensed under the OpenSSL license (the "License"). You may not use
# this file except in compliance with the License. You can obtain a copy
# in the file LICENSE in the source distribution or at
# https://www.openssl.org/source/license.html
# ====================================================================
# Written by Andy Polyakov <appro@openssl.org> for the OpenSSL
# project. The module is, however, dual licensed under OpenSSL and
# CRYPTOGAMS licenses depending on where you obtain it. For further
# details see http://www.openssl.org/~appro/cryptogams/.
# ====================================================================
#
# This module implements support for Intel AES-NI extension. In
# OpenSSL context it's used with Intel engine, but can also be used as
# drop-in replacement for crypto/aes/asm/aes-586.pl [see below for
# details].
#
# Performance.
#
# To start with see corresponding paragraph in aesni-x86_64.pl...
# Instead of filling table similar to one found there I've chosen to
# summarize *comparison* results for raw ECB, CTR and CBC benchmarks.
# The simplified table below represents 32-bit performance relative
# to 64-bit one in every given point. Ratios vary for different
# encryption modes, therefore interval values.
#
# 16-byte 64-byte 256-byte 1-KB 8-KB
# 53-67% 67-84% 91-94% 95-98% 97-99.5%
#
# Lower ratios for smaller block sizes are perfectly understandable,
# because function call overhead is higher in 32-bit mode. Largest
# 8-KB block performance is virtually same: 32-bit code is less than
# 1% slower for ECB, CBC and CCM, and ~3% slower otherwise.
# January 2011
#
# See aesni-x86_64.pl for details. Unlike x86_64 version this module
# interleaves at most 6 aes[enc|dec] instructions, because there are
# not enough registers for 8x interleave [which should be optimal for
# Sandy Bridge]. Actually, performance results for 6x interleave
# factor presented in aesni-x86_64.pl (except for CTR) are for this
# module.
# April 2011
#
# Add aesni_xts_[en|de]crypt. Westmere spends 1.50 cycles processing
# one byte out of 8KB with 128-bit key, Sandy Bridge - 1.09.
# November 2015
#
# Add aesni_ocb_[en|de]crypt.
######################################################################
# Current large-block performance in cycles per byte processed with
# 128-bit key (less is better).
#
# CBC en-/decrypt CTR XTS ECB OCB
# Westmere 3.77/1.37 1.37 1.52 1.27
# * Bridge 5.07/0.98 0.99 1.09 0.91 1.10
# Haswell 4.44/0.80 0.97 1.03 0.72 0.76
# Silvermont 5.77/3.56 3.67 4.03 3.46 4.03
# Bulldozer 5.80/0.98 1.05 1.24 0.93 1.23
$PREFIX="aesni"; # if $PREFIX is set to "AES", the script
# generates drop-in replacement for
# crypto/aes/asm/aes-586.pl:-)
$inline=1; # inline _aesni_[en|de]crypt
$0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1;
push(@INC,"${dir}","${dir}../../perlasm");
require "x86asm.pl";
$output = pop;
open OUT,">$output";
*STDOUT=*OUT;
&asm_init($ARGV[0],$0);
&external_label("OPENSSL_ia32cap_P");
&static_label("key_const");
if ($PREFIX eq "aesni") { $movekey=\&movups; }
else { $movekey=\&movups; }
$len="eax";
$rounds="ecx";
$key="edx";
$inp="esi";
$out="edi";
$rounds_="ebx"; # backup copy for $rounds
$key_="ebp"; # backup copy for $key
$rndkey0="xmm0";
$rndkey1="xmm1";
$inout0="xmm2";
$inout1="xmm3";
$inout2="xmm4";
$inout3="xmm5"; $in1="xmm5";
$inout4="xmm6"; $in0="xmm6";
$inout5="xmm7"; $ivec="xmm7";
# AESNI extension
sub aeskeygenassist
{ my($dst,$src,$imm)=@_;
if ("$dst:$src" =~ /xmm([0-7]):xmm([0-7])/)
{ &data_byte(0x66,0x0f,0x3a,0xdf,0xc0|($1<<3)|$2,$imm); }
}
sub aescommon
{ my($opcodelet,$dst,$src)=@_;
if ("$dst:$src" =~ /xmm([0-7]):xmm([0-7])/)
{ &data_byte(0x66,0x0f,0x38,$opcodelet,0xc0|($1<<3)|$2);}
}
sub aesimc { aescommon(0xdb,@_); }
sub aesenc { aescommon(0xdc,@_); }
sub aesenclast { aescommon(0xdd,@_); }
sub aesdec { aescommon(0xde,@_); }
sub aesdeclast { aescommon(0xdf,@_); }
# Inline version of internal aesni_[en|de]crypt1
{ my $sn;
sub aesni_inline_generate1
{ my ($p,$inout,$ivec)=@_; $inout=$inout0 if (!defined($inout));
$sn++;
&$movekey ($rndkey0,&QWP(0,$key));
&$movekey ($rndkey1,&QWP(16,$key));
&xorps ($ivec,$rndkey0) if (defined($ivec));
&lea ($key,&DWP(32,$key));
&xorps ($inout,$ivec) if (defined($ivec));
&xorps ($inout,$rndkey0) if (!defined($ivec));
&set_label("${p}1_loop_$sn");
eval"&aes${p} ($inout,$rndkey1)";
&dec ($rounds);
&$movekey ($rndkey1,&QWP(0,$key));
&lea ($key,&DWP(16,$key));
&jnz (&label("${p}1_loop_$sn"));
eval"&aes${p}last ($inout,$rndkey1)";
}}
sub aesni_generate1 # fully unrolled loop
{ my ($p,$inout)=@_; $inout=$inout0 if (!defined($inout));
&function_begin_B("_aesni_${p}rypt1");
&movups ($rndkey0,&QWP(0,$key));
&$movekey ($rndkey1,&QWP(0x10,$key));
&xorps ($inout,$rndkey0);
&$movekey ($rndkey0,&QWP(0x20,$key));
&lea ($key,&DWP(0x30,$key));
&cmp ($rounds,11);
&jb (&label("${p}128"));
&lea ($key,&DWP(0x20,$key));
&je (&label("${p}192"));
&lea ($key,&DWP(0x20,$key));
eval"&aes${p} ($inout,$rndkey1)";
&$movekey ($rndkey1,&QWP(-0x40,$key));
eval"&aes${p} ($inout,$rndkey0)";
&$movekey ($rndkey0,&QWP(-0x30,$key));
&set_label("${p}192");
eval"&aes${p} ($inout,$rndkey1)";
&$movekey ($rndkey1,&QWP(-0x20,$key));
eval"&aes${p} ($inout,$rndkey0)";
&$movekey ($rndkey0,&QWP(-0x10,$key));
&set_label("${p}128");
eval"&aes${p} ($inout,$rndkey1)";
&$movekey ($rndkey1,&QWP(0,$key));
eval"&aes${p} ($inout,$rndkey0)";
&$movekey ($rndkey0,&QWP(0x10,$key));
eval"&aes${p} ($inout,$rndkey1)";
&$movekey ($rndkey1,&QWP(0x20,$key));
eval"&aes${p} ($inout,$rndkey0)";
&$movekey ($rndkey0,&QWP(0x30,$key));
eval"&aes${p} ($inout,$rndkey1)";
&$movekey ($rndkey1,&QWP(0x40,$key));
eval"&aes${p} ($inout,$rndkey0)";
&$movekey ($rndkey0,&QWP(0x50,$key));
eval"&aes${p} ($inout,$rndkey1)";
&$movekey ($rndkey1,&QWP(0x60,$key));
eval"&aes${p} ($inout,$rndkey0)";
&$movekey ($rndkey0,&QWP(0x70,$key));
eval"&aes${p} ($inout,$rndkey1)";
eval"&aes${p}last ($inout,$rndkey0)";
&ret();
&function_end_B("_aesni_${p}rypt1");
}
# void $PREFIX_encrypt (const void *inp,void *out,const AES_KEY *key);
&aesni_generate1("enc") if (!$inline);
&function_begin_B("${PREFIX}_encrypt");
&mov ("eax",&wparam(0));
&mov ($key,&wparam(2));
&movups ($inout0,&QWP(0,"eax"));
&mov ($rounds,&DWP(240,$key));
&mov ("eax",&wparam(1));
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&pxor ($rndkey0,$rndkey0); # clear register bank
&pxor ($rndkey1,$rndkey1);
&movups (&QWP(0,"eax"),$inout0);
&pxor ($inout0,$inout0);
&ret ();
&function_end_B("${PREFIX}_encrypt");
# void $PREFIX_decrypt (const void *inp,void *out,const AES_KEY *key);
&aesni_generate1("dec") if(!$inline);
&function_begin_B("${PREFIX}_decrypt");
&mov ("eax",&wparam(0));
&mov ($key,&wparam(2));
&movups ($inout0,&QWP(0,"eax"));
&mov ($rounds,&DWP(240,$key));
&mov ("eax",&wparam(1));
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&pxor ($rndkey0,$rndkey0); # clear register bank
&pxor ($rndkey1,$rndkey1);
&movups (&QWP(0,"eax"),$inout0);
&pxor ($inout0,$inout0);
&ret ();
&function_end_B("${PREFIX}_decrypt");
# _aesni_[en|de]cryptN are private interfaces, N denotes interleave
# factor. Why 3x subroutine were originally used in loops? Even though
# aes[enc|dec] latency was originally 6, it could be scheduled only
# every *2nd* cycle. Thus 3x interleave was the one providing optimal
# utilization, i.e. when subroutine's throughput is virtually same as
# of non-interleaved subroutine [for number of input blocks up to 3].
# This is why it originally made no sense to implement 2x subroutine.
# But times change and it became appropriate to spend extra 192 bytes
# on 2x subroutine on Atom Silvermont account. For processors that
# can schedule aes[enc|dec] every cycle optimal interleave factor
# equals to corresponding instructions latency. 8x is optimal for
# * Bridge, but it's unfeasible to accommodate such implementation
# in XMM registers addreassable in 32-bit mode and therefore maximum
# of 6x is used instead...
sub aesni_generate2
{ my $p=shift;
&function_begin_B("_aesni_${p}rypt2");
&$movekey ($rndkey0,&QWP(0,$key));
&shl ($rounds,4);
&$movekey ($rndkey1,&QWP(16,$key));
&xorps ($inout0,$rndkey0);
&pxor ($inout1,$rndkey0);
&$movekey ($rndkey0,&QWP(32,$key));
&lea ($key,&DWP(32,$key,$rounds));
&neg ($rounds);
&add ($rounds,16);
&set_label("${p}2_loop");
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
&$movekey ($rndkey1,&QWP(0,$key,$rounds));
&add ($rounds,32);
eval"&aes${p} ($inout0,$rndkey0)";
eval"&aes${p} ($inout1,$rndkey0)";
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&jnz (&label("${p}2_loop"));
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
eval"&aes${p}last ($inout0,$rndkey0)";
eval"&aes${p}last ($inout1,$rndkey0)";
&ret();
&function_end_B("_aesni_${p}rypt2");
}
sub aesni_generate3
{ my $p=shift;
&function_begin_B("_aesni_${p}rypt3");
&$movekey ($rndkey0,&QWP(0,$key));
&shl ($rounds,4);
&$movekey ($rndkey1,&QWP(16,$key));
&xorps ($inout0,$rndkey0);
&pxor ($inout1,$rndkey0);
&pxor ($inout2,$rndkey0);
&$movekey ($rndkey0,&QWP(32,$key));
&lea ($key,&DWP(32,$key,$rounds));
&neg ($rounds);
&add ($rounds,16);
&set_label("${p}3_loop");
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
eval"&aes${p} ($inout2,$rndkey1)";
&$movekey ($rndkey1,&QWP(0,$key,$rounds));
&add ($rounds,32);
eval"&aes${p} ($inout0,$rndkey0)";
eval"&aes${p} ($inout1,$rndkey0)";
eval"&aes${p} ($inout2,$rndkey0)";
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&jnz (&label("${p}3_loop"));
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
eval"&aes${p} ($inout2,$rndkey1)";
eval"&aes${p}last ($inout0,$rndkey0)";
eval"&aes${p}last ($inout1,$rndkey0)";
eval"&aes${p}last ($inout2,$rndkey0)";
&ret();
&function_end_B("_aesni_${p}rypt3");
}
# 4x interleave is implemented to improve small block performance,
# most notably [and naturally] 4 block by ~30%. One can argue that one
# should have implemented 5x as well, but improvement would be <20%,
# so it's not worth it...
sub aesni_generate4
{ my $p=shift;
&function_begin_B("_aesni_${p}rypt4");
&$movekey ($rndkey0,&QWP(0,$key));
&$movekey ($rndkey1,&QWP(16,$key));
&shl ($rounds,4);
&xorps ($inout0,$rndkey0);
&pxor ($inout1,$rndkey0);
&pxor ($inout2,$rndkey0);
&pxor ($inout3,$rndkey0);
&$movekey ($rndkey0,&QWP(32,$key));
&lea ($key,&DWP(32,$key,$rounds));
&neg ($rounds);
&data_byte (0x0f,0x1f,0x40,0x00);
&add ($rounds,16);
&set_label("${p}4_loop");
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
eval"&aes${p} ($inout2,$rndkey1)";
eval"&aes${p} ($inout3,$rndkey1)";
&$movekey ($rndkey1,&QWP(0,$key,$rounds));
&add ($rounds,32);
eval"&aes${p} ($inout0,$rndkey0)";
eval"&aes${p} ($inout1,$rndkey0)";
eval"&aes${p} ($inout2,$rndkey0)";
eval"&aes${p} ($inout3,$rndkey0)";
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&jnz (&label("${p}4_loop"));
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
eval"&aes${p} ($inout2,$rndkey1)";
eval"&aes${p} ($inout3,$rndkey1)";
eval"&aes${p}last ($inout0,$rndkey0)";
eval"&aes${p}last ($inout1,$rndkey0)";
eval"&aes${p}last ($inout2,$rndkey0)";
eval"&aes${p}last ($inout3,$rndkey0)";
&ret();
&function_end_B("_aesni_${p}rypt4");
}
sub aesni_generate6
{ my $p=shift;
&function_begin_B("_aesni_${p}rypt6");
&static_label("_aesni_${p}rypt6_enter");
&$movekey ($rndkey0,&QWP(0,$key));
&shl ($rounds,4);
&$movekey ($rndkey1,&QWP(16,$key));
&xorps ($inout0,$rndkey0);
&pxor ($inout1,$rndkey0); # pxor does better here
&pxor ($inout2,$rndkey0);
eval"&aes${p} ($inout0,$rndkey1)";
&pxor ($inout3,$rndkey0);
&pxor ($inout4,$rndkey0);
eval"&aes${p} ($inout1,$rndkey1)";
&lea ($key,&DWP(32,$key,$rounds));
&neg ($rounds);
eval"&aes${p} ($inout2,$rndkey1)";
&pxor ($inout5,$rndkey0);
&$movekey ($rndkey0,&QWP(0,$key,$rounds));
&add ($rounds,16);
&jmp (&label("_aesni_${p}rypt6_inner"));
&set_label("${p}6_loop",16);
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
eval"&aes${p} ($inout2,$rndkey1)";
&set_label("_aesni_${p}rypt6_inner");
eval"&aes${p} ($inout3,$rndkey1)";
eval"&aes${p} ($inout4,$rndkey1)";
eval"&aes${p} ($inout5,$rndkey1)";
&set_label("_aesni_${p}rypt6_enter");
&$movekey ($rndkey1,&QWP(0,$key,$rounds));
&add ($rounds,32);
eval"&aes${p} ($inout0,$rndkey0)";
eval"&aes${p} ($inout1,$rndkey0)";
eval"&aes${p} ($inout2,$rndkey0)";
eval"&aes${p} ($inout3,$rndkey0)";
eval"&aes${p} ($inout4,$rndkey0)";
eval"&aes${p} ($inout5,$rndkey0)";
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&jnz (&label("${p}6_loop"));
eval"&aes${p} ($inout0,$rndkey1)";
eval"&aes${p} ($inout1,$rndkey1)";
eval"&aes${p} ($inout2,$rndkey1)";
eval"&aes${p} ($inout3,$rndkey1)";
eval"&aes${p} ($inout4,$rndkey1)";
eval"&aes${p} ($inout5,$rndkey1)";
eval"&aes${p}last ($inout0,$rndkey0)";
eval"&aes${p}last ($inout1,$rndkey0)";
eval"&aes${p}last ($inout2,$rndkey0)";
eval"&aes${p}last ($inout3,$rndkey0)";
eval"&aes${p}last ($inout4,$rndkey0)";
eval"&aes${p}last ($inout5,$rndkey0)";
&ret();
&function_end_B("_aesni_${p}rypt6");
}
&aesni_generate2("enc") if ($PREFIX eq "aesni");
&aesni_generate2("dec");
&aesni_generate3("enc") if ($PREFIX eq "aesni");
&aesni_generate3("dec");
&aesni_generate4("enc") if ($PREFIX eq "aesni");
&aesni_generate4("dec");
&aesni_generate6("enc") if ($PREFIX eq "aesni");
&aesni_generate6("dec");
if ($PREFIX eq "aesni") {
######################################################################
# void aesni_ecb_encrypt (const void *in, void *out,
# size_t length, const AES_KEY *key,
# int enc);
&function_begin("aesni_ecb_encrypt");
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3));
&mov ($rounds_,&wparam(4));
&and ($len,-16);
&jz (&label("ecb_ret"));
&mov ($rounds,&DWP(240,$key));
&test ($rounds_,$rounds_);
&jz (&label("ecb_decrypt"));
&mov ($key_,$key); # backup $key
&mov ($rounds_,$rounds); # backup $rounds
&cmp ($len,0x60);
&jb (&label("ecb_enc_tail"));
&movdqu ($inout0,&QWP(0,$inp));
&movdqu ($inout1,&QWP(0x10,$inp));
&movdqu ($inout2,&QWP(0x20,$inp));
&movdqu ($inout3,&QWP(0x30,$inp));
&movdqu ($inout4,&QWP(0x40,$inp));
&movdqu ($inout5,&QWP(0x50,$inp));
&lea ($inp,&DWP(0x60,$inp));
&sub ($len,0x60);
&jmp (&label("ecb_enc_loop6_enter"));
&set_label("ecb_enc_loop6",16);
&movups (&QWP(0,$out),$inout0);
&movdqu ($inout0,&QWP(0,$inp));
&movups (&QWP(0x10,$out),$inout1);
&movdqu ($inout1,&QWP(0x10,$inp));
&movups (&QWP(0x20,$out),$inout2);
&movdqu ($inout2,&QWP(0x20,$inp));
&movups (&QWP(0x30,$out),$inout3);
&movdqu ($inout3,&QWP(0x30,$inp));
&movups (&QWP(0x40,$out),$inout4);
&movdqu ($inout4,&QWP(0x40,$inp));
&movups (&QWP(0x50,$out),$inout5);
&lea ($out,&DWP(0x60,$out));
&movdqu ($inout5,&QWP(0x50,$inp));
&lea ($inp,&DWP(0x60,$inp));
&set_label("ecb_enc_loop6_enter");
&call ("_aesni_encrypt6");
&mov ($key,$key_); # restore $key
&mov ($rounds,$rounds_); # restore $rounds
&sub ($len,0x60);
&jnc (&label("ecb_enc_loop6"));
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&movups (&QWP(0x40,$out),$inout4);
&movups (&QWP(0x50,$out),$inout5);
&lea ($out,&DWP(0x60,$out));
&add ($len,0x60);
&jz (&label("ecb_ret"));
&set_label("ecb_enc_tail");
&movups ($inout0,&QWP(0,$inp));
&cmp ($len,0x20);
&jb (&label("ecb_enc_one"));
&movups ($inout1,&QWP(0x10,$inp));
&je (&label("ecb_enc_two"));
&movups ($inout2,&QWP(0x20,$inp));
&cmp ($len,0x40);
&jb (&label("ecb_enc_three"));
&movups ($inout3,&QWP(0x30,$inp));
&je (&label("ecb_enc_four"));
&movups ($inout4,&QWP(0x40,$inp));
&xorps ($inout5,$inout5);
&call ("_aesni_encrypt6");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&movups (&QWP(0x40,$out),$inout4);
jmp (&label("ecb_ret"));
&set_label("ecb_enc_one",16);
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&movups (&QWP(0,$out),$inout0);
&jmp (&label("ecb_ret"));
&set_label("ecb_enc_two",16);
&call ("_aesni_encrypt2");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&jmp (&label("ecb_ret"));
&set_label("ecb_enc_three",16);
&call ("_aesni_encrypt3");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&jmp (&label("ecb_ret"));
&set_label("ecb_enc_four",16);
&call ("_aesni_encrypt4");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&jmp (&label("ecb_ret"));
######################################################################
&set_label("ecb_decrypt",16);
&mov ($key_,$key); # backup $key
&mov ($rounds_,$rounds); # backup $rounds
&cmp ($len,0x60);
&jb (&label("ecb_dec_tail"));
&movdqu ($inout0,&QWP(0,$inp));
&movdqu ($inout1,&QWP(0x10,$inp));
&movdqu ($inout2,&QWP(0x20,$inp));
&movdqu ($inout3,&QWP(0x30,$inp));
&movdqu ($inout4,&QWP(0x40,$inp));
&movdqu ($inout5,&QWP(0x50,$inp));
&lea ($inp,&DWP(0x60,$inp));
&sub ($len,0x60);
&jmp (&label("ecb_dec_loop6_enter"));
&set_label("ecb_dec_loop6",16);
&movups (&QWP(0,$out),$inout0);
&movdqu ($inout0,&QWP(0,$inp));
&movups (&QWP(0x10,$out),$inout1);
&movdqu ($inout1,&QWP(0x10,$inp));
&movups (&QWP(0x20,$out),$inout2);
&movdqu ($inout2,&QWP(0x20,$inp));
&movups (&QWP(0x30,$out),$inout3);
&movdqu ($inout3,&QWP(0x30,$inp));
&movups (&QWP(0x40,$out),$inout4);
&movdqu ($inout4,&QWP(0x40,$inp));
&movups (&QWP(0x50,$out),$inout5);
&lea ($out,&DWP(0x60,$out));
&movdqu ($inout5,&QWP(0x50,$inp));
&lea ($inp,&DWP(0x60,$inp));
&set_label("ecb_dec_loop6_enter");
&call ("_aesni_decrypt6");
&mov ($key,$key_); # restore $key
&mov ($rounds,$rounds_); # restore $rounds
&sub ($len,0x60);
&jnc (&label("ecb_dec_loop6"));
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&movups (&QWP(0x40,$out),$inout4);
&movups (&QWP(0x50,$out),$inout5);
&lea ($out,&DWP(0x60,$out));
&add ($len,0x60);
&jz (&label("ecb_ret"));
&set_label("ecb_dec_tail");
&movups ($inout0,&QWP(0,$inp));
&cmp ($len,0x20);
&jb (&label("ecb_dec_one"));
&movups ($inout1,&QWP(0x10,$inp));
&je (&label("ecb_dec_two"));
&movups ($inout2,&QWP(0x20,$inp));
&cmp ($len,0x40);
&jb (&label("ecb_dec_three"));
&movups ($inout3,&QWP(0x30,$inp));
&je (&label("ecb_dec_four"));
&movups ($inout4,&QWP(0x40,$inp));
&xorps ($inout5,$inout5);
&call ("_aesni_decrypt6");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&movups (&QWP(0x40,$out),$inout4);
&jmp (&label("ecb_ret"));
&set_label("ecb_dec_one",16);
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&movups (&QWP(0,$out),$inout0);
&jmp (&label("ecb_ret"));
&set_label("ecb_dec_two",16);
&call ("_aesni_decrypt2");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&jmp (&label("ecb_ret"));
&set_label("ecb_dec_three",16);
&call ("_aesni_decrypt3");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&jmp (&label("ecb_ret"));
&set_label("ecb_dec_four",16);
&call ("_aesni_decrypt4");
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&set_label("ecb_ret");
&pxor ("xmm0","xmm0"); # clear register bank
&pxor ("xmm1","xmm1");
&pxor ("xmm2","xmm2");
&pxor ("xmm3","xmm3");
&pxor ("xmm4","xmm4");
&pxor ("xmm5","xmm5");
&pxor ("xmm6","xmm6");
&pxor ("xmm7","xmm7");
&function_end("aesni_ecb_encrypt");
######################################################################
# void aesni_ccm64_[en|de]crypt_blocks (const void *in, void *out,
# size_t blocks, const AES_KEY *key,
# const char *ivec,char *cmac);
#
# Handles only complete blocks, operates on 64-bit counter and
# does not update *ivec! Nor does it finalize CMAC value
# (see engine/eng_aesni.c for details)
#
{ my $cmac=$inout1;
&function_begin("aesni_ccm64_encrypt_blocks");
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3));
&mov ($rounds_,&wparam(4));
&mov ($rounds,&wparam(5));
&mov ($key_,"esp");
&sub ("esp",60);
&and ("esp",-16); # align stack
&mov (&DWP(48,"esp"),$key_);
&movdqu ($ivec,&QWP(0,$rounds_)); # load ivec
&movdqu ($cmac,&QWP(0,$rounds)); # load cmac
&mov ($rounds,&DWP(240,$key));
# compose byte-swap control mask for pshufb on stack
&mov (&DWP(0,"esp"),0x0c0d0e0f);
&mov (&DWP(4,"esp"),0x08090a0b);
&mov (&DWP(8,"esp"),0x04050607);
&mov (&DWP(12,"esp"),0x00010203);
# compose counter increment vector on stack
&mov ($rounds_,1);
&xor ($key_,$key_);
&mov (&DWP(16,"esp"),$rounds_);
&mov (&DWP(20,"esp"),$key_);
&mov (&DWP(24,"esp"),$key_);
&mov (&DWP(28,"esp"),$key_);
&shl ($rounds,4);
&mov ($rounds_,16);
&lea ($key_,&DWP(0,$key));
&movdqa ($inout3,&QWP(0,"esp"));
&movdqa ($inout0,$ivec);
&lea ($key,&DWP(32,$key,$rounds));
&sub ($rounds_,$rounds);
&pshufb ($ivec,$inout3);
&set_label("ccm64_enc_outer");
&$movekey ($rndkey0,&QWP(0,$key_));
&mov ($rounds,$rounds_);
&movups ($in0,&QWP(0,$inp));
&xorps ($inout0,$rndkey0);
&$movekey ($rndkey1,&QWP(16,$key_));
&xorps ($rndkey0,$in0);
&xorps ($cmac,$rndkey0); # cmac^=inp
&$movekey ($rndkey0,&QWP(32,$key_));
&set_label("ccm64_enc2_loop");
&aesenc ($inout0,$rndkey1);
&aesenc ($cmac,$rndkey1);
&$movekey ($rndkey1,&QWP(0,$key,$rounds));
&add ($rounds,32);
&aesenc ($inout0,$rndkey0);
&aesenc ($cmac,$rndkey0);
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&jnz (&label("ccm64_enc2_loop"));
&aesenc ($inout0,$rndkey1);
&aesenc ($cmac,$rndkey1);
&paddq ($ivec,&QWP(16,"esp"));
&dec ($len);
&aesenclast ($inout0,$rndkey0);
&aesenclast ($cmac,$rndkey0);
&lea ($inp,&DWP(16,$inp));
&xorps ($in0,$inout0); # inp^=E(ivec)
&movdqa ($inout0,$ivec);
&movups (&QWP(0,$out),$in0); # save output
&pshufb ($inout0,$inout3);
&lea ($out,&DWP(16,$out));
&jnz (&label("ccm64_enc_outer"));
&mov ("esp",&DWP(48,"esp"));
&mov ($out,&wparam(5));
&movups (&QWP(0,$out),$cmac);
&pxor ("xmm0","xmm0"); # clear register bank
&pxor ("xmm1","xmm1");
&pxor ("xmm2","xmm2");
&pxor ("xmm3","xmm3");
&pxor ("xmm4","xmm4");
&pxor ("xmm5","xmm5");
&pxor ("xmm6","xmm6");
&pxor ("xmm7","xmm7");
&function_end("aesni_ccm64_encrypt_blocks");
&function_begin("aesni_ccm64_decrypt_blocks");
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3));
&mov ($rounds_,&wparam(4));
&mov ($rounds,&wparam(5));
&mov ($key_,"esp");
&sub ("esp",60);
&and ("esp",-16); # align stack
&mov (&DWP(48,"esp"),$key_);
&movdqu ($ivec,&QWP(0,$rounds_)); # load ivec
&movdqu ($cmac,&QWP(0,$rounds)); # load cmac
&mov ($rounds,&DWP(240,$key));
# compose byte-swap control mask for pshufb on stack
&mov (&DWP(0,"esp"),0x0c0d0e0f);
&mov (&DWP(4,"esp"),0x08090a0b);
&mov (&DWP(8,"esp"),0x04050607);
&mov (&DWP(12,"esp"),0x00010203);
# compose counter increment vector on stack
&mov ($rounds_,1);
&xor ($key_,$key_);
&mov (&DWP(16,"esp"),$rounds_);
&mov (&DWP(20,"esp"),$key_);
&mov (&DWP(24,"esp"),$key_);
&mov (&DWP(28,"esp"),$key_);
&movdqa ($inout3,&QWP(0,"esp")); # bswap mask
&movdqa ($inout0,$ivec);
&mov ($key_,$key);
&mov ($rounds_,$rounds);
&pshufb ($ivec,$inout3);
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&shl ($rounds_,4);
&mov ($rounds,16);
&movups ($in0,&QWP(0,$inp)); # load inp
&paddq ($ivec,&QWP(16,"esp"));
&lea ($inp,&QWP(16,$inp));
&sub ($rounds,$rounds_);
&lea ($key,&DWP(32,$key_,$rounds_));
&mov ($rounds_,$rounds);
&jmp (&label("ccm64_dec_outer"));
&set_label("ccm64_dec_outer",16);
&xorps ($in0,$inout0); # inp ^= E(ivec)
&movdqa ($inout0,$ivec);
&movups (&QWP(0,$out),$in0); # save output
&lea ($out,&DWP(16,$out));
&pshufb ($inout0,$inout3);
&sub ($len,1);
&jz (&label("ccm64_dec_break"));
&$movekey ($rndkey0,&QWP(0,$key_));
&mov ($rounds,$rounds_);
&$movekey ($rndkey1,&QWP(16,$key_));
&xorps ($in0,$rndkey0);
&xorps ($inout0,$rndkey0);
&xorps ($cmac,$in0); # cmac^=out
&$movekey ($rndkey0,&QWP(32,$key_));
&set_label("ccm64_dec2_loop");
&aesenc ($inout0,$rndkey1);
&aesenc ($cmac,$rndkey1);
&$movekey ($rndkey1,&QWP(0,$key,$rounds));
&add ($rounds,32);
&aesenc ($inout0,$rndkey0);
&aesenc ($cmac,$rndkey0);
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&jnz (&label("ccm64_dec2_loop"));
&movups ($in0,&QWP(0,$inp)); # load inp
&paddq ($ivec,&QWP(16,"esp"));
&aesenc ($inout0,$rndkey1);
&aesenc ($cmac,$rndkey1);
&aesenclast ($inout0,$rndkey0);
&aesenclast ($cmac,$rndkey0);
&lea ($inp,&QWP(16,$inp));
&jmp (&label("ccm64_dec_outer"));
&set_label("ccm64_dec_break",16);
&mov ($rounds,&DWP(240,$key_));
&mov ($key,$key_);
if ($inline)
{ &aesni_inline_generate1("enc",$cmac,$in0); }
else
{ &call ("_aesni_encrypt1",$cmac); }
&mov ("esp",&DWP(48,"esp"));
&mov ($out,&wparam(5));
&movups (&QWP(0,$out),$cmac);
&pxor ("xmm0","xmm0"); # clear register bank
&pxor ("xmm1","xmm1");
&pxor ("xmm2","xmm2");
&pxor ("xmm3","xmm3");
&pxor ("xmm4","xmm4");
&pxor ("xmm5","xmm5");
&pxor ("xmm6","xmm6");
&pxor ("xmm7","xmm7");
&function_end("aesni_ccm64_decrypt_blocks");
}
######################################################################
# void aesni_ctr32_encrypt_blocks (const void *in, void *out,
# size_t blocks, const AES_KEY *key,
# const char *ivec);
#
# Handles only complete blocks, operates on 32-bit counter and
# does not update *ivec! (see crypto/modes/ctr128.c for details)
#
# stack layout:
# 0 pshufb mask
# 16 vector addend: 0,6,6,6
# 32 counter-less ivec
# 48 1st triplet of counter vector
# 64 2nd triplet of counter vector
# 80 saved %esp
&function_begin("aesni_ctr32_encrypt_blocks");
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3));
&mov ($rounds_,&wparam(4));
&mov ($key_,"esp");
&sub ("esp",88);
&and ("esp",-16); # align stack
&mov (&DWP(80,"esp"),$key_);
&cmp ($len,1);
&je (&label("ctr32_one_shortcut"));
&movdqu ($inout5,&QWP(0,$rounds_)); # load ivec
# compose byte-swap control mask for pshufb on stack
&mov (&DWP(0,"esp"),0x0c0d0e0f);
&mov (&DWP(4,"esp"),0x08090a0b);
&mov (&DWP(8,"esp"),0x04050607);
&mov (&DWP(12,"esp"),0x00010203);
# compose counter increment vector on stack
&mov ($rounds,6);
&xor ($key_,$key_);
&mov (&DWP(16,"esp"),$rounds);
&mov (&DWP(20,"esp"),$rounds);
&mov (&DWP(24,"esp"),$rounds);
&mov (&DWP(28,"esp"),$key_);
&pextrd ($rounds_,$inout5,3); # pull 32-bit counter
&pinsrd ($inout5,$key_,3); # wipe 32-bit counter
&mov ($rounds,&DWP(240,$key)); # key->rounds
# compose 2 vectors of 3x32-bit counters
&bswap ($rounds_);
&pxor ($rndkey0,$rndkey0);
&pxor ($rndkey1,$rndkey1);
&movdqa ($inout0,&QWP(0,"esp")); # load byte-swap mask
&pinsrd ($rndkey0,$rounds_,0);
&lea ($key_,&DWP(3,$rounds_));
&pinsrd ($rndkey1,$key_,0);
&inc ($rounds_);
&pinsrd ($rndkey0,$rounds_,1);
&inc ($key_);
&pinsrd ($rndkey1,$key_,1);
&inc ($rounds_);
&pinsrd ($rndkey0,$rounds_,2);
&inc ($key_);
&pinsrd ($rndkey1,$key_,2);
&movdqa (&QWP(48,"esp"),$rndkey0); # save 1st triplet
&pshufb ($rndkey0,$inout0); # byte swap
&movdqu ($inout4,&QWP(0,$key)); # key[0]
&movdqa (&QWP(64,"esp"),$rndkey1); # save 2nd triplet
&pshufb ($rndkey1,$inout0); # byte swap
&pshufd ($inout0,$rndkey0,3<<6); # place counter to upper dword
&pshufd ($inout1,$rndkey0,2<<6);
&cmp ($len,6);
&jb (&label("ctr32_tail"));
&pxor ($inout5,$inout4); # counter-less ivec^key[0]
&shl ($rounds,4);
&mov ($rounds_,16);
&movdqa (&QWP(32,"esp"),$inout5); # save counter-less ivec^key[0]
&mov ($key_,$key); # backup $key
&sub ($rounds_,$rounds); # backup twisted $rounds
&lea ($key,&DWP(32,$key,$rounds));
&sub ($len,6);
&jmp (&label("ctr32_loop6"));
&set_label("ctr32_loop6",16);
# inlining _aesni_encrypt6's prologue gives ~6% improvement...
&pshufd ($inout2,$rndkey0,1<<6);
&movdqa ($rndkey0,&QWP(32,"esp")); # pull counter-less ivec
&pshufd ($inout3,$rndkey1,3<<6);
&pxor ($inout0,$rndkey0); # merge counter-less ivec
&pshufd ($inout4,$rndkey1,2<<6);
&pxor ($inout1,$rndkey0);
&pshufd ($inout5,$rndkey1,1<<6);
&$movekey ($rndkey1,&QWP(16,$key_));
&pxor ($inout2,$rndkey0);
&pxor ($inout3,$rndkey0);
&aesenc ($inout0,$rndkey1);
&pxor ($inout4,$rndkey0);
&pxor ($inout5,$rndkey0);
&aesenc ($inout1,$rndkey1);
&$movekey ($rndkey0,&QWP(32,$key_));
&mov ($rounds,$rounds_);
&aesenc ($inout2,$rndkey1);
&aesenc ($inout3,$rndkey1);
&aesenc ($inout4,$rndkey1);
&aesenc ($inout5,$rndkey1);
&call (&label("_aesni_encrypt6_enter"));
&movups ($rndkey1,&QWP(0,$inp));
&movups ($rndkey0,&QWP(0x10,$inp));
&xorps ($inout0,$rndkey1);
&movups ($rndkey1,&QWP(0x20,$inp));
&xorps ($inout1,$rndkey0);
&movups (&QWP(0,$out),$inout0);
&movdqa ($rndkey0,&QWP(16,"esp")); # load increment
&xorps ($inout2,$rndkey1);
&movdqa ($rndkey1,&QWP(64,"esp")); # load 2nd triplet
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&paddd ($rndkey1,$rndkey0); # 2nd triplet increment
&paddd ($rndkey0,&QWP(48,"esp")); # 1st triplet increment
&movdqa ($inout0,&QWP(0,"esp")); # load byte swap mask
&movups ($inout1,&QWP(0x30,$inp));
&movups ($inout2,&QWP(0x40,$inp));
&xorps ($inout3,$inout1);
&movups ($inout1,&QWP(0x50,$inp));
&lea ($inp,&DWP(0x60,$inp));
&movdqa (&QWP(48,"esp"),$rndkey0); # save 1st triplet
&pshufb ($rndkey0,$inout0); # byte swap
&xorps ($inout4,$inout2);
&movups (&QWP(0x30,$out),$inout3);
&xorps ($inout5,$inout1);
&movdqa (&QWP(64,"esp"),$rndkey1); # save 2nd triplet
&pshufb ($rndkey1,$inout0); # byte swap
&movups (&QWP(0x40,$out),$inout4);
&pshufd ($inout0,$rndkey0,3<<6);
&movups (&QWP(0x50,$out),$inout5);
&lea ($out,&DWP(0x60,$out));
&pshufd ($inout1,$rndkey0,2<<6);
&sub ($len,6);
&jnc (&label("ctr32_loop6"));
&add ($len,6);
&jz (&label("ctr32_ret"));
&movdqu ($inout5,&QWP(0,$key_));
&mov ($key,$key_);
&pxor ($inout5,&QWP(32,"esp")); # restore count-less ivec
&mov ($rounds,&DWP(240,$key_)); # restore $rounds
&set_label("ctr32_tail");
&por ($inout0,$inout5);
&cmp ($len,2);
&jb (&label("ctr32_one"));
&pshufd ($inout2,$rndkey0,1<<6);
&por ($inout1,$inout5);
&je (&label("ctr32_two"));
&pshufd ($inout3,$rndkey1,3<<6);
&por ($inout2,$inout5);
&cmp ($len,4);
&jb (&label("ctr32_three"));
&pshufd ($inout4,$rndkey1,2<<6);
&por ($inout3,$inout5);
&je (&label("ctr32_four"));
&por ($inout4,$inout5);
&call ("_aesni_encrypt6");
&movups ($rndkey1,&QWP(0,$inp));
&movups ($rndkey0,&QWP(0x10,$inp));
&xorps ($inout0,$rndkey1);
&movups ($rndkey1,&QWP(0x20,$inp));
&xorps ($inout1,$rndkey0);
&movups ($rndkey0,&QWP(0x30,$inp));
&xorps ($inout2,$rndkey1);
&movups ($rndkey1,&QWP(0x40,$inp));
&xorps ($inout3,$rndkey0);
&movups (&QWP(0,$out),$inout0);
&xorps ($inout4,$rndkey1);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&movups (&QWP(0x40,$out),$inout4);
&jmp (&label("ctr32_ret"));
&set_label("ctr32_one_shortcut",16);
&movups ($inout0,&QWP(0,$rounds_)); # load ivec
&mov ($rounds,&DWP(240,$key));
&set_label("ctr32_one");
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&movups ($in0,&QWP(0,$inp));
&xorps ($in0,$inout0);
&movups (&QWP(0,$out),$in0);
&jmp (&label("ctr32_ret"));
&set_label("ctr32_two",16);
&call ("_aesni_encrypt2");
&movups ($inout3,&QWP(0,$inp));
&movups ($inout4,&QWP(0x10,$inp));
&xorps ($inout0,$inout3);
&xorps ($inout1,$inout4);
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&jmp (&label("ctr32_ret"));
&set_label("ctr32_three",16);
&call ("_aesni_encrypt3");
&movups ($inout3,&QWP(0,$inp));
&movups ($inout4,&QWP(0x10,$inp));
&xorps ($inout0,$inout3);
&movups ($inout5,&QWP(0x20,$inp));
&xorps ($inout1,$inout4);
&movups (&QWP(0,$out),$inout0);
&xorps ($inout2,$inout5);
&movups (&QWP(0x10,$out),$inout1);
&movups (&QWP(0x20,$out),$inout2);
&jmp (&label("ctr32_ret"));
&set_label("ctr32_four",16);
&call ("_aesni_encrypt4");
&movups ($inout4,&QWP(0,$inp));
&movups ($inout5,&QWP(0x10,$inp));
&movups ($rndkey1,&QWP(0x20,$inp));
&xorps ($inout0,$inout4);
&movups ($rndkey0,&QWP(0x30,$inp));
&xorps ($inout1,$inout5);
&movups (&QWP(0,$out),$inout0);
&xorps ($inout2,$rndkey1);
&movups (&QWP(0x10,$out),$inout1);
&xorps ($inout3,$rndkey0);
&movups (&QWP(0x20,$out),$inout2);
&movups (&QWP(0x30,$out),$inout3);
&set_label("ctr32_ret");
&pxor ("xmm0","xmm0"); # clear register bank
&pxor ("xmm1","xmm1");
&pxor ("xmm2","xmm2");
&pxor ("xmm3","xmm3");
&pxor ("xmm4","xmm4");
&movdqa (&QWP(32,"esp"),"xmm0"); # clear stack
&pxor ("xmm5","xmm5");
&movdqa (&QWP(48,"esp"),"xmm0");
&pxor ("xmm6","xmm6");
&movdqa (&QWP(64,"esp"),"xmm0");
&pxor ("xmm7","xmm7");
&mov ("esp",&DWP(80,"esp"));
&function_end("aesni_ctr32_encrypt_blocks");
######################################################################
# void aesni_xts_[en|de]crypt(const char *inp,char *out,size_t len,
# const AES_KEY *key1, const AES_KEY *key2
# const unsigned char iv[16]);
#
{ my ($tweak,$twtmp,$twres,$twmask)=($rndkey1,$rndkey0,$inout0,$inout1);
&function_begin("aesni_xts_encrypt");
&mov ($key,&wparam(4)); # key2
&mov ($inp,&wparam(5)); # clear-text tweak
&mov ($rounds,&DWP(240,$key)); # key2->rounds
&movups ($inout0,&QWP(0,$inp));
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3)); # key1
&mov ($key_,"esp");
&sub ("esp",16*7+8);
&mov ($rounds,&DWP(240,$key)); # key1->rounds
&and ("esp",-16); # align stack
&mov (&DWP(16*6+0,"esp"),0x87); # compose the magic constant
&mov (&DWP(16*6+4,"esp"),0);
&mov (&DWP(16*6+8,"esp"),1);
&mov (&DWP(16*6+12,"esp"),0);
&mov (&DWP(16*7+0,"esp"),$len); # save original $len
&mov (&DWP(16*7+4,"esp"),$key_); # save original %esp
&movdqa ($tweak,$inout0);
&pxor ($twtmp,$twtmp);
&movdqa ($twmask,&QWP(6*16,"esp")); # 0x0...010...87
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&and ($len,-16);
&mov ($key_,$key); # backup $key
&mov ($rounds_,$rounds); # backup $rounds
&sub ($len,16*6);
&jc (&label("xts_enc_short"));
&shl ($rounds,4);
&mov ($rounds_,16);
&sub ($rounds_,$rounds);
&lea ($key,&DWP(32,$key,$rounds));
&jmp (&label("xts_enc_loop6"));
&set_label("xts_enc_loop6",16);
for ($i=0;$i<4;$i++) {
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&movdqa (&QWP(16*$i,"esp"),$tweak);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd ($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
}
&pshufd ($inout5,$twtmp,0x13);
&movdqa (&QWP(16*$i++,"esp"),$tweak);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&$movekey ($rndkey0,&QWP(0,$key_));
&pand ($inout5,$twmask); # isolate carry and residue
&movups ($inout0,&QWP(0,$inp)); # load input
&pxor ($inout5,$tweak);
# inline _aesni_encrypt6 prologue and flip xor with tweak and key[0]
&mov ($rounds,$rounds_); # restore $rounds
&movdqu ($inout1,&QWP(16*1,$inp));
&xorps ($inout0,$rndkey0); # input^=rndkey[0]
&movdqu ($inout2,&QWP(16*2,$inp));
&pxor ($inout1,$rndkey0);
&movdqu ($inout3,&QWP(16*3,$inp));
&pxor ($inout2,$rndkey0);
&movdqu ($inout4,&QWP(16*4,$inp));
&pxor ($inout3,$rndkey0);
&movdqu ($rndkey1,&QWP(16*5,$inp));
&pxor ($inout4,$rndkey0);
&lea ($inp,&DWP(16*6,$inp));
&pxor ($inout0,&QWP(16*0,"esp")); # input^=tweak
&movdqa (&QWP(16*$i,"esp"),$inout5); # save last tweak
&pxor ($inout5,$rndkey1);
&$movekey ($rndkey1,&QWP(16,$key_));
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&aesenc ($inout0,$rndkey1);
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&aesenc ($inout1,$rndkey1);
&pxor ($inout5,$rndkey0);
&$movekey ($rndkey0,&QWP(32,$key_));
&aesenc ($inout2,$rndkey1);
&aesenc ($inout3,$rndkey1);
&aesenc ($inout4,$rndkey1);
&aesenc ($inout5,$rndkey1);
&call (&label("_aesni_encrypt6_enter"));
&movdqa ($tweak,&QWP(16*5,"esp")); # last tweak
&pxor ($twtmp,$twtmp);
&xorps ($inout0,&QWP(16*0,"esp")); # output^=tweak
&pcmpgtd ($twtmp,$tweak); # broadcast upper bits
&xorps ($inout1,&QWP(16*1,"esp"));
&movups (&QWP(16*0,$out),$inout0); # write output
&xorps ($inout2,&QWP(16*2,"esp"));
&movups (&QWP(16*1,$out),$inout1);
&xorps ($inout3,&QWP(16*3,"esp"));
&movups (&QWP(16*2,$out),$inout2);
&xorps ($inout4,&QWP(16*4,"esp"));
&movups (&QWP(16*3,$out),$inout3);
&xorps ($inout5,$tweak);
&movups (&QWP(16*4,$out),$inout4);
&pshufd ($twres,$twtmp,0x13);
&movups (&QWP(16*5,$out),$inout5);
&lea ($out,&DWP(16*6,$out));
&movdqa ($twmask,&QWP(16*6,"esp")); # 0x0...010...87
&pxor ($twtmp,$twtmp);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&sub ($len,16*6);
&jnc (&label("xts_enc_loop6"));
&mov ($rounds,&DWP(240,$key_)); # restore $rounds
&mov ($key,$key_); # restore $key
&mov ($rounds_,$rounds);
&set_label("xts_enc_short");
&add ($len,16*6);
&jz (&label("xts_enc_done6x"));
&movdqa ($inout3,$tweak); # put aside previous tweak
&cmp ($len,0x20);
&jb (&label("xts_enc_one"));
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&je (&label("xts_enc_two"));
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&movdqa ($inout4,$tweak); # put aside previous tweak
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&cmp ($len,0x40);
&jb (&label("xts_enc_three"));
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&movdqa ($inout5,$tweak); # put aside previous tweak
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&movdqa (&QWP(16*0,"esp"),$inout3);
&movdqa (&QWP(16*1,"esp"),$inout4);
&je (&label("xts_enc_four"));
&movdqa (&QWP(16*2,"esp"),$inout5);
&pshufd ($inout5,$twtmp,0x13);
&movdqa (&QWP(16*3,"esp"),$tweak);
&paddq ($tweak,$tweak); # &psllq($inout0,1);
&pand ($inout5,$twmask); # isolate carry and residue
&pxor ($inout5,$tweak);
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&pxor ($inout0,&QWP(16*0,"esp")); # input^=tweak
&movdqu ($inout3,&QWP(16*3,$inp));
&pxor ($inout1,&QWP(16*1,"esp"));
&movdqu ($inout4,&QWP(16*4,$inp));
&pxor ($inout2,&QWP(16*2,"esp"));
&lea ($inp,&DWP(16*5,$inp));
&pxor ($inout3,&QWP(16*3,"esp"));
&movdqa (&QWP(16*4,"esp"),$inout5); # save last tweak
&pxor ($inout4,$inout5);
&call ("_aesni_encrypt6");
&movaps ($tweak,&QWP(16*4,"esp")); # last tweak
&xorps ($inout0,&QWP(16*0,"esp")); # output^=tweak
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,&QWP(16*2,"esp"));
&movups (&QWP(16*0,$out),$inout0); # write output
&xorps ($inout3,&QWP(16*3,"esp"));
&movups (&QWP(16*1,$out),$inout1);
&xorps ($inout4,$tweak);
&movups (&QWP(16*2,$out),$inout2);
&movups (&QWP(16*3,$out),$inout3);
&movups (&QWP(16*4,$out),$inout4);
&lea ($out,&DWP(16*5,$out));
&jmp (&label("xts_enc_done"));
&set_label("xts_enc_one",16);
&movups ($inout0,&QWP(16*0,$inp)); # load input
&lea ($inp,&DWP(16*1,$inp));
&xorps ($inout0,$inout3); # input^=tweak
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&xorps ($inout0,$inout3); # output^=tweak
&movups (&QWP(16*0,$out),$inout0); # write output
&lea ($out,&DWP(16*1,$out));
&movdqa ($tweak,$inout3); # last tweak
&jmp (&label("xts_enc_done"));
&set_label("xts_enc_two",16);
&movaps ($inout4,$tweak); # put aside last tweak
&movups ($inout0,&QWP(16*0,$inp)); # load input
&movups ($inout1,&QWP(16*1,$inp));
&lea ($inp,&DWP(16*2,$inp));
&xorps ($inout0,$inout3); # input^=tweak
&xorps ($inout1,$inout4);
&call ("_aesni_encrypt2");
&xorps ($inout0,$inout3); # output^=tweak
&xorps ($inout1,$inout4);
&movups (&QWP(16*0,$out),$inout0); # write output
&movups (&QWP(16*1,$out),$inout1);
&lea ($out,&DWP(16*2,$out));
&movdqa ($tweak,$inout4); # last tweak
&jmp (&label("xts_enc_done"));
&set_label("xts_enc_three",16);
&movaps ($inout5,$tweak); # put aside last tweak
&movups ($inout0,&QWP(16*0,$inp)); # load input
&movups ($inout1,&QWP(16*1,$inp));
&movups ($inout2,&QWP(16*2,$inp));
&lea ($inp,&DWP(16*3,$inp));
&xorps ($inout0,$inout3); # input^=tweak
&xorps ($inout1,$inout4);
&xorps ($inout2,$inout5);
&call ("_aesni_encrypt3");
&xorps ($inout0,$inout3); # output^=tweak
&xorps ($inout1,$inout4);
&xorps ($inout2,$inout5);
&movups (&QWP(16*0,$out),$inout0); # write output
&movups (&QWP(16*1,$out),$inout1);
&movups (&QWP(16*2,$out),$inout2);
&lea ($out,&DWP(16*3,$out));
&movdqa ($tweak,$inout5); # last tweak
&jmp (&label("xts_enc_done"));
&set_label("xts_enc_four",16);
&movaps ($inout4,$tweak); # put aside last tweak
&movups ($inout0,&QWP(16*0,$inp)); # load input
&movups ($inout1,&QWP(16*1,$inp));
&movups ($inout2,&QWP(16*2,$inp));
&xorps ($inout0,&QWP(16*0,"esp")); # input^=tweak
&movups ($inout3,&QWP(16*3,$inp));
&lea ($inp,&DWP(16*4,$inp));
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,$inout5);
&xorps ($inout3,$inout4);
&call ("_aesni_encrypt4");
&xorps ($inout0,&QWP(16*0,"esp")); # output^=tweak
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,$inout5);
&movups (&QWP(16*0,$out),$inout0); # write output
&xorps ($inout3,$inout4);
&movups (&QWP(16*1,$out),$inout1);
&movups (&QWP(16*2,$out),$inout2);
&movups (&QWP(16*3,$out),$inout3);
&lea ($out,&DWP(16*4,$out));
&movdqa ($tweak,$inout4); # last tweak
&jmp (&label("xts_enc_done"));
&set_label("xts_enc_done6x",16); # $tweak is pre-calculated
&mov ($len,&DWP(16*7+0,"esp")); # restore original $len
&and ($len,15);
&jz (&label("xts_enc_ret"));
&movdqa ($inout3,$tweak);
&mov (&DWP(16*7+0,"esp"),$len); # save $len%16
&jmp (&label("xts_enc_steal"));
&set_label("xts_enc_done",16);
&mov ($len,&DWP(16*7+0,"esp")); # restore original $len
&pxor ($twtmp,$twtmp);
&and ($len,15);
&jz (&label("xts_enc_ret"));
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&mov (&DWP(16*7+0,"esp"),$len); # save $len%16
&pshufd ($inout3,$twtmp,0x13);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($inout3,&QWP(16*6,"esp")); # isolate carry and residue
&pxor ($inout3,$tweak);
&set_label("xts_enc_steal");
&movz ($rounds,&BP(0,$inp));
&movz ($key,&BP(-16,$out));
&lea ($inp,&DWP(1,$inp));
&mov (&BP(-16,$out),&LB($rounds));
&mov (&BP(0,$out),&LB($key));
&lea ($out,&DWP(1,$out));
&sub ($len,1);
&jnz (&label("xts_enc_steal"));
&sub ($out,&DWP(16*7+0,"esp")); # rewind $out
&mov ($key,$key_); # restore $key
&mov ($rounds,$rounds_); # restore $rounds
&movups ($inout0,&QWP(-16,$out)); # load input
&xorps ($inout0,$inout3); # input^=tweak
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&xorps ($inout0,$inout3); # output^=tweak
&movups (&QWP(-16,$out),$inout0); # write output
&set_label("xts_enc_ret");
&pxor ("xmm0","xmm0"); # clear register bank
&pxor ("xmm1","xmm1");
&pxor ("xmm2","xmm2");
&movdqa (&QWP(16*0,"esp"),"xmm0"); # clear stack
&pxor ("xmm3","xmm3");
&movdqa (&QWP(16*1,"esp"),"xmm0");
&pxor ("xmm4","xmm4");
&movdqa (&QWP(16*2,"esp"),"xmm0");
&pxor ("xmm5","xmm5");
&movdqa (&QWP(16*3,"esp"),"xmm0");
&pxor ("xmm6","xmm6");
&movdqa (&QWP(16*4,"esp"),"xmm0");
&pxor ("xmm7","xmm7");
&movdqa (&QWP(16*5,"esp"),"xmm0");
&mov ("esp",&DWP(16*7+4,"esp")); # restore %esp
&function_end("aesni_xts_encrypt");
&function_begin("aesni_xts_decrypt");
&mov ($key,&wparam(4)); # key2
&mov ($inp,&wparam(5)); # clear-text tweak
&mov ($rounds,&DWP(240,$key)); # key2->rounds
&movups ($inout0,&QWP(0,$inp));
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3)); # key1
&mov ($key_,"esp");
&sub ("esp",16*7+8);
&and ("esp",-16); # align stack
&xor ($rounds_,$rounds_); # if(len%16) len-=16;
&test ($len,15);
&setnz (&LB($rounds_));
&shl ($rounds_,4);
&sub ($len,$rounds_);
&mov (&DWP(16*6+0,"esp"),0x87); # compose the magic constant
&mov (&DWP(16*6+4,"esp"),0);
&mov (&DWP(16*6+8,"esp"),1);
&mov (&DWP(16*6+12,"esp"),0);
&mov (&DWP(16*7+0,"esp"),$len); # save original $len
&mov (&DWP(16*7+4,"esp"),$key_); # save original %esp
&mov ($rounds,&DWP(240,$key)); # key1->rounds
&mov ($key_,$key); # backup $key
&mov ($rounds_,$rounds); # backup $rounds
&movdqa ($tweak,$inout0);
&pxor ($twtmp,$twtmp);
&movdqa ($twmask,&QWP(6*16,"esp")); # 0x0...010...87
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&and ($len,-16);
&sub ($len,16*6);
&jc (&label("xts_dec_short"));
&shl ($rounds,4);
&mov ($rounds_,16);
&sub ($rounds_,$rounds);
&lea ($key,&DWP(32,$key,$rounds));
&jmp (&label("xts_dec_loop6"));
&set_label("xts_dec_loop6",16);
for ($i=0;$i<4;$i++) {
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&movdqa (&QWP(16*$i,"esp"),$tweak);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd ($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
}
&pshufd ($inout5,$twtmp,0x13);
&movdqa (&QWP(16*$i++,"esp"),$tweak);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&$movekey ($rndkey0,&QWP(0,$key_));
&pand ($inout5,$twmask); # isolate carry and residue
&movups ($inout0,&QWP(0,$inp)); # load input
&pxor ($inout5,$tweak);
# inline _aesni_encrypt6 prologue and flip xor with tweak and key[0]
&mov ($rounds,$rounds_);
&movdqu ($inout1,&QWP(16*1,$inp));
&xorps ($inout0,$rndkey0); # input^=rndkey[0]
&movdqu ($inout2,&QWP(16*2,$inp));
&pxor ($inout1,$rndkey0);
&movdqu ($inout3,&QWP(16*3,$inp));
&pxor ($inout2,$rndkey0);
&movdqu ($inout4,&QWP(16*4,$inp));
&pxor ($inout3,$rndkey0);
&movdqu ($rndkey1,&QWP(16*5,$inp));
&pxor ($inout4,$rndkey0);
&lea ($inp,&DWP(16*6,$inp));
&pxor ($inout0,&QWP(16*0,"esp")); # input^=tweak
&movdqa (&QWP(16*$i,"esp"),$inout5); # save last tweak
&pxor ($inout5,$rndkey1);
&$movekey ($rndkey1,&QWP(16,$key_));
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&aesdec ($inout0,$rndkey1);
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&aesdec ($inout1,$rndkey1);
&pxor ($inout5,$rndkey0);
&$movekey ($rndkey0,&QWP(32,$key_));
&aesdec ($inout2,$rndkey1);
&aesdec ($inout3,$rndkey1);
&aesdec ($inout4,$rndkey1);
&aesdec ($inout5,$rndkey1);
&call (&label("_aesni_decrypt6_enter"));
&movdqa ($tweak,&QWP(16*5,"esp")); # last tweak
&pxor ($twtmp,$twtmp);
&xorps ($inout0,&QWP(16*0,"esp")); # output^=tweak
&pcmpgtd ($twtmp,$tweak); # broadcast upper bits
&xorps ($inout1,&QWP(16*1,"esp"));
&movups (&QWP(16*0,$out),$inout0); # write output
&xorps ($inout2,&QWP(16*2,"esp"));
&movups (&QWP(16*1,$out),$inout1);
&xorps ($inout3,&QWP(16*3,"esp"));
&movups (&QWP(16*2,$out),$inout2);
&xorps ($inout4,&QWP(16*4,"esp"));
&movups (&QWP(16*3,$out),$inout3);
&xorps ($inout5,$tweak);
&movups (&QWP(16*4,$out),$inout4);
&pshufd ($twres,$twtmp,0x13);
&movups (&QWP(16*5,$out),$inout5);
&lea ($out,&DWP(16*6,$out));
&movdqa ($twmask,&QWP(16*6,"esp")); # 0x0...010...87
&pxor ($twtmp,$twtmp);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&sub ($len,16*6);
&jnc (&label("xts_dec_loop6"));
&mov ($rounds,&DWP(240,$key_)); # restore $rounds
&mov ($key,$key_); # restore $key
&mov ($rounds_,$rounds);
&set_label("xts_dec_short");
&add ($len,16*6);
&jz (&label("xts_dec_done6x"));
&movdqa ($inout3,$tweak); # put aside previous tweak
&cmp ($len,0x20);
&jb (&label("xts_dec_one"));
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&je (&label("xts_dec_two"));
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&movdqa ($inout4,$tweak); # put aside previous tweak
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&cmp ($len,0x40);
&jb (&label("xts_dec_three"));
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&movdqa ($inout5,$tweak); # put aside previous tweak
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&movdqa (&QWP(16*0,"esp"),$inout3);
&movdqa (&QWP(16*1,"esp"),$inout4);
&je (&label("xts_dec_four"));
&movdqa (&QWP(16*2,"esp"),$inout5);
&pshufd ($inout5,$twtmp,0x13);
&movdqa (&QWP(16*3,"esp"),$tweak);
&paddq ($tweak,$tweak); # &psllq($inout0,1);
&pand ($inout5,$twmask); # isolate carry and residue
&pxor ($inout5,$tweak);
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&pxor ($inout0,&QWP(16*0,"esp")); # input^=tweak
&movdqu ($inout3,&QWP(16*3,$inp));
&pxor ($inout1,&QWP(16*1,"esp"));
&movdqu ($inout4,&QWP(16*4,$inp));
&pxor ($inout2,&QWP(16*2,"esp"));
&lea ($inp,&DWP(16*5,$inp));
&pxor ($inout3,&QWP(16*3,"esp"));
&movdqa (&QWP(16*4,"esp"),$inout5); # save last tweak
&pxor ($inout4,$inout5);
&call ("_aesni_decrypt6");
&movaps ($tweak,&QWP(16*4,"esp")); # last tweak
&xorps ($inout0,&QWP(16*0,"esp")); # output^=tweak
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,&QWP(16*2,"esp"));
&movups (&QWP(16*0,$out),$inout0); # write output
&xorps ($inout3,&QWP(16*3,"esp"));
&movups (&QWP(16*1,$out),$inout1);
&xorps ($inout4,$tweak);
&movups (&QWP(16*2,$out),$inout2);
&movups (&QWP(16*3,$out),$inout3);
&movups (&QWP(16*4,$out),$inout4);
&lea ($out,&DWP(16*5,$out));
&jmp (&label("xts_dec_done"));
&set_label("xts_dec_one",16);
&movups ($inout0,&QWP(16*0,$inp)); # load input
&lea ($inp,&DWP(16*1,$inp));
&xorps ($inout0,$inout3); # input^=tweak
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&xorps ($inout0,$inout3); # output^=tweak
&movups (&QWP(16*0,$out),$inout0); # write output
&lea ($out,&DWP(16*1,$out));
&movdqa ($tweak,$inout3); # last tweak
&jmp (&label("xts_dec_done"));
&set_label("xts_dec_two",16);
&movaps ($inout4,$tweak); # put aside last tweak
&movups ($inout0,&QWP(16*0,$inp)); # load input
&movups ($inout1,&QWP(16*1,$inp));
&lea ($inp,&DWP(16*2,$inp));
&xorps ($inout0,$inout3); # input^=tweak
&xorps ($inout1,$inout4);
&call ("_aesni_decrypt2");
&xorps ($inout0,$inout3); # output^=tweak
&xorps ($inout1,$inout4);
&movups (&QWP(16*0,$out),$inout0); # write output
&movups (&QWP(16*1,$out),$inout1);
&lea ($out,&DWP(16*2,$out));
&movdqa ($tweak,$inout4); # last tweak
&jmp (&label("xts_dec_done"));
&set_label("xts_dec_three",16);
&movaps ($inout5,$tweak); # put aside last tweak
&movups ($inout0,&QWP(16*0,$inp)); # load input
&movups ($inout1,&QWP(16*1,$inp));
&movups ($inout2,&QWP(16*2,$inp));
&lea ($inp,&DWP(16*3,$inp));
&xorps ($inout0,$inout3); # input^=tweak
&xorps ($inout1,$inout4);
&xorps ($inout2,$inout5);
&call ("_aesni_decrypt3");
&xorps ($inout0,$inout3); # output^=tweak
&xorps ($inout1,$inout4);
&xorps ($inout2,$inout5);
&movups (&QWP(16*0,$out),$inout0); # write output
&movups (&QWP(16*1,$out),$inout1);
&movups (&QWP(16*2,$out),$inout2);
&lea ($out,&DWP(16*3,$out));
&movdqa ($tweak,$inout5); # last tweak
&jmp (&label("xts_dec_done"));
&set_label("xts_dec_four",16);
&movaps ($inout4,$tweak); # put aside last tweak
&movups ($inout0,&QWP(16*0,$inp)); # load input
&movups ($inout1,&QWP(16*1,$inp));
&movups ($inout2,&QWP(16*2,$inp));
&xorps ($inout0,&QWP(16*0,"esp")); # input^=tweak
&movups ($inout3,&QWP(16*3,$inp));
&lea ($inp,&DWP(16*4,$inp));
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,$inout5);
&xorps ($inout3,$inout4);
&call ("_aesni_decrypt4");
&xorps ($inout0,&QWP(16*0,"esp")); # output^=tweak
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,$inout5);
&movups (&QWP(16*0,$out),$inout0); # write output
&xorps ($inout3,$inout4);
&movups (&QWP(16*1,$out),$inout1);
&movups (&QWP(16*2,$out),$inout2);
&movups (&QWP(16*3,$out),$inout3);
&lea ($out,&DWP(16*4,$out));
&movdqa ($tweak,$inout4); # last tweak
&jmp (&label("xts_dec_done"));
&set_label("xts_dec_done6x",16); # $tweak is pre-calculated
&mov ($len,&DWP(16*7+0,"esp")); # restore original $len
&and ($len,15);
&jz (&label("xts_dec_ret"));
&mov (&DWP(16*7+0,"esp"),$len); # save $len%16
&jmp (&label("xts_dec_only_one_more"));
&set_label("xts_dec_done",16);
&mov ($len,&DWP(16*7+0,"esp")); # restore original $len
&pxor ($twtmp,$twtmp);
&and ($len,15);
&jz (&label("xts_dec_ret"));
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&mov (&DWP(16*7+0,"esp"),$len); # save $len%16
&pshufd ($twres,$twtmp,0x13);
&pxor ($twtmp,$twtmp);
&movdqa ($twmask,&QWP(16*6,"esp"));
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($twres,$twmask); # isolate carry and residue
&pcmpgtd($twtmp,$tweak); # broadcast upper bits
&pxor ($tweak,$twres);
&set_label("xts_dec_only_one_more");
&pshufd ($inout3,$twtmp,0x13);
&movdqa ($inout4,$tweak); # put aside previous tweak
&paddq ($tweak,$tweak); # &psllq($tweak,1);
&pand ($inout3,$twmask); # isolate carry and residue
&pxor ($inout3,$tweak);
&mov ($key,$key_); # restore $key
&mov ($rounds,$rounds_); # restore $rounds
&movups ($inout0,&QWP(0,$inp)); # load input
&xorps ($inout0,$inout3); # input^=tweak
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&xorps ($inout0,$inout3); # output^=tweak
&movups (&QWP(0,$out),$inout0); # write output
&set_label("xts_dec_steal");
&movz ($rounds,&BP(16,$inp));
&movz ($key,&BP(0,$out));
&lea ($inp,&DWP(1,$inp));
&mov (&BP(0,$out),&LB($rounds));
&mov (&BP(16,$out),&LB($key));
&lea ($out,&DWP(1,$out));
&sub ($len,1);
&jnz (&label("xts_dec_steal"));
&sub ($out,&DWP(16*7+0,"esp")); # rewind $out
&mov ($key,$key_); # restore $key
&mov ($rounds,$rounds_); # restore $rounds
&movups ($inout0,&QWP(0,$out)); # load input
&xorps ($inout0,$inout4); # input^=tweak
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&xorps ($inout0,$inout4); # output^=tweak
&movups (&QWP(0,$out),$inout0); # write output
&set_label("xts_dec_ret");
&pxor ("xmm0","xmm0"); # clear register bank
&pxor ("xmm1","xmm1");
&pxor ("xmm2","xmm2");
&movdqa (&QWP(16*0,"esp"),"xmm0"); # clear stack
&pxor ("xmm3","xmm3");
&movdqa (&QWP(16*1,"esp"),"xmm0");
&pxor ("xmm4","xmm4");
&movdqa (&QWP(16*2,"esp"),"xmm0");
&pxor ("xmm5","xmm5");
&movdqa (&QWP(16*3,"esp"),"xmm0");
&pxor ("xmm6","xmm6");
&movdqa (&QWP(16*4,"esp"),"xmm0");
&pxor ("xmm7","xmm7");
&movdqa (&QWP(16*5,"esp"),"xmm0");
&mov ("esp",&DWP(16*7+4,"esp")); # restore %esp
&function_end("aesni_xts_decrypt");
}
######################################################################
# void aesni_ocb_[en|de]crypt(const char *inp, char *out, size_t blocks,
# const AES_KEY *key, unsigned int start_block_num,
# unsigned char offset_i[16], const unsigned char L_[][16],
# unsigned char checksum[16]);
#
{
# offsets within stack frame
my $checksum = 16*6;
my ($key_off,$rounds_off,$out_off,$end_off,$esp_off)=map(16*7+4*$_,(0..4));
# reassigned registers
my ($l_,$block,$i1,$i3,$i5) = ($rounds_,$key_,$rounds,$len,$out);
# $l_, $blocks, $inp, $key are permanently allocated in registers;
# remaining non-volatile ones are offloaded to stack, which even
# stay invariant after written to stack.
&function_begin("aesni_ocb_encrypt");
&mov ($rounds,&wparam(5)); # &offset_i
&mov ($rounds_,&wparam(7)); # &checksum
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3));
&movdqu ($rndkey0,&QWP(0,$rounds)); # load offset_i
&mov ($block,&wparam(4)); # start_block_num
&movdqu ($rndkey1,&QWP(0,$rounds_)); # load checksum
&mov ($l_,&wparam(6)); # L_
&mov ($rounds,"esp");
&sub ("esp",$esp_off+4); # alloca
&and ("esp",-16); # align stack
&sub ($out,$inp);
&shl ($len,4);
&lea ($len,&DWP(-16*6,$inp,$len)); # end of input - 16*6
&mov (&DWP($out_off,"esp"),$out);
&mov (&DWP($end_off,"esp"),$len);
&mov (&DWP($esp_off,"esp"),$rounds);
&mov ($rounds,&DWP(240,$key));
&test ($block,1);
&jnz (&label("odd"));
&bsf ($i3,$block);
&add ($block,1);
&shl ($i3,4);
&movdqu ($inout5,&QWP(0,$l_,$i3));
&mov ($i3,$key); # put aside key
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&lea ($inp,&DWP(16,$inp));
&pxor ($inout5,$rndkey0); # ^ last offset_i
&pxor ($rndkey1,$inout0); # checksum
&pxor ($inout0,$inout5); # ^ offset_i
&movdqa ($inout4,$rndkey1);
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&xorps ($inout0,$inout5); # ^ offset_i
&movdqa ($rndkey0,$inout5); # pass last offset_i
&movdqa ($rndkey1,$inout4); # pass the checksum
&movups (&QWP(-16,$out,$inp),$inout0); # store output
&mov ($rounds,&DWP(240,$i3));
&mov ($key,$i3); # restore key
&mov ($len,&DWP($end_off,"esp"));
&set_label("odd");
&shl ($rounds,4);
&mov ($out,16);
&sub ($out,$rounds); # twisted rounds
&mov (&DWP($key_off,"esp"),$key);
&lea ($key,&DWP(32,$key,$rounds)); # end of key schedule
&mov (&DWP($rounds_off,"esp"),$out);
&cmp ($inp,$len);
&ja (&label("short"));
&jmp (&label("grandloop"));
&set_label("grandloop",32);
&lea ($i1,&DWP(1,$block));
&lea ($i3,&DWP(3,$block));
&lea ($i5,&DWP(5,$block));
&add ($block,6);
&bsf ($i1,$i1);
&bsf ($i3,$i3);
&bsf ($i5,$i5);
&shl ($i1,4);
&shl ($i3,4);
&shl ($i5,4);
&movdqu ($inout0,&QWP(0,$l_));
&movdqu ($inout1,&QWP(0,$l_,$i1));
&mov ($rounds,&DWP($rounds_off,"esp"));
&movdqa ($inout2,$inout0);
&movdqu ($inout3,&QWP(0,$l_,$i3));
&movdqa ($inout4,$inout0);
&movdqu ($inout5,&QWP(0,$l_,$i5));
&pxor ($inout0,$rndkey0); # ^ last offset_i
&pxor ($inout1,$inout0);
&movdqa (&QWP(16*0,"esp"),$inout0);
&pxor ($inout2,$inout1);
&movdqa (&QWP(16*1,"esp"),$inout1);
&pxor ($inout3,$inout2);
&movdqa (&QWP(16*2,"esp"),$inout2);
&pxor ($inout4,$inout3);
&movdqa (&QWP(16*3,"esp"),$inout3);
&pxor ($inout5,$inout4);
&movdqa (&QWP(16*4,"esp"),$inout4);
&movdqa (&QWP(16*5,"esp"),$inout5);
&$movekey ($rndkey0,&QWP(-48,$key,$rounds));
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&movdqu ($inout3,&QWP(16*3,$inp));
&movdqu ($inout4,&QWP(16*4,$inp));
&movdqu ($inout5,&QWP(16*5,$inp));
&lea ($inp,&DWP(16*6,$inp));
&pxor ($rndkey1,$inout0); # checksum
&pxor ($inout0,$rndkey0); # ^ roundkey[0]
&pxor ($rndkey1,$inout1);
&pxor ($inout1,$rndkey0);
&pxor ($rndkey1,$inout2);
&pxor ($inout2,$rndkey0);
&pxor ($rndkey1,$inout3);
&pxor ($inout3,$rndkey0);
&pxor ($rndkey1,$inout4);
&pxor ($inout4,$rndkey0);
&pxor ($rndkey1,$inout5);
&pxor ($inout5,$rndkey0);
&movdqa (&QWP($checksum,"esp"),$rndkey1);
&$movekey ($rndkey1,&QWP(-32,$key,$rounds));
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&pxor ($inout5,&QWP(16*5,"esp"));
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&aesenc ($inout0,$rndkey1);
&aesenc ($inout1,$rndkey1);
&aesenc ($inout2,$rndkey1);
&aesenc ($inout3,$rndkey1);
&aesenc ($inout4,$rndkey1);
&aesenc ($inout5,$rndkey1);
&mov ($out,&DWP($out_off,"esp"));
&mov ($len,&DWP($end_off,"esp"));
&call ("_aesni_encrypt6_enter");
&movdqa ($rndkey0,&QWP(16*5,"esp")); # pass last offset_i
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&pxor ($inout5,$rndkey0);
&movdqa ($rndkey1,&QWP($checksum,"esp"));# pass the checksum
&movdqu (&QWP(-16*6,$out,$inp),$inout0);# store output
&movdqu (&QWP(-16*5,$out,$inp),$inout1);
&movdqu (&QWP(-16*4,$out,$inp),$inout2);
&movdqu (&QWP(-16*3,$out,$inp),$inout3);
&movdqu (&QWP(-16*2,$out,$inp),$inout4);
&movdqu (&QWP(-16*1,$out,$inp),$inout5);
&cmp ($inp,$len); # done yet?
&jb (&label("grandloop"));
&set_label("short");
&add ($len,16*6);
&sub ($len,$inp);
&jz (&label("done"));
&cmp ($len,16*2);
&jb (&label("one"));
&je (&label("two"));
&cmp ($len,16*4);
&jb (&label("three"));
&je (&label("four"));
&lea ($i1,&DWP(1,$block));
&lea ($i3,&DWP(3,$block));
&bsf ($i1,$i1);
&bsf ($i3,$i3);
&shl ($i1,4);
&shl ($i3,4);
&movdqu ($inout0,&QWP(0,$l_));
&movdqu ($inout1,&QWP(0,$l_,$i1));
&mov ($rounds,&DWP($rounds_off,"esp"));
&movdqa ($inout2,$inout0);
&movdqu ($inout3,&QWP(0,$l_,$i3));
&movdqa ($inout4,$inout0);
&pxor ($inout0,$rndkey0); # ^ last offset_i
&pxor ($inout1,$inout0);
&movdqa (&QWP(16*0,"esp"),$inout0);
&pxor ($inout2,$inout1);
&movdqa (&QWP(16*1,"esp"),$inout1);
&pxor ($inout3,$inout2);
&movdqa (&QWP(16*2,"esp"),$inout2);
&pxor ($inout4,$inout3);
&movdqa (&QWP(16*3,"esp"),$inout3);
&pxor ($inout5,$inout4);
&movdqa (&QWP(16*4,"esp"),$inout4);
&$movekey ($rndkey0,&QWP(-48,$key,$rounds));
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&movdqu ($inout3,&QWP(16*3,$inp));
&movdqu ($inout4,&QWP(16*4,$inp));
&pxor ($inout5,$inout5);
&pxor ($rndkey1,$inout0); # checksum
&pxor ($inout0,$rndkey0); # ^ roundkey[0]
&pxor ($rndkey1,$inout1);
&pxor ($inout1,$rndkey0);
&pxor ($rndkey1,$inout2);
&pxor ($inout2,$rndkey0);
&pxor ($rndkey1,$inout3);
&pxor ($inout3,$rndkey0);
&pxor ($rndkey1,$inout4);
&pxor ($inout4,$rndkey0);
&movdqa (&QWP($checksum,"esp"),$rndkey1);
&$movekey ($rndkey1,&QWP(-32,$key,$rounds));
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&aesenc ($inout0,$rndkey1);
&aesenc ($inout1,$rndkey1);
&aesenc ($inout2,$rndkey1);
&aesenc ($inout3,$rndkey1);
&aesenc ($inout4,$rndkey1);
&aesenc ($inout5,$rndkey1);
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_encrypt6_enter");
&movdqa ($rndkey0,&QWP(16*4,"esp")); # pass last offset_i
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,$rndkey0);
&movdqa ($rndkey1,&QWP($checksum,"esp"));# pass the checksum
&movdqu (&QWP(16*0,$out,$inp),$inout0); # store output
&movdqu (&QWP(16*1,$out,$inp),$inout1);
&movdqu (&QWP(16*2,$out,$inp),$inout2);
&movdqu (&QWP(16*3,$out,$inp),$inout3);
&movdqu (&QWP(16*4,$out,$inp),$inout4);
&jmp (&label("done"));
&set_label("one",16);
&movdqu ($inout5,&QWP(0,$l_));
&mov ($key,&DWP($key_off,"esp")); # restore key
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&mov ($rounds,&DWP(240,$key));
&pxor ($inout5,$rndkey0); # ^ last offset_i
&pxor ($rndkey1,$inout0); # checksum
&pxor ($inout0,$inout5); # ^ offset_i
&movdqa ($inout4,$rndkey1);
&mov ($out,&DWP($out_off,"esp"));
if ($inline)
{ &aesni_inline_generate1("enc"); }
else
{ &call ("_aesni_encrypt1"); }
&xorps ($inout0,$inout5); # ^ offset_i
&movdqa ($rndkey0,$inout5); # pass last offset_i
&movdqa ($rndkey1,$inout4); # pass the checksum
&movups (&QWP(0,$out,$inp),$inout0);
&jmp (&label("done"));
&set_label("two",16);
&lea ($i1,&DWP(1,$block));
&mov ($key,&DWP($key_off,"esp")); # restore key
&bsf ($i1,$i1);
&shl ($i1,4);
&movdqu ($inout4,&QWP(0,$l_));
&movdqu ($inout5,&QWP(0,$l_,$i1));
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&mov ($rounds,&DWP(240,$key));
&pxor ($inout4,$rndkey0); # ^ last offset_i
&pxor ($inout5,$inout4);
&pxor ($rndkey1,$inout0); # checksum
&pxor ($inout0,$inout4); # ^ offset_i
&pxor ($rndkey1,$inout1);
&pxor ($inout1,$inout5);
&movdqa ($inout3,$rndkey1)
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_encrypt2");
&xorps ($inout0,$inout4); # ^ offset_i
&xorps ($inout1,$inout5);
&movdqa ($rndkey0,$inout5); # pass last offset_i
&movdqa ($rndkey1,$inout3); # pass the checksum
&movups (&QWP(16*0,$out,$inp),$inout0); # store output
&movups (&QWP(16*1,$out,$inp),$inout1);
&jmp (&label("done"));
&set_label("three",16);
&lea ($i1,&DWP(1,$block));
&mov ($key,&DWP($key_off,"esp")); # restore key
&bsf ($i1,$i1);
&shl ($i1,4);
&movdqu ($inout3,&QWP(0,$l_));
&movdqu ($inout4,&QWP(0,$l_,$i1));
&movdqa ($inout5,$inout3);
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&mov ($rounds,&DWP(240,$key));
&pxor ($inout3,$rndkey0); # ^ last offset_i
&pxor ($inout4,$inout3);
&pxor ($inout5,$inout4);
&pxor ($rndkey1,$inout0); # checksum
&pxor ($inout0,$inout3); # ^ offset_i
&pxor ($rndkey1,$inout1);
&pxor ($inout1,$inout4);
&pxor ($rndkey1,$inout2);
&pxor ($inout2,$inout5);
&movdqa (&QWP($checksum,"esp"),$rndkey1);
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_encrypt3");
&xorps ($inout0,$inout3); # ^ offset_i
&xorps ($inout1,$inout4);
&xorps ($inout2,$inout5);
&movdqa ($rndkey0,$inout5); # pass last offset_i
&movdqa ($rndkey1,&QWP($checksum,"esp"));# pass the checksum
&movups (&QWP(16*0,$out,$inp),$inout0); # store output
&movups (&QWP(16*1,$out,$inp),$inout1);
&movups (&QWP(16*2,$out,$inp),$inout2);
&jmp (&label("done"));
&set_label("four",16);
&lea ($i1,&DWP(1,$block));
&lea ($i3,&DWP(3,$block));
&bsf ($i1,$i1);
&bsf ($i3,$i3);
&mov ($key,&DWP($key_off,"esp")); # restore key
&shl ($i1,4);
&shl ($i3,4);
&movdqu ($inout2,&QWP(0,$l_));
&movdqu ($inout3,&QWP(0,$l_,$i1));
&movdqa ($inout4,$inout2);
&movdqu ($inout5,&QWP(0,$l_,$i3));
&pxor ($inout2,$rndkey0); # ^ last offset_i
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&pxor ($inout3,$inout2);
&movdqu ($inout1,&QWP(16*1,$inp));
&pxor ($inout4,$inout3);
&movdqa (&QWP(16*0,"esp"),$inout2);
&pxor ($inout5,$inout4);
&movdqa (&QWP(16*1,"esp"),$inout3);
&movdqu ($inout2,&QWP(16*2,$inp));
&movdqu ($inout3,&QWP(16*3,$inp));
&mov ($rounds,&DWP(240,$key));
&pxor ($rndkey1,$inout0); # checksum
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($rndkey1,$inout1);
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($rndkey1,$inout2);
&pxor ($inout2,$inout4);
&pxor ($rndkey1,$inout3);
&pxor ($inout3,$inout5);
&movdqa (&QWP($checksum,"esp"),$rndkey1)
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_encrypt4");
&xorps ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,$inout4);
&movups (&QWP(16*0,$out,$inp),$inout0); # store output
&xorps ($inout3,$inout5);
&movups (&QWP(16*1,$out,$inp),$inout1);
&movdqa ($rndkey0,$inout5); # pass last offset_i
&movups (&QWP(16*2,$out,$inp),$inout2);
&movdqa ($rndkey1,&QWP($checksum,"esp"));# pass the checksum
&movups (&QWP(16*3,$out,$inp),$inout3);
&set_label("done");
&mov ($key,&DWP($esp_off,"esp"));
&pxor ($inout0,$inout0); # clear register bank
&pxor ($inout1,$inout1);
&movdqa (&QWP(16*0,"esp"),$inout0); # clear stack
&pxor ($inout2,$inout2);
&movdqa (&QWP(16*1,"esp"),$inout0);
&pxor ($inout3,$inout3);
&movdqa (&QWP(16*2,"esp"),$inout0);
&pxor ($inout4,$inout4);
&movdqa (&QWP(16*3,"esp"),$inout0);
&pxor ($inout5,$inout5);
&movdqa (&QWP(16*4,"esp"),$inout0);
&movdqa (&QWP(16*5,"esp"),$inout0);
&movdqa (&QWP(16*6,"esp"),$inout0);
&lea ("esp",&DWP(0,$key));
&mov ($rounds,&wparam(5)); # &offset_i
&mov ($rounds_,&wparam(7)); # &checksum
&movdqu (&QWP(0,$rounds),$rndkey0);
&pxor ($rndkey0,$rndkey0);
&movdqu (&QWP(0,$rounds_),$rndkey1);
&pxor ($rndkey1,$rndkey1);
&function_end("aesni_ocb_encrypt");
&function_begin("aesni_ocb_decrypt");
&mov ($rounds,&wparam(5)); # &offset_i
&mov ($rounds_,&wparam(7)); # &checksum
&mov ($inp,&wparam(0));
&mov ($out,&wparam(1));
&mov ($len,&wparam(2));
&mov ($key,&wparam(3));
&movdqu ($rndkey0,&QWP(0,$rounds)); # load offset_i
&mov ($block,&wparam(4)); # start_block_num
&movdqu ($rndkey1,&QWP(0,$rounds_)); # load checksum
&mov ($l_,&wparam(6)); # L_
&mov ($rounds,"esp");
&sub ("esp",$esp_off+4); # alloca
&and ("esp",-16); # align stack
&sub ($out,$inp);
&shl ($len,4);
&lea ($len,&DWP(-16*6,$inp,$len)); # end of input - 16*6
&mov (&DWP($out_off,"esp"),$out);
&mov (&DWP($end_off,"esp"),$len);
&mov (&DWP($esp_off,"esp"),$rounds);
&mov ($rounds,&DWP(240,$key));
&test ($block,1);
&jnz (&label("odd"));
&bsf ($i3,$block);
&add ($block,1);
&shl ($i3,4);
&movdqu ($inout5,&QWP(0,$l_,$i3));
&mov ($i3,$key); # put aside key
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&lea ($inp,&DWP(16,$inp));
&pxor ($inout5,$rndkey0); # ^ last offset_i
&pxor ($inout0,$inout5); # ^ offset_i
&movdqa ($inout4,$rndkey1);
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&xorps ($inout0,$inout5); # ^ offset_i
&movaps ($rndkey1,$inout4); # pass the checksum
&movdqa ($rndkey0,$inout5); # pass last offset_i
&xorps ($rndkey1,$inout0); # checksum
&movups (&QWP(-16,$out,$inp),$inout0); # store output
&mov ($rounds,&DWP(240,$i3));
&mov ($key,$i3); # restore key
&mov ($len,&DWP($end_off,"esp"));
&set_label("odd");
&shl ($rounds,4);
&mov ($out,16);
&sub ($out,$rounds); # twisted rounds
&mov (&DWP($key_off,"esp"),$key);
&lea ($key,&DWP(32,$key,$rounds)); # end of key schedule
&mov (&DWP($rounds_off,"esp"),$out);
&cmp ($inp,$len);
&ja (&label("short"));
&jmp (&label("grandloop"));
&set_label("grandloop",32);
&lea ($i1,&DWP(1,$block));
&lea ($i3,&DWP(3,$block));
&lea ($i5,&DWP(5,$block));
&add ($block,6);
&bsf ($i1,$i1);
&bsf ($i3,$i3);
&bsf ($i5,$i5);
&shl ($i1,4);
&shl ($i3,4);
&shl ($i5,4);
&movdqu ($inout0,&QWP(0,$l_));
&movdqu ($inout1,&QWP(0,$l_,$i1));
&mov ($rounds,&DWP($rounds_off,"esp"));
&movdqa ($inout2,$inout0);
&movdqu ($inout3,&QWP(0,$l_,$i3));
&movdqa ($inout4,$inout0);
&movdqu ($inout5,&QWP(0,$l_,$i5));
&pxor ($inout0,$rndkey0); # ^ last offset_i
&pxor ($inout1,$inout0);
&movdqa (&QWP(16*0,"esp"),$inout0);
&pxor ($inout2,$inout1);
&movdqa (&QWP(16*1,"esp"),$inout1);
&pxor ($inout3,$inout2);
&movdqa (&QWP(16*2,"esp"),$inout2);
&pxor ($inout4,$inout3);
&movdqa (&QWP(16*3,"esp"),$inout3);
&pxor ($inout5,$inout4);
&movdqa (&QWP(16*4,"esp"),$inout4);
&movdqa (&QWP(16*5,"esp"),$inout5);
&$movekey ($rndkey0,&QWP(-48,$key,$rounds));
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&movdqu ($inout3,&QWP(16*3,$inp));
&movdqu ($inout4,&QWP(16*4,$inp));
&movdqu ($inout5,&QWP(16*5,$inp));
&lea ($inp,&DWP(16*6,$inp));
&movdqa (&QWP($checksum,"esp"),$rndkey1);
&pxor ($inout0,$rndkey0); # ^ roundkey[0]
&pxor ($inout1,$rndkey0);
&pxor ($inout2,$rndkey0);
&pxor ($inout3,$rndkey0);
&pxor ($inout4,$rndkey0);
&pxor ($inout5,$rndkey0);
&$movekey ($rndkey1,&QWP(-32,$key,$rounds));
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&pxor ($inout5,&QWP(16*5,"esp"));
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&aesdec ($inout0,$rndkey1);
&aesdec ($inout1,$rndkey1);
&aesdec ($inout2,$rndkey1);
&aesdec ($inout3,$rndkey1);
&aesdec ($inout4,$rndkey1);
&aesdec ($inout5,$rndkey1);
&mov ($out,&DWP($out_off,"esp"));
&mov ($len,&DWP($end_off,"esp"));
&call ("_aesni_decrypt6_enter");
&movdqa ($rndkey0,&QWP(16*5,"esp")); # pass last offset_i
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&movdqa ($rndkey1,&QWP($checksum,"esp"));
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&pxor ($inout5,$rndkey0);
&pxor ($rndkey1,$inout0); # checksum
&movdqu (&QWP(-16*6,$out,$inp),$inout0);# store output
&pxor ($rndkey1,$inout1);
&movdqu (&QWP(-16*5,$out,$inp),$inout1);
&pxor ($rndkey1,$inout2);
&movdqu (&QWP(-16*4,$out,$inp),$inout2);
&pxor ($rndkey1,$inout3);
&movdqu (&QWP(-16*3,$out,$inp),$inout3);
&pxor ($rndkey1,$inout4);
&movdqu (&QWP(-16*2,$out,$inp),$inout4);
&pxor ($rndkey1,$inout5);
&movdqu (&QWP(-16*1,$out,$inp),$inout5);
&cmp ($inp,$len); # done yet?
&jb (&label("grandloop"));
&set_label("short");
&add ($len,16*6);
&sub ($len,$inp);
&jz (&label("done"));
&cmp ($len,16*2);
&jb (&label("one"));
&je (&label("two"));
&cmp ($len,16*4);
&jb (&label("three"));
&je (&label("four"));
&lea ($i1,&DWP(1,$block));
&lea ($i3,&DWP(3,$block));
&bsf ($i1,$i1);
&bsf ($i3,$i3);
&shl ($i1,4);
&shl ($i3,4);
&movdqu ($inout0,&QWP(0,$l_));
&movdqu ($inout1,&QWP(0,$l_,$i1));
&mov ($rounds,&DWP($rounds_off,"esp"));
&movdqa ($inout2,$inout0);
&movdqu ($inout3,&QWP(0,$l_,$i3));
&movdqa ($inout4,$inout0);
&pxor ($inout0,$rndkey0); # ^ last offset_i
&pxor ($inout1,$inout0);
&movdqa (&QWP(16*0,"esp"),$inout0);
&pxor ($inout2,$inout1);
&movdqa (&QWP(16*1,"esp"),$inout1);
&pxor ($inout3,$inout2);
&movdqa (&QWP(16*2,"esp"),$inout2);
&pxor ($inout4,$inout3);
&movdqa (&QWP(16*3,"esp"),$inout3);
&pxor ($inout5,$inout4);
&movdqa (&QWP(16*4,"esp"),$inout4);
&$movekey ($rndkey0,&QWP(-48,$key,$rounds));
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&movdqu ($inout3,&QWP(16*3,$inp));
&movdqu ($inout4,&QWP(16*4,$inp));
&pxor ($inout5,$inout5);
&movdqa (&QWP($checksum,"esp"),$rndkey1);
&pxor ($inout0,$rndkey0); # ^ roundkey[0]
&pxor ($inout1,$rndkey0);
&pxor ($inout2,$rndkey0);
&pxor ($inout3,$rndkey0);
&pxor ($inout4,$rndkey0);
&$movekey ($rndkey1,&QWP(-32,$key,$rounds));
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,&QWP(16*4,"esp"));
&$movekey ($rndkey0,&QWP(-16,$key,$rounds));
&aesdec ($inout0,$rndkey1);
&aesdec ($inout1,$rndkey1);
&aesdec ($inout2,$rndkey1);
&aesdec ($inout3,$rndkey1);
&aesdec ($inout4,$rndkey1);
&aesdec ($inout5,$rndkey1);
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_decrypt6_enter");
&movdqa ($rndkey0,&QWP(16*4,"esp")); # pass last offset_i
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&movdqa ($rndkey1,&QWP($checksum,"esp"));
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,&QWP(16*2,"esp"));
&pxor ($inout3,&QWP(16*3,"esp"));
&pxor ($inout4,$rndkey0);
&pxor ($rndkey1,$inout0); # checksum
&movdqu (&QWP(16*0,$out,$inp),$inout0); # store output
&pxor ($rndkey1,$inout1);
&movdqu (&QWP(16*1,$out,$inp),$inout1);
&pxor ($rndkey1,$inout2);
&movdqu (&QWP(16*2,$out,$inp),$inout2);
&pxor ($rndkey1,$inout3);
&movdqu (&QWP(16*3,$out,$inp),$inout3);
&pxor ($rndkey1,$inout4);
&movdqu (&QWP(16*4,$out,$inp),$inout4);
&jmp (&label("done"));
&set_label("one",16);
&movdqu ($inout5,&QWP(0,$l_));
&mov ($key,&DWP($key_off,"esp")); # restore key
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&mov ($rounds,&DWP(240,$key));
&pxor ($inout5,$rndkey0); # ^ last offset_i
&pxor ($inout0,$inout5); # ^ offset_i
&movdqa ($inout4,$rndkey1);
&mov ($out,&DWP($out_off,"esp"));
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&xorps ($inout0,$inout5); # ^ offset_i
&movaps ($rndkey1,$inout4); # pass the checksum
&movdqa ($rndkey0,$inout5); # pass last offset_i
&xorps ($rndkey1,$inout0); # checksum
&movups (&QWP(0,$out,$inp),$inout0);
&jmp (&label("done"));
&set_label("two",16);
&lea ($i1,&DWP(1,$block));
&mov ($key,&DWP($key_off,"esp")); # restore key
&bsf ($i1,$i1);
&shl ($i1,4);
&movdqu ($inout4,&QWP(0,$l_));
&movdqu ($inout5,&QWP(0,$l_,$i1));
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&mov ($rounds,&DWP(240,$key));
&movdqa ($inout3,$rndkey1);
&pxor ($inout4,$rndkey0); # ^ last offset_i
&pxor ($inout5,$inout4);
&pxor ($inout0,$inout4); # ^ offset_i
&pxor ($inout1,$inout5);
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_decrypt2");
&xorps ($inout0,$inout4); # ^ offset_i
&xorps ($inout1,$inout5);
&movdqa ($rndkey0,$inout5); # pass last offset_i
&xorps ($inout3,$inout0); # checksum
&movups (&QWP(16*0,$out,$inp),$inout0); # store output
&xorps ($inout3,$inout1);
&movups (&QWP(16*1,$out,$inp),$inout1);
&movaps ($rndkey1,$inout3); # pass the checksum
&jmp (&label("done"));
&set_label("three",16);
&lea ($i1,&DWP(1,$block));
&mov ($key,&DWP($key_off,"esp")); # restore key
&bsf ($i1,$i1);
&shl ($i1,4);
&movdqu ($inout3,&QWP(0,$l_));
&movdqu ($inout4,&QWP(0,$l_,$i1));
&movdqa ($inout5,$inout3);
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&movdqu ($inout1,&QWP(16*1,$inp));
&movdqu ($inout2,&QWP(16*2,$inp));
&mov ($rounds,&DWP(240,$key));
&movdqa (&QWP($checksum,"esp"),$rndkey1);
&pxor ($inout3,$rndkey0); # ^ last offset_i
&pxor ($inout4,$inout3);
&pxor ($inout5,$inout4);
&pxor ($inout0,$inout3); # ^ offset_i
&pxor ($inout1,$inout4);
&pxor ($inout2,$inout5);
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_decrypt3");
&movdqa ($rndkey1,&QWP($checksum,"esp"));# pass the checksum
&xorps ($inout0,$inout3); # ^ offset_i
&xorps ($inout1,$inout4);
&xorps ($inout2,$inout5);
&movups (&QWP(16*0,$out,$inp),$inout0); # store output
&pxor ($rndkey1,$inout0); # checksum
&movdqa ($rndkey0,$inout5); # pass last offset_i
&movups (&QWP(16*1,$out,$inp),$inout1);
&pxor ($rndkey1,$inout1);
&movups (&QWP(16*2,$out,$inp),$inout2);
&pxor ($rndkey1,$inout2);
&jmp (&label("done"));
&set_label("four",16);
&lea ($i1,&DWP(1,$block));
&lea ($i3,&DWP(3,$block));
&bsf ($i1,$i1);
&bsf ($i3,$i3);
&mov ($key,&DWP($key_off,"esp")); # restore key
&shl ($i1,4);
&shl ($i3,4);
&movdqu ($inout2,&QWP(0,$l_));
&movdqu ($inout3,&QWP(0,$l_,$i1));
&movdqa ($inout4,$inout2);
&movdqu ($inout5,&QWP(0,$l_,$i3));
&pxor ($inout2,$rndkey0); # ^ last offset_i
&movdqu ($inout0,&QWP(16*0,$inp)); # load input
&pxor ($inout3,$inout2);
&movdqu ($inout1,&QWP(16*1,$inp));
&pxor ($inout4,$inout3);
&movdqa (&QWP(16*0,"esp"),$inout2);
&pxor ($inout5,$inout4);
&movdqa (&QWP(16*1,"esp"),$inout3);
&movdqu ($inout2,&QWP(16*2,$inp));
&movdqu ($inout3,&QWP(16*3,$inp));
&mov ($rounds,&DWP(240,$key));
&movdqa (&QWP($checksum,"esp"),$rndkey1);
&pxor ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&pxor ($inout1,&QWP(16*1,"esp"));
&pxor ($inout2,$inout4);
&pxor ($inout3,$inout5);
&mov ($out,&DWP($out_off,"esp"));
&call ("_aesni_decrypt4");
&movdqa ($rndkey1,&QWP($checksum,"esp"));# pass the checksum
&xorps ($inout0,&QWP(16*0,"esp")); # ^ offset_i
&xorps ($inout1,&QWP(16*1,"esp"));
&xorps ($inout2,$inout4);
&movups (&QWP(16*0,$out,$inp),$inout0); # store output
&pxor ($rndkey1,$inout0); # checksum
&xorps ($inout3,$inout5);
&movups (&QWP(16*1,$out,$inp),$inout1);
&pxor ($rndkey1,$inout1);
&movdqa ($rndkey0,$inout5); # pass last offset_i
&movups (&QWP(16*2,$out,$inp),$inout2);
&pxor ($rndkey1,$inout2);
&movups (&QWP(16*3,$out,$inp),$inout3);
&pxor ($rndkey1,$inout3);
&set_label("done");
&mov ($key,&DWP($esp_off,"esp"));
&pxor ($inout0,$inout0); # clear register bank
&pxor ($inout1,$inout1);
&movdqa (&QWP(16*0,"esp"),$inout0); # clear stack
&pxor ($inout2,$inout2);
&movdqa (&QWP(16*1,"esp"),$inout0);
&pxor ($inout3,$inout3);
&movdqa (&QWP(16*2,"esp"),$inout0);
&pxor ($inout4,$inout4);
&movdqa (&QWP(16*3,"esp"),$inout0);
&pxor ($inout5,$inout5);
&movdqa (&QWP(16*4,"esp"),$inout0);
&movdqa (&QWP(16*5,"esp"),$inout0);
&movdqa (&QWP(16*6,"esp"),$inout0);
&lea ("esp",&DWP(0,$key));
&mov ($rounds,&wparam(5)); # &offset_i
&mov ($rounds_,&wparam(7)); # &checksum
&movdqu (&QWP(0,$rounds),$rndkey0);
&pxor ($rndkey0,$rndkey0);
&movdqu (&QWP(0,$rounds_),$rndkey1);
&pxor ($rndkey1,$rndkey1);
&function_end("aesni_ocb_decrypt");
}
}
######################################################################
# void $PREFIX_cbc_encrypt (const void *inp, void *out,
# size_t length, const AES_KEY *key,
# unsigned char *ivp,const int enc);
&function_begin("${PREFIX}_cbc_encrypt");
&mov ($inp,&wparam(0));
&mov ($rounds_,"esp");
&mov ($out,&wparam(1));
&sub ($rounds_,24);
&mov ($len,&wparam(2));
&and ($rounds_,-16);
&mov ($key,&wparam(3));
&mov ($key_,&wparam(4));
&test ($len,$len);
&jz (&label("cbc_abort"));
&cmp (&wparam(5),0);
&xchg ($rounds_,"esp"); # alloca
&movups ($ivec,&QWP(0,$key_)); # load IV
&mov ($rounds,&DWP(240,$key));
&mov ($key_,$key); # backup $key
&mov (&DWP(16,"esp"),$rounds_); # save original %esp
&mov ($rounds_,$rounds); # backup $rounds
&je (&label("cbc_decrypt"));
&movaps ($inout0,$ivec);
&cmp ($len,16);
&jb (&label("cbc_enc_tail"));
&sub ($len,16);
&jmp (&label("cbc_enc_loop"));
&set_label("cbc_enc_loop",16);
&movups ($ivec,&QWP(0,$inp)); # input actually
&lea ($inp,&DWP(16,$inp));
if ($inline)
{ &aesni_inline_generate1("enc",$inout0,$ivec); }
else
{ &xorps($inout0,$ivec); &call("_aesni_encrypt1"); }
&mov ($rounds,$rounds_); # restore $rounds
&mov ($key,$key_); # restore $key
&movups (&QWP(0,$out),$inout0); # store output
&lea ($out,&DWP(16,$out));
&sub ($len,16);
&jnc (&label("cbc_enc_loop"));
&add ($len,16);
&jnz (&label("cbc_enc_tail"));
&movaps ($ivec,$inout0);
&pxor ($inout0,$inout0);
&jmp (&label("cbc_ret"));
&set_label("cbc_enc_tail");
&mov ("ecx",$len); # zaps $rounds
&data_word(0xA4F3F689); # rep movsb
&mov ("ecx",16); # zero tail
&sub ("ecx",$len);
&xor ("eax","eax"); # zaps $len
&data_word(0xAAF3F689); # rep stosb
&lea ($out,&DWP(-16,$out)); # rewind $out by 1 block
&mov ($rounds,$rounds_); # restore $rounds
&mov ($inp,$out); # $inp and $out are the same
&mov ($key,$key_); # restore $key
&jmp (&label("cbc_enc_loop"));
######################################################################
&set_label("cbc_decrypt",16);
&cmp ($len,0x50);
&jbe (&label("cbc_dec_tail"));
&movaps (&QWP(0,"esp"),$ivec); # save IV
&sub ($len,0x50);
&jmp (&label("cbc_dec_loop6_enter"));
&set_label("cbc_dec_loop6",16);
&movaps (&QWP(0,"esp"),$rndkey0); # save IV
&movups (&QWP(0,$out),$inout5);
&lea ($out,&DWP(0x10,$out));
&set_label("cbc_dec_loop6_enter");
&movdqu ($inout0,&QWP(0,$inp));
&movdqu ($inout1,&QWP(0x10,$inp));
&movdqu ($inout2,&QWP(0x20,$inp));
&movdqu ($inout3,&QWP(0x30,$inp));
&movdqu ($inout4,&QWP(0x40,$inp));
&movdqu ($inout5,&QWP(0x50,$inp));
&call ("_aesni_decrypt6");
&movups ($rndkey1,&QWP(0,$inp));
&movups ($rndkey0,&QWP(0x10,$inp));
&xorps ($inout0,&QWP(0,"esp")); # ^=IV
&xorps ($inout1,$rndkey1);
&movups ($rndkey1,&QWP(0x20,$inp));
&xorps ($inout2,$rndkey0);
&movups ($rndkey0,&QWP(0x30,$inp));
&xorps ($inout3,$rndkey1);
&movups ($rndkey1,&QWP(0x40,$inp));
&xorps ($inout4,$rndkey0);
&movups ($rndkey0,&QWP(0x50,$inp)); # IV
&xorps ($inout5,$rndkey1);
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&lea ($inp,&DWP(0x60,$inp));
&movups (&QWP(0x20,$out),$inout2);
&mov ($rounds,$rounds_); # restore $rounds
&movups (&QWP(0x30,$out),$inout3);
&mov ($key,$key_); # restore $key
&movups (&QWP(0x40,$out),$inout4);
&lea ($out,&DWP(0x50,$out));
&sub ($len,0x60);
&ja (&label("cbc_dec_loop6"));
&movaps ($inout0,$inout5);
&movaps ($ivec,$rndkey0);
&add ($len,0x50);
&jle (&label("cbc_dec_clear_tail_collected"));
&movups (&QWP(0,$out),$inout0);
&lea ($out,&DWP(0x10,$out));
&set_label("cbc_dec_tail");
&movups ($inout0,&QWP(0,$inp));
&movaps ($in0,$inout0);
&cmp ($len,0x10);
&jbe (&label("cbc_dec_one"));
&movups ($inout1,&QWP(0x10,$inp));
&movaps ($in1,$inout1);
&cmp ($len,0x20);
&jbe (&label("cbc_dec_two"));
&movups ($inout2,&QWP(0x20,$inp));
&cmp ($len,0x30);
&jbe (&label("cbc_dec_three"));
&movups ($inout3,&QWP(0x30,$inp));
&cmp ($len,0x40);
&jbe (&label("cbc_dec_four"));
&movups ($inout4,&QWP(0x40,$inp));
&movaps (&QWP(0,"esp"),$ivec); # save IV
&movups ($inout0,&QWP(0,$inp));
&xorps ($inout5,$inout5);
&call ("_aesni_decrypt6");
&movups ($rndkey1,&QWP(0,$inp));
&movups ($rndkey0,&QWP(0x10,$inp));
&xorps ($inout0,&QWP(0,"esp")); # ^= IV
&xorps ($inout1,$rndkey1);
&movups ($rndkey1,&QWP(0x20,$inp));
&xorps ($inout2,$rndkey0);
&movups ($rndkey0,&QWP(0x30,$inp));
&xorps ($inout3,$rndkey1);
&movups ($ivec,&QWP(0x40,$inp)); # IV
&xorps ($inout4,$rndkey0);
&movups (&QWP(0,$out),$inout0);
&movups (&QWP(0x10,$out),$inout1);
&pxor ($inout1,$inout1);
&movups (&QWP(0x20,$out),$inout2);
&pxor ($inout2,$inout2);
&movups (&QWP(0x30,$out),$inout3);
&pxor ($inout3,$inout3);
&lea ($out,&DWP(0x40,$out));
&movaps ($inout0,$inout4);
&pxor ($inout4,$inout4);
&sub ($len,0x50);
&jmp (&label("cbc_dec_tail_collected"));
&set_label("cbc_dec_one",16);
if ($inline)
{ &aesni_inline_generate1("dec"); }
else
{ &call ("_aesni_decrypt1"); }
&xorps ($inout0,$ivec);
&movaps ($ivec,$in0);
&sub ($len,0x10);
&jmp (&label("cbc_dec_tail_collected"));
&set_label("cbc_dec_two",16);
&call ("_aesni_decrypt2");
&xorps ($inout0,$ivec);
&xorps ($inout1,$in0);
&movups (&QWP(0,$out),$inout0);
&movaps ($inout0,$inout1);
&pxor ($inout1,$inout1);
&lea ($out,&DWP(0x10,$out));
&movaps ($ivec,$in1);
&sub ($len,0x20);
&jmp (&label("cbc_dec_tail_collected"));
&set_label("cbc_dec_three",16);
&call ("_aesni_decrypt3");
&xorps ($inout0,$ivec);
&xorps ($inout1,$in0);
&xorps ($inout2,$in1);
&movups (&QWP(0,$out),$inout0);
&movaps ($inout0,$inout2);
&pxor ($inout2,$inout2);
&movups (&QWP(0x10,$out),$inout1);
&pxor ($inout1,$inout1);
&lea ($out,&DWP(0x20,$out));
&movups ($ivec,&QWP(0x20,$inp));
&sub ($len,0x30);
&jmp (&label("cbc_dec_tail_collected"));
&set_label("cbc_dec_four",16);
&call ("_aesni_decrypt4");
&movups ($rndkey1,&QWP(0x10,$inp));
&movups ($rndkey0,&QWP(0x20,$inp));
&xorps ($inout0,$ivec);
&movups ($ivec,&QWP(0x30,$inp));
&xorps ($inout1,$in0);
&movups (&QWP(0,$out),$inout0);
&xorps ($inout2,$rndkey1);
&movups (&QWP(0x10,$out),$inout1);
&pxor ($inout1,$inout1);
&xorps ($inout3,$rndkey0);
&movups (&QWP(0x20,$out),$inout2);
&pxor ($inout2,$inout2);
&lea ($out,&DWP(0x30,$out));
&movaps ($inout0,$inout3);
&pxor ($inout3,$inout3);
&sub ($len,0x40);
&jmp (&label("cbc_dec_tail_collected"));
&set_label("cbc_dec_clear_tail_collected",16);
&pxor ($inout1,$inout1);
&pxor ($inout2,$inout2);
&pxor ($inout3,$inout3);
&pxor ($inout4,$inout4);
&set_label("cbc_dec_tail_collected");
&and ($len,15);
&jnz (&label("cbc_dec_tail_partial"));
&movups (&QWP(0,$out),$inout0);
&pxor ($rndkey0,$rndkey0);
&jmp (&label("cbc_ret"));
&set_label("cbc_dec_tail_partial",16);
&movaps (&QWP(0,"esp"),$inout0);
&pxor ($rndkey0,$rndkey0);
&mov ("ecx",16);
&mov ($inp,"esp");
&sub ("ecx",$len);
&data_word(0xA4F3F689); # rep movsb
&movdqa (&QWP(0,"esp"),$inout0);
&set_label("cbc_ret");
&mov ("esp",&DWP(16,"esp")); # pull original %esp
&mov ($key_,&wparam(4));
&pxor ($inout0,$inout0);
&pxor ($rndkey1,$rndkey1);
&movups (&QWP(0,$key_),$ivec); # output IV
&pxor ($ivec,$ivec);
&set_label("cbc_abort");
&function_end("${PREFIX}_cbc_encrypt");
######################################################################
# Mechanical port from aesni-x86_64.pl.
#
# _aesni_set_encrypt_key is private interface,
# input:
# "eax" const unsigned char *userKey
# $rounds int bits
# $key AES_KEY *key
# output:
# "eax" return code
# $round rounds
&function_begin_B("_aesni_set_encrypt_key");
&push ("ebp");
&push ("ebx");
&test ("eax","eax");
&jz (&label("bad_pointer"));
&test ($key,$key);
&jz (&label("bad_pointer"));
&call (&label("pic"));
&set_label("pic");
&blindpop("ebx");
&lea ("ebx",&DWP(&label("key_const")."-".&label("pic"),"ebx"));
&picmeup("ebp","OPENSSL_ia32cap_P","ebx",&label("key_const"));
&movups ("xmm0",&QWP(0,"eax")); # pull first 128 bits of *userKey
&xorps ("xmm4","xmm4"); # low dword of xmm4 is assumed 0
&mov ("ebp",&DWP(4,"ebp"));
&lea ($key,&DWP(16,$key));
&and ("ebp",1<<28|1<<11); # AVX and XOP bits
&cmp ($rounds,256);
&je (&label("14rounds"));
&cmp ($rounds,192);
&je (&label("12rounds"));
&cmp ($rounds,128);
&jne (&label("bad_keybits"));
&set_label("10rounds",16);
&cmp ("ebp",1<<28);
&je (&label("10rounds_alt"));
&mov ($rounds,9);
&$movekey (&QWP(-16,$key),"xmm0"); # round 0
&aeskeygenassist("xmm1","xmm0",0x01); # round 1
&call (&label("key_128_cold"));
&aeskeygenassist("xmm1","xmm0",0x2); # round 2
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x04); # round 3
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x08); # round 4
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x10); # round 5
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x20); # round 6
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x40); # round 7
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x80); # round 8
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x1b); # round 9
&call (&label("key_128"));
&aeskeygenassist("xmm1","xmm0",0x36); # round 10
&call (&label("key_128"));
&$movekey (&QWP(0,$key),"xmm0");
&mov (&DWP(80,$key),$rounds);
&jmp (&label("good_key"));
&set_label("key_128",16);
&$movekey (&QWP(0,$key),"xmm0");
&lea ($key,&DWP(16,$key));
&set_label("key_128_cold");
&shufps ("xmm4","xmm0",0b00010000);
&xorps ("xmm0","xmm4");
&shufps ("xmm4","xmm0",0b10001100);
&xorps ("xmm0","xmm4");
&shufps ("xmm1","xmm1",0b11111111); # critical path
&xorps ("xmm0","xmm1");
&ret();
&set_label("10rounds_alt",16);
&movdqa ("xmm5",&QWP(0x00,"ebx"));
&mov ($rounds,8);
&movdqa ("xmm4",&QWP(0x20,"ebx"));
&movdqa ("xmm2","xmm0");
&movdqu (&QWP(-16,$key),"xmm0");
&set_label("loop_key128");
&pshufb ("xmm0","xmm5");
&aesenclast ("xmm0","xmm4");
&pslld ("xmm4",1);
&lea ($key,&DWP(16,$key));
&movdqa ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm2","xmm3");
&pxor ("xmm0","xmm2");
&movdqu (&QWP(-16,$key),"xmm0");
&movdqa ("xmm2","xmm0");
&dec ($rounds);
&jnz (&label("loop_key128"));
&movdqa ("xmm4",&QWP(0x30,"ebx"));
&pshufb ("xmm0","xmm5");
&aesenclast ("xmm0","xmm4");
&pslld ("xmm4",1);
&movdqa ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm2","xmm3");
&pxor ("xmm0","xmm2");
&movdqu (&QWP(0,$key),"xmm0");
&movdqa ("xmm2","xmm0");
&pshufb ("xmm0","xmm5");
&aesenclast ("xmm0","xmm4");
&movdqa ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm3","xmm2");
&pslldq ("xmm2",4);
&pxor ("xmm2","xmm3");
&pxor ("xmm0","xmm2");
&movdqu (&QWP(16,$key),"xmm0");
&mov ($rounds,9);
&mov (&DWP(96,$key),$rounds);
&jmp (&label("good_key"));
&set_label("12rounds",16);
&movq ("xmm2",&QWP(16,"eax")); # remaining 1/3 of *userKey
&cmp ("ebp",1<<28);
&je (&label("12rounds_alt"));
&mov ($rounds,11);
&$movekey (&QWP(-16,$key),"xmm0"); # round 0
&aeskeygenassist("xmm1","xmm2",0x01); # round 1,2
&call (&label("key_192a_cold"));
&aeskeygenassist("xmm1","xmm2",0x02); # round 2,3
&call (&label("key_192b"));
&aeskeygenassist("xmm1","xmm2",0x04); # round 4,5
&call (&label("key_192a"));
&aeskeygenassist("xmm1","xmm2",0x08); # round 5,6
&call (&label("key_192b"));
&aeskeygenassist("xmm1","xmm2",0x10); # round 7,8
&call (&label("key_192a"));
&aeskeygenassist("xmm1","xmm2",0x20); # round 8,9
&call (&label("key_192b"));
&aeskeygenassist("xmm1","xmm2",0x40); # round 10,11
&call (&label("key_192a"));
&aeskeygenassist("xmm1","xmm2",0x80); # round 11,12
&call (&label("key_192b"));
&$movekey (&QWP(0,$key),"xmm0");
&mov (&DWP(48,$key),$rounds);
&jmp (&label("good_key"));
&set_label("key_192a",16);
&$movekey (&QWP(0,$key),"xmm0");
&lea ($key,&DWP(16,$key));
&set_label("key_192a_cold",16);
&movaps ("xmm5","xmm2");
&set_label("key_192b_warm");
&shufps ("xmm4","xmm0",0b00010000);
&movdqa ("xmm3","xmm2");
&xorps ("xmm0","xmm4");
&shufps ("xmm4","xmm0",0b10001100);
&pslldq ("xmm3",4);
&xorps ("xmm0","xmm4");
&pshufd ("xmm1","xmm1",0b01010101); # critical path
&pxor ("xmm2","xmm3");
&pxor ("xmm0","xmm1");
&pshufd ("xmm3","xmm0",0b11111111);
&pxor ("xmm2","xmm3");
&ret();
&set_label("key_192b",16);
&movaps ("xmm3","xmm0");
&shufps ("xmm5","xmm0",0b01000100);
&$movekey (&QWP(0,$key),"xmm5");
&shufps ("xmm3","xmm2",0b01001110);
&$movekey (&QWP(16,$key),"xmm3");
&lea ($key,&DWP(32,$key));
&jmp (&label("key_192b_warm"));
&set_label("12rounds_alt",16);
&movdqa ("xmm5",&QWP(0x10,"ebx"));
&movdqa ("xmm4",&QWP(0x20,"ebx"));
&mov ($rounds,8);
&movdqu (&QWP(-16,$key),"xmm0");
&set_label("loop_key192");
&movq (&QWP(0,$key),"xmm2");
&movdqa ("xmm1","xmm2");
&pshufb ("xmm2","xmm5");
&aesenclast ("xmm2","xmm4");
&pslld ("xmm4",1);
&lea ($key,&DWP(24,$key));
&movdqa ("xmm3","xmm0");
&pslldq ("xmm0",4);
&pxor ("xmm3","xmm0");
&pslldq ("xmm0",4);
&pxor ("xmm3","xmm0");
&pslldq ("xmm0",4);
&pxor ("xmm0","xmm3");
&pshufd ("xmm3","xmm0",0xff);
&pxor ("xmm3","xmm1");
&pslldq ("xmm1",4);
&pxor ("xmm3","xmm1");
&pxor ("xmm0","xmm2");
&pxor ("xmm2","xmm3");
&movdqu (&QWP(-16,$key),"xmm0");
&dec ($rounds);
&jnz (&label("loop_key192"));
&mov ($rounds,11);
&mov (&DWP(32,$key),$rounds);
&jmp (&label("good_key"));
&set_label("14rounds",16);
&movups ("xmm2",&QWP(16,"eax")); # remaining half of *userKey
&lea ($key,&DWP(16,$key));
&cmp ("ebp",1<<28);
&je (&label("14rounds_alt"));
&mov ($rounds,13);
&$movekey (&QWP(-32,$key),"xmm0"); # round 0
&$movekey (&QWP(-16,$key),"xmm2"); # round 1
&aeskeygenassist("xmm1","xmm2",0x01); # round 2
&call (&label("key_256a_cold"));
&aeskeygenassist("xmm1","xmm0",0x01); # round 3
&call (&label("key_256b"));
&aeskeygenassist("xmm1","xmm2",0x02); # round 4
&call (&label("key_256a"));
&aeskeygenassist("xmm1","xmm0",0x02); # round 5
&call (&label("key_256b"));
&aeskeygenassist("xmm1","xmm2",0x04); # round 6
&call (&label("key_256a"));
&aeskeygenassist("xmm1","xmm0",0x04); # round 7
&call (&label("key_256b"));
&aeskeygenassist("xmm1","xmm2",0x08); # round 8
&call (&label("key_256a"));
&aeskeygenassist("xmm1","xmm0",0x08); # round 9
&call (&label("key_256b"));
&aeskeygenassist("xmm1","xmm2",0x10); # round 10
&call (&label("key_256a"));
&aeskeygenassist("xmm1","xmm0",0x10); # round 11
&call (&label("key_256b"));
&aeskeygenassist("xmm1","xmm2",0x20); # round 12
&call (&label("key_256a"));
&aeskeygenassist("xmm1","xmm0",0x20); # round 13
&call (&label("key_256b"));
&aeskeygenassist("xmm1","xmm2",0x40); # round 14
&call (&label("key_256a"));
&$movekey (&QWP(0,$key),"xmm0");
&mov (&DWP(16,$key),$rounds);
&xor ("eax","eax");
&jmp (&label("good_key"));
&set_label("key_256a",16);
&$movekey (&QWP(0,$key),"xmm2");
&lea ($key,&DWP(16,$key));
&set_label("key_256a_cold");
&shufps ("xmm4","xmm0",0b00010000);
&xorps ("xmm0","xmm4");
&shufps ("xmm4","xmm0",0b10001100);
&xorps ("xmm0","xmm4");
&shufps ("xmm1","xmm1",0b11111111); # critical path
&xorps ("xmm0","xmm1");
&ret();
&set_label("key_256b",16);
&$movekey (&QWP(0,$key),"xmm0");
&lea ($key,&DWP(16,$key));
&shufps ("xmm4","xmm2",0b00010000);
&xorps ("xmm2","xmm4");
&shufps ("xmm4","xmm2",0b10001100);
&xorps ("xmm2","xmm4");
&shufps ("xmm1","xmm1",0b10101010); # critical path
&xorps ("xmm2","xmm1");
&ret();
&set_label("14rounds_alt",16);
&movdqa ("xmm5",&QWP(0x00,"ebx"));
&movdqa ("xmm4",&QWP(0x20,"ebx"));
&mov ($rounds,7);
&movdqu (&QWP(-32,$key),"xmm0");
&movdqa ("xmm1","xmm2");
&movdqu (&QWP(-16,$key),"xmm2");
&set_label("loop_key256");
&pshufb ("xmm2","xmm5");
&aesenclast ("xmm2","xmm4");
&movdqa ("xmm3","xmm0");
&pslldq ("xmm0",4);
&pxor ("xmm3","xmm0");
&pslldq ("xmm0",4);
&pxor ("xmm3","xmm0");
&pslldq ("xmm0",4);
&pxor ("xmm0","xmm3");
&pslld ("xmm4",1);
&pxor ("xmm0","xmm2");
&movdqu (&QWP(0,$key),"xmm0");
&dec ($rounds);
&jz (&label("done_key256"));
&pshufd ("xmm2","xmm0",0xff);
&pxor ("xmm3","xmm3");
&aesenclast ("xmm2","xmm3");
&movdqa ("xmm3","xmm1");
&pslldq ("xmm1",4);
&pxor ("xmm3","xmm1");
&pslldq ("xmm1",4);
&pxor ("xmm3","xmm1");
&pslldq ("xmm1",4);
&pxor ("xmm1","xmm3");
&pxor ("xmm2","xmm1");
&movdqu (&QWP(16,$key),"xmm2");
&lea ($key,&DWP(32,$key));
&movdqa ("xmm1","xmm2");
&jmp (&label("loop_key256"));
&set_label("done_key256");
&mov ($rounds,13);
&mov (&DWP(16,$key),$rounds);
&set_label("good_key");
&pxor ("xmm0","xmm0");
&pxor ("xmm1","xmm1");
&pxor ("xmm2","xmm2");
&pxor ("xmm3","xmm3");
&pxor ("xmm4","xmm4");
&pxor ("xmm5","xmm5");
&xor ("eax","eax");
&pop ("ebx");
&pop ("ebp");
&ret ();
&set_label("bad_pointer",4);
&mov ("eax",-1);
&pop ("ebx");
&pop ("ebp");
&ret ();
&set_label("bad_keybits",4);
&pxor ("xmm0","xmm0");
&mov ("eax",-2);
&pop ("ebx");
&pop ("ebp");
&ret ();
&function_end_B("_aesni_set_encrypt_key");
# int $PREFIX_set_encrypt_key (const unsigned char *userKey, int bits,
# AES_KEY *key)
&function_begin_B("${PREFIX}_set_encrypt_key");
&mov ("eax",&wparam(0));
&mov ($rounds,&wparam(1));
&mov ($key,&wparam(2));
&call ("_aesni_set_encrypt_key");
&ret ();
&function_end_B("${PREFIX}_set_encrypt_key");
# int $PREFIX_set_decrypt_key (const unsigned char *userKey, int bits,
# AES_KEY *key)
&function_begin_B("${PREFIX}_set_decrypt_key");
&mov ("eax",&wparam(0));
&mov ($rounds,&wparam(1));
&mov ($key,&wparam(2));
&call ("_aesni_set_encrypt_key");
&mov ($key,&wparam(2));
&shl ($rounds,4); # rounds-1 after _aesni_set_encrypt_key
&test ("eax","eax");
&jnz (&label("dec_key_ret"));
&lea ("eax",&DWP(16,$key,$rounds)); # end of key schedule
&$movekey ("xmm0",&QWP(0,$key)); # just swap
&$movekey ("xmm1",&QWP(0,"eax"));
&$movekey (&QWP(0,"eax"),"xmm0");
&$movekey (&QWP(0,$key),"xmm1");
&lea ($key,&DWP(16,$key));
&lea ("eax",&DWP(-16,"eax"));
&set_label("dec_key_inverse");
&$movekey ("xmm0",&QWP(0,$key)); # swap and inverse
&$movekey ("xmm1",&QWP(0,"eax"));
&aesimc ("xmm0","xmm0");
&aesimc ("xmm1","xmm1");
&lea ($key,&DWP(16,$key));
&lea ("eax",&DWP(-16,"eax"));
&$movekey (&QWP(16,"eax"),"xmm0");
&$movekey (&QWP(-16,$key),"xmm1");
&cmp ("eax",$key);
&ja (&label("dec_key_inverse"));
&$movekey ("xmm0",&QWP(0,$key)); # inverse middle
&aesimc ("xmm0","xmm0");
&$movekey (&QWP(0,$key),"xmm0");
&pxor ("xmm0","xmm0");
&pxor ("xmm1","xmm1");
&xor ("eax","eax"); # return success
&set_label("dec_key_ret");
&ret ();
&function_end_B("${PREFIX}_set_decrypt_key");
&set_label("key_const",64);
&data_word(0x0c0f0e0d,0x0c0f0e0d,0x0c0f0e0d,0x0c0f0e0d);
&data_word(0x04070605,0x04070605,0x04070605,0x04070605);
&data_word(1,1,1,1);
&data_word(0x1b,0x1b,0x1b,0x1b);
&asciz("AES for Intel AES-NI, CRYPTOGAMS by <appro\@openssl.org>");
&asm_finish();
close STDOUT;
| 29.89133 | 75 | 0.592186 |
73d26d5734e06050bc1bd570131211ade2e6865e | 3,877 | pm | Perl | perl-lib/apachelog.pm | benizi/dotfiles | d7727d544cfb41d5e991a75cb2f6ffe30ceed2a4 | [
"MIT"
]
| 2 | 2017-04-26T10:51:36.000Z | 2019-12-24T20:36:32.000Z | perl-lib/apachelog.pm | benizi/dotfiles | d7727d544cfb41d5e991a75cb2f6ffe30ceed2a4 | [
"MIT"
]
| null | null | null | perl-lib/apachelog.pm | benizi/dotfiles | d7727d544cfb41d5e991a75cb2f6ffe30ceed2a4 | [
"MIT"
]
| 1 | 2015-09-11T08:36:29.000Z | 2015-09-11T08:36:29.000Z | package apachelog;
use base 'Exporter';
our @EXPORT = our @EXPORT_OK = qw/&alog/;
sub alog { apachelog->new(@_ ? shift : $_) }
use Time::Local;
sub new {
my $self = bless {}, shift;
@_ == 1 and $self->_parseline(shift);
$self;
}
our %month_map = qw{
Jan 1 Feb 2 Mar 3 Apr 4 May 5 Jun 6
Jul 7 Aug 8 Sep 9 Oct 10 Nov 11 Dec 12
};
sub _parseline {
my $self = shift;
local $_ = shift;
my $orig = $_;
if (s/^(\d+(?:\.\d+){3})\s//) {
$$self{ip} = $1;
$$self{ipv} = 4;
} elsif (s/^([:\da-f]+)\s//) {
$$self{ip} = $1;
$$self{ipv} = 6;
}
unless (s/^- //) { s/^(\S+) // and $$self{wtf1} = $1; }
unless (s/^- //) { s/^(\S+) // and $$self{group} = $1; }
s{^\[(?<d>\d\d?)/(?<m>\w\w\w)/(?<Y>\d\d\d\d):(?<H>\d\d):(?<M>\d\d):(?<S>\d\d)(?:\s(?<z>(?<zp>[+\-])(?<zh>\d\d)(?<zm>\d\d)))?\] }{} or die "Bad dates: $_\n";
my %date = map ref()?@$_:$_, %-;
$date{m} = $month_map{$date{m}};
$date{m}--;
my @fields = @date{qw/S M H d m Y/};
my $t;
if (!grep !defined, @date{qw/zp zh zm/}) {
$t = timegm @fields;
my $mult = $date{zp} eq '-' ? -1 : 1;
$t -= 60 * $mult * ($date{zh} * 60 + $date{zm});
} else {
$t = timelocal @fields;
}
$$self{timestamp} = $t;
s/^"((?:[^\\\"]|\\[\\"])*)" // or warn "Bad request: $_\n";
$$self{req} = $1;
@$self{qw/method path httpversion/} = $$self{req} =~ /^([A-Z]+)\s(\S+)\s(\S+)$/;
unless (s/^- //) { s/^(\d+) // and $$self{status} = $1; $$self{good} = $$self{status} =~ /^[23]/ ? 1 : 0; }
unless (s/^- //) { s/^(\d+) // and $$self{transferred} = $1; }
unless (s/^"-" //) { s/^"([^"]*)" // and $$self{refer} = $1; }
s/"([^"]*)"$// or die "WTF? $orig\n$_\n";
$$self{useragent} = $1;
#die "$orig\n$_\n";
#use Data::Dumper; print Dumper $self;
}
sub _ip2bits {
shift;
my @pieces = split /\./, shift;
join '', map sprintf('%08b', $_), @pieces;
}
{
my %cached;
sub _get_mask {
my ($self, $net, $bits) = @_;
my $k = join ':', @_;
if (!$cached{$k}) {
$bits // (($net, $bits) = split m{/}, $net);
$net .= '.0' until 3 == $net =~ y/././;
my $match = $self->_ip2bits($net);
$cached{$k} = [$match,$bits];
}
$self, @{$cached{$k}};
}
sub subnet {
my ($self, $match, $bits) = &_get_mask;
my $ipbits = $self->_ip2bits($$self{ip});
# my $match = $self->_ip2bits($net);
# $match = substr($match, 0, $bits).('.' x (32-$bits));
# #print "NET=$net\nBIT=$bits\nMAT=$match\n";
# $ipbits =~ /^$match$/;
substr($match, 0, $bits) eq substr($ipbits, 0, $bits);
}
}
sub url { _url_pieces(path=>@_) }
sub refer { _url_pieces(refer=>@_) }
sub _url_pieces {
my $field = shift;
my $self = shift;
local $_ = $$self{$field} // '/';
s{^(?!http)}{http://www};
my $p = { whole => $_ };
s{^(\w+):(?://)?}{} and $$p{scheme} = $1;
s{^([^/:]+)}{} and $$p{host} = $1;
$$p{port} = s{^:(\d+)(?=/)}{} ? $1 : 80;
s{^(/[^?]*)(?=\?|$)}{} and $$p{path} = $1;
$$p{query} = s/^\?// ? $_ : '';
my $qs = $$p{query};
for (split /&/, $qs, -1) {
next unless length;
my ($k, $v) = split /=/, $_, 2;
$v //= \1;
$$p{q}{$k} = (exists $$p{q}{$k})
? [ map { (ref()||'') eq 'ARRAY' ? @$_ : $_ } $$p{q}{$k}, $v ]
: $v;
}
$p;
}
use Digest::MD5 qw/md5_hex md5_base64/;
{
my %cache;
sub agent_hash {
local $_ = shift;
if (!$cache{$_}) {
$cache{$_} = substr md5_base64($_), 0, 8;
}
$cache{$_};
}
}
sub uniqagent { &agent->{uniq} }
sub agent { _agent_pieces(useragent=>@_) }
sub _agent_pieces {
my $field = shift;
my $self = shift;
local $_ = $$self{$field} // 'Unknown/1.0';
my $p = {};
$$p{uniq} = agent_hash($_);# join '', sort grep /\w/, split //;
if (/\bMSIE\s(\S+);/) {
} else {
}
$p;
}
1;
| 27.892086 | 159 | 0.435646 |
ed4c929a3c6710a4fd0ad936c6ceb6b95c903bff | 2,720 | pl | Perl | ThirdParty/bullet-2.75/Extras/vectormathlibrary/tests/compare.pl | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
]
| 32 | 2016-05-22T23:09:19.000Z | 2022-03-13T03:32:27.000Z | ThirdParty/bullet-2.75/Extras/vectormathlibrary/tests/compare.pl | Palestar/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
]
| 2 | 2016-05-30T19:45:58.000Z | 2018-01-24T22:29:51.000Z | ThirdParty/bullet-2.75/Extras/vectormathlibrary/tests/compare.pl | Palestar/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
]
| 17 | 2016-05-27T11:01:42.000Z | 2022-03-13T03:32:30.000Z | #!/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";
}
}
}
}
| 28.333333 | 78 | 0.622794 |
ed867673dfdbfee77cb2c6df30d35cc350702373 | 305 | al | Perl | lib/auto/POSIX/vsprintf.al | basusingh/Nanny-Bot | 4f3368c750b378f1b4d38a48dad6ac095af14056 | [
"MIT"
]
| null | null | null | lib/auto/POSIX/vsprintf.al | basusingh/Nanny-Bot | 4f3368c750b378f1b4d38a48dad6ac095af14056 | [
"MIT"
]
| null | null | null | lib/auto/POSIX/vsprintf.al | basusingh/Nanny-Bot | 4f3368c750b378f1b4d38a48dad6ac095af14056 | [
"MIT"
]
| null | null | null | # NOTE: Derived from ..\..\lib\POSIX.pm.
# Changes made here will be lost when autosplit is run again.
# See AutoSplit.pm.
package POSIX;
#line 424 "..\..\lib\POSIX.pm (autosplit into ..\..\lib\auto\POSIX\vsprintf.al)"
sub vsprintf {
unimpl "vsprintf() is C-specific";
}
# end of POSIX::vsprintf
1;
| 23.461538 | 80 | 0.67541 |
ed5da5c31d3687ea4222927055e571d2b44a77dc | 1,181 | t | Perl | t/db.t | jmhutch/krang | fb96334f1be957ebbe63370ac50d989e28c3a8eb | [
"BSD-3-Clause"
]
| 1 | 2018-02-15T03:54:35.000Z | 2018-02-15T03:54:35.000Z | t/db.t | jmhutch/krang | fb96334f1be957ebbe63370ac50d989e28c3a8eb | [
"BSD-3-Clause"
]
| 1 | 2018-07-24T21:38:29.000Z | 2018-07-24T22:36:36.000Z | t/db.t | jmhutch/krang | fb96334f1be957ebbe63370ac50d989e28c3a8eb | [
"BSD-3-Clause"
]
| 2 | 2018-07-24T21:48:08.000Z | 2020-05-25T18:18:05.000Z | use Krang::ClassFactory qw(pkg);
use Test::More tests => 6;
use strict;
use warnings;
no warnings 'deprecated';
use Krang::ClassLoader 'Script';
use Krang::ClassLoader 'Conf';
use Krang::ClassLoader DB => qw(dbh forget_dbh);
my $dbh = dbh();
isa_ok($dbh, 'DBI::db', 'DBI handle for "' . pkg('Conf')->InstanceDBName . '" db');
my $results = $dbh->selectall_arrayref('show tables');
ok($results, 'selected some data');
forget_dbh();
my $dbh2 = dbh();
isa_ok($dbh2, 'DBI::db', 'DBI handle for "' . pkg('Conf')->InstanceDBName . '" db');
isnt($dbh, $dbh2);
# Test version control
$dbh = dbh();
# Fail to get dbh if version doesn't match
my ($db_version) = $dbh->selectrow_array("select db_version from db_version");
$dbh->do("update db_version set db_version='9999.9999'");
forget_dbh();
eval { $dbh2 = dbh(); };
like($@, qr/Database <-> Krang version mismatch!/, "dbh() detects version mismatch");
# Try to get dbh in spite of version mismatch (ignore_version=>1)
forget_dbh();
undef($dbh2);
eval { $dbh2 = dbh(ignore_version => 1); };
ok(ref($dbh2), "dbh() respects 'ignore_version' pragma");
# Fix version
$dbh->do("update db_version set db_version=?", undef, $db_version);
| 29.525 | 85 | 0.677392 |
ed64ab2b1a72675a981b9546f6981d2afa742204 | 11,612 | pm | Perl | centreon/common/fortinet/fortigate/mode/vpn.pm | xdrive05/centreon-plugins | 8227ba680fdfd2bb0d8a806ea61ec1611c2779dc | [
"Apache-2.0"
]
| null | null | null | centreon/common/fortinet/fortigate/mode/vpn.pm | xdrive05/centreon-plugins | 8227ba680fdfd2bb0d8a806ea61ec1611c2779dc | [
"Apache-2.0"
]
| null | null | null | centreon/common/fortinet/fortigate/mode/vpn.pm | xdrive05/centreon-plugins | 8227ba680fdfd2bb0d8a806ea61ec1611c2779dc | [
"Apache-2.0"
]
| null | null | null | #
# Copyright 2020 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package centreon::common::fortinet::fortigate::mode::vpn;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
sub custom_state_output {
my ($self, %options) = @_;
my $msg = sprintf("state is '%s'", $self->{result_values}->{state});
return $msg;
}
sub custom_state_calc {
my ($self, %options) = @_;
$self->{result_values}->{state} = $options{new_datas}->{$self->{instance} . '_state'};
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'vd', type => 3, cb_prefix_output => 'prefix_vd_output', cb_long_output => 'vd_long_output', indent_long_output => ' ', message_multiple => 'All virtual domains are OK',
group => [
{ name => 'global', type => 0, skipped_code => { -10 => 1 } },
{ name => 'vpn', display_long => 1, cb_prefix_output => 'prefix_vpn_output', message_multiple => 'All vpn are ok', type => 1, skipped_code => { -10 => 1 } },
]
}
];
$self->{maps_counters}->{global} = [
{ label => 'users', set => {
key_values => [ { name => 'users' } ],
output_template => 'Logged users: %s',
perfdatas => [
{ label => 'users', value => 'users_absolute', template => '%d',
min => 0, unit => 'users', label_extra_instance => 1 },
],
}
},
{ label => 'sessions', set => {
key_values => [ { name => 'sessions' }],
output_template => 'Active web sessions: %s',
perfdatas => [
{ label => 'sessions', value => 'sessions_absolute', template => '%d',
min => 0, unit => 'sessions', label_extra_instance => 1 },
],
}
},
{ label => 'tunnels', set => {
key_values => [ { name => 'tunnels' } ],
output_template => 'Active Tunnels: %s',
perfdatas => [
{ label => 'active_tunnels', value => 'tunnels_absolute', template => '%d',
min => 0, unit => 'tunnels', label_extra_instance => 1 },
],
}
},
];
$self->{maps_counters}->{vpn} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'state' }, { name => 'display' } ],
closure_custom_calc => \&custom_state_calc,
closure_custom_output => \&custom_state_output,
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
{ label => 'traffic-in', set => {
key_values => [ { name => 'traffic_in', diff => 1 }, { name => 'display' } ],
per_second => 1, output_change_bytes => 1,
output_template => 'Traffic In: %s %s/s',
perfdatas => [
{ label => 'traffic_in', value => 'traffic_in_per_second', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1 },
],
}
},
{ label => 'traffic-out', set => {
key_values => [ { name => 'traffic_out', diff => 1 }, { name => 'display' } ],
per_second => 1, output_change_bytes => 1,
output_template => 'Traffic Out: %s %s/s',
perfdatas => [
{ label => 'traffic_out', value => 'traffic_out_per_second', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1 },
],
}
}
];
}
sub prefix_vd_output {
my ($self, %options) = @_;
return "Virtual domain '" . $options{instance_value}->{display} . "' ";
}
sub vd_long_output {
my ($self, %options) = @_;
return "checking virtual domain '" . $options{instance_value}->{display} . "'";
}
sub prefix_vpn_output {
my ($self, %options) = @_;
return "Link '" . $options{instance_value}->{display} . "' ";
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
'filter-vpn:s' => { name => 'filter_vpn' },
'filter-vdomain:s' => { name => 'filter_vdomain' },
'warning-status:s' => { name => 'warning_status', default => '' },
'critical-status:s' => { name => 'critical_status', default => '%{state} eq "down"' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$self->change_macros(macros => ['warning_status', 'critical_status']);
}
my $map_status = { 1 => 'down', 2 => 'up' };
my $mapping = {
fgVpnTunEntPhase2Name => { oid => '.1.3.6.1.4.1.12356.101.12.2.2.1.3' },
fgVpnTunEntInOctets => { oid => '.1.3.6.1.4.1.12356.101.12.2.2.1.18' },
fgVpnTunEntOutOctets => { oid => '.1.3.6.1.4.1.12356.101.12.2.2.1.19' },
fgVpnTunEntStatus => { oid => '.1.3.6.1.4.1.12356.101.12.2.2.1.20', map => $map_status },
fgVpnTunEntVdom => { oid => '.1.3.6.1.4.1.12356.101.12.2.2.1.21' },
};
my $mapping2 = {
fgVpnSslStatsLoginUsers => { oid => '.1.3.6.1.4.1.12356.101.12.2.3.1.2' },
fgVpnSslStatsActiveWebSessions => { oid => '.1.3.6.1.4.1.12356.101.12.2.3.1.4' },
fgVpnSslStatsActiveTunnels => { oid => '.1.3.6.1.4.1.12356.101.12.2.3.1.6' },
};
my $oid_fgVpnTunTable = '.1.3.6.1.4.1.12356.101.12.2.2.1';
my $oid_fgVpnSslStatsTable = '.1.3.6.1.4.1.12356.101.12.2.3';
my $oid_fgVdEntName = '.1.3.6.1.4.1.12356.101.3.2.1.1.2';
sub manage_selection {
my ($self, %options) = @_;
$self->{cache_name} = "fortigate_" . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' . $self->{mode} . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_vpn}) ? md5_hex($self->{option_results}->{filter_vpn}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_vdomain}) ? md5_hex($self->{option_results}->{filter_vdomain}) : md5_hex('all'));
my $snmp_result = $options{snmp}->get_multiple_table(
oids => [
{ oid => $oid_fgVdEntName },
{ oid => $oid_fgVpnSslStatsTable },
],
nothing_quit => 1
);
my $snmp_result2 = $options{snmp}->get_multiple_table(
oids => [
{ oid => $mapping->{fgVpnTunEntPhase2Name}->{oid} },
{ oid => $oid_fgVpnTunTable, start => $mapping->{fgVpnTunEntInOctets}->{oid} },
],
return_type => 1,
nothing_quit => 1
);
$self->{vd} = {};
my $duplicated = {};
foreach my $oid (keys %{$snmp_result->{ $oid_fgVdEntName }}) {
$oid =~ /^$oid_fgVdEntName\.(.*)$/;
my $vdom_instance = $1;
my $result = $options{snmp}->map_instance(mapping => $mapping2, results => $snmp_result->{$oid_fgVpnSslStatsTable}, instance => $vdom_instance);
my $vdomain_name = $snmp_result->{$oid_fgVdEntName}->{$oid_fgVdEntName . '.' . $vdom_instance};
if (defined($self->{option_results}->{filter_vdomain}) && $self->{option_results}->{filter_vdomain} ne '' &&
$vdomain_name !~ /$self->{option_results}->{filter_vdomain}/) {
$self->{output}->output_add(long_msg => "skipping '" . $vdomain_name . "': no matching filter.", debug => 1);
next;
}
$self->{vd}->{$vdomain_name} = {
display => $vdomain_name,
global => {
users => $result->{fgVpnSslStatsLoginUsers},
tunnels => $result->{fgVpnSslStatsActiveTunnels},
sessions => $result->{fgVpnSslStatsActiveWebSessions}
},
vpn => {},
};
foreach (keys %$snmp_result2) {
next if (! /^$mapping->{fgVpnTunEntVdom}->{oid}\.(.*)$/ ||
$snmp_result2->{$_} != $vdom_instance
);
my $instance = $1;
$result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result2, instance => $instance);
if (defined($self->{option_results}->{filter_vpn}) && $self->{option_results}->{filter_vpn} ne '' &&
$result->{fgVpnTunEntPhase2Name} !~ /$self->{option_results}->{filter_vpn}/) {
$self->{output}->output_add(long_msg => "skipping '" . $result->{fgVpnTunEntPhase2Name} . "': no matching filter.", debug => 1);
next;
}
my $name = $result->{fgVpnTunEntPhase2Name};
$name .= '.' . $instance if (defined($duplicated->{$name}));
if (defined($self->{vd}->{$vdomain_name}->{vpn}->{$name})) {
$duplicated->{$name} = 1;
$self->{vd}->{$vdomain_name}->{vpn}->{$name . '.' . $self->{vd}->{$vdomain_name}->{vpn}->{$name}->{instance}} = $self->{vd}->{$vdomain_name}->{vpn}->{$name};
$self->{vd}->{$vdomain_name}->{vpn}->{$name . '.' . $self->{vd}->{$vdomain_name}->{vpn}->{$name}->{instance}}->{display} = $name . '.' . $self->{vd}->{$vdomain_name}->{vpn}->{$name}->{instance};
delete $self->{vd}->{$vdomain_name}->{vpn}->{$name};
$name = $result->{fgVpnTunEntPhase2Name} . '.' . $instance;
}
$self->{vd}->{$vdomain_name}->{vpn}->{$name} = {
display => $name,
instance => $instance,
state => $result->{fgVpnTunEntStatus},
traffic_in => $result->{fgVpnTunEntInOctets},
traffic_out => $result->{fgVpnTunEntOutOctets},
};
}
}
}
1;
__END__
=head1 MODE
Check Vdomain statistics and VPN state and traffic
=over 8
=item B<--filter-*>
Filter name with regexp. Can be ('vdomain', 'vpn')
=item B<--warning-*>
Warning on counters. Can be ('users', 'sessions', 'tunnels', 'traffic-in', 'traffic-out')
=item B<--critical-*>
Warning on counters. Can be ('users', 'sessions', 'tunnels', 'traffic-in', 'traffic-out')
=item B<--warning-status>
Set warning threshold for status. Use "%{state}" as a special variable.
Useful to be notified when tunnel is up "%{state} eq 'up'"
=item B<--critical-status>
Set critical threshold for status. Use "%{state}" as a special variable.
Useful to be notified when tunnel is up "%{state} eq 'up'"
=back
=cut
| 39.22973 | 210 | 0.540906 |
ed57ea02c3df3c1d87ab880d28101bae3e8ba574 | 8,761 | pm | Perl | network/a10/ax/snmp/mode/vserverusage.pm | nribault/centreon-plugins | e99276ba80ba202392791e78d72b00f1306d1a99 | [
"Apache-2.0"
]
| null | null | null | network/a10/ax/snmp/mode/vserverusage.pm | nribault/centreon-plugins | e99276ba80ba202392791e78d72b00f1306d1a99 | [
"Apache-2.0"
]
| null | null | null | network/a10/ax/snmp/mode/vserverusage.pm | nribault/centreon-plugins | e99276ba80ba202392791e78d72b00f1306d1a99 | [
"Apache-2.0"
]
| null | null | null | #
# Copyright 2020 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::a10::ax::snmp::mode::vserverusage;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Digest::MD5 qw(md5_hex);
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
sub custom_status_output {
my ($self, %options) = @_;
my $msg = 'status : ' . $self->{result_values}->{status};
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_axVirtualServerStatStatus'};
$self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'vserver', type => 1, cb_prefix_output => 'prefix_vserver_output', message_multiple => 'All virtual servers are ok' }
];
$self->{maps_counters}->{vserver} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'axVirtualServerStatStatus' }, { name => 'display' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
{ label => 'current-con', nlabel => 'virtualserver.connections.current.count', set => {
key_values => [ { name => 'axVirtualServerStatCurConns' }, { name => 'display' } ],
output_template => 'Current Connections : %s',
perfdatas => [
{ label => 'current_connections', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'total-con', nlabel => 'virtualserver.connections.total.count', set => {
key_values => [ { name => 'axVirtualServerStatTotConns', diff => 1 }, { name => 'display' } ],
output_template => 'Total Connections : %s',
perfdatas => [
{ label => 'total_connections', template => '%s',
min => 0, label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'traffic-in', nlabel => 'virtualserver.traffic.in.bitspersecond', set => {
key_values => [ { name => 'axVirtualServerStatBytesIn', per_second => 1 }, { name => 'display' } ],
output_template => 'Traffic In : %s %s/s',
output_change_bytes => 2,
perfdatas => [
{ label => 'traffic_in', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display' },
],
}
},
{ label => 'traffic-out', nlabel => 'virtualserver.traffic.out.bitspersecond', set => {
key_values => [ { name => 'axVirtualServerStatBytesOut', per_second => 1 }, { name => 'display' } ],
output_template => 'Traffic Out : %s %s/s',
output_change_bytes => 2,
perfdatas => [
{ label => 'traffic_out', template => '%.2f',
min => 0, unit => 'b/s', label_extra_instance => 1, instance_use => 'display' },
],
}
},
];
}
sub prefix_vserver_output {
my ($self, %options) = @_;
return "Virtual Server '" . $options{instance_value}->{display} . "' ";
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
'filter-name:s' => { name => 'filter_name' },
'warning-status:s' => { name => 'warning_status', default => '' },
'critical-status:s' => { name => 'critical_status', default => '%{status} =~ /down/i' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$self->change_macros(macros => ['warning_status', 'critical_status']);
}
my %map_status = (
1 => 'up', 2 => 'down', 3 => 'disabled',
);
my $oid_axVirtualServerStatName = '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.2';
my $mapping = {
axVirtualServerStatBytesIn => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.4' },
axVirtualServerStatBytesOut => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.6' },
axVirtualServerStatTotConns => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.8' },
axVirtualServerStatCurConns => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.9' },
axVirtualServerStatStatus => { oid => '.1.3.6.1.4.1.22610.2.4.3.4.2.1.1.10', map => \%map_status },
};
sub manage_selection {
my ($self, %options) = @_;
if ($options{snmp}->is_snmpv1()) {
$self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3.");
$self->{output}->option_exit();
}
my $snmp_result = $options{snmp}->get_table(oid => $oid_axVirtualServerStatName, nothing_quit => 1);
$self->{vserver} = {};
foreach my $oid (keys %{$snmp_result}) {
$oid =~ /^$oid_axVirtualServerStatName\.(.*)$/;
my $instance = $1;
$snmp_result->{$oid} =~ s/\\//g;
if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' &&
$snmp_result->{$oid} !~ /$self->{option_results}->{filter_name}/) {
$self->{output}->output_add(long_msg => "skipping virtual server '" . $snmp_result->{$oid} . "'.", debug => 1);
next;
}
$self->{vserver}->{$instance} = { display => $snmp_result->{$oid} };
}
$options{snmp}->load(oids => [$mapping->{axVirtualServerStatBytesIn}->{oid}, $mapping->{axVirtualServerStatBytesOut}->{oid},
$mapping->{axVirtualServerStatTotConns}->{oid}, $mapping->{axVirtualServerStatCurConns}->{oid},
$mapping->{axVirtualServerStatStatus}->{oid}
],
instances => [keys %{$self->{vserver}}], instance_regexp => '^(.*)$');
$snmp_result = $options{snmp}->get_leef(nothing_quit => 1);
foreach (keys %{$self->{vserver}}) {
my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $_);
foreach my $name (('axVirtualServerStatBytesIn', 'axVirtualServerStatBytesOut')) {
$result->{$name} *= 8;
}
foreach my $name (keys %$mapping) {
$self->{vserver}->{$_}->{$name} = $result->{$name};
}
}
if (scalar(keys %{$self->{vserver}}) <= 0) {
$self->{output}->add_option_msg(short_msg => "No virtual server found.");
$self->{output}->option_exit();
}
$self->{cache_name} = "a10_ax_" . $self->{mode} . '_' . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' .
(defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')) . '_' .
(defined($self->{option_results}->{filter_name}) ? md5_hex($self->{option_results}->{filter_name}) : md5_hex('all'));
}
1;
__END__
=head1 MODE
Check virtual server usage.
=over 8
=item B<--warning-status>
Set warning threshold for status.
Can used special variables like: %{status}, %{display}
=item B<--critical-status>
Set critical threshold for status (Default: '%{status} =~ /down/i').
Can used special variables like: %{status}, %{display}
=item B<--warning-*>
Threshold warning.
Can be: 'current-con', 'total-con', 'traffic-in', 'traffic-out'.
=item B<--critical-*>
Threshold critical.
Can be: 'current-con', 'total-con', 'traffic-in', 'traffic-out'.
=item B<--filter-name>
Filter by virtual server name (can be a regexp).
=back
=cut
| 38.091304 | 140 | 0.572652 |
ed6b9e4564b4105a27226bb8e193d3bb4dd1bc54 | 27 | t | Perl | t/01_encode.t | tokuhirom/nanobase | 5bd72ae57ec8bb06db4a2ec604bb0e11ec595c2c | [
"MIT",
"Unlicense"
]
| 1 | 2015-11-09T01:31:45.000Z | 2015-11-09T01:31:45.000Z | t/01_encode.t | tokuhirom/nanobase | 5bd72ae57ec8bb06db4a2ec604bb0e11ec595c2c | [
"MIT",
"Unlicense"
]
| null | null | null | t/01_encode.t | tokuhirom/nanobase | 5bd72ae57ec8bb06db4a2ec604bb0e11ec595c2c | [
"MIT",
"Unlicense"
]
| null | null | null | exec q{t/01_encode} or die | 27 | 27 | 0.740741 |
ed6e2c2cd9fef4d92d062f9edd3d04a5d1ba8f5a | 512 | pl | Perl | Perl STH/release.script/less.pl | lust4life/quick.dirty.perl | 2e279f9ab6fe1bfed78641911597d9b5edce62bf | [
"BSD-2-Clause-FreeBSD"
]
| null | null | null | Perl STH/release.script/less.pl | lust4life/quick.dirty.perl | 2e279f9ab6fe1bfed78641911597d9b5edce62bf | [
"BSD-2-Clause-FreeBSD"
]
| null | null | null | Perl STH/release.script/less.pl | lust4life/quick.dirty.perl | 2e279f9ab6fe1bfed78641911597d9b5edce62bf | [
"BSD-2-Clause-FreeBSD"
]
| null | null | null | use 5.16.0;
my $word_to_search = $ARGV[0];
my $show_line_match = $ARGV[1];
say qq(the \$word_to_search we match is $word_to_search);
if($word_to_search){
for(glob "*.less"){
my $file = $_;
open(FH, "<$file") or die "can not open $_ :$!";
my $has_show_file;
while(<FH>){
if(/$word_to_search/){
say $file unless $has_show_file;
$has_show_file = 1;
if($show_line_match){
# say __LINE__;
say qq($.===> $_);
}
else{
last;
}
}
}
close FH;
}
}
__DATA__
radius
| 16 | 57 | 0.578125 |
Subsets and Splits