code stringlengths 2 1.05M | repo_name stringlengths 5 101 | path stringlengths 4 991 | language stringclasses 3 values | license stringclasses 5 values | size int64 2 1.05M |
|---|---|---|---|---|---|
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2021] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::Web::TextSequence::Output;
use strict;
use warnings;
use EnsEMBL::Web::TextSequence::ClassToStyle::CSS;
use EnsEMBL::Web::TextSequence::Output::Web::Adorn;
use HTML::Entities qw(encode_entities);
use JSON qw(to_json);
use EnsEMBL::Web::TextSequence::Layout::String;
use List::Util qw(max);
sub new {
my ($proto) = @_;
my $class = ref($proto) || $proto;
my $self = {
template =>
qq(<pre class="text_sequence">%s</pre><p class="invisible">.</p>),
c2s => undef,
view => undef,
};
bless $self,$class;
$self->reset;
return $self;
}
sub reset {
my ($self) = @_;
%$self = (
%$self,
data => [],
legend => {},
more => undef,
);
}
sub subslicer { return $_[0]; }
sub make_c2s {
return EnsEMBL::Web::TextSequence::ClassToStyle::CSS->new($_[0]->view);
}
sub c2s { return ($_[0]->{'c2s'} ||= $_[0]->make_c2s); }
sub template { $_[0]->{'template'} = $_[1] if @_>1; return $_[0]->{'template'}; }
sub view { $_[0]->{'view'} = $_[1] if @_>1; return $_[0]->{'view'}; }
sub legend { $_[0]->{'legend'} = $_[1] if @_>1; return $_[0]->{'legend'}; }
sub more { $_[0]->{'more'} = $_[1] if @_>1; return $_[0]->{'more'}; }
sub final_wrapper { return $_[1]; }
sub format_letters { return $_[1]; }
sub prepare_line {
my ($self,$data,$num,$config,$vskip) = @_;
return {
# values
pre => $data->{'pre'},
label => $num->{'label'},
start => $num->{'start'},
end => $num->{'end'},
post_label => $num->{'post_label'},
h_space => $config->{'h_space'},
letters => $self->format_letters($data->{'line'},$config),
adid => $data->{'adid'},
post => $data->{'post'},
# flags
number => ($config->{'number'}||'off') ne 'off',
vskip => $vskip,
principal => $data->{'principal'},
};
}
sub goahead_line { return 1; }
sub format_lines {
my ($self,$layout,$config,$line_numbers,$multi) = @_;
my $view = $self->view;
my $ropes = [grep { !$_->hidden } @{$view->sequences}];
my @lines;
my $html = "";
if($view->interleaved) {
# Interleaved sequences
# We truncate to the length of the first sequence. This is a bug,
# but it's one relied on for TranscriptComparison to work.
my $num_lines = 0;
$num_lines = @{$ropes->[0]->output->lines}-1 if $ropes and @$ropes and $ropes->[0];
#
for my $x (0..$num_lines) {
my $y = 0;
foreach my $rope (@$ropes) {
my $ro = $rope->output->lines;
my $num = shift @{$line_numbers->{$y}};
next unless $self->goahead_line($ro->[$x]);
push @lines,$self->prepare_line($ro->[$x],$num,$config,$multi && $y == $#$ropes);
$y++;
}
}
} else {
# Non-interleaved sequences (eg Exon view)
my $y = 0;
foreach my $rope (@$ropes) {
my $ro = $rope->output;
my $i = 0;
my $lines = $ro->lines;
foreach my $x (@$lines) {
my $num = shift @{$line_numbers->{$y}};
push @lines,$self->prepare_line($x,$num,$config,$multi && $i == $#$lines);
$i++;
}
$y++;
}
}
$layout->prepare($_) for(@lines);
$layout->render($_) for(@lines);
return $layout;
}
1;
| Ensembl/ensembl-webcode | modules/EnsEMBL/Web/TextSequence/Output.pm | Perl | apache-2.0 | 3,856 |
#
# 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::aws::cloudwatchlogs::mode::getlogs;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use centreon::plugins::misc;
use centreon::plugins::statefile;
use Digest::MD5 qw(md5_hex);
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
sub custom_status_output {
my ($self, %options) = @_;
return sprintf(
'log [created: %s] [stream: %s] [message: %s] ',
centreon::plugins::misc::change_seconds(value => $self->{result_values}->{since}),
$self->{result_values}->{stream_name},
$self->{result_values}->{message}
);
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'alarms', type => 2, message_multiple => '0 logs detected', display_counter_problem => { label => 'logs', min => 0 },
group => [ { name => 'alarm', skipped_code => { -11 => 1 } } ]
}
];
$self->{maps_counters}->{alarm} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'message' }, { name => 'stream_name' }, { name => 'since' } ],
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold
}
}
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {
'group-name:s' => { name => 'group_name' },
'stream-name:s@' => { name => 'stream_name' },
'start-time-since:s' => { name => 'start_time_since' },
'unknown-status:s' => { name => 'unknown_status', default => '' },
'warning-status:s' => { name => 'warning_status', default => '' },
'critical-status:s' => { name => 'critical_status', default => '' }
});
$self->{statefile_cache} = centreon::plugins::statefile->new(%options);
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
if (!defined($self->{option_results}->{group_name}) || $self->{option_results}->{group_name} eq '') {
$self->{output}->add_option_msg(short_msg => 'please set --group-name option');
$self->{output}->option_exit();
}
if (defined($self->{option_results}->{start_time_since}) && $self->{option_results}->{start_time_since} =~ /(\d+)/) {
$self->{start_time} = time() - $1;
}
$self->{stream_names} = undef;
if (defined($self->{option_results}->{stream_name})) {
foreach my $stream_name (@{$self->{option_results}->{stream_name}}) {
if ($stream_name ne '') {
$self->{stream_names} = [] if (!defined($self->{stream_names}));
push @{$self->{stream_names}}, $stream_name;
}
}
}
$self->change_macros(macros => ['unknown_status', 'warning_status', 'critical_status']);
if (!defined($self->{start_time})) {
$self->{statefile_cache}->check_options(%options);
}
}
sub manage_selection {
my ($self, %options) = @_;
my $current_time = time();
if (!defined($self->{start_time})) {
$self->{statefile_cache}->read(
statefile =>
'cache_aws_' . $self->{mode} . '_' . $options{custom}->get_region() .
(defined($self->{option_results}->{group_name}) ? md5_hex($self->{option_results}->{group_name}) : md5_hex('all')) . '_' .
(defined($self->{stream_names}) ? md5_hex(join('-', @{$self->{stream_names}})) : md5_hex('all'))
);
$self->{start_time} = $self->{statefile_cache}->get(name => 'last_time');
$self->{statefile_cache}->write(data => { last_time => $current_time });
if (!defined($self->{start_time})) {
$self->{output}->output_add(
severity => 'OK',
short_msg => 'first execution. create cache'
);
$self->{output}->display();
$self->{output}->exit();
}
}
$self->{alarms}->{global} = { alarm => {} };
my $results = $options{custom}->cloudwatchlogs_filter_log_events(
group_name => $self->{option_results}->{group_name},
stream_names => $self->{stream_names},
start_time => $self->{start_time} * 1000
);
my $i = 1;
foreach my $entry (@$results) {
$entry->{message} =~ s/[\|\n]/ -- /msg;
$self->{alarms}->{global}->{alarm}->{$i} = {
message => $entry->{message},
stream_name => $entry->{logStreamName},
since => int($current_time - ($entry->{timestamp} / 1000))
};
$i++;
}
}
1;
__END__
=head1 MODE
Check cloudwatch logs.
=over 8
=item B<--group-name>
Set log group name (Required).
=item B<--stream-name>
Filters the results to only logs from the log stream (multiple option).
=item B<--start-time-since>
Lookup logs last X seconds ago.
If not set: lookup logs since the last execution.
=item B<--unknown-status>
Set unknown threshold for status (Default: '')
Can used special variables like: %{message}, %{stream_name}, %{since}
=item B<--warning-status>
Set warning threshold for status (Default: '')
Can used special variables like: %{message}, %{stream_name}, %{since}
=item B<--critical-status>
Set critical threshold for status (Default: '').
Can used special variables like: %{message}, %{stream_name}, %{since}
=back
=cut
| Tpo76/centreon-plugins | cloud/aws/cloudwatchlogs/mode/getlogs.pm | Perl | apache-2.0 | 6,358 |
package Paws::CloudDirectory::AttachObject;
use Moose;
has ChildReference => (is => 'ro', isa => 'Paws::CloudDirectory::ObjectReference', required => 1);
has DirectoryArn => (is => 'ro', isa => 'Str', traits => ['ParamInHeader'], header_name => 'x-amz-data-partition', required => 1);
has LinkName => (is => 'ro', isa => 'Str', required => 1);
has ParentReference => (is => 'ro', isa => 'Paws::CloudDirectory::ObjectReference', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'AttachObject');
class_has _api_uri => (isa => 'Str', is => 'ro', default => '/amazonclouddirectory/2017-01-11/object/attach');
class_has _api_method => (isa => 'Str', is => 'ro', default => 'PUT');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::CloudDirectory::AttachObjectResponse');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::CloudDirectory::AttachObject - Arguments for method AttachObject on Paws::CloudDirectory
=head1 DESCRIPTION
This class represents the parameters used for calling the method AttachObject on the
Amazon CloudDirectory service. Use the attributes of this class
as arguments to method AttachObject.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to AttachObject.
As an example:
$service_obj->AttachObject(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 B<REQUIRED> ChildReference => L<Paws::CloudDirectory::ObjectReference>
The child object reference to be attached to the object.
=head2 B<REQUIRED> DirectoryArn => Str
Amazon Resource Name (ARN) that is associated with the Directory where
both objects reside. For more information, see arns.
=head2 B<REQUIRED> LinkName => Str
The link name with which the child object is attached to the parent.
=head2 B<REQUIRED> ParentReference => L<Paws::CloudDirectory::ObjectReference>
The parent object reference.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method AttachObject in L<Paws::CloudDirectory>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/CloudDirectory/AttachObject.pm | Perl | apache-2.0 | 2,587 |
=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 XrefParser::miRBaseParser;
use strict;
use warnings;
use Carp;
use DBI;
use base qw(XrefParser::BaseParser);
sub run {
my ($self, $ref_arg) = @_;
my $source_id = $ref_arg->{source_id};
my $species_id = $ref_arg->{species_id};
my $files = $ref_arg->{files};
my $verbose = $ref_arg->{verbose};
if((!defined $source_id) or (!defined $species_id) or (!defined $files) ){
croak "Need to pass source_id, species_id and files as pairs";
}
$verbose |=0;
my $file = @{$files}[0];
if(!defined($species_id)){
$species_id = $self->get_species_id_for_filename($file);
}
my $xrefs = $self->create_xrefs($source_id, $file, $species_id);
if(!defined($xrefs)){
return 1; #error
}
# upload
if(!defined($self->upload_xref_object_graphs($xrefs))){
return 1;
}
return 0; # successfull
}
# --------------------------------------------------------------------------------
# Parse file into array of xref objects
sub create_xrefs {
my ($self, $source_id, $file, $species_id) = @_;
my %species2name = $self->species_id2name();
my @names = @{$species2name{$species_id}};
my %name2species_id = map{ $_=>$species_id } @names;
my $file_io = $self->get_filehandle($file);
if ( !defined $file_io ) {
print STDERR "ERROR: Could not open $file\n";
return 1; # 1 is an error
}
my @xrefs;
local $/ = "\n\/\/";
while ($_ = $file_io->getline()) {
my $xref;
my $entry = $_;
chomp $entry;
next if (!$entry);
my ($header, $sequence) = split (/\nSQ/, $entry, 2);
# remove newlines
my @seq_lines = split (/\n/, $sequence) if ($sequence);
# drop the information line
shift @seq_lines;
# put onto one line
$sequence = join("", @seq_lines);
# make uppercase
$sequence = uc($sequence);
# replace Ts for Us
$sequence =~ s/U/T/g;
# remove numbers and whitespace
$sequence =~ s/[\d+,\s+]//g;
# print "$header\n";
my ($name) = $header =~ /\nID\s+(\S+)\s+/;
my ($acc) = $header =~ /\nAC\s+(\S+);\s+/;
my ($description) = $header =~ /\nDE\s+(.+)\s+stem-loop/;
my @description_parts = split (/\s+/, $description) if ($description);
# remove the miRNA identifier
pop @description_parts;
my $species = join(" ", @description_parts);
$xref->{SEQUENCE_TYPE} = 'dna';
$xref->{STATUS} = 'experimental';
$xref->{SOURCE_ID} = $source_id;
$species = lc $species;
$species =~ s/ /_/;
my $species_id_check = $name2species_id{$species};
next if (!defined($species_id_check));
# skip xrefs for species that aren't in the species table
if (defined($species_id) and $species_id == $species_id_check) {
$xref->{ACCESSION} = $acc;
$xref->{LABEL} = $name;
$xref->{DESCRIPTION} = $name;
$xref->{SEQUENCE} = $sequence;
$xref->{SPECIES_ID} = $species_id;
# TODO synonyms, dependent xrefs etc
push @xrefs, $xref;
}
}
$file_io->close();
print "Read " . scalar(@xrefs) ." xrefs from $file\n";
return \@xrefs;
}
1;
| willmclaren/ensembl | misc-scripts/xref_mapping/XrefParser/miRBaseParser.pm | Perl | apache-2.0 | 3,743 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2021] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
package EnsEMBL::Web::ViewConfig::Gene::SpliceImage;
use strict;
use warnings;
use parent qw(EnsEMBL::Web::ViewConfig);
sub init_cacheable {
## Abstract method implementation
my $self = shift;
$self->image_config_type('gene_splice');
$self->title('Splice variants');
}
sub form_fields { } # No default fields
sub field_order { } # No default fields
1;
| Ensembl/ensembl-webcode | modules/EnsEMBL/Web/ViewConfig/Gene/SpliceImage.pm | Perl | apache-2.0 | 1,076 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package cloud::aws::ec2::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_custom);
sub new {
my ( $class, %options ) = @_;
my $self = $class->SUPER::new( package => __PACKAGE__, %options );
bless $self, $class;
$self->{version} = '0.1';
%{ $self->{modes} } = (
'asg-status' => 'cloud::aws::ec2::mode::asgstatus',
'cpu' => 'cloud::aws::ec2::mode::cpu',
'diskio' => 'cloud::aws::ec2::mode::diskio',
'instances-status' => 'cloud::aws::ec2::mode::instancesstatus',
'instances-types' => 'cloud::aws::ec2::mode::instancestypes',
'list-asg' => 'cloud::aws::ec2::mode::listasg',
'list-instances' => 'cloud::aws::ec2::mode::listinstances',
'network' => 'cloud::aws::ec2::mode::network',
'status' => 'cloud::aws::ec2::mode::status',
);
$self->{custom_modes}{paws} = 'cloud::aws::custom::paws';
$self->{custom_modes}{awscli} = 'cloud::aws::custom::awscli';
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Amazon Elastic Compute Cloud (Amazon EC2).
=cut
| wilfriedcomte/centreon-plugins | cloud/aws/ec2/plugin.pm | Perl | apache-2.0 | 1,957 |
=head1 TITLE
Beyond the amnesic eval
=head1 VERSION
Maintainer: Stéphane Payrard <stef@francenet.fr>
Date: 29 Sep 2000
Mailing List: perl6-language@perl.org
Number: 351
Version: 1
Status: Developing
=head1 ABSTRACT
An unscoped eval is needed. It is part of the necessary steps to
make Perl palatable as an interactive shell.
=head DESCRIPTION
A perl shell, beyond its intrinsic utility, will be a great
interactive learning tool. The absence of unscoped eval makes perl
based shells unattractive because they must be implemented as a scoped
eval around each command line. As a result most of the interesting
context is lost.
In command line mode, an interpretor reads a line typed by the user
then evaluates it. And so for the next lines, ad nauseam. It is only
natural to propagate the context from one line to another. This is
what make possible inteesting interactive uses.
This is not what happens in perl5 because C<eval> is always scoped.
The lost context is: the current package, special variables sets by
regexp ($1...), scoped variables (lexical and local).
A basic CLI can be built as a oneliner in classic Perl, the perl
debugger invoked by C<perl -de 0> is a glorified but specialized
command line. But without unscoped eval. It does not cut it.
An example of a frustrating session where a naive user expect a
unscoped eval:
DB<1> package FOO
DB<2> print __PACKAGE__
main
DB<3> $_='foo'
DB<4> print m/(foo)/
foo
DB<5> print $1
DB<6> my $foo = 'bar'
DB<7> print $foo
DB<8> local $foo = 'bar'
DB<9> print $foo
Certainly, one can get away by cramming a lot of stuff in one line.
But the idea of granular interactivity is lost:
DB<13> package FOO; print __PACKAGE__
FOO
DB<14> $_='foo'; print m/(foo)/
foo
DB<15> local $foo = 'bar'; print $foo
bar
DB<16> my $foo = 'bar'; print $foo
bar
=head2 Syntax
I propose the unary + as a marker that differentiates unscoped eval
from classic (scoped) eval. Or one may consider a explicit keyword.
I can't find a satisfactory one.
Classic eval:
eval {}
eval ""
Unscoped eval
+eval {}
+eval ""
=head1 IMPLEMENTATION
=head1 REFERENCES
Refeences to forthcoming RFCs.
There are other features needed to make perl6 a good shell. They can
be mode-dependant so as not to interfere with perl as a programming
language.
Command line languages make heavy usage of litterals. In perl6 command
line mode, the default should be to interpret most strings as
litteral. For example C</etc/> should be a string that will
interpreted as a filename. "Taking things litterally" will describe
what change of syntax this implies.
"User defined microsyntax" goes one step further and will propose user
defined litterals to avoid writing complex constructors.
| autarch/perlweb | docs/dev/perl6/rfc/351.pod | Perl | apache-2.0 | 2,810 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::protocols::radius::mode::login;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use Time::HiRes qw(gettimeofday tv_interval);
use Authen::Radius;
my $instance_mode;
my $radius_result_attributes = {};
sub custom_status_threshold {
my ($self, %options) = @_;
my $status = 'ok';
my $message;
eval {
local $SIG{__WARN__} = sub { $message = $_[0]; };
local $SIG{__DIE__} = sub { $message = $_[0]; };
if (defined($instance_mode->{option_results}->{critical_status}) && $instance_mode->{option_results}->{critical_status} ne '' &&
eval "$instance_mode->{option_results}->{critical_status}") {
$status = 'critical';
} elsif (defined($instance_mode->{option_results}->{warning_status}) && $instance_mode->{option_results}->{warning_status} ne '' &&
eval "$instance_mode->{option_results}->{warning_status}") {
$status = 'warning';
}
};
if (defined($message)) {
$self->{output}->output_add(long_msg => 'filter status issue: ' . $message);
}
return $status;
}
sub custom_status_output {
my ($self, %options) = @_;
my $msg = 'Radius Access Request Status: ' . $self->{result_values}->{status} .
' [error msg: ' . $self->{result_values}->{error_msg} . ']';
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_status'};
$self->{result_values}->{error_msg} = $options{new_datas}->{$self->{instance} . '_error_msg'};
$self->{result_values}->{attributes} = $radius_result_attributes;
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'radius', type => 0, message_separator => ' - ' },
];
$self->{maps_counters}->{radius} = [
{ label => 'status', threshold => 0, set => {
key_values => [ { name => 'status' }, { name => 'error_msg' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => $self->can('custom_status_threshold'),
}
},
{ label => 'time', set => {
key_values => [ { name => 'elapsed' } ],
output_template => 'Response time : %.3f second(s)',
perfdatas => [
{ label => 'time', value => 'elapsed_absolute', template => '%.3f',
min => 0, unit => 's' },
],
}
},
];
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"hostname:s" => { name => 'hostname' },
"port:s" => { name => 'port', default => 1812 },
"secret:s" => { name => 'secret' },
"username:s" => { name => 'username' },
"password:s" => { name => 'password' },
"warning:s" => { name => 'warning' },
"critical:s" => { name => 'critical' },
"timeout:s" => { name => 'timeout', default => 5 },
"retry:s" => { name => 'retry', default => 0 },
'radius-attribute:s%' => { name => 'radius_attribute' },
'radius-dictionary:s' => { name => 'radius_dictionary' },
"warning-status:s" => { name => 'warning_status', default => '' },
"critical-status:s" => { name => 'critical_status', default => '%{status} ne "accepted"' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
my @mandatory = ('hostname', 'secret');
push @mandatory, 'username', 'password' if (!defined($self->{option_results}->{radius_attribute}));
foreach (@mandatory) {
if (!defined($self->{option_results}->{$_})) {
$self->{output}->add_option_msg(short_msg => "Please set the " . $_ . " option");
$self->{output}->option_exit();
}
}
if (defined($self->{option_results}->{radius_attribute}) &&
(!defined($self->{option_results}->{radius_dictionary}) || $self->{option_results}->{radius_dictionary} eq '')) {
$self->{output}->add_option_msg(short_msg => "Please set radius-dictionary option");
$self->{output}->option_exit();
}
$self->{option_results}->{retry} = 0 if (!defined($self->{option_results}->{retry}) || $self->{option_results}->{retry} !~ /^\d+$/);
if (defined($self->{option_results}->{port}) && $self->{option_results}->{port} =~ /^\d+$/) {
$self->{option_results}->{hostname} .= ':' . $self->{option_results}->{port};
}
$instance_mode = $self;
$self->change_macros();
}
sub change_macros {
my ($self, %options) = @_;
foreach (('warning_status', 'critical_status')) {
if (defined($self->{option_results}->{$_})) {
$self->{option_results}->{$_} =~ s/%\{(.*?)\}/\$self->{result_values}->{$1}/g;
}
}
}
sub radius_simple_connection {
my ($self, %options) = @_;
$self->{timing0} = [gettimeofday];
my $retry = 0;
while ($retry <= $self->{option_results}->{retry}) {
if ($self->{radius_session}->check_pwd($self->{option_results}->{username}, $self->{option_results}->{password})) {
$self->{radius}->{status} = 'accepted';
last;
}
if ($retry + 1 > $self->{option_results}->{retry}) {
$self->{radius}->{status} = 'rejected';
$self->{radius}->{error_msg} = $self->{radius_session}->strerror();
}
$retry++;
}
}
sub radius_attr_connection {
my ($self, %options) = @_;
my $message;
eval {
local $SIG{__WARN__} = sub { $message = join(' - ', @_); };
local $SIG{__DIE__} = sub { $message = join(' - ', @_); };
Authen::Radius->load_dictionary($self->{option_results}->{radius_dictionary});
foreach (keys %{$self->{option_results}->{radius_attribute}}) {
$self->{radius_session}->add_attributes({ Name => $_, Value => $self->{option_results}->{radius_attribute}->{$_} });
}
};
if (defined($message)) {
$self->{output}->output_add(long_msg => $message, debug => 1);
$self->{output}->add_option_msg(short_msg => "Issue with dictionary and attributes");
$self->{output}->option_exit();
}
$self->{timing0} = [gettimeofday];
my $retry = 0;
while ($retry <= $self->{option_results}->{retry}) {
my $type;
if ($self->{radius_session}->send_packet(ACCESS_REQUEST) && ($type = $self->{radius_session}->recv_packet()) == ACCESS_ACCEPT) {
$self->{radius}->{status} = 'accepted';
last;
}
if ($retry + 1 > $self->{option_results}->{retry}) {
$self->{radius}->{status} = 'unknown';
$self->{radius}->{error_msg} = $self->{radius_session}->strerror();
if (defined($type) && $type == ACCESS_REJECT) {
$self->{radius}->{status} = 'rejected';
}
}
$retry++;
}
}
sub manage_selection {
my ($self, %options) = @_;
$self->{radius} = { status => 'unknown', error_msg => 'none' };
$self->{radius_session} = Authen::Radius->new(
Host => $self->{option_results}->{hostname},
Secret => $self->{option_results}->{secret},
TimeOut => $self->{option_results}->{timeout},
);
if (defined($self->{option_results}->{radius_attribute})) {
$self->radius_attr_connection();
} else {
$self->radius_simple_connection();
}
$self->{radius}->{elapsed} = tv_interval($self->{timing0}, [gettimeofday]);
foreach my $attr ($self->{radius_session}->get_attributes()) {
$radius_result_attributes->{$attr->{Name}} = defined($attr->{Value}) ? $attr->{Value} : '';
$self->{output}->output_add(long_msg => 'Attribute Name = ' . $attr->{Name} .
', Value = ' . (defined($attr->{Value}) ? $attr->{Value} : ''), debug => 1);
}
}
1;
__END__
=head1 MODE
Check login to a Radius Server.
Example with attributes:
centreon_plugins.pl --plugin=apps/protocols/radius/plugin.pm --mode=login --hostname=192.168.1.2 --secret=centreon --radius-attribute='User-Password=test' --radius-attribute='User-Name=user@test.com' --radius-dictionary=dictionary.txt
=over 8
=item B<--hostname>
IP Addr/FQDN of the radius host
=item B<--port>
Radius port (Default: 1812)
=item B<--secret>
Secret of the radius host
=item B<--username>
Specify username for authentication
=item B<--password>
Specify password for authentication
=item B<--timeout>
Connection timeout in seconds (Default: 5)
=item B<--retry>
Number of retry connection (Default: 0)
=item B<--radius-attribute>
If you need to add option, please following attributes.
Option username and password should be set with that option.
Example: --radius-attribute="User-Password=test"
=item B<--radius-dictionary>
Set radius-dictionary file (mandatory with --radius-attribute).
=item B<--warning-status>
Set warning threshold for status (Default: '').
Can used special variables like: %{status}, %{error_msg}, %{attributes}.
=item B<--critical-status>
Set critical threshold for status (Default: '%{status} ne "accepted"').
Can used special variables like: %{status}, %{error_msg}, %{attributes}.
=item B<--warning-time>
Threshold warning in seconds
=item B<--critical-time>
Threshold critical in seconds
=back
=cut
| wilfriedcomte/centreon-plugins | apps/protocols/radius/mode/login.pm | Perl | apache-2.0 | 10,605 |
package EBiSC::Question::Biosamples::BatchExported;
use Moose;
use namespace::autoclean;
use boolean qw(true false);
use strict;
use warnings;
our $title = 'Does Biosamples export all batch IDs found in IMS?';
our $description = <<EOF;
A batch is tested if it is listed for a cell line in the IMS API
Requirements to pass:
Biosamples exports that batch biosample in its API
EOF
sub run {
my ($self) = @_;
my $cursor = $self->db->ims_line->c->find(
{},
{projection => {'name' => 1, 'obj.batches.biosamples_id' => 1}},
);
my $num_tested = 0;
LINE:
while (my $next = $cursor->next) {
foreach my $id ( map {$_->{biosamples_id}} @{$next->{obj}{batches}}) {
$num_tested += 1;
my $biosamples_doc = $self->db->biosample_group->c->find_one(
{biosample_id => $id},
{'biosample_id' => 1},
);
next LINE if $biosamples_doc;
$self->add_failed_batch(cell_line => $next->{name}, batch => $id);
}
}
$self->num_tested($num_tested);
}
with 'EBiSC::Question::Role::Question';
1;
| EMBL-EBI-GCA/ebisc_tracker_2 | tracker/lib/EBiSC/Question/Biosamples/BatchExported.pm | Perl | apache-2.0 | 1,048 |
package VMOMI::GuestListFileInfo;
use parent 'VMOMI::DynamicData';
use strict;
use warnings;
our @class_ancestors = (
'DynamicData',
);
our @class_members = (
['files', 'GuestFileInfo', 1, 1],
['remaining', undef, 0, ],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/GuestListFileInfo.pm | Perl | apache-2.0 | 457 |
#!/usr/bin/perl
use lib "/perfstat/dev/1.40/lib";
use Service;
use Metric;
use Graph;
$perfhome = "/perfstat/dev/1.40";
#add create new service
$service = Service->new( RRA => "RRA:AVERAGE:0.5:1:288 RRA:AVERAGE:0.5:7:288 RRA:AVERAGE:0.5:30:288 RRA:AVERAGE:0.5:365:288",
operatingSystem => "Linux",
serviceName => "procs",
);
#add metric 0
$obj = Metric->new( rrdIndex => 0,
metricName => "totalProcs",
friendlyName => "Total Processes",
rrdDST => GAUGE,
rrdHeartbeat => 600,
rrdMin => 0,
rrdMax => U,
hasEvents => 1,
warnThreshold => 500,
critThreshold => 1000,
thresholdUnit => "Number",
);
$service->addMetric($obj);
#add graph 0
$obj = Graph->new( name => "Number Processes",
title => "process table on",
y_axis => "Number",
legend => "",
optionsArray => [],
defArray => [q{DEF:totalProcs=$RRD:totalProcs:AVERAGE}],
cdefArray => [],
lineArray => [qq{LINE2:totalProcs#0000ff:Total}],
text => "",
);
$service->addGraph($obj);
#print out this service
print ("Ref: ref($service)\n");
$os = $service->getOS();
$serviceName = $service->getServiceName();
$RRA = $service->getRRA();
print ("OS: $os\n");
print ("serviceName: $serviceName\n");
print ("RRA: $RRA\n");
#print out this services metrics
$arrayLength = $service->getMetricArrayLength();
print ("metric Array Length = $arrayLength\n\n");
for ($counter=0; $counter < $arrayLength; $counter++)
{
$metricObject = $service->{metricArray}->[$counter];
$rrdIndex = $metricObject->getRRDIndex();
$rrdDST = $metricObject->getRRDDST();
$rrdHeartbeat = $metricObject->getRRDHeartbeat();
$rrdMin = $metricObject->getRRDMin();
$rrdMax = $metricObject->getRRDMax();
$metricName = $metricObject->getMetricName();
$friendlyName = $metricObject->getFriendlyName();
$hasEvents = $metricObject->getHasEvents();
$warnThreshold = $metricObject->getWarnThreshold();
$critThreshold = $metricObject->getCritThreshold();
$thresholdUnit = $metricObject->getThresholdUnit();
print ("rrdIndex: $rrdIndex\n");
print ("rrdDST: $rrdDST\n");
print ("rrdHeartbeat: $rrdHeartbeat\n");
print ("rrdMin: $rrdMin\n");
print ("rrdMax: $rrdMax\n");
print ("metricName: $metricName\n");
print ("friendlyName: $friendlyName\n");
print ("hasEvents: $hasEvents\n");
print ("warnThreshold: $warnThreshold\n");
print ("critThreshold: $critThreshold\n");
print ("threshUnit: $thresholdUnit\n\n");
}
#print out this services graphs
$arrayLength = $service->getGraphArrayLength();
print ("graph Array Length = $arrayLength\n\n");
for ($counter=0; $counter < $arrayLength; $counter++)
{
$graphObject = $service->{graphArray}->[$counter];
$name = $graphObject->getName();
$title = $graphObject->getTitle();
$y_axis = $graphObject->getYaxis();
$legend = $graphObject->getLegend();
$text = $graphObject->getText();
print ("name: $name\n");
print ("title: $title\n");
print ("y_axis: $y_axis\n");
print ("legend: $legend\n");
print ("text: $text\n");
$arrayLength2 = $graphObject->getOptionsArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("option: $graphObject->{optionsArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getDefArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("def: $graphObject->{defArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getCdefArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("cdef: $graphObject->{cdefArray}->[$counter2]\n");
}
$arrayLength2 = $graphObject->getLineArrayLength();
for ($counter2=0; $counter2 < $arrayLength2; $counter2++)
{
print ("line: $graphObject->{lineArray}->[$counter2]\n");
}
}
#Store the service
$service->store("$perfhome/etc/configs/$service->{operatingSystem}/$service->{serviceName}.ser") or die("can't store $service->{serviceName}.ser?\n");
| ktenzer/perfstat | misc/serialize/create/Linux/62603/procs.pl | Perl | apache-2.0 | 3,980 |
:- use_package([]).
:- use_module(library('compiler/c_itf')).
:- use_module(library(ctrlcclean),[ctrlc_clean/1]).
:- use_module(library(errhandle),[error_protect/1]).
main(Files):-
set_prolog_flag(verbose_compilation,on),
cleanup_c_itf_data,
pass_one(Files,Files).
pass_one([File|Files],Fs):-
cleanup_itf_cache,
error_protect(ctrlc_clean(
process_file(File, xrefs, any,
recorda(Fs),
false, false, always)
)),
display('---------------------------------------------------------\n'),
pass_one(Files,Fs).
pass_one([],_Fs).
always(_BaseName).
recorda(BaseName,Files):-
defines_module(BaseName,M),
display(module_read(M)), nl,
debug(Files).
debug(Files):-
imports(Module,Imported,F,A),
member(Module,Files),
member(Imported,Files),
display(Module), display(-),
display(F), display(/),
display(A), display(-),
display(Imported), nl,
fail.
debug(_Files).
imports(Module,M,F,A):-
imports_pred(ModuleBase,ImpFile,F,A,_DefType,_Meta,_EndFile),
defines_module(ModuleBase,Module),
base_name(ImpFile,ImpModuleBase),
defines_module(ImpModuleBase,M).
| leuschel/ecce | www/CiaoDE/ciao/bugs/Unclassified/c_itf/try2.pl | Perl | apache-2.0 | 1,259 |
# 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.
package Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation::PIRSF;
use warnings ;
use vars qw(@ISA);
use strict;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation;
@ISA = qw(Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation);
###################
# analysis methods
###################
=head2 run_program
Title : run_program
Usage : $self->program
Function : makes the system call to program
Example :
Returns :
Args :
Throws :
=cut
sub run_analysis {
my ($self) = @_;
# run program
print STDERR "running ".$self->program." against ".$self->database."\n";
print STDERR "FILENAME: ".$self->queryfile."\n";
$self->resultsfile() ;
my $seqio = Bio::SeqIO->new(-format => 'fasta',
-file => $self->queryfile);
while (my $seq = $seqio->next_seq) {
my $filename = $self->create_filename($seq->id, 'fa') ;
$filename = $self->write_seq_file($seq, $filename) ;
my $cmd = $self->program .' '.
$self->analysis->parameters .' '.
'-i ' . $filename.' '.
'>> ' . $self->resultsfile;
print STDERR "$cmd\n";
$self->throw ("Error running PIRSF ".$self->program." on ".$self->queryfile)
unless ((system ($cmd)) == 0);
}
}
=head2 parse_results
Title : parse_results
Usage : $self->parse_results ($filename)
Function : parses program output to give a set of features
Example :
Returns :
Args : filename (optional, can be filename, filehandle or pipe, not implemented)
Throws :
=cut
sub parse_results {
my ($self) = @_;
my $filehandle;
my $resfile = $self->resultsfile();
my @fps;
if (-e $resfile) {
if (-z $resfile) {
print STDERR "PIRSF didn't find any hits\n";
return;
} else {
open (CPGOUT, "<$resfile") or $self->throw("Error opening ", $resfile, " \n"); #
}
}
# Example output:
#Query sequence: R186.4 matches PIRSF004870: Molybdenum cofactor molybdenum incorporation protein MoeA
#Full-length Match:
#Model Domain seq-f seq-t hmm-f hmm-t score E-value
#
#PIRSF004870 1/1 9 390 .. 1 443 [] 298.3 2e-87
#
my $id;
while (<CPGOUT>) {
chomp;
if (/^Query sequence:\s+(\S+)/) {
$id = $1;
}
if (my ($hid,
$start,
$end,
$hstart,
$hend,
$score,
$evalue) = /^(\S+)\s+\d+\/\d+\s+(\d+)\s+(\d+)\s+\S+\s+(\d+)\s+(\d+)\s+\S+\s+(\S+)\s+(\S+)/) {
$evalue = sprintf ("%.3e", $evalue);
my $percentIdentity = 0;
my $fp = $self->create_protein_feature($start,
$end,
$score,
$id,
$hstart,
$hend,
$hid,
$self->analysis,
$evalue,
$percentIdentity);
push @fps, $fp;
}
}
close (CPGOUT);
$self->output(\@fps);
}
1;
| mn1/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/Runnable/ProteinAnnotation/PIRSF.pm | Perl | apache-2.0 | 3,957 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
=head1 SYNOPSIS
=head1 DESCRIPTION
=head1 METHODS
=cut
package Bio::EnsEMBL::Utils::VegaCuration::Gene;
use strict;
use warnings;
use vars qw(@ISA);
use Bio::EnsEMBL::Utils::ConversionSupport;
@ISA = qw(Bio::EnsEMBL::Utils::ConversionSupport);
=head2 find_gaps
Args : arrayref of B::E::Transcripts
Example : my $gaps = find_gaps($all_transcripts)
Description: identifies regions of a gene that are not covered by any transcript
Returntype : int
Exceptions : none
Caller : internal
=cut
sub find_gaps {
my $self = shift;
my ($all_transcripts) = @_;
my $gaps = 0;
my @sorted_transcripts = sort {$a->start <=> $b->start || $b->end <=> $a->end} @{$all_transcripts};
if ( my $first_transcript = shift @sorted_transcripts ) {
my $pos = $first_transcript->end;
foreach my $transcript (@sorted_transcripts) {
next if ($transcript->end < $pos );
if ($transcript->start < $pos && $transcript->end > $pos ) {
$pos = $transcript->end;
next;
}
elsif ($transcript->end > $pos) {
$gaps++;
$pos = $transcript->end;
}
}
}
return $gaps;
}
| muffato/ensembl | modules/Bio/EnsEMBL/Utils/VegaCuration/Gene.pm | Perl | apache-2.0 | 2,105 |
:- module(faggr,[inject/3,preinject/3,postinject/4,merge/4,id/2,id/3,
prod/3,min/3,luka/3,dprod/3,max/3,dluka/3,'=>'/4],
[clpr,hiord]).
min(X,Y,Z):- X .=<. Y , Z .=. X.
min(X,Y,Z):- X .>. Y, Z .=. Y .
prod(X,Y,M):- M .=. X * Y.
luka(X,Y,M):- Z1.=.0,Z2.=. X + Y - 1,max(Z1,Z2,M).
max(X,Y,Z):- X .>=. Y, Z .=. X.
max(X,Y,Z):- Y .>. X, Z .=. Y.
dprod(X,Y,M):- M .=. X + Y - (X * Y).
dluka(X,Y,M):- Z1.=.1,Z2.=. X + Y, min(Z1,Z2,M).
:- meta_predicate preinject(?,pred(2),?).
id(L,L).
preinject([],_,[]):-!.
preinject(L,P,T):- P(L,T).
:- meta_predicate inject(?,pred(3),?).
inject([],_,_).
inject([T],_,T).
inject([X,Y|Rest],P,T):-
P(X,Y,T0),
inject([T0|Rest],P,T).
:- meta_predicate postinject(?,?,pred(3),?).
id(_,V,V).
postinject([],A,_,A):-!.
postinject(L,V,P,T):- P(L,V,T).
:- meta_predicate merge(?,?,pred(3),?).
merge([],L,_,L).
merge(L,[],_,L).
merge(L1,L2,P,L):-
list(L1),list(L2),!,
mergeaux(L1,L2,P,L).
mergeaux([],[],_,[]).
mergeaux([X|L1],[Y|L2],P,[Z|L]):-
P(X,Y,Z),
mergeaux(L1,L2,P,L).
:- new_declaration(is_fuzzy/3,on).
:- is_fuzzy('=>',4,truth).
:- meta_predicate =>(pred(3),goal,goal,?).
=>(Formula,($:(X)),($:(Y)),M):-
functor(X,_,Ax),
arg(Ax,X,Mx),
functor(Y,_,Ay),
arg(Ay,Y,My),
call(($:(X))),
call(($:(Y))),
call(Formula,Mx,My,M).
| leuschel/ecce | www/CiaoDE/ciao/library/fuzzy/faggr.pl | Perl | apache-2.0 | 1,291 |
#!/usr/bin/perl -w
###############################################################################
# $Id: vmware_cmd.pm 1670472 2015-03-31 20:34:45Z jfthomps $
###############################################################################
# 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.
###############################################################################
=head1 NAME
VCL::Module::Provisioning::VMware::vmware_cmd;
=head1 SYNOPSIS
my $vmhost_datastructure = $self->get_vmhost_datastructure();
my $vmware_cmd = VCL::Module::Provisioning::VMware::vmware_cmd->new({data_structure => $vmhost_datastructure});
my @registered_vms = $vmware_cmd->get_registered_vms();
=head1 DESCRIPTION
This module provides support for VMs to be controlled using VMware Server 1.x's
vmware-cmd command via SSH.
=cut
##############################################################################
package VCL::Module::Provisioning::VMware::vmware_cmd;
# Specify the lib path using FindBin
use FindBin;
use lib "$FindBin::Bin/../../../..";
# Configure inheritance
use base qw(VCL::Module::Provisioning::VMware::VMware);
# Specify the version of this module
our $VERSION = '2.4.2';
# Specify the version of Perl to use
use 5.008000;
use strict;
use warnings;
use diagnostics;
use VCL::utils;
##############################################################################
=head1 PRIVATE OBJECT METHODS
=cut
#/////////////////////////////////////////////////////////////////////////////
=head2 initialize
Parameters : none
Returns : boolean
Description : Initializes the vmware_cmd object by by checking if vmware-cmd is
available on the VM host.
=cut
sub initialize {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
my $args = shift;
# Check to make sure the VM host OS object is available
if (!defined $args->{vmhost_os}) {
notify($ERRORS{'WARNING'}, 0, "required 'vmhost_os' argument was not passed");
return;
}
elsif (ref $args->{vmhost_os} !~ /VCL::Module::OS/) {
notify($ERRORS{'CRITICAL'}, 0, "'vmhost_os' argument passed is not a reference to a VCL::Module::OS object, type: " . ref($args->{vmhost_os}));
return;
}
# Store a reference to the VM host OS object in this object
$self->{vmhost_os} = $args->{vmhost_os};
# Check if vmware-cmd is available on the VM host
my $command = 'vmware-cmd';
my ($exit_status, $output) = $self->vmhost_os->execute($command);
if (!defined($output)) {
notify($ERRORS{'WARNING'}, 0, "failed to run SSH command to determine if vmware-cmd is available on the VM host");
return;
}
elsif (grep(/not found/i, @$output)) {
notify($ERRORS{'DEBUG'}, 0, "vmware-cmd is not available on the VM host, output:\n" . join("\n", @$output));
return;
}
else {
notify($ERRORS{'DEBUG'}, 0, "vmware-cmd is available on VM host");
}
notify($ERRORS{'DEBUG'}, 0, ref($self) . " object initialized");
return 1;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 _run_vmware_cmd
Parameters : $vmware_cmd_arguments
Returns : array ($exit_status, $output)
Description : Runs vmware-cmd on the VMware host.
=cut
sub _run_vmware_cmd {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
my $vmware_cmd_arguments = shift;
if (!$vmware_cmd_arguments) {
notify($ERRORS{'WARNING'}, 0, "vmware-cmd arguments were not specified");
return;
}
my $vmhost_computer_name = $self->vmhost_os->data->get_computer_short_name();
my $command = "vmware-cmd $vmware_cmd_arguments";
my ($exit_status, $output) = $self->vmhost_os->execute($command);
if (!defined($output)) {
notify($ERRORS{'WARNING'}, 0, "failed to run vmware-cmd on VM host $vmhost_computer_name: '$command'");
}
else {
#notify($ERRORS{'DEBUG'}, 0, "executed vmware-cmd on VM host $vmhost_computer_name: '$command'");
return ($exit_status, $output);
}
}
##############################################################################
=head1 API OBJECT METHODS
=cut
#/////////////////////////////////////////////////////////////////////////////
=head2 get_registered_vms
Parameters : none
Returns : array
Description : Returns an array containing the vmx file paths of the VMs running
on the VM host.
=cut
sub get_registered_vms {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Run 'vmware-cmd -l'
my $vmware_cmd_arguments = "-l";
my ($exit_status, $output) = $self->_run_vmware_cmd($vmware_cmd_arguments);
return if !$output;
my @vmx_file_paths = grep(/^\//, @$output);
notify($ERRORS{'DEBUG'}, 0, "registered VMs found: " . scalar(@vmx_file_paths) . "\n" . join("\n", sort @vmx_file_paths));
return @vmx_file_paths;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_vm_power_state
Parameters : $vmx_file_path
Returns : string
Description : Returns a string containing the power state of the VM indicated
by the vmx file path argument. The string returned may be one of
the following values:
on
off
suspended
=cut
sub get_vm_power_state {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmx file path argument
my $vmx_file_path = shift;
if (!$vmx_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmx file path argument was not supplied");
return;
}
my $vmx_file_name = $self->_get_file_name($vmx_file_path);
# Run 'vmware-cmd <cfg> getstate'
my $vmware_cmd_arguments = "\"$vmx_file_path\" getstate";
my ($exit_status, $output) = $self->_run_vmware_cmd($vmware_cmd_arguments);
return if !$output;
# The output should look like this:
# getstate() = off
my $vm_power_state;
if (grep(/=\s*on/i, @$output)) {
$vm_power_state = 'on';
}
elsif (grep(/=\s*off/i, @$output)) {
$vm_power_state = 'off';
}
elsif (grep(/=\s*suspended/i, @$output)) {
$vm_power_state = 'suspended';
}
else {
notify($ERRORS{'WARNING'}, 0, "unexpected output returned while attempting to determine power state of '$vmx_file_path', vmware-cmd arguments: '$vmware_cmd_arguments' output:\n" . join("\n", @$output));
return;
}
notify($ERRORS{'DEBUG'}, 0, "power state of VM '$vmx_file_name': $vm_power_state");
return $vm_power_state;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 vm_power_on
Parameters : $vmx_file_path
Returns : boolean
Description : Powers on the VM indicated by the vmx file path argument.
=cut
sub vm_power_on {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmx file path argument
my $vmx_file_path = shift;
if (!$vmx_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmx file path argument was not supplied");
return;
}
my $vmx_file_name = $self->_get_file_name($vmx_file_path);
my $vmware_cmd_arguments = "\"$vmx_file_path\" start";
my ($exit_status, $output) = $self->_run_vmware_cmd($vmware_cmd_arguments);
return if !$output;
# Expected output if the VM was not previously powered on:
# start() = 1
# Expected output if the VM was previously powered on:
# VMControl error -8: Invalid operation for virtual machine's current state:
# The requested operation ("start") could not be completed because it
# conflicted with the state of the virtual machine ("on") at the time the
# request was received. This error often occurs because the state of the
# virtual machine changed before it received the request.
# Expected output if the VM is not registered: /usr/bin/vmware-cmd: Could not
# connect to VM /var/lib/vmware/Virtual Machines/Windows XP
# Professional/Windows XP Professional.vmx
# (VMControl error -11: No such virtual machine: The config file
# /var/lib/vmware/Virtual Machines/Windows XP Professional/Windows XP
# Professional.vmx is not registered.
# Please register the config file on the server. For example: vmware-cmd -s
# register "/var/lib/vmware/Virtual Machines/Windows XP Professional/Windows
# XP Professional.vmx")
if (grep(/\(\"on\"\)/i, @$output)) {
notify($ERRORS{'OK'}, 0, "VM is already powered on: '$vmx_file_name'");
return 1;
}
elsif (grep(/=\s*1/i, @$output)) {
notify($ERRORS{'OK'}, 0, "powered on VM: '$vmx_file_name'");
return 1;
}
elsif (grep(/error -11/i, @$output)) {
notify($ERRORS{'WARNING'}, 0, "unable to power on VM because it is not registered: '$vmx_file_path'");
return;
}
else {
notify($ERRORS{'WARNING'}, 0, "unexpected output returned while attempting to power on VM '$vmx_file_path', vmware-cmd arguments: '$vmware_cmd_arguments', output:\n" . join("\n", @$output));
return;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 vm_power_off
Parameters : $vmx_file_path
Returns : boolean
Description : Powers off the VM indicated by the vmx file path argument.
=cut
sub vm_power_off {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmx file path argument
my $vmx_file_path = shift;
if (!$vmx_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmx file path argument was not supplied");
return;
}
my $vmx_file_name = $self->_get_file_name($vmx_file_path);
my $vmware_cmd_arguments = "\"$vmx_file_path\" stop hard";
my ($exit_status, $output) = $self->_run_vmware_cmd($vmware_cmd_arguments);
return if !$output;
# Expected output if the VM was not previously powered on:
# stop(hard) = 1
# Expected output if the VM was previously powered on: VMControl error -8:
# Invalid operation for virtual machine's current state: The requested
# operation ("stop") could not be completed because it conflicted with the
# state of the virtual machine ("off") at the time the request was received.
# This error often occurs because the state of the virtual machine changed
# before it received the request.
# Expected output if the VM is not registered: /usr/bin/vmware-cmd: Could not
# connect to VM /var/lib/vmware/Virtual Machines/Windows XP
# Professional/Windows XP Professional.vmx
# (VMControl error -11: No such virtual machine: The config file
# /var/lib/vmware/Virtual Machines/Windows XP Professional/Windows XP
# Professional.vmx is not registered.
# Please register the config file on the server. For example: vmware-cmd -s
# register "/var/lib/vmware/Virtual Machines/Windows XP Professional/Windows
# XP Professional.vmx")
if (grep(/\(\"off\"\)/i, @$output)) {
notify($ERRORS{'OK'}, 0, "VM is already powered off: '$vmx_file_name'");
return 1;
}
elsif (grep(/=\s*1/i, @$output)) {
notify($ERRORS{'OK'}, 0, "powered off VM: '$vmx_file_name'");
return 1;
}
elsif (grep(/error -11/i, @$output)) {
notify($ERRORS{'WARNING'}, 0, "unable to power off VM because it is not registered: '$vmx_file_path'");
return;
}
else {
notify($ERRORS{'WARNING'}, 0, "unexpected output returned while attempting to power off VM '$vmx_file_path', vmware-cmd arguments: '$vmware_cmd_arguments', output:\n" . join("\n", @$output));
return;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 vm_register
Parameters : $vmx_file_path
Returns : boolean
Description : Registers the VM indicated by the vmx file path argument.
=cut
sub vm_register {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmx file path argument
my $vmx_file_path = shift;
if (!$vmx_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmx file path argument was not supplied");
return;
}
my $vmx_file_name = $self->_get_file_name($vmx_file_path);
my $vmware_cmd_arguments = "-s register \"$vmx_file_path\"";
my ($exit_status, $output) = $self->_run_vmware_cmd($vmware_cmd_arguments);
return if !$output;
# Expected output if the VM is already registered:
# VMControl error -20: Virtual machine already exists
# Expected output if the VM is successfully registered:
# register(<vmx path>) = 1
if (grep(/error -20/i, @$output)) {
notify($ERRORS{'OK'}, 0, "VM is already registered: '$vmx_file_name'");
return 1;
}
elsif (grep(/=\s*1/i, @$output)) {
notify($ERRORS{'OK'}, 0, "registered VM: '$vmx_file_name'");
return 1;
}
else {
notify($ERRORS{'WARNING'}, 0, "unexpected output returned while attempting to register VM '$vmx_file_path', vmware-cmd arguments: '$vmware_cmd_arguments', output:\n" . join("\n", @$output));
return;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 vm_unregister
Parameters : $vmx_file_path
Returns : boolean
Description : Unregisters the VM indicated by the vmx file path argument.
=cut
sub vm_unregister {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmx file path argument
my $vmx_file_path = shift;
if (!$vmx_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmx file path argument was not supplied");
return;
}
my $vmx_file_name = $self->_get_file_name($vmx_file_path);
# Check if the VM is not registered
if (!$self->is_vm_registered($vmx_file_path)) {
notify($ERRORS{'OK'}, 0, "VM not unregistered because it is not registered: '$vmx_file_name'");
return 1;
}
# Power off the VM if it is on
my $vm_power_state = $self->get_vm_power_state($vmx_file_path) || '';
if ($vm_power_state =~ /on/i && !$self->vm_power_off($vmx_file_path)) {
notify($ERRORS{'WARNING'}, 0, "failed to power off VM before unregistering it: '$vmx_file_name', VM power state: $vm_power_state");
return;
}
my $vmware_cmd_arguments = "-s unregister \"$vmx_file_path\"";
my ($exit_status, $output) = $self->_run_vmware_cmd($vmware_cmd_arguments);
return if !$output;
# Expected output if the VM is not registered:
# VMControl error -11: No such virtual machine
# Expected output if the VM is successfully unregistered:
# unregister(<vmx path>) = 1
if (grep(/error -11/i, @$output)) {
notify($ERRORS{'OK'}, 0, "VM is not registered: '$vmx_file_name'");
}
elsif (grep(/=\s*1/i, @$output)) {
notify($ERRORS{'OK'}, 0, "unregistered VM: '$vmx_file_name'");
}
else {
notify($ERRORS{'WARNING'}, 0, "unexpected output returned while attempting to unregister VM '$vmx_file_path', vmware-cmd arguments: '$vmware_cmd_arguments', output:\n" . join("\n", @$output));
return;
}
# Make sure the VM is not registered
if ($self->is_vm_registered($vmx_file_path)) {
notify($ERRORS{'WARNING'}, 0, "failed to unregister VM, it appears to still be registered: '$vmx_file_path'");
return;
}
return 1;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_virtual_disk_controller_type
Parameters : $vmdk_file_path
Returns :
Description : Retrieves the disk controller type configured for the virtual
disk specified by the vmdk file path argument. A string is
returned containing one of the following values:
-ide
-buslogic
-lsilogic
=cut
sub get_virtual_disk_controller_type {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmdk file path argument
my $vmdk_file_path = shift;
if (!$vmdk_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmdk file path argument was not supplied");
return;
}
my $vmdk_file_name = $self->_get_file_name($vmdk_file_path);
my $vmhost_computer_name = $self->vmhost_os->data->get_computer_short_name();
my $command = "grep -i adapterType \"$vmdk_file_path\"";
my ($exit_status, $output) = $self->vmhost_os->execute($command);
if (!defined($output)) {
notify($ERRORS{'WARNING'}, 0, "failed to run command on VM host $vmhost_computer_name: '$command'");
}
my ($adapter_type) = "@$output" =~ /adapterType\s*=\s*\"(\w+)\"/i;
if ($adapter_type) {
notify($ERRORS{'DEBUG'}, 0, "adapter type configured in '$vmdk_file_name': $adapter_type");
return $adapter_type;
}
else {
notify($ERRORS{'WARNING'}, 0, "unable to determine adapter type configured in '$vmdk_file_name', command: '$command', output:\n" . join("\n", @$output));
return;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_virtual_disk_type
Parameters : $vmdk_file_path
Returns :
Description : Retrieves the disk type configured for the virtual
disk specified by the vmdk file path argument. A string is
returned containing one of the following values:
-monolithicSparse
-twoGbMaxExtentSparse
-monolithicFlat
-twoGbMaxExtentFlat
=cut
sub get_virtual_disk_type {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmdk file path argument
my $vmdk_file_path = shift;
if (!$vmdk_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmdk file path argument was not supplied");
return;
}
my $vmdk_file_name = $self->_get_file_name($vmdk_file_path);
my $vmhost_computer_name = $self->vmhost_os->data->get_computer_short_name();
my $command = "grep -i createType \"$vmdk_file_path\"";
my ($exit_status, $output) = $self->vmhost_os->execute($command);
if (!defined($output)) {
notify($ERRORS{'WARNING'}, 0, "failed to run command on VM host $vmhost_computer_name: '$command'");
}
my ($disk_type) = "@$output" =~ /createType\s*=\s*\"(\w+)\"/i;
if ($disk_type) {
notify($ERRORS{'DEBUG'}, 0, "disk type configured in '$vmdk_file_name': $disk_type");
return $disk_type;
}
else {
notify($ERRORS{'WARNING'}, 0, "unable to determine disk type configured in '$vmdk_file_name', command: '$command', output:\n" . join("\n", @$output));
return;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_virtual_disk_hardware_version
Parameters : $vmdk_file_path
Returns : integer
Description : Retrieves the hardware version configured for the virtual
disk specified by the vmdk file path argument. False is returned
if the hardware version cannot be retrieved.
=cut
sub get_virtual_disk_hardware_version {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmdk file path argument
my $vmdk_file_path = shift;
if (!$vmdk_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmdk file path argument was not supplied");
return;
}
my $vmdk_file_name = $self->_get_file_name($vmdk_file_path);
my $vmhost_computer_name = $self->vmhost_os->data->get_computer_short_name();
my $command = "grep -i virtualHWVersion \"$vmdk_file_path\"";
my ($exit_status, $output) = $self->vmhost_os->execute($command);
if (!defined($output)) {
notify($ERRORS{'WARNING'}, 0, "failed to run command on VM host $vmhost_computer_name: '$command'");
}
my ($hardware_version) = "@$output" =~ /virtualHWVersion\s*=\s*\"(\w+)\"/i;
if (defined($hardware_version)) {
notify($ERRORS{'DEBUG'}, 0, "hardware version configured in '$vmdk_file_name': $hardware_version");
return $hardware_version;
}
else {
notify($ERRORS{'WARNING'}, 0, "unable to determine hardware version configured in '$vmdk_file_name', command: '$command', output:\n" . join("\n", @$output));
return;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 _get_datastore_info
Parameters : none
Returns : hash reference
Description : Retrieves information about the VM host's datastore from the
/etc/vmware/config file and returns a hash containing the
information.
=cut
sub _get_datastore_info {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
my $vmhost_profile_datastore_path = $self->data->get_vmhost_profile_datastore_path();
my $vmhost_profile_vmpath = $self->data->get_vmhost_profile_vmpath();
$vmhost_profile_datastore_path = normalize_file_path($vmhost_profile_datastore_path);
$vmhost_profile_vmpath = normalize_file_path($vmhost_profile_vmpath);
# Get the contents of the VMware config file
my $config_file_path = '/etc/vmware/config';
my $config_datastore_name;
my $config_datastore_path;
my @config_contents = $self->vmhost_os->get_file_contents($config_file_path);
if (@config_contents) {
notify($ERRORS{'DEBUG'}, 0, "retrieved contents of $config_file_path\n" . join("\n", @config_contents));
# Get the datastore name and path from the file contents
($config_datastore_name) = map { $_ =~ /datastore\.name\s*=\s*"([^"]+)"/ } @config_contents;
if (!$config_datastore_name) {
notify($ERRORS{'WARNING'}, 0, "failed to locate the 'datastore.name' line in $config_file_path");
}
($config_datastore_path) = map { $_ =~ /datastore\.localpath\s*=\s*"([^"]+)"/ } @config_contents;
if ($config_datastore_path) {
$config_datastore_path = normalize_file_path($config_datastore_path);
}
else {
notify($ERRORS{'WARNING'}, 0, "failed to locate the 'datastore.localpath' line in $config_file_path");
}
}
else {
notify($ERRORS{'WARNING'}, 0, "failed to retrieve the contents of $config_file_path");
}
# Create a hash containing datastore names and their paths
my %datastore_info;
# Keep track of paths added to returning %datastore_info hash so the same path isn't added more than once
my %datastore_paths;
# Add the datastore found in the config file
if (defined($config_datastore_name) && defined($config_datastore_path)) {
$datastore_info{$config_datastore_name}{normal_path} = $config_datastore_path;
$datastore_paths{$config_datastore_path} = 1;
};
# Add datastores for the VM host profile vmpath and datastore if they are different than what's in the config file
if (!defined($datastore_paths{$vmhost_profile_vmpath})) {
$datastore_info{'vmprofile-vmpath'}{normal_path} = $vmhost_profile_vmpath;
$datastore_paths{$vmhost_profile_vmpath} = 1;
}
if (!defined($datastore_paths{$vmhost_profile_datastore_path})) {
$datastore_info{'vmprofile-datastore'}{normal_path} = $vmhost_profile_datastore_path;
$datastore_paths{$vmhost_profile_vmpath} = 1;
}
# Construct a hash containing
for my $datastore_name (keys %datastore_info) {
my $datastore_path = $datastore_info{$datastore_name}{normal_path};
$datastore_info{$datastore_name}{accessible} = 'true';
$datastore_info{$datastore_name}{type} = 'local';
$datastore_info{$datastore_name}{url} = $datastore_path;
my $available_space = $self->vmhost_os->get_available_space($datastore_path);
if (defined($available_space)) {
$datastore_info{$datastore_name}{freeSpace} = $available_space;
}
else {
notify($ERRORS{'WARNING'}, 0, "failed to determine the amount of space available in datastore '$datastore_name' ($datastore_path)");
}
my $total_space = $self->vmhost_os->get_total_space($datastore_path);
if (defined($total_space)) {
$datastore_info{$datastore_name}{capacity} = $total_space;
}
else {
notify($ERRORS{'WARNING'}, 0, "failed to determine the total amount of space of the volume where datastore '$datastore_name' ($datastore_path) resides");
}
}
notify($ERRORS{'DEBUG'}, 0, "retrieved datastore info:\n" . format_data(\%datastore_info));
return \%datastore_info;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 create_snapshot
Parameters : $vmx_file_path
Returns : boolean
Description : Creates a snapshot of the VM.
=cut
sub create_snapshot {
my $self = shift;
if (ref($self) !~ /VCL::Module/i) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine was called as a function, it must be called as a class method");
return;
}
# Get the vmx file path argument
my $vmx_file_path = shift;
if (!$vmx_file_path) {
notify($ERRORS{'WARNING'}, 0, "vmx file path argument was not supplied");
return;
}
my $command = "vmrun snapshot \"$vmx_file_path\"";
my ($exit_status, $output) = $self->vmhost_os->execute($command, 1);
if (!defined($output)) {
notify($ERRORS{'WARNING'}, 0, "failed to execute vmrun to create a snapshot of VM: $vmx_file_path, command: '$command'");
return;
}
elsif ($exit_status != 0 || grep(/error/i, @$output)) {
notify($ERRORS{'WARNING'}, 0, "error occurred executing vmrun to create a snapshot of VM: $vmx_file_path, command: '$command', output:\n" . join("\n", @$output));
return;
}
else {
notify($ERRORS{'OK'}, 0, "created snapshot of VM: $vmx_file_path, output:\n" . join("\n", @$output));
return 1;
}
}
#/////////////////////////////////////////////////////////////////////////////
1;
__END__
=head1 SEE ALSO
L<http://cwiki.apache.org/VCL/>
=cut
| bq-xiao/apache-vcl | managementnode/lib/VCL/Module/Provisioning/VMware/vmware_cmd.pm | Perl | apache-2.0 | 26,423 |
#!/usr/bin/perl
open (FIN, "find . -type f|") || die;
while (<FIN>) {
$files ++;
chomp;
$t += -s;
if (/\.\S+(\.[^.]+)$/) {
$X{$1}++;
}
}
printf ("Files: %d\n", $files);
for (sort { $X{$a} <=> $X{$b} } keys %X) {
printf ("%7d %s\n", $X{$_}, $_);
}
| RobertTDowling/local | local/bin/speculative/extensions.pl | Perl | bsd-2-clause | 274 |
#!/pkg/gnu/bin//perl5
#
push(@INC, "$wd/bin");
require('WebStone-common.pl');
$oldfilelist = "$wd/conf/filelist";
html_begin();
if ($filelist ne $oldfilelist) {
$backup = $oldfilelist . ".bak";
print CLIENT "<BODY>Backing up $oldfilelist to $backup";
rename($oldfilelist, $backup);
print CLIENT "<P>Copying $filelist to $oldfilelist";
link($filelist, $oldfilelist);
print CLIENT "<P>Done.";
}
else
{
print CLIENT "<STRONG>Can't move $filelist <P>to $filelist</STRONG>";
}
html_end();
# end
| wfnex/openbras | src/ace/ACE_wrappers/apps/JAWS/clients/WebSTONE/bin/move-filelist.pl | Perl | bsd-3-clause | 524 |
package Reactive::Observable::Wrapper;
use Moose;
has wrap => (is => 'rw', required => 1);
extends 'Reactive::Observable::Composite';
sub initial_subscriptions { (shift->wrap) }
1;
| eilara/Rx.pl | lib/Reactive/Observable/Wrapper.pm | Perl | mit | 187 |
package Paws::EC2::EnableVpcClassicLinkDnsSupportResult;
use Moose;
has Return => (is => 'ro', isa => 'Bool', request_name => 'return', traits => ['NameInRequest',]);
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::EC2::EnableVpcClassicLinkDnsSupportResult
=head1 ATTRIBUTES
=head2 Return => Bool
Returns C<true> if the request succeeds; otherwise, it returns an
error.
=head2 _request_id => Str
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/EC2/EnableVpcClassicLinkDnsSupportResult.pm | Perl | apache-2.0 | 478 |
#!/usr/bin/perl -w
#
# ogflow.pl - Convert OmniGraffle File to Workflow Definition
#
# This script converts an OmniGraffle flowchart into an XML
# document for the Workflow module.
#
# TODO:
#
# Add code to reject conditions after actions -- there must be a state
# between them.
#
# Since OmniGraffle doesn't really understand the structure of our XML
# definition files, there are many assumptions that must be adhered to
# for this to work properly.
#
# In the "Document Description" (via the inspector), enter the unique
# identifier for your workflow (e.g.: SMARTCARD_PERS). This is then
# used for the I18N identifiers and the names of the output XML files.
#
# The following objects in the OG document are supported
#
# Shape:
#
# RoundRect = activity
#
# The following XML objects are written:
#
# state definitions (<state>)
#
# name = text field from graphics object
# autorun = set "autorun" to "yes" in the key/value table for the object
# description = 'workflow i18n prefix' + name
# actions = action objects that this connects to
# name = name of action
# resulting_state = state that action points to
# condition = name of condition
#
# activities (<action>)
#
# In "Properties: Note" in the inspector, the data key/values specified
# are appended to the <action name="yourname" ..." entity.
#
# Use the key "class" to specify the perl class for this action. If left empty,
# "Workflow::Actions::Null" is used.
#
# Additional parameters for the
# perl module may be specified here. Note: these are static parameters
# for this action.
#
# Fields (workflow instance arguments) may be specified in the first
# and second cells of the table object. These are comma-separated lists.
# The first cell specifies mandatory fields, whereas those in the second
# cell are optional.
#
#
# conditions (<condition>)
#
# In "Properties: Note" in the inspector, the data key/values specified
# are added to the entity as <param> items. The key is the param name
# and the value is the value of the parameter.
#
# Use the key "class" to specify the perl class for this condition.
#
# goto (an upside down house shape used to go to another page)
#
# When a link is coming from another page, just specify the name of the
# page on one line. These objects will be ignored during the processing.
#
# When a link goes to another page, specify the page name and resulting
# state name, separated with a colon, followed by a line feed (":<line feed>").
#
# Usage:
#
# ogflow.pl FILENAME
#
# Notes:
#
# asXml gets called when the object type is the primary type for the output
# file. For example, when creating workflow_def_<wfname>.xml, asXml gets called
# on the type 'state'. If it is a sub-type of the current output, as<wftype>Xml
# gets called. The type 'state' for example, can also be a child of another state.
# In this case, there is an implicit 'action' and calling asStateXml on the 'state'
# object returns the '<action name="null" resulting_state="<this state>"</action>'.
use strict;
use Mac::PropertyList;
use Data::Dumper;
use Carp;
use Cwd;
my $showUnknown = 1;
my $docVersion = ''; # from document data
my $docSubject = ''; # from document data
my $descPrefix = 'DOC_DESC_NOT_SET';
my $i18nPrefix = 'I18N_OPENXPKI_WF';
my $indentSpace = ' ' x 4;
my $namespace = '';
my $verbose = 0;
my $force = 1;
warn "WARN: force is with you\n";
my $sheetnum = 1;
our $objs = {};
our $connsByFromId = {};
our $condLabelsByLineId = ();
our $maxNull = 0;
# This is the base class for the following shape (non-line objects)
package WF::Shape;
use Class::InsideOut qw( public readonly private register id );
public notes => my %shape_notes;
public sheet => my %shape_sheet;
public oid => my %shape_oid;
public text => my %shape_text;
sub fqname {
my $self = shift;
# If text does not start with 'I18N', prepend the namespace
if ( $self->text =~ /^I18N/ ) {
return $self->text;
} else {
return $namespace . $self->text;
}
}
sub equals {
my ( $a, $b ) = @_;
foreach my $k (qw( notes text )) {
if ( ( not defined $a->$k ) and ( not defined $b->$k ) ) {
return 1;
}
elsif ( ( not defined $a->$k ) or ( not defined $b->$k ) ) {
return;
}
elsif ( $a->$k ne $b->$k ) {
warn "equals() field $k doesn't match:\n",
"Obj A: ", $a->dumpPretty( indent => 1 ),
"Obj B: ", $b->dumpPretty( indent => 1 );
return;
}
}
return 1;
}
sub dump {
my $self = shift;
# my @ret = map { $_, ( $_[0]->$_ ? $_[0]->$_ : '<undef>' ) }
# qw( type oid sheet text );
my @ret = "Object: "
. join( ' ',
map { "$_=" . ( $self->$_ ? $self->$_ : '<undef>' ) }
qw( type oid sheet text ) );
# my @ret = "Object: type=" . $self->type
# . " oid=" . $self->oid
# . " sheet=" . $self->sheet
# . " text=" . $self->text;
if ( exists $connsByFromId->{ $self->sheet }->{ $self->oid } ) {
push @ret, 'Connections: '
. join( ', ',
@{ $connsByFromId->{ $self->sheet }->{ $self->oid } } );
# foreach ( @{ $connsByFromId->{ $self->sheet }->{ $self->oid } } ) {
# push @ret, map { "\t" . $_ } $objs->{ $self->sheet }->{$_}->dump;
# }
}
return @ret;
}
sub dumpPretty {
my $self = shift;
my %p = @_;
my @ret = $self->dump;
my $indent = $p{indent} || 0;
return ( "\t" x $indent ) . join( "\n" . "\t" x $indent, @ret ) . "\n";
}
sub children {
my $self = shift;
my $line2lineFix = 0;
my @ret = ();
if ( exists $connsByFromId->{ $self->sheet }->{ $self->oid } ) {
foreach my $connLine ( map { $objs->{ $self->sheet }->{$_} }
@{ $connsByFromId->{ $self->sheet }->{ $self->oid } } )
{
my $nextObj = $objs->{ $connLine->sheet }->{ $connLine->to };
if ( not defined $nextObj ) {
Carp::cluck "Internal error (object id ", $connLine->to,
" not found) processing object:\n",
$self->dumpPretty( indent => 1 ),
"Line object with missing destination object:\n",
$connLine->dumpPretty( indent => 1 );
next;
}
my $obj;
if ( $nextObj->type eq 'goto' ) {
push @ret, $nextObj->children;
# my $obj;
# foreach $obj ( map { values %{$_} } values %{$objs} ) {
# next unless $obj->type eq 'state';
# if ( $obj->text eq $nextObj->state ) {
# push @ret, $obj;
# last;
# }
# }
}
elsif ( $line2lineFix and $nextObj->type eq 'line' ) {
# try to skip to next line
while ( defined $nextObj
and $nextObj->type eq 'line'
and $nextObj->to )
{
$nextObj = $objs->{ $self->sheet }->{ $nextObj->to };
}
push @ret, $nextObj if defined $nextObj;
}
else {
push @ret, $nextObj if $nextObj;
}
}
return @ret;
}
else {
return;
}
}
package WF::State;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
use Data::Dumper;
public userInfo => my %state_userInfo;
sub new { register(shift) }
sub type { return 'state' }
sub maxNull {
my $self = shift;
my $null;
foreach my $child ( $self->children ) {
if ( $child->type eq 'state' ) {
$null++;
if ( $null > $maxNull ) {
$maxNull = $null;
}
}
elsif ( $child->type eq 'condition' ) {
my @actions = $child->listActions;
# check for null
foreach my $a (@actions) {
if ( $a->[0] eq 'null' ) {
$null++;
if ( $null > $maxNull ) {
$maxNull = $null;
}
}
}
}
}
return $maxNull;
}
sub asXml {
my $self = shift;
my $indent = shift || 0;
my @out = ();
my $null = 0;
my $userInfo = $self->userInfo;
if ( $self->text =~ /^I18N_/ ) {
return;
}
push @out, $indentSpace x $indent++;
push @out, '<state name="', $self->text, '"';
if ( defined $userInfo and ref($userInfo) eq 'HASH' ) {
foreach my $k ( sort grep { not $_ eq 'class' } keys %{$userInfo} ) {
push @out, "\n", $indentSpace x ( $indent + 1 ), $k, '="',
$userInfo->{$k}, '"';
}
}
push @out, '>', "\n";
push @out, $indentSpace x $indent, '<description>',
$i18nPrefix, '_STATE_', $descPrefix, '_', $self->text,
'</description>', "\n";
foreach my $child ( $self->children ) {
warn $child->dumpPretty( indent => 1 ) if $verbose;
if ( $child->type eq 'action' ) {
push @out, $child->asStateXml($indent);
}
elsif ( $child->type eq 'state' ) {
$null++;
if ( $null > $maxNull ) {
$maxNull = $null;
}
push @out, $child->asStateXml( $indent, $null );
}
elsif ( $child->type eq 'condition' ) {
my @actions = $child->listActions;
# check for null
foreach my $a (@actions) {
if ( $a->[0] eq 'null' ) {
$null++;
if ( $null > $maxNull ) {
$maxNull = $null;
}
$a->[0] = 'null' . $null;
}
}
foreach my $rec (@actions) {
push @out, $indentSpace x $indent, '<action name="',
( $namespace . shift @{$rec} ),
'" resulting_state="', shift @{$rec}, '">', "\n";
foreach my $cond ( @{$rec} ) {
push @out, $indentSpace x ( $indent + 1 ),
'<condition name="', $cond, '"/>', "\n";
}
push @out, $indentSpace x $indent, '</action>', "\n";
}
}
else {
warn "unsupported child: ", $child->dump;
}
}
$indent--;
push @out, $indentSpace x $indent;
push @out, '</state>', "\n";
return @out;
}
sub asStateXml {
my $self = shift;
my $indent = shift || 0;
my $null = shift || 0;
my $condName = shift;
my @out = ();
push @out, $indentSpace x $indent, '<action name="', $namespace, 'null',
$null,
'" resulting_state="', $self->text, '">', "\n";
if ( defined $condName ) {
push @out, $indentSpace x ( $indent + 1 ),
'<condition name="', $condName, '">', "\n";
}
push @out, $indentSpace x $indent, '</action>', "\n";
return @out;
}
package WF::Condition;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
use XML::Simple;
public class => my %cond_class;
public params => my %cond_params;
sub new { register(shift) }
sub type { return 'condition' }
sub childLines {
my $self = shift;
my @ret = ();
if ( exists $connsByFromId->{ $self->sheet }->{ $self->oid } ) {
foreach my $connLine ( map { $objs->{ $self->sheet }->{$_} }
@{ $connsByFromId->{ $self->sheet }->{ $self->oid } } )
{
push @ret, $connLine;
}
return @ret;
}
else {
return;
}
}
sub asXml {
my $self = shift;
my $indent = shift || 0;
my @out = ();
my $class = $self->class; # || 'Class Not Set';
if ( $self->text =~ /^I18N_/ ) {
return;
}
push @out, $indentSpace x $indent++;
push @out, '<condition name="', $self->fqname, '"';
if ($class) {
push @out,, "\n", $indentSpace x ( $indent + 1 ), 'class="', $class,
'"';
}
push @out, '>', "\n";
# No, I don't have time at the moment to refactor _everything_
# to use XML::Simple, but I do need it to escape things like '<='
# in the parameter values, so here is just a quick hack.
my $params = $self->params;
foreach my $k ( keys %{$params} ) {
# push @out, $indentSpace x ($indent), '<param name="', $k,
# '" value="', $params->{$k}, '"/>', "\n";
push @out, $indentSpace x ($indent),
XMLout( { param => { name => $k, value => $params->{$k} } },
KeepRoot => 1 );
}
$indent--;
push @out, $indentSpace x $indent;
push @out, '</condition>', "\n";
return @out;
}
# return a list of actions in the form
# [ 'actionname', 'resulting state', 'condition1' [ , 'condition2' ...] ]
sub listActions {
my $self = shift;
my @ret = ();
foreach my $childLine ( $self->childLines ) {
my $child = $objs->{ $self->sheet }->{ $childLine->to };
if ( not defined $child ) {
warn "WARN: destination not defined for line:\n",
$childLine->dumpPretty;
next;
}
my $val = $condLabelsByLineId->{ $self->sheet }->{ $childLine->oid };
my $condName = $self->fqname;
if ( not defined $val ) {
warn "WARN: Label for line from condition not defined - ",
$self->dump;
}
elsif ( $val eq 'no' ) {
$condName = '!' . $condName;
}
if ( $child->type eq 'action' ) {
push @ret, [ $child->text, $child->nextState, $condName ];
}
elsif ( $child->type eq 'state' ) {
push @ret, [ 'null', $child->text, $condName ];
}
elsif ( $child->type eq 'goto' ) {
my $obj;
my $found = 0;
my @statesRejected = (); # for debugging
foreach $obj (
map {
sort { $a->oid <=> $b->oid }
values %{ $objs->{$_} }
} sort { $a <=> $b } keys %{$objs}
)
{
next unless $obj->type eq 'state';
if ( $obj->text eq $child->state ) {
$found++;
push @ret, [ 'null', $obj->text, $condName ];
last;
}
else {
push @statesRejected, $obj->text;
}
}
if ( not $found ) {
warn "Goto state '", $child->state, "' not found in (",
join( ', ', sort @statesRejected ), "): ",
$child->dump;
}
}
elsif ( $child->type eq 'condition' ) {
my @childActions = $child->listActions;
foreach my $ca (@childActions) {
push @ret, [ @{$ca}, $condName ];
}
}
else {
warn "unsupported child: ", $child->dump;
}
}
return @ret;
}
sub asStateXml {
my $self = shift;
my $indent = shift || 0;
my $null = shift || 0;
my @out = ();
push @out, $indentSpace x $indent;
foreach my $childLine ( $self->childLines ) {
my $child = $objs->{ $self->sheet }->{ $childLine->to };
my $val = $condLabelsByLineId->{ $self->sheet }->{ $childLine->oid };
my $condName = $self->text;
if ( not defined $val ) {
warn "WARN: Label for line from condition not defined - ",
$self->dump;
}
elsif ( $val eq 'no' ) {
$condName = '!' . $condName;
}
if ( $child->type eq 'action' ) {
push @out, $child->asStateXml( $indent, $condName );
}
elsif ( $child->type eq 'state' ) {
push @out, $child->asStateXml( $indent, $null, $condName );
}
elsif ( $child->type eq 'goto' ) {
my $obj;
my $found = 0;
my @statesRejected = (); # for debugging
foreach $obj (
map {
sort { $a->oid <=> $b->oid }
values %{ $objs->{$_} }
} sort { $a <=> $b } keys %{$objs}
)
{
next unless $obj->type eq 'state';
if ( $obj->text eq $child->state ) {
$found++;
push @out, $obj->asStateXml( $indent, $null, $condName );
last;
}
else {
push @statesRejected, $obj->text;
}
}
if ( not $found ) {
warn "Goto state '", $child->state, "' not found in (",
join( ', ', sort @statesRejected ), "): ",
$child->dump;
}
}
elsif ( $child->type eq 'condition' ) {
push @out, '<!-- multi-level condition: ', $child->dump, '-->',
"\n";
my @recs = $self->listActions;
foreach my $rec (@recs) {
push @out, '<action name="', $namespace . shift @{$rec},
'" resulting_state="', shift @{$rec}, '">', "\n";
foreach my $cond ( @{$rec} ) {
push @out, '<condition name="', $cond, '"/>', "\n";
}
push @out, '</action>', "\n";
}
}
else {
warn "unsupported child: ", $child->dump;
}
}
return @out;
}
package WF::Action;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
use Data::Dumper;
public userInfo => my %action_userInfo;
public fields => my %action_fields;
sub new { register(shift) }
sub type { return 'action' }
sub dump {
my $self = shift;
my @ret = $self->SUPER::dump();
foreach my $p (qw( userInfo fields )) {
my $href = $self->$p;
if ( defined $href ) {
push @ret, $p . '=(' . join( ', ', %{$href} ) . ')';
}
}
return @ret;
}
sub equals {
my ( $a, $b ) = @_;
foreach my $p (qw( userInfo fields )) {
# use Data::Dumper to serialize before comparing
my $d1 = Dumper( $a->$p );
my $d2 = Dumper( $b->$p );
if ( $d1 ne $d2 ) {
warn "equals() - field $p: '$d1' ne '$d2'", "\n",
"Obj A: ", $a->dumpPretty( indent => 1 ),
"Obj B: ", $b->dumpPretty( indent => 1 );
return;
}
}
return $a->SUPER::equals($b);
}
sub nextState {
my $self = shift;
my @children = grep { ( defined $_ ) and ( $_->type ne 'validator' ) }
$self->children;
if ( not scalar @children == 1 ) {
warn "Actions may only have one child and for this action, I found ",
scalar @children;
warn "\tCurrent action: ", $self->dump;
die "Cannot continue!";
}
my $child = $children[0];
if ( $child->type eq 'state' ) {
return $child->text;
}
return;
}
sub asXml {
my $self = shift;
my $indent = shift || 0;
my @out = ();
my $null = 0;
my $userInfo = $self->userInfo;
my $fields = $self->fields;
my $actionClass;
if ( $self->text =~ /^I18N_/ ) {
return;
}
if ( defined $userInfo and exists $userInfo->{class} ) {
$actionClass = $userInfo->{class};
}
else {
$actionClass = 'Workflow::Action::Null';
}
push @out, $indentSpace x $indent++;
push @out, '<action name="', $self->fqname, '"', "\n";
push @out, $indentSpace x ( $indent + 1 ), 'class="', $actionClass, '"';
if ( defined $userInfo and ref($userInfo) eq 'HASH' ) {
foreach my $k ( sort grep { not $_ eq 'class' } keys %{$userInfo} ) {
push @out, "\n", $indentSpace x ( $indent + 1 ), $k, '="',
$userInfo->{$k}, '"';
}
}
push @out, ">\n";
if ( $self->notes ) {
push @out, $indentSpace x ( $indent + 1 ),
'<description>', $self->notes, '</description>', "\n";
}
if ( defined $fields and ref($fields) eq 'HASH' ) {
foreach my $k ( sort keys %{$fields} ) {
push @out, $indentSpace x ( $indent + 1 ),
'<field name="', $k, '"';
if ( $fields->{$k} ) {
push @out, ' is_required="yes"';
}
push @out, "/>\n";
}
}
foreach my $val ( grep { $_->type eq 'validator' } $self->children ) {
push @out, $val->asActionXml( $indent + 1 );
}
$indent--;
push @out, $indentSpace x $indent;
push @out, '</action>', "\n";
return @out;
}
# Generates the <action> entity used in the state definition
sub asStateXml {
my $self = shift;
my $indent = shift || 0;
my $condName = shift;
my @children = grep { ( defined $_ ) and ( $_->type ne 'validator' ) }
$self->children;
if ( not scalar @children == 1 ) {
warn
"Actions must have one and only one child -- for this action, I found ",
scalar @children;
warn "Current action: ", $self->dumpPretty( indent => 1 );
foreach (@children) {
warn "Connection Details:\n",
$objs->{ $self->sheet }->{$_}->dumpPretty( indent => 1 );
}
if ( exists $connsByFromId->{ $self->sheet }->{ $self->oid } ) {
warn "Connections: \n";
foreach ( @{ $connsByFromId->{ $self->sheet }->{ $self->oid } } )
{
warn $objs->{ $self->sheet }->{$_}->dumpPretty( indent => 1 ),
"\n";
}
}
die "Cannot continue!";
}
my @out = ();
push @out, $indentSpace x $indent;
push @out, '<action name="', $self->fqname,
'" resulting_state="', $children[0]->text, '">', "\n";
if ( defined $condName ) {
push @out, $indentSpace x ( $indent + 1 ),
'<condition name="', $namespace . $condName, '">', "\n";
}
push @out, $indentSpace x $indent, '</action>', "\n";
return @out;
}
package WF::Validator;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
public args => my %validator_args;
public class => my %validator_class;
public params => my %validator_params;
sub new { register(shift) }
sub type { return 'validator' }
sub asXml {
my $self = shift;
my $indent = shift || 0;
my @out = ();
my $class = $self->class || 'Class Not Set';
if ( $self->text =~ /^I18N_/ ) {
return;
}
push @out, $indentSpace x $indent++;
push @out, '<validator name="', $self->fqname, '"', "\n";
push @out, $indentSpace x ( $indent + 1 ), 'class="', $class, '">', "\n";
my $params = $self->params;
foreach my $k ( keys %{$params} ) {
push @out, $indentSpace x ($indent), '<param name="', $k,
'" value="', $params->{$k}, '"/>', "\n";
}
$indent--;
push @out, $indentSpace x $indent;
push @out, '</validator>', "\n";
return @out;
}
sub asActionXml {
my $self = shift;
my $indent = shift || 0;
my @out = ();
push @out, $indentSpace x ( $indent + 0 ),
'<validator name="', $self->fqname, '"';
my $args = $self->args;
if ($args) {
push @out, '>', "\n";
foreach my $arg ( @{$args} ) {
push @out, $indentSpace x ( $indent + 1 ),
'<arg>', $arg, '</arg>', "\n";
}
push @out, $indentSpace x ( $indent + 0 ), '</validator>', "\n";
}
else {
push @out, '/>', "\n";
}
return @out;
}
package WF::Info;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
sub new { register(shift) }
sub type { return 'info' }
package WF::Goto;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
public page => my %goto_page;
public state => my %goto_state;
sub dump {
return join( ', ',
$_[0]->SUPER::dump, map { $_, $_[0]->$_ } qw( page state ) );
}
sub new { register(shift) }
sub type { return 'goto' }
sub children {
my $self = shift;
my @ret = ();
my $obj;
foreach $obj ( map { values %{$_} } values %{$objs} ) {
next unless $obj->type eq 'state';
if ( $obj->text eq $self->state ) {
push @ret, $obj;
last;
}
}
# if no state object was found, it's an error!
if ( not @ret ) {
die "ERROR: no state '", $self->state, "' found for goto object\n";
}
return @ret;
}
package WF::Line;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
public from => my %line_from;
public to => my %line_to;
sub dump {
my @ret = $_[0]->SUPER::dump;
push @ret, 'From object ' . $_[0]->from . ': ',
(
$objs->{ $_[0]->sheet }->{ $_[0]->from } ? map { "\t" . $_ }
$objs->{ $_[0]->sheet }->{ $_[0]->from }->dump
: '<unset>'
),
'To object ' . $_[0]->to . ': ',
(
$objs->{ $_[0]->sheet }->{ $_[0]->to } ? map { "\t" . $_ }
$objs->{ $_[0]->sheet }->{ $_[0]->to }->dump
: '<unset>'
);
return @ret;
}
sub new { register(shift) }
sub type { return 'line' }
package WF::LineLabel;
use Class::InsideOut qw( public readonly private register id );
use base 'WF::Shape';
public lineId => my %linelabel_lineId;
sub dump {
return
join( ', ', $_[0]->SUPER::dump, map { $_, $_[0]->$_ } qw( lineId ) );
}
sub new { register(shift) }
sub type { return 'label' }
package main;
my %link = ();
############################################################
############################################################
##
## Routines for parsing PList structure
##
############################################################
############################################################
sub parseTextVal {
my $s = shift;
# remove font/color tables
$s =~ s/\{\\(font|color)tbl.+?\}\s+//g;
# convert unicode line/paragraph separator to \n
$s =~ s/(\\uc0)?\\u8232/\n/g;
# remove RTF commands
$s =~ s/\\[^\\\s]+\s*//g;
# remove brackets at begin and end
$s =~ s/^\{//;
$s =~ s/\}$//;
# remove duplicate spaces
$s =~ s/\s\s/ /g;
# remove leading/trailing spaces
$s =~ s/^\s+//g;
$s =~ s/\s+$//g;
# replace single space with underscore
# $s =~ s/\s/_/g;
# remove wierd chars
$s =~ s/['\?]//g;
return $s;
}
sub parseGraphicsList {
my $graphicsList = shift;
# print "entered parseGraphicsList($graphicsList)\n";
foreach my $graphic ( @{$graphicsList} ) {
my $class;
if ( exists $graphic->value()->{Class} ) {
$class = $graphic->value()->{Class}->value();
}
if ( $class eq 'ShapedGraphic' ) {
parseShapedGraphic($graphic);
}
elsif ( $class eq 'LineGraphic' ) {
parseLineGraphic($graphic);
}
elsif ( $class eq 'TableGroup' ) {
parseTableGroup($graphic);
}
elsif ($showUnknown) {
print "WARN: unsupported graphics class '$class'\n";
print "\t\tID = ", $graphic->value()->{ID}->value(), "\n";
if ( exists $graphic->value()->{Text} ) {
my $text = _parseTextVal(
$graphic->value()->{Text}->value()->{Text}->value() );
print "\t\tText = ", $text, "\n";
}
}
}
}
sub parseShapedGraphic {
my $obj = shift;
my $id = $obj->{ID}->value();
my $shape = $obj->{Shape}->value();
my $text = '';
if ( exists $obj->{Text} and exists $obj->{Text}->value()->{Text} ) {
$text = parseTextVal( $obj->{Text}->value()->{Text}->value() );
}
my $name = $text;
$name =~ s/\s/_/g;
$objs->{$sheetnum} ||= {}; # ensure we have a separate dict for each sheet
if ( exists $objs->{$sheetnum}->{$id} ) {
warn "ERROR --- Whoa there, Cowboy!\n",
"just read following object: ShapedGraphic: id=$id, sheet=$sheetnum, shape=$shape, name='$name', text='$text'\n",
"but we already have that id: ", $objs->{$sheetnum}->{$id}->dump,
"\n",
"this can't be true!!!";
}
if ( $shape eq 'RoundRect' ) {
$objs->{$sheetnum}->{$id} = WF::State->new;
$objs->{$sheetnum}->{$id}->text($name);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->oid($id);
if ( exists $obj->{UserInfo} ) {
$objs->{$sheetnum}->{$id}
->userInfo( parseUserInfo( $obj->{UserInfo} ) );
}
}
elsif ( $shape eq 'Diamond' ) {
$name =~ s/\?$//g; # remove trailing '?'
$objs->{$sheetnum}->{$id} = WF::Condition->new;
$objs->{$sheetnum}->{$id}->text($name);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->oid($id);
if ( exists $obj->{UserInfo} ) {
my $userInfo = parseUserInfo( $obj->{UserInfo} );
if ( exists $userInfo->{class} ) {
$objs->{$sheetnum}->{$id}->class( $userInfo->{class} );
}
$objs->{$sheetnum}->{$id}->params(
{ map { $_, $userInfo->{$_} }
grep { $_ ne 'class' } keys %{$userInfo}
}
);
}
}
elsif ( $shape eq 'Rectangle' ) {
if ( exists $obj->{Line} ) {
# looks like the label of a line
$objs->{$sheetnum}->{$id} = WF::LineLabel->new;
$objs->{$sheetnum}->{$id}->text($text);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->oid($id);
$objs->{$sheetnum}->{$id}
->lineId( $obj->{Line}->value()->{ID}->value() );
$condLabelsByLineId->{$sheetnum}
->{ $obj->{Line}->value()->{ID}->value() } = $text;
}
else {
$objs->{$sheetnum}->{$id} = WF::Info->new;
$objs->{$sheetnum}->{$id}->text($text);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->oid($id);
}
}
elsif ( $shape eq 'House' ) {
my ( $page, $state ) = split( /:\s*/s, $text );
if ( defined $state ) {
$state =~ s/[\s]/_/g;
}
# if ($dest =~ /^[\S+[A
if ( defined $state ) {
$state =~ s/ \s/_/g;
$objs->{$sheetnum}->{$id} = WF::Goto->new;
$objs->{$sheetnum}->{$id}->text($text);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->oid($id);
$objs->{$sheetnum}->{$id}->page($page);
$objs->{$sheetnum}->{$id}->state($state);
}
}
elsif ( $shape eq 'ParallelLines' ) {
# ignore - from overview on main page
}
elsif (( $shape eq 'BevelledRectangle' )
or ( $shape eq 'FlattenedRectangle' ) )
{
my ( $name, $args ) = split( /\n/s, $text, 2 );
$name =~ s/\s/_/g;
$objs->{$sheetnum}->{$id} = WF::Validator->new;
$objs->{$sheetnum}->{$id}->text($name);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->oid($id);
$objs->{$sheetnum}->{$id}->args( [ split( /\s*, \s*/s, $args ) ] );
if ( exists $obj->{UserInfo} ) {
my $userInfo = parseUserInfo( $obj->{UserInfo} );
if ( exists $userInfo->{class} ) {
$objs->{$sheetnum}->{$id}->class( $userInfo->{class} );
}
$objs->{$sheetnum}->{$id}->params(
{ map { $_, $userInfo->{$_} }
grep { $_ ne 'class' } keys %{$userInfo}
}
);
}
}
else {
print
"parseShapedGrahic(): Unknown Object - ID=$id, Shape=$shape, text=$text\n";
return;
}
if ( $verbose and defined $objs->{$sheetnum}->{$id} ) {
warn "Parsed input ($shape): ",
$objs->{$sheetnum}->{$id}->dumpPretty( indent => 1 );
}
}
sub parseLineGraphic {
my $obj = shift;
my $id = $obj->{ID}->value();
my ( $head, $tail );
if ( not exists $obj->{Head} or not exists $obj->{Tail} ) {
# missing either head or tail (not sure which is worse ;-)
# In any case, this line isn't a connection between objects,
# so we can ignore it.
return;
}
my $headArrow
= $obj->{Style}->value()->{stroke}->value()->{HeadArrow}->value();
my $tailArrow
= $obj->{Style}->value()->{stroke}->value()->{TailArrow}->value();
$head = $obj->{Head}->value()->{ID}->value();
$tail = $obj->{Tail}->value()->{ID}->value();
if ( $headArrow and not $tailArrow ) {
$objs->{$sheetnum}->{$id} = WF::Line->new;
$objs->{$sheetnum}->{$id}->oid($id);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->from($tail);
$objs->{$sheetnum}->{$id}->to($head);
$connsByFromId->{$sheetnum}->{$tail} ||= [];
push @{ $connsByFromId->{$sheetnum}->{$tail} }, $id;
if ($verbose) {
warn "Parsed input (LineGraphic): ",
$objs->{$sheetnum}->{$id}->dumpPretty( indent => 1 );
}
}
elsif ( $headArrow and $tailArrow ) {
# appears to be a two-way connection, which is probably betwen
# two objects on the overview page and not an action/state/condition
return;
}
else {
print
"parseLineGraphic(): Unknown Line - ID=$id, head=$head/$headArrow, tail=$tail/$tailArrow\n";
}
}
sub parseTableGroup {
my $obj = shift;
my $id = $obj->{ID}->value();
my $i = 0;
my %cellMap = ();
my $userInfo;
my $notes;
if ( exists $obj->{GridV} ) {
# This looks like the table of parameters on the last page
return;
}
if ( exists $obj->{Notes} ) {
$notes = parseTextVal( $obj->{Notes}->value );
}
if ( exists $obj->{UserInfo} ) {
$userInfo = parseUserInfo( $obj->{UserInfo} );
}
foreach ( @{ $obj->{GridH}->value() } ) {
# there seems to be an erroneous array ref that we need to skip
if ( ref( $_->value() ) ) {
next;
}
$cellMap{ $_->value() } = $i++;
}
my @cells = ();
my $tableType = 'action'; # assume it's an action
foreach my $subobj ( @{ $obj->value()->{Graphics}->value() } ) {
if ( exists $subobj->{ImageID} and ( scalar keys %cellMap ) != 4 ) {
$tableType = 'info';
}
my $cellId = $subobj->{ID}->value();
my $cellText
= parseTextVal( $subobj->{Text}->value()->{Text}->value() );
if ( not exists $cellMap{$cellId} ) {
print "cellId not in CellMap: ", Dumper($obj), "\n";
}
else {
$cells[ $cellMap{$cellId} ] = $cellText;
}
}
if ( $tableType eq 'action' ) {
my $name = $cells[0];
$name =~ s/\s/_/g;
my $fields = {};
# split on comma, ignoring 'n/a'
foreach my $k ( grep { $_ ne 'n/a' } split( /\s*,\s* /, $cells[2] ) )
{
$fields->{$k} = 0;
}
foreach my $k ( grep { $_ ne 'n/a' } split( /\s*,\s*/, $cells[1] ) ) {
$fields->{$k} = 1;
}
$objs->{$sheetnum}->{$id} = WF::Action->new;
$objs->{$sheetnum}->{$id}->text($name);
$objs->{$sheetnum}->{$id}->sheet($sheetnum);
$objs->{$sheetnum}->{$id}->oid($id);
$objs->{$sheetnum}->{$id}->notes($notes);
$objs->{$sheetnum}->{$id}->userInfo($userInfo);
$objs->{$sheetnum}->{$id}->fields($fields);
if ($verbose) {
warn "Parsed input (TableGroup): ",
$objs->{$sheetnum}->{$id}->dumpPretty( indent => 1 );
}
}
else {
# warn "tableType = $tableType, id = $id, cells=", scalar keys %cellMap,
# " (", join( ', ', keys %cellMap ), ')';
}
}
sub parseUserInfo {
my $in = shift;
my $ret = {};
foreach my $k ( keys %{ $in->value } ) {
$ret->{$k} = $in->value->{$k}->value;
}
return $ret;
}
############################################################
############################################################
##
## MAIN
##
############################################################
############################################################
use Getopt::Long;
my ( $infile, $outfile, $outtype );
my $result = GetOptions(
"infile=s" => \$infile,
"outfile=s" => \$outfile,
"outtype=s" => \$outtype,
"verbose" => \$verbose,
"namespace=s" => \$namespace,
);
#my $file = $ARGV[0];
$infile ||= $ARGV[0];
if ( -d $infile ) {
$infile .= '/data.plist';
}
unless ( open FILE, $infile ) {
die("Could not open $infile");
}
my $data = do { local $/; <FILE> };
close FILE;
my $plist = Mac::PropertyList::parse_plist($data);
if ( $plist->{UserInfo} ) {
if ( exists $plist->{UserInfo}->value()->{kMDItemDescription} ) {
$descPrefix
= $plist->{UserInfo}->value()->{kMDItemDescription}->value();
}
if ( exists $plist->{UserInfo}->value()->{kMDItemVersion} ) {
$docVersion
= $plist->{UserInfo}->value()->{kMDItemVersion}->value();
}
if ( exists $plist->{UserInfo}->value()->{kMDItemSubject} ) {
$docSubject
= $plist->{UserInfo}->value()->{kMDItemSubject}->value();
}
if ( exists $plist->{UserInfo}->value()->{kMDItemKeywords} ) {
my $list = $plist->{UserInfo}->value()->{kMDItemKeywords}->value();
# warn "list=$list";
if ( ref($list) ) {
foreach my $entry ( @{ $list->value() } ) {
# warn "entry=$entry => '", $entry->value(), "'";
if ( $entry->value() =~ m/^namespace=(\S+)$/ ) {
$namespace = $1 . '_';
}
}
}
}
}
if ( exists $plist->{Sheets} ) {
# first, check whether we need to even parse this sheet
foreach my $sheet ( @{ $plist->{Sheets}->value() } ) {
my $parseflag = 1;
my $bg = $sheet->value()->{BackgroundGraphic};
if ( defined $bg ) {
my $ui = $bg->value()->{UserInfo};
if ( defined $ui ) {
my $is = $ui->value->{ignore_sheet};
if ( defined $ui->value->{ignore_sheet} ) {
my $val = $is->value;
if ( $val eq 'yes' ) {
# warn "Skipping sheet $sheetnum\n";
$parseflag = 0;
}
}
}
}
if ($parseflag) {
# warn "Processing sheet $sheetnum\n";
parseGraphicsList( $sheet->value()->{GraphicsList} );
}
$sheetnum++;
}
}
else {
parseGraphicsList( $plist->{GraphicsList} );
}
# quick prototype for gathering git info...
my $olddir = cwd();
my $gitdir = `dirname $infile`;
chomp($gitdir);
chdir($gitdir) || die "Error CD'ing to '$gitdir': $!";
my $gitinfo = `git rev-parse HEAD`;
chomp($gitinfo);
#warn "GITINFO: $gitinfo";
my $gitstatus;
my $git;
open($git, "git status --porcelain|");
if ( not $git ) {
die "Error running git: $!";
}
while (my $line = <$git>) {
my ($fstat, $fname) = ($line =~ m/^\s*(\S+)\s+(.+)$/);
if ( $fname eq $infile ) {
$gitstatus = $fstat;
last;
}
}
close $git;
#warn "GITSTATUS of '$infile': ", $gitstatus;
my %gitlabels = (
M => 'modified',
A => 'added',
D => 'deleted',
R => 'renamed',
C => 'copied',
U => 'updated but unmerged'
);
if ( $gitstatus ) {
$gitinfo .= ' (' . ($gitlabels{$gitstatus}||$gitstatus) . ')';
}
chdir($olddir) || die "Error CD'ing back to '$olddir': $!";
my $imprint
= "<!-- \n"
. ' Generated by: '
. $0 . ' '
. join( ', ', @ARGV ) . "\n\n"
. ' File: ' . $infile . "\n"
. ' Version: ' . $docVersion . "\n"
. ' Git: ' . $gitinfo . "\n"
. '-->' . "\n\n";
warn "\nGenerating XML output files...\n\n" if $verbose;
############################################################
# Generate state definitions
############################################################
if ( not $outtype or $outtype eq 'states' ) {
my %states = (); # avoid duplicates
my $defName = $outfile
|| 'workflow_def_' . lc($descPrefix) . '.xml';
open( DEF, ">$defName" ) or die "Error opening $defName: $!";
my $indent = 0;
print DEF $imprint, "\n";
print DEF $indentSpace x $indent, '<workflow>', "\n";
$indent++;
print DEF $indentSpace x $indent, '<type>',
$i18nPrefix, '_TYPE_', $descPrefix,
'</type>', "\n";
print DEF $indentSpace x $indent, '<description>',
$i18nPrefix, '_DESC_', $descPrefix,
'</description>', "\n";
print DEF $indentSpace x $indent,
'<persister>OpenXPKI</persister>',
"\n\n";
foreach my $state (
sort { $a->oid <=> $b->oid }
grep { $_->type eq 'state' }
map { values %{$_} } values %{$objs}
)
{
# warn "Processing child of ", $state->text, ":\n";
if ( $states{ $state->text }++ ) {
if ( $state->children ) {
# only complain about states that aren't end conditions
# (like SUCCESS or FAILURE)
warn "ERROR: state name is not unique in workflow: ",
$state->dump;
}
}
else {
print DEF $state->asXml($indent), "\n";
}
}
$indent--;
print DEF $indentSpace x $indent, '</workflow>', "\n";
close DEF;
}
############################################################
# Generate action definitions
############################################################
if ( not $outtype or $outtype eq 'actions' ) {
my %uniq = ();
my $defName = $outfile
|| 'workflow_activity_' . lc($descPrefix) . '.xml';
open( DEF, ">$defName" ) or die "Error opening $defName: $!";
my $indent = 0;
print DEF $imprint, "\n";
print DEF $indentSpace x $indent, '<actions>', "\n\n";
$indent++;
foreach my $rec (
sort { $a->oid <=> $b->oid }
grep { $_->type eq 'action' }
map { values %{$_} } values %{$objs}
)
{
if ( $uniq{ $rec->text } ) {
if ( not $rec->equals( $uniq{ $rec->text } ) ) {
die "ERROR: found multiple actions with name '",
$rec->text,
"' where definition not identical:\n",
"\tFirst rec: ", $uniq{ $rec->text }->dump, "\n",
"\tSecond rec: ", $rec->dump;
}
}
else {
$uniq{ $rec->text } = $rec;
print DEF $rec->asXml($indent), "\n";
}
}
foreach my $state (
sort { $a->oid <=> $b->oid }
grep { $_->type eq 'state' }
map { values %{$_} } values %{$objs}
)
{
$state->maxNull;
}
for ( my $i = 1; $i <= $maxNull; $i++ ) {
print DEF $indentSpace x $indent, '<action name="',
$namespace,
'null', $i,
'" class="Workflow::Action::Null"/>', "\n";
}
$indent--;
print DEF $indentSpace x $indent, '</actions>', "\n";
close DEF;
}
############################################################
# Generate condition definitions
############################################################
if ( not $outtype or $outtype eq 'conditions' ) {
my %uniq = ();
my $defName = $outfile
|| 'workflow_condition_' . lc($descPrefix) . '.xml';
open( DEF, ">$defName" ) or die "Error opening $defName: $!";
my $indent = 0;
print DEF $imprint, "\n";
print DEF $indentSpace x $indent, '<conditions>', "\n\n";
$indent++;
foreach my $rec (
sort { $a->oid <=> $b->oid }
grep { $_->type eq 'condition' }
map { values %{$_} } values %{$objs}
)
{
if ( $uniq{ $rec->text } ) {
if ( not $rec->equals( $uniq{ $rec->text } ) ) {
die "ERROR: found multiple actions with name '",
$rec->text,
"' where definition not identical:\n",
"\tFirst rec: ", $uniq{ $rec->text }->dump, "\n",
"\tSecond rec: ", $rec->dump;
}
}
else {
$uniq{ $rec->text } = $rec;
print DEF $rec->asXml($indent), "\n";
}
}
$indent--;
print DEF $indentSpace x $indent, '</conditions>', "\n";
close DEF;
}
############################################################
# Generate validator definitions
############################################################
if ( not $outtype or $outtype eq 'validators' ) {
my %uniq = ();
my $defName = $outfile
|| 'workflow_validator_' . lc($descPrefix) . '.xml';
open( DEF, ">$defName" ) or die "Error opening $defName: $!";
my $indent = 0;
print DEF $imprint, "\n";
print DEF $indentSpace x $indent, '<validators>', "\n\n";
$indent++;
foreach my $rec (
sort { $a->oid <=> $b->oid }
grep { $_->type eq 'validator' }
map { values %{$_} } values %{$objs}
)
{
if ( $uniq{ $rec->text }++ ) {
warn "ERROR: validator name is not unique in workflow: ",
$rec->dump;
}
print DEF $rec->asXml($indent), "\n";
}
$indent--;
print DEF $indentSpace x $indent, '</validators>', "\n";
close DEF;
}
| stefanomarty/openxpki | tools/scripts/ogflow.pl | Perl | apache-2.0 | 46,173 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 6.2.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
D7B0 D7FF
END
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/unicore/lib/Blk/JamoExtB.pl | Perl | mit | 433 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 8.0.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly. Use Unicode::UCD to access the Unicode character data
# base.
return <<'END';
V34
45
46
1418
1419
1470
1471
5120
5121
6150
6151
8208
8214
11799
11800
11802
11803
11834
11836
11840
11841
12316
12317
12336
12337
12448
12449
65073
65075
65112
65113
65123
65124
65293
65294
END
| operepo/ope | bin/usr/share/perl5/core_perl/unicore/lib/Gc/Pd.pl | Perl | mit | 678 |
#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG
# This is an automatically generated prolog.
#
# $Source: src/build/debug/Hostboot/Istep.pm $
#
# OpenPOWER HostBoot Project
#
# Contributors Listed Below - COPYRIGHT 2012,2017
# [+] International Business Machines Corp.
#
#
# 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.
#
# IBM_PROLOG_END_TAG
#
# Purpose: This perl script implements isteps on AWAN.
#
# Procedure:
# Call hb_Istep twice:
# 1) hb_Istep [--]istepmode
# called after loading but before starting HostBoot
# this will check to see if the user has set istep mode, if so
# it will write the Istep_mode signature to L3 memory to put
# HostBoot mode into single-step mode (spless).
# Then it will boot HostBoot until it is ready to receive commands.
# 2) hb_Istep [--]command
# Submit a istep/substep command for hostboot to run.
# Periodically call ::executeInstrCycles() to step through HostBoot.
# Checks for status from previous Isteps, and reports status.
#
# Author: Mark Wenning
#
# DEVELOPER NOTES:
# Do NOT put prints or printf's in this script!!!
# simics-debug-framework.pl and simics-debug-framework.py communicate
# (recvIPCmsg and sendIPCmsg) overstdin and stdout -
# if you print to STDOUT you will inadvertently send an empty/corrupted
# "IPC" message to python/simics which will usually cause ugly crashes.
#
#------------------------------------------------------------------------------
# Specify perl modules to use
#------------------------------------------------------------------------------
use strict;
use POSIX; # isdigit
## 64-bit input
use bigint;
no warnings 'portable';
## declare Istep package
package Hostboot::Istep;
use Exporter;
our @EXPORT_OK = ('main');
use File::Temp ('tempfile');
use Data::Dumper;
#------------------------------------------------------------------------------
# Constants
#------------------------------------------------------------------------------
## @todo extract these from splesscommon.H
use constant SPLESS_SINGLE_ISTEP_CMD => 0x00;
use constant SPLESS_RESUME_ISTEP_CMD => 0x01;
use constant SPLESS_CLEAR_TRACE_CMD => 0x02;
use constant MAX_ISTEPS => 256;
use constant MAX_SUBSTEPS => 25;
## Mailbox Scratchpad regs
use constant MBOX_SCRATCH1 => 0x00050038; ## conTrace addr
use constant MBOX_SCRATCH2 => 0x00050039; ## conTrace len
use constant MBOX_SCRATCH3 => 0x0005003a; ## Not used
use constant MBOX_SCRATCH4 => 0x0005003b; ## cmd reg
## extra parm for ::executeInstrCycles
use constant NOSHOW => 1;
#------------------------------------------------------------------------------
# Globals
#------------------------------------------------------------------------------
my $opt_debug = 0;
my $opt_splessmode = 0;
my $opt_command = 0;
my $opt_list = 0;
my $opt_resume = 0;
my $opt_clear_trace = 0;
my $attr_bin_file = "";
my $command = "";
my @inList;
my $THREAD = "0";
my $g_attr_fname = "";
my $g_attr_fh;
## --------------------------------------------------------------------------
## get any environment variables
## --------------------------------------------------------------------------
## @todo make this an enviroment var?
## NOTE: this is the # cycles used for simics, it is multiplied by 100
## in vpo-debug-framework.pl
my $hbDefaultCycles = 5000000;
my $hbCount = $ENV{'HB_COUNT'};
if ( !defined( $hbCount ) || ( $hbCount eq "" ) )
{
## set default
$hbCount = 0x2ff; ## default that should work for all env
}
## init global variables
my $ShutDownFlag = "";
my $ShutDownSts = "";
########################################################################
## MAIN ROUTINE, called from debug framework
########################################################################
sub main
{
## $packName is the name of the selected tool
## $args is a hashref to all the command-line arguments
my ($packName,$args) = @_;
## debug - save
while ( my ($k,$v) = each %$args )
{
::userDisplay "args: $k => $v\n";
}
::userDisplay "Welcome to hb-Istep 3.34 .\n";
::userDisplay "Note that in simics, multiple options must be in quotes,";
::userDisplay "separated by spaces\n\n";
## initialize inList to "undefined"
$inList[MAX_ISTEPS][MAX_SUBSTEPS] = ();
for( my $i = 0; $i < MAX_ISTEPS; $i++)
{
for(my $j = 0; $j < MAX_SUBSTEPS; $j++)
{
undef( $inList[$i][$j] );
}
}
## ---------------------------------------------------------------------------
## Fetch the symbols we need from syms file
## ---------------------------------------------------------------------------
$ShutDownFlag = getSymbol( "CpuManager::cv_shutdown_requested" );
$ShutDownSts = getSymbol( "CpuManager::cv_shutdown_status" );
## fetch the istep list
get_istep_list();
## debug, dump all the environment vars that we are interested in
## dumpEnvVar( "HB_TOOLS" );
## dumpEnvVar( "HB_IMGDIR" );
## dumpEnvVar( "HB_VBUTOOLS" );
## dumpEnvVar( "HB_COUNT" );
##--------------------------------------------------------------------------
## Start processing options
## process the "flag" standard options, then use a loop to go through
## the rest
##--------------------------------------------------------------------------
## Get all the command line options in an array
my @options = ( keys %$args );
## ::userDisplay join( ' ', @options );
if ( !(@options) )
{
::userDisplay "type \"help hb-istep\" for help\n";
exit;
}
##
## find all the standard options, set their flag, and remove them from
## the options list.
## vpo and simics use different command-line styles:
## simics wants you to say " hb-istep "debug s4" ",
## (note that multiple options must be in quotes, separated by spaces)
## and vpo wants you to say "hb-istep --debug --command s4" .
## This should accept both styles.
##
for ( my $i=0; $i <= $#options; $i++ )
{
$_ = $options[$i];
## ::userDisplay ".$_.";
if ( m/^\-{0,2}help$/ )
{
showHelp();
exit
}
if ( m/^\-{0,2}debug$/ )
{
$opt_debug = 1;
$options[$i] = "";
}
if ( m/^\-{0,2}list$/ )
{
$opt_list = 1;
$options[$i] = "";
}
if ( m/^\-{0,2}splessmode$/ )
{
$opt_splessmode = 1;
$options[$i] = "";
}
if ( m/^\-{0,2}command$/ )
{
## doesn't do much, just eats the option
$opt_command = 1;
$options[$i] = "";
}
if ( m/^\-{0,2}resume$/ )
{
$opt_resume = 1;
$options[$i] = "";
}
if ( m/^\-{0,2}clear-trace$/ )
{
$opt_clear_trace = 1;
$options[$i] = "";
}
if ( m/^\-{0,2}attr_bin$/ )
{
$attr_bin_file = $args->{"attr_bin"};
$options[$i] = "";
}
} ## endfor
## if there's anything left after this, assume it is a single command
$command = join( "", @options );
chomp $command;
## print out debug info
if ( $opt_debug )
{
::userDisplay "\n----- DEBUG: ------------------------------- \n";
::userDisplay "debug = $opt_debug\n";
::userDisplay "list = $opt_list\n";
::userDisplay "splessmode = $opt_splessmode\n";
::userDisplay "resume = $opt_resume\n";
::userDisplay "clear-trace = $opt_clear_trace\n";
::userDisplay "command flag = $opt_command\n";
::userDisplay "command = \"$command\"\n";
::userDisplay "ShutDownFlag = ", sprintf("0x%x",$ShutDownFlag), "\n";
::userDisplay "ShutDownSts = ", sprintf("0x%x",$ShutDownSts), "\n";
::userDisplay "hbCount = ", sprintf("0x%x",$hbCount), "\n";
::userDisplay "\n";
}
if ( $opt_debug ) { ::userDisplay "=== check ShutDown Status...\n"; }
if ( isShutDown() )
{
::userDisplay "Shutdown detected: cannot run HostBoot.\n";
exit;
}
## ----------------------------------------------------------------
## finally, run some commands.
## ----------------------------------------------------------------
if ( $opt_list )
{
::userDisplay "List isteps\n";
print_istep_list();
exit;
}
if ( $opt_splessmode )
{
::userDisplay "ENable splessmode\n";
setMode( "spless" );
::userDisplay "Done.\n";
exit;
}
## don't do any other commands unless ready bit is on.
if ( ! isReadyBitOn() )
{
::userDisplay "Ready bit is off, must run splessmode first.\n";
exit 1;
}
if ( $opt_clear_trace )
{
::userDisplay "Clear Trace\n";
clear_trace();
exit;
}
if ( $opt_resume )
{
::userDisplay "Resume\n";
resume_istep();
exit;
}
if ( $opt_command || ( $command ne "" ) )
{
::userDisplay "Process command \"$command\"\n";
process_command( $command );
exit;
}
::userDisplay "Done.\n";
exit 0;
} ## end main
########################################################################
## SUBROUTINES
########################################################################
##
sub helpInfo
{
my %info = (
name => "Istep",
intro => ["Executes isteps."],
options => { "list" => [" list out all supported isteps "],
"splessmode" => ["enable istep mode"],
"resume" => ["resume an istep that is at a break point"],
"clear-trace" => ["clear trace buffers before starting"],
"sN" => ["run istep N"],
"sN..M" => ["run isteps N through M"],
"<foo>" => ["run named istep \"foo\""],
"<foo>..<bar>" => ["run named isteps \"foo\" through \"bar\""],
}
);
}
sub showHelp
{
::userDisplay "Executes isteps.\n";
::userDisplay "Options =>\n";
::userDisplay " list => list out all supported isteps\n";
::userDisplay " resume => resume an istep at a break point\n";
::userDisplay " clear-trace => clear trace buffers before starting\n";
::userDisplay " sN => run istep N\n";
::userDisplay " sN..M => run isteps N through M\n";
::userDisplay " <foo> => run named istep \"foo\"\n";
::userDisplay " <foo>..<bar> => run isteps \"foo\" through \"bar\"\n";
exit 0;
}
## ---------------------------------------------------------------------------
## Check to see if there are debug bufs avail avail
## if so, extract type and call correct subroutine to handle
## ---------------------------------------------------------------------------
sub checkDebugBuf
{
my $SCRATCH_MBOX1 = 0x00050038;
my $SCRATCH_MBOX2 = 0x00050039;
my $MSG_TYPE_MASK = 0xFF00000000000000;
my $MSG_TYPE_TRACE = 0x0000000000000000;
my $MSG_TYPE_ATTR = 0x0100000000000000;
my $MSG_TYPE_SET_ATTR = 0x0200000000000000;
my $dbgAddr = "";
my $dbgSize = "";
$dbgAddr = ::readScom( $SCRATCH_MBOX1, 8 );
if ( $dbgAddr != 0 )
{
#There is something to do. Get the dbgSize to determine the type
$dbgSize = ::readScom( $SCRATCH_MBOX2, 8 );
#contTrace has the buffer, address MBOX_SCRATCH2 has size
#MBOX Scratch regs are only valid from 0:31, shift to give a num
my $buffAddr = $dbgAddr >> 32;
my $buffSize = ($dbgSize & (~$MSG_TYPE_MASK)) >> 32;
my $msgType = $dbgSize & $MSG_TYPE_MASK;
#::userDisplay ".";
#::userDisplay "DebugBuf addr[", sprintf("0x%x", $buffAddr),
# "] type[", sprintf("0x%x", $msgType),
# "] size[" , sprintf("0x%x",$buffSize), "]\n";
if ($msgType == $MSG_TYPE_TRACE)
{
handleContTrace($buffAddr, $buffSize);
}
elsif ($msgType == $MSG_TYPE_ATTR)
{
handleAttrDump($buffAddr, $buffSize);
}
elsif ($msgType == $MSG_TYPE_SET_ATTR)
{
handleAttrOverride($buffAddr, $buffSize);
}
#Write 0 to let HB know we extracted buf and it can continue
::writeScom($SCRATCH_MBOX1, 8, 0x0);
}
}
## ---------------------------------------------------------------------------
## Check to see if there are trace buffers avail
## if so, extract and write them out
## ---------------------------------------------------------------------------
sub handleContTrace
{
my $buffAddr = shift;
my $buffSize = shift;
my $ctName = "tracMERG.cont";
my $fh;
my $fname;
my $contFile;
($fh,$fname) = tempfile();
open ($contFile, '>>', $ctName) or die "Can't open '$ctName' $!";
binmode($fh);
print $fh (::readData($buffAddr, $buffSize));
open TRACE, ("fsp-trace -s ".::getImgPath().
"hbotStringFile $fname |") || die;
while (my $line = <TRACE>)
{
::userDisplay $line;
print $contFile $line;
}
unlink $fname;
}
## ---------------------------------------------------------------------------
## Extract an ATTR dump bin, when complete, call tool to parse.
## ---------------------------------------------------------------------------
sub handleAttrDump
{
my $buffAddr = shift;
my $buffSize = shift;
my $txtName = "hbAttrDump.txt";
#If there is an empty filename, need to create one, otherwise just append
if ($g_attr_fname eq "")
{
($g_attr_fh,$g_attr_fname) = tempfile();
binmode($g_attr_fh);
}
# Check to see if magic "done" address has been sent,
# if so call tool to parse
if ($buffAddr == 0xFFFFCAFE)
{
#::userDisplay "Got done, processing bin file[$g_attr_fname]\n";
close $g_attr_fh ;
##Call the FapiAttr tool module
$Hostboot::_DebugFramework::toolOpts{'attrbin'} = $g_attr_fname;
::callToolModule("FapiAttr");
unlink $g_attr_fname;
$g_attr_fname = "";
}
else # Write data to bin temp file
{
print $g_attr_fh (::readData($buffAddr, $buffSize));
}
}
## ---------------------------------------------------------------------------
## Push an ATTR override bin to memory
## ---------------------------------------------------------------------------
sub handleAttrOverride
{
my $buffAddr = shift;
my $buffSize = shift;
#Check to see if attr.bin file set
if ($attr_bin_file eq "")
{
::userDisplay "\nATTR BIN File not set,
use [--tool-options='attr_bin=<file> set_attr_overrides']\n";
exit 1;
}
#Open the file, get the size
my $attrBinFile;
open ($attrBinFile, '<', $attr_bin_file) or
die "Can't open '$attr_bin_file' $!";
my $size = -s $attr_bin_file;
#Check that file size is less than HB allocated size
if ($size > $buffSize)
{
::userDisplay "BIN file [$attr_bin_file] too big, $size vs $buffSize";
exit 1;
}
#Read in file data and actually write to mem
my $contents;
read($attrBinFile,$contents,$size);
::writeData($buffAddr, $size, $contents);
close $attrBinFile ;
}
## ---------------------------------------------------------------------------
## Dump environment variable specified.
## ---------------------------------------------------------------------------
sub dumpEnvVar( $ )
{
my $envvar = shift;
if ( defined( $ENV{$envvar} ) )
{
::userDisplay "$envvar = $ENV{$envvar}\n";
}
}
##
## Get symbol address from hbotSymsFile
##
sub getSymbol( )
{
my $symbol = shift;
my ($symAddr, $symSize) = ::findSymbolAddress( $symbol ) ;
if ( not defined( $symAddr ) )
{
::userDisplay "Cannot find $symbol.\n"; die;
}
return $symAddr;
}
##
## read in file with csv istep list and store in inList
##
sub get_istep_list()
{
my $istep, my $substep, my $name ;
my @isteplist = ::getIstepList();
## DEBUG: Comment in to test invalid minor and invalid major isteps
## $inList[7][8] = "invalid_minor";
## $inList[0][17] = "invalid_major";
foreach( @isteplist )
{
chomp;
( $istep, $substep, $name) = split( ",", $_ );
chomp $name;
## ::userDisplay "$_, $istep, $substep, $name\n" ;
if ( defined($name) && ( $name ne "" ) )
{
$inList[$istep][$substep] = $name;
}
}
}
##
## print the istep list to the screen.
##
sub print_istep_list( )
{
my $hdrflag = 1;
## ::userDisplay " IStep Name\n";
##::userDisplay "---------------------------------------------------\n";
for( my $i = 4; $i < MAX_ISTEPS; $i++)
{
for( my $j = 0; $j < MAX_SUBSTEPS; $j++)
{
## print all substeps
if ( defined( $inList[$i][$j] ) )
{
if ( $hdrflag )
{
::userDisplay " ----- IStep $i ----- \n";
$hdrflag = 0;
}
## will truncate after 40 chars, hopefully this will not be an issue
my $ss = sprintf( "%-40s", $inList[$i][$j] );
::userDisplay "$i.$j: $ss\n" ;
}
} ## end for $j
$hdrflag=1;
} ## end for $i
}
##
## Find istep name in inList array.
##
## @param[in] - name
##
## @return - istep #, substep #, found flag = true for success
## false for not found
##
sub find_in_inList( $ )
{
my ( $substepname ) = @_;
for(my $i = 0; $i < MAX_ISTEPS; $i++)
{
for(my $j = 0; $j < MAX_SUBSTEPS; $j++)
{
if ( defined($inList[$i][$j]) && ($inList[$i][$j] eq $substepname ) )
{
return ($i, $j, 1 );
}
}
}
return ( MAX_ISTEPS, MAX_SUBSTEPS, 0 )
}
##
## When HostBoot goes into singlestep mode, it turns on the ready bit in the
## status reg.
##
## @return nonzero if ready bit is on, else 0
##
sub isReadyBitOn()
{
my $result = 0;
my $readybit = 0;
$result = getStatus( );
$readybit = ( ( $result & 0x8000000000000000 ) >> 63 );
if ( $opt_debug ) { ::userDisplay "=== readybit: $readybit\n"; }
if ( $readybit )
{
return 1;
}
return 0;
}
##
## Check if HostBoot has already run and shutdown.
##
## @return nonzero if it has, 0 otherwise
##
sub isShutDown()
{
my $flag = ::read64( $ShutDownFlag );
my $status = ::read64( $ShutDownSts );
if ( $opt_debug )
{
::userDisplay "=== isShutDown : Shutdown Flag = $flag\n";
::userDisplay "=== isShutDown : Shutdown Status = ",
sprintf( "0x%x", $status), "\n";
}
if ( $flag )
{
::userDisplay "HostBoot has shut down with status ",
sprintf( "0x%x", $status), ".\n";
return 1;
}
return 0;
}
## --------------------------------------------------------------------
## Write command reg
##
## @param[in] - HEX STRING containing the 64-bit command word
##
## @return none
##
## --------------------------------------------------------------------
sub sendCommand( $ )
{
my $data = shift;
my $read_bindata;
if ( $opt_debug )
{ ::userDisplay "=== sendCommand( $data )\n"; }
## because of the way the SIO regs work on the BMC,
## Hostboot expects a key to be set to trigger the command
## when doing via scom we simply need to read, modify write
## the reg
$read_bindata = ::readScom( MBOX_SCRATCH4, 8 );
my $key = (($read_bindata) & 0x1F00000000000000);
## convert to binary before sending to writescom
my $bindata = ( hex $data );
## Or in key
my $bindata = (($bindata) & 0xE0FFFFFFFFFFFFFF);
$bindata = (($bindata) | ($key));
## now write the data
::writeScom( MBOX_SCRATCH4, 8, $bindata );
if ( $opt_debug )
{
## sanity check
::executeInstrCycles( 10, NOSHOW );
my $readback = ::readScom( MBOX_SCRATCH4, 8 );
::userDisplay "=== sendCommand readback: $readback\n";
}
}
## --------------------------------------------------------------------
## read status reg
##
## Note - mbox scratchpad regs are only 32 bits, so HostBoot will return
## status in mbox 2 (hi32 bits) and mbox 1 (lo32 bits).
## mbox 0 is reserved for continuous trace.
##
##
##
## @return binary 64-bit value
## --------------------------------------------------------------------
sub getStatus()
{
my $status = 0;
my $statusHi = "";
my $statusLo = "";
$statusHi = ::readScom( MBOX_SCRATCH4, 8 );
if ( $opt_debug ) { ::userDisplay "=== statusHi: $statusHi \n"; }
$statusLo = 0;
$status = ( ( $statusHi) & 0xffffffff00000000 );
if ( $opt_debug )
{
::userDisplay "=== getStatus() returned ", (sprintf( "0x%lx", $status ) ), "\n";
}
return $status;
}
##
## keep trying to get status until readybit turns back on
##
sub getSyncStatus( )
{
# set # of retries
my $count = $hbCount ;
my $result = 0;
my $running = 0;
my $ready = 0;
## get response
while(1)
{
## advance HostBoot code by a certain # of cycles, then check the
## sequence number to see if it has changed. rinse and repeat.
::executeInstrCycles( $hbDefaultCycles, NOSHOW );
## check to see if we need to dump trace - no-op in simics
checkDebugBuf();
$result = getStatus();
$running = ( ( $result & 0x2000000000000000 ) >> 61 );
$ready = ( ( $result & 0x8000000000000000 ) >> 63 );
## @todo great place to add some debug, check running bit BEFORE
## starting the clock (should be off), then run (relatively) small
## number of clocks till the bit turns on.
## Wait for the readybit to turn back on
if ( $ready )
{
return $result;
}
if ( $count <= 0)
{
::userDisplay "TIMEOUT waiting for readyBit to assert again\n";
return -1;
}
$count--;
} ## endwhile
}
##
## Run an istep
##
sub runIStep( $$ )
{
my ( $istep, $substep) = @_;
my $byte0, my $command;
my $cmd;
my $result;
::userDisplay "run $istep.$substep $inList[$istep][$substep]:\n" ;
$byte0 = 0x40; ## gobit
$command = SPLESS_SINGLE_ISTEP_CMD;
$cmd = sprintf( "0x%2.2x%2.2x%2.2x%2.2x00000000", $byte0, $command, $istep, $substep );
sendCommand( $cmd );
$result = getSyncStatus();
## if result is -1 we have a timeout
if ( $result == -1 )
{
::userDisplay "-----------------------------------------------------------------\n";
exit 1;
}
else
{
my $taskStatus = ( ( $result & 0x00FF000000000000 ) >> 48 );
my $stsIStep = ( ( $result & 0x0000ff0000000000 ) >> 40 );
my $stsSubstep = ( ( $result & 0x000000ff00000000 ) >> 32 );
::userDisplay "---------------------------------\n";
if ( $taskStatus != 0 )
{
::userDisplay "Istep $stsIStep.$stsSubstep FAILED , task status is $taskStatus, check error logs\n" ;
exit 1;
}
else
{
::userDisplay "Istep $stsIStep.$stsSubstep $inList[$istep][$substep] returned Status: ",
sprintf("%x",$taskStatus),
"\n" ;
if ( $taskStatus == 0xa )
{
::userDisplay ": not implemented yet.\n";
}
elsif ( $taskStatus != 0 )
{
exit 1;
}
}
}
}
##
## run command = "sN"
##
sub sCommand( $ )
{
my ( $scommand ) = @_;
my $i = $scommand;
my $j = 0;
# execute all the substeps in the IStep
for( $j=0; $j<MAX_SUBSTEPS; $j++ )
{
if ( defined( $inList[$i][$j] ) )
{
runIStep( $i, $j );
}
}
}
##
## parse --command [command] option and execute it.
##
sub process_command( $ )
{
my ( $command ) = @_;
my @execlist;
my $istepM, my $substepM, my $foundit, my $istepN, my $substepN;
my $M, my $N, my $scommand;
my @ss_list;
## check to see if we have an 's' command (string starts with 's' and a number)
chomp( $command);
if ( $command =~ m/^s+[0-9].*/ )
{
## run "s" command
if ($opt_debug) { ::userDisplay "=== s command \"$command\" \n"; }
substr( $command, 0, 1, "" );
if ( POSIX::isdigit($command) )
{
# command = "sN"
if ($opt_debug) { ::userDisplay "=== single IStep: ", $command, "\n"; }
sCommand( $command );
}
else
{
# list of substeps = "sM..N"
( $M, $N ) = split( /\.\./, $command );
if ($opt_debug) { ::userDisplay "=== multiple ISteps: ", $M, "-", $N, "\n"; }
for ( my $x=$M; $x<$N+1; $x++ )
{
sCommand( $x );
}
}
}
else
{
## <substep name>, or <substep name>..<substep name>
@ss_list = split( /\.\./, $command );
if ($opt_debug) { ::userDisplay "=== named commands : ", @ss_list, "\n"; }
( $istepM, $substepM, $foundit) = find_in_inList( $ss_list[0] );
$istepN = $istepM;
$substepN = $substepM;
if ( ! $foundit )
{
::userDisplay "Invalid substep ", $ss_list[0], "\n" ;
return -1;
}
if ( $#ss_list > 0 )
{
( $istepN, $substepN, $foundit) = find_in_inList( $ss_list[1] );
if ( ! $foundit )
{
::userDisplay "Invalid substep $ss_list[1] \n" ;
return -1;
}
}
for(my $x=$istepM; $x<=$istepN; $x++)
{
if ($istepM == $istepN)
{
# First and Last Steps are the same.
# Run all requested substeps between the same step
for(my $y=$substepM; $y<=$substepN; $y++)
{
if (defined($inList[$x][$y]))
{
runIStep($x, $y);
}
}
}
elsif ($x == $istepM)
{
# First requested Step, run from requested substep
for(my $y=$substepM; $y<MAX_SUBSTEPS; $y++)
{
if (defined($inList[$x][$y]))
{
runIStep($x, $y);
}
}
}
elsif ($x == $istepN)
{
# Last requested Step, run up to requested substep
for(my $y=0; $y<=$substepN; $y++)
{
if (defined($inList[$x][$y]))
{
runIStep($x, $y);
}
}
}
else
{
# Middle istep, run all substeps
for(my $y=0; $y<MAX_SUBSTEPS; $y++)
{
if (defined($inList[$x][$y]))
{
runIStep($x, $y);
}
}
}
}
}
}
##
## write to mem to set istep or normal mode, check return status
##
## Note that this only happens once at the beginning, when "splessmode"
## is run.
##
sub setMode( $ )
{
my ( $cmd ) = @_;
my $count = 0;
my $readybit = 0;
my $result = 0;
if ( $cmd eq "spless" )
{
::userDisplay "This command doesn't force HB into SPLESS mode anymore\n";
::userDisplay "It only establish SPLESS communication (clocks model in sim)\n";
::userDisplay "Use attributes to enter SPLESS mode\n";
::userDisplay "\tSP_FUNCTIONS:mailboxEnabled = 0b0\n";
::userDisplay "\tISTEP_MODE = 0x1\n";
::userDisplay "\n WAITING for readybit to come on";
}
else
{
::userDisplay "invalid setMode command: $cmd\n" ;
return -1;
}
## Loop, advancing clock, and wait for readybit
$count = $hbCount ;
while(1)
{
if ( $opt_debug ) { ::userDisplay "=== executeInstrCycles( $hbDefaultCycles )\n"; }
## advance HostBoot code by a certain # of cycles, then check the
## sequence number to see if it has changed. rinse and repeat.
::executeInstrCycles( $hbDefaultCycles, NOSHOW );
if ( $opt_debug ) { ::userDisplay "=== checkDebugBuf\n"; }
## check to see if it's time to dump trace - no-op in simics
checkDebugBuf();
if ( $opt_debug ) { ::userDisplay "=== isShutDown\n"; }
## check for system crash
if ( isShutDown( ) )
{
::userDisplay "Shutdown detected: cannot run HostBoot.\n";
return -1;
}
if ( $opt_debug ) { ::userDisplay "=== isReadyBitOn\n"; }
if ( isReadyBitOn() )
{
::userDisplay "READY!\n";
return 0;
}
else
{
::userDisplay ".";
}
if ( $count <= 0 )
{
::userDisplay "TIMEOUT waiting for readybit, status=$result\n" ;
return -1;
}
$count--;
if ( $opt_debug ) { ::userDisplay "=== count = $count\n"; }
}
}
sub resume_istep()
{
my $byte0;
my $command;
my $cmd;
my $result;
::userDisplay "resume istep\n";
$byte0 = 0x40 ; ## gobit
$command = SPLESS_RESUME_ISTEP_CMD;
$cmd = sprintf( "0x%2.2x%2.2x000000000000", $byte0, $command );
sendCommand( $cmd );
$result = getSyncStatus();
## if result is -1 we have a timeout
if ( $result == -1 )
{
::userDisplay "-----------------------------------------------------------------\n";
}
else
{
my $taskStatus = ( ( $result & 0x00FF000000000000 ) >> 48 );
::userDisplay "-----------------------------------------------------------------\n";
if ( $taskStatus != 0 )
{
# This probably means istep was not at a breakpoint.
::userDisplay "resume istep FAILED, task status is $taskStatus\n", $taskStatus ;
}
else
{
::userDisplay "resume istep returned success\n" ;
}
::userDisplay "-----------------------------------------------------------------\n";
}
}
sub clear_trace( )
{
my $byte0, my $command;
my $cmd;
my $result;
$byte0 = 0x40; ## gobit
$command = SPLESS_CLEAR_TRACE_CMD;
$cmd = sprintf( "0x%2.2x%2.2x%2.2x%2.2x00000000", $byte0, $command, 0, 0 );
sendCommand( $cmd );
$result = getSyncStatus();
## if result is -1 we have a timeout
if ( $result == -1 )
{
::userDisplay "-----------------------------------------------------------------\n";
}
else
{
my $taskStatus = ( ( $result & 0x00FF000000000000 ) >> 48 );
::userDisplay "-----------------------------------------------------------------\n";
if ( $taskStatus != 0 )
{
::userDisplay "Clear Trace FAILED, task status is taskStatus\n" ;
}
else
{
::userDisplay "Clear Trace returned Status: $taskStatus\n" ;
}
::userDisplay "-----------------------------------------------------------------\n";
}
}
# A Perl module must end with a true value or else it is considered not to
# have loaded. By convention this value is usually 1 though it can be
# any true value. A module can end with false to indicate failure but
# this is rarely used and it would instead die() (exit with an error).
1;
__END__
| Over-enthusiastic/hostboot | src/build/debug/Hostboot/Istep.pm | Perl | apache-2.0 | 33,905 |
#-----------------------------------------------------------
# removdev.pl
# Parse Microsoft\Windows Portable Devices\Devices key on Vista
# Get historical information about drive letter assigned to devices
#
# Change history
# 20090118 [hca] * changed the name of the plugin from "removdev"
# 20110830 [fpi] + banner, no change to the version number
#
# References
#
# NOTE: Credit for "discovery" goes to Rob Lee
#
# copyright 2008 H. Carvey, keydet89@yahoo.com
#-----------------------------------------------------------
package removdev;
use strict;
my %config = (hive => "Software",
osmask => 192,
hasShortDescr => 1,
hasDescr => 0,
hasRefs => 0,
version => 200800611);
sub getConfig{return %config}
sub getShortDescr {
return "Parses Windows Portable Devices key (Vista)";
}
sub getDescr{}
sub getRefs {}
sub getHive {return $config{hive};}
sub getVersion {return $config{version};}
my $VERSION = getVersion();
sub pluginmain {
my $class = shift;
my $hive = shift;
::logMsg("Launching removdev v.".$VERSION);
::rptMsg("removdev v.".$VERSION); # 20110830 [fpi] + banner
::rptMsg("(".getHive().") ".getShortDescr()."\n"); # 20110830 [fpi] + banner
my $reg = Parse::Win32Registry->new($hive);
my $root_key = $reg->get_root_key;
my $key_path = "Microsoft\\Windows Portable Devices\\Devices";
my $key;
if ($key = $root_key->get_subkey($key_path)) {
::rptMsg("RemovDev");
::rptMsg($key_path);
::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)");
::rptMsg("");
my @subkeys = $key->get_list_of_subkeys();
if (scalar(@subkeys) > 0) {
foreach my $s (@subkeys) {
my $name = $s->get_name();
my $lastwrite = $s->get_timestamp();
my $letter;
eval {
$letter = $s->get_value("FriendlyName")->get_data();
};
::rptMsg($name." key error: $@") if ($@);
my $half;
if (grep(/##/,$name)) {
$half = (split(/##/,$name))[1];
}
if (grep(/\?\?/,$name)) {
$half = (split(/\?\?/,$name))[1];
}
my ($dev,$sn) = (split(/#/,$half))[1,2];
::rptMsg("Device : ".$dev);
::rptMsg("LastWrite : ".gmtime($lastwrite)." (UTC)");
::rptMsg("SN : ".$sn);
::rptMsg("Drive : ".$letter);
::rptMsg("");
}
}
else {
::rptMsg($key_path." has no subkeys.");
}
}
else {
::rptMsg($key_path." not found.");
::logMsg($key_path." not found.");
}
}
1; | APriestman/autopsy | thirdparty/rr-full/plugins/removdev.pl | Perl | apache-2.0 | 2,520 |
package Maximus::FormField::AlNum;
use namespace::autoclean;
use HTML::FormHandler::Moose;
extends 'HTML::FormHandler::Field::Text';
apply [
{ check => sub { shift !~ /[^a-z0-9]/i },
message => 'Only alphanumerical values are accepted'
}
];
__PACKAGE__->meta->make_immutable;
=head1 NAME
Maximus::FormField::AlNum - Alpha-Numerical field
=head1 DESCRIPTION
This module provides a Alpha-Numerical field to a L<HTML::FormHandler> form.
=head1 AUTHOR
Christiaan Kras
=head1 LICENSE
Copyright (c) 2010-2013 Christiaan Kras
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.
=cut
1;
| maximos/maximus-web | lib/Maximus/FormField/AlNum.pm | Perl | mit | 1,581 |
use Dancer2;
# at first
get '/about' => sub { template 'about' };
get '/admin' => sub { template 'admin' };
# then
get '/:page' => sub { template param('page') };
# lastly
get '/:page/:inner' => sub {
template param('page') . '/' . param('inner');
};
# or simply...
set autopage => 1;
# or in config.yml:
# autopage: 1
1;
| xsawyerx/dancer-training-notes | 08-handlers/01-without-autopage.pl | Perl | mit | 332 |
# Data API for Assembly entities. This API provides methods for retrieving
# summary information such as GC content, total length, external source information
# as well as methods for retrieving individual contig sequences and gathering contig lengths and contig GC.
require 5.6.0;
use strict;
use warnings;
use Thrift;
use Thrift::BinaryProtocol;
use Thrift::HttpClient;
use Thrift::BufferedTransport;
use DOEKBase::DataAPI::sequence::assembly::thrift_service;
use DOEKBase::DataAPI::sequence::assembly::Types;
package DOEKBase::DataAPI::sequence::assembly::ClientAPI;
use Try::Tiny;
use Carp;
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
foreach my $arg ('url','token','ref')
{
confess "Need to provide a $arg" unless $vals->{$arg};
}
my $transport = new Thrift::HttpClient($vals->{'url'});
# the default timeout is too short
$transport->setSendTimeout(30000);
my $protocol = new Thrift::BinaryProtocol($transport);
my $client = new DOEKBase::DataAPI::sequence::assembly::thrift_serviceClient($protocol);
$transport->open();
$self->{'client'} = $client;
$self->{'token'} = $vals->{'token'};
$self->{'ref'} = $vals->{'ref'};
return bless($self,$classname);
}
sub get_assembly_id {
my $self=shift;
my $result = try {
$self->{'client'}->get_assembly_id($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_genome_annotations {
my $self=shift;
my $result = try {
$self->{'client'}->get_genome_annotations($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_external_source_info {
my $self=shift;
my $result = try {
$self->{'client'}->get_external_source_info($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_stats {
my $self=shift;
my $result = try {
$self->{'client'}->get_stats($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_number_contigs {
my $self=shift;
my $result = try {
$self->{'client'}->get_number_contigs($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_gc_content {
my $self=shift;
my $result = try {
$self->{'client'}->get_gc_content($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_dna_size {
my $self=shift;
my $result = try {
$self->{'client'}->get_dna_size($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_contig_ids {
my $self=shift;
my $result = try {
$self->{'client'}->get_contig_ids($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_contig_lengths {
my $self=shift;
my $result = try {
$self->{'client'}->get_contig_lengths($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_contig_gc_content {
my $self=shift;
my $result = try {
$self->{'client'}->get_contig_gc_content($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
sub get_contigs {
my $self=shift;
my $result = try {
$self->{'client'}->get_contigs($self->{'token'},$self->{'ref'});
} catch {
confess 'Exception thrown: code ' . $_->{'code'} . ' message ' . $_->{'message'};
};
return $result;
}
1;
| kbase/data_api_perl_clients | lib/DOEKBase/DataAPI/sequence/assembly/ClientAPI.pm | Perl | mit | 4,141 |
/* Part of JPL -- SWI-Prolog/Java interface
Author: Paul Singleton, Fred Dushin and Jan Wielemaker
E-mail: paul@jbgb.com
WWW: http://www.swi-prolog.org
Copyright (c) 2004-2020, Paul Singleton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(jpl,
[ jpl_get_default_jvm_opts/1,
jpl_set_default_jvm_opts/1,
jpl_get_actual_jvm_opts/1,
jpl_pl_lib_version/1,
jpl_c_lib_version/1,
jpl_pl_syntax/1,
jpl_new/3,
jpl_call/4,
jpl_get/3,
jpl_set/3,
jpl_servlet_byref/3,
jpl_servlet_byval/3,
jpl_class_to_classname/2,
jpl_class_to_type/2,
jpl_classname_to_class/2,
jpl_classname_to_type/2, % name does not reflect that it deals with entity names
jpl_datum_to_type/2,
jpl_entityname_to_type/2, % new alias for jpl_classname_to_type/2
jpl_false/1,
jpl_is_class/1,
jpl_is_false/1,
jpl_is_null/1,
jpl_is_object/1,
jpl_is_object_type/1,
jpl_is_ref/1,
jpl_is_true/1,
jpl_is_type/1,
jpl_is_void/1,
jpl_null/1,
jpl_object_to_class/2,
jpl_object_to_type/2,
jpl_primitive_type/1,
jpl_ref_to_type/2,
jpl_true/1,
jpl_type_to_class/2,
jpl_type_to_classname/2, % name does not reflect that it deals with entity names
jpl_type_to_entityname/2, % new alias for jpl_type_to_classname/2
jpl_void/1,
jpl_array_to_length/2,
jpl_array_to_list/2,
jpl_datums_to_array/2,
jpl_enumeration_element/2,
jpl_enumeration_to_list/2,
jpl_hashtable_pair/2,
jpl_iterator_element/2,
jpl_list_to_array/2,
jpl_terms_to_array/2,
jpl_array_to_terms/2,
jpl_map_element/2,
jpl_set_element/2
]).
:- autoload(library(apply),[maplist/2]).
:- autoload(library(debug),[debugging/1,debug/3]).
:- autoload(library(lists),
[member/2,nth0/3,nth1/3,append/3,flatten/2,select/3]).
:- autoload(library(shlib),[load_foreign_library/1]).
/** <module> A Java interface for SWI Prolog 7.x
The library(jpl) provides a bidirectional interface to a Java Virtual Machine.
@see http://jpl7.org/
*/
% suppress debugging this library
:- set_prolog_flag(generate_debug_info, false).
%! jpl_new(+X, +Params, -V) is det.
%
% X can be:
% * an atomic classname, e.g. =|'java.lang.String'|=
% * or an atomic descriptor, e.g. =|'[I'|= or =|'Ljava.lang.String;'|=
% * or a suitable type, i.e. any class(_,_) or array(_), e.g. class([java,util],['Date'])
%
% If X is an object (non-array) type or descriptor and Params is a
% list of values or references, then V is the result of an invocation
% of that type's most specifically-typed constructor to whose
% respective formal parameters the actual Params are assignable (and
% assigned).
%
% If X is an array type or descriptor and Params is a list of values
% or references, each of which is (independently) assignable to the
% array element type, then V is a new array of as many elements as
% Params has members, initialised with the respective members of
% Params.
%
% If X is an array type or descriptor and Params is a non-negative
% integer N, then V is a new array of that type, with N elements, each
% initialised to Java's appropriate default value for the type.
%
% If V is literally =|{Term}|= then we attempt to convert a
% =|new org.jpl7.Term|= instance to
% a corresponding term; this is of little obvious use here, but is
% consistent with jpl_call/4 and jpl_get/3.
jpl_new(X, Params, V) :-
( var(X)
-> throwme(jpl_new,x_is_var)
; jpl_is_type(X) % NB Should check for "instantiable type"? Also accepts "double" for example.
-> Type = X
; atom(X) % an atom not captured by jpl_is_type/1 e.g. 'java.lang.String', '[L', even "void"
-> ( jpl_entityname_to_type(X, Type)
-> true
; throwme(jpl_new,x_not_classname(X))
)
; throwme(jpl_new,x_not_instantiable(X))
),
jpl_new_1(Type, Params, Vx),
( nonvar(V),
V = {Term} % yucky way of requesting Term->term conversion
-> ( jni_jref_to_term(Vx, TermX) % fails if Vx is not a JRef to a org.jpl7.Term
-> Term = TermX
; throwme(jpl_new,not_a_jpl_term(Vx))
)
; V = Vx
).
%! jpl_new_1(+Tx, +Params, -Vx)
%
% (serves only jpl_new/3)
%
% Tx can be a class(_,_) or array(_) type.
%
% Params must be a proper list of constructor parameters.
%
% At exit, Vx is bound to a JPL reference to a new, initialised instance of Tx
jpl_new_1(class(Ps,Cs), Params, Vx) :-
!, % green (see below)
Tx = class(Ps,Cs),
( var(Params)
-> throwme(jpl_new_class,params_is_var)
; \+ is_list(Params)
-> throwme(jpl_new_class,params_is_not_list(Params))
; true
),
length(Params, A), % the "arity" of the required constructor
jpl_type_to_class(Tx, Cx), % throws Java exception if class is not found
N = '<init>', % JNI's constructor naming convention for GetMethodID()
Tr = void, % all constructors have this return "type"
findall(
z3(I,MID,Tfps),
jpl_method_spec(Tx, I, N, A, _Mods, MID, Tr, Tfps), % cached
Z3s
),
( Z3s == [] % no constructors which require the given qty of parameters?
-> ( jpl_call(Cx, isInterface, [], @(true))
-> throwme(jpl_new_class,class_is_interface(Tx))
; throwme(jpl_new_class,class_without_constructor(Tx,A))
)
; ( catch(
jpl_datums_to_types(Params, Taps), % infer actual parameter types
% 2020-07-21: make catcher's 1st context arg an "anonvar" instead of a overspecified predicate indicator
error(type_error(acyclic,Te),context(_,Msg)),
throwme(jpl_new_class,acyclic(Te,Msg)) % rethrow
)
-> true
; throwme(jpl_new_class,bad_jpl_datum(Params))
),
findall(
z3(I,MID,Tfps), % select constructors to which actual parameters are assignable
( member(z3(I,MID,Tfps), Z3s),
jpl_types_fit_types(Taps, Tfps) % assignability test: actual parameter types "fit" formal parameter types?
),
Z3sA
),
( Z3sA == [] % no type-assignable constructors?
-> ( Z3s = [_]
-> throwme(jpl_new_class,single_constructor_mismatch(Tx/A))
; throwme(jpl_new_class,any_constructor_mismatch(Params))
)
; Z3sA = [z3(I,MID,Tfps)]
-> true
; jpl_z3s_to_most_specific_z3(Z3sA, z3(I,MID,Tfps))
-> true
; throwme(jpl_new_class,constructor_multimatch(Params))
)
),
catch(
jNewObject(Cx, MID, Tfps, Params, Vx),
error(java_exception(_), 'java.lang.InstantiationException'),
throwme(jpl_new_class,class_is_abstract(Tx)) % Rethrow
),
jpl_cache_type_of_ref(Tx, Vx). % since we know it
jpl_new_1(array(T), Params, Vx) :-
!,
( var(Params)
-> throwme(jpl_new_array,params_is_var)
; integer(Params) % integer I -> array[0..I-1] of default values
-> ( Params >= 0
-> Len is Params
; throwme(jpl_new_array,params_is_negative(Params))
)
; is_list(Params) % [V1,..VN] -> array[0..N-1] of respective values
-> length(Params, Len)
),
jpl_new_array(T, Len, Vx), % NB may throw out-of-memory exception
( nth0(I, Params, Param), % nmember fails silently when Params is integer
jpl_set(Vx, I, Param),
fail
; true
),
jpl_cache_type_of_ref(array(T), Vx). % since we know it
jpl_new_1(T, _Params, _Vx) :- % doomed attempt to create new primitive type instance (formerly a dubious completist feature :-)
jpl_primitive_type(T),
!,
throwme(jpl_new_primitive,primitive_type_requested(T)).
% ( var(Params)
% -> throwme(jpl_new_primitive,params_is_var)
% ; Params == []
% -> jpl_primitive_type_default_value(T, Vx)
% ; Params = [Param]
% -> jpl_primitive_type_term_to_value(T, Param, Vx)
% ; throwme(jpl_new_primitive,params_is_bad(Params))
% ).
jpl_new_1(T, _, _) :- throwme(jpl_new_catchall,catchall(T)).
%! jpl_new_array(+ElementType, +Length, -NewArray) is det
%
% binds NewArray to a jref to a newly created Java array of ElementType and Length
jpl_new_array(boolean, Len, A) :-
jNewBooleanArray(Len, A).
jpl_new_array(byte, Len, A) :-
jNewByteArray(Len, A).
jpl_new_array(char, Len, A) :-
jNewCharArray(Len, A).
jpl_new_array(short, Len, A) :-
jNewShortArray(Len, A).
jpl_new_array(int, Len, A) :-
jNewIntArray(Len, A).
jpl_new_array(long, Len, A) :-
jNewLongArray(Len, A).
jpl_new_array(float, Len, A) :-
jNewFloatArray(Len, A).
jpl_new_array(double, Len, A) :-
jNewDoubleArray(Len, A).
jpl_new_array(array(T), Len, A) :-
jpl_type_to_class(array(T), C),
jNewObjectArray(Len, C, @(null), A). % initialise each element to null
jpl_new_array(class(Ps,Cs), Len, A) :-
jpl_type_to_class(class(Ps,Cs), C),
jNewObjectArray(Len, C, @(null), A).
%! jpl_call(+X, +MethodName:atom, +Params:list(datum), -Result:datum) is det
%
% X should be either
% * an object reference, e.g. =|<jref>(1552320)|= (for static or instance methods)
% * or a classname, e.g. =|'java.util.Date'|= (for static methods only)
% * or a descriptor, e.g. =|'Ljava.util.Date;'|= (for static methods only)
% * or type, e.g. =|class([java,util],['Date'])|= (for static methods only)
%
% MethodName should be a method name (as an atom) (may involve dynamic overload resolution based on inferred types of params)
%
% Params should be a proper list (perhaps empty) of suitable actual parameters for the named method.
%
% The class or object may have several methods with the given name;
% JPL will resolve (per call) to the most appropriate method based on the quantity and inferred types of Params.
% This resolution mimics the corresponding static resolution performed by Java compilers.
%
% Finally, an attempt will be made to unify Result with the method's returned value,
% or with =|@(void)|= (the compound term with name =|@|= and argument =|void|=) if it has none.
jpl_call(X, Mspec, Params, R) :-
( jpl_object_to_type(X, Type) % the usual case (goal fails safely if X is var or rubbish)
-> Obj = X,
Kind = instance
; var(X)
-> throwme(jpl_call,arg1_is_var)
; atom(X)
-> ( jpl_entityname_to_type(X, Type) % does this attempt to load the class?
-> ( jpl_type_to_class(Type, ClassObj)
-> Kind = static
; throwme(jpl_call,no_such_class(X))
)
; throwme(jpl_call,arg1_is_bad(X))
)
; X = class(_,_)
-> Type = X,
jpl_type_to_class(Type, ClassObj),
Kind = static
; X = array(_)
-> throwme(jpl_call,arg1_is_array(X))
; throwme(jpl_call,arg1_is_bad(X))
),
( atom(Mspec) % the usual case, i.e. a method name
-> true
; var(Mspec)
-> throwme(jpl_call,mspec_is_var)
; throwme(jpl_call,mspec_is_bad(Mspec))
),
( is_list(Params)
-> ( catch(
jpl_datums_to_types(Params, Taps),
% 2020-07-21: make catcher's 1st context arg an "anonvar" instead of a overspecified predicate indicator
error(type_error(acyclic,Te),context(_,Msg)),
throwme(jpl_call,acyclic(Te,Msg)) % rethrow
)
-> true
; throwme(jpl_call,nonconvertible_params(Params))
),
length(Params, A)
; var(Params)
-> throwme(jpl_call,arg3_is_var)
; throwme(jpl_call,arg3_is_bad(Params))
),
( Kind == instance
-> jpl_call_instance(Type, Obj, Mspec, Params, Taps, A, Rx)
; jpl_call_static(Type, ClassObj, Mspec, Params, Taps, A, Rx)
),
( nonvar(R),
R = {Term} % yucky way of requesting Term->term conversion
-> ( jni_jref_to_term(Rx, TermX) % fails if Rx isn't a JRef to a org.jpl7.Term
-> Term = TermX
; throwme(jpl_call,not_a_jpl_term(Rx))
)
; R = Rx
).
%! jpl_call_instance(+ObjectType, +Object, +MethodName, +Params, +ActualParamTypes, +Arity, -Result)
%
% calls the MethodName-d method (instance or static) of Object (which is of ObjectType),
% which most specifically applies to Params,
% which we have found to be (respectively) of ActualParamTypes,
% and of which there are Arity, yielding Result.
jpl_call_instance(Type, Obj, Mname, Params, Taps, A, Rx) :-
findall( % get remaining details of all accessible methods of Obj's class (as denoted by Type)
z5(I,Mods,MID,Tr,Tfps),
jpl_method_spec(Type, I, Mname, A, Mods, MID, Tr, Tfps),
Z5s
),
( Z5s = []
-> throwme(jpl_call_instance,no_such_method(Mname/A))
; findall(
z5(I,Mods,MID,Tr,Tfps), % those to which Params is assignable
( member(z5(I,Mods,MID,Tr,Tfps), Z5s),
jpl_types_fit_types(Taps, Tfps) % assignability test: actual param types "fit" formal param types
),
Z5sA % Params-assignable methods
),
( Z5sA == []
-> throwme(jpl_call_instance,param_not_assignable(Params))
; Z5sA = [z5(I,Mods,MID,Tr,Tfps)]
-> true % exactly one applicable method
; jpl_z5s_to_most_specific_z5(Z5sA, z5(I,Mods,MID,Tr,Tfps))
-> true % exactly one most-specific applicable method
; throwme(jpl_call_instance,multiple_most_specific(Mname/Params))
)
),
( member(static, Mods) % if the chosen method is static
-> jpl_object_to_class(Obj, ClassObj), % get a java.lang.Class instance which personifies Obj's class
jpl_call_static_method(Tr, ClassObj, MID, Tfps, Params, Rx) % call static method w.r.t. associated Class object
; jpl_call_instance_method(Tr, Obj, MID, Tfps, Params, Rx) % else call (non-static) method w.r.t. object itself
).
%! jpl_call_static(+ClassType, +ClassObject, +MethodName, +Params, +ActualParamTypes, +Arity, -Result)
%
% calls the MethodName-d static method of the class (which is of ClassType,
% and which is represented by the java.lang.Class instance ClassObject)
% which most specifically applies to Params,
% which we have found to be (respectively) of ActualParamTypes,
% and of which there are Arity, yielding Result.
jpl_call_static(Type, ClassObj, Mname, Params, Taps, A, Rx) :-
findall( % get all accessible static methods of the class denoted by Type and ClassObj
z5(I,Mods,MID,Tr,Tfps),
( jpl_method_spec(Type, I, Mname, A, Mods, MID, Tr, Tfps),
member(static, Mods)
),
Z5s
),
( Z5s = []
-> throwme(jpl_call_static,no_such_method(Mname))
; findall(
z5(I,Mods,MID,Tr,Tfps),
( member(z5(I,Mods,MID,Tr,Tfps), Z5s),
jpl_types_fit_types(Taps, Tfps) % assignability test: actual param types "fit" formal param types
),
Z5sA % Params-assignable methods
),
( Z5sA == []
-> throwme(jpl_call_static,param_not_assignable(Params))
; Z5sA = [z5(I,Mods,MID,Tr,Tfps)]
-> true % exactly one applicable method
; jpl_z5s_to_most_specific_z5(Z5sA, z5(I,Mods,MID,Tr,Tfps))
-> true % exactly one most-specific applicable method
; throwme(jpl_call_instance,multiple_most_specific(Mname/Params))
)
),
jpl_call_static_method(Tr, ClassObj, MID, Tfps, Params, Rx).
%! jpl_call_instance_method(+Type, +ClassObject, +MethodID, +FormalParamTypes, +Params, -Result)
jpl_call_instance_method(void, Class, MID, Tfps, Ps, R) :-
jCallVoidMethod(Class, MID, Tfps, Ps),
jpl_void(R).
jpl_call_instance_method(boolean, Class, MID, Tfps, Ps, R) :-
jCallBooleanMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(byte, Class, MID, Tfps, Ps, R) :-
jCallByteMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(char, Class, MID, Tfps, Ps, R) :-
jCallCharMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(short, Class, MID, Tfps, Ps, R) :-
jCallShortMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(int, Class, MID, Tfps, Ps, R) :-
jCallIntMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(long, Class, MID, Tfps, Ps, R) :-
jCallLongMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(float, Class, MID, Tfps, Ps, R) :-
jCallFloatMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(double, Class, MID, Tfps, Ps, R) :-
jCallDoubleMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(array(_), Class, MID, Tfps, Ps, R) :-
jCallObjectMethod(Class, MID, Tfps, Ps, R).
jpl_call_instance_method(class(_,_), Class, MID, Tfps, Ps, R) :-
jCallObjectMethod(Class, MID, Tfps, Ps, R).
%! jpl_call_static_method(+Type, +ClassObject, +MethodID, +FormalParamTypes, +Params, -Result)
jpl_call_static_method(void, Class, MID, Tfps, Ps, R) :-
jCallStaticVoidMethod(Class, MID, Tfps, Ps),
jpl_void(R).
jpl_call_static_method(boolean, Class, MID, Tfps, Ps, R) :-
jCallStaticBooleanMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(byte, Class, MID, Tfps, Ps, R) :-
jCallStaticByteMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(char, Class, MID, Tfps, Ps, R) :-
jCallStaticCharMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(short, Class, MID, Tfps, Ps, R) :-
jCallStaticShortMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(int, Class, MID, Tfps, Ps, R) :-
jCallStaticIntMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(long, Class, MID, Tfps, Ps, R) :-
jCallStaticLongMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(float, Class, MID, Tfps, Ps, R) :-
jCallStaticFloatMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(double, Class, MID, Tfps, Ps, R) :-
jCallStaticDoubleMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(array(_), Class, MID, Tfps, Ps, R) :-
jCallStaticObjectMethod(Class, MID, Tfps, Ps, R).
jpl_call_static_method(class(_,_), Class, MID, Tfps, Ps, R) :-
jCallStaticObjectMethod(Class, MID, Tfps, Ps, R).
%! jpl_get(+X, +Fspec, -V:datum) is det
%
% X can be
%
% * a classname
% * or a descriptor
% * or an (object or array) type (for static fields)
% * or a non-array object (for static and non-static fields)
% * or an array (for 'length' pseudo field, or indexed element retrieval)
%
% Fspec can be
%
% * an atomic field name
% * or an integral array index (to get an element from an array)
% * or a pair I-J of integers (to get a subrange of an array).
%
% Finally, an attempt will be made to unify V with the retrieved value or object reference.
%
% Examples
%
% ==
% jpl_get('java.awt.Cursor', 'NE_RESIZE_CURSOR', Q).
% Q = 7.
%
% jpl_new(array(class([java,lang],['String'])), [for,while,do,if,then,else,try,catch,finally], A),
% jpl_get(A, 3-5, B).
% B = [if, then, else].
% ==
jpl_get(X, Fspec, V) :-
( jpl_object_to_type(X, Type)
-> Obj = X,
jpl_get_instance(Type, Type, Obj, Fspec, Vx) % pass Type twice for FAI
; var(X)
-> throwme(jpl_get,arg1_is_var)
; jpl_is_type(X) % e.g. class([java,lang],['String']), array(int)
-> Type = X,
( jpl_type_to_class(Type, ClassObj)
-> jpl_get_static(Type, ClassObj, Fspec, Vx)
; throwme(jpl_get,named_class_not_found(Type))
)
; atom(X)
-> ( jpl_entityname_to_type(X, Type) % does this attempt to load the class? (NO!)
-> ( jpl_type_to_class(Type, ClassObj)
-> jpl_get_static(Type, ClassObj, Fspec, Vx)
; throwme(jpl_get,named_class_not_found(Type))
)
; throwme(jpl_get,arg1_is_bad(X))
)
; throwme(jpl_get,arg1_is_bad_2(X))
),
( nonvar(V),
V = {Term} % yucky way of requesting Term->term conversion
-> ( jni_jref_to_term(Vx, TermX) % fails if Rx is not a JRef to a org.jpl7.Term
-> Term = TermX
; throwme(jpl_get,not_a_jpl_term(X))
)
; V = Vx
).
%! jpl_get_static(+Type:type, +ClassObject:jref, +FieldName:atom, -Value:datum) is det
%
% ClassObject is an instance of java.lang.Class which represents
% the same class as Type; Value (Vx below) is guaranteed unbound
% on entry, and will, before exit, be unified with the retrieved
% value
jpl_get_static(Type, ClassObj, Fname, Vx) :-
( atom(Fname) % assume it's a field name
-> true
; var(Fname)
-> throwme(jpl_get_static,arg2_is_var)
; throwme(jpl_get_static,arg2_is_bad(Fname))
),
% get static fields of the denoted class
findall(
z4(I,Mods,FID,Tf),
( jpl_field_spec(Type, I, Fname, Mods, FID, Tf),
member(static, Mods)
),
Z4s
),
( Z4s = []
-> throwme(jpl_get_static,no_such_field(Fname))
; Z4s = [z4(I,_Mods,FID,Tf)]
-> jpl_get_static_field(Tf, ClassObj, FID, Vx)
; throwme(jpl_get_static,multiple_fields(Fname))
).
%! jpl_get_instance(+Type, +Type, +Object, +FieldSpecifier, -Value) is det
jpl_get_instance(class(_,_), Type, Obj, Fname, Vx) :-
( atom(Fname) % the usual case
-> true
; var(Fname)
-> throwme(jpl_get_instance,arg2_is_var)
; throwme(jpl_get_instance,arg2_is_bad(Fname))
),
findall(
z4(I,Mods,FID,Tf),
jpl_field_spec(Type, I, Fname, Mods, FID, Tf),
Z4s
),
( Z4s = []
-> throwme(jpl_get_instance,no_such_field(Fname))
; Z4s = [z4(I,Mods,FID,Tf)]
-> ( member(static, Mods)
-> jpl_object_to_class(Obj, ClassObj),
jpl_get_static_field(Tf, ClassObj, FID, Vx)
; jpl_get_instance_field(Tf, Obj, FID, Vx)
)
; throwme(jpl_get_instance,multiple_fields(Fname))
).
jpl_get_instance(array(ElementType), _, Array, Fspec, Vx) :-
( var(Fspec)
-> throwme(jpl_get_instance_array,arg2_is_var)
; integer(Fspec)
-> ( Fspec < 0 % lo bound check
-> throwme(jpl_get_instance_array,arg2_is_bad(Fspec))
; jGetArrayLength(Array, Len),
Fspec >= Len % hi bound check
-> throwme(jpl_get_instance_array,arg2_is_too_large(Fspec))
; jpl_get_array_element(ElementType, Array, Fspec, Vx)
)
; Fspec = N-M % NB should we support e.g. 3-2 -> [] ?
-> ( integer(N),
integer(M)
-> ( N >= 0,
M >= N
-> jGetArrayLength(Array, Len),
( N >= Len
-> throwme(jpl_get_instance_array,bad_range_low(N-M))
; M >= Len
-> throwme(jpl_get_instance_array,bad_range_high(N-M))
; jpl_get_array_elements(ElementType, Array, N, M, Vx)
)
; throwme(jpl_get_instance_array,bad_range_pair_values(N-M))
)
; throwme(jpl_get_instance_array,bad_range_pair_types(N-M))
)
; atom(Fspec)
-> ( Fspec == length % special-case for this solitary array "method"
-> jGetArrayLength(Array, Vx)
; throwme(jpl_get_instance_array,no_such_field(Fspec))
)
; throwme(jpl_get_instance_array,wrong_spec(Fspec))
).
%! jpl_get_array_element(+ElementType:type, +Array:jref, +Index, -Vc) is det
%
% Array is a JPL reference to a Java array of ElementType; Vc is
% (unified with a JPL repn of) its Index-th (numbered from 0)
% element Java values are now converted to Prolog terms within
% foreign code
%
% @tbd more of this could be done within foreign code
jpl_get_array_element(Type, Array, Index, Vc) :-
( ( Type = class(_,_)
; Type = array(_)
)
-> jGetObjectArrayElement(Array, Index, Vr)
; jpl_primitive_type(Type)
-> jni_type_to_xput_code(Type, Xc),
jni_alloc_buffer(Xc, 1, Bp), % one-element buf for a Type
jpl_get_primitive_array_region(Type, Array, Index, 1, Bp),
jni_fetch_buffer_value(Bp, 0, Vr, Xc), % zero-th element
jni_free_buffer(Bp)
),
Vr = Vc. % redundant since Vc is always (?) unbound at call
%! jpl_get_array_elements(+ElementType, +Array, +N, +M, -Vs)
%
% serves only jpl_get_instance/5
%
% Vs will always be unbound on entry
jpl_get_array_elements(ElementType, Array, N, M, Vs) :-
( ( ElementType = class(_,_)
; ElementType = array(_)
)
-> jpl_get_object_array_elements(Array, N, M, Vs)
; jpl_get_primitive_array_elements(ElementType, Array, N, M, Vs)
).
jpl_get_instance_field(boolean, Obj, FieldID, V) :-
jGetBooleanField(Obj, FieldID, V).
jpl_get_instance_field(byte, Obj, FieldID, V) :-
jGetByteField(Obj, FieldID, V).
jpl_get_instance_field(char, Obj, FieldID, V) :-
jGetCharField(Obj, FieldID, V).
jpl_get_instance_field(short, Obj, FieldID, V) :-
jGetShortField(Obj, FieldID, V).
jpl_get_instance_field(int, Obj, FieldID, V) :-
jGetIntField(Obj, FieldID, V).
jpl_get_instance_field(long, Obj, FieldID, V) :-
jGetLongField(Obj, FieldID, V).
jpl_get_instance_field(float, Obj, FieldID, V) :-
jGetFloatField(Obj, FieldID, V).
jpl_get_instance_field(double, Obj, FieldID, V) :-
jGetDoubleField(Obj, FieldID, V).
jpl_get_instance_field(class(_,_), Obj, FieldID, V) :-
jGetObjectField(Obj, FieldID, V).
jpl_get_instance_field(array(_), Obj, FieldID, V) :-
jGetObjectField(Obj, FieldID, V).
%! jpl_get_object_array_elements(+Array, +LoIndex, +HiIndex, -Vcs) is det
%
% Array should be a (zero-based) array of some object (array or
% non-array) type; LoIndex is an integer, 0 =< LoIndex <
% length(Array); HiIndex is an integer, LoIndex-1 =< HiIndex <
% length(Array); at call, Vcs will be unbound; at exit, Vcs will be a
% list of (references to) the array's elements [LoIndex..HiIndex]
% inclusive
jpl_get_object_array_elements(Array, Lo, Hi, Vcs) :-
( Lo =< Hi
-> Vcs = [Vc|Vcs2],
jGetObjectArrayElement(Array, Lo, Vc),
Next is Lo+1,
jpl_get_object_array_elements(Array, Next, Hi, Vcs2)
; Vcs = []
).
%! jpl_get_primitive_array_elements(+ElementType, +Array, +LoIndex, +HiIndex, -Vcs) is det.
%
% Array should be a (zero-based) Java array of (primitive)
% ElementType; Vcs should be unbound on entry, and on exit will be
% a list of (JPL representations of the values of) the elements
% [LoIndex..HiIndex] inclusive
jpl_get_primitive_array_elements(ElementType, Array, Lo, Hi, Vcs) :-
Size is Hi-Lo+1,
( Size == 0
-> Vcs = []
; jni_type_to_xput_code(ElementType, Xc),
jni_alloc_buffer(Xc, Size, Bp),
jpl_get_primitive_array_region(ElementType, Array, Lo, Size, Bp),
jpl_primitive_buffer_to_array(ElementType, Xc, Bp, 0, Size, Vcs),
jni_free_buffer(Bp)
).
jpl_get_primitive_array_region(boolean, Array, Lo, S, I) :-
jGetBooleanArrayRegion(Array, Lo, S, jbuf(I,boolean)).
jpl_get_primitive_array_region(byte, Array, Lo, S, I) :-
jGetByteArrayRegion(Array, Lo, S, jbuf(I,byte)).
jpl_get_primitive_array_region(char, Array, Lo, S, I) :-
jGetCharArrayRegion(Array, Lo, S, jbuf(I,char)).
jpl_get_primitive_array_region(short, Array, Lo, S, I) :-
jGetShortArrayRegion(Array, Lo, S, jbuf(I,short)).
jpl_get_primitive_array_region(int, Array, Lo, S, I) :-
jGetIntArrayRegion(Array, Lo, S, jbuf(I,int)).
jpl_get_primitive_array_region(long, Array, Lo, S, I) :-
jGetLongArrayRegion(Array, Lo, S, jbuf(I,long)).
jpl_get_primitive_array_region(float, Array, Lo, S, I) :-
jGetFloatArrayRegion(Array, Lo, S, jbuf(I,float)).
jpl_get_primitive_array_region(double, Array, Lo, S, I) :-
jGetDoubleArrayRegion(Array, Lo, S, jbuf(I,double)).
jpl_get_static_field(boolean, Array, FieldID, V) :-
jGetStaticBooleanField(Array, FieldID, V).
jpl_get_static_field(byte, Array, FieldID, V) :-
jGetStaticByteField(Array, FieldID, V).
jpl_get_static_field(char, Array, FieldID, V) :-
jGetStaticCharField(Array, FieldID, V).
jpl_get_static_field(short, Array, FieldID, V) :-
jGetStaticShortField(Array, FieldID, V).
jpl_get_static_field(int, Array, FieldID, V) :-
jGetStaticIntField(Array, FieldID, V).
jpl_get_static_field(long, Array, FieldID, V) :-
jGetStaticLongField(Array, FieldID, V).
jpl_get_static_field(float, Array, FieldID, V) :-
jGetStaticFloatField(Array, FieldID, V).
jpl_get_static_field(double, Array, FieldID, V) :-
jGetStaticDoubleField(Array, FieldID, V).
jpl_get_static_field(class(_,_), Array, FieldID, V) :-
jGetStaticObjectField(Array, FieldID, V).
jpl_get_static_field(array(_), Array, FieldID, V) :-
jGetStaticObjectField(Array, FieldID, V).
%! jpl_set(+X, +Fspec, +V) is det.
%
% sets the Fspec-th field of (class or object) X to value V iff it is assignable
%
% X can be
% * a class instance (for static or non-static fields)
% * or an array (for indexed element or subrange assignment)
% * or a classname, or a class(_,_) or array(_) type (for static fields)
% * but not a String (no fields to retrieve)
%
% Fspec can be
% * an atomic field name (overloading through shadowing has yet to be handled properly)
% * or an array index I (X must be an array object: V is assigned to X[I])
% * or a pair I-J of integers (X must be an array object, V must be a list of values: successive members of V are assigned to X[I..J])
%
% V must be a suitable value or object.
jpl_set(X, Fspec, V) :-
( jpl_object_to_type(X, Type) % the usual case (test is safe if X is var or rubbish)
-> Obj = X,
catch(
jpl_set_instance(Type, Type, Obj, Fspec, V), % first 'Type' is for FAI
% 2020-07-21: make catcher's 1st context arg an "anonvar" instead of a overspecified predicate indicator
error(type_error(acyclic,Te),context(_,Msg)),
throwme(jpl_set,acyclic(Te,Msg)) % rethrow
)
; var(X)
-> throwme(jpl_set,arg1_is_var)
; ( atom(X)
-> ( jpl_entityname_to_type(X, Type) % it's a classname or descriptor...
-> true
; throwme(jpl_set,classname_does_not_resolve(X))
)
; ( X = class(_,_) % it's a class type...
; X = array(_) % ...or an array type
)
-> Type = X
),
( jpl_type_to_class(Type, ClassObj) % ...whose Class object is available
-> true
; throwme(jpl_set,named_class_not_found(Type))
)
-> catch(
jpl_set_static(Type, ClassObj, Fspec, V),
% 2020-07-21: make catcher's 1st context arg an "anonvar" instead of a overspecified predicate indicator
error(type_error(acyclic,Te),context(_,Msg)),
throwme(jpl_set,acyclic(Te,Msg)) % rethrow
)
; throwme(jpl_set,arg1_is_bad(X))
).
%! jpl_set_instance(+Type, +Type, +ObjectReference, +FieldName, +Value) is det.
%
% ObjectReference is a JPL reference to a Java object
% of the class denoted by Type (which is passed twice for first agument indexing);
%
% FieldName should name a public, non-final (static or non-static) field of this object,
% but could be anything, and is validated here;
%
% Value should be assignable to the named field, but could be anything, and is validated here
jpl_set_instance(class(_,_), Type, Obj, Fname, V) :- % a non-array object
( atom(Fname) % the usual case
-> true
; var(Fname)
-> throwme(jpl_set_instance_class,arg2_is_var)
; throwme(jpl_set_instance_class,arg2_is_bad(Fname))
),
findall(
z4(I,Mods,FID,Tf),
jpl_field_spec(Type, I, Fname, Mods, FID, Tf), % public fields of class denoted by Type
Z4s
),
( Z4s = []
-> throwme(jpl_set_instance_class,no_such_field(Fname))
; Z4s = [z4(I,Mods,FID,Tf)]
-> ( member(final, Mods)
-> throwme(jpl_set_instance_class,field_is_final(Fname))
; jpl_datum_to_type(V, Tv)
-> ( jpl_type_fits_type(Tv, Tf)
-> ( member(static, Mods)
-> jpl_object_to_class(Obj, ClassObj),
jpl_set_static_field(Tf, ClassObj, FID, V)
; jpl_set_instance_field(Tf, Obj, FID, V) % oughta be jpl_set_instance_field?
)
; throwme(jpl_set_instance_class,incompatible_value(Tf,V))
)
; throwme(jpl_set_instance_class,arg3_is_bad(V))
)
; throwme(jpl_set_instance_class,multiple_fields(Fname)) % 'existence'? or some other sort of error maybe?
).
jpl_set_instance(array(Type), _, Obj, Fspec, V) :-
( is_list(V) % a list of array element values
-> Vs = V
; var(V)
-> throwme(jpl_set_instance_array,arg3_is_var)
; Vs = [V] % a single array element value
),
length(Vs, Iv),
( var(Fspec)
-> throwme(jpl_set_instance_array,arg2_is_var)
; integer(Fspec) % single-element assignment
-> ( Fspec < 0
-> throwme(jpl_set_instance_array,arg2_is_bad(Fspec))
; Iv is 1
-> N is Fspec
; Iv is 0
-> throwme(jpl_set_instance_array,no_values(Fspec,Vs))
; throwme(jpl_set_instance_array,more_than_one_value(Fspec,Vs))
)
; Fspec = N-M % element-sequence assignment
-> ( integer(N),
integer(M)
-> ( N >= 0,
Size is (M-N)+1,
Size >= 0
-> ( Size == Iv
-> true
; Size < Iv
-> throwme(jpl_set_instance_array,too_few_values(N-M,Vs))
; throwme(jpl_set_instance_array,too_many_values(N-M,Vs))
)
; throwme(jpl_set_instance_array,bad_range_pair_values(N-M))
)
; throwme(jpl_set_instance_array,bad_range_pair_types(N-M))
)
; atom(Fspec)
-> ( Fspec == length
-> throwme(jpl_set_instance_array,cannot_assign_to_final_field)
; throwme(jpl_set_instance_array,no_such_field(Fspec))
)
; throwme(jpl_set_instance_array,arg2_is_bad_2(Fspec))
),
jpl_set_array(Type, Obj, N, Iv, Vs).
%! jpl_set_static(+Type, +ClassObj, +FieldName, +Value) is det.
%
% We can rely on:
% * Type being a class/2 type representing some accessible class
% * ClassObj being an instance of java.lang.Class which represents the same class as Type
%
% but FieldName could be anything, so we validate it here,
% look for a suitable (static) field of the target class,
% then call jpl_set_static_field/4 to attempt to assign Value (which could be anything) to it
%
% NB this does not yet handle shadowed fields correctly.
jpl_set_static(Type, ClassObj, Fname, V) :-
( atom(Fname) % the usual case
-> true
; var(Fname)
-> throwme(jpl_set_static,arg2_is_unbound)
; throwme(jpl_set_static,arg2_is_bad(Fname))
),
findall( % get all static fields of the denoted class
z4(I,Mods,FID,Tf),
( jpl_field_spec(Type, I, Fname, Mods, FID, Tf),
member(static, Mods)
),
Z4s
),
( Z4s = []
-> throwme(jpl_set_static,no_such_public_static_field(field,Fname))
; Z4s = [z4(I,Mods,FID,Tf)] % exactly one synonymous field?
-> ( member(final, Mods)
-> throwme(jpl_set_static,cannot_assign_final_field(Fname))
; jpl_datum_to_type(V, Tv)
-> ( jpl_type_fits_type(Tv, Tf)
-> jpl_set_static_field(Tf, ClassObj, FID, V)
; throwme(jpl_set_static,value_not_assignable(Tf,V))
)
; throwme(jpl_set_static,arg3_is_bad(field_value,V))
)
; throwme(jpl_set_static,multiple_matches(field,Fname))
).
%! jpl_set_array(+ElementType, +Array, +Offset, +DatumQty, +Datums) is det.
%
% Datums, of which there are DatumQty, are stashed in successive
% elements of Array which is an array of ElementType starting at
% the Offset-th (numbered from 0)
% throws error(type_error(acyclic,_),context(jpl_datum_to_type/2,_))
jpl_set_array(T, A, N, I, Ds) :-
( jpl_datums_to_types(Ds, Tds) % most specialised types of given values
-> ( jpl_types_fit_type(Tds, T) % all assignable to element type?
-> true
; throwme(jpl_set_array,not_all_values_assignable(T,Ds))
)
; throwme(jpl_set_array,not_all_values_convertible(T,Ds))
),
( ( T = class(_,_)
; T = array(_) % array elements are objects
)
-> ( nth0(J, Ds, D), % for each datum
Nd is N+J, % compute array index
( D = {Tq} % quoted term?
-> jni_term_to_jref(Tq, D2) % convert to a JPL reference to a corresponding org.jpl7.Term object
; D = D2
),
jSetObjectArrayElement(A, Nd, D2),
fail % iterate
; true
)
; jpl_primitive_type(T) % array elements are primitive values
-> jni_type_to_xput_code(T, Xc),
jni_alloc_buffer(Xc, I, Bp), % I-element buf of required primitive type
jpl_set_array_1(Ds, T, 0, Bp),
jpl_set_elements(T, A, N, I, Bp),
jni_free_buffer(Bp)
;
% T is neither a class, nor an array type nor a primitive type
throwme(jpl_set_array,element_type_unknown(array_element_type,T))
).
%! jpl_set_array_1(+Values, +Type, +BufferIndex, +BufferPointer) is det.
%
% successive members of Values are stashed as (primitive) Type
% from the BufferIndex-th element (numbered from 0) onwards of the
% buffer indicated by BufferPointer
%
% NB this could be done more efficiently (?) within foreign code...
jpl_set_array_1([], _, _, _).
jpl_set_array_1([V|Vs], Tprim, Ib, Bp) :-
jni_type_to_xput_code(Tprim, Xc),
jni_stash_buffer_value(Bp, Ib, V, Xc),
Ibnext is Ib+1,
jpl_set_array_1(Vs, Tprim, Ibnext, Bp).
jpl_set_elements(boolean, Obj, N, I, Bp) :-
jSetBooleanArrayRegion(Obj, N, I, jbuf(Bp,boolean)).
jpl_set_elements(char, Obj, N, I, Bp) :-
jSetCharArrayRegion(Obj, N, I, jbuf(Bp,char)).
jpl_set_elements(byte, Obj, N, I, Bp) :-
jSetByteArrayRegion(Obj, N, I, jbuf(Bp,byte)).
jpl_set_elements(short, Obj, N, I, Bp) :-
jSetShortArrayRegion(Obj, N, I, jbuf(Bp,short)).
jpl_set_elements(int, Obj, N, I, Bp) :-
jSetIntArrayRegion(Obj, N, I, jbuf(Bp,int)).
jpl_set_elements(long, Obj, N, I, Bp) :-
jSetLongArrayRegion(Obj, N, I, jbuf(Bp,long)).
jpl_set_elements(float, Obj, N, I, Bp) :-
jSetFloatArrayRegion(Obj, N, I, jbuf(Bp,float)).
jpl_set_elements(double, Obj, N, I, Bp) :-
jSetDoubleArrayRegion(Obj, N, I, jbuf(Bp,double)).
%! jpl_set_instance_field(+Type, +Obj, +FieldID, +V) is det.
%
% We can rely on Type, Obj and FieldID being valid, and on V being
% assignable (if V is a quoted term then it is converted here)
jpl_set_instance_field(boolean, Obj, FieldID, V) :-
jSetBooleanField(Obj, FieldID, V).
jpl_set_instance_field(byte, Obj, FieldID, V) :-
jSetByteField(Obj, FieldID, V).
jpl_set_instance_field(char, Obj, FieldID, V) :-
jSetCharField(Obj, FieldID, V).
jpl_set_instance_field(short, Obj, FieldID, V) :-
jSetShortField(Obj, FieldID, V).
jpl_set_instance_field(int, Obj, FieldID, V) :-
jSetIntField(Obj, FieldID, V).
jpl_set_instance_field(long, Obj, FieldID, V) :-
jSetLongField(Obj, FieldID, V).
jpl_set_instance_field(float, Obj, FieldID, V) :-
jSetFloatField(Obj, FieldID, V).
jpl_set_instance_field(double, Obj, FieldID, V) :-
jSetDoubleField(Obj, FieldID, V).
jpl_set_instance_field(class(_,_), Obj, FieldID, V) :- % also handles byval term assignments
( V = {T} % quoted term?
-> jni_term_to_jref(T, V2) % convert to a JPL reference to a corresponding org.jpl7.Term object
; V = V2
),
jSetObjectField(Obj, FieldID, V2).
jpl_set_instance_field(array(_), Obj, FieldID, V) :-
jSetObjectField(Obj, FieldID, V).
%! jpl_set_static_field(+Type, +ClassObj, +FieldID, +V)
%
% We can rely on Type, ClassObj and FieldID being valid,
% and on V being assignable (if V is a quoted term then it is converted here).
jpl_set_static_field(boolean, Obj, FieldID, V) :-
jSetStaticBooleanField(Obj, FieldID, V).
jpl_set_static_field(byte, Obj, FieldID, V) :-
jSetStaticByteField(Obj, FieldID, V).
jpl_set_static_field(char, Obj, FieldID, V) :-
jSetStaticCharField(Obj, FieldID, V).
jpl_set_static_field(short, Obj, FieldID, V) :-
jSetStaticShortField(Obj, FieldID, V).
jpl_set_static_field(int, Obj, FieldID, V) :-
jSetStaticIntField(Obj, FieldID, V).
jpl_set_static_field(long, Obj, FieldID, V) :-
jSetStaticLongField(Obj, FieldID, V).
jpl_set_static_field(float, Obj, FieldID, V) :-
jSetStaticFloatField(Obj, FieldID, V).
jpl_set_static_field(double, Obj, FieldID, V) :-
jSetStaticDoubleField(Obj, FieldID, V).
jpl_set_static_field(class(_,_), Obj, FieldID, V) :- % also handles byval term assignments
( V = {T} % quoted term?
-> jni_term_to_jref(T, V2) % convert to a JPL reference to a corresponding org.jpl7.Term object
; V = V2
),
jSetStaticObjectField(Obj, FieldID, V2).
jpl_set_static_field(array(_), Obj, FieldID, V) :-
jSetStaticObjectField(Obj, FieldID, V).
%! jpl_get_default_jvm_opts(-Opts:list(atom)) is det
%
% Returns (as a list of atoms) the options which will be passed to the JVM when it is initialised,
% e.g. =|['-Xrs']|=
jpl_get_default_jvm_opts(Opts) :-
jni_get_default_jvm_opts(Opts).
%! jpl_set_default_jvm_opts(+Opts:list(atom)) is det
%
% Replaces the default JVM initialisation options with those supplied.
jpl_set_default_jvm_opts(Opts) :-
is_list(Opts),
length(Opts, N),
jni_set_default_jvm_opts(N, Opts).
%! jpl_get_actual_jvm_opts(-Opts:list(atom)) is semidet
%
% Returns (as a list of atoms) the options with which the JVM was initialised.
%
% Fails silently if a JVM has not yet been started, and can thus be used to test for this.
jpl_get_actual_jvm_opts(Opts) :-
jni_get_actual_jvm_opts(Opts).
% ===========================================================================
% Caching
% ===========================================================================
% In principle the predicates subject to assert/1 must be declared with the
% dynamic/1 directive. However, they are automatically declared as "dynamic"
% if they appear in an assert/1 call first. Anyway, we declare then dynamic
% right here!
:- dynamic jpl_field_spec_cache/6. % document this...
:- dynamic jpl_field_spec_is_cached/1. % document this...
:- dynamic jpl_method_spec_cache/8.
:- dynamic jpl_method_spec_is_cached/1.
:- dynamic jpl_iref_type_cache/2.
%! jpl_classname_type_cache( -Classname:className, -Type:type)
%
% Classname is the atomic name of Type.
%
% NB may denote a class which cannot be found.
:- dynamic jpl_classname_type_cache/2.
%! jpl_class_tag_type_cache(-Class:jref, -Type:jpl_type)
%
% `Class` is a reference to an instance of `java.lang.Class`
% which denotes `Type`.
%
% We index on `Class` (a jref) so as to keep these objects around
% even after an atom garbage collection (if needed once, they are likely
% to be needed again)
%
% (Is it possble to have different Ref for the same ClassType,
% which happens once several ClassLoaders become involved?) (Most likely)
:- dynamic jpl_class_tag_type_cache/2.
%! jpl_assert(+Fact:term)
%
% Assert a fact listed in jpl_assert_policy/2 with "yes" into the Prolog
% database.
%
% From the SWI-Prolog manual:
%
% > "In SWI-Prolog, querying dynamic predicates has the same performance as
% > static ones. The manipulation predicates are fast."
%
% And:
%
% > "By default, a predicate declared dynamic (see dynamic/1) is shared by
% > all threads. Each thread may assert, retract and run the dynamic
% > predicate. Synchronisation inside Prolog guarantees the consistency of
% > the predicate. Updates are logical: visible clauses are not affected
% > by assert/retract after a query started on the predicate. In many
% > cases primitives from section 10.4 should be used to ensure that
% > application invariants on the predicate are maintained.
%
% @see https://eu.swi-prolog.org/pldoc/man?section=db
% @see https://eu.swi-prolog.org/pldoc/man?section=threadlocal
jpl_assert(Fact) :-
( jpl_assert_policy(Fact, yes)
-> assertz(Fact)
; true
).
% ---
% policies
% ---
jpl_assert_policy(jpl_field_spec_cache(_,_,_,_,_,_), yes).
jpl_assert_policy(jpl_field_spec_is_cached(_), YN) :-
jpl_assert_policy(jpl_field_spec_cache(_,_,_,_,_,_), YN).
jpl_assert_policy(jpl_method_spec_cache(_,_,_,_,_,_,_,_), yes).
jpl_assert_policy(jpl_method_spec_is_cached(_), YN) :-
jpl_assert_policy(jpl_method_spec_cache(_,_,_,_,_,_,_,_), YN).
jpl_assert_policy(jpl_class_tag_type_cache(_,_), yes).
jpl_assert_policy(jpl_classname_type_cache(_,_), yes).
jpl_assert_policy(jpl_iref_type_cache(_,_), no). % must correspond to JPL_CACHE_TYPE_OF_REF in jpl.c
%! jpl_tidy_iref_type_cache(+Iref) is det.
%
% Delete the cached type info, if any, under Iref.
%
% Called from jpl.c's jni_free_iref() via jni_tidy_iref_type_cache()
jpl_tidy_iref_type_cache(Iref) :-
% write('[decaching types for iref='), write(Iref), write(']'), nl,
retractall(jpl_iref_type_cache(Iref,_)),
true.
jpl_fergus_find_candidate([], Candidate, Candidate, []).
jpl_fergus_find_candidate([X|Xs], Candidate0, Candidate, Rest) :-
( jpl_fergus_greater(X, Candidate0)
-> Candidate1 = X,
Rest = [Candidate0|Rest1]
; Candidate1 = Candidate0,
Rest = [X|Rest1]
),
jpl_fergus_find_candidate(Xs, Candidate1, Candidate, Rest1).
jpl_fergus_greater(z5(_,_,_,_,Tps1), z5(_,_,_,_,Tps2)) :-
jpl_types_fit_types(Tps1, Tps2).
jpl_fergus_greater(z3(_,_,Tps1), z3(_,_,Tps2)) :-
jpl_types_fit_types(Tps1, Tps2).
%! jpl_fergus_is_the_greatest(+Xs:list(T), -GreatestX:T)
%
% Xs is a list of things for which jpl_fergus_greater/2 defines a
% partial ordering; GreatestX is one of those, than which none is
% greater; fails if there is more than one such; this algorithm
% was contributed to c.l.p by Fergus Henderson in response to my
% "there must be a better way" challenge: there was, this is it
jpl_fergus_is_the_greatest([X|Xs], Greatest) :-
jpl_fergus_find_candidate(Xs, X, Greatest, Rest),
forall(
member(R, Rest),
jpl_fergus_greater(Greatest, R)
).
%! jpl_z3s_to_most_specific_z3(+Zs, -Z)
%
% Zs is a list of arity-matching, type-suitable z3(I,MID,Tfps).
%
% Z is the single most specific element of Zs,
% i.e. that than which no other z3/3 has a more specialised signature (fails if there is more than one such).
jpl_z3s_to_most_specific_z3(Zs, Z) :-
jpl_fergus_is_the_greatest(Zs, Z).
%! jpl_z5s_to_most_specific_z5(+Zs, -Z)
%
% Zs is a list of arity-matching, type-suitable z5(I,Mods,MID,Tr,Tfps)
%
% Z is the single most specific element of Zs,
% i.e. that than which no other z5/5 has a more specialised signature (fails if there is more than one such)
jpl_z5s_to_most_specific_z5(Zs, Z) :-
jpl_fergus_is_the_greatest(Zs, Z).
%! jpl_pl_lib_version(-Version)
%
% Version is the fully qualified version identifier of the in-use Prolog component (jpl.pl) of JPL.
%
% It should exactly match the version identifiers of JPL's C (jpl.c) and Java (jpl.jar) components.
%
% Example
%
% ==
% ?- jpl_pl_lib_version(V).
% V = '7.6.1'.
% ==
jpl_pl_lib_version(VersionString) :-
jpl_pl_lib_version(Major, Minor, Patch, Status),
atomic_list_concat([Major,'.',Minor,'.',Patch,'-',Status], VersionString).
%! jpl_pl_lib_version(-Major, -Minor, -Patch, -Status)
%
% Major, Minor, Patch and Status are the respective components of the version identifier of the in-use C component (jpl.c) of JPL.
%
% Example
%
% ==
% ?- jpl:jpl_pl_lib_version(Major, Minor, Patch, Status).
% Major = 7,
% Minor = 4,
% Patch = 0,
% Status = alpha.
% ==
jpl_pl_lib_version(7, 6, 1, stable). % jref as blob
%! jpl_c_lib_version(-Version)
%
% Version is the fully qualified version identifier of the in-use C component (jpl.c) of JPL.
%
% It should exactly match the version identifiers of JPL's Prolog (jpl.pl) and Java (jpl.jar) components.
%
% Example
%
% ==
% ?- jpl_c_lib_version(V).
% V = '7.4.0-alpha'.
% ==
%! jpl_java_lib_version(-Version)
%
% Version is the fully qualified version identifier of the in-use Java component (jpl.jar) of JPL.
%
% Example
%
% ==
% ?- jpl:jpl_java_lib_version(V).
% V = '7.4.0-alpha'.
% ==
%! jpl_java_lib_version(V)
jpl_java_lib_version(V) :-
jpl_call('org.jpl7.JPL', version_string, [], V).
%! jpl_pl_lib_path(-Path:atom)
jpl_pl_lib_path(Path) :-
module_property(jpl, file(Path)).
%! jpl_c_lib_path(-Path:atom)
jpl_c_lib_path(Path) :-
shlib:current_library(_, _, Path, jpl, _),
!.
%! jpl_java_lib_path(-Path:atom)
jpl_java_lib_path(Path) :-
jpl_call('org.jpl7.JPL', jarPath, [], Path).
%! jCallBooleanMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rbool:boolean)
jCallBooleanMethod(Obj, MethodID, Types, Params, Rbool) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(39, Obj, MethodID, ParamBuf, Rbool).
%! jCallByteMethod(+Obj:jref, +MethodID:methodId, +Types, +Params:list(datum), -Rbyte:byte)
jCallByteMethod(Obj, MethodID, Types, Params, Rbyte) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(42, Obj, MethodID, ParamBuf, Rbyte).
%! jCallCharMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rchar:char)
jCallCharMethod(Obj, MethodID, Types, Params, Rchar) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(45, Obj, MethodID, ParamBuf, Rchar).
%! jCallDoubleMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rdouble:double)
jCallDoubleMethod(Obj, MethodID, Types, Params, Rdouble) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(60, Obj, MethodID, ParamBuf, Rdouble).
%! jCallFloatMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rfloat:float)
jCallFloatMethod(Obj, MethodID, Types, Params, Rfloat) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(57, Obj, MethodID, ParamBuf, Rfloat).
%! jCallIntMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rint:int)
jCallIntMethod(Obj, MethodID, Types, Params, Rint) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(51, Obj, MethodID, ParamBuf, Rint).
%! jCallLongMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rlong:long)
jCallLongMethod(Obj, MethodID, Types, Params, Rlong) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(54, Obj, MethodID, ParamBuf, Rlong).
%! jCallObjectMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Robj:jref)
jCallObjectMethod(Obj, MethodID, Types, Params, Robj) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(36, Obj, MethodID, ParamBuf, Robj).
%! jCallShortMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rshort:short)
jCallShortMethod(Obj, MethodID, Types, Params, Rshort) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(48, Obj, MethodID, ParamBuf, Rshort).
%! jCallStaticBooleanMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rbool:boolean)
jCallStaticBooleanMethod(Class, MethodID, Types, Params, Rbool) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(119, Class, MethodID, ParamBuf, Rbool).
%! jCallStaticByteMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rbyte:byte)
jCallStaticByteMethod(Class, MethodID, Types, Params, Rbyte) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(122, Class, MethodID, ParamBuf, Rbyte).
%! jCallStaticCharMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rchar:char)
jCallStaticCharMethod(Class, MethodID, Types, Params, Rchar) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(125, Class, MethodID, ParamBuf, Rchar).
%! jCallStaticDoubleMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rdouble:double)
jCallStaticDoubleMethod(Class, MethodID, Types, Params, Rdouble) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(140, Class, MethodID, ParamBuf, Rdouble).
%! jCallStaticFloatMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rfloat:float)
jCallStaticFloatMethod(Class, MethodID, Types, Params, Rfloat) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(137, Class, MethodID, ParamBuf, Rfloat).
%! jCallStaticIntMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rint:int)
jCallStaticIntMethod(Class, MethodID, Types, Params, Rint) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(131, Class, MethodID, ParamBuf, Rint).
%! jCallStaticLongMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rlong:long)
jCallStaticLongMethod(Class, MethodID, Types, Params, Rlong) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(134, Class, MethodID, ParamBuf, Rlong).
%! jCallStaticObjectMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Robj:jref)
jCallStaticObjectMethod(Class, MethodID, Types, Params, Robj) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(116, Class, MethodID, ParamBuf, Robj).
%! jCallStaticShortMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Rshort:short)
jCallStaticShortMethod(Class, MethodID, Types, Params, Rshort) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(128, Class, MethodID, ParamBuf, Rshort).
%! jCallStaticVoidMethod(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum))
jCallStaticVoidMethod(Class, MethodID, Types, Params) :-
jni_params_put(Params, Types, ParamBuf),
jni_void(143, Class, MethodID, ParamBuf).
%! jCallVoidMethod(+Obj:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum))
jCallVoidMethod(Obj, MethodID, Types, Params) :-
jni_params_put(Params, Types, ParamBuf),
jni_void(63, Obj, MethodID, ParamBuf).
%! jFindClass(+ClassName:findclassname, -Class:jref)
jFindClass(ClassName, Class) :-
jni_func(6, ClassName, Class).
%! jGetArrayLength(+Array:jref, -Size:int)
jGetArrayLength(Array, Size) :-
jni_func(171, Array, Size).
%! jGetBooleanArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:boolean_buf)
jGetBooleanArrayRegion(Array, Start, Len, Buf) :-
jni_void(199, Array, Start, Len, Buf).
%! jGetBooleanField(+Obj:jref, +FieldID:fieldId, -Rbool:boolean)
jGetBooleanField(Obj, FieldID, Rbool) :-
jni_func(96, Obj, FieldID, Rbool).
%! jGetByteArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:byte_buf)
jGetByteArrayRegion(Array, Start, Len, Buf) :-
jni_void(200, Array, Start, Len, Buf).
%! jGetByteField(+Obj:jref, +FieldID:fieldId, -Rbyte:byte)
jGetByteField(Obj, FieldID, Rbyte) :-
jni_func(97, Obj, FieldID, Rbyte).
%! jGetCharArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:char_buf)
jGetCharArrayRegion(Array, Start, Len, Buf) :-
jni_void(201, Array, Start, Len, Buf).
%! jGetCharField(+Obj:jref, +FieldID:fieldId, -Rchar:char)
jGetCharField(Obj, FieldID, Rchar) :-
jni_func(98, Obj, FieldID, Rchar).
%! jGetDoubleArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:double_buf)
jGetDoubleArrayRegion(Array, Start, Len, Buf) :-
jni_void(206, Array, Start, Len, Buf).
%! jGetDoubleField(+Obj:jref, +FieldID:fieldId, -Rdouble:double)
jGetDoubleField(Obj, FieldID, Rdouble) :-
jni_func(103, Obj, FieldID, Rdouble).
%! jGetFieldID(+Class:jref, +Name:fieldName, +Type:type, -FieldID:fieldId)
jGetFieldID(Class, Name, Type, FieldID) :-
jpl_type_to_java_field_descriptor(Type, FD),
jni_func(94, Class, Name, FD, FieldID).
%! jGetFloatArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:float_buf)
jGetFloatArrayRegion(Array, Start, Len, Buf) :-
jni_void(205, Array, Start, Len, Buf).
%! jGetFloatField(+Obj:jref, +FieldID:fieldId, -Rfloat:float)
jGetFloatField(Obj, FieldID, Rfloat) :-
jni_func(102, Obj, FieldID, Rfloat).
%! jGetIntArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:int_buf)
jGetIntArrayRegion(Array, Start, Len, Buf) :-
jni_void(203, Array, Start, Len, Buf).
%! jGetIntField(+Obj:jref, +FieldID:fieldId, -Rint:int)
jGetIntField(Obj, FieldID, Rint) :-
jni_func(100, Obj, FieldID, Rint).
%! jGetLongArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:long_buf)
jGetLongArrayRegion(Array, Start, Len, Buf) :-
jni_void(204, Array, Start, Len, Buf).
%! jGetLongField(+Obj:jref, +FieldID:fieldId, -Rlong:long)
jGetLongField(Obj, FieldID, Rlong) :-
jni_func(101, Obj, FieldID, Rlong).
%! jGetMethodID(+Class:jref, +Name:atom, +Type:type, -MethodID:methodId)
jGetMethodID(Class, Name, Type, MethodID) :-
jpl_type_to_java_method_descriptor(Type, MD),
jni_func(33, Class, Name, MD, MethodID).
%! jGetObjectArrayElement(+Array:jref, +Index:int, -Obj:jref)
jGetObjectArrayElement(Array, Index, Obj) :-
jni_func(173, Array, Index, Obj).
%! jGetObjectClass(+Object:jref, -Class:jref)
jGetObjectClass(Object, Class) :-
jni_func(31, Object, Class).
%! jGetObjectField(+Obj:jref, +FieldID:fieldId, -RObj:jref)
jGetObjectField(Obj, FieldID, Robj) :-
jni_func(95, Obj, FieldID, Robj).
%! jGetShortArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:short_buf)
jGetShortArrayRegion(Array, Start, Len, Buf) :-
jni_void(202, Array, Start, Len, Buf).
%! jGetShortField(+Obj:jref, +FieldID:fieldId, -Rshort:short)
jGetShortField(Obj, FieldID, Rshort) :-
jni_func(99, Obj, FieldID, Rshort).
%! jGetStaticBooleanField(+Class:jref, +FieldID:fieldId, -Rbool:boolean)
jGetStaticBooleanField(Class, FieldID, Rbool) :-
jni_func(146, Class, FieldID, Rbool).
%! jGetStaticByteField(+Class:jref, +FieldID:fieldId, -Rbyte:byte)
jGetStaticByteField(Class, FieldID, Rbyte) :-
jni_func(147, Class, FieldID, Rbyte).
%! jGetStaticCharField(+Class:jref, +FieldID:fieldId, -Rchar:char)
jGetStaticCharField(Class, FieldID, Rchar) :-
jni_func(148, Class, FieldID, Rchar).
%! jGetStaticDoubleField(+Class:jref, +FieldID:fieldId, -Rdouble:double)
jGetStaticDoubleField(Class, FieldID, Rdouble) :-
jni_func(153, Class, FieldID, Rdouble).
%! jGetStaticFieldID(+Class:jref, +Name:fieldName, +Type:type, -FieldID:fieldId)
jGetStaticFieldID(Class, Name, Type, FieldID) :-
jpl_type_to_java_field_descriptor(Type, TD), % cache this?
jni_func(144, Class, Name, TD, FieldID).
%! jGetStaticFloatField(+Class:jref, +FieldID:fieldId, -Rfloat:float)
jGetStaticFloatField(Class, FieldID, Rfloat) :-
jni_func(152, Class, FieldID, Rfloat).
%! jGetStaticIntField(+Class:jref, +FieldID:fieldId, -Rint:int)
jGetStaticIntField(Class, FieldID, Rint) :-
jni_func(150, Class, FieldID, Rint).
%! jGetStaticLongField(+Class:jref, +FieldID:fieldId, -Rlong:long)
jGetStaticLongField(Class, FieldID, Rlong) :-
jni_func(151, Class, FieldID, Rlong).
%! jGetStaticMethodID(+Class:jref, +Name:methodName, +Type:type, -MethodID:methodId)
jGetStaticMethodID(Class, Name, Type, MethodID) :-
jpl_type_to_java_method_descriptor(Type, TD),
jni_func(113, Class, Name, TD, MethodID).
%! jGetStaticObjectField(+Class:jref, +FieldID:fieldId, -RObj:jref)
jGetStaticObjectField(Class, FieldID, Robj) :-
jni_func(145, Class, FieldID, Robj).
%! jGetStaticShortField(+Class:jref, +FieldID:fieldId, -Rshort:short)
jGetStaticShortField(Class, FieldID, Rshort) :-
jni_func(149, Class, FieldID, Rshort).
%! jGetSuperclass(+Class1:jref, -Class2:jref)
jGetSuperclass(Class1, Class2) :-
jni_func(10, Class1, Class2).
%! jIsAssignableFrom(+Class1:jref, +Class2:jref)
jIsAssignableFrom(Class1, Class2) :-
jni_func(11, Class1, Class2, @(true)).
%! jNewBooleanArray(+Length:int, -Array:jref)
jNewBooleanArray(Length, Array) :-
jni_func(175, Length, Array).
%! jNewByteArray(+Length:int, -Array:jref)
jNewByteArray(Length, Array) :-
jni_func(176, Length, Array).
%! jNewCharArray(+Length:int, -Array:jref)
jNewCharArray(Length, Array) :-
jni_func(177, Length, Array).
%! jNewDoubleArray(+Length:int, -Array:jref)
jNewDoubleArray(Length, Array) :-
jni_func(182, Length, Array).
%! jNewFloatArray(+Length:int, -Array:jref)
jNewFloatArray(Length, Array) :-
jni_func(181, Length, Array).
%! jNewIntArray(+Length:int, -Array:jref)
jNewIntArray(Length, Array) :-
jni_func(179, Length, Array).
%! jNewLongArray(+Length:int, -Array:jref)
jNewLongArray(Length, Array) :-
jni_func(180, Length, Array).
%! jNewObject(+Class:jref, +MethodID:methodId, +Types:list(type), +Params:list(datum), -Obj:jref)
jNewObject(Class, MethodID, Types, Params, Obj) :-
jni_params_put(Params, Types, ParamBuf),
jni_func(30, Class, MethodID, ParamBuf, Obj).
%! jNewObjectArray(+Len:int, +Class:jref, +InitVal:jref, -Array:jref)
jNewObjectArray(Len, Class, InitVal, Array) :-
jni_func(172, Len, Class, InitVal, Array).
%! jNewShortArray(+Length:int, -Array:jref)
jNewShortArray(Length, Array) :-
jni_func(178, Length, Array).
%! jSetBooleanArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:boolean_buf)
jSetBooleanArrayRegion(Array, Start, Len, Buf) :-
jni_void(207, Array, Start, Len, Buf).
%! jSetBooleanField(+Obj:jref, +FieldID:fieldId, +Rbool:boolean)
jSetBooleanField(Obj, FieldID, Rbool) :-
jni_void(105, Obj, FieldID, Rbool).
%! jSetByteArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:byte_buf)
jSetByteArrayRegion(Array, Start, Len, Buf) :-
jni_void(208, Array, Start, Len, Buf).
%! jSetByteField(+Obj:jref, +FieldID:fieldId, +Rbyte:byte)
jSetByteField(Obj, FieldID, Rbyte) :-
jni_void(106, Obj, FieldID, Rbyte).
%! jSetCharArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:char_buf)
jSetCharArrayRegion(Array, Start, Len, Buf) :-
jni_void(209, Array, Start, Len, Buf).
%! jSetCharField(+Obj:jref, +FieldID:fieldId, +Rchar:char)
jSetCharField(Obj, FieldID, Rchar) :-
jni_void(107, Obj, FieldID, Rchar).
%! jSetDoubleArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:double_buf)
jSetDoubleArrayRegion(Array, Start, Len, Buf) :-
jni_void(214, Array, Start, Len, Buf).
%! jSetDoubleField(+Obj:jref, +FieldID:fieldId, +Rdouble:double)
jSetDoubleField(Obj, FieldID, Rdouble) :-
jni_void(112, Obj, FieldID, Rdouble).
%! jSetFloatArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:float_buf)
jSetFloatArrayRegion(Array, Start, Len, Buf) :-
jni_void(213, Array, Start, Len, Buf).
%! jSetFloatField(+Obj:jref, +FieldID:fieldId, +Rfloat:float)
jSetFloatField(Obj, FieldID, Rfloat) :-
jni_void(111, Obj, FieldID, Rfloat).
%! jSetIntArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:int_buf)
jSetIntArrayRegion(Array, Start, Len, Buf) :-
jni_void(211, Array, Start, Len, Buf).
%! jSetIntField(+Obj:jref, +FieldID:fieldId, +Rint:int)
jSetIntField(Obj, FieldID, Rint) :-
jni_void(109, Obj, FieldID, Rint).
%! jSetLongArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:long_buf)
jSetLongArrayRegion(Array, Start, Len, Buf) :-
jni_void(212, Array, Start, Len, Buf).
%! jSetLongField(+Obj:jref, +FieldID:fieldId, +Rlong:long)
jSetLongField(Obj, FieldID, Rlong) :-
jni_void(110, Obj, FieldID, Rlong).
%! jSetObjectArrayElement(+Array:jref, +Index:int, +Obj:jref)
jSetObjectArrayElement(Array, Index, Obj) :-
jni_void(174, Array, Index, Obj).
%! jSetObjectField(+Obj:jref, +FieldID:fieldId, +RObj:jref)
jSetObjectField(Obj, FieldID, Robj) :-
jni_void(104, Obj, FieldID, Robj).
%! jSetShortArrayRegion(+Array:jref, +Start:int, +Len:int, +Buf:short_buf)
jSetShortArrayRegion(Array, Start, Len, Buf) :-
jni_void(210, Array, Start, Len, Buf).
%! jSetShortField(+Obj:jref, +FieldID:fieldId, +Rshort:short)
jSetShortField(Obj, FieldID, Rshort) :-
jni_void(108, Obj, FieldID, Rshort).
%! jSetStaticBooleanField(+Class:jref, +FieldID:fieldId, +Rbool:boolean)
jSetStaticBooleanField(Class, FieldID, Rbool) :-
jni_void(155, Class, FieldID, Rbool).
%! jSetStaticByteField(+Class:jref, +FieldID:fieldId, +Rbyte:byte)
jSetStaticByteField(Class, FieldID, Rbyte) :-
jni_void(156, Class, FieldID, Rbyte).
%! jSetStaticCharField(+Class:jref, +FieldID:fieldId, +Rchar:char)
jSetStaticCharField(Class, FieldID, Rchar) :-
jni_void(157, Class, FieldID, Rchar).
%! jSetStaticDoubleField(+Class:jref, +FieldID:fieldId, +Rdouble:double)
jSetStaticDoubleField(Class, FieldID, Rdouble) :-
jni_void(162, Class, FieldID, Rdouble).
%! jSetStaticFloatField(+Class:jref, +FieldID:fieldId, +Rfloat:float)
jSetStaticFloatField(Class, FieldID, Rfloat) :-
jni_void(161, Class, FieldID, Rfloat).
%! jSetStaticIntField(+Class:jref, +FieldID:fieldId, +Rint:int)
jSetStaticIntField(Class, FieldID, Rint) :-
jni_void(159, Class, FieldID, Rint).
%! jSetStaticLongField(+Class:jref, +FieldID:fieldId, +Rlong)
jSetStaticLongField(Class, FieldID, Rlong) :-
jni_void(160, Class, FieldID, Rlong).
%! jSetStaticObjectField(+Class:jref, +FieldID:fieldId, +Robj:jref)
jSetStaticObjectField(Class, FieldID, Robj) :-
jni_void(154, Class, FieldID, Robj).
%! jSetStaticShortField(+Class:jref, +FieldID:fieldId, +Rshort:short)
jSetStaticShortField(Class, FieldID, Rshort) :-
jni_void(158, Class, FieldID, Rshort).
%! jni_params_put(+Params:list(datum), +Types:list(type), -ParamBuf:paramBuf)
%
% The old form used a static buffer, hence was not re-entrant;
% the new form allocates a buffer of one jvalue per arg,
% puts the (converted) args into respective elements, then returns it
% (the caller is responsible for freeing it).
jni_params_put(As, Ts, ParamBuf) :-
jni_ensure_jvm, % in case e.g. NewStringUTF() is called
length(As, N),
jni_type_to_xput_code(jvalue, Xc), % Xc will be 15
jni_alloc_buffer(Xc, N, ParamBuf),
jni_params_put_1(As, 0, Ts, ParamBuf).
%! jni_params_put_1(+Params:list(datum), +N:integer, +JPLTypes:list(type), +ParamBuf:paramBuf)
%
% Params is a (full or partial) list of args-not-yet-stashed.
%
% Types are their (JPL) types (e.g. 'boolean').
%
% N is the arg and buffer index (0+) at which the head of Params is to be stashed.
%
% The old form used a static buffer and hence was non-reentrant;
% the new form uses a dynamically allocated buffer (which oughta be freed after use).
%
% NB if the (user-provided) actual params were to be unsuitable for conversion
% to the method-required types, this would fail silently (without freeing the buffer);
% it's not clear whether the overloaded-method-resolution ensures that all args
% are convertible
jni_params_put_1([], _, [], _).
jni_params_put_1([A|As], N, [Tjni|Ts], ParamBuf) :- % type checking?
( jni_type_to_xput_code(Tjni, Xc)
-> ( A = {Term} % a quoted general term?
-> jni_term_to_jref(Term, Ax) % convert it to a @(Tag) ref to a new Term instance
; A = Ax
),
jni_param_put(N, Xc, Ax, ParamBuf) % foreign
; fail % oughta raise an exception?
),
N2 is N+1,
jni_params_put_1(As, N2, Ts, ParamBuf). % stash remaining params (if any)
%! jni_type_to_xput_code(+JspType, -JniXputCode)
%
% NB JniXputCode determines widening and casting in foreign code
%
% NB the codes could be compiled into jni_method_spec_cache etc.
% instead of, or as well as, types (for - small - efficiency gain)
jni_type_to_xput_code(boolean, 1). % JNI_XPUT_BOOLEAN
jni_type_to_xput_code(byte, 2). % JNI_XPUT_BYTE
jni_type_to_xput_code(char, 3). % JNI_XPUT_CHAR
jni_type_to_xput_code(short, 4). % JNI_XPUT_SHORT
jni_type_to_xput_code(int, 5). % JNI_XPUT_INT
jni_type_to_xput_code(long, 6). % JNI_XPUT_LONG
jni_type_to_xput_code(float, 7). % JNI_XPUT_FLOAT
jni_type_to_xput_code(double, 8). % JNI_XPUT_DOUBLE
jni_type_to_xput_code(class(_,_), 12). % JNI_XPUT_REF
jni_type_to_xput_code(array(_), 12). % JNI_XPUT_REF
jni_type_to_xput_code(jvalue, 15). % JNI_XPUT_JVALUE
%! jpl_class_to_constructor_array(+Class:jref, -MethodArray:jref)
%
% NB might this be done more efficiently in foreign code? or in Java?
jpl_class_to_constructor_array(Cx, Ma) :-
jpl_entityname_to_class('java.lang.Class', CC), % cacheable?
jGetMethodID( CC, getConstructors, method([],array(class([java,lang,reflect],['Constructor']))), MID), % cacheable?
jCallObjectMethod(Cx, MID, [], [], Ma).
%! jpl_class_to_constructors(+Class:jref, -Methods:list(jref))
jpl_class_to_constructors(Cx, Ms) :-
jpl_class_to_constructor_array(Cx, Ma),
jpl_object_array_to_list(Ma, Ms).
%! jpl_class_to_field_array(+Class:jref, -FieldArray:jref)
jpl_class_to_field_array(Cx, Fa) :-
jpl_entityname_to_class('java.lang.Class', CC), % cacheable?
jGetMethodID(CC, getFields, method([],array(class([java,lang,reflect],['Field']))), MID), % cacheable?
jCallObjectMethod(Cx, MID, [], [], Fa).
%! jpl_class_to_fields(+Class:jref, -Fields:list(jref))
%
% NB do this in Java (ditto for methods)?
jpl_class_to_fields(C, Fs) :-
jpl_class_to_field_array(C, Fa),
jpl_object_array_to_list(Fa, Fs).
%! jpl_class_to_method_array(+Class:jref, -MethodArray:jref)
%
% NB migrate into foreign code for efficiency?
jpl_class_to_method_array(Cx, Ma) :-
jpl_entityname_to_class('java.lang.Class', CC), % cacheable?
jGetMethodID(CC, getMethods, method([],array(class([java,lang,reflect],['Method']))), MID), % cacheable?
jCallObjectMethod(Cx, MID, [], [], Ma).
%! jpl_class_to_methods(+Class:jref, -Methods:list(jref))
%
% NB also used for constructors.
%
% NB do this in Java (ditto for fields)?
jpl_class_to_methods(Cx, Ms) :-
jpl_class_to_method_array(Cx, Ma),
jpl_object_array_to_list(Ma, Ms).
%! jpl_constructor_to_modifiers(+Method, -Modifiers)
%
% NB migrate into foreign code for efficiency?
jpl_constructor_to_modifiers(X, Ms) :-
jpl_entityname_to_class('java.lang.reflect.Constructor', Cx), % cached?
jpl_method_to_modifiers_1(X, Cx, Ms).
%! jpl_constructor_to_name(+Method:jref, -Name:atom)
%
% It is a JNI convention that each constructor behaves (at least,
% for reflection), as a method whose name is '<init>'.
jpl_constructor_to_name(_X, '<init>').
%! jpl_constructor_to_parameter_types(+Method:jref, -ParameterTypes:list(type))
%
% NB migrate to foreign code for efficiency?
jpl_constructor_to_parameter_types(X, Tfps) :-
jpl_entityname_to_class('java.lang.reflect.Constructor', Cx), % cached?
jpl_method_to_parameter_types_1(X, Cx, Tfps).
%! jpl_constructor_to_return_type(+Method:jref, -Type:type)
%
% It is a JNI convention that, for the purposes of retrieving a MethodID,
% a constructor has a return type of 'void'.
jpl_constructor_to_return_type(_X, void).
%! jpl_field_spec(+Type:type, -Index:integer, -Name:atom, -Modifiers, -MID:mId, -FieldType:type)
%
% I'm unsure whether arrays have fields, but if they do, this will handle them correctly.
jpl_field_spec(T, I, N, Mods, MID, Tf) :-
( jpl_field_spec_is_cached(T)
-> jpl_field_spec_cache(T, I, N, Mods, MID, Tf)
; jpl_type_to_class(T, C),
jpl_class_to_fields(C, Fs),
( T = array(_BaseType) % regardless of base type...
-> Tci = array(_) % ...the "cache index" type is this
; Tci = T
),
jpl_field_spec_1(C, Tci, Fs),
jpl_assert(jpl_field_spec_is_cached(Tci)),
jpl_field_spec_cache(Tci, I, N, Mods, MID, Tf)
).
jpl_field_spec_1(C, Tci, Fs) :-
( nth1(I, Fs, F),
jpl_field_to_name(F, N),
jpl_field_to_modifiers(F, Mods),
jpl_field_to_type(F, Tf),
( member(static, Mods)
-> jGetStaticFieldID(C, N, Tf, MID)
; jGetFieldID(C, N, Tf, MID)
),
jpl_assert(jpl_field_spec_cache(Tci,I,N,Mods,MID,Tf)),
fail
; true
).
%! jpl_field_to_modifiers(+Field:jref, -Modifiers:ordset(modifier))
jpl_field_to_modifiers(F, Ms) :-
jpl_entityname_to_class('java.lang.reflect.Field', Cf),
jpl_method_to_modifiers_1(F, Cf, Ms).
%! jpl_field_to_name(+Field:jref, -Name:atom)
jpl_field_to_name(F, N) :-
jpl_entityname_to_class('java.lang.reflect.Field', Cf),
jpl_member_to_name_1(F, Cf, N).
%! jpl_field_to_type(+Field:jref, -Type:type)
jpl_field_to_type(F, Tf) :-
jpl_entityname_to_class('java.lang.reflect.Field', Cf),
jGetMethodID(Cf, getType, method([],class([java,lang],['Class'])), MID),
jCallObjectMethod(F, MID, [], [], Cr),
jpl_class_to_type(Cr, Tf).
%! jpl_method_spec(+Type:type, -Index:integer, -Name:atom, -Arity:integer, -Modifiers:ordset(modifier), -MID:methodId, -ReturnType:type, -ParameterTypes:list(type))
%
% Generates pertinent details of all accessible methods of Type (class/2 or array/1),
% populating or using the cache as appropriate.
jpl_method_spec(T, I, N, A, Mods, MID, Tr, Tfps) :-
( jpl_method_spec_is_cached(T)
-> jpl_method_spec_cache(T, I, N, A, Mods, MID, Tr, Tfps)
; jpl_type_to_class(T, C),
jpl_class_to_constructors(C, Xs),
jpl_class_to_methods(C, Ms),
( T = array(_BaseType) % regardless of base type...
-> Tci = array(_) % ...the "cache index" type is this
; Tci = T
),
jpl_method_spec_1(C, Tci, Xs, Ms),
jpl_assert(jpl_method_spec_is_cached(Tci)),
jpl_method_spec_cache(Tci, I, N, A, Mods, MID, Tr, Tfps)
).
%! jpl_method_spec_1(+Class:jref, +CacheIndexType:partialType, +Constructors:list(method), +Methods:list(method))
%
% If the original type is e.g. array(byte) then CacheIndexType is array(_) else it is that type.
jpl_method_spec_1(C, Tci, Xs, Ms) :-
( ( nth1(I, Xs, X), % generate constructors, numbered from 1
jpl_constructor_to_name(X, N),
jpl_constructor_to_modifiers(X, Mods),
jpl_constructor_to_return_type(X, Tr),
jpl_constructor_to_parameter_types(X, Tfps)
; length(Xs, J0),
nth1(J, Ms, M), % generate members, continuing numbering
I is J0+J,
jpl_method_to_name(M, N),
jpl_method_to_modifiers(M, Mods),
jpl_method_to_return_type(M, Tr),
jpl_method_to_parameter_types(M, Tfps)
),
length(Tfps, A), % arity
( member(static, Mods)
-> jGetStaticMethodID(C, N, method(Tfps,Tr), MID)
; jGetMethodID(C, N, method(Tfps,Tr), MID)
),
jpl_assert(jpl_method_spec_cache(Tci,I,N,A,Mods,MID,Tr,Tfps)),
fail
; true
).
%! jpl_method_to_modifiers(+Method:jref, -ModifierSet:ordset(modifier))
jpl_method_to_modifiers(M, Ms) :-
jpl_entityname_to_class('java.lang.reflect.Method', Cm),
jpl_method_to_modifiers_1(M, Cm, Ms).
%! jpl_method_to_modifiers_1(+Method:jref, +ConstructorClass:jref, -ModifierSet:ordset(modifier))
jpl_method_to_modifiers_1(XM, Cxm, Ms) :-
jGetMethodID(Cxm, getModifiers, method([],int), MID),
jCallIntMethod(XM, MID, [], [], I),
jpl_modifier_int_to_modifiers(I, Ms).
%! jpl_method_to_name(+Method:jref, -Name:atom)
jpl_method_to_name(M, N) :-
jpl_entityname_to_class('java.lang.reflect.Method', CM),
jpl_member_to_name_1(M, CM, N).
%! jpl_member_to_name_1(+Member:jref, +CM:jref, -Name:atom)
jpl_member_to_name_1(M, CM, N) :-
jGetMethodID(CM, getName, method([],class([java,lang],['String'])), MID),
jCallObjectMethod(M, MID, [], [], N).
%! jpl_method_to_parameter_types(+Method:jref, -Types:list(type))
jpl_method_to_parameter_types(M, Tfps) :-
jpl_entityname_to_class('java.lang.reflect.Method', Cm),
jpl_method_to_parameter_types_1(M, Cm, Tfps).
%! jpl_method_to_parameter_types_1(+XM:jref, +Cxm:jref, -Tfps:list(type))
%
% XM is (a JPL ref to) an instance of java.lang.reflect.[Constructor|Method]
jpl_method_to_parameter_types_1(XM, Cxm, Tfps) :-
jGetMethodID(Cxm, getParameterTypes, method([],array(class([java,lang],['Class']))), MID),
jCallObjectMethod(XM, MID, [], [], Atp),
jpl_object_array_to_list(Atp, Ctps),
jpl_classes_to_types(Ctps, Tfps).
%! jpl_method_to_return_type(+Method:jref, -Type:type)
jpl_method_to_return_type(M, Tr) :-
jpl_entityname_to_class('java.lang.reflect.Method', Cm),
jGetMethodID(Cm, getReturnType, method([],class([java,lang],['Class'])), MID),
jCallObjectMethod(M, MID, [], [], Cr),
jpl_class_to_type(Cr, Tr).
jpl_modifier_bit(public, 0x001).
jpl_modifier_bit(private, 0x002).
jpl_modifier_bit(protected, 0x004).
jpl_modifier_bit(static, 0x008).
jpl_modifier_bit(final, 0x010).
jpl_modifier_bit(synchronized, 0x020).
jpl_modifier_bit(volatile, 0x040).
jpl_modifier_bit(transient, 0x080).
jpl_modifier_bit(native, 0x100).
jpl_modifier_bit(interface, 0x200).
jpl_modifier_bit(abstract, 0x400).
%! jpl_modifier_int_to_modifiers(+Int:integer, -ModifierSet:ordset(modifier))
%
% ModifierSet is an ordered (hence canonical) list,
% possibly empty (although I suspect never in practice?),
% of modifier atoms, e.g. [public,static]
jpl_modifier_int_to_modifiers(I, Ms) :-
setof(
M, % should use e.g. set_of_all/3
B^( jpl_modifier_bit(M, B),
(B /\ I) =\= 0
),
Ms
).
%! jpl_cache_type_of_ref(+Type:type, +Ref:jref)
%
% Type must be a proper (concrete) JPL type
%
% Ref must be a proper JPL reference (not void)
%
% Type is memoed (if policy so dictates) as the type of the referenced object (unless it's null)
% by iref (so as not to disable atom-based GC)
%
% NB obsolete lemmas must be watched-out-for and removed
jpl_cache_type_of_ref(T, Ref) :-
( jpl_assert_policy(jpl_iref_type_cache(_,_), no)
-> true
; \+ ground(T) % shouldn't happen (implementation error)
-> write('[jpl_cache_type_of_ref/2: arg 1 is not ground]'), nl, % oughta throw an exception
fail
; Ref == @(null) % a null ref? (this is valid)
-> true % silently ignore it
; ( jpl_iref_type_cache(Ref, TC) % we expect TC == T
-> ( T == TC
-> true
; % write('[JPL: found obsolete tag-type lemma...]'), nl, % or keep statistics? (why?)
retractall(jpl_iref_type_cache(Ref,_)),
jpl_assert(jpl_iref_type_cache(Ref,T))
)
; jpl_assert(jpl_iref_type_cache(Ref,T))
)
).
%! jpl_class_to_ancestor_classes(+Class:jref, -AncestorClasses:list(jref))
%
% AncestorClasses will be a list of (JPL references to) instances of java.lang.Class
% denoting the "implements" lineage (?), nearest first
% (the first member denotes the class which Class directly implements,
% the next (if any) denotes the class which *that* class implements,
% and so on to java.lang.Object)
jpl_class_to_ancestor_classes(C, Cas) :-
( jpl_class_to_super_class(C, Ca)
-> Cas = [Ca|Cas2],
jpl_class_to_ancestor_classes(Ca, Cas2)
; Cas = []
).
%! jpl_class_to_classname(+Class:jref, -ClassName:entityName)
%
% Class is a reference to a class object.
%
% ClassName is its canonical (?) source-syntax (dotted) name,
% e.g. =|'java.util.Date'|=
%
% NB not used outside jni_junk and jpl_test (is this (still) true?)
%
% NB oughta use the available caches (but their indexing doesn't suit)
%
% TODO This shouldn't exist as we have jpl_class_to_entityname/2 ???
%
% The implementation actually just calls `Class.getName()` to get
% the entity name (dotted name)
jpl_class_to_classname(C, CN) :-
jpl_call(C, getName, [], CN).
%! jpl_class_to_entityname(+Class:jref, -EntityName:atom)
%
% The `Class` is a reference to a class object.
% The `EntityName` is the string as returned by `Class.getName()`.
%
% This predicate actually calls `Class.getName()` on the class corresponding to `Class`.
%
% @see https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#getName()
jpl_class_to_entityname(Class, EntityName) :-
jpl_entityname_to_class('java.lang.Class', CC), % cached?
jGetMethodID(CC, getName, method([],class([java,lang],['String'])), MIDgetName), % does this ever change?
jCallObjectMethod(Class, MIDgetName, [], [], S),
S = EntityName.
jpl_class_to_super_class(C, Cx) :-
jGetSuperclass(C, Cx),
Cx \== @(null), % as returned when C is java.lang.Object, i.e. no superclass
jpl_cache_type_of_ref(class([java,lang],['Class']), Cx).
%! jpl_class_to_type(+Class:jref, -Type:jpl_type)
%
% The `Class` is a reference to a (Java Universe) instance of `java.lang.Class`.
% The `Type` is the (Prolog Universe) JPL type term denoting the same type as does
% the instance of `Class`.
%
% NB should ensure that, if not found in cache, then cache is updated.
%
% Intriguingly, getParameterTypes returns class objects (undocumented AFAIK) with names
% 'boolean', 'byte' etc. and even 'void' (?!)
jpl_class_to_type(Class, Type) :-
assertion(blob(Class,jref)), % "Class" cannot be uninstantiated and must be blob jref
( jpl_class_tag_type_cache(Class, Tx) % found in cache!
-> true
; jpl_class_to_entityname(Class, EN), % uncached ??
jpl_entityname_to_type(EN, Tr),
jpl_type_to_canonical_type(Tr, Tx), % map e.g. class([],[byte]) -> byte (TODO: Looks like a dirty fix; I would say this is not needed now)
jpl_assert(jpl_class_tag_type_cache(Class,Tx))
-> true % the elseif goal should be determinate, but just in case... TODO: Replace by a once
),
Type = Tx.
jpl_classes_to_types([], []).
jpl_classes_to_types([C|Cs], [T|Ts]) :-
jpl_class_to_type(C, T),
jpl_classes_to_types(Cs, Ts).
%! jpl_entityname_to_class(+EntityName:atom, -Class:jref)
%
% `EntityName` is the entity name to be mapped to a class reference.
%
% `Class` is a (canonical) reference to the corresponding class object.
%
% NB uses caches where the class is already encountered.
jpl_entityname_to_class(EntityName, Class) :-
jpl_entityname_to_type(EntityName, T), % cached
jpl_type_to_class(T, Class). % cached
%! jpl_classname_to_class(+EntityName:atom, -Class:jref)
%
% `EntityName` is the entity name to be mapped to a class reference.
%
% `Class` is a (canonical) reference to the corresponding class object.
%
% NB uses caches where the class has already been mapped once before.
jpl_classname_to_class(EntityName, Class) :-
jpl_entityname_to_class(EntityName, Class). % wrapper for historical usage/export
% =========================================================
% Java Entity Name (atom) <----> JPL Type (Prolog term)
% =========================================================
%! jpl_entityname_to_type(+EntityName:atom, -Type:jpl_type)
%
% `EntityName` is the entity name (an atom) denoting a Java type,
% to be mapped to a JPL type. This is the string returned by
% `java.lang.Class.getName()`.
%
% `Type` is the JPL type (a ground term) denoting the same Java type
% as `EntityName` does.
%
% The Java type in question may be a reference type (class, abstract
% class, interface), and array type or a primitive, including "void".
%
% Examples:
%
% ~~~
% int int
% integer class([],[integer])
% void void
% char char
% double double
% [D array(double)
% [[I array(array(int))
% java.lang.String class([java,lang],['String'])
% [Ljava.lang.String; array(class([java,lang],['String']))
% [[Ljava.lang.String; array(array(class([java, lang], ['String'])))
% [[[Ljava.util.Calendar; array(array(array(class([java,util],['Calendar']))))
% foo.bar.Bling$Blong class([foo,bar],['Bling','Blong'])
% ~~~
%
% NB uses caches where the class has already been mapped once before.
%
% @see https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#getName()
jpl_entityname_to_type(EntityName, Type) :-
assertion(atomic(EntityName)),
(jpl_classname_type_cache(EntityName, Tx)
-> (Tx = Type)
; jpl_entityname_to_type_with_caching(EntityName, Type)).
jpl_entityname_to_type_with_caching(EN, T) :-
(atom_codes(EN,Cs),phrase(jpl_entityname(T), Cs))
-> jpl_assert(jpl_classname_type_cache(EN,T)).
%! jpl_type_to_entityname(+Type:jpl_type, -EntityName:atom)
%
% This is the converse of jpl_entityname_to_type/2
jpl_type_to_entityname(Type, EntityName) :-
assertion(ground(Type)),
phrase(jpl_entityname(Type), Cs),
atom_codes(EntityName, Cs).
%! jpl_classname_to_type(+EntityName:atom, -Type:jpl_type)
%
% This is a wrapper around jpl_entityname_to_type/2 to keep the
% old exported predicate alive. The name of this predicate does
% not fully reflect that it actually deals in entity names
% instead of just class names.
%
% Use jpl_entityname_to_type/2 in preference.
jpl_classname_to_type(EntityName, Type) :-
jpl_entityname_to_type(EntityName, Type).
%! jpl_type_to_classname(+Type:jpl_type, -EntityName:atom)
%
% This is a wrapper around jpl_type_to_entityname/2 to keep the
% old exported predicate alive. The name of this predicate does
% not fully reflect that it actually deals in entity names
% instead of just class names.
%
% Use jpl_type_to_entityname/2 in preference.
% N.B. This predicate is exported, but internally it is only used to generate
% exception information.
jpl_type_to_classname(Type, EntityName) :-
jpl_type_to_entityname(Type, EntityName).
% =========================================================
%! jpl_datum_to_type(+Datum:datum, -Type:type)
%
% Datum must be a JPL representation of an instance of one (or more) Java types;
%
% Type is the unique most specialised type of which Datum denotes an instance;
%
% NB 3 is an instance of byte, char, short, int and long,
% of which byte and char are the joint, overlapping most specialised types,
% so this relates 3 to the pseudo subtype 'char_byte';
%
% @see jpl_type_to_preferred_concrete_type/2 for converting inferred types to instantiable types
jpl_datum_to_type(D, T) :-
( jpl_value_to_type(D, T)
-> true
; jpl_ref_to_type(D, T)
-> true
; nonvar(D),
D = {Term}
-> ( cyclic_term(Term)
-> throwme(jpl_datum_to_type,is_cyclic(Term))
; atom(Term)
-> T = class([org,jpl7],['Atom'])
; integer(Term)
-> T = class([org,jpl7],['Integer'])
; float(Term)
-> T = class([org,jpl7],['Float'])
; var(Term)
-> T = class([org,jpl7],['Variable'])
; T = class([org,jpl7],['Compound'])
)
).
jpl_datums_to_most_specific_common_ancestor_type([D], T) :-
jpl_datum_to_type(D, T).
jpl_datums_to_most_specific_common_ancestor_type([D1,D2|Ds], T0) :-
jpl_datum_to_type(D1, T1),
jpl_type_to_ancestor_types(T1, Ts1),
jpl_datums_to_most_specific_common_ancestor_type_1([D2|Ds], [T1|Ts1], [T0|_]).
jpl_datums_to_most_specific_common_ancestor_type_1([], Ts, Ts).
jpl_datums_to_most_specific_common_ancestor_type_1([D|Ds], Ts1, Ts0) :-
jpl_datum_to_type(D, Tx),
jpl_lineage_types_type_to_common_lineage_types(Ts1, Tx, Ts2),
jpl_datums_to_most_specific_common_ancestor_type_1(Ds, Ts2, Ts0).
%! jpl_datums_to_types(+Datums:list(datum), -Types:list(type))
%
% Each member of Datums is a JPL value or reference,
% denoting an instance of some Java type,
% and the corresponding member of Types denotes the most specialised type
% of which it is an instance (including some I invented for the overlaps
% between e.g. char and short).
jpl_datums_to_types([], []).
jpl_datums_to_types([D|Ds], [T|Ts]) :-
jpl_datum_to_type(D, T),
jpl_datums_to_types(Ds, Ts).
%! jpl_ground_is_type(+X:jpl_type)
%
% `X`, known to be ground, is (or at least superficially resembles :-) a JPL type.
%
% A (more complete) alternative would be to try to transfrom the `X` into its
% entityname and see whether that works.
jpl_ground_is_type(X) :-
jpl_primitive_type(X),
!.
jpl_ground_is_type(array(X)) :-
jpl_ground_is_type(X).
jpl_ground_is_type(class(_,_)). % Should one check that the anonymous params are list of atoms, with the second list nonempty?
jpl_ground_is_type(method(_,_)). % Additional checks possible
jpl_lineage_types_type_to_common_lineage_types(Ts, Tx, Ts0) :-
( append(_, [Tx|Ts2], Ts)
-> [Tx|Ts2] = Ts0
; jpl_type_to_super_type(Tx, Tx2)
-> jpl_lineage_types_type_to_common_lineage_types(Ts, Tx2, Ts0)
).
jpl_non_var_is_object_type(class(_,_)).
jpl_non_var_is_object_type(array(_)).
%! jpl_object_array_to_list(+Array:jref, -Values:list(datum))
%
% Values is a list of JPL values (primitive values or object references)
% representing the respective elements of Array.
jpl_object_array_to_list(A, Vs) :-
jpl_array_to_length(A, N),
jpl_object_array_to_list_1(A, 0, N, Vs).
%! jpl_object_array_to_list_1(+A, +I, +N, -Xs)
jpl_object_array_to_list_1(A, I, N, Xs) :-
( I == N
-> Xs = []
; jGetObjectArrayElement(A, I, X),
Xs = [X|Xs2],
J is I+1,
jpl_object_array_to_list_1(A, J, N, Xs2)
).
%! jpl_object_to_class(+Object:jref, -Class:jref)
%
% fails silently if Object is not a valid reference to a Java object
%
% Class is a (canonical) reference to the (canonical) class object
% which represents the class of Object
%
% NB what's the point of caching the type if we don't look there first?
jpl_object_to_class(Obj, C) :-
jpl_is_object(Obj),
jGetObjectClass(Obj, C),
jpl_cache_type_of_ref(class([java,lang],['Class']), C).
%! jpl_object_to_type(+Object:jref, -Type:type)
%
% Object must be a proper JPL reference to a Java object
% (i.e. a class or array instance, but not null, void or String).
%
% Type is the JPL type of that object.
jpl_object_to_type(Ref, Type) :-
jpl_is_object(Ref),
( jpl_iref_type_cache(Ref, T)
-> true % T is Tag's type
; jpl_object_to_class(Ref, Cobj), % else get ref to class obj
jpl_class_to_type(Cobj, T), % get type of class it denotes
jpl_assert(jpl_iref_type_cache(Ref,T))
),
Type = T.
jpl_object_type_to_super_type(T, Tx) :-
( ( T = class(_,_)
; T = array(_)
)
-> jpl_type_to_class(T, C),
jpl_class_to_super_class(C, Cx),
Cx \== @(null),
jpl_class_to_type(Cx, Tx)
).
%! jpl_primitive_buffer_to_array(+Type, +Xc, +Bp, +I, +Size, -Vcs)
%
% Bp points to a buffer of (sufficient) Type values.
%
% Vcs will be unbound on entry,
% and on exit will be a list of Size of them, starting at index I
% (the buffer is indexed from zero)
jpl_primitive_buffer_to_array(T, Xc, Bp, I, Size, [Vc|Vcs]) :-
jni_fetch_buffer_value(Bp, I, Vc, Xc),
Ix is I+1,
( Ix < Size
-> jpl_primitive_buffer_to_array(T, Xc, Bp, Ix, Size, Vcs)
; Vcs = []
).
%! jpl_primitive_type(-Type:atom) is nondet
%
% Type is an atomic JPL representation of one of Java's primitive types.
% N.B: `void` is not included.
%
% ==
% ?- setof(Type, jpl_primitive_type(Type), Types).
% Types = [boolean, byte, char, double, float, int, long, short].
% ==
jpl_primitive_type(boolean).
jpl_primitive_type(char).
jpl_primitive_type(byte).
jpl_primitive_type(short).
jpl_primitive_type(int). % N.B. "int" not "integer"
jpl_primitive_type(long).
jpl_primitive_type(float).
jpl_primitive_type(double).
%! jpl_primitive_type_default_value(-Type:type, -Value:datum)
%
% Each element of any array of (primitive) Type created by jpl_new/3,
% or any instance of (primitive) Type created by jpl_new/3,
% will be initialised to Value (to mimic Java semantics).
jpl_primitive_type_default_value(boolean, @(false)).
jpl_primitive_type_default_value(char, 0).
jpl_primitive_type_default_value(byte, 0).
jpl_primitive_type_default_value(short, 0).
jpl_primitive_type_default_value(int, 0).
jpl_primitive_type_default_value(long, 0).
jpl_primitive_type_default_value(float, 0.0).
jpl_primitive_type_default_value(double, 0.0).
jpl_primitive_type_super_type(T, Tx) :-
( jpl_type_fits_type_direct_prim(T, Tx)
; jpl_type_fits_type_direct_xtra(T, Tx)
).
%! jpl_primitive_type_term_to_value(+Type, +Term, -Val)
%
% Term, after widening iff appropriate, represents an instance of Type.
%
% Val is the instance of Type which it represents (often the same thing).
%
% NB currently used only by jpl_new_1 when creating an "instance"
% of a primitive type (which may be misguided completism - you can't
% do that in Java)
jpl_primitive_type_term_to_value(Type, Term, Val) :-
once(jpl_primitive_type_term_to_value_1(Type, Term, Val)). % make deterministic
%! jpl_primitive_type_term_to_value_1(+Type, +RawValue, -WidenedValue)
%
% I'm not worried about structure duplication here.
%
% NB this oughta be done in foreign code.
jpl_primitive_type_term_to_value_1(boolean, @(false), @(false)).
jpl_primitive_type_term_to_value_1(boolean, @(true), @(true)).
jpl_primitive_type_term_to_value_1(char, I, I) :-
integer(I),
I >= 0,
I =< 65535. % (2**16)-1.
jpl_primitive_type_term_to_value_1(byte, I, I) :-
integer(I),
I >= 128, % -(2**7)
I =< 127. % (2**7)-1
jpl_primitive_type_term_to_value_1(short, I, I) :-
integer(I),
I >= -32768, % -(2**15)
I =< 32767. % (2**15)-1
jpl_primitive_type_term_to_value_1(int, I, I) :-
integer(I),
I >= -2147483648, % -(2**31)
I =< 2147483647. % (2**31)-1
jpl_primitive_type_term_to_value_1(long, I, I) :-
integer(I),
I >= -9223372036854775808, % -(2**63)
I =< 9223372036854775807. % (2**63)-1
jpl_primitive_type_term_to_value_1(float, V, F) :-
( integer(V)
-> F is float(V)
; float(V)
-> F = V
).
jpl_primitive_type_term_to_value_1(double, V, F) :-
( integer(V)
-> F is float(V)
; float(V)
-> F = V
).
jpl_primitive_type_to_ancestor_types(T, Ts) :-
( jpl_primitive_type_super_type(T, Ta)
-> Ts = [Ta|Tas],
jpl_primitive_type_to_ancestor_types(Ta, Tas)
; Ts = []
).
jpl_primitive_type_to_super_type(T, Tx) :-
jpl_primitive_type_super_type(T, Tx).
%! jpl_ref_to_type(+Ref:jref, -Type:type)
%
% Ref must be a proper JPL reference (to an object, null or void).
%
% Type is its type.
jpl_ref_to_type(Ref, T) :-
( Ref == @(null)
-> T = null
; Ref == @(void)
-> T = void
; jpl_object_to_type(Ref, T)
).
%! jpl_tag_to_type(+Tag:tag, -Type:type)
%
% Tag must be an (atomic) object tag.
%
% Type is its type (either from the cache or by reflection).
% OBSOLETE
jpl_tag_to_type(Tag, Type) :-
jni_tag_to_iref(Tag, Iref),
( jpl_iref_type_cache(Iref, T)
-> true % T is Tag's type
; jpl_object_to_class(@(Tag), Cobj), % else get ref to class obj
jpl_class_to_type(Cobj, T), % get type of class it denotes
jpl_assert(jpl_iref_type_cache(Iref,T))
),
Type = T.
%! jpl_type_fits_type(+TypeX:type, +TypeY:type) is semidet
%
% TypeX and TypeY must each be proper JPL types.
%
% This succeeds iff TypeX is assignable to TypeY.
jpl_type_fits_type(Tx, Ty) :-
once(jpl_type_fits_type_1(Tx, Ty)). % make deterministic
%! jpl_type_fits_type_1(+T1:type, +T2:type)
%
% NB it doesn't matter that this leaves choicepoints; it serves only jpl_type_fits_type/2
jpl_type_fits_type_1(T, T).
jpl_type_fits_type_1(class(Ps1,Cs1), class(Ps2,Cs2)) :-
jpl_type_to_class(class(Ps1,Cs1), C1),
jpl_type_to_class(class(Ps2,Cs2), C2),
jIsAssignableFrom(C1, C2).
jpl_type_fits_type_1(array(T1), class(Ps2,Cs2)) :-
jpl_type_to_class(array(T1), C1),
jpl_type_to_class(class(Ps2,Cs2), C2),
jIsAssignableFrom(C1, C2).
jpl_type_fits_type_1(array(T1), array(T2)) :-
jpl_type_to_class(array(T1), C1),
jpl_type_to_class(array(T2), C2),
jIsAssignableFrom(C1, C2).
jpl_type_fits_type_1(null, class(_,_)).
jpl_type_fits_type_1(null, array(_)).
jpl_type_fits_type_1(T1, T2) :-
jpl_type_fits_type_xprim(T1, T2).
jpl_type_fits_type_direct_prim(float, double).
jpl_type_fits_type_direct_prim(long, float).
jpl_type_fits_type_direct_prim(int, long).
jpl_type_fits_type_direct_prim(char, int).
jpl_type_fits_type_direct_prim(short, int).
jpl_type_fits_type_direct_prim(byte, short).
jpl_type_fits_type_direct_xprim(Tp, Tq) :-
jpl_type_fits_type_direct_prim(Tp, Tq).
jpl_type_fits_type_direct_xprim(Tp, Tq) :-
jpl_type_fits_type_direct_xtra(Tp, Tq).
%! jpl_type_fits_type_direct_xtra(-PseudoType:type, -ConcreteType:type)
%
% This defines the direct subtype-supertype relationships
% which involve the intersection pseudo types =|char_int|=, =|char_short|= and =|char_byte|=
jpl_type_fits_type_direct_xtra(char_int, int). % char_int is a direct subtype of int
jpl_type_fits_type_direct_xtra(char_int, char). % etc.
jpl_type_fits_type_direct_xtra(char_short, short).
jpl_type_fits_type_direct_xtra(char_short, char).
jpl_type_fits_type_direct_xtra(char_byte, byte).
jpl_type_fits_type_direct_xtra(char_byte, char).
jpl_type_fits_type_direct_xtra(overlong, float). % 6/Oct/2006 experiment
%! jpl_type_fits_type_xprim(-Tp, -T) is nondet
%
% NB serves only jpl_type_fits_type_1/2
jpl_type_fits_type_xprim(Tp, T) :-
jpl_type_fits_type_direct_xprim(Tp, Tq),
( Tq = T
; jpl_type_fits_type_xprim(Tq, T)
).
%! jpl_type_to_ancestor_types(+T:type, -Tas:list(type))
%
% This does not accommodate the assignability of null,
% but that's OK (?) since "type assignability" and "type ancestry" are not equivalent.
jpl_type_to_ancestor_types(T, Tas) :-
( ( T = class(_,_)
; T = array(_)
)
-> jpl_type_to_class(T, C),
jpl_class_to_ancestor_classes(C, Cas),
jpl_classes_to_types(Cas, Tas)
; jpl_primitive_type_to_ancestor_types(T, Tas)
-> true
).
%! jpl_type_to_canonical_type(+Type:type, -CanonicalType:type)
%
% Type must be a type, not necessarily canonical.
%
% CanonicalType will be equivalent and canonical.
%
% Example
% ==
% ?- jpl:jpl_type_to_canonical_type(class([],[byte]), T).
% T = byte.
% ==
jpl_type_to_canonical_type(array(T), array(Tc)) :-
!,
jpl_type_to_canonical_type(T, Tc).
jpl_type_to_canonical_type(class([],[void]), void) :-
!.
jpl_type_to_canonical_type(class([],[N]), N) :-
jpl_primitive_type(N),
!.
jpl_type_to_canonical_type(class(Ps,Cs), class(Ps,Cs)) :-
!.
jpl_type_to_canonical_type(void, void) :-
!.
jpl_type_to_canonical_type(P, P) :-
jpl_primitive_type(P).
%! jpl_type_to_class(+Type:jpl_type, -Class:jref)
%
% `Type` is the JPL type, a ground term designating a class or an array type.
%
% Incomplete types are now never cached (or otherwise passed around).
%
% jFindClass throws an exception if FCN can't be found.
jpl_type_to_class(Type, Class) :-
(ground(Type)
-> true
; throwme(jpl_type_to_class,arg1_is_var)), % outta here if not ground
(jpl_class_tag_type_cache(RefB, Type)
-> true
; ( jpl_type_to_java_findclass_descriptor(Type, FCN)
-> jFindClass(FCN, RefB), % which caches type of RefB
jpl_cache_type_of_ref(class([java,lang],['Class']), RefB) % 9/Nov/2004 bugfix (?)
),
jpl_assert(jpl_class_tag_type_cache(RefB,Type))
),
Class = RefB.
%! jpl_type_to_java_field_descriptor(+Type:jpl_type, -Descriptor:atom)
%
% Type (the JPL type, a Prolog term) is mapped to the corresponding stringy
% Java field descriptor (an atom)
%
% TODO: I'd cache this, but I'd prefer more efficient indexing on types (hashed?)
jpl_type_to_java_field_descriptor(T, FD) :-
% once(phrase(jpl_field_descriptor(T,slashy), Cs)), % make deterministic
phrase(jpl_field_descriptor(T,slashy), Cs), % make deterministic
atom_codes(FD, Cs).
%! jpl_type_to_java_method_descriptor(+Type:jpl_type, -Descriptor:atom)
%
% Type (the JPL type, a Prolog term) is mapped to the corresponding stringy
% Java method descriptor (an atom)
%
% TODO: Caching might be nice (but is it worth it?)
jpl_type_to_java_method_descriptor(T, MD) :-
% once(phrase(jpl_method_descriptor(T), Cs)), % make deterministic (should not be needed)
phrase(jpl_method_descriptor(T), Cs),
atom_codes(MD, Cs).
%! jpl_type_to_java_findclass_descriptor(+Type:jpl_type, -Descriptor:atom)
%
% Type (the JPL type, a Prolog term) is mapped to the corresponding stringy
% Java findclass descriptor (an atom) to be used for JNI's "FindClass" function.
jpl_type_to_java_findclass_descriptor(T, FCD) :-
% once(phrase(jpl_findclass_descriptor(T), Cs)), % make deterministic (should not be needed)
phrase(jpl_findclass_descriptor(T), Cs),
atom_codes(FCD, Cs).
%! jpl_type_to_super_type(+Type:type, -SuperType:type)
%
% Type should be a proper JPL type.
%
% SuperType is the (at most one) type which it directly implements (if it's a class).
%
% If Type denotes a class, this works only if that class can be found.
jpl_type_to_super_type(T, Tx) :-
( jpl_object_type_to_super_type(T, Tx)
-> true
; jpl_primitive_type_to_super_type(T, Tx)
-> true
).
%! jpl_type_to_preferred_concrete_type(+Type:type, -ConcreteType:type)
%
% Type must be a canonical JPL type,
% possibly an inferred pseudo type such as =|char_int|= or =|array(char_byte)|=
%
% ConcreteType is the preferred concrete (Java-instantiable) type.
%
% Example
% ==
% ?- jpl_type_to_preferred_concrete_type(array(char_byte), T).
% T = array(byte).
% ==
%
% NB introduced 16/Apr/2005 to fix bug whereby jpl_list_to_array([1,2,3],A) failed
% because the lists's inferred type of array(char_byte) is not Java-instantiable
jpl_type_to_preferred_concrete_type(T, Tc) :-
( jpl_type_to_preferred_concrete_type_1(T, TcX)
-> Tc = TcX
).
jpl_type_to_preferred_concrete_type_1(char_int, int).
jpl_type_to_preferred_concrete_type_1(char_short, short).
jpl_type_to_preferred_concrete_type_1(char_byte, byte).
jpl_type_to_preferred_concrete_type_1(array(T), array(Tc)) :-
jpl_type_to_preferred_concrete_type_1(T, Tc).
jpl_type_to_preferred_concrete_type_1(T, T).
%! jpl_types_fit_type(+Types:list(type), +Type:type)
%
% Each member of Types is (independently) (if that means anything) assignable to Type.
%
% Used in dynamic type check when attempting to e.g. assign list of values to array.
jpl_types_fit_type([], _).
jpl_types_fit_type([T1|T1s], T2) :-
jpl_type_fits_type(T1, T2),
jpl_types_fit_type(T1s, T2).
%! jpl_types_fit_types(+Types1:list(type), +Types2:list(type))
%
% Each member type of Types1 "fits" the respective member type of Types2.
jpl_types_fit_types([], []).
jpl_types_fit_types([T1|T1s], [T2|T2s]) :-
jpl_type_fits_type(T1, T2),
jpl_types_fit_types(T1s, T2s).
%! jpl_value_to_type(+Value:datum, -Type:type)
%
% Value must be a proper JPL datum other than a ref
% i.e. primitive, String or void
%
% Type is its unique most specific type,
% which may be one of the pseudo types =|char_byte|=, =|char_short|= or =|char_int|=.
jpl_value_to_type(V, T) :-
ground(V), % critically assumed by jpl_value_to_type_1/2
( jpl_value_to_type_1(V, Tv) % 2nd arg must be unbound
-> T = Tv
).
%! jpl_value_to_type_1(+Value:datum, -Type:type) is semidet
%
% Type is the unique most specific JPL type of which Value represents an instance.
%
% Called solely by jpl_value_to_type/2, which commits to first solution.
%
% NB some integer values are of JPL-peculiar uniquely most
% specific subtypes, i.e. char_byte, char_short, char_int but all
% are understood by JPL's internal utilities which call this proc.
%
% NB we regard float as subtype of double.
%
% NB objects and refs always have straightforward types.
jpl_value_to_type_1(@(false), boolean) :- !.
jpl_value_to_type_1(@(true), boolean) :- !.
jpl_value_to_type_1(A, class([java,lang],['String'])) :- % yes it's a "value"
atom(A),
!.
jpl_value_to_type_1(I, T) :-
integer(I),
!,
( I >= 0
-> ( I < 128 -> T = char_byte
; I < 32768 -> T = char_short
; I < 65536 -> T = char_int
; I < 2147483648 -> T = int
; I =< 9223372036854775807 -> T = long
; T = overlong
)
; I >= -128 -> T = byte
; I >= -32768 -> T = short
; I >= -2147483648 -> T = int
; I >= -9223372036854775808 -> T = long
; T = overlong
).
jpl_value_to_type_1(F, float) :-
float(F).
%! jpl_is_class(@Term)
%
% True if Term is a JPL reference to an instance of =|java.lang.Class|=.
jpl_is_class(X) :-
jpl_is_object(X),
jpl_object_to_type(X, class([java,lang],['Class'])).
%! jpl_is_false(@Term)
%
% True if Term is =|@(false)|=, the JPL representation of the Java boolean value 'false'.
jpl_is_false(X) :-
X == @(false).
%! jpl_is_fieldID(-X)
%
% X is a JPL field ID structure (jfieldID/1)..
%
% NB JPL internal use only.
%
% NB applications should not be messing with these.
%
% NB a var arg may get bound.
jpl_is_fieldID(jfieldID(X)) :-
integer(X).
%! jpl_is_methodID(-X)
%
% X is a JPL method ID structure (jmethodID/1).
%
% NB JPL internal use only.
%
% NB applications should not be messing with these.
%
% NB a var arg may get bound.
jpl_is_methodID(jmethodID(X)) :- % NB a var arg may get bound...
integer(X).
%! jpl_is_null(@Term)
%
% True if Term is =|@(null)|=, the JPL representation of Java's 'null' reference.
jpl_is_null(X) :-
X == @(null).
%! jpl_is_object(@Term)
%
% True if Term is a well-formed JPL object reference.
%
% NB this checks only syntax, not whether the object exists.
jpl_is_object(X) :-
blob(X, jref).
%! jpl_is_object_type(@Term)
%
% True if Term is an object (class or array) type, not e.g. a primitive, null or void.
jpl_is_object_type(T) :-
\+ var(T),
jpl_non_var_is_object_type(T).
%! jpl_is_ref(@Term)
%
% True if Term is a well-formed JPL reference,
% either to a Java object
% or to Java's notional but important 'null' non-object.
jpl_is_ref(Term) :-
( jpl_is_object(Term)
-> true
; jpl_is_null(Term)
-> true
).
%! jpl_is_true(@Term)
%
% True if Term is =|@(true)|=, the JPL representation of the Java
% boolean value 'true'.
jpl_is_true(X) :-
X == @(true).
%! jpl_is_type(@Term)
%
% True if Term is a well-formed JPL type structure.
jpl_is_type(X) :-
ground(X),
jpl_ground_is_type(X).
%! jpl_is_void(@Term)
%
% True if Term is =|@(void)|=, the JPL representation of the pseudo
% Java value 'void' (which is returned by jpl_call/4 when invoked on
% void methods).
%
% NB you can try passing 'void' back to Java, but it won't ever be
% interested.
jpl_is_void(X) :-
X == @(void).
%! jpl_false(-X:datum) is semidet
%
% X is =|@(false)|=, the JPL representation of the Java boolean value
% 'false'.
%
% @see jpl_is_false/1
jpl_false(@(false)).
%! jpl_null(-X:datum) is semidet
%
% X is =|@(null)|=, the JPL representation of Java's 'null' reference.
%
% @see jpl_is_null/1
jpl_null(@(null)).
%! jpl_true(-X:datum) is semidet
%
% X is =|@(true)|=, the JPL representation of the Java boolean value
% 'true'.
%
% @see jpl_is_true/1
jpl_true(@(true)).
%! jpl_void(-X:datum) is semidet
%
% X is =|@(void)|=, the JPL representation of the pseudo Java value
% 'void'.
%
% @see jpl_is_void/1
jpl_void(@(void)).
%! jpl_array_to_length(+Array:jref, -Length:integer)
%
% Array should be a JPL reference to a Java array of any type.
%
% Length is the length of that array. This is a utility predicate,
% defined thus:
%
% ```
% jpl_array_to_length(A, N) :-
% ( jpl_ref_to_type(A, array(_))
% -> jGetArrayLength(A, N)
% ).
% ```
jpl_array_to_length(A, N) :-
( jpl_ref_to_type(A, array(_)) % can this be done cheaper e.g. in foreign code?
-> jGetArrayLength(A, N) % *must* be array, else undefined (crash?)
).
%! jpl_array_to_list(+Array:jref, -Elements:list(datum))
%
% Array should be a JPL reference to a Java array of any type.
%
% Elements is a Prolog list of JPL representations of the array's
% elements (values or references, as appropriate). This is a utility
% predicate, defined thus:
%
% ```
% jpl_array_to_list(A, Es) :-
% jpl_array_to_length(A, Len),
% ( Len > 0
% -> LoBound is 0,
% HiBound is Len-1,
% jpl_get(A, LoBound-HiBound, Es)
% ; Es = []
% ).
% ```
jpl_array_to_list(A, Es) :-
jpl_array_to_length(A, Len),
( Len > 0
-> LoBound is 0,
HiBound is Len-1,
jpl_get(A, LoBound-HiBound, Es)
; Es = []
).
%! jpl_datums_to_array(+Datums:list(datum), -A:jref)
%
% A will be a JPL reference to a new Java array, whose base type is the
% most specific Java type of which each member of Datums is (directly
% or indirectly) an instance.
%
% NB this fails silently if
%
% - Datums is an empty list (no base type can be inferred)
% - Datums contains both a primitive value and an object (including
% array) reference (no common supertype)
jpl_datums_to_array(Ds, A) :-
ground(Ds),
jpl_datums_to_most_specific_common_ancestor_type(Ds, T), % T may be pseudo e.g. char_byte
jpl_type_to_preferred_concrete_type(T, Tc), % bugfix added 16/Apr/2005
jpl_new(array(Tc), Ds, A).
%! jpl_enumeration_element(+Enumeration:jref, -Element:datum)
%
% Generates each Element from Enumeration.
%
% - if the element is a java.lang.String then Element will be an atom
% - if the element is null then Element will (oughta) be null
% - otherwise I reckon it has to be an object ref
jpl_enumeration_element(En, E) :-
( jpl_call(En, hasMoreElements, [], @(true))
-> jpl_call(En, nextElement, [], Ex),
( E = Ex
; jpl_enumeration_element(En, E)
)
).
%! jpl_enumeration_to_list(+Enumeration:jref, -Elements:list(datum))
%
% Enumeration should be a JPL reference to an object which implements
% the =|Enumeration|= interface.
%
% Elements is a Prolog list of JPL references to the enumerated
% objects. This is a utility predicate, defined thus:
%
% ```
% jpl_enumeration_to_list(Enumeration, Es) :-
% ( jpl_call(Enumeration, hasMoreElements, [], @(true))
% -> jpl_call(Enumeration, nextElement, [], E),
% Es = [E|Es1],
% jpl_enumeration_to_list(Enumeration, Es1)
% ; Es = []
% ).
% ```
jpl_enumeration_to_list(Enumeration, Es) :-
( jpl_call(Enumeration, hasMoreElements, [], @(true))
-> jpl_call(Enumeration, nextElement, [], E),
Es = [E|Es1],
jpl_enumeration_to_list(Enumeration, Es1)
; Es = []
).
%! jpl_hashtable_pair(+HashTable:jref, -KeyValuePair:pair(datum,datum)) is nondet
%
% Generates Key-Value pairs from the given HashTable.
%
% NB String is converted to atom but Integer is presumably returned as
% an object ref (i.e. as elsewhere, no auto unboxing);
%
% NB this is anachronistic: the Map interface is preferred.
jpl_hashtable_pair(HT, K-V) :-
jpl_call(HT, keys, [], Ek),
jpl_enumeration_to_list(Ek, Ks),
member(K, Ks),
jpl_call(HT, get, [K], V).
%! jpl_iterator_element(+Iterator:jref, -Element:datum)
%
% Iterator should be a JPL reference to an object which implements the
% =|java.util.Iterator|= interface.
%
% Element is the JPL representation of the next element in the
% iteration. This is a utility predicate, defined thus:
%
% ```
% jpl_iterator_element(I, E) :-
% ( jpl_call(I, hasNext, [], @(true))
% -> ( jpl_call(I, next, [], E)
% ; jpl_iterator_element(I, E)
% )
% ).
% ```
jpl_iterator_element(I, E) :-
( jpl_call(I, hasNext, [], @(true))
-> ( jpl_call(I, next, [], E)
; jpl_iterator_element(I, E)
)
).
%! jpl_list_to_array(+Datums:list(datum), -Array:jref)
%
% Datums should be a proper Prolog list of JPL datums (values or
% references).
%
% If Datums have a most specific common supertype, then Array is a JPL
% reference to a new Java array, whose base type is that common
% supertype, and whose respective elements are the Java values or
% objects represented by Datums.
jpl_list_to_array(Ds, A) :-
jpl_datums_to_array(Ds, A).
%! jpl_terms_to_array(+Terms:list(term), -Array:jref) is semidet
%
% Terms should be a proper Prolog list of arbitrary terms.
%
% Array is a JPL reference to a new Java array of ``org.jpl7.Term``,
% whose elements represent the respective members of the list.
jpl_terms_to_array(Ts, A) :-
jpl_terms_to_array_1(Ts, Ts2),
jpl_new(array(class([org,jpl7],['Term'])), Ts2, A).
jpl_terms_to_array_1([], []).
jpl_terms_to_array_1([T|Ts], [{T}|Ts2]) :-
jpl_terms_to_array_1(Ts, Ts2).
%! jpl_array_to_terms(+JRef:jref, -Terms:list(term))
%
% JRef should be a JPL reference to a Java array of org.jpl7.Term
% instances (or ots subtypes); Terms will be a list of the terms which
% the respective array elements represent.
jpl_array_to_terms(JRef, Terms) :-
jpl_call('org.jpl7.Util', termArrayToList, [JRef], {Terms}).
%! jpl_map_element(+Map:jref, -KeyValue:pair(datum,datum)) is nondet
%
% Map must be a JPL Reference to an object which implements the
% =|java.util.Map|= interface
%
% This generates each Key-Value pair from the Map, e.g.
%
% ```
% ?- jpl_call('java.lang.System', getProperties, [], Map), jpl_map_element(Map, E).
% Map = @<jref>(0x20b5c38),
% E = 'java.runtime.name'-'Java(TM) SE Runtime Environment' ;
% Map = @<jref>(0x20b5c38),
% E = 'sun.boot.library.path'-'C:\\Program Files\\Java\\jre7\\bin'
% etc.
% ```
%
% This is a utility predicate, defined thus:
%
% ```
% jpl_map_element(Map, K-V) :-
% jpl_call(Map, entrySet, [], ES),
% jpl_set_element(ES, E),
% jpl_call(E, getKey, [], K),
% jpl_call(E, getValue, [], V).
% ```
jpl_map_element(Map, K-V) :-
jpl_call(Map, entrySet, [], ES),
jpl_set_element(ES, E),
jpl_call(E, getKey, [], K),
jpl_call(E, getValue, [], V).
%! jpl_set_element(+Set:jref, -Element:datum) is nondet
%
% Set must be a JPL reference to an object which implements the
% =|java.util.Set|= interface.
%
% On backtracking, Element is bound to a JPL representation of each
% element of Set. This is a utility predicate, defined thus:
%
% ```
% jpl_set_element(S, E) :-
% jpl_call(S, iterator, [], I),
% jpl_iterator_element(I, E).
% ```
jpl_set_element(S, E) :-
jpl_call(S, iterator, [], I),
jpl_iterator_element(I, E).
%! jpl_servlet_byref(+Config, +Request, +Response)
%
% This serves the _byref_ servlet demo, exemplifying one tactic for
% implementing a servlet in Prolog by accepting the Request and
% Response objects as JPL references and accessing their members via
% JPL as required;
%
% @see jpl_servlet_byval/3
jpl_servlet_byref(Config, Request, Response) :-
jpl_call(Config, getServletContext, [], Context),
jpl_call(Response, setStatus, [200], _),
jpl_call(Response, setContentType, ['text/html'], _),
jpl_call(Response, getWriter, [], W),
jpl_call(W, println, ['<html><head></head><body><h2>jpl_servlet_byref/3 says:</h2><pre>'], _),
jpl_call(W, println, ['\nservlet context stuff:'], _),
jpl_call(Context, getInitParameterNames, [], ContextInitParameterNameEnum),
jpl_enumeration_to_list(ContextInitParameterNameEnum, ContextInitParameterNames),
length(ContextInitParameterNames, NContextInitParameterNames),
atomic_list_concat(['\tContext.InitParameters = ',NContextInitParameterNames], NContextInitParameterNamesMsg),
jpl_call(W, println, [NContextInitParameterNamesMsg], _),
( member(ContextInitParameterName, ContextInitParameterNames),
jpl_call(Context, getInitParameter, [ContextInitParameterName], ContextInitParameter),
atomic_list_concat(['\t\tContext.InitParameter[',ContextInitParameterName,'] = ',ContextInitParameter], ContextInitParameterMsg),
jpl_call(W, println, [ContextInitParameterMsg], _),
fail
; true
),
jpl_call(Context, getMajorVersion, [], MajorVersion),
atomic_list_concat(['\tContext.MajorVersion = ',MajorVersion], MajorVersionMsg),
jpl_call(W, println, [MajorVersionMsg], _),
jpl_call(Context, getMinorVersion, [], MinorVersion),
atomic_list_concat(['\tContext.MinorVersion = ',MinorVersion], MinorVersionMsg),
jpl_call(W, println, [MinorVersionMsg], _),
jpl_call(Context, getServerInfo, [], ServerInfo),
atomic_list_concat(['\tContext.ServerInfo = ',ServerInfo], ServerInfoMsg),
jpl_call(W, println, [ServerInfoMsg], _),
jpl_call(W, println, ['\nservlet config stuff:'], _),
jpl_call(Config, getServletName, [], ServletName),
( ServletName == @(null)
-> ServletNameAtom = null
; ServletNameAtom = ServletName
),
atomic_list_concat(['\tConfig.ServletName = ',ServletNameAtom], ServletNameMsg),
jpl_call(W, println, [ServletNameMsg], _),
jpl_call(Config, getInitParameterNames, [], ConfigInitParameterNameEnum),
jpl_enumeration_to_list(ConfigInitParameterNameEnum, ConfigInitParameterNames),
length(ConfigInitParameterNames, NConfigInitParameterNames),
atomic_list_concat(['\tConfig.InitParameters = ',NConfigInitParameterNames], NConfigInitParameterNamesMsg),
jpl_call(W, println, [NConfigInitParameterNamesMsg], _),
( member(ConfigInitParameterName, ConfigInitParameterNames),
jpl_call(Config, getInitParameter, [ConfigInitParameterName], ConfigInitParameter),
atomic_list_concat(['\t\tConfig.InitParameter[',ConfigInitParameterName,'] = ',ConfigInitParameter], ConfigInitParameterMsg),
jpl_call(W, println, [ConfigInitParameterMsg], _),
fail
; true
),
jpl_call(W, println, ['\nrequest stuff:'], _),
jpl_call(Request, getAttributeNames, [], AttributeNameEnum),
jpl_enumeration_to_list(AttributeNameEnum, AttributeNames),
length(AttributeNames, NAttributeNames),
atomic_list_concat(['\tRequest.Attributes = ',NAttributeNames], NAttributeNamesMsg),
jpl_call(W, println, [NAttributeNamesMsg], _),
( member(AttributeName, AttributeNames),
jpl_call(Request, getAttribute, [AttributeName], Attribute),
jpl_call(Attribute, toString, [], AttributeString),
atomic_list_concat(['\t\tRequest.Attribute[',AttributeName,'] = ',AttributeString], AttributeMsg),
jpl_call(W, println, [AttributeMsg], _),
fail
; true
),
jpl_call(Request, getCharacterEncoding, [], CharacterEncoding),
( CharacterEncoding == @(null)
-> CharacterEncodingAtom = ''
; CharacterEncodingAtom = CharacterEncoding
),
atomic_list_concat(['\tRequest.CharacterEncoding',' = ',CharacterEncodingAtom], CharacterEncodingMsg),
jpl_call(W, println, [CharacterEncodingMsg], _),
jpl_call(Request, getContentLength, [], ContentLength),
atomic_list_concat(['\tRequest.ContentLength',' = ',ContentLength], ContentLengthMsg),
jpl_call(W, println, [ContentLengthMsg], _),
jpl_call(Request, getContentType, [], ContentType),
( ContentType == @(null)
-> ContentTypeAtom = ''
; ContentTypeAtom = ContentType
),
atomic_list_concat(['\tRequest.ContentType',' = ',ContentTypeAtom], ContentTypeMsg),
jpl_call(W, println, [ContentTypeMsg], _),
jpl_call(Request, getParameterNames, [], ParameterNameEnum),
jpl_enumeration_to_list(ParameterNameEnum, ParameterNames),
length(ParameterNames, NParameterNames),
atomic_list_concat(['\tRequest.Parameters = ',NParameterNames], NParameterNamesMsg),
jpl_call(W, println, [NParameterNamesMsg], _),
( member(ParameterName, ParameterNames),
jpl_call(Request, getParameter, [ParameterName], Parameter),
atomic_list_concat(['\t\tRequest.Parameter[',ParameterName,'] = ',Parameter], ParameterMsg),
jpl_call(W, println, [ParameterMsg], _),
fail
; true
),
jpl_call(Request, getProtocol, [], Protocol),
atomic_list_concat(['\tRequest.Protocol',' = ',Protocol], ProtocolMsg),
jpl_call(W, println, [ProtocolMsg], _),
jpl_call(Request, getRemoteAddr, [], RemoteAddr),
atomic_list_concat(['\tRequest.RemoteAddr',' = ',RemoteAddr], RemoteAddrMsg),
jpl_call(W, println, [RemoteAddrMsg], _),
jpl_call(Request, getRemoteHost, [], RemoteHost),
atomic_list_concat(['\tRequest.RemoteHost',' = ',RemoteHost], RemoteHostMsg),
jpl_call(W, println, [RemoteHostMsg], _),
jpl_call(Request, getScheme, [], Scheme),
atomic_list_concat(['\tRequest.Scheme',' = ',Scheme], SchemeMsg),
jpl_call(W, println, [SchemeMsg], _),
jpl_call(Request, getServerName, [], ServerName),
atomic_list_concat(['\tRequest.ServerName',' = ',ServerName], ServerNameMsg),
jpl_call(W, println, [ServerNameMsg], _),
jpl_call(Request, getServerPort, [], ServerPort),
atomic_list_concat(['\tRequest.ServerPort',' = ',ServerPort], ServerPortMsg),
jpl_call(W, println, [ServerPortMsg], _),
jpl_call(Request, isSecure, [], @(Secure)),
atomic_list_concat(['\tRequest.Secure',' = ',Secure], SecureMsg),
jpl_call(W, println, [SecureMsg], _),
jpl_call(W, println, ['\nHTTP request stuff:'], _),
jpl_call(Request, getAuthType, [], AuthType),
( AuthType == @(null)
-> AuthTypeAtom = ''
; AuthTypeAtom = AuthType
),
atomic_list_concat(['\tRequest.AuthType',' = ',AuthTypeAtom], AuthTypeMsg),
jpl_call(W, println, [AuthTypeMsg], _),
jpl_call(Request, getContextPath, [], ContextPath),
( ContextPath == @(null)
-> ContextPathAtom = ''
; ContextPathAtom = ContextPath
),
atomic_list_concat(['\tRequest.ContextPath',' = ',ContextPathAtom], ContextPathMsg),
jpl_call(W, println, [ContextPathMsg], _),
jpl_call(Request, getCookies, [], CookieArray),
( CookieArray == @(null)
-> Cookies = []
; jpl_array_to_list(CookieArray, Cookies)
),
length(Cookies, NCookies),
atomic_list_concat(['\tRequest.Cookies',' = ',NCookies], NCookiesMsg),
jpl_call(W, println, [NCookiesMsg], _),
( nth0(NCookie, Cookies, Cookie),
atomic_list_concat(['\t\tRequest.Cookie[',NCookie,']'], CookieMsg),
jpl_call(W, println, [CookieMsg], _),
jpl_call(Cookie, getName, [], CookieName),
atomic_list_concat(['\t\t\tRequest.Cookie.Name = ',CookieName], CookieNameMsg),
jpl_call(W, println, [CookieNameMsg], _),
jpl_call(Cookie, getValue, [], CookieValue),
atomic_list_concat(['\t\t\tRequest.Cookie.Value = ',CookieValue], CookieValueMsg),
jpl_call(W, println, [CookieValueMsg], _),
jpl_call(Cookie, getPath, [], CookiePath),
( CookiePath == @(null)
-> CookiePathAtom = ''
; CookiePathAtom = CookiePath
),
atomic_list_concat(['\t\t\tRequest.Cookie.Path = ',CookiePathAtom], CookiePathMsg),
jpl_call(W, println, [CookiePathMsg], _),
jpl_call(Cookie, getComment, [], CookieComment),
( CookieComment == @(null)
-> CookieCommentAtom = ''
; CookieCommentAtom = CookieComment
),
atomic_list_concat(['\t\t\tRequest.Cookie.Comment = ',CookieCommentAtom], CookieCommentMsg),
jpl_call(W, println, [CookieCommentMsg], _),
jpl_call(Cookie, getDomain, [], CookieDomain),
( CookieDomain == @(null)
-> CookieDomainAtom = ''
; CookieDomainAtom = CookieDomain
),
atomic_list_concat(['\t\t\tRequest.Cookie.Domain = ',CookieDomainAtom], CookieDomainMsg),
jpl_call(W, println, [CookieDomainMsg], _),
jpl_call(Cookie, getMaxAge, [], CookieMaxAge),
atomic_list_concat(['\t\t\tRequest.Cookie.MaxAge = ',CookieMaxAge], CookieMaxAgeMsg),
jpl_call(W, println, [CookieMaxAgeMsg], _),
jpl_call(Cookie, getVersion, [], CookieVersion),
atomic_list_concat(['\t\t\tRequest.Cookie.Version = ',CookieVersion], CookieVersionMsg),
jpl_call(W, println, [CookieVersionMsg], _),
jpl_call(Cookie, getSecure, [], @(CookieSecure)),
atomic_list_concat(['\t\t\tRequest.Cookie.Secure',' = ',CookieSecure], CookieSecureMsg),
jpl_call(W, println, [CookieSecureMsg], _),
fail
; true
),
jpl_call(W, println, ['</pre></body></html>'], _),
true.
%! jpl_servlet_byval(+MultiMap, -ContentType:atom, -Body:atom)
%
% This exemplifies an alternative (to jpl_servlet_byref) tactic for
% implementing a servlet in Prolog; most Request fields are extracted
% in Java before this is called, and passed in as a multimap (a map,
% some of whose values are maps).
jpl_servlet_byval(MM, CT, Ba) :-
CT = 'text/html',
multimap_to_atom(MM, MMa),
atomic_list_concat(['<html><head></head><body>','<h2>jpl_servlet_byval/3 says:</h2><pre>', MMa,'</pre></body></html>'], Ba).
%! is_pair(?T:term)
%
% I define a half-decent "pair" as having a ground key (any val).
is_pair(Key-_Val) :-
ground(Key).
is_pairs(List) :-
is_list(List),
maplist(is_pair, List).
multimap_to_atom(KVs, A) :-
multimap_to_atom_1(KVs, '', Cz, []),
flatten(Cz, Cs),
atomic_list_concat(Cs, A).
multimap_to_atom_1([], _, Cs, Cs).
multimap_to_atom_1([K-V|KVs], T, Cs1, Cs0) :-
Cs1 = [T,K,' = '|Cs2],
( is_list(V)
-> ( is_pairs(V)
-> V = V2
; findall(N-Ve, nth1(N, V, Ve), V2)
),
T2 = [' ',T],
Cs2 = ['\n'|Cs2a],
multimap_to_atom_1(V2, T2, Cs2a, Cs3)
; to_atom(V, AV),
Cs2 = [AV,'\n'|Cs3]
),
multimap_to_atom_1(KVs, T, Cs3, Cs0).
%! to_atom(+Term, -Atom)
%
% Unifies Atom with a printed representation of Term.
%
% @tbd Sort of quoting requirements and use format(codes(Codes),...)
to_atom(Term, Atom) :-
( atom(Term)
-> Atom = Term % avoid superfluous quotes
; term_to_atom(Term, Atom)
).
%! jpl_pl_syntax(-Syntax:atom)
%
% Unifies Syntax with 'traditional' or 'modern' according to the mode
% in which SWI Prolog 7.x was started
jpl_pl_syntax(Syntax) :-
( [] == '[]'
-> Syntax = traditional
; Syntax = modern
).
/*******************************
* MESSAGES *
*******************************/
:- multifile
prolog:error_message/3.
prolog:error_message(java_exception(Ex)) -->
( { jpl_call(Ex, toString, [], Msg)
}
-> [ 'Java exception: ~w'-[Msg] ]
; [ 'Java exception: ~w'-[Ex] ]
).
/*******************************
* PATHS *
*******************************/
:- multifile user:file_search_path/2.
:- dynamic user:file_search_path/2.
user:file_search_path(jar, swi(lib)).
classpath(DirOrJar) :-
getenv('CLASSPATH', ClassPath),
search_path_separator(Sep),
atomic_list_concat(Elems, Sep, ClassPath),
member(DirOrJar, Elems).
%! add_search_path(+Var, +Value) is det.
%
% Add value to the end of search-path Var. Value is normally a
% directory. Does not change the environment if Dir is already in Var.
%
% @param Value Path to add in OS notation.
add_search_path(Path, Dir) :-
( getenv(Path, Old)
-> search_path_separator(Sep),
( atomic_list_concat(Current, Sep, Old),
memberchk(Dir, Current)
-> true % already present
; atomic_list_concat([Old, Sep, Dir], New),
( debugging(jpl(path))
-> env_var_separators(A,Z),
debug(jpl(path), 'Set ~w~w~w to ~p', [A,Path,Z,New])
; true
),
setenv(Path, New)
)
; setenv(Path, Dir)
).
%! search_path_separator(-Sep:atom)
%
% Separator used the the OS in =PATH=, =LD_LIBRARY_PATH=,
% =CLASSPATH=, etc.
search_path_separator((;)) :-
current_prolog_flag(windows, true),
!.
search_path_separator(:).
env_var_separators('%','%') :-
current_prolog_flag(windows, true),
!.
env_var_separators($,'').
/*******************************
* LOAD THE JVM *
*******************************/
%! check_java_environment
%
% Verify the Java environment. Preferably we would create, but
% most Unix systems do not allow putenv("LD_LIBRARY_PATH=..." in
% the current process. A suggesting found on the net is to modify
% LD_LIBRARY_PATH right at startup and next execv() yourself, but
% this doesn't work if we want to load Java on demand or if Prolog
% itself is embedded in another application.
%
% So, after reading lots of pages on the web, I decided checking
% the environment and producing a sensible error message is the
% best we can do.
%
% Please not that Java2 doesn't require $CLASSPATH to be set, so
% we do not check for that.
check_java_environment :-
current_prolog_flag(apple, true),
!,
print_message(error, jpl(run(jpl_config_dylib))).
check_java_environment :-
check_lib(jvm).
check_lib(Name) :-
check_shared_object(Name, File, EnvVar, Absolute),
( Absolute == (-)
-> env_var_separators(A, Z),
format(string(Msg), 'Please add directory holding ~w to ~w~w~w',
[ File, A, EnvVar, Z ]),
throwme(check_lib,lib_not_found(Name,Msg))
; true
).
%! check_shared_object(+Lib, -File, -EnvVar, -AbsFile) is semidet.
%
% True if AbsFile is existing .so/.dll file for Lib.
%
% @arg File Full name of Lib (i.e. libjpl.so or jpl.dll)
% @arg EnvVar Search-path for shared objects.
check_shared_object(Name, File, EnvVar, Absolute) :-
libfile(Name, File),
library_search_path(Path, EnvVar),
( member(Dir, Path),
atomic_list_concat([Dir, File], /, Absolute),
exists_file(Absolute)
-> true
; Absolute = (-)
).
libfile(Base, File) :-
current_prolog_flag(unix, true),
!,
atom_concat(lib, Base, F0),
current_prolog_flag(shared_object_extension, Ext),
file_name_extension(F0, Ext, File).
libfile(Base, File) :-
current_prolog_flag(windows, true),
!,
current_prolog_flag(shared_object_extension, Ext),
file_name_extension(Base, Ext, File).
%! library_search_path(-Dirs:list, -EnvVar) is det.
%
% Dirs is the list of directories searched for shared objects/DLLs.
% EnvVar is the variable in which the search path os stored.
library_search_path(Path, EnvVar) :-
current_prolog_flag(shared_object_search_path, EnvVar),
search_path_separator(Sep),
( getenv(EnvVar, Env),
atomic_list_concat(Path, Sep, Env)
-> true
; Path = []
).
%! add_jpl_to_classpath
%
% Add jpl.jar to =CLASSPATH= to facilitate callbacks. If `jpl.jar` is
% already in CLASSPATH, do nothing. Note that this may result in the
% user picking up a different version of `jpl.jar`. We'll assume the
% user is right in this case.
%
% @tbd Should we warn if both `classpath` and `jar` return a result
% that is different? What is different? According to same_file/2 or
% content?
add_jpl_to_classpath :-
classpath(Jar),
file_base_name(Jar, 'jpl.jar'),
!.
add_jpl_to_classpath :-
classpath(Dir),
( sub_atom(Dir, _, _, 0, /)
-> atom_concat(Dir, 'jpl.jar', File)
; atom_concat(Dir, '/jpl.jar', File)
),
access_file(File, read),
!.
add_jpl_to_classpath :-
absolute_file_name(jar('jpl.jar'), JplJAR,
[ access(read)
]),
!,
( getenv('CLASSPATH', Old)
-> search_path_separator(Separator),
atomic_list_concat([JplJAR, Old], Separator, New)
; New = JplJAR
),
setenv('CLASSPATH', New).
%! libjpl(-Spec) is det.
%
% Return the spec for loading the JPL shared object. This shared
% object must be called libjpl.so as the Java System.loadLibrary()
% call used by jpl.jar adds the lib* prefix.
%
% In Windows we should __not__ use foreign(jpl) as this eventually
% calls LoadLibrary() with an absolute path, disabling the Windows DLL
% search process for the dependent `jvm.dll` and possibly other Java
% dll dependencies.
libjpl(File) :-
( current_prolog_flag(unix, true)
-> File = foreign(libjpl)
; File = foreign(jpl) % Windows
).
%! add_jpl_to_ldpath(+JPL) is det.
%
% Add the directory holding jpl.so to search path for dynamic
% libraries. This is needed for callback from Java. Java appears to
% use its own search and the new value of the variable is picked up
% correctly.
add_jpl_to_ldpath(JPL) :-
absolute_file_name(JPL, File,
[ file_type(executable),
access(read),
file_errors(fail)
]),
!,
file_directory_name(File, Dir),
prolog_to_os_filename(Dir, OsDir),
extend_java_library_path(OsDir),
current_prolog_flag(shared_object_search_path, PathVar),
add_search_path(PathVar, OsDir).
add_jpl_to_ldpath(_).
%! add_java_to_ldpath is det.
%
% Adds the directories holding jvm.dll to the %PATH%. This appears to
% work on Windows. Unfortunately most Unix systems appear to inspect
% the content of =LD_LIBRARY_PATH= (=DYLD_LIBRARY_PATH= on MacOS) only
% once.
:- if(current_prolog_flag(windows,true)).
add_java_to_ldpath :-
current_prolog_flag(windows, true),
!,
phrase(java_dirs, Extra),
( Extra \== []
-> print_message(informational, extend_ld_path(Extra)),
maplist(extend_dll_search_path, Extra)
; true
).
:- endif.
add_java_to_ldpath.
%! extend_dll_search_path(+Dir)
%
% Add Dir to search for DLL files. We use win_add_dll_directory/1, but
% this doesn't seem to work on Wine, so we also add these directories
% to %PATH% on this platform.
:- if(current_prolog_flag(windows,true)).
extend_dll_search_path(Dir) :-
win_add_dll_directory(Dir),
( current_prolog_flag(wine_version, _)
-> prolog_to_os_filename(Dir, OSDir),
( getenv('PATH', Path0)
-> atomic_list_concat([Path0, OSDir], ';', Path),
setenv('PATH', Path)
; setenv('PATH', OSDir)
)
; true
).
:- endif.
%! extend_java_library_path(+OsDir)
%
% Add Dir (in OS notation) to the Java =|-Djava.library.path|= init
% options.
extend_java_library_path(OsDir) :-
jpl_get_default_jvm_opts(Opts0),
( select(PathOpt0, Opts0, Rest),
sub_atom(PathOpt0, 0, _, _, '-Djava.library.path=')
-> search_path_separator(Separator),
atomic_list_concat([PathOpt0, Separator, OsDir], PathOpt),
NewOpts = [PathOpt|Rest]
; atom_concat('-Djava.library.path=', OsDir, PathOpt),
NewOpts = [PathOpt|Opts0]
),
debug(jpl(path), 'Setting Java options to ~p', [NewOpts]),
jpl_set_default_jvm_opts(NewOpts).
%! java_dirs// is det.
%
% DCG that produces existing candidate directories holding Java
% related DLLs
java_dirs -->
% JDK directories
java_dir(jvm, '/jre/bin/client'),
java_dir(jvm, '/jre/bin/server'),
java_dir(java, '/jre/bin'),
% JRE directories
java_dir(jvm, '/bin/client'),
java_dir(jvm, '/bin/server'),
java_dir(java, '/bin').
java_dir(DLL, _SubPath) -->
{ check_shared_object(DLL, _, _Var, Abs),
Abs \== (-)
},
!.
java_dir(_DLL, SubPath) -->
{ java_home(JavaHome),
atom_concat(JavaHome, SubPath, SubDir),
exists_directory(SubDir)
},
!,
[SubDir].
java_dir(_, _) --> [].
%! java_home(-Home) is semidet
%
% Find the home location of Java.
%
% @arg Home JAVA home in OS notation
java_home_win_key(
jdk,
'HKEY_LOCAL_MACHINE/Software/JavaSoft/JDK'). % new style
java_home_win_key(
jdk,
'HKEY_LOCAL_MACHINE/Software/JavaSoft/Java Development Kit').
java_home_win_key(
jre,
'HKEY_LOCAL_MACHINE/Software/JavaSoft/JRE').
java_home_win_key(
jre,
'HKEY_LOCAL_MACHINE/Software/JavaSoft/Java Runtime Environment').
java_home(Home) :-
getenv('JAVA_HOME', Home),
exists_directory(Home),
!.
:- if(current_prolog_flag(windows, true)).
java_home(Home) :-
java_home_win_key(_, Key0), % TBD: user can't choose jre or jdk
catch(win_registry_get_value(Key0, 'CurrentVersion', Version), _, fail),
atomic_list_concat([Key0, Version], /, Key),
win_registry_get_value(Key, 'JavaHome', WinHome),
prolog_to_os_filename(Home, WinHome),
exists_directory(Home),
!.
:- else.
java_home(Home) :-
member(Home, [ '/usr/lib/java',
'/usr/local/lib/java'
]),
exists_directory(Home),
!.
:- endif.
:- dynamic
jvm_ready/0.
:- volatile
jvm_ready/0.
setup_jvm :-
jvm_ready,
!.
setup_jvm :-
add_jpl_to_classpath,
add_java_to_ldpath,
libjpl(JPL),
catch(load_foreign_library(JPL), E, report_java_setup_problem(E)),
add_jpl_to_ldpath(JPL),
assert(jvm_ready).
report_java_setup_problem(E) :-
print_message(error, E),
check_java_environment.
/*******************************
* MESSAGES *
*******************************/
:- multifile
prolog:message//1.
prolog:message(extend_ld_path(Dirs)) -->
[ 'Extended DLL search path with'-[] ],
dir_per_line(Dirs).
prolog:message(jpl(run(Command))) -->
[ 'Could not find libjpl.dylib dependencies.'-[],
'Please run `?- ~p.` to correct this'-[Command]
].
dir_per_line([]) --> [].
dir_per_line([H|T]) -->
[ nl, ' ~q'-[H] ],
dir_per_line(T).
/****************************************************************************
* PARSING/GENERATING ENTITY NAME / FINDCLASS DESCRIPTOR / METHOD DESCRIPTOR *
****************************************************************************/
% ===
% PRINCIPLE
%
% We process list of character codes in the DCG (as opposed to lists of
% characters)
%
% In SWI Prolog the character codes are the Unicode code values - the DCGs
% looking at individual characters of a Java identifier expect this.
%
% To generate list of character codes from literals, the backquote notation
% can be used:
%
% ?- X=`alpha`.
% X = [97, 108, 112, 104, 97].
%
% However, Jab Wielmaker says:
%
% "Please use "string" for terminals in DCGs. The SWI-Prolog DCG compiler
% handles these correctly and this retains compatibility."
%
% So we do that.
% ===
% jpl_entityname//1
%
% Relate a Java-side "entity name" (a String as returned by Class.getName())
% (in the DCG accumulator as a list of Unicode code values) to JPL's
% Prolog-side "type term".
%
% For example:
%
% ~~~
% Java-side "entity name" <-----> JPL Prolog-side "type term"
% "java.util.Date" class([java,util],['Date'])
% ~~~
%
% @see https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#getName()
%
% Example for getName() calls generating entity names
%
% ~~~
%
% class TJ {
% public static final void main(String[] argv) {
%
% System.out.println(void.class.getName()); // void
% System.out.println(Void.TYPE.getName()); // void
% System.out.println(Void.class.getName()); // java.lang.Void
%
% System.out.println(char.class.getName()); // char
% System.out.println(Character.TYPE.getName()); // char
% System.out.println(Character.class.getName()); // java.lang.Character
% System.out.println(Character.valueOf('x').getClass().getName()); // java.lang.Character
%
% System.out.println(int[].class.getName()); // [I
% System.out.println((new int[4]).getClass().getName()); // [I
% int[] a = {1,2,3}; System.out.println(a.getClass().getName()); // [I
%
% System.out.println(int[][].class.getName()); // [[I
% System.out.println((new int[4][4]).getClass().getName()); // [[I
% int[][] aa = {{1},{2},{3}}; System.out.println(aa.getClass().getName()); // [[I
%
% System.out.println(Integer[][].class.getName()); // [[Ljava.lang.Integer;
% System.out.println((new Integer[4][4]).getClass().getName()); // [[Ljava.lang.Integer;
% Integer[][] bb = {{1},{2},{3}}; System.out.println(bb.getClass().getName()); // [[Ljava.lang.Integer;
%
% }
% }
% ~~~
%
% Note that We can list the possible "jpl type terms" directly in the head of
% jpl_entityname//1 (except for the primitives). This helps in clause selection
% and documentation. Note that the fact that the last two clauses T are not tagged as
% "primitive()" makes this representation nonuniform; should be fixed at some time.
% ---
jpl_entityname(class(Ps,Cs)) --> jpl_classname(class(Ps,Cs),dotty),!.
jpl_entityname(array(T)) --> jpl_array_type_descriptor(array(T),dotty),!.
jpl_entityname(void) --> "void",!.
jpl_entityname(P) --> jpl_primitive_entityname(P).
% ---
% The "findclass descriptor" is used for the JNI function FindClass and is
% either an array type descriptor with a "slashy" package name or directly
% a classname, also with a "slasgy" package name
% ---
jpl_findclass_descriptor(array(T)) --> jpl_array_type_descriptor(array(T),slashy),!.
jpl_findclass_descriptor(class(Ps,Cs)) --> jpl_classname(class(Ps,Cs),slashy).
% ---
% The "method descriptor" is used to find a method ID based on the method
% signature. It contains method arguments and type of method return value
% ---
jpl_method_descriptor(method(Ts,T)) --> "(", jpl_method_descriptor_args(Ts), ")", jpl_method_descriptor_retval(T).
jpl_method_descriptor_args([T|Ts]) --> jpl_field_descriptor(T,slashy), !, jpl_method_descriptor_args(Ts).
jpl_method_descriptor_args([]) --> [].
jpl_method_descriptor_retval(void) --> "V".
jpl_method_descriptor_retval(T) --> jpl_field_descriptor(T,slashy).
% ---
% The "binary classname" (i.e. the classname as it appears in binaries) as
% specified in The "Java Language Specification".
% See "Binary Compatibility" - "The Form of a Binary"
% https://docs.oracle.com/javase/specs/jls/se14/html/jls-13.html#jls-13.1
% which points to the "fully qualified name" and "canonical name"
% https://docs.oracle.com/javase/specs/jls/se14/html/jls-6.html#jls-6.7
%
% For JNI, we can switch to "slashy" mode instead of the "dotty" mode, which
% technically makes this NOT the "binary classname", but we keep the predicate name.
% ---
jpl_classname(class(Ps,Cs),Mode) --> jpl_package_parts(Ps,Mode), jpl_class_parts(Cs).
% ---
% The qualified name of the package (which may be empty if it is the
% unnamed package). This is a series of Java identifiers separated by dots, but
% in order to reduce codesize, we switch to the "slash" separator depending
% on a second argument, the mode, which is either "dotty" or "slashy".
% "The fully qualified name of a named package that is not a subpackage of a
% named package is its simple name." ... "A simple name is a single identifier."
% https://docs.oracle.com/javase/specs/jls/se14/html/jls-6.html#jls-6.7
% Note that the last '.' is not considered a separator towards the subsequent
% class parts but as a terminator of the package parts sequence (it's a view
% less demanding of backtracking)
% ---
jpl_package_parts([A|As],dotty) --> jpl_java_id(A), ".", !, jpl_package_parts(As,dotty).
jpl_package_parts([A|As],slashy) --> jpl_java_id(A), "/", !, jpl_package_parts(As,slashy).
jpl_package_parts([],_) --> [].
% ---
% The class parts of a class name (everything beyond the last dot
% of the package prefix, if it exists). This comes from "13.1 - The form of
% a binary", where it is laid out a bit confusingly.
% https://docs.oracle.com/javase/specs/jls/se14/html/jls-13.html#jls-13.1
%
% PROBLEM 2020-08:
%
% Here is an ambiguity that I haven't been able to resolve: '$' is a perfectly
% legitimate character both at the start and in the middle of a classname,
% in fact you can create classes with '$' inside the classname and they compile
% marvelously (try it!). However it is also used as separator for inner class
% names ... but not really! In fact, it is just a concatentation character for
% a _generated class name_ (that makes sense - an inner class is a syntactic
% construct of Java the Language, but of no concern to the JVM, not even for
% access checking because the compiler is supposed to have bleached out any
% problemtic code).
% Parsing such a generated class name can go south in several different ways:
% '$' at the begging, '$' at the end, multiple runs of '$$$' .. one should not
% attempt to do it!
% But the original JPL code does, so we keep this practice for now.
% ---
jpl_class_parts(Cs) --> { nonvar(Cs), ! }, % guard
{ atomic_list_concat(Cs,'$',A) }, % fuse known Cs with '$'
jpl_java_type_id(A). % verify it & insert it into list
jpl_class_parts(Cs) --> { var(Cs), ! }, % guard
jpl_java_type_id(A), % grab an id including its '$'
{ messy_dollar_split(A,Cs) }. % split it along '$'
% ---
% "field descriptors" appear in method signatures or inside array type
% descriptors (which are itself field descriptors)
% ---
jpl_field_descriptor(class(Ps,Cs),Mode) --> jpl_reference_type_descriptor(class(Ps,Cs),Mode),!.
jpl_field_descriptor(array(T),Mode) --> jpl_array_type_descriptor(array(T),Mode),!.
jpl_field_descriptor(T,_) --> jpl_primitive_type_descriptor(T). % sadly untagged with primitive(_) in the head
jpl_reference_type_descriptor(class(Ps,Cs),Mode) --> "L", jpl_classname(class(Ps,Cs),Mode), ";".
jpl_array_type_descriptor(array(T),Mode) --> "[", jpl_field_descriptor(T,Mode).
% ---
% Breaking a bare classname at the '$'
% ---
% Heuristic: Only a '$' flanked to the left by a valid character
% that is a non-dollar and to the right by a valid character that
% may or may not be a dollar gives rise to split.
%
% The INVERSE of messy_dollar_split/2 is atomic_list_concat/3
messy_dollar_split(A,Out) :-
assertion(A \== ''),
atom_chars(A,Chars),
append([''|Chars],[''],GAChars), % GA is a "guarded A char list" flanked by empties and contains at least 3 chars
triple_process(GAChars,[],[],RunsOut),
postprocess_messy_dollar_split_runs(RunsOut,Out).
postprocess_messy_dollar_split_runs(Runs,Out) :-
reverse(Runs,R1),
maplist([Rin,Rout]>>reverse(Rin,Rout),R1,O1),
maplist([Chars,Atom]>>atom_chars(Atom,Chars),O1,Out).
% Split only between P and N, dropping C, when:
% 1) C is a $ and P is not a dollar and not a start of line
% 2) N is not the end of line
triple_process([P,'$',N|Rest],Run,Runs,Out) :-
N \== '', P \== '$' , P \== '',!,
triple_process(['',N|Rest],[],[Run|Runs],Out).
triple_process(['','$',N|Rest],Run,Runs,Out) :-
!,
triple_process(['',N|Rest],['$'|Run],Runs,Out).
triple_process([_,C,N|Rest],Run,Runs,Out) :-
C \== '$',!,
triple_process([C,N|Rest],[C|Run],Runs,Out).
triple_process([_,C,''],Run,Runs,[[C|Run]|Runs]) :- !.
triple_process([_,''],Run,Runs,[Run|Runs]).
% ===
% Low-level DCG rules
% ===
% ---
% A Java type identifier is a Java identifier different from "var" and "yield"
% ---
jpl_java_type_id(I) --> jpl_java_id(I), { \+memberchk(I,[var,yield]) }.
% ---
% The Java identifier is described at
% https://docs.oracle.com/javase/specs/jls/se14/html/jls-3.html#jls-Identifier
% ---
jpl_java_id(I) --> jpl_java_id_raw(I),
{ \+jpl_java_keyword(I),
\+jpl_java_boolean_literal(I),
\+jpl_java_null_literal(I) }.
% ---
% For direct handling of an identifier, we suffer symmetry breakdown.
% ---
jpl_java_id_raw(A) --> { atom(A),! }, % guard
{ atom_codes(A,[C|Cs]) }, % explode A
{ jpl_java_id_start_char(C) },
[C],
jpl_java_id_part_chars(Cs).
% building X from the character code list
jpl_java_id_raw(A) --> { var(A),! }, % guard
[C],
{ jpl_java_id_start_char(C) },
jpl_java_id_part_chars(Cs),
{ atom_codes(A,[C|Cs]) }. % fuse A
jpl_java_id_part_chars([C|Cs]) --> [C], { jpl_java_id_part_char(C) } ,!, jpl_java_id_part_chars(Cs).
jpl_java_id_part_chars([]) --> [].
% ---
% jpl_primitive_in_array//1
% Described informally in Javadoc for Class.getName()
% https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Class.html#getName()
% The left-hand side should (the JPL type) really be tagged with primitive(boolean) etc.
% ---
jpl_primitive_type_descriptor(boolean) --> "Z",!.
jpl_primitive_type_descriptor(byte) --> "B",!.
jpl_primitive_type_descriptor(char) --> "C",!.
jpl_primitive_type_descriptor(double) --> "D",!.
jpl_primitive_type_descriptor(float) --> "F",!.
jpl_primitive_type_descriptor(int) --> "I",!.
jpl_primitive_type_descriptor(long) --> "J",!.
jpl_primitive_type_descriptor(short) --> "S".
% ---
% jpl_primitive_entityname//1
% These are just the primitive names.
% The left-hand side should (the JPL type) really be tagged with primitive(boolean) etc.
% ---
jpl_primitive_entityname(boolean) --> "boolean" ,!.
jpl_primitive_entityname(byte) --> "byte" ,!.
jpl_primitive_entityname(char) --> "char" ,!.
jpl_primitive_entityname(double) --> "double" ,!.
jpl_primitive_entityname(float) --> "float" ,!.
jpl_primitive_entityname(int) --> "int" ,!.
jpl_primitive_entityname(long) --> "long" ,!.
jpl_primitive_entityname(short) --> "short".
% ---
% Certain java keywords that may not occur as java identifier
% ---
jpl_java_boolean_literal(true).
jpl_java_boolean_literal(false).
jpl_java_null_literal(null).
jpl_java_keyword('_').
jpl_java_keyword(abstract).
jpl_java_keyword(assert).
jpl_java_keyword(boolean).
jpl_java_keyword(break).
jpl_java_keyword(byte).
jpl_java_keyword(case).
jpl_java_keyword(catch).
jpl_java_keyword(char).
jpl_java_keyword(class).
jpl_java_keyword(const).
jpl_java_keyword(continue).
jpl_java_keyword(default).
jpl_java_keyword(do).
jpl_java_keyword(double).
jpl_java_keyword(else).
jpl_java_keyword(enum).
jpl_java_keyword(extends).
jpl_java_keyword(final).
jpl_java_keyword(finally).
jpl_java_keyword(float).
jpl_java_keyword(for).
jpl_java_keyword(goto).
jpl_java_keyword(if).
jpl_java_keyword(implements).
jpl_java_keyword(import).
jpl_java_keyword(instanceof).
jpl_java_keyword(int).
jpl_java_keyword(interface).
jpl_java_keyword(long).
jpl_java_keyword(native).
jpl_java_keyword(new).
jpl_java_keyword(package).
jpl_java_keyword(private).
jpl_java_keyword(protected).
jpl_java_keyword(public).
jpl_java_keyword(return).
jpl_java_keyword(short).
jpl_java_keyword(static).
jpl_java_keyword(strictfp).
jpl_java_keyword(super).
jpl_java_keyword(switch).
jpl_java_keyword(synchronized).
jpl_java_keyword(this).
jpl_java_keyword(throw).
jpl_java_keyword(throws).
jpl_java_keyword(transient).
jpl_java_keyword(try).
jpl_java_keyword(void).
jpl_java_keyword(volatile).
jpl_java_keyword(while).
% ===
% Classify codepoints (i.e. integers) as "Java identifier start/part characters"
%
% A "Java identifier" starts with a "Java identifier start character" and
% continues with a "Java identifier part character".
%
% A "Java identifier start character" is a character for which
% Character.isJavaIdentifierStart(c) returns true, where "c" can be a
% Java char or an integer Unicode code value (basically, that's the definition).
%
% Similarly, a "Java identifier part character" is a character for which
% point Character.isJavaIdentifierPart(c) returns true
%
% See:
%
% https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Character.html#isJavaIdentifierStart(int)
% https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Character.html#isJavaIdentifierPart(int)
%
% A simple Java program was used to generate the runs of unicode character
% points listed below. They are searched lineraly. Generally, a
% code point/value encountered by jpl would be below even 255 and so be
% found quickly
%
% PROBLEM:
%
% 1) If the Prolog implementation does not represent characters internally
% with Unicode code values, i.e. if atom_codes/2 takes/returns other values
% than Unicode code values (may be the case for Prologs other than SWI Prolog)
% an implementation-dependent mapping from/to Unicode will have to be performed
% first!
%
% 2) Is this slow or not? It depends on what the compiler does.
% ===
jpl_java_id_start_char(C) :-
assertion(integer(C)),
java_id_start_char_ranges(Ranges), % retrieve ranges
char_inside_range(C,Ranges). % check
jpl_java_id_part_char(C) :-
assertion(integer(C)),
java_id_part_char_ranges(Ranges), % retrieve ranges
char_inside_range(C,Ranges). % check
char_inside_range(C,[[_Low,High]|Ranges]) :-
High < C,!,char_inside_range(C,Ranges).
char_inside_range(C,[[Low,High]|_]) :-
Low =< C, C =< High.
% ---
% The ranges below are generated with a Java program, then printed
% See "CharRangePrinter.java"
% Note that 36 is "$" which IS allowed as start and part character!
% In fact, there are class names that start with '$' (which is why the
% current version of JPL cannot connect to LibreOffice)
% ---
java_id_start_char_ranges(
[[36,36],[65,90],[95,95],[97,122],[162,165],[170,170],[181,181],[186,186],
[192,214],[216,246],[248,705],[710,721],[736,740],[748,748],[750,750],
[880,884],[886,887],[890,893],[895,895],[902,902],[904,906],[908,908],
[910,929],[931,1013],[1015,1153],[1162,1327],[1329,1366],[1369,1369],
[1376,1416],[1423,1423],[1488,1514],[1519,1522],[1547,1547],[1568,1610],
[1646,1647],[1649,1747],[1749,1749],[1765,1766],[1774,1775],[1786,1788],
[1791,1791],[1808,1808],[1810,1839],[1869,1957],[1969,1969],[1994,2026],
[2036,2037],[2042,2042],[2046,2069],[2074,2074],[2084,2084],[2088,2088],
[2112,2136],[2144,2154],[2208,2228],[2230,2237],[2308,2361],[2365,2365],
[2384,2384],[2392,2401],[2417,2432],[2437,2444],[2447,2448],[2451,2472],
[2474,2480],[2482,2482],[2486,2489],[2493,2493],[2510,2510],[2524,2525],
[2527,2529],[2544,2547],[2555,2556],[2565,2570],[2575,2576],[2579,2600],
[2602,2608],[2610,2611],[2613,2614],[2616,2617],[2649,2652],[2654,2654],
[2674,2676],[2693,2701],[2703,2705],[2707,2728],[2730,2736],[2738,2739],
[2741,2745],[2749,2749],[2768,2768],[2784,2785],[2801,2801],[2809,2809],
[2821,2828],[2831,2832],[2835,2856],[2858,2864],[2866,2867],[2869,2873],
[2877,2877],[2908,2909],[2911,2913],[2929,2929],[2947,2947],[2949,2954],
[2958,2960],[2962,2965],[2969,2970],[2972,2972],[2974,2975],[2979,2980],
[2984,2986],[2990,3001],[3024,3024],[3065,3065],[3077,3084],[3086,3088],
[3090,3112],[3114,3129],[3133,3133],[3160,3162],[3168,3169],[3200,3200],
[3205,3212],[3214,3216],[3218,3240],[3242,3251],[3253,3257],[3261,3261],
[3294,3294],[3296,3297],[3313,3314],[3333,3340],[3342,3344],[3346,3386],
[3389,3389],[3406,3406],[3412,3414],[3423,3425],[3450,3455],[3461,3478],
[3482,3505],[3507,3515],[3517,3517],[3520,3526],[3585,3632],[3634,3635],
[3647,3654],[3713,3714],[3716,3716],[3718,3722],[3724,3747],[3749,3749],
[3751,3760],[3762,3763],[3773,3773],[3776,3780],[3782,3782],[3804,3807],
[3840,3840],[3904,3911],[3913,3948],[3976,3980],[4096,4138],[4159,4159],
[4176,4181],[4186,4189],[4193,4193],[4197,4198],[4206,4208],[4213,4225],
[4238,4238],[4256,4293],[4295,4295],[4301,4301],[4304,4346],[4348,4680],
[4682,4685],[4688,4694],[4696,4696],[4698,4701],[4704,4744],[4746,4749],
[4752,4784],[4786,4789],[4792,4798],[4800,4800],[4802,4805],[4808,4822],
[4824,4880],[4882,4885],[4888,4954],[4992,5007],[5024,5109],[5112,5117],
[5121,5740],[5743,5759],[5761,5786],[5792,5866],[5870,5880],[5888,5900],
[5902,5905],[5920,5937],[5952,5969],[5984,5996],[5998,6000],[6016,6067],
[6103,6103],[6107,6108],[6176,6264],[6272,6276],[6279,6312],[6314,6314],
[6320,6389],[6400,6430],[6480,6509],[6512,6516],[6528,6571],[6576,6601],
[6656,6678],[6688,6740],[6823,6823],[6917,6963],[6981,6987],[7043,7072],
[7086,7087],[7098,7141],[7168,7203],[7245,7247],[7258,7293],[7296,7304],
[7312,7354],[7357,7359],[7401,7404],[7406,7411],[7413,7414],[7418,7418],
[7424,7615],[7680,7957],[7960,7965],[7968,8005],[8008,8013],[8016,8023],
[8025,8025],[8027,8027],[8029,8029],[8031,8061],[8064,8116],[8118,8124],
[8126,8126],[8130,8132],[8134,8140],[8144,8147],[8150,8155],[8160,8172],
[8178,8180],[8182,8188],[8255,8256],[8276,8276],[8305,8305],[8319,8319],
[8336,8348],[8352,8383],[8450,8450],[8455,8455],[8458,8467],[8469,8469],
[8473,8477],[8484,8484],[8486,8486],[8488,8488],[8490,8493],[8495,8505],
[8508,8511],[8517,8521],[8526,8526],[8544,8584],[11264,11310],[11312,11358],
[11360,11492],[11499,11502],[11506,11507],[11520,11557],[11559,11559],
[11565,11565],[11568,11623],[11631,11631],[11648,11670],[11680,11686],
[11688,11694],[11696,11702],[11704,11710],[11712,11718],[11720,11726],
[11728,11734],[11736,11742],[11823,11823],[12293,12295],[12321,12329],
[12337,12341],[12344,12348],[12353,12438],[12445,12447],[12449,12538],
[12540,12543],[12549,12591],[12593,12686],[12704,12730],[12784,12799],
[13312,19893],[19968,40943],[40960,42124],[42192,42237],[42240,42508],
[42512,42527],[42538,42539],[42560,42606],[42623,42653],[42656,42735],
[42775,42783],[42786,42888],[42891,42943],[42946,42950],[42999,43009],
[43011,43013],[43015,43018],[43020,43042],[43064,43064],[43072,43123],
[43138,43187],[43250,43255],[43259,43259],[43261,43262],[43274,43301],
[43312,43334],[43360,43388],[43396,43442],[43471,43471],[43488,43492],
[43494,43503],[43514,43518],[43520,43560],[43584,43586],[43588,43595],
[43616,43638],[43642,43642],[43646,43695],[43697,43697],[43701,43702],
[43705,43709],[43712,43712],[43714,43714],[43739,43741],[43744,43754],
[43762,43764],[43777,43782],[43785,43790],[43793,43798],[43808,43814],
[43816,43822],[43824,43866],[43868,43879],[43888,44002],[44032,55203],
[55216,55238],[55243,55291],[63744,64109],[64112,64217],[64256,64262],
[64275,64279],[64285,64285],[64287,64296],[64298,64310],[64312,64316],
[64318,64318],[64320,64321],[64323,64324],[64326,64433],[64467,64829],
[64848,64911],[64914,64967],[65008,65020],[65075,65076],[65101,65103],
[65129,65129],[65136,65140],[65142,65276],[65284,65284],[65313,65338],
[65343,65343],[65345,65370],[65382,65470],[65474,65479],[65482,65487],
[65490,65495],[65498,65500],[65504,65505],[65509,65510]]).
java_id_part_char_ranges(
[[0,8],[14,27],[36,36],[48,57],[65,90],[95,95],[97,122],[127,159],[162,165],
[170,170],[173,173],[181,181],[186,186],[192,214],[216,246],[248,705],
[710,721],[736,740],[748,748],[750,750],[768,884],[886,887],[890,893],
[895,895],[902,902],[904,906],[908,908],[910,929],[931,1013],[1015,1153],
[1155,1159],[1162,1327],[1329,1366],[1369,1369],[1376,1416],[1423,1423],
[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1488,1514],
[1519,1522],[1536,1541],[1547,1547],[1552,1562],[1564,1564],[1568,1641],
[1646,1747],[1749,1757],[1759,1768],[1770,1788],[1791,1791],[1807,1866],
[1869,1969],[1984,2037],[2042,2042],[2045,2093],[2112,2139],[2144,2154],
[2208,2228],[2230,2237],[2259,2403],[2406,2415],[2417,2435],[2437,2444],
[2447,2448],[2451,2472],[2474,2480],[2482,2482],[2486,2489],[2492,2500],
[2503,2504],[2507,2510],[2519,2519],[2524,2525],[2527,2531],[2534,2547],
[2555,2556],[2558,2558],[2561,2563],[2565,2570],[2575,2576],[2579,2600],
[2602,2608],[2610,2611],[2613,2614],[2616,2617],[2620,2620],[2622,2626],
[2631,2632],[2635,2637],[2641,2641],[2649,2652],[2654,2654],[2662,2677],
[2689,2691],[2693,2701],[2703,2705],[2707,2728],[2730,2736],[2738,2739],
[2741,2745],[2748,2757],[2759,2761],[2763,2765],[2768,2768],[2784,2787],
[2790,2799],[2801,2801],[2809,2815],[2817,2819],[2821,2828],[2831,2832],
[2835,2856],[2858,2864],[2866,2867],[2869,2873],[2876,2884],[2887,2888],
[2891,2893],[2902,2903],[2908,2909],[2911,2915],[2918,2927],[2929,2929],
[2946,2947],[2949,2954],[2958,2960],[2962,2965],[2969,2970],[2972,2972],
[2974,2975],[2979,2980],[2984,2986],[2990,3001],[3006,3010],[3014,3016],
[3018,3021],[3024,3024],[3031,3031],[3046,3055],[3065,3065],[3072,3084],
[3086,3088],[3090,3112],[3114,3129],[3133,3140],[3142,3144],[3146,3149],
[3157,3158],[3160,3162],[3168,3171],[3174,3183],[3200,3203],[3205,3212],
[3214,3216],[3218,3240],[3242,3251],[3253,3257],[3260,3268],[3270,3272],
[3274,3277],[3285,3286],[3294,3294],[3296,3299],[3302,3311],[3313,3314],
[3328,3331],[3333,3340],[3342,3344],[3346,3396],[3398,3400],[3402,3406],
[3412,3415],[3423,3427],[3430,3439],[3450,3455],[3458,3459],[3461,3478],
[3482,3505],[3507,3515],[3517,3517],[3520,3526],[3530,3530],[3535,3540],
[3542,3542],[3544,3551],[3558,3567],[3570,3571],[3585,3642],[3647,3662],
[3664,3673],[3713,3714],[3716,3716],[3718,3722],[3724,3747],[3749,3749],
[3751,3773],[3776,3780],[3782,3782],[3784,3789],[3792,3801],[3804,3807],
[3840,3840],[3864,3865],[3872,3881],[3893,3893],[3895,3895],[3897,3897],
[3902,3911],[3913,3948],[3953,3972],[3974,3991],[3993,4028],[4038,4038],
[4096,4169],[4176,4253],[4256,4293],[4295,4295],[4301,4301],[4304,4346],
[4348,4680],[4682,4685],[4688,4694],[4696,4696],[4698,4701],[4704,4744],
[4746,4749],[4752,4784],[4786,4789],[4792,4798],[4800,4800],[4802,4805],
[4808,4822],[4824,4880],[4882,4885],[4888,4954],[4957,4959],[4992,5007],
[5024,5109],[5112,5117],[5121,5740],[5743,5759],[5761,5786],[5792,5866],
[5870,5880],[5888,5900],[5902,5908],[5920,5940],[5952,5971],[5984,5996],
[5998,6000],[6002,6003],[6016,6099],[6103,6103],[6107,6109],[6112,6121],
[6155,6158],[6160,6169],[6176,6264],[6272,6314],[6320,6389],[6400,6430],
[6432,6443],[6448,6459],[6470,6509],[6512,6516],[6528,6571],[6576,6601],
[6608,6617],[6656,6683],[6688,6750],[6752,6780],[6783,6793],[6800,6809],
[6823,6823],[6832,6845],[6912,6987],[6992,7001],[7019,7027],[7040,7155],
[7168,7223],[7232,7241],[7245,7293],[7296,7304],[7312,7354],[7357,7359],
[7376,7378],[7380,7418],[7424,7673],[7675,7957],[7960,7965],[7968,8005],
[8008,8013],[8016,8023],[8025,8025],[8027,8027],[8029,8029],[8031,8061],
[8064,8116],[8118,8124],[8126,8126],[8130,8132],[8134,8140],[8144,8147],
[8150,8155],[8160,8172],[8178,8180],[8182,8188],[8203,8207],[8234,8238],
[8255,8256],[8276,8276],[8288,8292],[8294,8303],[8305,8305],[8319,8319],
[8336,8348],[8352,8383],[8400,8412],[8417,8417],[8421,8432],[8450,8450],
[8455,8455],[8458,8467],[8469,8469],[8473,8477],[8484,8484],[8486,8486],
[8488,8488],[8490,8493],[8495,8505],[8508,8511],[8517,8521],[8526,8526],
[8544,8584],[11264,11310],[11312,11358],[11360,11492],[11499,11507],
[11520,11557],[11559,11559],[11565,11565],[11568,11623],[11631,11631],
[11647,11670],[11680,11686],[11688,11694],[11696,11702],[11704,11710],
[11712,11718],[11720,11726],[11728,11734],[11736,11742],[11744,11775],
[11823,11823],[12293,12295],[12321,12335],[12337,12341],[12344,12348],
[12353,12438],[12441,12442],[12445,12447],[12449,12538],[12540,12543],
[12549,12591],[12593,12686],[12704,12730],[12784,12799],[13312,19893],
[19968,40943],[40960,42124],[42192,42237],[42240,42508],[42512,42539],
[42560,42607],[42612,42621],[42623,42737],[42775,42783],[42786,42888],
[42891,42943],[42946,42950],[42999,43047],[43064,43064],[43072,43123],
[43136,43205],[43216,43225],[43232,43255],[43259,43259],[43261,43309],
[43312,43347],[43360,43388],[43392,43456],[43471,43481],[43488,43518],
[43520,43574],[43584,43597],[43600,43609],[43616,43638],[43642,43714],
[43739,43741],[43744,43759],[43762,43766],[43777,43782],[43785,43790],
[43793,43798],[43808,43814],[43816,43822],[43824,43866],[43868,43879],
[43888,44010],[44012,44013],[44016,44025],[44032,55203],[55216,55238],
[55243,55291],[63744,64109],[64112,64217],[64256,64262],[64275,64279],
[64285,64296],[64298,64310],[64312,64316],[64318,64318],[64320,64321],
[64323,64324],[64326,64433],[64467,64829],[64848,64911],[64914,64967],
[65008,65020],[65024,65039],[65056,65071],[65075,65076],[65101,65103],
[65129,65129],[65136,65140],[65142,65276],[65279,65279],[65284,65284],
[65296,65305],[65313,65338],[65343,65343],[65345,65370],[65382,65470],
[65474,65479],[65482,65487],[65490,65495],[65498,65500],[65504,65505],
[65509,65510],[65529,65531]]).
/*******************************
* EXCEPTION HANDLING *
*******************************/
% ===
% throwme(+LookupPred,+LookupTerm)
%
% Predicate called to construct an exception term and throw it. Information
% about how to construct the actual exception is found by performing a lookup
% based on the key formed by the pair (LookupPred,LookupTerm).
%
% LookupPred :
% What predicate is throwing; this is an atom (a keyword) generally shaped
% after the actual predicate name of the throwing predicate. It is not a
% predicate indicator.
%
% LookupTerm :
% A term, possibly compound, that describes the problem somehow. It is both
% programmer-interpretable (but still abstract) as well as a way of passing
% values that can be inserted into the "Formal" part.
%
% Example: throwme(setter_atomic,nonzero(A))
% ===
throwme(LookupPred,LookupTerm) :-
findall([Location,Formal,Msg],exc_desc(LookupPred,LookupTerm,Location,Formal,Msg),Bag),
length(Bag,BagLength),
throwme_help(BagLength,Bag,LookupPred,LookupTerm).
% Helper invoked if exactly 1 applicable "exception descriptor" could be found.
% Throw the corresponding exception!
% This is the first clause in line. If there is no match on arg1, the catchall
% fallback is used instead.
% The constructed error term is "quasi ISO-standard" because its structure is
% "error(Formal,Context)" -- but there is not guarantee that the "Formal" term
% is any of the ISO-listed allowed "Formal" term (in fact, it generally is not).
% The "Context" (about which the ISO standard says nothing, leaving it to be
% "implementation-defined") is structured according to SWI-Prolog conventions:
% "context(Location,Msg)" where "Location", if left fresh, can be filled with
% a stack trace on the toplevel or by a catching catch_with_backtrace/3. It
% is, however, often filled with the predicate indicator of the throwing
% predicate. The "Msg" should be a stringy thing to printed out, i.e. a
% human-readable explainer that is either an atom or a string.
% - Is there a requirement that "Msg" be forced to an atom?
% ---
throwme_help(1,[[Location,Formal,Msg]],_,_) :-
throw(error(Formal,context(Location,Msg))).
% ---
% Helper invoked if not exactly 1 applicable "exception descriptor" could be found.
% That means the set of exception descriptors is incomplete/ambiguous or the lookup
% query is wrong. Throws a quasi-ISO-standard exception following the format
% error(_,_) but with the formal term the non-ISO atom 'programming_error'.
% - Note that "Msg" is an atom, not a string (is that ok? it should probably be
% a String, at least in SWI-Prolog)
% - Note that the second argument for error(_,_) follows SWI-Prolog conventions
% and with its first position fresh, may be filled with a backtrace.
% ---
throwme_help(Count,_,LookupPred,LookupTerm) :-
Count \== 1,
with_output_to(
atom(Msg),
format("Instead of 1, found ~d exception descriptors for LookupPred = ~q, LookupTerm = ~q",
[Count,LookupPred,LookupTerm])),
throw(error(programming_error,context(_,Msg))).
% ===
% exc_desc(+LookupPred,+LookupTerm,?Location,?Formal,?Msg)
% ===
% Descriptors for exceptions.
%
% The first two arguments are used for lookup. See throwme/2 for an explainer.
%
% The three last arguments are output values which are use to construct
% the exception term that is suppoed to be thrown by the caller.
%
% If "Location" is left a freshvar, it can be instantiated to a backtrack if
% the exception reaches the Prolog Toplevel or is caught by
% catch_with_backtrace/3.
%
% Otherwise, "Location" should be a predicate indicator or something similar.
%
% Example:
%
% exc_desc(jpl_call_static,no_such_method(M),
% jpl_call/4,
% existence_error(method,M),
% 'some text')
%
% exc_desc(jpl_call_static,no_such_method(M),
% _,
% existence_error(method,M),
% 'some text')
%
% The "Msg" is a user-readable message. For now, it is not dynamically
% constructed (i.e. using format/3 calls) inside of exc_desc/5, nor is
% internationalization supported for that matter. In some cases, the "Msg"
% has been created by caller and is passed in inside "LookupTerm", from where
% it is unification-picked-out-of-there into arg 5.
%
% The "Formal" is exactly the "formal term" that will used in the "exception
% term", and it is built by unification doing pick/put against "LookupTerm".
% It may or may not be ISO-Standard.
%
% Note that the fact that we adhere to ISO standard atoms instead of defining
% our own for JPL has the advantage that exception-printing handlers on the
% toplevel still work but the generated text is confusing: for example the
% exception-generating handler receives a "type_error" (which is meant to
% indicate a type problem inside a Prolog program, but here is also used to
% indicate a type problem of a very different nature, e.g. the caller wants
% to instantiate a Java interface) and the argument passed in the formal is
% the name of the Java class as an atom. Then the printing handler will say
% this: "there is a problem because this is an atom: 'foo.bar.Interface'" and
% only by reading the cleartext message will the actual problem be revealed:
% "you tried to instantiate an interface".
% ---
safe_type_to_classname(Type,CN) :-
catch(
(jpl_type_to_classname(Type,CN)
-> true
; with_output_to(atom(CN),format("~q",[Type]))),
_DontCareCatcher,
CN='???').
exc_desc(jpl_new,x_is_var,
jpl_new/3,
instantiation_error,
'1st arg must be bound to a classname, descriptor or object type').
exc_desc(jpl_new,x_not_classname(X),
jpl_new/3,
domain_error(classname,X),
'if 1st arg is an atom, it must be a classname or descriptor').
exc_desc(jpl_new,x_not_instantiable(X),
jpl_new/3,
type_error(instantiable,X),
'1st arg must be a classname, descriptor or object type').
exc_desc(jpl_new,not_a_jpl_term(X),
jpl_new/3,
type_error(term,X),
'result is not a org.jpl7.Term instance as required').
% ---
exc_desc(jpl_new_class,params_is_var,
jpl_new/3,
instantiation_error,
'2nd arg must be a proper list of valid parameters for a constructor').
exc_desc(jpl_new_class,params_is_not_list(Params),
jpl_new/3,
type_error(list,Params),
'2nd arg must be a proper list of valid parameters for a constructor').
exc_desc(jpl_new_class,class_is_interface(Type),
jpl_new/3,
type_error(concrete_class,CN),
'cannot create instance of an interface') :- safe_type_to_classname(Type,CN).
exc_desc(jpl_new_class,class_without_constructor(Type,Arity),
jpl_new/3,
existence_error(constructor,CN/Arity),
'no constructor found with the corresponding quantity of parameters') :- safe_type_to_classname(Type,CN).
exc_desc(jpl_new_class,acyclic(X,Msg),
jpl_new/3,
type_error(acyclic,X),
Msg).
exc_desc(jpl_new_class,bad_jpl_datum(Params),
jpl_new/3,
domain_error(list(jpl_datum),Params),
'one or more of the actual parameters is not a valid representation of any Java value or object').
exc_desc(jpl_new_class,single_constructor_mismatch(Co),
jpl_new/3,
existence_error(constructor,Co),
'the actual parameters are not assignable to the formal parameter types of the only constructor which takes this qty of parameters').
exc_desc(jpl_new_class,any_constructor_mismatch(Params),
jpl_new/3,
type_error(constructor_args,Params),
'the actual parameters are not assignable to the formal parameter types of any of the constructors which take this qty of parameters').
exc_desc(jpl_new_class,constructor_multimatch(Params),
jpl_new/3,
type_error(constructor_params,Params),
'more than one most-specific matching constructor (shouldn''t happen)').
exc_desc(jpl_new_class,class_is_abstract(Type),
jpl_new/3,
type_error(concrete_class,CN),
'cannot create instance of an abstract class') :- safe_type_to_classname(Type,CN).
% ---
exc_desc(jpl_new_array,params_is_var,
jpl_new/3,
instantiation_error,
'when constructing a new array, 2nd arg must either be a non-negative integer (denoting the required array length) or a proper list of valid element values').
exc_desc(jpl_new_array,params_is_negative(Params),
jpl_new/3,
domain_error(array_length,Params),
'when constructing a new array, if the 2nd arg is an integer (denoting the required array length) then it must be non-negative').
% ---
exc_desc(jpl_new_primitive,primitive_type_requested(T),
jpl_new/3,
domain_error(object_type,T),
'cannot construct an instance of a primitive type').
% the call to this is commented out in jpl.pl
exc_desc(jpl_new_primitive,params_is_var,
jpl_new/3,
instantiation_error,
'when constructing a new instance of a primitive type, 2nd arg must be bound (to a representation of a suitable value)').
% the call to this is commented out in jpl.pl
exc_desc(jpl_new_primitive,params_is_bad(Params),
jpl_new/3,
domain_error(constructor_args,Params),Msg) :-
atomic_list_concat([
'when constructing a new instance of a primitive type, 2nd arg must either be an ',
'empty list (indicating that the default value of that type is required) or a ',
'list containing exactly one representation of a suitable value'],Msg).
% ---
exc_desc(jpl_new_catchall,catchall(T),
jpl_new/3,
domain_error(jpl_type,T),
'1st arg must denote a known or plausible type').
% ---
exc_desc(jpl_call,arg1_is_var,
jpl_call/4,
instantiation_error,
'1st arg must be bound to an object, classname, descriptor or type').
exc_desc(jpl_call,no_such_class(X),
jpl_call/4,
existence_error(class,X),
'the named class cannot be found').
exc_desc(jpl_call,arg1_is_bad(X),
jpl_call/4,
type_error(class_name_or_descriptor,X),
'1st arg must be an object, classname, descriptor or type').
exc_desc(jpl_call,arg1_is_array(X),
jpl_call/4,
type_error(object_or_class,X),
'cannot call a static method of an array type, as none exists').
exc_desc(jpl_call,arg1_is_bad_2(X),
jpl_call/4,
domain_error(object_or_class,X),
'1st arg must be an object, classname, descriptor or type').
exc_desc(jpl_call,mspec_is_var,
jpl_call/4,
instantiation_error,
'2nd arg must be an atom naming a public method of the class or object').
exc_desc(jpl_call,mspec_is_bad(Mspec),
jpl_call/4,
type_error(method_name,Mspec),
'2nd arg must be an atom naming a public method of the class or object').
exc_desc(jpl_call,acyclic(Te,Msg),
jpl_call/4,
type_error(acyclic,Te),
Msg).
exc_desc(jpl_call,nonconvertible_params(Params),
jpl_call/4,
type_error(method_params,Params),
'not all actual parameters are convertible to Java values or references').
exc_desc(jpl_call,arg3_is_var,
jpl_call/4,
instantiation_error,
'3rd arg must be a proper list of actual parameters for the named method').
exc_desc(jpl_call,arg3_is_bad(Params),
jpl_call/4,
type_error(method_params,Params),
'3rd arg must be a proper list of actual parameters for the named method').
exc_desc(jpl_call,not_a_jpl_term(X),
jpl_call/4,
type_error(jni_jref,X),
'result is not a org.jpl7.Term instance as required').
% ---
exc_desc(jpl_call_instance,no_such_method(M),
jpl_call/4,
existence_error(method,M),
'the class or object has no public methods with the given name and quantity of parameters').
exc_desc(jpl_call_instance,param_not_assignable(P),
jpl_call/4,
type_error(method_params,P),
'the actual parameters are not assignable to the formal parameters of any of the named methods').
exc_desc(jpl_call_instance,multiple_most_specific(M),
jpl_call/4,
existence_error(most_specific_method,M),
'more than one most-specific method is found for the actual parameters (this should not happen)').
% ---
exc_desc(jpl_call_static,no_such_method(M),
jpl_call/4,
existence_error(method,M),
'the class has no public static methods with the given name and quantity of parameters').
exc_desc(jpl_call_static,param_not_assignable(P),
jpl_call/4,
type_error(method_params,P),
'the actual parameters are not assignable to the formal parameters of any of the named methods').
exc_desc(jpl_call_static,multiple_most_specific(M),
jpl_call/4,
existence_error(most_specific_method,M),
'more than one most-specific method is found for the actual parameters (this should not happen)').
% ---
exc_desc(jpl_get,arg1_is_var,
jpl_get/3,
instantiation_error,
'1st arg must be bound to an object, classname, descriptor or type').
exc_desc(jpl_get,named_class_not_found(Type),
jpl_get/3,
existence_error(class,CN),
'the named class cannot be found') :- safe_type_to_classname(Type,CN).
exc_desc(jpl_get,arg1_is_bad(X),
jpl_get/3,
type_error(class_name_or_descriptor,X),
'1st arg must be an object, classname, descriptor or type').
exc_desc(jpl_get,arg1_is_bad_2(X),
jpl_get/3,
domain_error(object_or_class,X),
'1st arg must be an object, classname, descriptor or type').
exc_desc(jpl_get,not_a_jpl_term(X),
jpl_get/3,
type_error(jni_ref,X),
'result is not a org.jpl7.Term instance as required').
% ---
exc_desc(jpl_get_static,arg2_is_var,
jpl_get/3,
instantiation_error,
'2nd arg must be bound to an atom naming a public field of the class').
exc_desc(jpl_get_static,arg2_is_bad(F),
jpl_get/3,
type_error(field_name,F),
'2nd arg must be an atom naming a public field of the class').
exc_desc(jpl_get_static,no_such_field(F),
jpl_get/3,
existence_error(field,F),
'the class or object has no public static field with the given name').
exc_desc(jpl_get_static,multiple_fields(F),
jpl_get/3,
existence_error(unique_field,F),
'more than one field is found with the given name').
% ---
exc_desc(jpl_get_instance,arg2_is_var,
jpl_get/3,
instantiation_error,
'2nd arg must be bound to an atom naming a public field of the class or object').
exc_desc(jpl_get_instance,arg2_is_bad(X),
jpl_get/3,
type_error(field_name,X),
'2nd arg must be an atom naming a public field of the class or object').
exc_desc(jpl_get_instance,no_such_field(Fname),
jpl_get/3,
existence_error(field,Fname),
'the class or object has no public field with the given name').
exc_desc(jpl_get_instance,multiple_fields(Fname),
jpl_get/3,
existence_error(unique_field,Fname),
'more than one field is found with the given name').
% ---
exc_desc(jpl_get_instance_array,arg2_is_var,
jpl_get/3,
instantiation_error,
'when 1st arg is an array, 2nd arg must be bound to an index, an index range, or ''length''').
exc_desc(jpl_get_instance_array,arg2_is_bad(X),
jpl_get/3,
domain_error(array_index,X),
'when 1st arg is an array, integral 2nd arg must be non-negative').
exc_desc(jpl_get_instance_array,arg2_is_too_large(X),
jpl_get/3,
domain_error(array_index,X),
'when 1st arg is an array, integral 2nd arg must not exceed upper bound of array').
exc_desc(jpl_get_instance_array,bad_range_low(R),
jpl_get/3,
domain_error(array_index_range,R),
'lower bound of array index range must not exceed upper bound of array').
exc_desc(jpl_get_instance_array,bad_range_high(R),
jpl_get/3,
domain_error(array_index_range,R),
'upper bound of array index range must not exceed upper bound of array').
exc_desc(jpl_get_instance_array,bad_range_pair_values(R),
jpl_get/3,
domain_error(array_index_range,R),
'array index range must be a non-decreasing pair of non-negative integers').
exc_desc(jpl_get_instance_array,bad_range_pair_types(R),
jpl_get/3,
type_error(array_index_range,R),
'array index range must be a non-decreasing pair of non-negative integers').
exc_desc(jpl_get_instance_array,no_such_field(F),
jpl_get/3,
domain_error(array_field_name,F),
'the array has no public field with the given name').
exc_desc(jpl_get_instance_array,wrong_spec(F),
jpl_get/3,
type_error(array_lookup_spec,F),
'when 1st arg is an array, 2nd arg must be an index, an index range, or ''length''').
% ---
exc_desc(jpl_set,arg1_is_var,
jpl_set/3,
instantiation_error,
'1st arg must be an object, classname, descriptor or type').
exc_desc(jpl_set,classname_does_not_resolve(X),
jpl_set/3,
existence_error(class,X),
'the named class cannot be found').
exc_desc(jpl_set,named_class_not_found(Type),
jpl_set/3,
existence_error(class,CN),
'the named class cannot be found') :- safe_type_to_classname(Type,CN).
exc_desc(jpl_set,acyclic(X,Msg),
jpl_set/3,
type_error(acyclic,X),
Msg).
exc_desc(jpl_set,arg1_is_bad(X),
jpl_set/3,
domain_error(object_or_class,X),
'1st arg must be an object, classname, descriptor or type').
% ---
exc_desc(jpl_set_instance_class,arg2_is_var,
jpl_set/3,
instantiation_error,
'2nd arg must be bound to the name of a public, non-final field').
exc_desc(jpl_set_instance_class,arg2_is_bad(Fname),
jpl_set/3,
type_error(field_name,Fname),
'2nd arg must be the name of a public, non-final field').
exc_desc(jpl_set_instance_class,no_such_field(Fname),
jpl_set/3,
existence_error(field,Fname),
'no public fields of the object have this name').
exc_desc(jpl_set_instance_class,field_is_final(Fname),
jpl_set/3,
permission_error(modify,final_field,Fname),
'cannot assign a value to a final field (actually you could but I''ve decided not to let you)').
exc_desc(jpl_set_instance_class,incompatible_value(Type,V),
jpl_set/3,
type_error(CN,V),
'the value is not assignable to the named field of the class') :- safe_type_to_classname(Type,CN).
exc_desc(jpl_set_instance_class,arg3_is_bad(V),
jpl_set/3,
type_error(field_value,V),
'3rd arg does not represent any Java value or object').
exc_desc(jpl_set_instance_class,multiple_fields(Fname),
jpl_set/3,
existence_error(field,Fname),
'more than one public field of the object has this name (this should not happen)').
% ---
exc_desc(jpl_set_instance_array,arg3_is_var,
jpl_set/3,
instantiation_error,
'when 1st arg is an array, 3rd arg must be bound to a suitable element value or list of values').
exc_desc(jpl_set_instance_array,arg2_is_var,
jpl_set/3,
instantiation_error,
'when 1st arg is an array, 2nd arg must be bound to an index or index range').
exc_desc(jpl_set_instance_array,arg2_is_bad(FSpec),
jpl_set/3,
domain_error(array_index,FSpec),
'when 1st arg is an array, an integral 2nd arg must be a non-negative index').
exc_desc(jpl_set_instance_array,no_values(Fspec,Vs),
jpl_set/3,
domain_error(array_element(Fspec),Vs),
'no values for array element assignment: needs one').
exc_desc(jpl_set_instance_array,more_than_one_value(Fspec,Vs),
jpl_set/3,
domain_error(array_element(Fspec),Vs),
'too many values for array element assignment: needs one').
exc_desc(jpl_set_instance_array,too_few_values(N-M,Vs),
jpl_set/3,
domain_error(array_elements(N-M),Vs),
'too few values for array range assignment').
exc_desc(jpl_set_instance_array,too_many_values(N-M,Vs),
jpl_set/3,
domain_error(array_elements(N-M),Vs),
'too many values for array range assignment').
exc_desc(jpl_set_instance_array,bad_range_pair_values(N-M),
jpl_set/3,
domain_error(array_index_range,N-M),
'array index range must be a non-decreasing pair of non-negative integers').
exc_desc(jpl_set_instance_array,bad_range_pair_types(N-M),
jpl_set/3,
type_error(array_index_range,N-M),
'array index range must be a non-decreasing pair of non-negative integers').
exc_desc(jpl_set_instance_array,cannot_assign_to_final_field,
jpl_set/3,
permission_error(modify,final_field,length),
'cannot assign a value to a final field').
exc_desc(jpl_set_instance_array,no_such_field(Fspec),
jpl_set/3,
existence_error(field,Fspec),
'array has no field with that name').
exc_desc(jpl_set_instance_array,arg2_is_bad_2(Fspec),
jpl_set/3,
domain_error(array_index,Fspec),
'when 1st arg is an array object, 2nd arg must be a non-negative index or index range').
% ---
exc_desc(jpl_set_static,arg2_is_unbound,
jpl_set/3,
instantiation_error,
'when 1st arg denotes a class, 2nd arg must be bound to the name of a public, static, non-final field').
exc_desc(jpl_set_static,arg2_is_bad(Fname),
jpl_set/3,
type_error(field_name,Fname),
'when 1st arg denotes a class, 2nd arg must be the name of a public, static, non-final field').
exc_desc(jpl_set_static,no_such_public_static_field(field,Fname),
jpl_set/3,
existence_error(field,Fname),
'class has no public static fields of this name').
exc_desc(jpl_set_static,cannot_assign_final_field(Fname),
jpl_set/3,
permission_error(modify,final_field,Fname),
'cannot assign a value to a final field').
exc_desc(jpl_set_static,value_not_assignable(Type,V),
jpl_set/3,
type_error(CN,V),
'the value is not assignable to the named field of the class') :- safe_type_to_classname(Type,CN).
exc_desc(jpl_set_static,arg3_is_bad(field_value,V),
jpl_set/3,
type_error(field_value,V),
'3rd arg does not represent any Java value or object').
exc_desc(jpl_set_static,multiple_matches(field,Fname),
jpl_set/3,
existence_error(field,Fname),
'more than one public static field of the class has this name (this should not happen)(?)').
% ---
exc_desc(jpl_set_array,not_all_values_assignable(T,Ds),
jpl_set/3,
type_error(array(T),Ds),
'not all values are assignable to the array element type').
exc_desc(jpl_set_array,not_all_values_convertible(T,Ds),
jpl_set/3,
type_error(array(T),Ds),
'not all values are convertible to Java values or references').
exc_desc(jpl_set_array,element_type_unknown(array_element_type,T),
jpl_set/3,
type_error(array_element_type,T),
'array element type is unknown: neither a class, nor an array type, nor a primitive type').
% ---
exc_desc(jpl_datum_to_type,is_cyclic(Term),
jpl_call/4, % I don't know why, but the tests expect jpl_call/4 here
type_error(acyclic,Term),
'must be acyclic').
% ---
exc_desc(jpl_type_to_class,arg1_is_var,
jpl_type_to_class/2,
instantiation_error,
'1st arg must be bound to a JPL type').
% ---
exc_desc(check_lib,lib_not_found(Name,Msg),
check_lib/2,
existence_error(library,Name),
Msg).
/*******************************
* Initialize JVM *
*******************************/
:- initialization(setup_jvm, now). % must be ready before export
| TeamSPoon/logicmoo_workspace | docker/rootfs/usr/local/lib/swipl/library/jpl.pl | Perl | mit | 191,348 |
#!/sw/bin/perl
=head1 NAME
B<norms.pl>
=head1 DESCRIPTION
Compares various normalization methods. Also, creates files with normalizing factors that are used by C<plot_gene_pileup.pl> and other scripts. There are no options.
=cut
use strict;
use warnings;
use PDL;
use PDL::NiceSlice;
use PDL::Graphics::PLplot;
use GRNASeq;
use GetOpt;
use Stats;
use PLgraphs;
use Tools;
$| = 1;
Stamp();
ReadDefs();
GetMyOptions();
#my @norms = qw(deseq tmm totcount totcountm);
my @norms = qw(deseq totcountm);
my @cols = qw(BLUE GREEN RED GOLD2 GREY);
my %h = ();
my %x = ();
for my $norm (@norms)
{
#my ($d, $m, $s, $nrep, $ngen, $genes, $name, $sel, $f, $xsel) =
my %d = GetNormalizedData(
norm=>$norm,
nonzero=>1,
type=>$type,
clean=>$clean,
spclean=>$spclean
);
for my $cond (@conds)
{
my ($d, $m, $s, $nrep, $ngen, $genes, $name, $sel, $f, $xsel) = @{$d{$cond}};
$h{$cond}{$norm} = $f;
$x{$cond} = $xsel + 1;
}
}
PlotNorms();
CompareNorms();
sub PlotNorms
{
my $w = NewWindow($psfile);
$PL_ny = 2;
my $pan = 1;
my $nrep = 48;
my $maxx = $nrep + 1;
for my $cond (@conds)
{
my $x = $x{$cond};
my ($min, $max) = (0, 1.99);
PlotPanelN($w, $pan++,
BOX => [0, $maxx, $min, $max],
XLAB => 'Replicate #',
YLAB => 'Normalization factor',
#xbox => 'I', ybox => 'I'
);
# for my $r (1 .. $nrep)
# {LinePlot($w, pdl($r,$r), pdl($min, $max), COLOR=>'GREY')}
my $i = 0;
for my $norm (@norms)
{
my $f = $h{$cond}{$norm};
my $col = $cols[$i];
print nelem($x), " ",nelem($f), "\n";
LinePlot($w, $x, $f, COLOR=>'GREY');
PointPlot($w, $x, $f, COLOR=>$col, SYMBOLSIZE=>0.9);
wcols "%2d %5.3f", $x, $f, "${cond}_${norm}_normfac.txt";
my $y = 0.5 - 0.08 * $i;
LinePlot($w, pdl(2,5), pdl($y, $y), COLOR=>$col);
$w->text($norm, COLOR=>$col, CHARSIZE=>0.6, TEXTPOSITION=>[5.5, $y, 0, 0, 0]);
$i++;
}
LinePlot($w, pdl(0,$maxx+1), pdl(1,1), COLOR=>'RED');
TopText($w, $cond, x=>0.07, y=>-2, CHARSIZE => 0.7);
my $spf = SpikeinFile('yeast', $cond);
#my ($rep, $sp, $spe) = rcols $spf, 0, 1, 2;
#my $sp_norm = 1 / $sp;
#my $sp_err = $spe / $sp**2;
my $sp = rcols $spf, 1;
my $sp_norm = 1 / $sp;
#PointPlot($w, $x, $sp_norm($x-1), YERRORBAR=>2*$sp_err($x-1));
PointPlot($w, $x, $sp_norm($x-1));
}
$w->close();
}
sub CompareNorms
{
my $w = NewWindow($psfile);
$PL_nx = 2;
$PL_ymin = 0.5;
my $pan = 1;
my $norm1 = 'totcountm';
my $norm2 = 'spikein';
for my $cond (@conds)
{
my ($min, $max) = (0, 3.5);
PlotPanelN($w, $pan++,
BOX => [$min, $max, $min, $max],
XLAB => $norm1,
YLAB => $norm2,
#xbox => 'I', ybox => 'I'
);
my $sel = $x{$cond} - 1;
my $x = $h{$cond}{$norm1};
my ($y, $ye);
if($norm2 eq 'spikein')
{
my $spf = SpikeinFile('yeast', $cond);
my ($rep, $sp, $spe) = rcols $spf, 0, 1, 2;
$y = 1 / $sp;
$spe = zeroes($sp) unless defined $spe;
$ye = $spe / $sp**2;
PointPlot($w, $x, $y($sel), YERRORBAR=>2*$ye($sel));
#wcols $sel+1, $x, $y($sel);
print "max=", max($y), "\n";
}
else
{
$y = $h{$cond}{$norm2};
PointPlot($w, $x, $y, SYMBOLSIZE=>0.9);
}
LinePlot($w, pdl(0,10), pdl(0,10), COLOR=>'RED');
TopText($w, $cond);
}
$w->close();
}
| bartongroup/profDGE48 | Normalization/norms.pl | Perl | mit | 3,524 |
motif('PS00012').
motif('PS00013').
motif('PS00014').
motif('PS00017').
motif('PS00018').
motif('PS00019').
motif('PS00020').
motif('PS00022').
motif('PS00027').
motif('PS00028').
motif('PS00030').
motif('PS00036').
motif('PS00037').
motif('PS00038').
motif('PS00039').
motif('PS00044').
motif('PS00046').
motif('PS00047').
motif('PS00050').
motif('PS00051').
motif('PS00052').
motif('PS00054').
motif('PS00056').
motif('PS00058').
motif('PS00059').
motif('PS00061').
motif('PS00063').
motif('PS00065').
motif('PS00066').
motif('PS00070').
motif('PS00071').
motif('PS00074').
motif('PS00078').
motif('PS00079').
motif('PS00086').
motif('PS00087').
motif('PS00089').
motif('PS00092').
motif('PS00097').
motif('PS00098').
motif('PS00101').
motif('PS00103').
motif('PS00105').
motif('PS00106').
motif('PS00107').
motif('PS00108').
motif('PS00110').
motif('PS00114').
motif('PS00115').
motif('PS00116').
motif('PS00120').
motif('PS00123').
motif('PS00125').
motif('PS00126').
motif('PS00129').
motif('PS00133').
motif('PS00136').
motif('PS00137').
motif('PS00141').
motif('PS00142').
motif('PS00143').
motif('PS00147').
motif('PS00148').
motif('PS00152').
motif('PS00153').
motif('PS00154').
motif('PS00156').
motif('PS00161').
motif('PS00165').
motif('PS00167').
motif('PS00168').
motif('PS00170').
motif('PS00174').
motif('PS00175').
motif('PS00176').
motif('PS00177').
motif('PS00178').
motif('PS00179').
motif('PS00183').
motif('PS00187').
motif('PS00188').
motif('PS00189').
motif('PS00190').
motif('PS00191').
motif('PS00194').
motif('PS00197').
motif('PS00198').
motif('PS00199').
motif('PS00200').
motif('PS00211').
motif('PS00213').
motif('PS00215').
motif('PS00216').
motif('PS00217').
motif('PS00218').
motif('PS00221').
motif('PS00225').
motif('PS00227').
motif('PS00228').
motif('PS00231').
motif('PS00237').
motif('PS00284').
motif('PS00292').
motif('PS00293').
motif('PS00294').
motif('PS00296').
motif('PS00297').
motif('PS00298').
motif('PS00299').
motif('PS00300').
motif('PS00301').
motif('PS00317').
motif('PS00322').
motif('PS00324').
motif('PS00325').
motif('PS00327').
motif('PS00329').
motif('PS00332').
motif('PS00333').
motif('PS00334').
motif('PS00339').
motif('PS00340').
motif('PS00343').
motif('PS00344').
motif('PS00350').
motif('PS00351').
motif('PS00357').
motif('PS00368').
motif('PS00373').
motif('PS00378').
motif('PS00379').
motif('PS00383').
motif('PS00387').
motif('PS00388').
motif('PS00389').
motif('PS00396').
motif('PS00399').
motif('PS00402').
motif('PS00406').
motif('PS00410').
motif('PS00411').
motif('PS00414').
motif('PS00417').
motif('PS00422').
motif('PS00430').
motif('PS00432').
motif('PS00433').
motif('PS00434').
motif('PS00436').
motif('PS00442').
motif('PS00443').
motif('PS00444').
motif('PS00445').
motif('PS00446').
motif('PS00450').
motif('PS00453').
motif('PS00454').
motif('PS00455').
motif('PS00460').
motif('PS00463').
motif('PS00466').
motif('PS00469').
motif('PS00470').
motif('PS00478').
motif('PS00479').
motif('PS00480').
motif('PS00485').
motif('PS00486').
motif('PS00487').
motif('PS00499').
motif('PS00501').
motif('PS00504').
motif('PS00509').
motif('PS00510').
motif('PS00518').
motif('PS00521').
motif('PS00526').
motif('PS00554').
motif('PS00557').
motif('PS00564').
motif('PS00565').
motif('PS00566').
motif('PS00572').
motif('PS00573').
motif('PS00581').
motif('PS00583').
motif('PS00595').
motif('PS00599').
motif('PS00600').
motif('PS00606').
motif('PS00611').
motif('PS00615').
motif('PS00625').
motif('PS00626').
motif('PS00627').
motif('PS00633').
motif('PS00636').
motif('PS00637').
motif('PS00646').
motif('PS00657').
motif('PS00658').
motif('PS00659').
motif('PS00670').
motif('PS00674').
motif('PS00675').
motif('PS00678').
motif('PS00680').
motif('PS00681').
motif('PS00685').
motif('PS00686').
motif('PS00687').
motif('PS00690').
motif('PS00697').
motif('PS00709').
motif('PS00720').
motif('PS00723').
motif('PS00724').
motif('PS00733').
motif('PS00735').
motif('PS00736').
motif('PS00737').
motif('PS00741').
motif('PS00748').
motif('PS00749').
motif('PS00750').
motif('PS00751').
motif('PS00752').
motif('PS00753').
motif('PS00755').
motif('PS00760').
motif('PS00761').
motif('PS00763').
motif('PS00765').
motif('PS00770').
motif('PS00782').
motif('PS00783').
motif('PS00796').
motif('PS00797').
motif('PS00801').
motif('PS00802').
motif('PS00813').
motif('PS00815').
motif('PS00816').
motif('PS00821').
motif('PS00822').
motif('PS00824').
motif('PS00825').
motif('PS00841').
motif('PS00842').
motif('PS00845').
motif('PS00847').
motif('PS00854').
motif('PS00859').
motif('PS00860').
motif('PS00865').
motif('PS00866').
motif('PS00867').
motif('PS00868').
motif('PS00870').
motif('PS00871').
motif('PS00888').
motif('PS00889').
motif('PS00893').
motif('PS00901').
motif('PS00903').
motif('PS00904').
motif('PS00905').
motif('PS00910').
motif('PS00914').
motif('PS00915').
motif('PS00916').
motif('PS00924').
motif('PS00927').
motif('PS00928').
motif('PS00929').
motif('PS00933').
motif('PS00944').
motif('PS00945').
motif('PS00951').
motif('PS00952').
motif('PS00954').
motif('PS00955').
motif('PS00957').
motif('PS00959').
motif('PS00961').
motif('PS00972').
motif('PS00973').
motif('PS00975').
motif('PS00976').
motif('PS00989').
motif('PS00990').
motif('PS00991').
motif('PS00993').
motif('PS00997').
motif('PS00998').
motif('PS01000').
motif('PS01001').
motif('PS01002').
motif('PS01003').
motif('PS01013').
motif('PS01019').
motif('PS01020').
motif('PS01021').
motif('PS01024').
motif('PS01025').
motif('PS01030').
motif('PS01032').
motif('PS01036').
motif('PS01042').
motif('PS01046').
motif('PS01047').
motif('PS01067').
motif('PS01071').
motif('PS01077').
motif('PS01082').
motif('PS01088').
motif('PS01089').
motif('PS01101').
motif('PS01112').
motif('PS01118').
motif('PS01119').
motif('PS01132').
motif('PS01133').
motif('PS01145').
motif('PS01152').
motif('PS01154').
motif('PS01159').
motif('PS01166').
motif('PS01168').
motif('PS01175').
motif('PS01183').
motif('PS01184').
motif('PS01186').
motif('PS01188').
motif('PS01199').
motif('PS01202').
motif('PS01215').
motif('PS01216').
motif('PS01223').
motif('PS01235').
motif('PS01236').
motif('PS01239').
motif('PS01240').
motif('PS01244').
motif('PS01247').
motif('PS01248').
motif('PS01251').
motif('PS01256').
motif('PS01257').
motif('PS01280').
motif('PS01281').
| JoseCSantos/GILPS | datasets/metabolism/motif1.pl | Perl | mit | 6,669 |
package Paws::ElasticBeanstalk::ApplicationDescription;
use Moose;
has ApplicationName => (is => 'ro', isa => 'Str');
has ConfigurationTemplates => (is => 'ro', isa => 'ArrayRef[Str|Undef]');
has DateCreated => (is => 'ro', isa => 'Str');
has DateUpdated => (is => 'ro', isa => 'Str');
has Description => (is => 'ro', isa => 'Str');
has ResourceLifecycleConfig => (is => 'ro', isa => 'Paws::ElasticBeanstalk::ApplicationResourceLifecycleConfig');
has Versions => (is => 'ro', isa => 'ArrayRef[Str|Undef]');
1;
### main pod documentation begin ###
=head1 NAME
Paws::ElasticBeanstalk::ApplicationDescription
=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::ElasticBeanstalk::ApplicationDescription object:
$service_obj->Method(Att1 => { ApplicationName => $value, ..., Versions => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::ElasticBeanstalk::ApplicationDescription object:
$result = $service_obj->Method(...);
$result->Att1->ApplicationName
=head1 DESCRIPTION
Describes the properties of an application.
=head1 ATTRIBUTES
=head2 ApplicationName => Str
The name of the application.
=head2 ConfigurationTemplates => ArrayRef[Str|Undef]
The names of the configuration templates associated with this
application.
=head2 DateCreated => Str
The date when the application was created.
=head2 DateUpdated => Str
The date when the application was last modified.
=head2 Description => Str
User-defined description of the application.
=head2 ResourceLifecycleConfig => L<Paws::ElasticBeanstalk::ApplicationResourceLifecycleConfig>
The lifecycle settings for the application.
=head2 Versions => ArrayRef[Str|Undef]
The names of the versions for this application.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::ElasticBeanstalk>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/ElasticBeanstalk/ApplicationDescription.pm | Perl | apache-2.0 | 2,379 |
package Paws::IoT::Certificate;
use Moose;
has CertificateArn => (is => 'ro', isa => 'Str', request_name => 'certificateArn', traits => ['NameInRequest']);
has CertificateId => (is => 'ro', isa => 'Str', request_name => 'certificateId', traits => ['NameInRequest']);
has CreationDate => (is => 'ro', isa => 'Str', request_name => 'creationDate', traits => ['NameInRequest']);
has Status => (is => 'ro', isa => 'Str', request_name => 'status', traits => ['NameInRequest']);
1;
### main pod documentation begin ###
=head1 NAME
Paws::IoT::Certificate
=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::IoT::Certificate object:
$service_obj->Method(Att1 => { CertificateArn => $value, ..., Status => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::IoT::Certificate object:
$result = $service_obj->Method(...);
$result->Att1->CertificateArn
=head1 DESCRIPTION
Information about a certificate.
=head1 ATTRIBUTES
=head2 CertificateArn => Str
The ARN of the certificate.
=head2 CertificateId => Str
The ID of the certificate.
=head2 CreationDate => Str
The date and time the certificate was created.
=head2 Status => Str
The status of the certificate.
The status value REGISTER_INACTIVE is deprecated and should not be
used.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::IoT>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/IoT/Certificate.pm | Perl | apache-2.0 | 1,907 |
#
# Copyright 2022 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::automation::ansible::tower::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 => {
'group' => { name => 'group' },
'inventory' => { name => 'inventory' },
'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 $hosts = $options{custom}->tower_list_hosts(
group => $self->{option_results}->{group},
inventory => $self->{option_results}->{inventory}
);
$disco_stats->{end_time} = time();
$disco_stats->{duration} = $disco_stats->{end_time} - $disco_stats->{start_time};
foreach my $host (@$hosts) {
my %host;
$host{name} = $host->{name};
$host{id} = $host->{id};
$host{description} = $host->{description};
$host{type} = $host->{type};
$host{inventory_id} = $host->{inventory};
$host{inventory_name} = $host->{summary_fields}->{inventory}->{name};
$host{groups} = $host->{summary_fields}->{groups}->{results};
$host{enabled} = $host->{enabled};
push @disco_data, \%host;
}
$disco_stats->{discovered_items} = @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
Resources discovery.
=over 8
=item B<--group>
Specify host group.
=item B<--inventory>
Specify host inventory.
=item B<--prettify>
Prettify JSON output.
=back
=cut
| centreon/centreon-plugins | apps/automation/ansible/tower/mode/discovery.pm | Perl | apache-2.0 | 3,132 |
#
# 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::cloudsql::mysql::mode::queries;
use base qw(cloud::google::gcp::custom::mode);
use strict;
use warnings;
sub get_metrics_mapping {
my ($self, %options) = @_;
my $metrics_mapping = {
'database/mysql/questions' => {
output_string => 'questions: %.2f',
perfdata => {
absolute => {
nlabel => 'database.mysql.questions.count',
format => '%.2f',
min => 0
},
per_second => {
nlabel => 'database.mysql.questions.persecond',
format => '%.2f',
min => 0
}
},
threshold => 'questions',
order => 1
},
'database/mysql/queries' => {
output_string => 'queries: %.2f',
perfdata => {
absolute => {
nlabel => 'database.mysql.queries.count',
format => '%.2f',
min => 0
},
per_second => {
nlabel => 'database.mysql.queries.persecond',
format => '%.2f',
min => 0
}
},
threshold => 'queries',
order => 2
}
};
return $metrics_mapping;
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
'dimension-name:s' => { name => 'dimension_name', default => 'resource.labels.database_id' },
'dimension-operator:s' => { name => 'dimension_operator', default => 'equals' },
'dimension-value:s' => { name => 'dimension_value' },
'filter-metric:s' => { name => 'filter_metric' },
"per-second" => { name => 'per_second' },
'timeframe:s' => { name => 'timeframe' },
'aggregation:s@' => { name => 'aggregation' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$self->{gcp_api} = 'cloudsql.googleapis.com';
$self->{gcp_dimension_name} = (!defined($self->{option_results}->{dimension_name}) || $self->{option_results}->{dimension_name} eq '') ? 'resource.labels.database_id' : $self->{option_results}->{dimension_name};
$self->{gcp_dimension_zeroed} = 'resource.labels.database_id';
$self->{gcp_instance_key} = 'resource.labels.database_id';
$self->{gcp_dimension_operator} = $self->{option_results}->{dimension_operator};
$self->{gcp_dimension_value} = $self->{option_results}->{dimension_value};
}
1;
__END__
=head1 MODE
Check mysql queries metrics.
Example:
perl centreon_plugins.pl --plugin=cloud::google::gcp::cloudsql::mysql::plugin
--mode=diskio --dimension-value=mydatabaseid --filter-metric='queries'
--aggregation='average' --verbose
Default aggregation: 'average' / All aggregations are valid.
=over 8
=item B<--dimension-name>
Set dimension name (Default: 'resource.labels.database_id'). Can be: 'resources.labels.region'.
=item B<--dimension-operator>
Set dimension operator (Default: 'equals'. Can also be: 'regexp', 'starts').
=item B<--dimension-value>
Set dimension value (Required).
=item B<--filter-metric>
Filter metrics (Can be: 'database/mysql/questions', 'database/mysql/queries') (Can be a regexp).
=item B<--timeframe>
Set timeframe in seconds (i.e. 3600 to check last hour).
=item B<--aggregation>
Set monitor aggregation (Can be multiple, Can be: 'minimum', 'maximum', 'average', 'total').
=item B<--warning-*> B<--critical-*>
Thresholds (Can be: 'queries', 'questions').
=item B<--per-second>
Change the data to be unit/sec.
=back
=cut
| Tpo76/centreon-plugins | cloud/google/gcp/cloudsql/mysql/mode/queries.pm | Perl | apache-2.0 | 4,642 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package network::juniper::common::junos::mode::listbgppeers;
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 => {});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
}
my %map_peer_state = (
1 => 'idle',
2 => 'connect',
3 => 'active',
4 => 'opensent',
5 => 'openconfirm',
6 => 'established',
);
my %map_peer_status = (
1 => 'halted',
2 => 'running',
);
my $oid_jnxBgpM2PeerTable = '.1.3.6.1.4.1.2636.5.1.1.2.1.1';
my $mapping = {
jnxBgpM2PeerIdentifier => { oid => '.1.3.6.1.4.1.2636.5.1.1.2.1.1.1.1' },
jnxBgpM2PeerState => { oid => '.1.3.6.1.4.1.2636.5.1.1.2.1.1.1.2', map => \%map_peer_state },
jnxBgpM2PeerStatus => { oid => '.1.3.6.1.4.1.2636.5.1.1.2.1.1.1.3', map => \%map_peer_status },
};
sub manage_selection {
my ($self, %options) = @_;
$self->{peers} = {};
my $snmp_result = $options{snmp}->get_table(
oid => $oid_jnxBgpM2PeerTable,
start => $mapping->{jnxBgpM2PeerIdentifier}->{oid},
end => $mapping->{jnxBgpM2PeerStatus}->{oid},
nothing_quit => 1
);
foreach my $oid (keys %{$snmp_result}) {
next if ($oid !~ /^$mapping->{jnxBgpM2PeerIdentifier}->{oid}\.(.*)$/);
my $instance = $1;
my $result = $options{snmp}->map_instance(
mapping => $mapping,
results => $snmp_result,
instance => $instance
);
$result->{jnxBgpM2PeerIdentifier} = join('.', map { hex($_) } unpack('(H2)*', $result->{jnxBgpM2PeerIdentifier}));
$self->{peers}->{$instance} = { %{$result} };
}
}
sub run {
my ($self, %options) = @_;
$self->manage_selection(%options);
foreach my $instance (sort keys %{$self->{peers}}) {
$self->{output}->output_add(
long_msg => '[name = ' . $self->{peers}->{$instance}->{jnxBgpM2PeerIdentifier} .
"] [status = '" . $self->{peers}->{$instance}->{jnxBgpM2PeerStatus} . "'] [state = '" .
$self->{peers}->{$instance}->{jnxBgpM2PeerState} . "']"
);
}
$self->{output}->output_add(severity => 'OK',
short_msg => 'List peers:');
$self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1);
$self->{output}->exit();
}
sub disco_format {
my ($self, %options) = @_;
$self->{output}->add_disco_format(elements => ['name', 'status', 'state']);
}
sub disco_show {
my ($self, %options) = @_;
$self->manage_selection(%options);
foreach my $instance (sort keys %{$self->{peers}}) {
$self->{output}->add_disco_entry(
name => $self->{peers}->{$instance}->{jnxBgpM2PeerIdentifier},
status => $self->{peers}->{$instance}->{jnxBgpM2PeerStatus},
state => $self->{peers}->{$instance}->{jnxBgpM2PeerState}
);
}
}
1;
__END__
=head1 MODE
List peers.
=over 8
=back
=cut
| Tpo76/centreon-plugins | network/juniper/common/junos/mode/listbgppeers.pm | Perl | apache-2.0 | 3,962 |
Return-Path: <pdcawley@bofh.org.uk>
Delivered-To: rspier@newbabe.mengwong.com
Received: from newbabe.mengwong.com [208.210.125.227]
by localhost with IMAP (fetchmail-6.2.0)
for rspier@localhost (single-drop); Tue, 14 Jan 2003 08:17:13 -0800 (PST)
Received: from cali-2.pobox.com (cali-2.pobox.com [64.71.166.115])
by newbabe.mengwong.com (Postfix) with ESMTP id CDB7F1F68B
for <rspier@newbabe.mengwong.com>; Tue, 14 Jan 2003 11:13:50 -0500 (EST)
Received: from cali-2.pobox.com (localhost.localdomain [127.0.0.1])
by cali-2.pobox.com (Postfix) with ESMTP
id 278923E84B; Tue, 14 Jan 2003 11:13:47 -0500 (EST)
Delivered-To: rspier@pobox.com
Received: from mail.hybyte.com (unknown [217.89.91.12])
by cali-2.pobox.com (Postfix) with SMTP id DB07B3E9E2
for <rspier@pobox.com>; Tue, 14 Jan 2003 11:10:16 -0500 (EST)
Received: (qmail 6679 invoked from network); 14 Jan 2003 16:08:09 -0000
Received: from pdcawley@bofh.org.uk by mail.hybyte.com by uid 504 with qmail-scanner-1.13
(uvscan: v4.1.40/v4242. Clear:.
Processed in 0.351218 secs); 14 Jan 2003 16:08:09 -0000
Received: from unknown (HELO localhost) (217.89.91.13)
by 0 with SMTP; 14 Jan 2003 16:08:09 -0000
Received: from pdcawley by localhost with local (Exim 4.10)
id H8POX8-000BNQ-00; Tue, 14 Jan 2003 16:10:20 +0000
To: Robert Spier <rspier@pobox.com>,
Simon Cozens <simon@simon-cozens.org>
Subject: This week's summary
From: Piers Cawley <pdcawley@bofh.org.uk>
Date: Tue, 14 Jan 2003 16:10:20 +0000
Message-ID: <m27kd790gj.fsf@TiBook.bofh.org.uk>
User-Agent: Gnus/5.090011 (Oort Gnus v0.11) XEmacs/21.5 (burdock,
powerpc-apple-darwin6.3)
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment; filename=p6summary.2003-01-12.pod
Content-Description: summary for week ending 20030112
X-Spam-Status: No, hits=-1.8 required=5.0
tests=AWL,SPAM_PHRASE_01_02,USER_AGENT,USER_AGENT_GNUS_UA
version=2.43
X-Spam-Level:
=head1 The Perl 6 Summary for the week ending 20030112
... and we're back. Yup, it's summary time again. We'll dive straight
in with perl6-internals (as if you expected anything else).
=head2 More thoughts on DOD
Leopold TE<ouml>tsch posted a test program showing the effects of PMC
size and timing of garbage collection and allocation and suggested
ways of improving the GC system based on the conclusions he drew from
its results. Leo, Dan and Mitchell N Charity discussed this further
and tried a few different approaches to try and improve performance
(though Mitchell did worry about premature optimization). Work in this
area is ongoing.
L<http://groups.google.com/groups?threadm=3E1976F7.1060106%40toetsch.at>
=head2 The Perl 6 Parser
Dan asked about the current state of the Perl 6 parser, wanting to
know what was and wasn't implemented and wondered about adding the
Perl 6 tests into the standard parrot test suite. Sean O'Rourke and
Joseph F. Ryan both gave a summaries of where things stood. Joseph
also suggested a few refactorings of the parser to deal with the
fluidity of the current spec (almost all the operators have changed
symbols since the parser was first written for instance).
L<http://groups.google.com/groups?threadm=a05200f15ba425a3d908d%40%5B192.168.2.1%5D>
=head2 LXR - Source code indexing
Last week I said that Robert Spier had 'started work on getting a
browseable, cross referenced version of the Parrot source up on
perl.org'. What actually happened was that Robert asked Zach Lipton to
do the work. This week Zach delivered the goods which, I must say,
look fabulous.
I'm sure that if someone were to extend LXR so it had a better
understanding of .pasm, .pmc, .ops and other special Parrot source
types then the community would be very grateful indeed. I know I would.
L<http://groups.google.com/groups?threadm=BA41F83F.8F2D%25zach%40zachlipton.com> -- Announcement
L<http://tinderbox.perl.org/lxr/parrot/source>
=head2 Thoughts on infant mortality
Piers Cawley offered what he thought might be a new approach to
dealing with the infant mortality problem which got efficiently shot
down by Leo TE<ouml>tsch. Which led to further discussion of possible
answers, and it looks like Leo's proposed solution involving a small
amount of code reordering and early anchoring will be the one that's
tried next. All being well it won't require walking the C stack and
hardware register set, which can only be a good thing.
Later on, Leo asked if it'd be okay to check in his work so far on
redoing the GC because he was up to 15 affected files and was starting
to worry about integration hell. Steve Fink wasn't sure about one of
his changes, so Leo checked everything else in.
L<http://groups.google.com/groups?threadm=m27kdere5g.fsf%40TiBook.bofh.org.uk>
L<http://groups.google.com/groups?threadm=3E1D47B6.20301%40toetsch.at>
=head2 Objects, finally (try 1)
Last week I mentioned that Leon Brocard's wishlist for the next Parrot
iteration included Objects. This week Dan posted his first draft of
what Parrot Objects would and wouldn't be able to do. The eleventh
entry on Dan's list (Objects are all orange) seemed to be custom made
to please Leon. There was a fair amount of discussion (of course), but
the consensus was positive.
L<http://groups.google.com/groups?threadm=a05200f06ba439cb1436b%40%5B192.168.2.1%5D>
=head2 The benchmarking problem
Nicholas Clark crossposted to p5p and perl6-internals to discuss the
problems of benchmarking parrot against perl 5. One of parrot's aims
is, of course, to go faster than perl 5. The problem is, how do you
measure 'faster'? Nicholas has been working on making perl 5 go faster
and was distressed to find out that using 'perlbench' a patch of his
went 5% faster, 1% slower, 0% and 1% faster, depending on what
machine/compiler combination he ran the benchmark on. Leo TE<ouml>tsch
commented that he'd found performance varying by over 50% in a JIT
test, depending on the position of a loop in memory. Andreas Koenig
commented that he'd come to the conclusion that bugs in glibc meant
that there was little point in benchmarking Perl at all if it was
built with a glibc older than version 2.3 (apparently malloc/free
proved to be gloriously erratic...) I'm afraid not much was actually
resolved though.
L<http://groups.google.com/groups?threadm=20030111190521.GK283%40Bagpuss.unfortu.net>
=head1 Meanwhile, in perl6-language
The discussion of Variable types vs Value types continued from the
previous week. Dan opined that Arrays weren't necessarily objects,
which brought forth squawks from Piers Cawley who pointed out that
being able to do:
class PersistentList is Array {
method FETCH ($index) {
...
}
...
}
would be much nicer than tying a value in the Perl 5ish fashion. Dan
reckoned that delegation would probably be enough which, IMHO seemed
to miss the point. Various other people chimed in to, essentially,
tell Dan that he was wrong, but I'm not sure Dan agreed with them.
Meanwhile, in a subthread sprouting lower on the thread tree, Damian
pointed out that there were two types associated with any Perl
variable, the 'storage type' and the 'implementation type' (see his
post for details, but essentially the storage type is the type
associated with the contents of a variable and the implementation type
is the type of the 'thing' that does the storing (usually one of
SCALAR, HASH or ARRAY -- ie, related to the variable's sigil)
specifying a different implementation type will probably be how Perl 6
does tying.)
L<http://groups.google.com/groups?threadm=a05200f07ba3e5ebbf80c%40%5B192.168.3.1%5D>
L<http://groups.google.com/groups?threadm=3E1BF672.2020606%40conway.org>
=head2 Array Questions
In a thread that spilt over from the previous discussion about
whether arrays were objects or not, Michael Lazzaro put up a list of
example usages that seem to imply rather strongly that arrays are
either objects or indistinguishable from them and there was general
muttering that being able to overload tied Perl containers in this way
was a neat way of implementing tie semantics. Mr Nobody attempted to
restart the left to right versus right to left argument all over
again. There was also some discussion of the sickness of C<< my Foo
@foo is Foo >> (which, in Perl 5ish parlance creates a tied array
(using Foo as the tying class) which can only contain objects in class
Foo.) Damian agreed that this was definitely sick, and that he for one
would be making use of it.
L<http://groups.google.com/groups?threadm=6B9F6C55-226A-11D7-81AD-00050245244A%40cognitivity.com>
=head2 L2R/R2L syntax
Argh! No! It's back and this time it means business. The dreaded
left->right versus right->left thing came back, and this time it was
Damian applying the electrodes to the corpse. Of course, it being
Damian he was instantly forgiven as he came up with the very cool,
very low precedence C<< ~> >> and C<< <~ >> operators, allowing you to
write
@out = @a ~> grep {...} ~> map {...} ~> sort;
Which is, to these eyes at least, lovely. See Damian's post for the
full details. The general response to this was definitely on the
'lovely' side of the balance, though one detractor did induce a sense
of humour failure on Damian's part. There was also a certain amount of
discussion about whether this was exactly the right syntax to go with
the semantics, but where would perl6-language be without a great deal
of syntactic quibbling? (A good deal easier to summarize). The most
popular alternatives were C<< |> >> and C<< <| >>. There was also a
certain amount of discussion of what I can only describe as 'evil'
uses of the syntax, involving arrows going in different directions in
one statement. Rafael Garcia-Suarez earned at least one giggle when he
suggested that we just needed C<< v~ >> C<< ^~ >> and we had our own
flavour of Befunge.
There was a fair amount more discussion, mostly thrashing out details
and edge cases.
L<http://groups.google.com/groups?threadm=3E1BA592.6050902%40conway.org>
=head2 "Disappearing" code
John Siracusa wondered if there would be a perl6ish way of creating
code that was 'the spiritual equivalent of #ifdef, only Perlish'. To
which the answer is, of course, 'yes'. Damian showed off a neat trick
(modulo a couple of pretty typos) with an immediate function that
demonstrated using Perl 6 as its own macro language.
L<http://groups.google.com/groups?threadm=BA438428.E548%25siracusa%40mindspring.com>
L<http://groups.google.com/groups?threadm=BA447213.2B258%25siracusa%40mindspring.com> -- Damian's neat trick
=head1 In Brief
Jim Radford fixed some typos in the F<rx.ops> documentation.
=head1 Who's Who in Perl 6
=over
=item Who are you?
Steve Fink. Some guy who writes code.
=item What do you do for/with Perl 6?
The only thing I set out to do was implement a regular expression
compiler. Along the way, I seem to have implemented hashtables,
patched the configuration system, messed with memory management,
implemented some stuff for IMCC, beefed up the PMC file parser, fixed
some problems with the JIT, and a few other things. Then I got a job
and ran out of time to work on parrot, so they made me pumpking. And I
still haven't made it that far with the regex compiler.
=item Where are you coming from?
Computer games, originally. First language BASIC, second language 6502
assembly. Then a failed attempt at C, then more successful encounters
with Pascal and 68000 assembly, and then C++. Next, a few more
assembly languages together with SML, NESL, Lisp, Scheme, COBOL, Tcl,
Prolog, and a few others. And at last Perl4 and then Perl5. Oh, and
Java, fairly recently. My day job is now in a combination of Perl5 and
C++, as well as C when nobody's looking.
=item When do you think Perl 6 will be released?
Probably smoothing the path for other developers and keeping them
motivated. My highest priority is applying (and testing) other
people's patches, since the mostly likely reason for someone to lose
interest is to not have their hard work make it into the distribution.
I would also like to somehow make people's contributions more visible
-- anyone who has contributed anything significant should at least be
able to point to something and say "Look! I did that! See my name?!"
=item I said, when do you think Perl 6 will be released?
Obviously Leopold TE<ouml>tsch. Anyone paying an iota of attention
would know that. Particularly someone who's been writing the
summaries, unless you're stupid or something. Leo's amazing; I don't
know how he finds the time. To accomplish that much, I'd need to be
working full-time about 26 hours a day.
=item No, really. When do you think Perl 6 will be released?
No, not really. I was originally thinking of Perl6 when I got
involved, but since then the Parrot VM itself has become more
interesting to me. Although I still wish Perl6 development would pick up --
there's a lot that can be done even with the limited amount of the
language that's been defined. Sean O'Rourke did an excellent job in a
short amount of time, but it looks like Real Life has drawn him back
into its fold, and nobody seems to have picked up the slack.
=item Why are you doing this?
Heh. That is the question, isn't it? Making a release is probably the
most concrete measure of how I'm doing as a pumpking, and by that
standard I'm a dismal failure. As soon as we reclaim the tinderbox
(and without dropping any machines off it in order to do so!)
Everything else I wanted to get in is already there.
=item You have five words. Describe yourself.
No, I don't think so. Maybe I'm wrong, but I know that I personally
had to put aside a lot of the actual coding I was working on in order
to concentrate on making sure everyone else's changes were being given
proper consideration. I'd much rather relieve him of that burden, and
let him continue to exercise his demonstrated talent at churning out
quality code.
=item Do you have anything to declare?
No. It kind of makes sense, but I remember how I first started by
rewriting a bunch of Dan Sugalski's code, and then seeing most of my
code get rewritten. I used to be disturbed by that, but now I think of
it more as a badge of honor -- it proves that what I wrote was worth
rewriting. Much more so in Dan's case, I suppose, since he stated
up-front that he was merely doing a reference implementation of a
design. Dan's done an amazing job of laying out a design that hasn't
needed to change at its core, and so has been a very dependable guide
to the implementation of the backbone. But even in my case, I can see
a number of ideas that were carried through in the reimplementation,
even if no actual code survived. (Interestingly, my tests did. Which
kind of makes sense if you think about it.)
=item Are you finished yet?
Why yes, thank you.
=back
Ahem. Thanks Steve. Really.
=head1 Acknowledgements
Another Monday evening, another summary running over into Tuesday
morning. Ah well. Distractions were provided by the usual suspects
(Mike and Sully, our ginger kittens), supplemented this week by a
horrible cold (the compulsion to find a tissue does tend to derail the
train of thought).
Proofreading was once more handled by Aspell and me. This week we even
made sure that the Who's Who section contains the name of the person
answering the questions rather than making you wait 'til the
acknowledgements section.
Speaking of which, many thanks to Steve Fink for his answers to the
questionnaire (well, to the questions he wanted to answer anyway). The
questionnaire queue is now quite empty so, unless a few more folks in
the Perl 6 community send me some answers soon then the Who's Who
section may be going on hiatus. Send your answers (or request the
'correct' question list from) L<5Ws@bofh.org.uk>.
If you didn't like this summary, how did you get this far? If you did
like it, please consider one or more of the following options:
=over
=item *
Send money to the Perl Foundation at
L<http://donate.perl-foundation.org/> and help support the ongoing
development of Perl 6.
=item *
Get involve in the Perl 6 process. The mailing lists are open to
all. L<http://dev.perl.org/perl6/> and L<http://www.parrotcode.org/>
are good starting points with links to the appropriate mailing lists.
=item *
Send feedback, flames, money and or a couple of first class flights to
from London to Portland for this year's OSCON to
L<mailto:p6summarizer@bofh.org.uk> ("Aim high!" they told me.)
=back
The fee paid for the publication of these summarise on perl.com is
paid directly to the Perl Foundation.
The Perl 6 Summarizer disclaims any and all responsibility for the
sanity of his readers; he's having enough trouble hanging onto his
own.
| autarch/perlweb | docs/dev/perl6/list-summaries/2003/p6summary.2003-01-12.pod | Perl | apache-2.0 | 16,688 |
package UI::Parameter;
#
#
# 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.
#
#
#
# JvD Note: you always want to put Utils as the first use. Sh*t don't work if it's after the Mojo lines.
use UI::Utils;
use Mojo::Base 'Mojolicious::Controller';
use Data::Dumper;
#Table View
sub index {
my $self = shift;
my $filter = $self->param('filter');
my $value = $self->param('byvalue');
my $filter_title = "Cachegroup/Profile name";
if ( defined($filter) ) {
$self->stash(
filter => $filter,
value => $value
);
$filter_title = $filter . " name";
$filter_title =~ s/(^\w)/\U$1/x;
}
$self->stash( filter_title => $filter_title );
&navbarpage($self);
}
sub view {
my $self = shift;
my $mode = $self->param('mode');
my $id = $self->param('id');
my $rs_param = $self->db->resultset('Parameter')->search( { id => $id } );
my $data = $rs_param->single;
$self->conceal_secure_parameter_value( $data->{'_column_data'}{'secure'}, \$data->{'_column_data'}{'value'} );
$self->stash( parameter => $data );
&stash_role($self);
my %assigned_profiles = $self->get_assigned_profiles();
my %assigned_cachegroups = $self->get_assigned_cachegroups();
$self->stash(
assigned_profiles => \%assigned_profiles,
assigned_cachegroups => \%assigned_cachegroups,
fbox_layout => 1,
);
}
sub get_assigned_profiles {
my $self = shift;
my $id = $self->param('id');
my @profile_ids = $self->db->resultset('ProfileParameter')->search( { parameter => $id } )->get_column('profile')->all;
my %assigned_profiles;
foreach my $p_id (@profile_ids) {
my $profile = $self->db->resultset('Profile')->search( { id => $p_id } )->single;
$assigned_profiles{$p_id} = {
desc => $profile->description,
name => $profile->name
};
}
return %assigned_profiles;
}
sub get_assigned_cachegroups {
my $self = shift;
my $id = $self->param('id');
my @cg_ids = $self->db->resultset('CachegroupParameter')->search( { parameter => $id } )->get_column('cachegroup')->all;
my %assigned_cachegroups;
foreach my $l_id (@cg_ids) {
my $cachegroup = $self->db->resultset('Cachegroup')->search( { id => $l_id } )->single;
$assigned_cachegroups{$l_id} = {
short_name => $cachegroup->short_name,
name => $cachegroup->name
};
}
return %assigned_cachegroups;
}
# Read
sub readparameter {
my $self = shift;
my @data;
my $orderby = "name";
$orderby = $self->param('orderby') if ( defined $self->param('orderby') );
my $rs_data = $self->db->resultset("Parameter")->search( undef, { order_by => $orderby } );
while ( my $row = $rs_data->next ) {
my $value = $row->value;
$self->conceal_secure_parameter_value( $row->secure, \$value );
push(
@data, {
"id" => $row->id,
"name" => $row->name,
"config_file" => $row->config_file,
"value" => $value,
"secure" => $row->secure,
"last_updated" => $row->last_updated,
}
);
}
$self->render( json => \@data );
}
sub readparameter_for_profile {
my $self = shift;
my $profile_name = $self->param('profile_name');
my $rs_data = $self->db->resultset("ProfileParameter")->search( { 'profile.name' => $profile_name }, { prefetch => [ 'parameter', 'profile' ] } );
my @data = ();
while ( my $row = $rs_data->next ) {
my $value = $row->parameter->value;
$self->conceal_secure_parameter_value( $row->parameter->secure, \$value );
push(
@data, {
"name" => $row->parameter->name,
"config_file" => $row->parameter->config_file,
"value" => $value,
"secure" => $row->parameter->secure,
"last_updated" => $row->parameter->last_updated,
}
);
}
$self->render( json => \@data );
}
# Delete
sub delete {
my $self = shift;
my $id = $self->param('id');
if ( !&is_oper($self) ) {
$self->flash( alertmsg => "No can do. Get more privs." );
}
else {
my $secure = $self->db->resultset('Parameter')->search( { id => $id } )->get_column('secure')->single();
if ( (1==$secure) && !&is_admin($self) ) {
$self->flash( alertmsg => "Forbidden. Admin role required to delete a secure parameter." );
}
else {
my $p_name = $self->db->resultset('Parameter')->search( { id => $id } )->get_column('name')->single();
my $delete = $self->db->resultset('Parameter')->search( { id => $id } );
$delete->delete();
&log( $self, "Delete parameter " . $p_name, "UICHANGE" );
}
}
return $self->redirect_to('/close_fancybox.html');
}
# Update
sub update {
my $self = shift;
my $id = $self->param('id');
if ( $self->is_valid() ) {
my $update = $self->db->resultset('Parameter')->find( { id => $self->param('id') } );
$update->name( $self->param('parameter.name') );
$update->config_file( $self->param('parameter.config_file') );
$update->value( $self->param('parameter.value') );
if ( &is_admin($self) ) {
my $secure = defined( $self->param('parameter.secure') ) ? $self->param('parameter.secure') : 0;
$update->secure($secure);
}
$update->update();
# if the update has failed, we don't even get here, we go to the exception page.
&log( $self, "Update parameter with name: " . $self->param('parameter.name'), "UICHANGE" );
$self->flash( message => "Parameter updated successfully." );
return $self->redirect_to( '/parameter/' . $self->param('id') );
}
else {
&stash_role($self);
my $rs_param = $self->db->resultset('Parameter')->search( { id => $id } );
my $data = $rs_param->single;
$self->conceal_secure_parameter_value( $data->{'_column_data'}{'secure'}, \$data->{'_column_data'}{'value'} );
my %assigned_profiles = &get_assigned_profiles($self);
my %assigned_cachegroups = &get_assigned_cachegroups($self);
$self->stash(
assigned_profiles => \%assigned_profiles,
assigned_cachegroups => \%assigned_cachegroups,
parameter => $data,
fbox_layout => 1
);
$self->render('/parameter/view');
}
}
sub is_valid {
my $self = shift;
my $mode = shift;
my $name = $self->param('parameter.name');
my $config_file = $self->param('parameter.config_file');
my $value = $self->param('parameter.value');
my $secure = defined( $self->param('parameter.secure') ) && $self->param('parameter.secure');
#Check permissions
if ( !&is_oper($self) ) {
$self->field('parameter.name')->is_equal( "", "You do not have the permissions to perform this operation!" );
}
if ( !&is_admin($self) ) {
my $id = $self->param('id');
if ( defined($id) ) {
my $rs_param = $self->db->resultset('Parameter')->search( { id => $id } );
my $data = $rs_param->single;
my $original_secure = $data->{'_column_data'}{'secure'};
if ( $original_secure == 1 ) {
$self->field('parameter.name')->is_equal( "", "You must be an ADMIN to modify a secure parameter!" );
}
} else {
if ( $secure == 1 ) {
$self->field('parameter.name')->is_equal( "", "You must be an ADMIN to create a secure parameter!" );
}
}
}
#Check required fields
$self->field('parameter.name')->is_required;
$self->field('parameter.config_file')->is_required;
$self->field('parameter.value')->is_required;
#Make sure the same Parameter doesn't already exist
my $existing_param =
$self->db->resultset('Parameter')->search( { name => $name, value => $value, config_file => $config_file, secure => $secure } )->get_column('id')->single();
if ($existing_param) {
$self->field('parameter.name')
->is_equal( "", "A parameter with the name \"$name\", config_file \"$config_file\", and value \"$value\" already exists." );
}
return $self->valid;
}
# Create
sub create {
my $self = shift;
my $new_id = -1;
if ( $self->is_valid() ) {
my $secure = defined( $self->param('parameter.secure') ) ? $self->param('parameter.secure') : 0;
my $insert = $self->db->resultset('Parameter')->create(
{
name => $self->param('parameter.name'),
config_file => $self->param('parameter.config_file'),
value => $self->param('parameter.value'),
secure => $secure,
}
);
$insert->insert();
# if the insert has failed, we don't even get here, we go to the exception page.
&log( $self, "Create parameter with name " . $self->param('parameter.name') . " and value " . $self->param('parameter.value'), "UICHANGE" );
$new_id = $insert->id();
if ( $new_id == -1 ) {
my $referer = $self->req->headers->header('referer');
return $self->redirect_to($referer);
}
else {
$self->flash( message => "Parameter added successfully! Please associate to profiles or cache groups now." );
return $self->redirect_to( '/parameter/' . $new_id );
}
}
else {
&stash_role($self);
$self->stash( parameter => { secure => 0 }, fbox_layout => 1 );
$self->render('parameter/add');
}
}
# add parameter view
sub add {
my $self = shift;
&stash_role($self);
$self->stash( fbox_layout => 1, parameter => { secure => 0 } );
}
# conceal secure parameter value
sub conceal_secure_parameter_value {
my $self = shift;
my $secure = shift;
my $value = shift;
if ( $secure == 1 && !&is_admin($self) ) {
$$value = '*********';
}
}
1;
| knutsel/traffic_control-1 | traffic_ops/app/lib/UI/Parameter.pm | Perl | apache-2.0 | 9,625 |
#
# Copyright 2022 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package storage::ibm::storwize::ssh::mode::components::portfc;
use strict;
use warnings;
sub load {
my ($self) = @_;
$self->{ssh_commands} .= 'echo "==========lsportfc=========="; lsportfc -delim : ; echo "===============";';
}
sub check {
my ($self) = @_;
$self->{output}->output_add(long_msg => "Checking portfc");
$self->{components}->{portfc} = {name => 'portfc', total => 0, skip => 0};
return if ($self->check_filter(section => 'portfc'));
return if ($self->{results} !~ /==========lsportfc==.*?\n(.*?)==============/msi);
my $content = $1;
my $result = $self->{custom}->get_hasharray(content => $content, delim => ':');
foreach (@$result) {
next if ($self->check_filter(section => 'portfc', instance => $_->{id}));
$self->{components}->{portfc}->{total}++;
my $name = $_->{node_name} . "." . $_->{WWPN};
$self->{output}->output_add(
long_msg => sprintf(
"portfc '%s' status is '%s' [instance: %s].",
$name,
$_->{status},
$_->{id}
)
);
my $exit = $self->get_severity(section => 'portfc', value => $_->{status});
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(
severity => $exit,
short_msg => sprintf(
"PortFC '%s' status is '%s'",
$name,
$_->{status}
)
);
}
}
}
1;
| centreon/centreon-plugins | storage/ibm/storwize/ssh/mode/components/portfc.pm | Perl | apache-2.0 | 2,341 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package cloud::aws::elb::classic::mode::targetshealth;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
my %metrics_mapping = (
'HealthyHostCount' => {
'output' => 'Healthy Hosts',
'label' => 'healthyhostcount',
'nlabel' => 'elb.healthyhostcount.count',
},
'UnHealthyHostCount' => {
'output' => 'Unhealthy Hosts',
'label' => 'unhealthyhostcount',
'nlabel' => 'elb.unhealthyhostcount.count',
},
);
my %map_type = (
"loadbalancer" => "LoadBalancerName",
"availabilityzone" => "AvailabilityZone",
);
sub prefix_metric_output {
my ($self, %options) = @_;
my $availability_zone = "";
if (defined($options{instance_value}->{availability_zone}) && $options{instance_value}->{availability_zone} ne '') {
$availability_zone = "[$options{instance_value}->{availability_zone}] ";
}
return ucfirst($self->{option_results}->{type}) . " '" . $options{instance_value}->{display} . "' " . $availability_zone;
}
sub prefix_statistics_output {
my ($self, %options) = @_;
return "Statistic '" . $options{instance_value}->{display} . "' Metrics ";
}
sub long_output {
my ($self, %options) = @_;
my $availability_zone = "";
if (defined($options{instance_value}->{availability_zone}) && $options{instance_value}->{availability_zone} ne '') {
$availability_zone = "[$options{instance_value}->{availability_zone}] ";
}
return "Checking " . ucfirst($self->{option_results}->{type}) . " '" . $options{instance_value}->{display} . "' " . $availability_zone;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'metrics', type => 3, cb_prefix_output => 'prefix_metric_output', cb_long_output => 'long_output',
message_multiple => 'All elb metrics are ok', indent_long_output => ' ',
group => [
{ name => 'statistics', display_long => 1, cb_prefix_output => 'prefix_statistics_output',
message_multiple => 'All metrics are ok', type => 1, skipped_code => { -10 => 1 } },
]
}
];
foreach my $metric (keys %metrics_mapping) {
my $entry = {
label => $metrics_mapping{$metric}->{label},
nlabel => $metrics_mapping{$metric}->{nlabel},
set => {
key_values => [ { name => $metric }, { name => 'display' } ],
output_template => $metrics_mapping{$metric}->{output} . ': %.2f',
perfdatas => [
{ value => $metric , template => '%.2f', label_extra_instance => 1 }
],
}
};
push @{$self->{maps_counters}->{statistics}}, $entry;
}
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1);
bless $self, $class;
$options{options}->add_options(arguments => {
"type:s" => { name => 'type' },
"name:s@" => { name => 'name' },
"availability-zone:s" => { name => 'availability_zone' },
"filter-metric:s" => { name => 'filter_metric' },
"statistic:s@" => { name => 'statistic' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
if (!defined($self->{option_results}->{type}) || $self->{option_results}->{type} eq '') {
$self->{output}->add_option_msg(short_msg => "Need to specify --type option.");
$self->{output}->option_exit();
}
if ($self->{option_results}->{type} ne 'loadbalancer' && $self->{option_results}->{type} ne 'availabilityzone') {
$self->{output}->add_option_msg(short_msg => "Instance type '" . $self->{option_results}->{type} . "' is not handled for this mode");
$self->{output}->option_exit();
}
if ($self->{option_results}->{type} eq 'availabilityzone' && defined($self->{option_results}->{availability_zone})) {
$self->{output}->add_option_msg(short_msg => "Can't specify --availability-zone option with availabilityzone instance's type");
$self->{output}->option_exit();
}
if (!defined($self->{option_results}->{name}) || $self->{option_results}->{name} eq '') {
$self->{output}->add_option_msg(short_msg => "Need to specify --name option.");
$self->{output}->option_exit();
}
foreach my $instance (@{$self->{option_results}->{name}}) {
if ($instance ne '') {
push @{$self->{aws_instance}}, $instance;
}
}
$self->{aws_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 600;
$self->{aws_period} = defined($self->{option_results}->{period}) ? $self->{option_results}->{period} : 60;
$self->{aws_statistics} = ['Average'];
if (defined($self->{option_results}->{statistic})) {
$self->{aws_statistics} = [];
foreach my $stat (@{$self->{option_results}->{statistic}}) {
if ($stat ne '') {
push @{$self->{aws_statistics}}, ucfirst(lc($stat));
}
}
}
foreach my $metric (keys %metrics_mapping) {
next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne ''
&& $metric !~ /$self->{option_results}->{filter_metric}/);
push @{$self->{aws_metrics}}, $metric;
}
}
sub manage_selection {
my ($self, %options) = @_;
my %metric_results;
foreach my $instance (@{$self->{aws_instance}}) {
push @{$self->{aws_dimensions}}, { Name => $map_type{$self->{option_results}->{type}}, Value => $instance };
if (defined($self->{option_results}->{availability_zone}) && $self->{option_results}->{availability_zone} ne '') {
push @{$self->{aws_dimensions}}, { Name => 'AvailabilityZone', Value => $self->{option_results}->{availability_zone} };
}
$metric_results{$instance} = $options{custom}->cloudwatch_get_metrics(
namespace => 'AWS/ELB',
dimensions => $self->{aws_dimensions},
metrics => $self->{aws_metrics},
statistics => $self->{aws_statistics},
timeframe => $self->{aws_timeframe},
period => $self->{aws_period},
);
foreach my $metric (@{$self->{aws_metrics}}) {
foreach my $statistic (@{$self->{aws_statistics}}) {
next if (!defined($metric_results{$instance}->{$metric}->{lc($statistic)}) && !defined($self->{option_results}->{zeroed}));
$self->{metrics}->{$instance}->{display} = $instance;
$self->{metrics}->{$instance}->{availability_zone} = $self->{option_results}->{availability_zone};
$self->{metrics}->{$instance}->{statistics}->{lc($statistic)}->{display} = $statistic;
$self->{metrics}->{$instance}->{statistics}->{lc($statistic)}->{$metric} = defined($metric_results{$instance}->{$metric}->{lc($statistic)}) ? $metric_results{$instance}->{$metric}->{lc($statistic)} : 0;
}
}
}
if (scalar(keys %{$self->{metrics}}) <= 0) {
$self->{output}->add_option_msg(short_msg => 'No metrics. Check your options or use --zeroed option to set 0 on undefined values');
$self->{output}->option_exit();
}
}
1;
__END__
=head1 MODE
Check Classic ELB instances health.
Example:
perl centreon_plugins.pl --plugin=cloud::aws::elb::classic::plugin --custommode=paws --mode=instancehealth --region='eu-west-1'
--type='loadbalancer' --name='elb-www-fr' --critical-healthyhostcount='10' --verbose
See 'https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-cloudwatch-metrics.html' for more informations.
Default statistic: 'average' / Most usefull statistics: 'average', 'minimum', 'maximum'.
=over 8
=item B<--type>
Set the instance type (Required) (Can be: 'loadbalancer', 'availabilityzone').
=item B<--name>
Set the instance name (Required) (Can be multiple).
=item B<--availability-zone>
Add Availability Zone dimension (only with --type='loadbalancer').
=item B<--filter-metric>
Filter metrics (Can be: 'HealthyHostCount', 'UnHealthyHostCount')
(Can be a regexp).
=item B<--warning-*> B<--critical-*>
Thresholds warning (Can be: 'healthyhostcount', 'unhealthyhostcount').
=back
=cut
| Tpo76/centreon-plugins | cloud/aws/elb/classic/mode/targetshealth.pm | Perl | apache-2.0 | 9,234 |
=head1 LICENSE
Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::DBSQL::MiscSetAdaptor - Provides database interaction for
Bio::EnsEMBL::MiscSet objects.
=head1 SYNOPSIS
my $msa = $registry->get_adaptor( 'Human', 'Core', 'MiscSet' );
my $misc_set = $msa->fetch_by_dbID(1234);
$misc_set = $msa->fetch_by_code('clone');
=head1 DESCRIPTION
This class provides database interactivity for MiscSet objects.
MiscSets are used to classify MiscFeatures into groups.
=head1 METHODS
=cut
package Bio::EnsEMBL::DBSQL::MiscSetAdaptor;
use strict;
use warnings;
use Bio::EnsEMBL::MiscSet;
use Bio::EnsEMBL::DBSQL::BaseAdaptor;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use vars qw(@ISA);
@ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor);
=head2 new
Arg [...] : Superclass args. See Bio::EnsEMBL::DBSQL::BaseAdaptor
Description: Instantiates a Bio::EnsEMBL::DBSQL::MiscSetAdaptor and
caches the contents of the MiscSet table.
Returntype : Bio::EnsEMBL::MiscSet
Exceptions : none
Caller : MiscFeatureAdaptor
Status : Stable
=cut
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
$self->{'_id_cache'} = {};
$self->{'_code_cache'} = {};
# cache the entire contents of the misc set table
# the table is small and it removes the need to repeatedly query the
# table or join to the table
$self->fetch_all();
return $self;
}
=head2 fetch_all
Arg [1] : none
Example : foreach my $ms (@{$msa->fetch_all()}) {
print $ms->code(), ' ', $ms->name(), "\n";
}
Description: Retrieves every MiscSet defined in the DB.
NOTE: In a multi-species database, this method will
return all the entries matching the search criteria, not
just the ones associated with the current species.
Returntype : listref of Bio::EnsEMBL::MiscSets
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_all {
my $self = shift;
my $sth = $self->prepare
('SELECT misc_set_id, code, name, description, max_length FROM misc_set');
$sth->execute();
my ($dbID, $code, $name, $desc, $max_len);
$sth->bind_columns(\$dbID, \$code, \$name, \$desc, \$max_len);
my @all;
while($sth->fetch()) {
my $ms = Bio::EnsEMBL::MiscSet->new
(-DBID => $dbID,
-ADAPTOR => $self,
-CODE => $code,
-NAME => $name,
-DESCRIPTION => $desc,
-LONGEST_FEATURE => $max_len);
$self->{'_id_cache'}->{$dbID} = $ms;
$self->{'_code_cache'}->{lc($code)} = $ms;
push @all, $ms;
}
$sth->finish();
return \@all;
}
=head2 fetch_by_dbID
Arg [1] : int $dbID
The internal identifier of the misc set to retrieve
Example : my $ms = $msa->fetch_by_dbID($dbID);
Description: Retrieves a misc set via its internal identifier
Returntype : Bio::EnsEMBL::MiscSet
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_by_dbID {
my $self = shift;
my $dbID = shift;
if(!$self->{'_id_cache'}->{$dbID}) {
# on a cache miss reread the whole table and reload the cache
$self->fetch_all();
}
return $self->{'_id_cache'}->{$dbID};
}
=head2 fetch_by_code
Arg [1] : string $code
The unique code of the MiscSet to retrieve
Example : my $ms = $msa->fetch_by_code('clone');
Description: Retrieves a MiscSet via its code
Returntype : Bio::EnsEMBL::MiscSet
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_by_code {
my $self = shift;
my $code = shift;
if(!$self->{'_code_cache'}->{lc($code)}) {
# on cache miss, reread whole table and reload cache
$self->fetch_all();
}
return $self->{'_code_cache'}->{lc($code)};
}
=head2 store
Arg [1] : list of MiscSets @mist_sets
Example : $misc_set_adaptor->store(@misc_sets);
Description: Stores a list of MiscSets in the database, and sets the
dbID and adaptor attributes of the stored sets.
Returntype : none
Exceptions : throw on incorrect arguments
warning if a feature is already stored in this database
Caller : MiscFeatureAdaptor::store
Status : Stable
=cut
sub store {
my $self = shift;
my @misc_sets = @_;
# we use 'insert ignore' so that inserts can occur safely on the farm
# otherwise 2 processes could try to insert at the same time and one
# would fail
my $insert_ignore = $self->insert_ignore_clause();
my $sth = $self->prepare(
qq{${insert_ignore} INTO misc_set (
code,
name,
description,
max_length
) VALUES (?, ?, ?, ?)
});
my $db = $self->db();
SET:
foreach my $ms (@misc_sets) {
if(!ref($ms) || !$ms->isa('Bio::EnsEMBL::MiscSet')) {
throw("List of MiscSet arguments expected.");
}
if($ms->is_stored($db)) {
warning("MiscSet [".$ms->dbID."] is already stored in this database.");
next SET;
}
$sth->bind_param(1,$ms->code,SQL_VARCHAR);
$sth->bind_param(2,$ms->name,SQL_VARCHAR);
$sth->bind_param(3,$ms->description,SQL_LONGVARCHAR);
$sth->bind_param(4,$ms->longest_feature,SQL_INTEGER);
my $num_inserted = $sth->execute();
my $dbID;
if($num_inserted == 0) {
# insert failed because set with this code already exists
my $sth2 = $self->prepare("SELECT misc_set_id from misc_set " .
"WHERE code = ?");
$sth2->bind_param(1,$ms->code,SQL_VARCHAR);
$sth2->execute();
($dbID) = $sth2->fetchrow_array();
if($sth2->rows() != 1) {
throw("Could not retrieve or store MiscSet, code=[".$ms->code."]\n".
"Wrong database user/permissions?");
}
} else {
$dbID = $self->last_insert_id('misc_set_id', undef, 'misc_set');
}
$ms->dbID($dbID);
$ms->adaptor($self);
# update the internal caches
$self->{'_id_cache'}->{$dbID} = $ms;
$self->{'_code_cache'}->{lc($ms->code())} = $ms;
}
return;
}
=head2 update
Arg [1] : Bio::EnsEMBL::MiscSet $miscset
Example : $adaptor->update($miscset)
Description: Updates this misc_set in the database
Returntype : int 1 if update is performed, undef if it is not
Exceptions : throw if arg is not an misc_set object
Caller : ?
Status : Stable
=cut
sub update {
my $self = shift;
my $m = shift;
if (!ref($m) || !$m->isa('Bio::EnsEMBL::MiscSet')) {
throw("Expected Bio::EnsEMBL::MiscSet argument.");
}
if(!$m->is_stored($self->db())) {
return undef;
}
my $sth = $self->prepare("UPDATE misc_set ".
"SET code =?, name =?, description = ?, max_length = ? ".
"WHERE misc_set_id = ?");
$sth->bind_param(1,$m->code,SQL_VARCHAR);
$sth->bind_param(2,$m->name,SQL_VARCHAR);
$sth->bind_param(3,$m->description,SQL_VARCHAR);
$sth->bind_param(4,$m->longest_feature,SQL_INTEGER);
$sth->bind_param(5,$m->dbID,SQL_INTEGER);
$sth->execute();
$sth->finish();
# update the internal caches
$self->{'_id_cache'}->{$m->dbID} = $m;
$self->{'_code_cache'}->{lc($m->code())} = $m;
}
1;
| willmclaren/ensembl | modules/Bio/EnsEMBL/DBSQL/MiscSetAdaptor.pm | Perl | apache-2.0 | 8,005 |
#!/usr/bin/env perl
=head1 NAME
load_from_otter.pl
=head1 SYNOPSIS
load_from_otter.pl
=head1 DESCRIPTION
This script is used to load one or several sequence sets from an organisme
specific otter database into either a pipeline or a loutre database, both based
on ensembl schema version 20+. The loaded sequences are either Pfetched or fetched
from fasta files in the current directory. If the login, password and port parameters
are not provided, they will be recovered from the ~/.netrc file.
See the Net::Netrc module for more details.
here is an example commandline
./load_from_otter.pl
-set chr11-02
-o_host ecs4
-o_port 3352
-o_name otter_human
-o_user pipuser
-o_pass *****
-host otterpipe2
-port 3352
-name pipe_human
-user pipuser
-pass *****
=head1 OPTIONS
-o_host (default:otterlive) host name for the dataset specific otter database (gets put as ohost= in locator)
-o_name (default:otter_human) For RDBs, what name to connect to (oname= in locator)
-o_user (check the ~/.netrc file) For RDBs, what username to connect as (ouser= in locator)
-o_pass (check the ~/.netrc file) For RDBs, what password to use (opass= in locator)
-o_port (check the ~/.netrc file) For RDBs, what port to use (oport= in locator)
-host (default:otterpipe1) host name for the target database (gets put as phost= in locator)
-name (no default) For RDBs, what name to connect to (pname= in locator)
-user (check the ~/.netrc file) For RDBs, what username to connect as (puser= in locator)
-pass (check the ~/.netrc file) For RDBs, what password to use (ppass= in locator)
-port (check the ~/.netrc file) For RDBs, what port to use (pport= in locator)
-cs_version (default:Otter) the version of the chromosome coordinate system being stored
-set|chr the sequence set to load
-nosubmit don't prime the pipeline with the SubmitContig analysis in case of pipeline
database
-help|h displays this documentation with PERLDOC
=head1 CONTACT
Mustapha Larbaoui B<email> ml6@sanger.ac.uk
=cut
use warnings ;
use strict;
use Getopt::Long;
use Net::Netrc;
use Bio::SeqIO;
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Pipeline::DBSQL::Finished::DBAdaptor;
use Bio::EnsEMBL::Pipeline::SeqFetcher::Finished_Pfetch;
use Bio::EnsEMBL::Slice;
use Bio::EnsEMBL::Attribute;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
# otter and destination database connexion parameters, default values.
my $host = 'otterpipe1';
my $port = '';
my $name = '';
my $user = '';
my $pass = '';
my $ohost = 'otterlive';
my $oport = '';
my $oname = 'otter_human';
my $ouser = '';
my $opass = '';
my $cs_version = 'Otter';
my @seq_sets;
my $do_submit = 1; # Set if we want to prime the pipeline with the SubmitContig analysis
my $usage = sub { exec( 'perldoc', $0 ); };
&GetOptions(
'host:s' => \$host,
'port:n' => \$port,
'name=s' => \$name,
'user:s' => \$user,
'pass:s' => \$pass,
'o_host:s' => \$ohost,
'o_port:n' => \$oport,
'o_name:s' => \$oname,
'o_user:s' => \$ouser,
'o_pass:s' => \$opass,
'cs_version:s' => \$cs_version,
'chr|set=s' => \@seq_sets,
'no_submit!' => sub{ $do_submit = 0 },
'submit!' => \$do_submit,
'h|help!' => $usage
)
or $usage->();
if ( !$user || !$pass || !$port ) {
my @param = &get_db_param($host);
$user = $param[0] unless $user;
$pass = $param[1] unless $pass;
$port = $param[2] unless $port;
}
if ( !$ouser || !$opass || !$oport ) {
my @param = &get_db_param($ohost);
$ouser = $param[0] unless $ouser;
$opass = $param[1] unless $opass;
$oport = $param[2] unless $oport;
}
if ( !$name ) {
print STDERR
"Can't load sequence set without a target loutre/pipeline database name\n";
print STDERR "-host $host -user $user -pass $pass\n";
}
if ( !scalar(@seq_sets) ) {
print STDERR "Need chr|set to be able to run\n";
}
my $otter_dbc = Bio::EnsEMBL::DBSQL::DBConnection->new(
-user => $ouser,
-dbname => $oname,
-host => $ohost,
-port => $oport,
-pass => $opass
);
my $module = $name =~ /pipe_/ ? 'Bio::EnsEMBL::Pipeline::DBSQL::Finished::DBAdaptor' :
'Bio::EnsEMBL::DBSQL::DBAdaptor';
my $target_dba = $module->new(
-user => $user,
-dbname => $name,
-host => $host,
-port => $port,
-pass => $pass
);
my $target_dbc = $target_dba->dbc();
my %end_value;
my $contigs_hashref = {};
my $seqset_info = {};
#
# Get the sequence data set from Otter database and store it in a Hashtable.
#
{
print STDOUT
"Getting Sequence set @seq_sets from Otter database: $oname ($ohost:$oport)\n";
my $contigs_sth = $otter_dbc->prepare(
q{
SELECT chr.name, a.chr_start, a.chr_end
, a.contig_start, a.contig_end, a.contig_ori
, c.embl_acc, c.embl_version
FROM chromosome chr
, assembly a
, contig g
, clone c
WHERE chr.chromosome_id = a.chromosome_id
AND a.contig_id = g.contig_id
AND g.clone_id = c.clone_id
AND a.type = ?
ORDER BY a.chr_start
}
);
my $description_sth = $otter_dbc->prepare(
q{
SELECT description, hide
FROM sequence_set
WHERE assembly_type = ?
}
);
SET:foreach my $sequence_set (@seq_sets) {
my $contig_number = 0;
my $chr_href;
# fetch all the contigs for this sequence set
$contigs_sth->execute($sequence_set);
CONTIG:while (
my (
$chr_name, $chr_start, $chr_end,
$contig_start, $contig_end, $strand,
$acc, $sv
)
= $contigs_sth->fetchrow
)
{
if ( !$end_value{$sequence_set} ) {
$end_value{$sequence_set} = $chr_end;
}
else {
if ( $chr_end > $end_value{$sequence_set} ) {
$end_value{$sequence_set} = $chr_end;
}
}
$contigs_hashref->{ $acc . $sv.$sequence_set } = [
$chr_name, $chr_start, $chr_end,
$contig_start, $contig_end, $strand,
$acc, $sv, $sequence_set
];
$chr_href->{$chr_name} = 1;
$contig_number++;
}
# fetch the sequence set description from the sequence_set table
$description_sth->execute($sequence_set);
my ($desc, $hide) = $description_sth->fetchrow;
$hide = $hide eq 'N' ? 0 : 1;
my @chrs = keys %$chr_href;
throw("Set $sequence_set should contains (only) one chromosome: [@chrs]")
unless (scalar(@chrs) == 1);
$seqset_info->{$sequence_set} = [ shift @chrs,$desc, $hide ];
throw("No data for '$sequence_set' in $oname")
unless ($contig_number);
print STDOUT $contig_number." contigs retrieved for $sequence_set\n";
}
}
#
# Load the sequence data set into the loutre/pipeline database
#
{
print STDOUT
"Writing data into database: $name ($host:$port)\n";
my $dbh = $target_dbc->db_handle;
$dbh->begin_work;
my %asm_seq_reg_id;
my $attr_a = $target_dba->get_AttributeAdaptor();
my $cs_a = $target_dba->get_CoordSystemAdaptor();
my $slice_a = $target_dba->get_SliceAdaptor();
my $seq_a = $target_dba->get_SequenceAdaptor();
my $analysis_a = $target_dba->get_AnalysisAdaptor;
my $state_info_container = $target_dba->get_StateInfoContainer if($name =~ /pipe_/);
my $chromosome_cs;
my $clone_cs;
my $contig_cs;
eval {
$chromosome_cs =
$cs_a->fetch_by_name( "chromosome", $cs_version );
$clone_cs = $cs_a->fetch_by_name("clone");
$contig_cs = $cs_a->fetch_by_name("contig");
};
if ($@) {
throw(
qq{
A coord_system matching the arguments does not exsist in the cord_system table,
please ensure you have the right coord_system entry in the database [$@]
}
);
}
my $slice;
my $ana = $analysis_a->fetch_by_logic_name('SubmitContig');
# insert the sequence sets as chromosomes in seq_region
# table and their attributes in seq_region_attrib & attrib_type tables
foreach my $set_name ( keys(%end_value) ) {
my $endv = $end_value{$set_name};
eval {
$slice =
$slice_a->fetch_by_region( 'chromosome', $set_name, undef, undef,
undef, $cs_version );
};
if ($slice) {
print STDOUT "Sequence set <$set_name> is already in database <$name>\n";
throw( "There is a difference in size for $set_name: stored ["
. $slice->length. "] =! new [". $endv. "]" )
unless ( $slice->length eq $endv );
$asm_seq_reg_id{$set_name} = $slice->get_seq_region_id;
}
else {
$slice = &make_slice( $set_name, 1, $endv, $endv, 1, $chromosome_cs );
$asm_seq_reg_id{$set_name} = $slice_a->store($slice);
$attr_a->store_on_Slice( $slice,
&make_seq_set_attribute( $seqset_info->{$set_name} ) );
}
}
# insert clone & contig in seq_region, seq_region_attrib,
# dna and assembly tables
my $insert_query = qq{
INSERT IGNORE INTO assembly
(asm_seq_region_id, cmp_seq_region_id,asm_start,asm_end,cmp_start,cmp_end,ori)
values
(?,?,?,?,?,?,?)};
my $insert_sth = $target_dbc->prepare($insert_query);
for ( values %$contigs_hashref ) {
my $chr_name = $_->[0];
my $sequence_set = $_->[8];
my $chr_start = $_->[1];
my $chr_end = $_->[2];
my $ctg_start = $_->[3];
my $ctg_end = $_->[4];
my $ctg_ori = $_->[5];
my $acc = $_->[6];
my $ver = $_->[7];
my $acc_ver = $acc . "." . $ver;
my $clone;
my $clone_seq_reg_id;
my $contig;
my $contig_name = $acc_ver . "." . "1" . ".";
my $ctg_seq_reg_id;
my $seqlen;
eval {
$clone = $slice_a->fetch_by_region( 'clone', $acc_ver );
$seqlen = $clone->length;
$contig_name .= $seqlen;
$contig = $slice_a->fetch_by_region( 'contig', $contig_name );
};
if ( $clone && $contig ) {
print STDOUT "\tclone and contig < ${acc_ver} ; ${contig_name} > are already in the database\n";
$clone_seq_reg_id = $clone->get_seq_region_id;
$ctg_seq_reg_id = $contig->get_seq_region_id;
}
elsif ( $clone && !$contig ) {
$dbh->rollback;
### code to be added to create contigs related to the clone
throw(
"Missing contig entry in the database for clone ${acc_ver}"
);
}
else {
##fetch the dna sequence from pfetch server with acc_ver id
my $seqobj;
eval {
$seqobj = &pfetch_acc_sv($acc_ver);
#$seqobj = &pfetch_acc_sv($acc);
};
if($@) {
$dbh->rollback;
throw($@);
#print STDERR "$sequence_set => $acc_ver\n";
#next;
}
my $seq = $seqobj->seq;
$seqlen = $seqobj->length;
$contig_name .= $seqlen;
##make clone and insert clone to seq_region table
$clone = &make_slice( $acc_ver, 1, $seqlen, $seqlen, 1, $clone_cs );
$clone_seq_reg_id = $slice_a->store($clone);
if(!$clone_seq_reg_id) {
$dbh->rollback;
throw("clone seq_region_id has not been returned for the accession $acc_ver");
}
##make attribute for clone and insert attribute to seq_region_attrib & attrib_type tables
$attr_a->store_on_Slice( $clone,
&make_clone_attribute( $acc, $ver ) );
##make contig and insert contig, and associated dna sequence to seq_region & dna table
$contig =
&make_slice( $contig_name, 1, $seqlen, $seqlen, 1, $contig_cs );
$ctg_seq_reg_id = $slice_a->store( $contig, \$seq );
if(!$ctg_seq_reg_id){
$dbh->rollback;
throw("contig seq_region_id has not been returned for the contig $contig_name");
}
}
##insert chromosome to contig assembly data into assembly table
$insert_sth->execute( $asm_seq_reg_id{$sequence_set}, $ctg_seq_reg_id,
$chr_start, $chr_end, $ctg_start, $ctg_end, $ctg_ori );
##insert clone to contig assembly data into assembly table
$insert_sth->execute( $clone_seq_reg_id, $ctg_seq_reg_id, 1, $seqlen, 1,
$seqlen, 1 );
##prime the input_id_analysis table
$state_info_container->store_input_id_analysis( $contig->name(), $ana,'' )
if($do_submit && $name =~ /pipe_/);
}
#$dbh->rollback;
$dbh->commit;
}
#
# Methods
#
sub make_clone_attribute {
my ( $acc, $ver ) = @_;
my @attrib;
my $attrib = &make_attribute(
'htg', 'htg',
'High Throughput phase attribute', '3'
);
push @attrib, $attrib;
# push @attrib,
# &make_attribute( 'intl_clone_name', 'International Clone Name',
# '', '' );
push @attrib,
&make_attribute( 'embl_acc', 'EMBL accession', '', $acc );
push @attrib, &make_attribute( 'embl_version', 'EMBL Version', '', $ver );
return \@attrib;
}
sub make_seq_set_attribute {
my ($arr_ref) = @_;
my ($chr,$desc,$hide,$write) = @$arr_ref;
my @attrib;
$hide = defined($hide) ? $hide : 1;
$write = defined($write) ? $write : 1;
push @attrib,
&make_attribute(
'description',
'Description',
'A general descriptive text attribute', $desc
);
push @attrib,
&make_attribute(
'chr',
'Chromosome Name',
'Chromosome Name Contained in the Assembly', $chr
);
push @attrib,
&make_attribute(
'write_access',
'Write access for Sequence Set',
'1 for writable , 0 for read-only', $write
);
push @attrib,
&make_attribute(
'hidden',
'Hidden Sequence Set', '',$hide
);
return \@attrib;
}
sub make_attribute {
my ( $code, $name, $description, $value ) = @_;
my $attrib = Bio::EnsEMBL::Attribute->new(
-CODE => $code,
-NAME => $name,
-DESCRIPTION => $description,
-VALUE => $value
);
return $attrib;
}
sub make_slice {
my ( $name, $start, $end, $length, $strand, $coordinate_system ) = @_;
my $slice = Bio::EnsEMBL::Slice->new(
-seq_region_name => $name,
-start => $start,
-end => $end,
-seq_region_length => $length,
-strand => $strand,
-coord_system => $coordinate_system,
);
return $slice;
}
sub get_db_param {
my ( $dbhost ) = @_;
my ( $dbuser, $dbpass, $dbport );
my $ref = Net::Netrc->lookup($dbhost);
throw("$dbhost entry is missing from ~/.netrc") unless ($ref);
$dbuser = $ref->login;
$dbpass = $ref->password;
$dbport = $ref->account;
throw(
"Missing parameter in the ~/.netrc file:\n
machine " . ( $dbhost || 'missing' ) . "\n
login " . ( $dbuser || 'missing' ) . "\n
password " . ( $dbpass || 'missing' ) . "\n
account "
. ( $dbport || 'missing' )
. " (should be used to set the port number)"
)
unless ( $dbuser && $dbpass && $dbport );
return ( $dbuser, $dbpass, $dbport );
}
#
# Pfetch the sequences
#-------------------------------------------------------------------------------
# If the sequence isn't available from the default pfetch
# the archive pfetch server is tried.
#
{
my ( $pfetch );
sub pfetch_acc_sv {
my ($acc_ver) = @_;
print "Fetching '$acc_ver'\n";
$pfetch ||= Bio::EnsEMBL::Pipeline::SeqFetcher::Finished_Pfetch->new;
my $seq = $pfetch->get_Seq_by_acc($acc_ver);
unless ($seq) {
my $seq_file = "$acc_ver.seq";
warn
"Attempting to read fasta file <$acc_ver.seq> in current dir.\n";
my $in = Bio::SeqIO->new(
-file => $seq_file,
-format => 'FASTA',
);
$seq = $in->next_seq;
my $name = $seq->display_id;
unless ( $name eq $acc_ver ) {
die "Sequence in '$seq_file' is called '$name' not '$acc_ver'";
}
}
return $seq;
}
}
1;
| Ensembl/ensembl-pipeline | scripts/Finished/load_from_otter.pl | Perl | apache-2.0 | 15,100 |
# 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.
=pod
=head1 NAME
Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation::Tmhmm
=head1 SYNOPSIS
my $seqstream = Bio::SeqIO->new ( -file => $clonefile,
-fmt => 'Fasta',
);
$seq = $seqstream->next_seq;
my $tmhmm = Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation::Tmhmm->new(-analysis => $ana,
-query => $seq,
-modelfile => $mf,
-optionsfile => $o);
$tmhmm->run;
my @results = $tmhmm->output;
=head1 DESCRIPTION
=cut
package Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation::Tmhmm;
use warnings ;
use vars qw(@ISA);
use strict;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation;
@ISA = qw(Bio::EnsEMBL::Analysis::Runnable::ProteinAnnotation);
sub new {
my ($class, @args) = @_;
my $self = $class->SUPER::new(@args);
my ($options_file,
$model_file) = rearrange(['OPTIONSFILE',
'MODELFILE'
], @args);
throw("You must supply a model file for Tmhmm")
if not defined $model_file;
$self->options_file($options_file)
if defined $options_file;
$self->model_file($model_file);
return $self;
}
sub run_analysis {
my ($self) = @_;
# run program
my $cmd = "cat " . $self->queryfile . " | " . $self->program;
if ($self->options_file) {
$cmd .= " -f " . $self->options_file;
}
if ($self->options) {
$cmd .= " " . $self->options;
}
$cmd .= " -modelfile " . $self->model_file . " > " . $self->resultsfile;
print "Running $cmd\n";
# decodeanhmm returns a non-zero exit status, even when successful
# So we just have to run it and wait until we parse the output
# file to see whether it ran successfully
system($cmd);
}
sub parse_results {
my ($self) = @_;
my ($fh, $id, @pfs);
my $resfile = $self->resultsfile;
if (-e $resfile) {
# it's a filename
if (-z $resfile) {
return;
} else {
open ($fh, "<$resfile") or throw("Error opening $resfile");
}
} else {
# it'a a filehandle
$fh = $resfile;
}
my $id_count = 0;
while (<$fh>) {
chomp;
next if /^$/;
if (/^\>(\S+)/) {
$id = $1;
$id_count++;
}
elsif (/^\%pred/) {
my ($junk, $values) = split /:/;
my @tm = split (/,/, $values);
foreach (@tm) {
/(\w+)\s+(\d+)\s+(\d+)/;
my $orien = $1;
my $start = $2;
my $end = $3;
$orien = uc ($orien);
if ($orien eq "M") {
my $fp = $self->create_protein_feature($start, $end, 0, $id, 0,
0, 'Tmhmm',
$self->analysis, 0, 0);
push @pfs, $fp;
}
}
}
}
close($fh);
throw("Something went wrong when running decodeanhmm; no ids found in output")
if not $id_count;
$self->output(\@pfs);
}
sub model_file {
my ($self, $val) = @_;
if (defined $val) {
$self->{_model_file} = $val;
}
return $self->{_model_file};
}
sub options_file {
my ($self, $val) = @_;
if (defined $val) {
$self->{_options_file} = $val;
}
return $self->{_options_file};
}
1;
| Ensembl/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/Runnable/ProteinAnnotation/Tmhmm.pm | Perl | apache-2.0 | 4,252 |
:- module(ho_module_tr,[ho_module_tr/2],[]).
%% Expands:
%% Lists::member(X,[1,2,3])
%% where Lists = lists(_,_...)
ho_module_tr( '::'(ObjectId,Call), Conjunction ) :-
Conjunction = (
Call =.. [MethodName|Args],
member(MethodName:PredId,ObjectId),
RealCall =.. [call,PredId|Args],
call(RealCall)
),
display('Goals '),
display(Conjunction),
nl.
| leuschel/ecce | www/CiaoDE/ciao/library.development/ho_test/ho_module_tr.pl | Perl | apache-2.0 | 366 |
#!/usr/bin/perl -w
# MGEL
# Surya Saha 4/01/07
# reading 5 noise itemset files and real itemset generated by m.out2f_itemsets
# writing out the real itemsets along with the with
# Diff occurences = occurences - random occurences
# Diff Conf = Occ Conf - Random Conf
# NOTE: If noise>real occurences, then a 0 is recorded
# NOTE: If noise conf>real Conf, then a 0.00 is recorded
# OUTPUT:
# fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Strand, Category
# v2 : 06/27/07
# v2 : Changed output to F1 relation F2 style
# OUTPUT:
# fam1, Category, fam2, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Strand, fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen
# v2 : Fixed divide by 0 error for Rand coincidence numbers
# v3 : Changed the scoring function to fam1 from min(|fam1|,|fam2|).
# v3 : Printing output to different files for each strand
# v4 : Adapt script to read the config file to record stats accordingly
my ($ver);
$ver="4.0";
# use strict;
use warnings;
use POSIX;
# #fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen, Occurence, Strand, Category
# R=15 4 259 R=15 4 259 3 + u1
#0 1 2 3 4 5 6 7 8
unless (@ARGV == 7){
print "USAGE: $0 <input real f_itemsets file> <input noise f_itemsets file 1> <input noise f_itemsets file 2> <input noise f_itemsets file 3> <input noise f_itemsets file 4> <input noise f_itemsets file 5> <relations config file>\n";
exit;
}
my ($ifname,$rec,@temp,@stats,@merged_table,@real_table,%rels_stats,
%noise_hash_1,%noise_hash_2,%noise_hash_3,%noise_hash_4,%noise_hash_5, %temphash,$ctr,$i,$j,$k,$user_t,$system_t,$cuser_t,$csystem_t);
$ifname=$ARGV[0];
chomp $ifname;
unless(open(INFILEREALDATA,$ifname)){print "not able to open ".$ifname."\n\n";exit;}
#slurping in the whole real itemset file
while($rec=<INFILEREALDATA>){
if($rec =~ /#/){next;}
if(length ($rec) < 10){next;}#for avoiding last line
push @real_table, [split(' ',$rec)];
}
close (INFILEREALDATA);
unless(open(OUTFILEDATAPOS,">$ifname.merged.f_itemsets.pos.tab")){print "not able to open ".$ifname."merged.f_itemsets.pos.tab \n\n";exit;}
unless(open(OUTFILEDATANEG,">$ifname.merged.f_itemsets.neg.tab")){print "not able to open ".$ifname."merged.f_itemsets.neg.tab \n\n";exit;}
unless(open(OUTFILEDATABOTH,">$ifname.merged.f_itemsets.both.tab")){print "not able to open ".$ifname."merged.f_itemsets.both.tab \n\n";exit;}
unless(open(OUTFILESTATS,">$ifname.merged.f_itemsets.stats.tab")){print "not able to open ".$ifname."merged.f_itemsets.stats.tab \n\n";exit;}
$ifname=$ARGV[1];
chomp $ifname;
unless(open(INFILENOISEDATA_1,$ifname)){print "not able to open ".$ifname."\n\n";exit;}
# slurping in the whole noise 1 itemset file
# put the noise data into a hash
while($rec=<INFILENOISEDATA_1>){
if($rec =~ /#/){next;}
if(length ($rec) < 10){next;}#for avoiding last line
@temp = split(' ',$rec);
$noise_hash_1{"$temp[0] $temp[3] $temp[7] $temp[8]"} = "$temp[6]";
}
close (INFILENOISEDATA_1);
$ifname=$ARGV[2];
chomp $ifname;
unless(open(INFILENOISEDATA_2,$ifname)){print "not able to open ".$ifname."\n\n";exit;}
# slurping in the whole noise 2 itemset file
# put the noise data into a hash
while($rec=<INFILENOISEDATA_2>){
if($rec =~ /#/){next;}
if(length ($rec) < 10){next;}#for avoiding last line
@temp = split(' ',$rec);
$noise_hash_2{"$temp[0] $temp[3] $temp[7] $temp[8]"} = "$temp[6]";
}
close (INFILENOISEDATA_2);
$ifname=$ARGV[3];
chomp $ifname;
unless(open(INFILENOISEDATA_3,$ifname)){print "not able to open ".$ifname."\n\n";exit;}
# slurping in the whole noise 3 itemset file
# put the noise data into a hash
while($rec=<INFILENOISEDATA_3>){
if($rec =~ /#/){next;}
if(length ($rec) < 10){next;}#for avoiding last line
@temp = split(' ',$rec);
$noise_hash_3{"$temp[0] $temp[3] $temp[7] $temp[8]"} = "$temp[6]";
}
close (INFILENOISEDATA_3);
$ifname=$ARGV[4];
chomp $ifname;
unless(open(INFILENOISEDATA_4,$ifname)){print "not able to open ".$ifname."\n\n";exit;}
# slurping in the whole noise 4 itemset file
# put the noise data into a hash
while($rec=<INFILENOISEDATA_4>){
if($rec =~ /#/){next;}
if(length ($rec) < 10){next;}#for avoiding last line
@temp = split(' ',$rec);
$noise_hash_4{"$temp[0] $temp[3] $temp[7] $temp[8]"} = "$temp[6]";
}
close (INFILENOISEDATA_4);
$ifname=$ARGV[5];
chomp $ifname;
unless(open(INFILENOISEDATA_5,$ifname)){print "not able to open ".$ifname."\n\n";exit;}
# slurping in the whole noise 5 itemset file
# put the noise data into a hash
while($rec=<INFILENOISEDATA_5>){
if($rec =~ /#/){next;}
if(length ($rec) < 10){next;}#for avoiding last line
@temp = split(' ',$rec);
$noise_hash_5{"$temp[0] $temp[3] $temp[7] $temp[8]"} = "$temp[6]";
}
close (INFILENOISEDATA_5);
# READ IN CONFIG FILE
# #Dir Rel Rng Strt Rng End Reci Rel
# U u1 0 500 d1
# U u2 500 1000 d2
$ifname=$ARGV[6];
chomp $ifname;
unless(open(INFILERELCONFIG,$ifname)){print "not able to open ".$ifname."\n\n";exit;}
# put the rel names data into a hash as keys
# total, count and conf will be stored in the value array
# %rels_stats :Strand rel => rel count, total count , total conf values
# hash value points to an array with 3 elements
while($rec=<INFILERELCONFIG>){
if($rec =~ /#/){next;}
if(length ($rec) < 10){next;}#for avoiding last line
@temp = split(' ',$rec);
# intializing rel count, total count and total conf values
# for each strand
$rels_stats{"+ $temp[1]"}=[0,0,0];# init for Pos strand
$rels_stats{"C $temp[1]"}=[0,0,0];# init for Comp strand
$rels_stats{"B $temp[1]"}=[0,0,0];# init for Both (strand independent)
}
close (INFILERELCONFIG);
# add an IN and CONTAINS for each strand
# hash value points to an array with 3 elements
$rels_stats{"+ IN"}=[0,0,0]; $rels_stats{"+ CONT"}=[0,0,0];
$rels_stats{"C IN"}=[0,0,0]; $rels_stats{"C CONT"}=[0,0,0];
$rels_stats{"B IN"}=[0,0,0]; $rels_stats{"B CONT"}=[0,0,0];
sub round2{
my ($num);
$num=$_[0];
$num=$num*100;
$num=int($num);
$num=$num/100;
return $num;
}
$i=localtime();
# calculating time taken
($user_t,$system_t,$cuser_t,$csystem_t) = times;
print OUTFILEDATAPOS "\# Version: $ver\n";
print OUTFILEDATAPOS "\# Time: $i\n\n";
print OUTFILEDATAPOS "\# Runtime details after preparing all hashes:\n";
print OUTFILEDATAPOS "\# System time for process: ",ceil($system_t/60)," mins\n";
print OUTFILEDATAPOS "\# User time for process: ",ceil($user_t/60)," mins\n\n";
print OUTFILEDATANEG "\# Version: $ver\n";
print OUTFILEDATANEG "\# Time: $i\n\n";
print OUTFILEDATANEG "\# Runtime details after preparing all hashes:\n";
print OUTFILEDATANEG "\# System time for process: ",ceil($system_t/60)," mins\n";
print OUTFILEDATANEG "\# User time for process: ",ceil($user_t/60)," mins\n\n";
print OUTFILEDATABOTH "\# Version: $ver\n";
print OUTFILEDATABOTH "\# Time: $i\n\n";
print OUTFILEDATABOTH "\# Runtime details after preparing all hashes:\n";
print OUTFILEDATABOTH "\# System time for process: ",ceil($system_t/60)," mins\n";
print OUTFILEDATABOTH "\# User time for process: ",ceil($user_t/60)," mins\n\n";
print OUTFILESTATS "\# Version: $ver\n";
print OUTFILESTATS "\# Time: $i\n\n";
print OUTFILESTATS "\# Runtime details after preparing all hashes:\n";
print OUTFILESTATS "\# System time for process: ",ceil($system_t/60)," mins\n";
print OUTFILESTATS "\# User time for process: ",ceil($user_t/60)," mins\n\n";
print STDERR "\# Runtime details after preparing all hashes:\n";
print STDERR "\# System time for process: ",ceil($system_t/60)," mins\n";
print STDERR "\# User time for process: ",ceil($user_t/60)," mins\n\n";
#filling up the @merged_table array the merged file
# @real_table
# #fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen, Occurence, Strand, Category
# R=15 4 259 R=15 4 259 3 + u1
#0 1 2 3 4 5 6 7 8
# @merged_table:fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen, Occurence, Occurence conf., Avg. Rand Coin., Avg. Rand Coin. conf., Diff, Diff conf., Strand, Category
$ctr=0;
foreach $i (@real_table){
$merged_table[$ctr][0] = $i->[0];# fam1
$merged_table[$ctr][1] = $i->[1];# fam1-count
$merged_table[$ctr][2] = $i->[2];# fam1-avg len
$merged_table[$ctr][3] = $i->[3];# fam2
$merged_table[$ctr][4] = $i->[4];# fam2-count
$merged_table[$ctr][5] = $i->[5];# fam2-avg len
$merged_table[$ctr][6] = $i->[6];# Occurence count
# calculating occ. conf
$merged_table[$ctr][7] = &round2($i->[6]/$i->[1]);
# Avg Rand Coin. count
#get the noise data
$j=$k=0;
#check if the relation even exists in noise 1
if (exists $noise_hash_1{"$i->[0] $i->[3] $i->[7] $i->[8]"}){
$j += $noise_hash_1{"$i->[0] $i->[3] $i->[7] $i->[8]"};
$k++;
}
#check if the relation even exists in noise 2
if (exists $noise_hash_2{"$i->[0] $i->[3] $i->[7] $i->[8]"}){
$j += $noise_hash_2{"$i->[0] $i->[3] $i->[7] $i->[8]"};
$k++;
}
#check if the relation even exists in noise 3
if (exists $noise_hash_3{"$i->[0] $i->[3] $i->[7] $i->[8]"}){
$j += $noise_hash_3{"$i->[0] $i->[3] $i->[7] $i->[8]"};
$k++;
}
#check if the relation even exists in noise 4
if (exists $noise_hash_4{"$i->[0] $i->[3] $i->[7] $i->[8]"}){
$j += $noise_hash_4{"$i->[0] $i->[3] $i->[7] $i->[8]"};
$k++;
}
#check if the relation even exists in noise 5
if (exists $noise_hash_1{"$i->[0] $i->[3] $i->[7] $i->[8]"}){
$j += $noise_hash_1{"$i->[0] $i->[3] $i->[7] $i->[8]"};
$k++;
}
# Random Coincidence
if ($k>0){ # rand coin value found
# Avg Rand Coin. count
$merged_table[$ctr][8] = ceil($j/$k);
# calculating Avg Rand Coin. conf
$merged_table[$ctr][9] = &round2($merged_table[$ctr][8]/$i->[1]);
}
else{ # no rand coin values found
$merged_table[$ctr][8] = 0;# Avg Rand Coin. count
$merged_table[$ctr][9] = 0.00;# Avg Rand Coin. conf
}
#Diff
#in order to store only >= 0 values
if($i->[6] - $merged_table[$ctr][8] > -1) {
$merged_table[$ctr][10] = $i->[6] - $merged_table[$ctr][8];
}
else{
$merged_table[$ctr][10] = 0;
}
# calculating Diff. conf
if ($merged_table[$ctr][10] > 0){# to avoid divide by 0
$merged_table[$ctr][11] = &round2($merged_table[$ctr][10]/$i->[1]);
}
else{
$merged_table[$ctr][11] = 0.00;# Diff. conf
}
$merged_table[$ctr][12] = $i->[7];# Strand
$merged_table[$ctr][13] = $i->[8];# Category
# get info for statistics
# incrementing rel count
# %rels_stats :Strand rel => rel count, total count , total conf values
$rels_stats{"$merged_table[$ctr][12] $merged_table[$ctr][13]"}[0]++;
# incrementing tot count
$rels_stats{"$merged_table[$ctr][12] $merged_table[$ctr][13]"}[1]+=$merged_table[$ctr][10];
# incrementing tot conf
$rels_stats{"$merged_table[$ctr][12] $merged_table[$ctr][13]"}[2]+=$merged_table[$ctr][11];
$ctr++; # increment for next record
if(($ctr % 10000) == 0){ print STDERR '.';}
}
print STDERR "\n\n";
#sort @merged_table on strand, difference conf, difference
# @merged_table:fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen, Occurence, Occurence conf., Avg. Rand Coin., Avg. Rand Coin. conf., Diff, Diff conf., Strand, Category
@temp = sort {($a->[12] cmp $b->[12]) or ($b->[11] <=> $a->[11]) or ($b->[10] <=> $a->[10])} @merged_table;
@merged_table=@temp;
#print data to file
print OUTFILEDATAPOS "\#Output sorted on difference conf and difference\n\n";
print OUTFILEDATAPOS "\#fam1, Category, fam2, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Strand, fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen\n";
print OUTFILEDATANEG "\#Output sorted on difference conf and difference\n\n";
print OUTFILEDATANEG "\#fam1, Category, fam2, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Strand, fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen\n";
print OUTFILEDATABOTH "\#Output sorted on difference conf and difference\n\n";
print OUTFILEDATABOTH "\#fam1, Category, fam2, Occ, Occ conf, Avg Rand Coin, Avg Rand Coin conf, Diff, Diff conf, Strand, fam1, fam1-count, fam1-avglen, fam2, fam2-count, fam2-avglen\n";
foreach $i (@merged_table){
if($i->[12] eq '+'){
print OUTFILEDATAPOS "$i->[0]\t$i->[13]\t$i->[3]\t$i->[6]\t$i->[7]\t$i->[8]\t$i->[9]\t";
print OUTFILEDATAPOS "$i->[10]\t$i->[11]\t$i->[12]\t$i->[0]\t$i->[1]\t$i->[2]\t$i->[3]\t";
print OUTFILEDATAPOS "$i->[4]\t$i->[5]\n";
}
elsif($i->[12] eq 'C'){
print OUTFILEDATANEG "$i->[0]\t$i->[13]\t$i->[3]\t$i->[6]\t$i->[7]\t$i->[8]\t$i->[9]\t";
print OUTFILEDATANEG "$i->[10]\t$i->[11]\t$i->[12]\t$i->[0]\t$i->[1]\t$i->[2]\t$i->[3]\t";
print OUTFILEDATANEG "$i->[4]\t$i->[5]\n";
}
elsif($i->[12] eq 'B'){
print OUTFILEDATABOTH "$i->[0]\t$i->[13]\t$i->[3]\t$i->[6]\t$i->[7]\t$i->[8]\t$i->[9]\t";
print OUTFILEDATABOTH "$i->[10]\t$i->[11]\t$i->[12]\t$i->[0]\t$i->[1]\t$i->[2]\t$i->[3]\t";
print OUTFILEDATABOTH "$i->[4]\t$i->[5]\n";
}
}
# calculating time taken
($user_t,$system_t,$cuser_t,$csystem_t) = times;
print OUTFILEDATAPOS "\n\# Runtime details after printing the relationships: \n";
print OUTFILEDATAPOS "\# System time for process: ",ceil($system_t/60)," mins\n";
print OUTFILEDATAPOS "\# User time for process: ",ceil($user_t/60)," mins\n";
print OUTFILEDATANEG "\n\# Runtime details after printing the relationships: \n";
print OUTFILEDATANEG "\# System time for process: ",ceil($system_t/60)," mins\n";
print OUTFILEDATANEG "\# User time for process: ",ceil($user_t/60)," mins\n";
print OUTFILEDATABOTH "\n\# Runtime details after printing the relationships: \n";
print OUTFILEDATABOTH "\# System time for process: ",ceil($system_t/60)," mins\n";
print OUTFILEDATABOTH "\# User time for process: ",ceil($user_t/60)," mins\n";
# Get all stats
# %rels_stats :Strand rel => rel count, total count , total conf values
@temp=();
$ctr=0;
while ( ($i,$j) = each %rels_stats){
if ($j->[0]>0){# if count > 0
$temp[$ctr][0]=$i; $temp[$ctr][1]=$j->[0]; $temp[$ctr][2]=$j->[1];
$temp[$ctr][3]=ceil($j->[1]/$j->[0]); $temp[$ctr][4]=&round2($j->[2]);
$temp[$ctr++][5]=&round2($j->[2]/$j->[0]);
}
}
#sort @temp on count and avg conf
# @temp:Str Rel\tCnt\tFreqSum\tAvgFreq\tConfSum\tAvgConf\n";
@stats = sort {($b->[5] <=> $a->[5])} @temp;
#print stats to file
print OUTFILESTATS "NOTE: All avg. statistics are for the diff. counts and conf's\n\n";
# print OUTFILESTATS "Stats are not calculated for CONT rels because it is same as Within\n\n";
print OUTFILESTATS "Str Rel\tCnt\tFreqSum\tAvgFreq\tConfSum\tAvgConf\n";
foreach $i (@stats){
print OUTFILESTATS "$i->[0]\t$i->[1]\t$i->[2]\t$i->[3]\t$i->[4]\t$i->[5]\n";
}
# calculating time taken
($user_t,$system_t,$cuser_t,$csystem_t) = times;
print OUTFILESTATS "\n\# Runtime details after printing the itemsets: \n";
print OUTFILESTATS "\# System time for process: ",ceil($system_t/60)," mins\n";
#print OUTFILEDATA "\# System time for children: $csystem_t\n";
print OUTFILESTATS "\# User time for process: ",ceil($user_t/60)," mins\n";
#print OUTFILEDATA "\# User time for children: $cuser_t\n";
close (OUTFILEDATAPOS);
close (OUTFILEDATANEG);
close (OUTFILEDATABOTH);
close (OUTFILESTATS);
print STDERR "\# Runtime details after printing the itemsets: \n";
print STDERR "\# System time for process: ",ceil($system_t/60)," mins\n";
print STDERR "\# User time for process: ",ceil($user_t/60)," mins\n";
# print STDERR "NOTE: Stats are not calculated for CONT rels because it is same as Within\n\n";
exit;
| suryasaha/ProxMiner | scripts/miner.merge_ALL_f_itemsets.v4.pl | Perl | bsd-2-clause | 15,339 |
package WebService::Recruit::AbRoad::TourTally;
use strict;
use base qw( WebService::Recruit::AbRoad::Base );
use vars qw( $VERSION );
use Class::Accessor::Fast;
use Class::Accessor::Children::Fast;
$VERSION = '0.0.1';
sub http_method { 'GET'; }
sub url { 'http://webservice.recruit.co.jp/ab-road/tour_tally/v1/'; }
sub query_class { 'WebService::Recruit::AbRoad::TourTally::Query'; }
sub query_fields { [
'key', 'keyword', 'dept', 'ym', 'ymd', 'price_min', 'price_max', 'term_min', 'term_max', 'airline', 'kodaw', 'axis', 'order', 'start', 'count'
]; }
sub default_param { {
'format' => 'xml'
}; }
sub notnull_param { [
'key', 'keyword'
]; }
sub elem_class { 'WebService::Recruit::AbRoad::TourTally::Element'; }
sub root_elem { 'results'; }
sub elem_fields { {
'area' => ['code', 'name'],
'country' => ['code', 'name'],
'error' => ['message'],
'results' => ['api_version', 'results_available', 'results_returned', 'results_start', 'tour_tally', 'api_version', 'error'],
'tour_tally' => ['type', 'code', 'name', 'tour_count', 'lat', 'lng', 'area', 'country'],
}; }
sub force_array { [
'tour_tally'
]; }
# __PACKAGE__->mk_query_accessors();
@WebService::Recruit::AbRoad::TourTally::Query::ISA = qw( Class::Accessor::Fast );
WebService::Recruit::AbRoad::TourTally::Query->mk_accessors( @{query_fields()} );
# __PACKAGE__->mk_elem_accessors();
@WebService::Recruit::AbRoad::TourTally::Element::ISA = qw( Class::Accessor::Children::Fast );
WebService::Recruit::AbRoad::TourTally::Element->mk_ro_accessors( root_elem() );
WebService::Recruit::AbRoad::TourTally::Element->mk_child_ro_accessors( %{elem_fields()} );
=head1 NAME
WebService::Recruit::AbRoad::TourTally - AB-ROAD Web Service "tour_tally" API
=head1 SYNOPSIS
use WebService::Recruit::AbRoad;
my $service = WebService::Recruit::AbRoad->new();
my $param = {
'key' => $ENV{'WEBSERVICE_RECRUIT_KEY'},
'keyword' => '登山',
};
my $res = $service->tour_tally( %$param );
my $data = $res->root;
print "api_version: $data->api_version\n";
print "results_available: $data->results_available\n";
print "results_returned: $data->results_returned\n";
print "results_start: $data->results_start\n";
print "tour_tally: $data->tour_tally\n";
print "...\n";
=head1 DESCRIPTION
This module is a interface for the C<tour_tally> API.
It accepts following query parameters to make an request.
my $param = {
'key' => 'XXXXXXXX',
'keyword' => '登山',
'dept' => 'XXXXXXXX',
'ym' => 'XXXXXXXX',
'ymd' => 'XXXXXXXX',
'price_min' => 'XXXXXXXX',
'price_max' => 'XXXXXXXX',
'term_min' => 'XXXXXXXX',
'term_max' => 'XXXXXXXX',
'airline' => 'XXXXXXXX',
'kodaw' => 'XXXXXXXX',
'axis' => 'XXXXXXXX',
'order' => 'XXXXXXXX',
'start' => 'XXXXXXXX',
'count' => 'XXXXXXXX',
};
my $res = $service->tour_tally( %$param );
C<$service> above is an instance of L<WebService::Recruit::AbRoad>.
=head1 METHODS
=head2 root
This returns the root element of the response.
my $root = $res->root;
You can retrieve each element by the following accessors.
$root->api_version
$root->results_available
$root->results_returned
$root->results_start
$root->tour_tally
$root->tour_tally->[0]->type
$root->tour_tally->[0]->code
$root->tour_tally->[0]->name
$root->tour_tally->[0]->tour_count
$root->tour_tally->[0]->lat
$root->tour_tally->[0]->lng
$root->tour_tally->[0]->area
$root->tour_tally->[0]->country
$root->tour_tally->[0]->area->code
$root->tour_tally->[0]->area->name
$root->tour_tally->[0]->country->code
$root->tour_tally->[0]->country->name
=head2 xml
This returns the raw response context itself.
print $res->xml, "\n";
=head2 code
This returns the response status code.
my $code = $res->code; # usually "200" when succeeded
=head2 is_error
This returns true value when the response has an error.
die 'error!' if $res->is_error;
=head1 SEE ALSO
L<WebService::Recruit::AbRoad>
=head1 AUTHOR
RECRUIT Media Technology Labs <mtl@cpan.org>
=head1 COPYRIGHT
Copyright 2008 RECRUIT Media Technology Labs
=cut
1;
| gitpan/WebService-Recruit-AbRoad | lib/WebService/Recruit/AbRoad/TourTally.pm | Perl | bsd-3-clause | 4,296 |
use strict;
open( INFILE, "<", $ARGV[0] )
or die("Cannot open file $ARGV[0] for reading: $!");
while ( my $line = <INFILE> ) {
chomp($line);
my @r;
foreach my $i ( split( / \| /, $line ) ) {
if ( @r == 0 ) {
@r = split( / /, $i );
}
else {
my $jx = 0;
foreach my $j ( split( / /, $i ) ) {
@r[$jx] = $j if ( $j > @r[$jx] );
$jx++;
}
}
}
printf( "%s\n", join( ' ', @r ) );
}
close(INFILE);
| nikai3d/ce-challenges | easy/find_the_highest_score.pl | Perl | bsd-3-clause | 522 |
=pod
=head1 NAME
genrsa - generate an RSA private key
=head1 SYNOPSIS
B<openssl> B<genrsa>
[B<-out filename>]
[B<-passout arg>]
[B<-des>]
[B<-des3>]
[B<-idea>]
[B<-f4>]
[B<-3>]
[B<-rand file(s)>]
[B<-engine id>]
[B<numbits>]
=head1 DESCRIPTION
The B<genrsa> command generates an RSA private key.
=head1 OPTIONS
=over 4
=item B<-out filename>
the output filename. If this argument is not specified then standard output is
used.
=item B<-passout arg>
the output file password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.
=item B<-des|-des3|-idea>
These options encrypt the private key with the DES, triple DES, or the
IDEA ciphers respectively before outputting it. If none of these options is
specified no encryption is used. If encryption is used a pass phrase is prompted
for if it is not supplied via the B<-passout> argument.
=item B<-F4|-3>
the public exponent to use, either 65537 or 3. The default is 65537.
=item B<-rand file(s)>
a file or files containing random data used to seed the random number
generator, or an EGD socket (see L<RAND_egd(3)|RAND_egd(3)>).
Multiple files can be specified separated by a OS-dependent character.
The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for
all others.
=item B<-engine id>
specifying an engine (by its unique B<id> string) will cause B<genrsa>
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.
=item B<numbits>
the size of the private key to generate in bits. This must be the last option
specified. The default is 2048.
=back
=head1 NOTES
RSA private key generation essentially involves the generation of two prime
numbers. When generating a private key various symbols will be output to
indicate the progress of the generation. A B<.> represents each number which
has passed an initial sieve test, B<+> means a number has passed a single
round of the Miller-Rabin primality test. A newline means that the number has
passed all the prime tests (the actual number depends on the key size).
Because key generation is a random process the time taken to generate a key
may vary somewhat.
=head1 BUGS
A quirk of the prime generation algorithm is that it cannot generate small
primes. Therefore the number of bits should not be less that 64. For typical
private keys this will not matter because for security reasons they will
be much larger (typically 1024 bits).
=head1 SEE ALSO
L<gendsa(1)|gendsa(1)>
=cut
| GaloisInc/hacrypto | src/C/libssl/HEAD/src/doc/apps/genrsa.pod | Perl | bsd-3-clause | 2,609 |
# Copyright (c)2000-2013, Chris Pressey, Cat's Eye Technologies.
# All rights reserved.
# Distributed under a BSD-style license; see file LICENSE for more info.
package Actor;
### BUILT-IN ACTORS ###
$giant_honeybee = Actor->new('name' => 'giant honeybee',
'max' => {
'strength' => Dice->new(1,2,+1),
'constitution' => Dice->new(1,3,+2),
'dexterity' => Dice->new(1,3,+15),
'intelligence' => Dice->new(1,1),
'spirit' => Dice->new(1,2,+1),
'charisma' => Dice->new(1,1),
},
'arms' => $Item::nonexistant_part,
'hands' => $Item::nonexistant_part,
'sex' => $Distribution::hive_sex,
'race' => 'Bee',
'melee_attacks'=> [ $Attack::bee_sting ],
'hitbonus' => -1,
'appearance' => 'bee',
'color' => 'brown',
'hair_type' => 'fuzzy',
'hair_color' => 'brown',
'eye_color' => 'multifaceted',
'skin_type' => 'puffy',
'skin_color' => 'black',
'body_aim' => 'small_winged');
#$giant_honeybee->take(Distribution->new(
# 0.050 => $Item::golden_honeycomb->bunch(1),
# 0.018 => $Item::golden_honeycomb->bunch(2),
# 0.005 => $Item::royal_jelly->bunch(1),
# ));
$giant_honeybee->{belongings} = [ Distribution->new(
0.050 => $Item::golden_honeycomb->bunch(1),
0.018 => $Item::golden_honeycomb->bunch(2),
0.005 => $Item::royal_jelly->bunch(1),
)];
$queen_honeybee = Actor->new('name' => 'queen honeybee',
'max' => {
'strength' => Dice->new(1,2,+2),
'constitution' => Dice->new(2,2,+6),
'dexterity' => Dice->new(1,3,+10),
'intelligence' => Dice->new(2,2),
'spirit' => Dice->new(2,2,+2),
'charisma' => Dice->new(1,1),
},
'arms' => $Item::nonexistant_part,
'hands' => $Item::nonexistant_part,
'sex' => 'Female',
'race' => 'Bee',
'melee_attacks'=> [ $Attack::bee_sting ],
# todo: poison
'hitbonus' => -1,
'appearance' => 'bee',
'color' => 'yellow',
'hair_type' => 'fuzzy',
'hair_color' => 'yellow',
'eye_color' => 'multifaceted',
'skin_type' => 'bloated',
'skin_color' => 'red',
'body_aim' => 'small_winged');
$queen_honeybee->{belongings} = [ Distribution->new(
0.300 => $Item::royal_jelly->bunch(4),
0.300 => $Item::royal_jelly->bunch(3),
0.300 => $Item::royal_jelly->bunch(2),
0.100 => $Item::royal_jelly->bunch(1),
)];
$giant_grasshopper = Actor->new('name' => 'giant grasshopper',
'max' => {
'strength' => Dice->new(2,3),
'constitution' => Dice->new(2,2,+2),
'dexterity' => Dice->new(1,4,+16),
'intelligence' => Dice->new(1,1),
'spirit' => Dice->new(1,2),
'charisma' => Dice->new(1,1),
},
'hands' => $Item::nonexistant_part,
'sex' => $Distribution::even_sex,
'race' => 'Grasshopper',
'melee_attacks'=> [ $Attack::insect_kick, $Attack::insect_kick ],
'appearance' => 'grasshopper',
'color' => 'green',
'hair_color' => 'no',
'eye_color' => 'multifaceted',
'skin_type' => 'shiny',
'skin_color' => 'green',
'body_aim' => 'pouncer');
$forest_cat = Actor->new('name' => 'forest cat',
'max' => {
'strength' => Dice->new(2,3,+1),
'constitution' => Dice->new(2,3,+2),
'dexterity' => Dice->new(1,3,+19),
'intelligence' => Dice->new(2,2,+2),
'spirit' => Dice->new(2,3),
'charisma' => Dice->new(3,3,+3),
},
'nightvision' => 1,
'sex' => $Distribution::even_sex,
'race' => 'Feline',
'melee_attacks'=> [ $Attack::cat_bite, $Attack::cat_claw, $Attack::cat_claw ],
'hitbonus' => -1,
'appearance' => 'feline',
'color' => 'brown',
'hair_type' => 'sleek',
'hair_color' => 'beige',
'eye_type' => 'deep',
'eye_color' => Distribution->new(0.60 => 'green', 0.40 => 'brown'),
'skin_type' => 'fair',
'skin_color' => 'grey',
'body_aim' => 'pouncer');
# cat: lick wounds
# cat: tail == waist? subsceptible?
$grizzly_bear = Actor->new('name' => 'grizzly bear',
'max' => {
'strength' => Dice->new(4,6,+1),
'constitution' => Dice->new(4,5,+2),
'dexterity' => Dice->new(3,5),
'intelligence' => Dice->new(2,3,+1),
'spirit' => Dice->new(2,3),
'charisma' => Dice->new(2,3),
},
'nightvision' => 1,
'torso' => $Item::thick_fur->clone,
'arms' => $Item::thick_fur->clone,
'legs' => $Item::thick_fur->clone,
'head' => $Item::thick_fur->clone,
'shoulders' => $Item::thick_fur->clone,
'hands' => $Item::thick_fur->clone,
'feet' => $Item::thick_fur->clone,
'sex' => $Distribution::even_sex,
'race' => 'Bear',
'melee_attacks'=> [ $Attack::bear_claw, $Attack::bear_claw, $Attack::bear_hug ],
'negotiate' =>
{
'Neutral' => 50,
},
'appearance' => 'ursine',
'color' => 'brown',
'hair_type' => 'thick',
'hair_color' => 'brown',
'eye_type' => 'piercing',
'eye_color' => 'black',
'skin_type' => 'oily',
'skin_color' => 'grey',
'body_aim' => 'smart_biped');
$sylvan_snake = Actor->new('name' => 'sylvan snake',
'max' => {
'strength' => Dice->new(2,3,-1),
'constitution' => Dice->new(2,3,+1),
'dexterity' => Dice->new(1,6,+13),
'intelligence' => Dice->new(2,2),
'spirit' => Dice->new(2,2),
'charisma' => 1,
},
'nightvision' => 1,
'torso' => $Item::reptilian_scales->clone,
'head' => $Item::reptilian_scales->clone,
'legs' => $Item::nonexistant_part,
'feet' => $Item::nonexistant_part,
'arms' => $Item::nonexistant_part,
'hands' => $Item::nonexistant_part,
'shoulders' => $Item::nonexistant_part,
'waist' => $Item::nonexistant_part,
'hair_color' => 'no',
'eye_type' => 'beady',
'eye_color' => 'black',
'skin_type' => 'scaly',
'skin_color' => 'green',
'sex' => $Distribution::even_sex,
'race' => 'Snake',
'melee_attacks'=> [ $Attack::sylvan_snake_bite ],
'hitbonus' => 0,
'appearance' => 'serpent',
'color' => 'green',
'body_aim' => 'creepy_crawly');
$juggler_snake = Actor->new('name' => 'juggler snake',
'max' => {
'strength' => Dice->new(1,2),
'constitution' => Dice->new(2,3),
'dexterity' => Dice->new(1,6,+9),
'intelligence' => Dice->new(1,2,+3),
'spirit' => 1,
'charisma' => Dice->new(1,4,+16),
},
'nightvision' => 1,
'legs' => $Item::nonexistant_part,
'feet' => $Item::nonexistant_part,
'arms' => $Item::nonexistant_part,
'hands' => $Item::nonexistant_part,
'shoulders' => $Item::nonexistant_part,
'waist' => $Item::nonexistant_part,
'hair_color' => 'no',
'eye_color' => 'hypnotizing',
'skin_type' => 'scaly',
'skin_color' => 'red',
'sex' => $Distribution::even_sex,
'race' => 'Snake',
'melee_attacks'=> [ $Attack::sylvan_snake_bite ], # not exactly
'hitbonus' => 0,
'appearance' => 'serpent',
'color' => 'red',
'body_aim' => 'creepy_crawly');
# $juggler_snake->learn($Talent::charm);
$blue_spider = Actor->new('name' => 'blue spider',
'max' => {
'strength' => 1,
'constitution' => 1,
'dexterity' => Dice->new(3,3,+18),
'intelligence' => 1,
'spirit' => 1,
'charisma' => 1,
},
'arms' => $Item::nonexistant_part,
'hands' => $Item::nonexistant_part,
'shoulders' => $Item::nonexistant_part,
'waist' => $Item::nonexistant_part,
'sex' => $Distribution::even_sex,
'race' => 'Arachnid',
'melee_attacks'=> [ $Attack::blue_spider_bite ],
# todo: poison
'hitbonus' => -2,
'appearance' => 'spider',
'color' => 'blue',
'hair_type' => 'spiky',
'hair_color' => 'blue',
'eye_type' => 'beady',
'eye_color' => 'black',
'skin_type' => 'mottled',
'skin_color' => 'blue',
'body_aim' => 'creepy_crawly');
### PLAINS
$scutter_skunk = Actor->new('name' => 'scutter skunk',
'max' => {
'strength' => Dice->new(2,3,+2),
'constitution' => Dice->new(2,5),
'dexterity' => Dice->new(1,3,+15),
'intelligence' => Dice->new(2,2,+1),
'spirit' => Dice->new(2,3,-1),
'charisma' => Dice->new(1,2),
},
'nightvision' => 1,
'sex' => $Distribution::even_sex,
'race' => 'Feline', # not exactly
'melee_attacks'=> [ $Attack::cat_claw, $Attack::cat_claw ],
'hitbonus' => -1,
'negotiate' =>
{
'Respectful' => 25,
},
'appearance' => 'feline',
'color' => 'white',
'hair_type' => 'striped',
'hair_color' => 'white',
'eye_type' => 'piercing',
'eye_color' => 'red',
'skin_type' => 'gummy',
'skin_color' => 'black',
'body_aim' => 'pouncer');
### SWAMP
$green_alligator = Actor->new('name' => 'green alligator',
'max' => {
'strength' => Dice->new(3,6,+7),
'constitution' => Dice->new(2,10,+10),
'dexterity' => Dice->new(2,3),
'intelligence' => Dice->new(1,2,+1),
'spirit' => 1,
'charisma' => Dice->new(2,2),
},
'nightvision' => 1,
'torso' => $Item::reptilian_scales->clone,
'arms' => $Item::nonexistant_part->clone,
'legs' => $Item::reptilian_scales->clone,
'head' => $Item::reptilian_scales->clone,
'shoulders' => $Item::reptilian_scales->clone,
'hands' => $Item::nonexistant_part->clone,
'feet' => $Item::reptilian_scales->clone,
'sex' => $Distribution::even_sex,
'race' => 'Reptile',
'melee_attacks'=> [ $Attack::gator_grip ],
'appearance' => 'gator',
'color' => 'green',
'hair_color' => 'no',
'eye_type' => 'empty',
'eye_color' => 'yellow',
'skin_type' => 'tough',
'skin_color' => 'green',
'body_aim' => 'creepy_crawly')->implies($Adj::aquatic);
$wetland_viper = Actor->new('name' => 'wetland viper',
'max' => {
'strength' => Dice->new(1,4),
'constitution' => Dice->new(3,3,+3),
'dexterity' => Dice->new(1,2,+16),
'intelligence' => Dice->new(1,6),
'spirit' => Dice->new(1,6),
'charisma' => Dice->new(1,6),
},
'nightvision' => 1,
'torso' => $Item::reptilian_scales->clone,
'head' => $Item::reptilian_scales->clone,
'legs' => $Item::nonexistant_part,
'feet' => $Item::nonexistant_part,
'arms' => $Item::nonexistant_part,
'hands' => $Item::nonexistant_part,
'shoulders' => $Item::nonexistant_part,
'waist' => $Item::nonexistant_part,
'negotiate' =>
{
'Scary' => 25,
'Familiar' => 25,
},
'hair_color' => 'no',
'eye_type' => 'milky',
'eye_color' => 'grey',
'skin_type' => 'scaly',
'skin_color' => 'yellow',
'sex' => $Distribution::even_sex,
'race' => 'Snake',
'melee_attacks'=> [ $Attack::blue_spider_bite ],
# todo poison
'hitbonus' => 0,
'appearance' => 'serpent',
'color' => 'yellow',
'body_aim' => 'creepy_crawly')->implies($Adj::aquatic);
# purple catfish
# brown eel
$pond_spider = Actor->new('name' => 'pond spider',
'max' => {
'strength' => Dice->new(1,3),
'constitution' => Dice->new(2,3,+1),
'dexterity' => Dice->new(3,3,+10),
'intelligence' => Dice->new(1,3),
'spirit' => Dice->new(1,2),
'charisma' => Dice->new(1,2),
},
'arms' => $Item::nonexistant_part,
'hands' => $Item::nonexistant_part,
'shoulders' => $Item::nonexistant_part,
'waist' => $Item::nonexistant_part,
'sex' => $Distribution::even_sex,
'race' => 'Arachnid',
'melee_attacks'=> [ $Attack::blue_spider_bite ], # not exactly
# todo poison
'appearance' => 'spider',
'color' => 'blue',
'hair_type' => 'spiky',
'hair_color' => 'blue',
'eye_type' => 'beady',
'eye_color' => 'black',
'skin_type' => 'mottled',
'skin_color' => 'blue',
'body_aim' => 'creepy_crawly');
$shadow_owl = Actor->new('name' => 'shadow owl',
'max' => {
'strength' => Dice->new(2,2,+2),
'constitution' => Dice->new(2,2,+2),
'dexterity' => Dice->new(2,3,+13),
'intelligence' => Dice->new(2,3,+2),
'spirit' => Dice->new(2,6),
'charisma' => Dice->new(1,10),
},
'nightvision' => 1,
'sex' => $Distribution::even_sex,
'race' => 'Owl',
'melee_attacks'=> [ $Attack::talon, $Attack::talon, $Attack::beak ], # not exactly
'appearance' => 'bird',
'color' => 'grey',
'hair_color' => 'feathers, not',
'eye_type' => 'knowing',
'eye_color' => 'brown',
'skin_type' => 'ashy',
'skin_color' => 'grey',
'body_aim' => 'small_winged')->implies($Adj::airborne);
1;
| catseye/Corona-Realm-of-Magic | src/corona/Animal.pm | Perl | bsd-3-clause | 20,311 |
#ExStart:1
use lib 'lib';
use strict;
use warnings;
use utf8;
use File::Slurp; # From CPAN
use JSON;
use AsposeStorageCloud::StorageApi;
use AsposeStorageCloud::ApiClient;
use AsposeStorageCloud::Configuration;
use AsposeCellsCloud::CellsApi;
use AsposeCellsCloud::ApiClient;
use AsposeCellsCloud::Configuration;
my $configFile = '../Config/config.json';
my $configPropsText = read_file($configFile);
my $configProps = decode_json($configPropsText);
my $data_path = '../../../Data/';
my $out_path = $configProps->{'out_folder'};
$AsposeCellsCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeCellsCloud::Configuration::api_key = $configProps->{'api_key'};
$AsposeCellsCloud::Configuration::debug = 1;
$AsposeStorageCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeStorageCloud::Configuration::api_key = $configProps->{'api_key'};
# Instantiate Aspose.Storage and Aspose.Cells API SDK
my $storageApi = AsposeStorageCloud::StorageApi->new();
my $cellsApi = AsposeCellsCloud::CellsApi->new();
# Set input file name
my $name = 'Sample_Test_Book.xls';
my $sheetName = 'Sheet2';
my $range = 'A1:A12';
# Upload file to aspose cloud storage
my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name);
# Invoke Aspose.Cells Cloud SDK API to clear cells formatting in a worksheet
$response = $cellsApi->PostClearFormats(name=> $name, sheetName=>$sheetName, range=>$range);
if($response->{'Status'} eq 'OK'){
# Download updated Workbook from storage server
my $output_file = $out_path. $name;
$response = $storageApi->GetDownload(Path => $name);;
write_file($output_file, { binmode => ":raw" }, $response->{'Content'});
}
#ExEnd:1 | asposecells/Aspose_Cells_Cloud | Examples/Perl/Cells/ClearCellFormattingWorksheet.pl | Perl | mit | 1,705 |
#------------------------------------------------------------------------------
# File: MPC.pm
#
# Description: Read Musepack audio meta information
#
# Revisions: 11/14/2006 - P. Harvey Created
#
# References: 1) http://www.musepack.net/
#------------------------------------------------------------------------------
package Image::ExifTool::MPC;
use strict;
use vars qw($VERSION);
use Image::ExifTool qw(:DataAccess :Utils);
use Image::ExifTool::FLAC;
$VERSION = '1.00';
# MPC metadata blocks
%Image::ExifTool::MPC::Main = (
PROCESS_PROC => \&Image::ExifTool::FLAC::ProcessBitStream,
GROUPS => { 2 => 'Audio' },
NOTES => q{
Tags used in Musepack (MPC) audio files. ExifTool also extracts ID3 and APE
information from these files.
},
'Bit032-063' => 'TotalFrames',
'Bit080-081' => {
Name => 'SampleRate',
PrintConv => {
0 => 44100,
1 => 48000,
2 => 37800,
3 => 32000,
},
},
'Bit084-087' => {
Name => 'Quality',
PrintConv => {
1 => 'Unstable/Experimental',
5 => '0',
6 => '1',
7 => '2 (Telephone)',
8 => '3 (Thumb)',
9 => '4 (Radio)',
10 => '5 (Standard)',
11 => '6 (Xtreme)',
12 => '7 (Insane)',
13 => '8 (BrainDead)',
14 => '9',
15 => '10',
},
},
'Bit088-093' => 'MaxBand',
'Bit096-111' => 'ReplayGainTrackPeak',
'Bit112-127' => 'ReplayGainTrackGain',
'Bit128-143' => 'ReplayGainAlbumPeak',
'Bit144-159' => 'ReplayGainAlbumGain',
'Bit179' => {
Name => 'FastSeek',
PrintConv => { 0 => 'No', 1 => 'Yes' },
},
'Bit191' => {
Name => 'Gapless',
PrintConv => { 0 => 'No', 1 => 'Yes' },
},
'Bit216-223' => {
Name => 'EncoderVersion',
PrintConv => '$val =~ s/(\d)(\d)(\d)$/$1.$2.$3/; $val',
},
);
#------------------------------------------------------------------------------
# Extract information from an MPC file
# Inputs: 0) ExifTool object reference, 1) dirInfo reference
# - Just looks for MPC trailer if FileType is already set
# Returns: 1 on success, 0 if this wasn't a valid MPC file
sub ProcessMPC($$)
{
my ($exifTool, $dirInfo) = @_;
# must first check for leading ID3 information
unless ($exifTool->{DoneID3}) {
require Image::ExifTool::ID3;
Image::ExifTool::ID3::ProcessID3($exifTool, $dirInfo) and return 1;
}
my $raf = $$dirInfo{RAF};
my $buff;
# check MPC signature
$raf->Read($buff, 32) == 32 and $buff =~ /^MP\+(.)/s or return 0;
my $vers = ord($1) & 0x0f;
$exifTool->SetFileType();
# extract audio information (currently only from version 7 MPC files)
if ($vers == 0x07) {
SetByteOrder('II');
my $pos = $raf->Tell() - 32;
if ($exifTool->Options('Verbose')) {
$exifTool->VPrint(0, "MPC Header (32 bytes):\n");
$exifTool->VerboseDump(\$buff, DataPos => $pos);
}
my $tagTablePtr = GetTagTable('Image::ExifTool::MPC::Main');
my %dirInfo = ( DataPt => \$buff, DataPos => $pos );
$exifTool->ProcessDirectory(\%dirInfo, $tagTablePtr);
} else {
$exifTool->Warn('Audio info not currently extracted from this version MPC file');
}
# process APE trailer if it exists
require Image::ExifTool::APE;
Image::ExifTool::APE::ProcessAPE($exifTool, $dirInfo);
return 1;
}
1; # end
__END__
=head1 NAME
Image::ExifTool::MPC - Read Musepack audio meta information
=head1 SYNOPSIS
This module is used by Image::ExifTool
=head1 DESCRIPTION
This module contains definitions required by Image::ExifTool to extract meta
information from Musepack (MPC) audio files.
=head1 AUTHOR
Copyright 2003-2009, Phil Harvey (phil at owl.phy.queensu.ca)
This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=head1 REFERENCES
=over 4
=item L<http://www.musepack.net/>
=back
=head1 SEE ALSO
L<Image::ExifTool::TagNames/MPC Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>
=cut
| opf-attic/ref | tools/fits/0.5.0/tools/exiftool/perl/lib/Image/ExifTool/MPC.pm | Perl | apache-2.0 | 4,214 |
package Paws::MigrationHub::ListMigrationTasksResult;
use Moose;
has MigrationTaskSummaryList => (is => 'ro', isa => 'ArrayRef[Paws::MigrationHub::MigrationTaskSummary]');
has NextToken => (is => 'ro', isa => 'Str');
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::MigrationHub::ListMigrationTasksResult
=head1 ATTRIBUTES
=head2 MigrationTaskSummaryList => ArrayRef[L<Paws::MigrationHub::MigrationTaskSummary>]
Lists the migration task's summary which includes:
C<MigrationTaskName>, C<ProgressPercent>, C<ProgressUpdateStream>,
C<Status>, and the C<UpdateDateTime> for each task.
=head2 NextToken => Str
If there are more migration tasks than the max result, return the next
token to be passed to the next call as a bookmark of where to start
from.
=head2 _request_id => Str
=cut
1; | ioanrogers/aws-sdk-perl | auto-lib/Paws/MigrationHub/ListMigrationTasksResult.pm | Perl | apache-2.0 | 862 |
package #
Date::Manip::Offset::off082;
# Copyright (c) 2008-2014 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
# This file was automatically generated. Any changes to this file will
# be lost the next time 'tzdata' is run.
# Generated on: Fri Nov 21 11:03:45 EST 2014
# Data version: tzdata2014j
# Code version: tzcode2014j
# This module contains data from the zoneinfo time zone database. The original
# data was obtained from the URL:
# ftp://ftp.iana.orgtz
use strict;
use warnings;
require 5.010000;
our ($VERSION);
$VERSION='6.48';
END { undef $VERSION; }
our ($Offset,%Offset);
END {
undef $Offset;
undef %Offset;
}
$Offset = '+03:21:04';
%Offset = (
0 => [
'asia/aqtau',
],
);
1;
| nriley/Pester | Source/Manip/Offset/off082.pm | Perl | bsd-2-clause | 848 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 6.2.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
0370 03FF
END
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/unicore/lib/Blk/Greek.pl | Perl | mit | 433 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 8.0.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly. Use Unicode::UCD to access the Unicode character data
# base.
return <<'END';
V567
0
45
46
48
58
160
161
178
180
215
216
2304
2384
2385
2387
2389
2404
2406
2416
2418
2432
2433
2436
2437
2445
2447
2449
2451
2473
2474
2481
2482
2483
2486
2490
2492
2501
2503
2505
2507
2511
2519
2520
2524
2526
2527
2532
2534
2546
2561
2564
2565
2571
2575
2577
2579
2601
2602
2609
2610
2612
2613
2615
2616
2618
2620
2621
2622
2627
2631
2633
2635
2638
2649
2653
2654
2655
2662
2676
2677
2678
2689
2692
2693
2702
2703
2706
2707
2729
2730
2737
2738
2740
2741
2746
2748
2758
2759
2762
2763
2766
2784
2788
2790
2800
2809
2810
2817
2820
2821
2829
2831
2833
2835
2857
2858
2865
2866
2868
2869
2874
2876
2885
2887
2889
2891
2894
2902
2904
2908
2910
2911
2916
2918
2928
2929
2930
2946
2948
2949
2955
2958
2961
2962
2966
2969
2971
2972
2973
2974
2976
2979
2981
2984
2987
2990
3002
3006
3011
3014
3017
3018
3022
3031
3032
3046
3056
3072
3076
3077
3085
3086
3089
3090
3113
3114
3130
3133
3141
3142
3145
3146
3150
3157
3159
3160
3163
3168
3172
3174
3184
3201
3204
3205
3213
3214
3217
3218
3241
3242
3252
3253
3258
3260
3269
3270
3273
3274
3278
3285
3287
3294
3295
3296
3300
3302
3312
3313
3315
3329
3332
3333
3341
3342
3345
3346
3387
3389
3397
3398
3401
3402
3407
3415
3416
3423
3428
3430
3440
3450
3456
3458
3460
3461
3479
3482
3506
3507
3516
3517
3518
3520
3527
3530
3531
3535
3541
3542
3543
3544
3552
3558
3568
3570
3572
3585
3631
3632
3643
3648
3654
3655
3663
3664
3674
3713
3715
3716
3717
3719
3721
3722
3723
3725
3726
3732
3736
3737
3744
3745
3748
3749
3750
3751
3752
3754
3756
3757
3759
3760
3770
3771
3774
3776
3781
3784
3788
3789
3790
3792
3802
3804
3808
3872
3892
3893
3894
3895
3896
3897
3898
3904
3912
3913
3949
3953
3974
3976
3992
3993
4029
4038
4039
4096
4170
4174
4175
4176
4254
5888
5901
5902
5909
5920
5941
5952
5972
5984
5997
5998
6001
6002
6004
6016
6068
6070
6100
6108
6109
6112
6122
6400
6431
6432
6444
6448
6460
6470
6510
6512
6517
6528
6572
6576
6602
6608
6618
6656
6684
6688
6751
6752
6781
6783
6794
6800
6810
6912
6988
6992
7002
7040
7156
7168
7224
7232
7242
7245
7248
7376
7379
7380
7394
7410
7413
7416
7418
8204
8206
8208
8213
8308
8309
8322
8325
9676
9677
43008
43010
43011
43048
43072
43124
43136
43205
43216
43226
43232
43250
43264
43310
43312
43348
43392
43457
43472
43482
43488
43494
43495
43519
43520
43575
43584
43598
43600
43610
43616
43632
43633
43636
43642
43715
43744
43760
43765
43767
43968
44011
44012
44014
44016
44026
68096
68100
68101
68103
68108
68116
68117
68120
68121
68148
68152
68155
68159
68168
69632
69703
69714
69744
69759
69819
69888
69941
69942
69952
69968
70004
70016
70084
70090
70093
70096
70106
70113
70133
70144
70162
70163
70200
70272
70279
70280
70281
70282
70286
70287
70302
70303
70313
70320
70379
70384
70394
70400
70404
70405
70413
70415
70417
70419
70441
70442
70449
70450
70452
70453
70458
70460
70469
70471
70473
70475
70478
70487
70488
70496
70500
70502
70509
70512
70517
70785
70853
70864
70874
71040
71094
71096
71105
71128
71134
71168
71233
71248
71258
71296
71352
71360
71370
71424
71450
71453
71468
71472
71484
END
| operepo/ope | bin/usr/share/perl5/core_perl/unicore/lib/InSC/Other.pl | Perl | mit | 3,459 |
=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
# POD documentation - main docs before the code
=pod
=head1 NAME
Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::NCTreeBestMMerge
=cut
=head1 SYNOPSIS
my $db = Bio::EnsEMBL::Compara::DBAdaptor->new($locator);
my $treebest_mmerge = Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::NCTreeBestMMerge->new
(
-db => $db,
-input_id => $input_id,
-analysis => $analysis
);
$treebest_mmerge->fetch_input(); #reads from DB
$treebest_mmerge->run();
$treebest_mmerge->write_output(); #writes to DB
=cut
=head1 DESCRIPTION
This Analysis will take the sequences from a cluster, the cm from
nc_profile and run a profiled alignment, storing the results as
cigar_lines for each sequence.
=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 APPENDIX
The rest of the documentation details each of the object methods.
Internal methods are usually preceded with a _
=cut
package Bio::EnsEMBL::Compara::RunnableDB::ncRNAtrees::NCTreeBestMMerge;
use strict;
use Bio::EnsEMBL::Compara::Graph::NewickParser;
use base ('Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::TreeBest', 'Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::StoreTree');
sub param_defaults {
return {
'store_tree_support' => 1,
};
}
=head2 fetch_input
Title : fetch_input
Usage : $self->fetch_input
Function: Fetches input data from the database
Returns : none
Args : none
=cut
sub fetch_input {
my( $self) = @_;
my $gene_tree = $self->compara_dba->get_GeneTreeAdaptor->fetch_by_dbID($self->param('gene_tree_id'));
$self->param('gene_tree', $gene_tree);
$self->param('inputtrees_unrooted', {});
$self->param('inputtrees_rooted', {});
$self->_load_species_tree_string_from_db();
$self->load_input_trees;
}
=head2 run
Title : run
Usage : $self->run
Function: runs something
Returns : none
Args : none
=cut
sub run {
my $self = shift;
$self->reroot_inputtrees;
$self->param('ref_support', [keys %{$self->param('inputtrees_rooted')}]);
my $input_trees = [map {$self->param('inputtrees_rooted')->{$_}} @{$self->param('ref_support')}];
my $merged_tree = $self->run_treebest_mmerge($input_trees);
my $input_aln = $self->dumpTreeMultipleAlignmentToWorkdir($self->param('gene_tree'), 'fasta', {-APPEND_SPECIES_TREE_NODE_ID => 1});
my $leafcount = scalar(@{$self->param('gene_tree')->get_all_leaves});
$merged_tree = $self->run_treebest_branchlength_nj($input_aln, $merged_tree) if ($leafcount >= 3);
$self->parse_newick_into_tree($merged_tree, $self->param('gene_tree'), $self->param('ref_support'));
}
=head2 write_output
Title : write_output
Usage : $self->write_output
Function: stores something
Returns : none
Args : none
=cut
sub write_output {
my ($self) = @_;
$self->store_genetree($self->param('gene_tree')) if defined $self->param('inputtrees_unrooted');
}
sub post_cleanup {
my $self = shift;
if($self->param('gene_tree')) {
printf("NctreeBestMMerge::post_cleanup releasing tree\n") if($self->debug);
$self->param('gene_tree')->release_tree;
$self->param('gene_tree', undef);
}
$self->SUPER::post_cleanup if $self->can("SUPER::post_cleanup");
}
##########################################
#
# internal methods
#
##########################################
sub reroot_inputtrees {
my $self = shift;
foreach my $method (keys %{$self->param('inputtrees_unrooted')}) {
my $inputtree = $self->param('inputtrees_unrooted')->{$method};
# Parse the rooted tree string
my $rootedstring = $self->run_treebest_sdi($inputtree, 1);
$self->param('inputtrees_rooted')->{$method} = $rootedstring;
}
}
sub load_input_trees {
my $self = shift;
my $tree = $self->param('gene_tree');
for my $other_tree (values %{$tree->alternative_trees}) {
$other_tree->preload();
# horrible hack: we replace taxon_id with species_tree_node_id
foreach my $leaf (@{$other_tree->get_all_leaves}) {
$leaf->taxon_id($leaf->genome_db->_species_tree_node_id);
}
print STDERR $other_tree->newick_format('ryo','%{-m}%{"_"-x}:%{d}') if ($self->debug);
my $tag = $other_tree->clusterset_id;
$self->param('inputtrees_unrooted')->{$tag} = $other_tree->newick_format('ryo','%{-m}%{"_"-x}:%{d}');
}
}
1;
| ckongEbi/ensembl-compara | modules/Bio/EnsEMBL/Compara/RunnableDB/ncRNAtrees/NCTreeBestMMerge.pm | Perl | apache-2.0 | 5,229 |
=pod
=head1 NAME
EVP_KEYMGMT,
EVP_KEYMGMT_fetch,
EVP_KEYMGMT_up_ref,
EVP_KEYMGMT_free,
EVP_KEYMGMT_get0_provider,
EVP_KEYMGMT_is_a,
EVP_KEYMGMT_get0_description,
EVP_KEYMGMT_get0_name,
EVP_KEYMGMT_do_all_provided,
EVP_KEYMGMT_names_do_all,
EVP_KEYMGMT_gettable_params,
EVP_KEYMGMT_settable_params,
EVP_KEYMGMT_gen_settable_params
- EVP key management routines
=head1 SYNOPSIS
#include <openssl/evp.h>
typedef struct evp_keymgmt_st EVP_KEYMGMT;
EVP_KEYMGMT *EVP_KEYMGMT_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
const char *properties);
int EVP_KEYMGMT_up_ref(EVP_KEYMGMT *keymgmt);
void EVP_KEYMGMT_free(EVP_KEYMGMT *keymgmt);
const OSSL_PROVIDER *EVP_KEYMGMT_get0_provider(const EVP_KEYMGMT *keymgmt);
int EVP_KEYMGMT_is_a(const EVP_KEYMGMT *keymgmt, const char *name);
const char *EVP_KEYMGMT_get0_name(const EVP_KEYMGMT *keymgmt);
const char *EVP_KEYMGMT_get0_description(const EVP_KEYMGMT *keymgmt);
void EVP_KEYMGMT_do_all_provided(OSSL_LIB_CTX *libctx,
void (*fn)(EVP_KEYMGMT *keymgmt, void *arg),
void *arg);
int EVP_KEYMGMT_names_do_all(const EVP_KEYMGMT *keymgmt,
void (*fn)(const char *name, void *data),
void *data);
const OSSL_PARAM *EVP_KEYMGMT_gettable_params(const EVP_KEYMGMT *keymgmt);
const OSSL_PARAM *EVP_KEYMGMT_settable_params(const EVP_KEYMGMT *keymgmt);
const OSSL_PARAM *EVP_KEYMGMT_gen_settable_params(const EVP_KEYMGMT *keymgmt);
=head1 DESCRIPTION
B<EVP_KEYMGMT> is a method object that represents key management
implementations for different cryptographic algorithms.
This method object provides functionality to have providers import key
material from the outside, as well as export key material to the
outside.
Most of the functionality can only be used internally and has no
public interface, this object is simply passed into other functions
when needed.
EVP_KEYMGMT_fetch() looks for an algorithm within the provider that
has been loaded into the B<OSSL_LIB_CTX> given by I<ctx>, having the
name given by I<algorithm> and the properties given by I<properties>.
EVP_KEYMGMT_up_ref() increments the reference count for the given
B<EVP_KEYMGMT> I<keymgmt>.
EVP_KEYMGMT_free() decrements the reference count for the given
B<EVP_KEYMGMT> I<keymgmt>, and when the count reaches zero, frees it.
EVP_KEYMGMT_get0_provider() returns the provider that has this particular
implementation.
EVP_KEYMGMT_is_a() checks if I<keymgmt> is an implementation of an
algorithm that's identifiable with I<name>.
EVP_KEYMGMT_get0_name() returns the algorithm name from the provided
implementation for the given I<keymgmt>. Note that the I<keymgmt> may have
multiple synonyms associated with it. In this case the first name from the
algorithm definition is returned. Ownership of the returned string is
retained by the I<keymgmt> object and should not be freed by the caller.
EVP_KEYMGMT_names_do_all() traverses all names for the I<keymgmt>, and
calls I<fn> with each name and I<data>.
EVP_KEYMGMT_get0_description() returns a description of the I<keymgmt>, meant
for display and human consumption. The description is at the discretion
of the I<keymgmt> implementation.
EVP_KEYMGMT_do_all_provided() traverses all key keymgmt implementations by
all activated providers in the library context I<libctx>, and for each
of the implementations, calls I<fn> with the implementation method and
I<data> as arguments.
EVP_KEYMGMT_gettable_params() and EVP_KEYMGMT_settable_params() return a
constant B<OSSL_PARAM> array that describes the names and types of key
parameters that can be retrieved or set.
EVP_KEYMGMT_gettable_params() is used by L<EVP_PKEY_gettable_params(3)>.
See L<OSSL_PARAM(3)> for the use of B<OSSL_PARAM> as a parameter descriptor.
EVP_KEYMGMT_gen_settable_params() returns a constant B<OSSL_PARAM> array that
describes the names and types of key generation parameters that can be set via
L<EVP_PKEY_CTX_set_params(3)>.
=head1 NOTES
EVP_KEYMGMT_fetch() may be called implicitly by other fetching
functions, using the same library context and properties.
Any other API that uses keys will typically do this.
=head1 RETURN VALUES
EVP_KEYMGMT_fetch() returns a pointer to the key management
implementation represented by an EVP_KEYMGMT object, or NULL on
error.
EVP_KEYMGMT_up_ref() returns 1 on success, or 0 on error.
EVP_KEYMGMT_names_do_all() returns 1 if the callback was called for all
names. A return value of 0 means that the callback was not called for any names.
EVP_KEYMGMT_free() doesn't return any value.
EVP_KEYMGMT_get0_provider() returns a pointer to a provider object, or NULL
on error.
EVP_KEYMGMT_is_a() returns 1 of I<keymgmt> was identifiable,
otherwise 0.
EVP_KEYMGMT_get0_name() returns the algorithm name, or NULL on error.
EVP_KEYMGMT_get0_description() returns a pointer to a decription, or NULL if
there isn't one.
EVP_KEYMGMT_gettable_params(), EVP_KEYMGMT_settable_params() and
EVP_KEYMGMT_gen_settable_params() return a constant B<OSSL_PARAM> array or
NULL on error.
=head1 SEE ALSO
L<EVP_MD_fetch(3)>, L<OSSL_LIB_CTX(3)>
=head1 HISTORY
The functions described here were added in OpenSSL 3.0.
=head1 COPYRIGHT
Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the Apache License 2.0 (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| jens-maus/amissl | openssl/doc/man3/EVP_KEYMGMT.pod | Perl | bsd-3-clause | 5,600 |
#==========================================================================
# Copyright (c) 1995-1998 Martien Verbruggen
#--------------------------------------------------------------------------
#
# Name:
# GD::Graph::pie.pm
#
# $Id: pie.pm,v 1.21 2007/04/26 03:16:09 ben Exp $
#
#==========================================================================
package GD::Graph::pie;
($GD::Graph::pie::VERSION) = '$Revision: 1.21 $' =~ /\s([\d.]+)/;
use strict;
use constant PI => 4 * atan2(1,1);
use GD;
use GD::Graph;
use GD::Graph::utils qw(:all);
use GD::Graph::colour qw(:colours :lists);
use GD::Text::Align;
use Carp;
@GD::Graph::pie::ISA = qw( GD::Graph );
my $ANGLE_OFFSET = 90;
my %Defaults = (
# Set the height of the pie.
# Because of the dependency of this on runtime information, this
# is being set in GD::Graph::pie::initialise
# pie_height => _round(0.1*${'width'}),
pie_height => undef,
# Do you want a 3D pie?
'3d' => 1,
# The angle at which to start the first data set
# 0 is at the front/bottom
start_angle => 0,
# Angle below which a label on a pie slice is suppressed.
suppress_angle => 0, # CONTRIB idea ryan <xomina@bitstream.net>
# and some public attributes without defaults
label => undef,
# This misnamed attribute is used for pie marker colours
axislabelclr => 'black',
);
# PRIVATE
sub _has_default {
my $self = shift;
my $attr = shift || return;
exists $Defaults{$attr} || $self->SUPER::_has_default($attr);
}
sub initialise
{
my $self = shift;
$self->SUPER::initialise();
while (my($key, $val) = each %Defaults)
{ $self->{$key} = $val }
$self->set( pie_height => _round(0.1 * $self->{height}) );
$self->set_value_font(gdTinyFont);
$self->set_label_font(gdSmallFont);
}
# PUBLIC methods, documented in pod
sub plot
{
my $self = shift;
my $data = shift;
$self->check_data($data) or return;
$self->init_graph() or return;
$self->setup_text() or return;
$self->setup_coords() or return;
$self->draw_text() or return;
$self->draw_pie() or return;
$self->draw_data() or return;
return $self->{graph};
}
sub set_label_font # (fontname)
{
my $self = shift;
$self->_set_font('gdta_label', @_) or return;
$self->{gdta_label}->set_align('bottom', 'center');
}
sub set_value_font # (fontname)
{
my $self = shift;
$self->_set_font('gdta_value', @_) or return;
$self->{gdta_value}->set_align('center', 'center');
}
# Inherit defaults() from GD::Graph
# inherit checkdata from GD::Graph
# Setup the coordinate system and colours, calculate the
# relative axis coordinates in respect to the canvas size.
sub setup_coords()
{
my $self = shift;
# Make sure we're not reserving space we don't need.
$self->{'3d'} = 0 if $self->{pie_height} <= 0;
$self->set(pie_height => 0) unless $self->{'3d'};
my $tfh = $self->{title} ? $self->{gdta_title}->get('height') : 0;
my $lfh = $self->{label} ? $self->{gdta_label}->get('height') : 0;
# Calculate the bounding box for the pie, and
# some width, height, and centre parameters (don't forget fenceposts!)
$self->{bottom} =
$self->{height} - $self->{pie_height} - $self->{b_margin} -
( $lfh ? $lfh + $self->{text_space} : 0 ) - 1;
$self->{top} =
$self->{t_margin} + ( $tfh ? $tfh + $self->{text_space} : 0 );
return $self->_set_error('Vertical size too small')
if $self->{bottom} - $self->{top} <= 0;
$self->{left} = $self->{l_margin};
$self->{right} = $self->{width} - $self->{r_margin} - 1;
# ensure that the center is a single pixel, not a half-pixel position
$self->{right}-- if ($self->{right} - $self->{left}) % 2;
$self->{bottom}-- if ($self->{bottom} - $self->{top}) % 2;
return $self->_set_error('Horizontal size too small')
if $self->{right} - $self->{left} <= 0;
$self->{w} = $self->{right} - $self->{left} + 1;
$self->{h} = $self->{bottom} - $self->{top} + 1;
$self->{xc} = ($self->{right} + $self->{left})/2;
$self->{yc} = ($self->{bottom} + $self->{top})/2;
return $self;
}
# inherit open_graph from GD::Graph
# Setup the parameters for the text elements
sub setup_text
{
my $self = shift;
if ( $self->{title} )
{
#print "'$s->{title}' at ($s->{xc},$s->{t_margin})\n";
$self->{gdta_title}->set(colour => $self->{tci});
$self->{gdta_title}->set_text($self->{title});
}
if ( $self->{label} )
{
$self->{gdta_label}->set(colour => $self->{lci});
$self->{gdta_label}->set_text($self->{label});
}
$self->{gdta_value}->set(colour => $self->{alci});
return $self;
}
# Put the text on the canvas.
sub draw_text
{
my $self = shift;
$self->{gdta_title}->draw($self->{xc}, $self->{t_margin})
if $self->{title};
$self->{gdta_label}->draw($self->{xc}, $self->{height} - $self->{b_margin})
if $self->{label};
return $self;
}
# draw the pie, without the data slices
sub draw_pie
{
my $self = shift;
my $left = $self->{xc} - $self->{w}/2;
$self->{graph}->arc(
$self->{xc}, $self->{yc},
$self->{w}, $self->{h},
0, 360, $self->{acci}
);
$self->{graph}->arc(
$self->{xc}, $self->{yc} + $self->{pie_height},
$self->{w}, $self->{h},
0, 180, $self->{acci}
) if ( $self->{'3d'} );
$self->{graph}->line(
$left, $self->{yc},
$left, $self->{yc} + $self->{pie_height},
$self->{acci}
);
$self->{graph}->line(
$left + $self->{w}, $self->{yc},
$left + $self->{w}, $self->{yc} + $self->{pie_height},
$self->{acci}
);
return $self;
}
# Draw the data slices
sub draw_data
{
my $self = shift;
my $total = 0;
my @values = $self->{_data}->y_values(1); # for now, only one pie..
for (@values)
{
$total += $_
}
return $self->_set_error("Pie data total is <= 0")
unless $total > 0;
my $ac = $self->{acci}; # Accent colour
my $pb = $self->{start_angle};
for (my $i = 0; $i < @values; $i++)
{
# Set the data colour
my $dc = $self->set_clr_uniq($self->pick_data_clr($i + 1));
# Set the angles of the pie slice
# Angle 0 faces down, positive angles are clockwise
# from there.
# ---
# / \
# | |
# \ | /
# ---
# 0
# $pa/$pb include the start_angle (so if start_angle
# is 90, there will be no pa/pb < 90.
my $pa = $pb;
$pb += my $slice_angle = 360 * $values[$i]/$total;
# Calculate the end points of the lines at the boundaries of
# the pie slice
my ($xe, $ye) = cartesian(
$self->{w}/2, $pa,
$self->{xc}, $self->{yc}, $self->{h}/$self->{w}
);
$self->{graph}->line($self->{xc}, $self->{yc}, $xe, $ye, $ac);
# Draw the lines on the front of the pie
$self->{graph}->line($xe, $ye, $xe, $ye + $self->{pie_height}, $ac)
if in_front($pa) && $self->{'3d'};
# Make an estimate of a point in the middle of the pie slice
# And fill it
($xe, $ye) = cartesian(
3 * $self->{w}/8, ($pa+$pb)/2,
$self->{xc}, $self->{yc}, $self->{h}/$self->{w}
);
$self->{graph}->fillToBorder($xe, $ye, $ac, $dc);
# If it's 3d, colour the front ones as well
#
# if one slice is very large (>180 deg) then we will need to
# fill it twice. sbonds.
#
# Independently noted and fixed by Jeremy Wadsack, in a slightly
# different way.
if ($self->{'3d'})
{
foreach my $fill ($self->_get_pie_front_coords($pa, $pb))
{
my ($fx,$fy) = @$fill;
my $new_y = $fy + $self->{pie_height}/2;
# Edge case (literally): if lines have converged, back up
# looking for a gap to fill
while ( $new_y > $fy ) {
if ($self->{graph}->getPixel($fx,$new_y) != $ac) {
$self->{graph}->fillToBorder($fx, $new_y, $ac, $dc);
last;
}
} continue { $new_y-- }
}
}
}
# CONTRIB Jeremy Wadsack
#
# Large text, sticking out over the pie edge, could cause 3D pies to
# fill improperly: Drawing the text for a given slice before the
# next slice was drawn and filled could make the slice boundary
# disappear, causing the fill colour to flow out. With this
# implementation, all the text is on top of the pie.
$pb = $self->{start_angle};
for (my $i = 0; $i < @values; $i++)
{
next unless $values[$i];
my $pa = $pb;
$pb += my $slice_angle = 360 * $values[$i]/$total;
next if $slice_angle <= $self->{suppress_angle};
my ($xe, $ye) =
cartesian(
3 * $self->{w}/8, ($pa+$pb)/2,
$self->{xc}, $self->{yc}, $self->{h}/$self->{w}
);
$self->put_slice_label($xe, $ye, $self->{_data}->get_x($i));
}
return $self;
} #GD::Graph::pie::draw_data
sub _get_pie_front_coords # (angle 1, angle 2)
{
my $self = shift;
my $pa = level_angle(shift);
my $pb = level_angle(shift);
my @fills = ();
if (in_front($pa))
{
if (in_front($pb))
{
# both in front
# don't do anything
# Ah, but if this wraps all the way around the back
# then both pieces of the front need to be filled.
# sbonds.
if ($pa > $pb )
{
# This takes care of the left bit on the front
# Since we know exactly where we are, and in which
# direction this works, we can just get the coordinates
# for $pa.
my ($x, $y) = cartesian(
$self->{w}/2, $pa,
$self->{xc}, $self->{yc}, $self->{h}/$self->{w}
);
# and move one pixel to the left, but only if we don't
# fall out of the pie!.
push @fills, [$x - 1, $y]
if $x - 1 > $self->{xc} - $self->{w}/2;
# Reset $pa to the right edge of the front arc, to do
# the right bit on the front.
$pa = level_angle(-$ANGLE_OFFSET);
}
}
else
{
# start in front, end in back
$pb = $ANGLE_OFFSET;
}
}
else
{
if (in_front($pb))
{
# start in back, end in front
$pa = $ANGLE_OFFSET - 180;
}
elsif ( # both in back, but wrapping around the front
# CONTRIB kedlubnowski, Dan Rosendorf
$pa > 90 && $pb > 90 && $pa >= $pb
or $pa < -90 && $pb < -90 && $pa >= $pb
or $pa < -90 && $pb > 90
)
{
$pa=$ANGLE_OFFSET - 180;
$pb=$ANGLE_OFFSET;
}
else
{
return;
}
}
my ($x, $y) = cartesian(
$self->{w}/2, ($pa + $pb)/2,
$self->{xc}, $self->{yc}, $self->{h}/$self->{w}
);
push @fills, [$x, $y];
return @fills;
}
# return true if this angle is on the front of the pie
# XXX UGLY! We need to leave a slight room for error because of rounding
# problems
sub in_front
{
my $a = level_angle(shift);
return
$a > ($ANGLE_OFFSET - 180 + 0.00000001) &&
$a < $ANGLE_OFFSET - 0.000000001;
}
# XXX Ugh! I need to fix this. See the GD::Text module for better ways
# of doing this.
# return a value for angle between -180 and 180
sub level_angle # (angle)
{
my $a = shift;
return level_angle($a-360) if ( $a > 180 );
return level_angle($a+360) if ( $a <= -180 );
return $a;
}
# put the slice label on the pie
sub put_slice_label
{
my $self = shift;
my ($x, $y, $label) = @_;
return unless defined $label;
$self->{gdta_value}->set_text($label);
$self->{gdta_value}->draw($x, $y);
}
# return x, y coordinates from input
# radius, angle, center x and y and a scaling factor (height/width)
#
# $ANGLE_OFFSET is used to define where 0 is meant to be
sub cartesian
{
my ($r, $phi, $xi, $yi, $cr) = @_;
return map _round($_), (
$xi + $r * cos(PI * ($phi + $ANGLE_OFFSET)/180),
$yi + $cr * $r * sin(PI * ($phi + $ANGLE_OFFSET)/180)
)
}
"Just another true value";
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/GD/Graph/pie.pm | Perl | mit | 12,905 |
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Question rules
%
% Version: 1.0.1
% Last modified: 02/08/04
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- multifile best_parse_cats/1, rule/2.
:- dynamic best_parse_cats/1, rule/2.
% Best Parse Categories
best_parse_cats([s,sbar,sinv,q,relc,nfvp,fvp,whnp,whpp,howadjp,np,pp]).
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Question Prefix
% -- ensures relc rules not fired at beginning of question
% -- note * question * can throw off taggers -- WP's may
% become NN as no longer at start of sentence, so
% capitalisation may imply unknown words -- robotag has
% been modifed to avoid this
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
rule(q(sem: QSem),
[sym(s_form:'*'),
n(m_root:'question'),
sym(s_form:'*'),
q(sem: QSem)
]).
rule(q(sem: QSem),
[n(m_root:'*'),
n(m_root:'question'),
n(m_root:'*'),
q(sem: QSem)
]).
% REMOVED: causes weird ordering effects in embedded
% rule application
%rule(q(sem: QVar^E^[QSem,ASem,[rule,q1]]),
% [qbody(sem: QVar^E^QSem),
% adjuncts(sem:ASem),
% sym(s_form:'?')]).
%rule(q(sem: QVar^E^[QSem,ASem,PPSem,[rule,q2]]),
% [qbody(sem: QVar^E^QSem), pp(sem:PPSem)]).
% sym(s_form:'?')]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Questions
% WHO questions
% WHAT questions
% WHNP questions
% WHPP questions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%
%% WHO QUESTIONS
%%%%%%%%%%%%%%%%
% Who1
%% Who1: Q -> WP FVP(active|passive)
% "Who built the Eiffel Tower?"
rule(q(sem: QVar^E^[[qvar,QVar],[qattr,QVar,name],[person,QVar],[lsubj,E,QVar],
VPSem,[qcon,E,verb],[rule,who1a]]),
[wp(m_root:'who'),
fvp(voice:active,sem:E^VPSem)
]).
% "Who was eaten by the tiger?"
rule(q(sem: QVar^E^[[qvar,QVar],[qattr,QVar,name],[person,QVar],[lobj,E,QVar],
VPSem,[qcon,E,verb],[rule,who1b]]),
[wp(m_root:'who'),
fvp(voice:passive,sem:E^VPSem)
]).
% Who2
%% Who2: Q -> WP(who) VPCORE(be) NP
% "Who was the President of Turkmenistan in 1994?"
rule(q(sem: QVar^E^[[qvar, QVar],[qattr,QVar,name],[person,QVar],[lsubj,E,QVar],
VPSem, NPSem, ASem,[rule,who2]]),
[wp(m_root:'who'),
vpcore(m_root:'be',sem:E^VPSem),
np(sem:QVar^NPSem)
]).
% Who3
%% Who3: Q -> WP(who/whom) SINV
% "Who(m) did John disobey?"
rule(q(sem: QVar^E^[[qvar, QVar],[qattr,QVar,name],[person,QVar],
[lobj, E, QVar], SinvSem,[qcon,E,verb],[rule,who3]]),
[wp(m_root:'who'),
sinv(voice:active, sem:E^SinvSem)
]).
rule(q(sem: QVar^E^[[qvar, QVar],[qattr,QVar,name],[person,QVar],
[lobj, E, QVar], SinvSem,[qcon,E,verb],[rule,who3]]),
[wp(m_root:'whom'),
sinv(voice:active, sem:E^SinvSem)
]).
%%%%%%%%%%%%%%%%%
%% WHAT QUESTIONS
%%%%%%%%%%%%%%%%%
% WHAT1
%% What1: Q -> WP(what) FVP (active|passive)
% "What was eating/was eaten by John?"
rule(q(sem: QVar^E^[[qvar, QVar],[lsubj, E, QVar], VPSem,[rule,what1a]]),
[wp(m_root:'what'),
fvp(voice:active, sem:E^VPSem)
]).
rule(q(sem: QVar^E^[[qvar, QVar],[lobj, E, QVar], VPSem,
[qcon,E,verb],[rule,what1b]]),
[wp(m_root:'what'),
fvp(voice:passive, sem:E^VPSem)
]).
% WHAT2
%% What2: Q -> WP(what) VPCORE(be) NP ?
% "What is the capital of Uganda?"
rule(q(sem: QVar^E^[[qvar, QVar],[lsubj,E,QVar],
VPSem,NP2Sem,ASem,[rule,what2]]),
[wp(m_root:'what'),
vpcore(m_root:'be',sem:E^VPSem),
np(sem:QVar^NP2Sem)
]).
% WHAT3
%% What3: Q -> WP(what) SINV
% "What did John eat?"
rule(q(sem: QVar^E^[[qvar, QVar],[lobj, E, QVar], SinvSem,
[qcon,E,verb],[rule,what3]]),
[wp(m_root:'what'),
sinv(voice:active, sem:E^SinvSem)
]).
% WHAT4
%% WHAT4: Q -> WP(what) VPCORE(be) DT N(name|term) IN(of|for) NP
% What is the name of Whistler's mother?
rule(q(sem: QVar^E^[[qvar, QVar],[qattr,QVar,name],VPSem,NPSem,[rule,what4]]),
[wp(m_root:'what'),
vpcore(m_root:'be',sem:E^VPSem),
dt(m_root:D),
[n(m_root:'name'),
n(m_root:'term')],
[in(m_root:'of'),
in(m_root:'for')],
np(sem:NPSem)
]).
% WHAT5
%% WHAT5: Q -> WP(what) VPCORE(be) DT N(capital) IN(of) NP
% What is the capital of Uganda?
rule(q(sem: QVar^E^CapEnt^[[qvar, QVar],[qattr,QVar,name],
[capital,CapEnt],[city,QVar],VPSem,NPSem,[rule,what5]]),
[wp(m_root:'what'),
vpcore(m_root:'be',sem:E^VPSem),
dt(m_root:D),
n(m_root:'capital'),
in(m_root:'of'),
np(sem:NPSem)
]).
% WHAT6
%% WHAT6: Q -> WP(what) VPCORE(be) NP VPCORE
% What are pennies made of?
% What are baby frogs called
rule(q(sem: QVar^E^NP^[[qvar, QVar],[lobj,E,NP],VSem,NPSem,[rule,what6]]),
[wp(m_root:'what'),
v(m_root:'be'),
np(sem:NP^NPSem),
vpcore(vform:nform,sem:E^VSem)
]).
% WHAT6
%% WHAT6: Q -> WP(what) VPCORE(be) NP VPCORE P
% What is tequila made from?
rule(q(sem: QVar^E^NP^[[qvar, QVar],[lobj,E,NP],[P,E,QVar],VSem,NPSem,[rule,what7]]),
[wp(m_root:'what'),
v(m_root:'be'),
np(sem:NP^NPSem),
vpcore(vform:nform,sem:E^VSem),
in(m_root:P)
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% WHNP QUESTIONS: What/which/how many/how much/ X
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WHNPQ0
%% WhNP0: Q -> WHNP
% Default
rule(q(sem: [WHNPSem]),
[whnp(sem:WHNPSem)
]).
% WHNPQ1
%% WhHPQ1: Q -> WHNP FVP(active|passive)
% "What|which car consumes the least petrol?"
% This also works for how much/how many, etc.
rule(q(sem: QVar^E^[[lsubj,E,QVar],NPSem,VPSem,[qcon,E,verb],[rule,whnpq1a]]),
[whnp(sem:QVar^NPSem),
fvp(sem:E^VPSem,voice:active)
]).
rule(q(sem: QVar^E^[[lobj,E,QVar],NPSem,VPSem,[qcon,E,verb],[rule,whnpq1b]]),
[whnp(sem:QVar^NPSem),
fvp(sem:E^VPSem,voice:passive)
]).
% WHNPQ2
%% WhNPQ2: Q -> WHNP VPCORE(be) NP ?
% "[What|which city] is the capital of Uganda?"
rule(q(sem: QVar^E^[[lsubj,E,QVar],
NP1Sem,VPSem,NP2Sem,[rule,whnpq2]]),
[whnp(sem:QVar^NP1Sem),
vpcore(m_root:'be',sem:E^VPSem),
np(sem:QVar^NP2Sem)
]).
% WHNPQ3
%% WhNPQ3: Q -> WHNP SINV
% "What food did John eat?"
rule(q(sem: QVar^E^[[lobj, E, QVar], NPSem, SinvSem,
[qcon,E,verb],[rule,whnpq3]]),
[whnp(sem:QVar^NPSem),
sinv(voice:active, sem:E^SinvSem)
]).
% WHNPQ4
%% WhNPQ4: Q -> WHNP(head="year"|"date") SINV(active)
% "What year did Columbus discover America?"
rule(q(sem: QVar^E^[NPSem, SinvSem,[qcon,E,verb],[rule,whnpq4]]),
[[whnp(s_form:'year',sem:QVar^NPSem),whnp(s_form:'date',sem:QVar^NPSem)],
sinv(voice:active, sem:E^SinvSem)
]).
% WHNPQ5
%% WhNPQ5: Q -> WHNP(head="year") SINV(passive)
% "What year was the Magna Carta signed ?
rule(q(sem: QVar^E^[[in, E, QVar], NPSem, SinvSem,[qcon,E,verb],[rule,whnpq5]]),
[whnp(s_form:'year',sem:QVar^NPSem),
sinv(voice: passive,sem:E^SinvSem)
]).
% WHNPQ6
%% WHNPPQ6: WHNP -> WP|WDT POSS BNP_CORE
% What fruit's stone does Laetrile come from?
rule(q(sem:QVar^N^E^[[qvar, QVar],[lobj,E,N],[realisation,E,Edge],
PossNSem,NSem,SinvSem,[rule,whnpq6]]),
[[wp(m_root:'what'),wdt(m_root:'which')],
poss(sem:N^QVar^PossNSem),
bnp_core(sem:N^NSem,number:Num,s_form:S),
sinv(voice:active,sem:E^SinvSem)
]).
%%%%%%%%%%%%%%%%%%
%% WHPP QUESTIONS
%%%%%%%%%%%%%%%%%%
% WHPPQ0
%% WhPPQ0: Q -> WHPP
% Default
rule(q(sem: [WHPPSem,[rule,whppq0]]),
[whpp(sem:WHPPSem)
]).
% WHPPQ1
%% WhPPQ1: Q -> WHPP SINV
% At what age did Rossini stop writing opera?
rule(q(sem: QVar^E^Agent^[PPSem,SinvSem,[qcon,E,verb],[rule,whppq1]]),
[whpp(sem:QVar^E^PPSem),
sinv(sem:E^Agent^SinvSem)
]).
%%%%%%%%%%%%%%%%%%
%% WHERE QUESTIONS
%%%%%%%%%%%%%%%%%%
% Where0
%% Where0: Q -> WRB(where)
% Default
rule(se(sem:QVar^[[qvar,QVar],[qattr,QVar,name],[location,QVar],[rule,where0]]),
[wrb(m_root:'where')
]).
% Where1
%% Where1: Q -> WRB(where) VPCORE(be) NP
% "Where is Bolivia?"
rule(q(sem: QVar^E^X^[[qvar, QVar],[qattr,QVar,name],[location, QVar],
[in, X, QVar], VPSem,NPSem,[rule,where1]]),
[wrb(m_root:'where'),
vpcore(m_root:'be',sem:E^VPSem),
np(sem:X^NPSem)
]).
% Where2
%% Where2: Q -> WRB(where) SINV
% "Where did Dylan Thomas die?"
rule(q(sem: QVar^E^[[qvar, QVar],[qattr,QVar,name],[location, QVar],
[qcon,E,verb], SinvSem,[rule,where2]]),
[wrb(m_root:'where'),
sinv(sem:E^SinvSem)
]).
%%%%%%%%%%%%%%%%%
%% WHEN QUESTIONS
%%%%%%%%%%%%%%%%%
% When0
%% When0: Q -> WRB(when)
% Default
rule(q(sem:QVar^[[qvar,QVar],[qattr,QVar,name],[date,QVar],[rule,when0]]),
[wrb(m_root:'when')
]).
% When1
%% When1: Q -> WRB(when) VPCORE NP
% "When is Christmas?
rule(q(sem: QVar^E^X^[[qvar, QVar],[qattr,QVar,name],[date, QVar],
[on, X, QVar],VPSem,NPSem,[rule,when1]]),
[wrb(m_root:'when'),
vpcore(m_root:'be',sem:E^VPSem),
np(sem:X^NPSem)
]).
% When2
%% When2: Q -> WRB(when) SINV
% "When did Nelson Mandela become President?"
rule(q(sem: QVar^E^[[qvar, QVar],[qattr,QVar,name],[date, QVar],
[in, E, QVar],[qcon,E,verb],SinvSem,[rule,when2]]),
[wrb(m_root:'when'),
sinv(sem:E^SinvSem)
]).
%%%%%%%%%%%%%%%%%
%% HOW QUESTIONS
%%%%%%%%%%%%%%%%%
% How1
%% How1: Q -> WRB(how) SINV
% "How did Socrates die" = Socrates died by ___
rule(q(sem: QVar^E^[[qvar,QVar],[qcon,E,verb],SinvSem,[rule,how1]]),
[wrb(m_root:'how'),
sinv(sem:E^SinvSem)
]).
% How2a
%% How2a: Q -> WRB(how) RB SINV
% "How often is someone murdered in the US
% default for adverbs
rule(q(sem: QVar^E^[[qvar,QVar],[qcon,E,verb],SinvSem,[rule,how2a]]),
[wrb(m_root:'how'),
rb(m_root: RB),
sinv(sem:E^SinvSem)
]).
% How2b
%% How2b: Q -> HOWADVP SINV
% "How fast/quickly can a nuclear submarine travel?
rule(q(sem: QVar^E^[[qvar,QVar],[qcon,E,verb],HowAdvpSem,SinvSem,[rule,how2b]]),
[howadvp(sem:QVar^HowAdvpSem),
sinv(sem:E^SinvSem)
]).
% How2b
%% How2b: Q -> HOWADVP SINV
% "How fast/quickly can a nuclear submarine travel?
rule(q(sem: QVar^E^[[qvar,QVar],[qcon,E,verb],HowAdvpSem,SinvSem,[rule,how2b1]]),
[howadjp(sem:QVar^HowAdvpSem),
fvp(sem:E^SinvSem)
]).
% How2c
%% How2c: Q -> HOWADJP SINV
% "How big does a pig get?
rule(q(sem: QVar^E^[[qvar,QVar],[qcon,E,verb],HowAdjpSem,SinvSem,[rule,how2c]]),
[howadjp(sem:QVar^HowAdjpSem),
sinv(sem:E^SinvSem)
]).
% How3a
%% How3a: Q -> HOW JJ(miscellaneous -- not handled by HOWADJP) VPCORE(be) NP
% "How accurate are HIV tests
% NB: Last rule in source file which matches is preferred
rule(q(sem: QVar^X^[[qual,QVar,X],[adj,X,JJ],NPSem,[rule,how3a]]),
[wrb(m_root:'how'),
jj(m_root:JJ),
vpcore(m_root:'be',sem:_),
np(sem:X^NPSem)
]).
% How3b
%% How3b: Q -> HOWADJP VPCORE(be) NP
% "How tall is the Statue of Liberty?"
% NB: Last rule in source file which matches is preferred
rule(q(sem: QVar^X^[[qvar,QVar],[qual,QVar,X],NPSem,HowAdjpSem,[rule,how3b]]),
[howadjp(sem:QVar^HowAdjpSem),
vpcore(m_root:'be',sem:_),
np(sem:X^NPSem)
]).
% How4
%% How4: Q -> HOWADVP VPCORE(be) NP
% "How fast is an eye blink?"
rule(q(sem: QVar^X^[[qual,QVar,X],NPSem,HowAdvpSem,[rule,how4]]),
[howadvp(sem:QVar^HowAdvpSem),
vpcore(m_root:'be',sem:_),
np(sem:X^NPSem)
]).
% How5
%% How5: Q -> WRB(how) JJ(long) VPCORE(do) PRP(it) VPCORE(take) NFVP
% "How long does it take to X"
rule(q(sem: QVar^E^[[qvar, QVar],[time,QVar],
[duration_of, E,QVar], VPSem, ASem,[rule,how5]]),
[wrb(m_root:'how'),
jj(m_root:'long'),
vpcore(m_root:'do',vform:sform),
prp(m_root:'it'),
vpcore(m_root:'take'),
nfvp(sem:E^VPSem)
]).
% How6a
%% How6a: Q -> HOWADJP(How far) VPCORE(be) NP IN(from) NP
% "How far is Yaroslavl from Moscow?
rule(q(sem: QVar^X1^X2^[NPSem1,NPSem2,HowAdjpSem,[rule,how6a]]),
[howadjp(sem:QVar^HowAdjpSem,s_form:'far'),
vpcore(m_root:'be',sem:_),
bnp(sem:X1^NPSem1),
in(s_form:'from'),
bnp(sem:X2^NPSem2)
]).
% How6b
%% How6b: Q -> HOWADJP(How far) VPCORE(be) PPS(it) IN(from) NP TO(to) NP
% "How far is it from Earth to Mars?
rule(q(sem: QVar^X1^X2^[NPSem1,NPSem2,HowAdjpSem,[rule,how6b]]),
[howadjp(sem:QVar^HowAdjpSem,s_form:'far'),
vpcore(m_root:'be',sem:_),
pps(s_form:'it'),
in(s_form:'from'),
bnp(sem:X1^NPSem1),
to(s_form:'to'),
bnp(sem:X2^NPSem2)
]).
% How7
%% How7: Q -> HOWADJP (how close) VPCORE(be) NP To(to) NP
% "How close is Mercury to the Sun?
rule(q(sem: QVar^X1^X2^[NPSem1,NPSem2,HowAdjpSem,[rule,how7]]),
[howadjp(sem:QVar^HowAdjpSem,s_form:'close'),
vpcore(m_root:'be',sem:_),
bnp(sem:X1^NPSem1),
to(s_form:'to'),
bnp(sem:X2^NPSem2)
]).
% How8
%% How8: Q -> WRB(how) JJ(long) IN(before|...) SBAR
% "How long before ...?
rule(q(sem: QVar^[[qvar, QVar],[measure,QVar],[measure_type,Qvar,time],
SSem, [rule,how8]]),
[wrb(m_root:'How'),
rb(m_root:'long'),
sbar(sem:QVar^SSem)]
).
%%%%%%%%%%%%%%%%
%% WHY QUESTIONS
%%%%%%%%%%%%%%%%
% Why0
%% Why0: Q -> WRB(why)
% Default
rule(q(sem:QVar^[[qvar,QVar],[rule,why0]]),
[wrb(m_root:'why')
]).
% Why1
%% Why1: Q -> WRB(why) SINV
% Why did David Koresh ask the FBI for a word processor?
rule(q(sem: QVar^E^[[qvar,QVar],SSem,[rule,why1]]),
[wrb(m_root:'why'),
sinv(sem:E^SSem)
]).
%%%%%%%%%%%%%%%%%%%%%%%%%
% Embedded WHPP QUESTIONS
%%%%%%%%%%%%%%%%%%%%%%%%%
% EWHPP1
%% EWHPP1: Q -> S WHPP
% John died/ate quiche in which Northern European country?
rule(q(sem:QVar^E^[SSem,WHPPSem,[qcon,E,verb],[rule,ewhpp1]]),
[s(sem:E^SSem),
whpp(sem:E^QVar^WHPPSem)
]).
% EWHPP2
%% EWHPP2: Q -> NP VPCORE(be) WHPP
% The Faroes are in which Northern European country?
rule(q(sem:QVar^E^X^[NPSem,VPSem,WHPPSem,[rule,ewhpp2]]),
[np(sem:X^NPSem),
vpcore(m_root:'be',sem:E^VPSem),
whpp(sem:X^QVar^WHPPSem)
]).
%%%%%%%%%%%
%% COMMANDS
%%%%%%%%%%%
% Name1
%% Name0: Q -> N(name) NP
% Default
rule(q(sem: QVar^[[qvar, QVar],[qattr,QVar,name],NPSem,[rule,name0]]),
[n(m_root:'name'),
np(sem:NPSem)
]).
% Name1
%% Name1: Q -> N(name) BNP RELC
% Name the first man who walked on the moon
% event marked as a type2 constraint
rule(q(sem: QVar^E^Agent^[[qvar,QVar],[qattr,QVar,name],NPSem,[qcon,E,verb],
RelcSem,[rule,name1]]),
[n(m_root:'name'),
bnp(sem:Agent^NPSem),
relc(sem:Agent^E^RelcSem)
]).
% Name2
%% Name2: Q -> N(name) BNP NFVP(base)
% Name the first man to walk on the moon
% event marked as a type2 constraint
rule(q(sem: QVar^E^Agent^[[qvar,QVar],[qattr,QVar,name],NPSem,[qcon,E,verb],
InfSem,[rule,name2]]),
[n(m_root:'name'),
bnp(sem:Agent^NPSem),
nfvp(vform:base,sem:E^InfSem)
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SINV Rules
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%rule(q(sem:SinvSem),
% [sinv(sem:SinvSem)
%]).
%% SINV -> V (do|will) NP AV ?
% Did/Will John die?
rule(sinv(voice:active,sem:Event^Agent^X^[NPSem,[R,Event],VSem,[time, Event,T],
[lsubj,Event,Agent],ASem,PPSem,[rule,sinv1]]),
[ [v(m_root:'do',tense:T,vform:F,number:N,person:P),
md(_)],
np(person:P,number:N,sem:Agent^NPSem),
vpcore(m_root:R,vform:base,sem:Event^VSem),
{[adjuncts(sem:ASem),pp(sem:Event^X^PPSem)]}
% sym(s_form:'?')
]).
%% SINV -> V (do|will) NP AV NP ?
% Did/Will John eat the elephant?
rule(sinv(voice:active, sem:Event^Agent^Obj^[NPSem,[R,Event],VSem,[time,Event,T],NP2Sem,
[lsubj,Event,Agent],[lobj,Event,Obj],ASem,[rule,sinv2]]),
[ [v(m_root:'do',tense:T,vform:F, number:N,person:P),
md(s_form:_)],
np(person:P,number:N,sem:Agent^NPSem),
vpcore(m_root:R,vform:base,sem:Event^VSem),
np(sem:Obj^NP2Sem),
{adjuncts(sem:ASem)}
% sym(s_form:'?')
]).
%% SINV -> V (do|will) NP AV ?
% Was the Magna Carta signed ?
rule(sinv(voice:passive,sem:Event^Patient^X^[NPSem,[R,Event],ASem,[time, Event,T],
[lobj,Event,Patient],PPSem,[rule,sinv3]]),
[ v(m_root:'be',tense:T,vform:F,number:N,person:P),
np(person:P,number:N,sem:Patient^NPSem),
[vpcore(m_root:R,vform:nform,sem:Event^ASem),
vpcore(m_root:R,vform:dform,sem:Event^ASem)], % dform for bad tagging
{[adjuncts(sem:ASem),pp(sem:Event^X^PPSem)]}
% sym(s_form:'?')
]).
%% SINV -> V (be) NP?
% is the River Seine?
rule(sinv(voice:passive,sem:Agent^Verb^[NPSem,[time,Verb,T],[lsubj,Verb,Agent],[be,Verb],
[rule,sinv3b]]),
[ v(m_root:'be',tense:T,vform:F,number:N,person:P),
np(person:P,number:N,sem:Agent^NPSem)
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WHNP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WHNP1
%% WHNP1: WHNP -> WP|WDT BNP_CORE
% what|which city
% which city in Nevada
rule(whnp(sem:QVar^[H,[qvar, QVar],[realisation,E,Edge],
PPSem,[rule,whnp1]],number:N,s_form:S,edge:Edge),
[[wp(m_root:'what'), wdt(m_root:'which')],
bnp_core(sem:QVar^H,number:N,s_form:S),
{pp(sem:QVar^PPSem)}
]).
% WHNP2
%% WHNP2: WHNP -> WRB(how) JJ (many) BNP_CORE {PP}
% how many inches
% how many cities in Nevada
rule(whnp(sem:QVar^[[qvar,QVar],[qattr,QVar,count],[realisation,QVar,Edge],
H,PPSem,[rule,whnp2]]),
[wrb(m_root:'how'),
jj(m_root:'many'),
bnp_core(sem:QVar^H),
{pp(sem:QVar^PPSem)}
]).
% WHNP3
%% WHNP3: WHNP -> WRB(how) JJ (many) PP
% how many of the gold medallists
rule(whnp(sem:QVar^[[qvar,QVar],[qattr,QVar,count],[realisation,QVar,Edge],
H,E^Qvar^PPSem,[rule,whnp3]]),
[wrb(m_root:'how'),
jj(m_root:'many'),
pp(sem:E^QVar^PPSem)
]).
% WHNP4
%% WHNP4: WHNP -> WRB(how) JJ(much) | RB(much)
% Ask for a quantity
% how much (assume "how much" on its own is money)
rule(whnp(sem:QVar^[[qvar, QVar],[money,QVar],[qattr,QVar,name],
[realisation,QVar,Edge],[rule,whnp4]]),
[wrb(m_root:'how'),
[jj(m_root:'much'),rb(m_root:'much')]
]).
% WHNP5
%% WHNP5: WHNP -> WRB(how) JJ(much) | RB(much) BNP_CORE {PP}
% Ask for a quantity
% how much butter
rule(whnp(sem:QVar^[[qvar, QVar],[realisation,QVar,Edge],[qattr,QVar,count],
H,PPSem,[rule,whnp5]]),
[wrb(m_root:'how'),
[jj(m_root:'much'),rb(m_root:'much')],
bnp_core(sem:QVar^H),
{pp(sem:QVar^PPSem)}
]).
% WHNP6
%% WHNP6: WHNP -> WRB(how) JJ(much) | RB(much) BNP_CORE {PP}
% Ask for a quantity
% how much butter
rule(whnp(sem:QVar^[[qvar, QVar],[realisation,QVar,Edge],[qattr,QVar,count],
H,PPSem,[rule,whnp6]]),
[wrb(m_root:'how'),
[jj(m_root:'much'),rb(m_root:'much')],
bnp_core(sem:QVar^H),
{pp(sem:QVar^PPSem)}
]).
% WHNP7
%% WHNP7: WHNP -> WRB(What) BNP_CORE(day|month|year)
% Ask for a date
% What day did Pearl Harbor occur?
rule(whnp(sem:QVar^[[qvar, QVar],[realisation,QVar,Edge],[qattr,QVar,name],
[date,QVar],[rule,whnp7]]),
[[wp(m_root:'what'), wdt(m_root:'which')],
[n(m_root:'day'),n(m_root:'month'),n(m_root:'year')]
]).
% WHNP8
%% WHNP8: WHNP -> WRB(What)
% Ask for a date
% What day and month did Nixon resign
rule(whnp(sem:QVar^[[qvar, QVar],[realisation,QVar,Edge],[qattr,QVar,name],
[date,QVar],[rule,whnp7b]]),
[[wp(m_root:'what'), wdt(m_root:'which')],
[bnp_core(m_root:'day'),bnp_core(m_root:'month'),bnp_core(m_root:'year')],
cc(_), [bnp_core(m_root:'day'),bnp_core(m_root:'month'),bnp_core(m_root:'year')]
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WHPP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% WHPP1
%% WHPP1: WHPP -> IN WHNP
% At what age
% In which city in Nevada
rule(whpp(sem:E^QVar^[[R,E,QVar],WHNPSem,[realisation,E,Edge],[rule,whpp1]]),
[in(m_root:R),
whnp(sem:QVar^WHNPSem)
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HOWADJP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HOWADJP1a
%% HOWADJP1a: HOWADJP -> WRB(how) JJ(far|wide|near|close|wide|tall|high|large|big|small|huge
% How tall is the Statue of Liberty?
rule(howadjp(sem:QVar^[[qvar, QVar],[qattr,QVar,count],[qattr,QVar,unit],
[measure,QVar],[measure_type,QVar,distance],[realisation,QVar,Edge],[rule,howadjp1a]],s_form:S),
[wrb(m_root:'how'),
[jj(m_root:'far',s_form:S),rb(m_root:'far',s_form:S),jj(m_root:'near',s_form:S),jj(m_root:'close',s_form:S),v(m_root:'close',s_form:S),
jj(m_root:'long',s_form:S),jj(m_root:'wide',s_form:S),jj(m_root:'tall',s_form:S),jj(m_root:'high',s_form:S),n(m_root:'high',s_form:S),
jj(m_root:'large',s_form:S),jj(m_root:'big',s_form:S),jj(m_root:'small',s_form:S),jj(m_root:'huge',s_form:S)]
]).
% HOWADJP1b
%% HOWADJP1b: HOWADJP -> WRB(how) JJ(far|wide|near|close|wide|tall|high|large|big|small|huge
% How tall in feet is the Statue of Liberty?
% Units not handled properly
rule(howadjp(sem:QVar^X^[[qvar, QVar],[qattr,QVar,count],
[measure,QVar],[measure_type,QVar,distance],PNPSem,[realisation,QVar,Edge],[rule,howadjp1b]],s_form:S),
[wrb(m_root:'how'),
[jj(m_root:'far',s_form:S),rb(m_root:'far',s_form:S),jj(m_root:'near',s_form:S),jj(m_root:'close',s_form:S),v(m_root:'close',s_form:S),
jj(m_root:'long',s_form:S),jj(m_root:'wide',s_form:S),jj(m_root:'tall',s_form:S),jj(m_root:'high',s_form:S),n(m_root:'high',s_form:S),
jj(m_root:'large',s_form:S),jj(m_root:'big',s_form:S),jj(m_root:'small',s_form:S),jj(m_root:'huge',s_form:S)],
in(m_root:in),
bnp(sem:X^PNPSem)
]).
% HOWADJP2
%% HOWADJP2: HOWADJP -> WRB(how) JJ(heavy|massive)
% How heavy is the Statue of Liberty?
rule(howadjp(sem:QVar^[[qvar, QVar],[qattr,QVar,count], [qattr,QVar,unit],
[measure,QVar],[measure_type,QVar,mass],[realisation,QVar,Edge],[rule,howadjp2]]),
[wrb(m_root:'how'),
[jj(m_root:'heavy'),jj(m_root:'massive')]
]).
% HOWADJP3
%% HOWADJP3: HOWADJP -> WRB(how) JJ(late)
% How late is Disneyland open?
rule(howadjp(sem:QVar^[[qvar, QVar],
[date,QVar],[realisation,QVar,Edge],[rule,howadjp3]]),
[wrb(m_root:'how'),
jj(m_root:'late')
]).
% HOWADJP4
%% HOWADJP4: HOWADJP -> WRB(how) JJ(fast)
% How fast can a nuclear submarine travel?
rule(howadjp(sem:QVar^[[qvar, QVar],[qattr,QVar,count],[qattr,QVar,unit],
[measure,QVar],[measure_type,QVar,speed],[realisation,QVar,Edge],[rule,howadjp4]]),
[wrb(m_root:'how'),
jj(m_root:'fast')
]).
% HOWADJP5
%% HOWADJP5: HOWADJP -> WRB(how) JJ(hot|cold)| N(cold)
% How hot/cold/ is the sun?
rule(howadjp(sem:QVar^[[qvar, QVar],[qattr,QVar,count],[qattr,QVar,unit],
[measure,QVar],[measure_type,QVar,temp],[realisation,QVar,Edge],[rule,howadjp5]]),
[wrb(m_root:'how'),
[jj(m_root:'hot'), jj(m_root:'cold'),n(m_root:'cold')]
]).
% HOWADJP6
%% HOWADJP6: HOWADJP -> WRB(how) JJ(old)
% How old is the Red Pyramid?
rule(howadjp(sem:QVar^[[qvar, QVar],[qattr,QVar,count],[qattr,QVar,unit],
[measure,QVar],[measure_type,QVar,age],[realisation,QVar,Edge],[rule,howadjp6]]),
[[wrb(m_root:'how'),wrb(m_root:'How')],
jj(m_root:'old')
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HOWADVP
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% HOWADVP1
%% HOWADVP1: HOWADVP -> WRB(how) JJ(fast)|RB(quickly)
% How fast can a nuclear submarine travel?
rule(howadvp(sem:QVar^[[qvar, QVar],[qattr,QVar,count],[qattr,QVar,unit],
[measure,QVar],[measure_type,QVar,speed],[realisation,QVar,Edge],[rule,howadvp1]]),
[wrb(m_root:'how'),
[rb(m_root:'fast'),rb(m_root:'quickly')]
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Adjuncts
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% to New York
rule(adjuncts(sem:[PPSem]),
[pp(sem:PPSem)
]).
% To New York in a Concorde
rule(adjuncts(sem:[PP1Sem,PP2Sem]),
[pp(sem:PP1Sem),
pp(sem:PP2Sem)
]).
% when Columbus landed in 1492
rule(adjuncts(sem:[SBarSem]),
[sbar(sem:SBarSem)
]).
% to set foot
%rule(adjuncts(sem:[NFVPSem]),
% [nfvp(sem:NFVPSem)
%]).
% to set foot on the moon
%rule(adjuncts(sem:[NFVPSem,PPSem]),
% [nfvp(sem:NFVPSem),
% pp(sem:PPSem)
%]).
| Network-of-BioThings/GettinCRAFTy | src/main/resources/gate/plugins/Parser_SUPPLE/prolog/grammar/q_rules.pl | Perl | apache-2.0 | 24,066 |
#-----------------------------------------------------------
# vncviewer
#
#
# History:
# 20121231 - Updated to include VNCViewer4
# 20080325 - created
#
#
#
#-----------------------------------------------------------
package vncviewer;
use strict;
my %config = (hive => "NTUSER\.DAT",
hasShortDescr => 1,
hasDescr => 0,
hasRefs => 0,
osmask => 22,
version => 20121231);
sub getConfig{return %config}
sub getShortDescr {
return "Get VNCViewer system list";
}
sub getDescr{}
sub getRefs {}
sub getHive {return $config{hive};}
sub getVersion {return $config{version};}
my $VERSION = getVersion();
sub pluginmain {
my $class = shift;
my $hive = shift;
::logMsg("Launching vncviewer v.".$VERSION);
::rptMsg("vncviewer v.".$VERSION); # banner
::rptMsg("(".getHive().") ".getShortDescr()."\n"); # banner
my $reg = Parse::Win32Registry->new($hive);
my $root_key = $reg->get_root_key;
my $key_path = "Software\\ORL\\VNCviewer\\MRU";
my $key;
if ($key = $root_key->get_subkey($key_path)) {
::rptMsg("VNCViewer\\MRU");
::rptMsg($key_path);
::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)");
my @vals = $key->get_list_of_values();
if (scalar(@vals) > 0) {
my %vnc;
foreach my $v (@vals) {
$vnc{$v->get_name()} = $v->get_data();
}
my $ind;
if (exists $vnc{'index'}) {
$ind = $vnc{'index'};
delete $vnc{'index'};
}
::rptMsg("Index = ".$ind);
my @i = split(//,$ind);
foreach my $i (@i) {
::rptMsg(" ".$i." -> ".$vnc{$i});
}
::rptMsg("");
}
else {
::rptMsg($key_path." has no values.");
}
}
else {
::rptMsg($key_path." not found.");
}
$key_path = "Software\\RealVNC\\VNCViewer4\\MRU";
if ($key = $root_key->get_subkey($key_path)) {
::rptMsg($key_path);
::rptMsg("LastWrite Time ".gmtime($key->get_timestamp())." (UTC)");
my @vals = $key->get_list_of_values();
if (scalar(@vals) > 0) {
foreach my $v (@vals) {
my $name = $v->get_name();
my $type = $v->get_type();
my $data;
if ($type == 3) {
$data = $v->get_data_as_string();
}
else {
$data = $v->get_data();
}
::rptMsg(sprintf "%-8s %-25s",$name,$data);
}
}
else {
::rptMsg($key_path." has no values.");
}
}
else {
::rptMsg($key_path." not found.");
}
}
1;
| millmanorama/autopsy | thirdparty/rr-full/plugins/vncviewer.pl | Perl | apache-2.0 | 2,421 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
0800 083F
END
| liuyangning/WX_web | xampp/perl/lib/unicore/lib/Blk/Samarita.pl | Perl | mit | 421 |
use strict;
use warnings;
package Test::Reporter::Transport::File;
use base 'Test::Reporter::Transport';
use vars qw/$VERSION/;
$VERSION = '1.4002';
$VERSION = eval $VERSION;
sub new {
my ($class, $dir) = @_;
die "target directory '$dir' doesn't exist or can't be written to"
unless -d $dir && -w $dir;
return bless { dir => $dir } => $class;
}
sub send {
my ($self, $report) = @_;
$report->dir( $self->{dir} );
return $report->write();
}
1;
__END__
=head1 NAME
Test::Reporter::Transport::File - File transport for Test::Reporter
=head1 SYNOPSIS
my $report = Test::Reporter->new(
transport => 'File',
transport_args => [ $dir ],
);
=head1 DESCRIPTION
This module saves a Test::Reporter report to the specified directory (using
the C<write> method from Test::Reporter.
This lets you save reports during offline operation. The files may later be
uploaded using C<< Test::Reporter->read() >>.
Test::Reporter->read( $file )->send();
=head1 USAGE
See L<Test::Reporter> and L<Test::Reporter::Transport> for general usage
information.
=head2 Transport Arguments
$report->transport_args( $dir );
This transport class must have a writeable directory as its argument.
=head1 METHODS
These methods are only for internal use by Test::Reporter.
=head2 new
my $sender = Test::Reporter::Transport::File->new( $dir );
The C<new> method is the object constructor.
=head2 send
$sender->send( $report );
The C<send> method transmits the report.
=head1 AUTHOR
=over
=item *
David A. Golden (DAGOLDEN)
=item *
Ricardo Signes (RJBS)
=back
=head1 COPYRIGHT
Copyright (C) 2008 David A. Golden
Copyright (C) 2008 Ricardo Signes
All rights reserved.
=head1 LICENSE
This program is free software; you may redistribute it and/or modify it under
the same terms as Perl itself.
=cut
| leighpauls/k2cro4 | third_party/cygwin/lib/perl5/vendor_perl/5.10/Test/Reporter/Transport/File.pm | Perl | bsd-3-clause | 1,870 |
package DDG::Goodie::Combination;
# ABSTRACT: Compute combinations and permutations
use strict;
use DDG::Goodie;
with 'DDG::GoodieRole::NumberStyler';
zci answer_type => "combination";
zci is_cached => 1;
triggers any => "choose", "permute", "permutation", "npr", "ncr";
my $number_re = number_style_regex();
# Handle statement
handle query => sub {
my $query = $_;
return unless /^($number_re) (choose|permute|permutation|npr|ncr) ($number_re)$/i;
my $style = number_style_for($1,$3);
return unless $style; #Cannot determine number format
my $operation = lc $2;
#If contains a 'p' then it is permutation
if (index($operation, 'p') != -1) {
$operation = 'permute';
} else {
$operation = 'choose';
}
#$n choose $k
my $n = $style->for_computation($1);
my $k = $style->for_computation($3);
#Ensure both are non-negative integers
return unless $n =~ /^\d+$/ && $k =~ /^\d+$/;
#Do not try to calculate undefined combinations
return unless $n >= $k;
my $result;
if ('choose' eq $operation) {
$result = choose($n, $k);
} else { #must be permute
$result = permute($n, $k);
}
#Return no result if overflow
return if $result eq '-nan' or $result eq 'nan';
my $formatted_result = $style->for_display($result);
return $formatted_result, structured_answer => {
data => {
title => $formatted_result,
subtitle => $style->for_display($n) . " $operation " . $style->for_display($k)
},
templates => {
group => 'text'
}
};
};
#Computes the cumulative product of the numbers from $_[0] to $_[1] inclusive
#Do not call when first parameter is greater then second.
sub cumprod {
my $acc = 1;
for (my $i = $_[0]; $i <= $_[1]; $i++) {
$acc *= $i;
}
return $acc;
}
sub choose {
my ($n, $k) = @_;
#optimiztion combination is semetric
my $diff = $n - $k;
if ($k > $diff) {
$k = $diff;
}
return cumprod($n - $k + 1, $n) / cumprod(1, $k);
}
sub permute {
my ($n, $k) = @_;
return cumprod($n - $k + 1, $n);
}
1;
| charles-l/zeroclickinfo-goodies | lib/DDG/Goodie/Combination.pm | Perl | apache-2.0 | 2,171 |
package DDG::Spice::Videos;
# ABSTRACT: Video search
use strict;
use DDG::Spice;
spice to => 'https://duckduckgo.com/v.js?q=$1&n=20&callback={{callback}}';
# 2014.05.07 (caine): moving to startend until
# we are invariably required to do entity extraction
# 'batman video games' shouldn't trigger this module
#triggers startend =>
# 'video',
# 'videos',
# 'youtube',
# 'vimeo',
# ;
my %skip = map { $_ => 0 } (
'calendar',
'authy remove account',
'www',
'yt',
'18+'
);
# 2014.05.19 (ct): deep spice.
triggers start => '///***never trigger***///';
handle remainder => sub {
return $_ if $_ && !exists $skip{lc $_};
return;
};
1;
| soleo/zeroclickinfo-spice | lib/DDG/Spice/Videos.pm | Perl | apache-2.0 | 678 |
=head1 NAME
basic.pod - Test of various basic POD features in translators.
=head1 HEADINGS
Try a few different levels of headings, with embedded formatting codes and
other interesting bits.
=head1 This C<is> a "level 1" heading
=head2 ``Level'' "2 I<heading>
=head3 Level 3 B<heading I<with C<weird F<stuff "" (double quote)>>>>
=head4 Level "4 C<heading>
Now try again with B<intermixed> F<text>.
=head1 This C<is> a "level 1" heading
Text.
=head2 ``Level'' 2 I<heading>
Text.
=head3 Level 3 B<heading I<with C<weird F<stuff>>>>
Text.
=head4 Level "4 C<heading>
Text.
=head1 LINKS
These are all taken from the Pod::Parser tests.
Try out I<LOTS> of different ways of specifying references:
Reference the L<manpage/section>
Reference the L<"manpage"/section>
Reference the L<manpage/"section">
Now try it using the new "|" stuff ...
Reference the L<thistext|manpage/section>|
Reference the L<thistext | manpage / section>|
Reference the L<thistext| manpage/ section>|
Reference the L<thistext |manpage /section>|
Reference the L<thistext|manpage/"section">|
Reference the L<thistext|
manpage/
section>|
And then throw in a few new ones of my own.
L<foo>
L<foo|bar>
L<foo/bar>
L<foo/"baz boo">
L</bar>
L</"baz boo">
L</baz boo>
L<foo bar/baz boo>
L<"boo var baz">
L<bar baz>
L</boo>, L</bar>, and L</baz>
L<fooZ<>bar>
L<Testing I<italics>|foo/bar>
L<foo/I<Italic> text>
L<fooE<verbar>barZ<>/Section C<with> I<B<other> markup>>
L<Nested L<http://www.perl.org/>|fooE<sol>bar>
=head1 OVER AND ITEMS
Taken from Pod::Parser tests, this is a test to ensure that multiline
=item paragraphs get indented appropriately.
=over 4
=item This
is
a
test.
=back
There should be whitespace now before this line.
Taken from Pod::Parser tests, this is a test to ensure the nested =item
paragraphs get indented appropriately.
=over 2
=item 1
First section.
=over 2
=item a
this is item a
=item b
this is item b
=back
=item 2
Second section.
=over 2
=item a
this is item a
=item b
this is item b
=item c
=item d
This is item c & d.
=back
=back
Now some additional weirdness of our own. Make sure that multiple tags
for one paragraph are properly compacted.
=over 4
=item "foo"
=item B<bar>
=item C<baz>
There shouldn't be any spaces between any of these item tags; this idiom
is used in perlfunc.
=item Some longer item text
Just to make sure that we test paragraphs where the item text doesn't fit
in the margin of the paragraph (and make sure that this paragraph fills a
few lines).
Let's also make it multiple paragraphs to be sure that works.
=back
Test use of =over without =item as a block "quote" or block paragraph.
=over 4
This should be indented four spaces but otherwise formatted the same as
any other regular text paragraph. Make sure it's long enough to see the
results of the formatting.....
=back
Now try the same thing nested, and make sure that the indentation is reset
back properly.
=over 4
=over 4
This paragraph should be doubly indented.
=back
This paragraph should only be singly indented.
=over 4
=item
This is an item in the middle of a block-quote, which should be allowed.
=item
We're also testing tagless item commands.
=back
Should be back to the single level of indentation.
=back
Should be back to regular indentation.
Now also check the transformation of * into real bullets for man pages.
=over
=item *
An item. We're also testing using =over without a number, and making sure
that item text wraps properly.
=item *
Another item.
=back
and now test the numbering of item blocks.
=over 4
=item 1.
First item.
=item 2.
Second item.
=back
=head1 FORMATTING CODES
Another test taken from Pod::Parser.
This is a test to see if I can do not only C<$self> and C<method()>, but
also C<< $self->method() >> and C<< $self->{FIELDNAME} >> and
C<< $Foo <=> $Bar >> without resorting to escape sequences. If
I want to refer to the right-shift operator I can do something
like C<<< $x >> 3 >>> or even C<<<< $y >> 5 >>>>.
Now for the grand finale of C<< $self->method()->{FIELDNAME} = {FOO=>BAR} >>.
And I also want to make sure that newlines work like this
C<<<
$self->{FOOBAR} >> 3 and [$b => $a]->[$a <=> $b]
>>>
Of course I should still be able to do all this I<with> escape sequences
too: C<$self-E<gt>method()> and C<$self-E<gt>{FIELDNAME}> and
C<{FOO=E<gt>BAR}>.
Dont forget C<$self-E<gt>method()-E<gt>{FIELDNAME} = {FOO=E<gt>BAR}>.
And make sure that C<0> works too!
Now, if I use << or >> as my delimiters, then I have to use whitespace.
So things like C<<$self->method()>> and C<<$self->{FIELDNAME}>> wont end
up doing what you might expect since the first > will still terminate
the first < seen.
Lets make sure these work for empty ones too, like C<< >> and C<< >> >>
(just to be obnoxious)
The statement: C<This is dog kind's I<finest> hour!> is a parody of a
quotation from Winston Churchill.
The following tests are added to those:
Make sure that a few othZ<>er odd I<Z<>things> still work. This should be
a vertical bar: E<verbar>. Here's a test of a few more special escapes
that have to be supported:
=over 3
=item E<amp>
An ampersand.
=item E<apos>
An apostrophe.
=item E<lt>
A less-than sign.
=item E<gt>
A greater-than sign.
=item E<quot>
A double quotation mark.
=item E<sol>
A forward slash.
=back
Try to get this bit of text over towards the edge so S<|that all of this
text inside SE<lt>E<gt> won't|> be wrapped. Also test the
|sameE<nbsp>thingE<nbsp>withE<nbsp>non-breakingS< spaces>.|
There is a soft hyE<shy>phen in hyphen at hy-phen.
This is a test of an X<index entry>index entry.
=head1 VERBATIM
Throw in a few verbatim paragraphs.
use Term::ANSIColor;
print color 'bold blue';
print "This text is bold blue.\n";
print color 'reset';
print "This text is normal.\n";
print colored ("Yellow on magenta.\n", 'yellow on_magenta');
print "This text is normal.\n";
print colored ['yellow on_magenta'], "Yellow on magenta.\n";
use Term::ANSIColor qw(uncolor);
print uncolor '01;31', "\n";
But this isn't verbatim (make sure it wraps properly), and the next
paragraph is again:
use Term::ANSIColor qw(:constants);
print BOLD, BLUE, "This text is in bold blue.\n", RESET;
use Term::ANSIColor qw(:constants); $Term::ANSIColor::AUTORESET = 1; print BOLD BLUE "This text is in bold blue.\n"; print "This text is normal.\n";
(Ugh, that's obnoxiously long.) Try different spacing:
Starting with a tab.
Not
starting
with
a
tab. But this should still be verbatim.
As should this.
This isn't.
This is. And this: is an internal tab. It should be:
|--| <= lined up with that.
(Tricky, but tabs should be expanded before the translator starts in on
the text since otherwise text with mixed tabs and spaces will get messed
up.)
And now we test verbatim paragraphs right before a heading. Older
versions of Pod::Man generated two spaces between paragraphs like this
and the heading. (In order to properly test this, one may have to
visually inspect the nroff output when run on the generated *roff
text, unfortunately.)
=head1 CONCLUSION
That's all, folks!
=cut
| Lh4cKg/sl4a | perl/src/lib/Pod/t/basic.pod | Perl | apache-2.0 | 7,243 |
# $Id$
package XML::SAX::PurePerl::Reader::String;
use strict;
use vars qw(@ISA);
use XML::SAX::PurePerl::Reader qw(
LINE
COLUMN
BUFFER
ENCODING
EOF
);
@ISA = ('XML::SAX::PurePerl::Reader');
use constant DISCARDED => 8;
use constant STRING => 9;
use constant USED => 10;
use constant CHUNK_SIZE => 2048;
sub new {
my $class = shift;
my $string = shift;
my @parts;
@parts[BUFFER, EOF, LINE, COLUMN, DISCARDED, STRING, USED] =
('', 0, 1, 0, 0, $string, 0);
return bless \@parts, $class;
}
sub read_more () {
my $self = shift;
if ($self->[USED] >= length($self->[STRING])) {
$self->[EOF]++;
return 0;
}
my $bytes = CHUNK_SIZE;
if ($bytes > (length($self->[STRING]) - $self->[USED])) {
$bytes = (length($self->[STRING]) - $self->[USED]);
}
$self->[BUFFER] .= substr($self->[STRING], $self->[USED], $bytes);
$self->[USED] += $bytes;
return 1;
}
sub move_along {
my($self, $bytes) = @_;
my $discarded = substr($self->[BUFFER], 0, $bytes, '');
$self->[DISCARDED] += length($discarded);
# Wish I could skip this lot - tells us where we are in the file
my $lines = $discarded =~ tr/\n//;
$self->[LINE] += $lines;
if ($lines) {
$discarded =~ /\n([^\n]*)$/;
$self->[COLUMN] = length($1);
}
else {
$self->[COLUMN] += $_[0];
}
}
sub set_encoding {
my $self = shift;
my ($encoding) = @_;
XML::SAX::PurePerl::Reader::switch_encoding_string($self->[BUFFER], $encoding, "utf-8");
$self->[ENCODING] = $encoding;
}
sub bytepos {
my $self = shift;
$self->[DISCARDED];
}
1;
| Dokaponteam/ITF_Project | xampp/perl/vendor/lib/XML/SAX/PurePerl/Reader/String.pm | Perl | mit | 1,691 |
package File::Dir::Dumper::Scanner;
use warnings;
use strict;
use 5.012;
use parent 'File::Dir::Dumper::Base';
use Carp;
use File::Find::Object;
use Devel::CheckOS qw(:booleans);
use POSIX qw(strftime);
use List::Util qw(min);
__PACKAGE__->mk_accessors(
qw(
_file_find
_group_cache
_last_result
_queue
_reached_end
_result
_user_cache
)
);
=head1 NAME
File::Dir::Dumper::Scanner - scans a directory and returns a stream of Perl
hash-refs
=head1 VERSION
Version 0.0.10
=cut
our $VERSION = '0.0.10';
=head1 SYNOPSIS
use File::Dir::Dumper::Scanner;
my $scanner = File::Dir::Dumper::Scanner->new(
{
dir => $dir_pathname
}
);
while (defined(my $token = $scanner->fetch()))
{
}
=head1 METHODS
=head2 $self->new({ dir => $dir_path})
Scans the directory $dir_path.
=head2 my $hash_ref = $self->fetch()
Outputs the next token as a hash ref.
=cut
sub _init
{
my $self = shift;
my $args = shift;
my $dir_to_dump = $args->{dir};
$self->_file_find(
File::Find::Object->new(
{
followlink => 0,
},
$dir_to_dump,
)
);
$self->_queue([]);
$self->_add({ type => "header", dir_to_dump => $dir_to_dump, stream_type => "Directory Dump"});
$self->_user_cache({});
$self->_group_cache({});
return;
}
sub _add
{
my $self = shift;
my $token = shift;
push @{$self->_queue()}, $token;
return;
}
sub fetch
{
my $self = shift;
if (! @{$self->_queue()})
{
$self->_populate_queue();
}
return shift(@{$self->_queue()});
}
sub _up_to_level
{
my $self = shift;
my $target_level = shift;
my $last_result = $self->_last_result();
for my $level (
reverse($target_level .. $#{$last_result->dir_components()})
)
{
$self->_add(
{
type => "updir",
depth => $level+1,
}
)
}
return;
}
sub _find_new_common_depth
{
my $self = shift;
my $result = $self->_result();
my $last_result = $self->_last_result();
my $depth = 0;
my $upper_limit =
min(
scalar(@{$last_result->dir_components()}),
scalar(@{$result->dir_components()}),
);
FIND_I:
while ($depth < $upper_limit)
{
if ($last_result->dir_components()->[$depth] ne
$result->dir_components()->[$depth]
)
{
last FIND_I;
}
}
continue
{
$depth++;
}
return $depth;
}
BEGIN
{
if (os_is('Unix'))
{
*_my_getpwuid =
sub {
my $uid = shift; return scalar(getpwuid($uid));
};
*_my_getgrgid =
sub {
my $gid = shift; return scalar(getgrgid($gid));
};
}
else
{
*_my_getpwuid = sub { return "unknown"; };
*_my_getgrgid = sub { return "unknown"; };
}
}
sub _get_user_name
{
my $self = shift;
my $uid = shift;
if (!exists($self->_user_cache()->{$uid}))
{
$self->_user_cache()->{$uid} = _my_getpwuid($uid);
}
return $self->_user_cache()->{$uid};
}
sub _get_group_name
{
my $self = shift;
my $gid = shift;
if (!exists($self->_group_cache()->{$gid}))
{
$self->_group_cache()->{$gid} = _my_getgrgid($gid);
}
return $self->_group_cache()->{$gid};
}
sub _calc_file_or_dir_token
{
my $self = shift;
my $result = $self->_result();
my @stat = stat($result->path());
return
{
filename => $result->full_components()->[-1],
depth => scalar(@{$result->full_components()}),
perms => sprintf("%04o", ($stat[2]&07777)),
mtime => strftime("%Y-%m-%dT%H:%M:%S", localtime($stat[9])),
user => $self->_get_user_name($stat[4]),
group => $self->_get_group_name($stat[5]),
($result->is_dir()
? (type => "dir",)
: (type => "file", size => $stat[7],)
),
};
}
sub _populate_queue
{
my $self = shift;
if ($self->_reached_end())
{
return;
}
$self->_result($self->_file_find->next_obj());
if (! $self->_last_result())
{
$self->_add({ type => "dir", depth => 0 });
}
elsif (! $self->_result())
{
$self->_up_to_level(-1);
$self->_add({type => "footer"});
$self->_reached_end(1);
}
else
{
$self->_up_to_level($self->_find_new_common_depth());
$self->_add(
$self->_calc_file_or_dir_token()
);
}
$self->_last_result($self->_result());
}
=head1 AUTHOR
Shlomi Fish, C<< <shlomif@cpan.org> >>
=head1 BUGS
Please report any bugs or feature requests to C<bug-file-dir-dumper at rt.cpan.org>, or through
the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=File-Dir-Dumper>. I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.
=head1 SUPPORT
You can find documentation for this module with the perldoc command.
perldoc File::Dir::Dumper
You can also look for information at:
=over 4
=item * RT: CPAN's request tracker
L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Dir-Dumper>
=item * AnnoCPAN: Annotated CPAN documentation
L<http://annocpan.org/dist/File-Dir-Dumper>
=item * CPAN Ratings
L<http://cpanratings.perl.org/d/File-Dir-Dumper>
=item * Search CPAN
L<http://search.cpan.org/dist/File-Dir-Dumper>
=back
=head1 ACKNOWLEDGEMENTS
=head1 COPYRIGHT & LICENSE
Copyright 2008 Shlomi Fish, all rights reserved.
This program is released under the following license: MIT/X11 Licence.
=cut
1; # End of File::Dir::Dumper
| gitpan/File-Dir-Dumper | lib/File/Dir/Dumper/Scanner.pm | Perl | mit | 5,790 |
use Encode;
use utf8;
if (scalar(@ARGV) ne 3)
{
print STDERR "perl LiNMT-num.pl config input output\n";
exit(1);
}
$config_string = "";
open (CONFIG, "<:encoding(utf8)", $ARGV[0]) or die "Error: can not read $ARGV[0]!\n";
while (my $line = <CONFIG>)
{
$line =~ s/[\r\n]//g;
$config_string .= $line;
}
close(CONFIG);
open (INPUT, "<:encoding(utf8)", $ARGV[1]) or die "Error: can not read $ARGV[1]!\n";
open (OUTPUT, ">:encoding(utf8)", $ARGV[2]) or die "Error: can not write $ARGV[2]!\n";
$line_num = 0;
$find_num = 0;
while (my $line = <INPUT>)
{
++$line_num;
$line =~ s/[\r\n]//g;
if ($line =~ /[[0-9$config_string]/)
{
++$find_num;
print OUTPUT $line."\n";
print STDERR "\rLINE=$line_num FIND=$find_num";
}
}
print STDERR "\rLINE=$line_num FIND=$find_num\n";
close(INPUT);
close(OUTPUT);
| liqiangnlp/LiNMT | scripts/number.recognition/LiNMT-num.pl | Perl | mit | 830 |
% Question 1
list_of(_, []).
list_of(Elt, [Elt|Tail]) :-
list_of(Elt, Tail).
% Question 2
all_same([Head|Tail]) :- list_of(Head, Tail).
% Question 3
adjacent(E1, E2, List) :-
append(_, [E1,E2|_], List).
% Question 4
adjacent(E1, E2, [E1,E2|_]).
adjacent(E1, E2, [Head|Tail]) :-
adjacent(E1,E2, Tail).
| martindavid/code-sandbox | comp90048/workshop/my_answer/w08.pl | Perl | mit | 314 |
:- expects_dialect(lps).
:- dynamic located(Party, thirdCountry),
decisionPursuantToArticle_45_3(Event), legallyBindingEnforceableInstrument(Process),
bindingCorporateRules(Process), standardDataProtectionClauses(Process),
approvedCodeOfConduct(Process), approvedCertificateMechanism(Process).
permitted(Event) :- isa(Event, transfer(Enterprise, Data, Party) ),
not decisionPursuantToArticle_45_3(Event),
( isa(Enterprise, controller); isa(Enterprise, processor)),
isa(Data, personalData),
( located(Party, thirdCountry); isa(Party, internationalOrganisation)),
partOf(Event, Process),
appropriateSafeguards(Process),
enforceableDataSubjectRights(Process),
legalRemediesForDataSubjects(Process).
appropriateSafeguards(Process) :- legallyBindingEnforceableInstrument(Process);
bindingCorporateRules(Process);
standardDataProtectionClauses(Process);
approvedCodeOfConduct(Process);
approvedCertificateMechanism(Process).
isa(event001, transfer(companyA_Ireland, data, companyA_US) ).
isa(companyA_Ireland, controller).
isa(data, personalData).
located(companyA_US, thirdCountry).
partOf(event001, process001).
enforceableDataSubjectRights(process001).
legalRemediesForDataSubjects(process001).
% bindingCorporateRules(process001).
/** <examples>
?- permitted(event001).
?- appropriateSafeguards(Process).
*/
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_ec/test/lps_user_examples/GDPR compliance - article 46.pl | Perl | mit | 1,347 |
#!/usr/bin/perl
#
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2005, 2007, 2008, 2009, 2010 Zimbra, Inc.
#
# The contents of this file are subject to the Zimbra Public License
# Version 1.3 ("License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.zimbra.com/license.
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
# ***** END LICENSE BLOCK *****
#
use strict;
use Migrate;
Migrate::verifySchemaVersion(20);
dropRedoLogSequence();
Migrate::updateSchemaVersion(20, 21);
exit(0);
#####################
sub dropRedoLogSequence() {
my $sql = "drop table if exists redolog_sequence;";
Migrate::runSql($sql);
}
| nico01f/z-pec | ZimbraServer/src/db/migration/migrate20050927-DropRedologSequence.pl | Perl | mit | 833 |
=head1 NAME
The mod_perl Mailing List Guidelines
=head1 Description
Ninety percent of the questions asked on the List have already been
asked before, and answers will be found at one of the links below.
Before you post to the mod_perl List, please read the following.
Hopefully it will save you (and everyone else) some time.
Except where noted the language of all documents is English.
=head1 What is mod_perl?
See the L<mod_perl Guide|docs::1.0::guide::intro>.
=head1 What you need to know to be able to use mod_perl
You need to know about Apache, CGI and of course about Perl itself.
This document explains where to find more information about these and
related topics.
If you already have Perl on your machine then it's likely that you
already have all the Perl documentation. Try typing `perldoc perldoc'
and `man perl'.
=head1 How To Get Help With mod_perl Itself
Please read the sections on L<getting help with mod_perl
1.0|docs::1.0::guide::help> or L<getting help with mod_perl
2.0|docs::2.0::user::help::help>, depending on what version
you are using.
=head2 Documentation which comes with the distribution
Read the documents which came with mod_perl, particularly the ones
named INSTALL, README and SUPPORT. Also read the documents to which
they refer. Read all the relevant documentation about your operating
system, any tools you use such as compilers and databases, and about
the Apache Web server.
You will get a much better response from the mod_perl List if you can
show that you have made the effort of reading the documentation.
=head2 Other documentation
There are dozens of references to many authoritative resources in the
L<Offsite Resources|docs::offsite::index> section.
=head1 How to get on (and off!) the mod_perl mailing list
=head2 To Get On The List
There are two stages to getting on the list. Firstly you have to send
a mail message to: modperl-subscribe@perl.apache.org and wait for
receiving a response from the mail server with instructions to
proceed.
Secondly you have to do what it says in the instructions. After you
are subscribed you will receive a messsage with lots of useful
information about the List. Read it. Print it, even. Save a copy of
it. You B<can> get another copy of it, but then you'll feel silly.
Traffic on the mod_perl list can be high at times, several hundred
posts per week, so you might want to consider subscribing to the
mod_perl digest list as an alternative to the mod_perl list. To do so,
send an email to modperl-digest-subscribe@perl.apache.org instead.
=head2 To Get Off The List
Instructions on how to unsubscribe are posted in the headers of every
message which you receive from the List. All you have to do is send a
message to: modperl-unsubscribe@perl.apache.org (or
modperl-digest-unsubscribe@perl.apache.org if you are on the digest
list)
To prevent malicious individuals from unsubscribing other people, the
mailing list software insists that the message requesting that an
email address be unsubscribed comes from that same address. If your
email address has changed you can still unsubscribe, but you will need
to read the help document, which can be recieved by sending an empty
email to: modperl-help@perl.apache.org
=head1 To post to the List
I<Posting> to the list is just sending a message to the address which
you will be given after you subscribe.
To keep the list safe from spam, any message posted from an unsubscribed
email address is sent to a moderator for manual approval.
Do not post to modperl-subscribe@perl.apache.org, except to subscribe
to the list! Please do not post to the list itself to attempt to
unsubscribe from it.
=head2 Private Mail
Please do not send private mail to list members unless it is
invited. Even if they have answered your question on the list, you
should continue the discussion on the list.
On the other hand, if someone replies to you personally, you shouldn't
forward the reply to the list unless you have received permission from
this person.
=head2 Other Tips
=head3 Read The Documentation
Please read as much of the L<documentation|docs::index> as you can
before posting. Please also try to see if your question has been
asked recently, there are links to searchable archives on the
L<mailing list pages|maillist::index>.
=head3 Give Full Information
Don't forget that the people reading the list have no idea even what
operating system your computer runs unless you tell them. When
reporting problems include at least the information requested in the
document entitled I<SUPPORT> which you will find in the mod_perl
source distribution.
You can find many excellent examples of posts with good supporting
information by looking at the mod_perl mailing list archives. There
are URLs for several archives (with several different search engines)
on the mod_perl home page. Followup posts will show you how easy the
writer made it for the person who replied to deduce the problem and to
suggest a way of solving it, or to find some further item information.
If after reading the I<SUPPORT> document you think that more
information is needed for your particular problem, but you still don't
know what information to give, ask on the list rather than sending
long scripts and configuration files which few people will have the
time to read.
=head3 Error Messages
If you include error messages in your post, make sure that they are
EXACTLY the messages which you saw. Use a text editor to transfer
them directly into your message if you can. Try not to say things
like "the computer said something about not recognizing a command" but
instead to say something like this:
"When logged in as root I typed the command:
httpd -X
at the console and on the console I saw the message
Syntax error on line 393 of /etc/httpd/conf/httpd.conf: Invalid
command 'PerlHandler', perhaps mis-spelled or defined by a module
not included in the server configuration [FAILED]"
=head3 The Subject Line
The I<Subject:> line is B<very> important. Choose an B<informative>
I<Subject> line for the mail header. Busy list members will skip
messages with unclear I<Subject> lines.
=head3 Preserve The Threads
Messages which all have the same I<Subject> line text (possibly
preceded by the word "Re:" which is automatically added by your
mailer) are together known as a "thread". List members and mail
archive use mail unique-ids and/or the Subject line to sort mail. Do
not change the text without a very good reason, because this may break
the thread. Breaking the thread makes it difficult to follow the
discussion and can be very confusing. It may be better to start a new
thread than to continue an old one if you change the theme.
=head3 Post in PLAIN TEXT
Do not post in HTML. Microsoft users in particular should take
careful note of this. Use either the US-ASCII or ISO-8859-1 (Latin-1)
character set, do not use other character sets which may be designed
for those who do not speak English and which may not be displayable on
many terminals. If you ignore this advice then the chances are
greater that your message will not be read.
=head3 Time and Bandwidth
Remember that thousands of people may read your messages. To save
time and to keep badwidth usage to a minimum, please keep posts
reasonably short, but please make it clear precisely what you are
asking. If you can, send a B<small> example of a script or
configuration which reproduces your problem. Please do not send long
scripts which cannot easily be understood. Please do not send large
attachments of many kilobytes, if they are needed then put them on the
Web somewhere or say in your message that you can send them separately
if they are requested.
=head3 Tags
It can be helpful if you use a C<[tag]> in square brackets in the
I<Subject:> line, as well as the brief description of your post.
Some suggested tags are:
ADMIN Stuff about running the List.
ADVOCACY Promoting the use of mod_perl, printing T-shirts, stuff like
that. Please don't start another discussion about whether we
should put this on a different list, we've been there before.
ANNOUNCE Announcements of new software tools, packages and updates.
BENCHMARK Apache/mod_perl performance issues.
BUG Report of possible fault in mod_perl or associated software
- it's better if you can send a patch instead!
DBI Stuff generally concerning Apache/mod_perl interaction
with databases.
FYI For information only.
JOB Any post about mod_perl jobs is welcome as long as it is
brief and to the point. Note: Not "JOBS".
MASON Jonathan Swartz' implementation of Perl embedded in HTML.
NEWS Items of news likely to be interesting to mod_perlers.
OT Off-topic items, please try to keep traffic low.
PATCH Suggested fix for fault in mod_perl or associated software.
QUESTION Questions about mod_perl which is not covered by one of the
more specific headings.
RareModules Occasional reminders about little-used modules on CPAN.
RFC Requests for comment from the mod_perl community.
SITE Things about running the Apache/mod_perl servers.
SUMMARY After investigation and perhaps fixing a fault, and after an
extended discussion of a specific topic, it is helpful if
someone summarizes the thread. Don't be shy, everyone will
appreciate the effort.
mod_perl2 As currently both versions of mod_perl are beeing supported
or on the same list, adding a tag to specifiy which version you
mp2 are talking about might be a good idea.
If you can't find a tag which fits your subject, don't worry. If you
have a very specific subject to discuss, feel free to choose your own
tag, for example C<[mod_proxy]> or C<[Perl Sections]> but remember
that the main reasons for the I<Subject> line are to save people time
and to improve the response to your posts. It does not matter whether
you use C<[UPPER CASE]> or C<[lower case]> or even a C<[Mixture Of
Both]> in the tag. Try to keep the tag short. The tag should be the
first thing in the I<Subject> line.
=head3 If You Don't Get a Reply
Sometimes you will not get a reply. Try to be patient, but it is OK
to try again after a few days. Sometimes the replies you get will be
very short. Please do not worry about that. People are very busy,
that's all.
Of course if your post is C<[OT]> for the list then you may not get a
reply, or you may get one telling you to try a different forum.
=head3 If You Don't Understand a Reply
Just say so.
=head3 General Perl and Apache questions
The mod_perl list is NOT for general questions about Apache and the
Perl language. The majority view is tolerant of off-topic posts, but
it is considered impolite to post general Perl and Apache questions on
the mod_perl list. The best you can hope for is a private reply and a
polite reminder that the question is off-topic for this list. If you
catch someone on a bad day, you might not get the best. There are
often bad days in software development departments...
If the Perl and Apache documentation has not answered your question
then you could try looking at http://lists.perl.org/ or one of the
comp.lang.* newsgroups. From time to time there are efforts to start
a dedicated Perl mailing list and these usually result in a message or
two on the mod_perl list, so it might be worth your while to search
the archives.
Please note that there are now separate mailing lists for ASP, EmbPerl
and Mason, but although we keep trying to get a separate list off the
ground for I<Advocacy> it always seems to end up back on the mod_perl
list.
=head1 Replying to posts
=head2 The "Subject:" line
Make sure that you include the exact I<Subject:> from the original
post, unmodified. This makes it much easier for people (and for the
mail software) to deal with the mail. If you must change the subject
line then please append the words "was originally" plus the original
subject line to your new subject line so that folks can see what is
going on.
=head2 Extracts From the Post You Reply to
When replying to a post, please include B<short> excerpts from the
post to which you are replying so that others can follow the
conversation without having to wade through reams of superfluous text.
If you are lazy about this then messages can get very long indeed and
can become a burden to the other people who might be trying to help.
Make sure that there is a clear distinction between the text(s) of the
message(s) to which you are replying and your reply itself.
Please do not quote the original message you reply to at the bottom of
the email, as we already have the original message in the mail list
archives. Either quote only the relevant parts you reply to, if you
reply under those quotes, or don't quote at all if you can't be
bothered to maintain context.
=head2 Unnecessary Duplication
If you know that the intended recipients are subscribed to the List,
there is no need to send messages both to them and to the list. They
will get more than one copy of the message which is wasteful.
=head2 Private replies
It is helpful to keep most of your replies on the list, so that others
see that help is being given and so they do not waste time on problems
which have already been solved. Where it is appropriate to take a
discussion off the list (for example where it veers off-topic, as
often happens), say so in a message so that everyone is aware of it.
=head2 Flames
The readers of the mod_perl List aren't interested in that kind of
thing. Don't get involved.
=head1 The mod_perl documentation
You absolutely B<must> read the L<mod_perl documentation|docs::index>.
There are many documents, but they are worth reading, as they might
solve your problems and teach you better coding. Each document also
has a C<[PDF]> link so that you can print it. If you want to download
the documentation locally, see the L<Documentation
download|download::docs> section. You can then build the whole site
locally.
Contributions are very welcome, see the same page for details on how
to submit patches.
=head1 Related Links
"How To Ask Questions The Smart Way" by Eric Steven Raymond and Rick
Moen: http://www.catb.org/~esr/faqs/smart-questions.html
=cut
| Distrotech/mod_perl | docs/src/maillist/email-etiquette.pod | Perl | apache-2.0 | 14,304 |
#
# Ensembl module for Bio::EnsEMBL::DBSQL::Funcgen::ResultFeatureAdaptor
#
# You may distribute this module under the same terms as Perl itself
=head1 NAME
Bio::EnsEMBL::DBSQL::Funcgen::ResultFeatureAdaptor - adaptor for fetching and storing ResultFeature objects
=head1 SYNOPSIS
my $rfeature_adaptor = $db->get_ResultFeatureAdaptor();
my @result_features = @{$rfeature_adaptor->fetch_all_by_ResultSet_Slice($rset, $slice)};
=head1 DESCRIPTION
The ResultFeatureAdaptor is a database adaptor for storing and retrieving
ResultFeature objects.
This will automatically query the web optimised result_feature
table if a data is present, else it will query the underlying raw data tables.
=head1 LICENSE
Copyright (c) 1999-2011 The European Bioinformatics Institute and
Genome Research Limited. All rights reserved.
This software is distributed under a modified Apache license.
For license details, please see
http://www.ensembl.org/info/about/code_licence.html
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <ensembl-dev@ebi.ac.uk>.
Questions may also be sent to the Ensembl help desk at
<helpdesk@ensembl.org>.
=cut
#How are we going to track the association between raw experimental_chip and collection result set?
#ExperimentalChip/Channel ResultSets will probably go away, so ignore this association problem for now.
#Association between FeatureSet and Input/ResultSet to be handled in import pipeline
#ResultFeature ResultSets now have a RESULT_FEATURE_SET status entry.
#Add some details about file based collections
package Bio::EnsEMBL::Funcgen::DBSQL::ResultFeatureAdaptor;
use strict;
use warnings;
use Bio::EnsEMBL::Utils::Exception qw( throw warning deprecate );
use Bio::EnsEMBL::Funcgen::ResultSet;
use Bio::EnsEMBL::Funcgen::ResultFeature;
use Bio::EnsEMBL::Funcgen::Utils::EFGUtils qw(mean median);
#Bareword SQL_TYPES not exported from BaseFeatureAdpator unless it is 'use'd first
use Bio::EnsEMBL::Funcgen::DBSQL::BaseFeatureAdaptor;
use Bio::EnsEMBL::Funcgen::Collector::ResultFeature;
use base qw(Bio::EnsEMBL::Funcgen::DBSQL::BaseFeatureAdaptor
Bio::EnsEMBL::Funcgen::Collector::ResultFeature);
#Private vars to used to maintain simple implementation of Collector
#Should be set in each method to enable trimmingof the start and end bins.
#Cannot depend on $dest_slice_start/end in _objs_from_sth
#As _collection_start/end are adjusted to the nearest bin
my ($_scores_field, $_collection_start, $_collection_end);
#my ($_window_size);#Need to be a method as it is used by the BaseFeatureAdaptor. or our?
=head2 _tables
Args : None
Example : None
Description: PROTECTED implementation of superclass abstract method.
Returns the names and aliases of the tables to use for queries.
Returntype : List of listrefs of strings
Exceptions : None
Caller : Internal
Status : At Risk
=cut
sub _tables {
my $self = shift;
return ([ 'result_feature', 'rf' ]);
}
=head2 _columns
Args : None
Example : None
Description: PROTECTED implementation of superclass abstract method.
Returns a list of columns to use for queries.
Returntype : List of strings
Exceptions : None
Caller : Internal
Status : At Risk
=cut
sub _columns {
my $self = shift;
return ('rf.seq_region_start', 'rf.seq_region_end', 'rf.seq_region_strand',
"$_scores_field", 'rf.result_set_id', 'rf.window_size');
}
=head2 _objs_from_sth
Arg [1] : DBI statement handle object
Example : None
Description: PROTECTED implementation of superclass abstract method.
Creates Array objects from an executed DBI statement
handle.
Returntype : Listref of Bio::EnsEMBL::Funcgen::Experiment objects
Exceptions : None
Caller : Internal
Status : At Risk - Moving to DBFile implementation
=cut
sub _objs_from_sth {
my ($self, $sth, $mapper, $dest_slice) = @_;
if(! $dest_slice){
throw('ResultFeatureAdaptor always requires a dest_slice argument');
#Is this correct?
#ExperimentalChip based normalisation?
#Currently does not use this method
#Never have non-Slice based fetchs, so will always have dest_slice and seq_region info.
}
my (%rfeats, $start, $end, $strand, $scores, $rset_id, $window_size);
#Could dynamically define simple obj hash dependant on whether feature is stranded and new_fast?
#We never call _obj_from_sth for extended queries
#This is only for result_feature table queries i.e. standard/new queries
$sth->bind_columns(\$start, \$end, \$strand, \$scores, \$rset_id, \$window_size);
#Test slice is loaded in eFG?
my $slice_adaptor = $self->db->get_SliceAdaptor;
if(! $slice_adaptor->get_seq_region_id($dest_slice)){
warn "Cannot get eFG slice for:".$dest_slice->name.
"\nThe region you are using is not present in the current dna DB";
return;
}
if($mapper) {
throw('Cannot dynamically assembly map Collections yet');
#See GeneAdaptor for mapping code if required
}
my $dest_slice_start;
my $dest_slice_end;
my $dest_slice_strand;
my $dest_slice_length;
my $dest_slice_sr_name;
my $dest_slice_sr_id;
$dest_slice_start = $dest_slice->start();
$dest_slice_end = $dest_slice->end();
$dest_slice_strand = $dest_slice->strand();
$dest_slice_length = $dest_slice->length();
$dest_slice_sr_name = $dest_slice->seq_region_name();
$dest_slice_sr_id = $dest_slice->get_seq_region_id();
my (@scores, $slice, $start_pad, $end_pad);
#Set up the %rfeats arrays here to prevent having to test in loop
#This will speed up 0 wsize, but most likely slow others?
FEATURE: while ( $sth->fetch() ) {
if($window_size == 0){
warn "0bp window size array based collections are no longer supported";
}
else{
#Cannot have a collection which does not start at 1
#As we cannot compute the bin start/ends correctly?
#Actually we can do so long as they have been stored correctly
#i.e. start and end are valid bin bounds(extending past the end of the seq_region if needed)
#Let's keep it simple for now
throw("Collections with a window size > 0 must start at 1, not ($start)") if $start !=1;
#Can remove this if we test start and end are valid bin bounds for the given wsize
#Account for oversized slices
#This is if the slice seq_region_start/end are outside of the range of the record
#As collections should really represent a complete seq_region
#This should only happen if a slice is defined outside the the bounds of a seq_region
#i.e. seq_region_start < collection_start or seq_region_end > slice length
#if a test slice has been stored which does not represent the complete seq_region
#We don't need to pad at all, just adjust the $_collection_start/ends!!!
#Don't need to account for slice start < 1
#Start and end should always be valid bin bounds
#These could be removed if we force only full length seq_region collections
$_collection_start = $start if($_collection_start < $start);
$_collection_end = $end if($_collection_end > $end);
#warn "col start now $_collection_start";
#warn "col end now $_collection_end";
# If the dest_slice starts at 1 and is foward strand, nothing needs doing
# else convert coords
# These need to use $_collection_start/end rather than dest_slice_start/end
if($dest_slice_start != 1 || $dest_slice_strand != 1) {
if($dest_slice_strand == 1) {
$start = $_collection_start - $dest_slice_start + 1;
$end = $_collection_end - $dest_slice_start + 1;
} else {
my $tmp_seq_region_start = $_collection_start;
$start = $dest_slice_end - $_collection_end + 1;
$end = $dest_slice_end - $tmp_seq_region_start + 1;
$strand *= -1;
}
}
#What about 0 strand slices?
#throw away features off the end of the requested slice or on different seq_region
if($end < 1 || $start > $dest_slice_length){# ||
#( $dest_slice_sr_id ne $seq_region_id )) {
#This would only happen if assembly mapper had placed it on a different seq_region
#Dynamically mapped features are not guaranteed to come back in correct order?
next FEATURE;
}
@scores = unpack('('.$self->pack_template.')'.(($_collection_end - $_collection_start + 1)/$window_size ), $scores);
}
push @{$rfeats{$rset_id}}, Bio::EnsEMBL::Funcgen::Collection::ResultFeature->new_fast({
start => $start,
end => $end,
strand =>$strand,
scores => [@scores],
#undef,
#undef,
window_size => $window_size,
slice => $dest_slice,
});
}
return \%rfeats;
}
=head2 store
Args[0] : List of Bio::EnsEMBL::Funcgen::ResultFeature objects
Args[1] : Bio::EnsEMBL::Funcgen::ResultSet
Args[2] : Optional - Assembly to project to e.g. GRCh37
Example : $rfa->store(@rfeats);
Description: Stores ResultFeature objects in the result_feature table.
Returntype : None
Exceptions : Throws if a List of ResultFeature objects is not provided or if
any of the attributes are not set or valid.
Caller : General
Status : At Risk - Moving to DBFile implementation
=cut
sub store{
my ($self, $rfeats, $rset, $new_assembly) = @_;
#We can't project collections to a new assembly after they have been generated
#as this will mess up the standardised bin bounds.
#Just project the 0 window size and then rebuild other window_sizes form there
$self->set_collection_defs_by_ResultSet($rset);
throw("Must provide a list of ResultFeature objects") if(scalar(@$rfeats == 0));
#These are in the order of the ResultFeature attr array(excluding probe_id, which is the result/probe_feature query only attr))
my $sth = $self->prepare('INSERT INTO result_feature (result_set_id, seq_region_id, seq_region_start, seq_region_end, seq_region_strand, window_size, scores) VALUES (?, ?, ?, ?, ?, ?, ?)');
my $db = $self->db();
my ($pack_template, $packed_string);
#my @max_allowed_packet = $self->dbc->db_handle->selectrow_array('show variables like "max_allowed_packet"');
#warn "@max_allowed_packet";
FEATURE: foreach my $rfeat (@$rfeats) {
if( ! (ref($rfeat) && $rfeat->isa('Bio::EnsEMBL::Funcgen::Collection::ResultFeature'))) {
throw('Must be a Bio::EnsEMBL::Funcgen::Collection::ResultFeature object to store');
}
#This is the only validation! So all the validation must be done in the caller as we are simply dealing with ints?
#Remove result_feature_set from result_set and set as status?
my $seq_region_id;
($rfeat, $seq_region_id) = $self->_pre_store($rfeat, $new_assembly);
next if ! $rfeat;#No projection to new assembly
#Is there a way of logging which ones don't make it?
#This captures non full length collections at end of seq_region
$pack_template = '('.$self->pack_template.')'.scalar(@{$rfeat->scores});
#Check that we have non-0 values in compressed collections
if($rfeat->window_size != 0){
if(! grep { /[^0]/ } @{$rfeat->scores} ){
warn('Collection contains no non-0 scores. Skipping store for '.
$rfeat->slice->name.' '.$rfeat->window_size." window_size\n");
next;
}
}
$packed_string = pack($pack_template, @{$rfeat->scores});
#use Devel::Size qw(size total_size);
#warn "Storing ".$rfeat->result_set_id,' '.$seq_region_id.' '.$rfeat->start.' '.$rfeat->end.' '.$rfeat->strand,' ',$rfeat->window_size."\nWith packed string size:\t".size($packed_string);
$sth->bind_param(1, $rfeat->result_set_id, SQL_INTEGER);
$sth->bind_param(2, $seq_region_id, SQL_INTEGER);
$sth->bind_param(3, $rfeat->start, SQL_INTEGER);
$sth->bind_param(4, $rfeat->end, SQL_INTEGER);
$sth->bind_param(5, $rfeat->strand, SQL_INTEGER);
$sth->bind_param(6, $rfeat->window_size, SQL_INTEGER);
$sth->bind_param(7, $packed_string, SQL_BLOB);
$sth->execute();
}
return $rfeats;
}
#This is no applicable to ResultFeatures
=head2 list_dbIDs
Args : None
Example : my @rsets_ids = @{$rsa->list_dbIDs()};
Description: Gets an array of internal IDs for all ResultFeature objects in
the current database.
Returntype : List of ints
Exceptions : None
Caller : general
Status : stable
=cut
sub list_dbIDs {
my $self = shift;
return $self->_list_dbIDs('result_feature');
}
=head2 _window_size
Args : None
Example : my $wsize = $self->_window_size
Description: Gets the window_size of the current ResultFeature query.
This needs to be a method rather than just a private variable
as it is used by the BaseFeatureAdaptor.
Returntype : int
Exceptions : None
Caller : Bio::EnsEMBL::BaseFeatureAdaptor
Status : At risk - ??? Is this required anymore
=cut
sub _window_size{
my $self = shift;
return $self->{'window_size'};
}
=head2 set_collection_config_by_Slice_ResultSets
Args[0] : Bio::EnsEMBL::Slice
Args[1] : ARRAYREF of Bio::EnsEMBL::Funcgen::ResultSet object
Args[2] : int - Maximum number of bins required i.e. number of pixels in drawable region
Example : $self->set_collection_defss_by_ResultSet([$rset]);
Description: Similar to set_collection_defs_by_ResultSet, but used
to set a config hash used for multi-ResultSet fetches.
Returntype : None
Exceptions : throws is args are not valid
throws if supporting InputSet is not of type result (i.e. short reads import)
throws if supporting InputSet format is not SEQUENCING (i.e. short reads import)
throws if ResultSet is not and input_set or experimental_chip based ResultSet (i.e. channel etc)
Caller : ResultFeatureAdaptor::fetch_all_by_Slice_ResultSets
Status : At Risk
=cut
sub set_collection_config_by_Slice_ResultSets{
my ($self, $slice, $rsets, $max_bins, $window_size) = @_;
if(ref($rsets) ne 'ARRAY'){
throw('You must pass an ARRAYREF of Bio::EnsEMBL::ResultSet objects.');
}
if(! (ref($slice) && $slice->isa('Bio::EnsEMBL::Slice'))){
throw('You must pass a valid Bio::EnsEMBL::Slice');
}
my ($wsize, $window_element, @rsets, %wsize_config);
my ($collection_start, $collection_end);
if($window_size && $max_bins){
warn "Over-riding max_bins with specific window_size, omit window_size to calculate window_size using max_bins";
}
my ($is_rf_set);
my $rf_source = 'file';
foreach my $rset(@{$rsets}){
$is_rf_set = $rset->has_status('RESULT_FEATURE_SET') || 0;
$self->db->is_stored_and_valid('Bio::EnsEMBL::Funcgen::ResultSet', $rset);
if(! ($rset->table_name eq 'input_set' || $is_rf_set)){
warn("Skipping non-ResultFeature ResultSet:\t".$rset->name);
next;
}
#Eventually will want to completely remove DB sets?
#Depends on how we handle 0bp window sets, BigWig?
#Leave 0bp sets in DB for v62 which means we need an extra status
#Assume all input_set rsets are file based
#NOTE:
#Don't need to check for packed_size and packed_template differences as they are now the
#same for all collections i.e. float. These would need to be separate queries otherwise.
#This method makes assumptions about the window_sizes array structure
#If this is to change more the the 0 - 30 bp change below then the config hash generation
#needs to be reviewed
if($rset->table_name eq 'experimental_chip'){ #Array Intensities i.e. single float
$Bio::EnsEMBL::Utils::Collector::window_sizes->[0] = 0;#Can have natural resolution for low density array data
}
elsif($rset->table_name eq 'input_set'){
$Bio::EnsEMBL::Utils::Collector::window_sizes->[0] = 30;
#Currently only expecting int from InputSet
my @isets = @{$rset->get_InputSets};
my @tmp_isets = grep { !/result/ } (map { $_->feature_class } @isets );
if(@tmp_isets){
throw("Bio::EnsEMBL::Funcgen::Collector::ResultFeature only supports result type InputSets, not @tmp_isets types");
}
#We still have no way of encoding pack_type for result_feature InputSets
@tmp_isets = grep { !/SEQUENCING/ } (map { $_->format } @isets);
if(@tmp_isets){
throw("Bio::EnsEMBL::Funcgen::Collector::ResultFeature only supports SEQUENCING format InputSets, not @tmp_isets formats");
}
}
else{
throw('Bio::EnsEMBL::Funcgen::Collector:ResultFeature does not support ResultSets of type'.$rset->table_name);
}
### SET ResultSet CONFIG BASED ON OPTIMAL WINDOW SIZE
# This sets all based on $rf_source=file
# For wsize==0 (experimental_chip), the rf_source is fixed after this loop
# This is done to prevent cyclical dependancy and improve cache checking speed
if( (defined $window_element ) &&
exists $wsize_config{$rf_source}{$Bio::EnsEMBL::Utils::Collector::window_sizes->[$window_element]} ){
$wsize_config{$rf_source}{$Bio::EnsEMBL::Utils::Collector::window_sizes->[$window_element]}{'result_sets'}{$rset->dbID} = $rset;
}
else{ #We have not seen this wsize before
#This is currently entirely based on the position of the first wsize.
#We can't strictly rely that the same window_element will be optimal for each collection
#However this will work if they are size ordered and only the first element changes e.g. 0 || 30
#Will need to do for each set if window_sizes change
if(! defined $window_element){
my @sizes = @{$self->window_sizes};
#we need to remove wsize 0 if ResultSet was generated from high density seq reads
#0 should always be first
shift @sizes if ($sizes[0] == 0 && ($rset->table_name eq 'input_set'));
$max_bins ||= 700;#This is default size of display?
#The speed of this track is directly proportional
#to the display size, unlike other tracks!
#e.g
#let's say we have 300000bp
#700 pixels will use 450 wsize > Faster but lower resolution
#2000 pixels will use 150 wsize > Slower but higher resolution
if(defined $window_size){
if(! grep { /^${window_size}$/ } @sizes){
warn "The ResultFeature window_size specifed($window_size) is not valid, the next largest will be chosen from:\t".join(', ', @sizes);
}
else{
$wsize = $window_size;
}
}
else{#! defined $window_size
#Work out window size here based on Slice length
#Select 0 wsize if slice is small enough
#As loop will never pick 0
#probably half 150 max length for current wsize
#Will also be proportional to display size
#This depends on size ordered window sizes arrays
$window_size = ($slice->length)/$max_bins;
if($Bio::EnsEMBL::Utils::Collector::window_sizes->[0] == 0){
my $zero_wsize_limit = ($max_bins * $sizes[1])/2;
if($slice->length <= $zero_wsize_limit){
$wsize = 0;
$window_element = 0;
}
}
}
#Let's try and avoid this loop if we have already grep'd or set to 0
#In the browser this is only ever likely to speed up the 0 window
if (! defined $wsize) {
#default is maximum
$wsize = $sizes[-1]; #Last element
#Try and find the next biggest window
#As we don't want more bins than there are pixels
for (my $i = 0; $i <= $#sizes; $i++) {
#We have problems here if we want to define just one window size
#In the store methods, this resets the wsizes so we can only pick from those
#specified, hence we cannot force the use of 0
#@sizes needs to always be the full range of valid windows sizes
#Need to always add 0 and skip_zero window if 0 not defined in window_sizes?
if ($window_size <= $sizes[$i]) {
$window_element = $i;
$wsize = $sizes[$i];
last;
}
}
}
}
else{ #ASSUME the same window_element has the optimal window_size
$wsize = $Bio::EnsEMBL::Utils::Collector::window_sizes->[$window_element];
}
#Set BLOB access & collection_start/end config
if ( $wsize == 0) {
$wsize_config{$rf_source}{$wsize}{scores_field} = 'rf.scores';
#No need to set start end config here as these are normal features
} else {
#We want a substring of a whole seq_region collection
#Correct to the nearest bin bounds
#int rounds towards 0, not always down!
#down if +ve or up if -ve
#This causes problems with setting start as we round up to zero
#Sub this lot as we will use it in the Collector for building indexes?
my $start_bin = $slice->start/$wsize;
$collection_start = int($start_bin);
#Add 1 here so we avoid multiply by 0 below
if ($collection_start < $start_bin) {
$collection_start +=1; #Add 1 to the bin due to int rounding down
}
$collection_start = ($collection_start * $wsize) - $wsize + 1 ; #seq_region
$collection_end = int($slice->end/$wsize) * $wsize; #This will be <= $slice->end
#Add another window if the end doesn't meet the end of the slice
if (($collection_end > 0) &&
($collection_end < $slice->end)) {
$collection_end += $wsize;
}
#Now correct for packed size
#Substring on a blob returns bytes not 2byte ascii chars!
#start at the first char of the first bin
my $sub_start = (((($collection_start - 1)/$wsize) * $self->packed_size) + 1); #add first char
#Default to 1 as mysql substring starts < 1 do funny things
$sub_start = 1 if $sub_start < 1;
my $sub_end = (($collection_end/$wsize) * ($self->packed_size));
#Set local start end config for collections
$wsize_config{$rf_source}{$wsize}{collection_start} = $collection_start;
$wsize_config{$rf_source}{$wsize}{collection_end} = $collection_end;
if($rf_source eq 'file'){ #file BLOB access config
$wsize_config{$rf_source}{$wsize}{'byte_offset'} = $sub_start -1; #offset is always start - 1
$wsize_config{$rf_source}{$wsize}{'byte_length'} = ($sub_end - $sub_start + 1);
#warn "byte_offset = $sub_start";
#warn "byte_length = ($sub_end - $sub_start + 1) => ". ($sub_end - $sub_start + 1);
}
else{ #DB BLOB access config
#Finally set scores column for fetch
$wsize_config{$rf_source}{$wsize}{scores_field} = "substring(rf.scores, $sub_start, ".
($sub_end - $sub_start + 1).')';
}
}
#Set the result_set and scores field config
#Would also need to set pack template here if this
#were to change between collections
$wsize_config{$rf_source}{$wsize}{result_sets}{$rset->dbID} = $rset;
}
}
#Fix the 0 wsize source as will be set to 'file' but should be 'db'
if(exists $wsize_config{'file'}{0}){
$wsize_config{'db'}{0} = $wsize_config{'file'}{0};
delete $wsize_config{'file'}{0};
if(keys(%{$wsize_config{'file'}}) == 0){
delete $wsize_config{'file'};
}
}
$self->{'_collection_config'} = \%wsize_config;
return $self->{'_collection_config'};
}
=head2 fetch_all_by_Slice_ResultSets
Arg[1] : Bio::EnsEMBL::Slice - Slice to retrieve results from
Arg[2] : ARRAYREF of Bio::EnsEMBL::Funcgen::ResultSets - ResultSet to retrieve results from
Arg[3] : OPTIONAL int - max bins, maximum number of scores required
Arg[4] : OPTIONAL int - window size, size of bin/window size in base pirs
Arg[5] : OPTIONAL string - sql contraint for use only with DB collections
Arg[6] : OPTIONAL hasref - config hash
Example : my %rfeatures = %{$rsa->fetch_all_by_Slice_ResultSets($slice, [@rsets])};
Description: Gets a list of lightweight ResultFeature collection(s) for the ResultSets and Slice passed.
Returntype : HASHREF of ResultSet keys with a LISTREF of ResultFeature collection values
Exceptions : Warns and skips ResultSets which are not RESULT_FEATURE_SETS.
Caller : general
Status : At risk
=cut
sub fetch_all_by_Slice_ResultSets{
my ($self, $slice, $rsets, $max_bins, $window_size, $orig_constraint) = @_;
$orig_constraint .= (defined $orig_constraint) ? ' AND ' : '';
#currently does not accomodate raw experimental_chip ResultSets!
my $conf = $self->set_collection_config_by_Slice_ResultSets($slice, $rsets, $max_bins, $window_size);
#Loop through each wsize build constraint set private vars and query
my (%rset_rfs, $constraint);
#Remove this block now we don't really support table based RFs
my $rf_conf = $conf->{db};
foreach my $wsize(keys(%{$rf_conf})){
$self->{'window_size'} = $wsize;
$_scores_field = $rf_conf->{$wsize}->{scores_field};
$constraint = 'rf.result_set_id IN ('.join(', ', keys(%{$rf_conf->{$wsize}->{result_sets}})).')'.
" AND rf.window_size=$wsize";
if ($wsize != 0){
$_collection_start = $rf_conf->{$wsize}->{collection_start};
$_collection_end = $rf_conf->{$wsize}->{collection_end};
}
my ($rset_results) = @{$self->fetch_all_by_Slice_constraint($slice, $orig_constraint.$constraint)};
#This maybe undef if the slice is not present
$rset_results ||= {};
#Will this work for wsize split queries?
#We are not setting values for empty queries
#Which is causing errors on deref
%rset_rfs = (%rset_rfs,
%{$rset_results});
#Account for DB rsets which return no features
foreach my $rset(values %{$rf_conf->{$wsize}{result_sets}}){
if(! exists $rset_rfs{$rset->dbID}){
$rset_rfs{$rset->dbID} = [];
}
}
}
#Two blocks to prevent extra if-conditional for each rset.
#Can easily remove one block if/when we deprecate DB collections
#Should always be the same wsize if we are using a file i.e. no 0bp
#Unless we have differing window_size ranges
my $rf;
$rf_conf = $conf->{file};
foreach my $wsize(keys(%{$rf_conf})){
foreach my $file_rset(values %{$rf_conf->{$wsize}{result_sets}}){
$rf = $self->_fetch_from_file_by_Slice_ResultSet($slice, $file_rset, $wsize, $rf_conf);
$rset_rfs{$file_rset->dbID} = defined($rf) ? [$rf] : [];
}
}
return \%rset_rfs;
}
=head2 _fetch_from_file_by_Slice_ResultSet
Arg[1] : Bio::EnsEMBL::Slice - Slice to retrieve results from
Arg[2] : Bio::EnsEMBL::Funcgen::ResultSets - ResultSet to retrieve results from
Arg[3] : int - valid window size defined by set_collection_config_by_ResultSets
Arg[4] : HASHREF - Window size config for file based ResultSets
Example : my $rfeat = $self->_fetch_from_file_by_Slice_ResultSet($slice, $rset, $wsize, $conf);
Description: Generates ResultFeature collection reading packed scores from a 'col' file.
Returntype : Bio::EnsEMBL::Funcgen::Collection::ResultFeature
Exceptions :
Caller : fetch_all_by_Slice_ResultSets
Status : At risk
=cut
#Set/store filepath in ResultSet to avoid having to regenerate?
sub _fetch_from_file_by_Slice_ResultSet{
my ($self, $slice, $rset, $window_size, $conf) = @_;
#private as window_size needs to ba valid i.e. generated by set_collection_config_by_ResultSets
#and no class tests
#Cache this as ResultSet::get_dbfile_path_prefix?
#Is there any point if the rsets aren't cached?
#Data is cached anyway, so no redundant calls
#ResultSets are always regenerated
#Key would either have to be query or dbID
#Former would be hard?(constraint key, is this already done for features?)
#Later would be object cache, so we would still do sql query but skip the object generation
#given the dbID is enough to pull a valid object from the cache
#How can we cache result/feature sets?
#Would this really speed anything up?
#if(! exists $conf->{$window_size}){
# throw("Specified window_size($window_size) is not present in config.\n".
# "Have you called this private method directly?\n".
# "Try using the fetch_by_Slice_ResultSets warpapper method\n".
# "Or set the RESULT_FEATURE_FILE_SET status and window_size correctly.");
# }
my $rf;
my $efg_sr_id = $self->get_seq_region_id_by_Slice($slice);
if($efg_sr_id){
my $packed_scores = $self->read_collection_blob
(
$rset->get_dbfile_path_by_window_size($window_size),
#Would be in analysis object for unique analysis tracks/data
$efg_sr_id,
$conf->{$window_size}{'byte_offset'},
$conf->{$window_size}{'byte_length'},
);
my ($start, $end, @scores);
if(defined $packed_scores){
($start, $end) = ($conf->{$window_size}{collection_start},
$conf->{$window_size}{collection_end});
#Need to capture unpack failure here and undef the fh?
#i.e. pack/unpack repeat count overflow
@scores = unpack('('.$self->pack_template.')'.(($end - $start + 1)/$window_size),
$packed_scores);
#could validate scores size here
#will only ever be <= than expected value
#as unpack will discard excess
#better validate length of $packed_scores
$rf = Bio::EnsEMBL::Funcgen::Collection::ResultFeature->new_fast
({
start => $start,
end => $end,
strand => 0, #These are strandless features
scores => [@scores],
window_size => $window_size,
});
}
}
return $rf;
}
=head2 fetch_all_by_Slice_ResultSet
Arg[1] : Bio::EnsEMBL::Slice - Slice to retrieve results from
Arg[2] : Bio::EnsEMBL::Funcgen::ResultSet - ResultSet to retrieve results from
Arg[3] : OPTIONAL int - max bins, maximum number of scores required
Arg[4] : OPTIONAL int - window size, size of bin/window size in base pirs
Arg[5] : OPTIONAL string - sql contraint for use only with DB collections
Arg[6] : OPTIONAL hasref - config hash
Example : my %rfeatures = %{$rsa->fetch_all_by_Slice_ResultSets($slice, [@rsets])};
Description: Gets a list of lightweight Collection of ResultFeatures for the ResultSet and Slice passed.
NOTE: ExperimentalChip/Channel based ResultFeatures was removed in version 63.
Returntype : Bio::EnsEMBL::Funcgen::Collection::ResultFeature
Exceptions : None
Caller : general
Status : At risk
=cut
#To do
#remove Bio::EnsEMBL::Funcgen::ResultFeature in favour of Collection::ResultFeature?
sub fetch_all_by_Slice_ResultSet{
my ($self, $slice, $rset, $max_bins, $window_size, $orig_constraint) = @_;
#Do this first to avoid double validation of rset
my $rf_hashref = $self->fetch_all_by_Slice_ResultSets($slice, [$rset], $max_bins, $window_size, $orig_constraint);
return $rf_hashref->{$rset->dbID};
}
sub fetch_Iterator_by_Slice_ResultSet{
my ($self, $slice, $rset, $max_bins, $window_size, $constraint, $chunk_size) = @_;
return $self->fetch_collection_Iterator_by_Slice_method
($self->can('fetch_all_by_Slice_ResultSet'),
[$slice, $rset, $max_bins, $window_size, $constraint],
0,#Slice idx
$chunk_size #Iterator chunk length
);
}
=head2 fetch_collection_Iterator_by_Slice_method
Arg [1] : CODE ref of Slice fetch method
Arg [2] : ARRAY ref of parameters for Slice fetch method
Arg [3] : Optional int: Slice index in parameters array
Arg [4] : Optional int: Slice chunk size. Default=500000
Example : my $slice_iter = $feature_adaptor->fetch_Iterator_by_Slice_method
($feature_adaptor->can('fetch_all_by_Slice_Arrays'),
\@fetch_method_params,
0,#Slice idx
#500 #chunk length
);
while(my $feature = $slice_iter->next && defined $feature){
#Do something here
}
Description: Creates an Iterator which chunks the query Slice to facilitate
large Slice queries which would have previously run out of memory
Returntype : Bio::EnsEMBL::Utils::Iterator
Exceptions : Throws if mandatory params not valid
Caller : general
Status : at risk - move to core BaseFeatureAdaptor
=cut
#Essentially the only difference here we have one feature with an array of 'scores'
sub fetch_collection_Iterator_by_Slice_method{
my ($self, $slice_method_ref, $params_ref, $slice_idx, $chunk_size) = @_;
if(! ( defined $slice_method_ref &&
ref($slice_method_ref) eq 'CODE')
){
throw('Must pass a valid Slice fetch method CODE ref');
}
if (! ($params_ref &&
ref($params_ref) eq 'ARRAY')) {
#Don't need to check size here so long as we have valid Slice
throw('You must pass a method params ARRAYREF');
}
$slice_idx = 0 if(! defined $slice_idx);
my $slice = $params_ref->[$slice_idx];
$chunk_size ||= 1000000;
my $collection;
my $finished = 0;
my $start = 1; #local coord for sub slice
my $end = $slice->length;
my $overlap = 0;
my $coderef =
sub {
my $collection;
if(! $finished) {
my $new_end = ($start + $chunk_size - 1);
if ($new_end >= $end) {
# this is our last chunk
$new_end = $end;
$finished = 1;
}
#Chunk by sub slicing
my $sub_slice = $slice->sub_Slice($start, $new_end);
$params_ref->[$slice_idx] = $sub_slice;
($collection) = @{ $slice_method_ref->($self, @$params_ref)};
if(! $collection){
$finished = 1;
}
else{
#Trim score and start if overlapping found
#Will only ever be on overlapping 'score'
if($overlap){
shift @{$collection->scores};
$collection->{start} = $collection->start + $collection->window_size;
$overlap = 0;
}
if ( $collection->end > $sub_slice->end ){
$overlap = 1;
}
$start = $new_end + 1;
}
}
return $collection;
};
return Bio::EnsEMBL::Utils::Iterator->new($coderef);
}
# Over-ride/deprecate generic methods
# which do not work with ResultFeature Collections
sub fetch_all{
deprecate('The fetch_all method has been disabled as it is not appropriate for the ResultFeatureAdaptor');
return;
}
sub fetch_by_dbID{
warn 'The fetch_by_dbID method has been disabled as it is not appropriate for the ResultFeatureAdaptor';
#Could use it for 0 wsize DB based data, but not useful.
return;
}
sub fetch_all_by_dbID_list {
warn 'The fetch_all_by_dbID_list method has been disabled as it is not appropriate for the ResultFeatureAdaptor';
#Could use it for 0 wsize DB based data, but not useful.
return;
}
sub fetch_all_by_logic_name {
warn 'The fetch_all_by_logic_name method has been disabled as it is not appropriate for the ResultFeatureAdaptor';
#Could use it for 0 wsize DB based data, but not useful.
return;
}
sub _list_seq_region_ids{
warn 'The _list_seq_region_ids method has been disabled as it is not appropriate for the ResultFeatureAdaptor';
#Could use it for 0 wsize DB based data, but not useful.
return
}
#Over-ride fetch_all_by_display_label? Or move this to the individual FeatureAdaptors?
#Same with fetch_all_by_stable_Storable_FeatureSEts and wrappers (fetch_all_by_external_name)?
#Basically this is not a DBAdaptor anymore so should inherit from somewhere else.
#Need to separate the common utility methods and have co-inheritance e.g.
#DBFile::Adaptor Utils::FeatureAdaptor
#DBAdaptor::Adaptor Utils::FeatureAdaptor
#Deprecated/Removed
=head2 resolve_replicates_by_ResultSet
Arg[0] : HASHREF - result_set_input_id => @scores pairs
#Arg[1] : Bio::EnsEMBL::Funcgen::ResultSet - ResultSet to retrieve results from
Example : my @rfeatures = @{$rsa->fetch_ResultFeatures_by_Slice_ResultSet($slice, $rset, 'DISPLAYABLE')};
Description: Gets a list of lightweight ResultFeatures from the ResultSet and Slice passed.
Replicates are combined using a median of biological replicates based on
their mean techinical replicate scores
Returntype : List of Bio::EnsEMBL::Funcgen::ResultFeature
Exceptions : None
Caller : general
Status : deprecated
=cut
sub resolve_replicates_by_ResultSet{
die('ExperimentalChip/Channel based ResultFeature support was removed in version 63');
}
=head2 fetch_results_by_probe_id_ResultSet
Arg [1] : int - probe dbID
Arg [2] : Bio::EnsEMBL::Funcgen::ResultSet
Example : my @probe_results = @{$ofa->fetch_results_by_ProbeFeature_ResultSet($pid, $result_set)};
Description: Gets result for a given probe in a ResultSet
Returntype : ARRAYREF
Exceptions : throws if args not valid
Caller : General
Status : deprecated
=cut
sub fetch_results_by_probe_id_ResultSet{
die('ExperimentalChip/Channel based ResultFeature support was removed in version 63');
}
1;
| adamsardar/perl-libs-custom | EnsemblAPI/ensembl-functgenomics/modules/Bio/EnsEMBL/Funcgen/DBSQL/ResultFeatureAdaptor.pm | Perl | apache-2.0 | 36,354 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V8::Enums::ConversionLagBucketEnum;
use strict;
use warnings;
use Const::Exporter enums => [
UNSPECIFIED => "UNSPECIFIED",
UNKNOWN => "UNKNOWN",
LESS_THAN_ONE_DAY => "LESS_THAN_ONE_DAY",
ONE_TO_TWO_DAYS => "ONE_TO_TWO_DAYS",
TWO_TO_THREE_DAYS => "TWO_TO_THREE_DAYS",
THREE_TO_FOUR_DAYS => "THREE_TO_FOUR_DAYS",
FOUR_TO_FIVE_DAYS => "FOUR_TO_FIVE_DAYS",
FIVE_TO_SIX_DAYS => "FIVE_TO_SIX_DAYS",
SIX_TO_SEVEN_DAYS => "SIX_TO_SEVEN_DAYS",
SEVEN_TO_EIGHT_DAYS => "SEVEN_TO_EIGHT_DAYS",
EIGHT_TO_NINE_DAYS => "EIGHT_TO_NINE_DAYS",
NINE_TO_TEN_DAYS => "NINE_TO_TEN_DAYS",
TEN_TO_ELEVEN_DAYS => "TEN_TO_ELEVEN_DAYS",
ELEVEN_TO_TWELVE_DAYS => "ELEVEN_TO_TWELVE_DAYS",
TWELVE_TO_THIRTEEN_DAYS => "TWELVE_TO_THIRTEEN_DAYS",
THIRTEEN_TO_FOURTEEN_DAYS => "THIRTEEN_TO_FOURTEEN_DAYS",
FOURTEEN_TO_TWENTY_ONE_DAYS => "FOURTEEN_TO_TWENTY_ONE_DAYS",
TWENTY_ONE_TO_THIRTY_DAYS => "TWENTY_ONE_TO_THIRTY_DAYS",
THIRTY_TO_FORTY_FIVE_DAYS => "THIRTY_TO_FORTY_FIVE_DAYS",
FORTY_FIVE_TO_SIXTY_DAYS => "FORTY_FIVE_TO_SIXTY_DAYS",
SIXTY_TO_NINETY_DAYS => "SIXTY_TO_NINETY_DAYS"
];
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V8/Enums/ConversionLagBucketEnum.pm | Perl | apache-2.0 | 1,882 |
package Paws::IAM::GetUserResponse;
use Moose;
has User => (is => 'ro', isa => 'Paws::IAM::User', required => 1);
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::IAM::GetUserResponse
=head1 ATTRIBUTES
=head2 B<REQUIRED> User => L<Paws::IAM::User>
A structure containing details about the IAM user.
=head2 _request_id => Str
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/IAM/GetUserResponse.pm | Perl | apache-2.0 | 406 |
# Ensembl module for Bio::EnsEMBL::Funcgen::BindingMatrixFrequencies
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2020] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 NAME
Bio::EnsEMBL::Funcgen::BindingMatrixFrequencies - A module to represent a BindingMatrixFrequencies.
In EFG this represents the binding affinities of a Transcription Factor to DNA.
=head1 SYNOPSIS
use Bio::EnsEMBL::Funcgen::BindingMatrixFrequencies;
# A C G T frequency matrix
my $freqs = "1126 6975 6741 2506 7171 0 11 13 812 867 899 1332
4583 0 99 1117 0 12 0 0 5637 1681 875 4568
801 181 268 3282 0 0 7160 7158 38 2765 4655 391
661 15 63 266 0 7159 0 0 684 1858 742 880";
my $bmfx = Bio::EnsEMBL::Funcgen::BindingMatrixFrequencies->new(
- binding_matrix => $binding_matrix,
- position => $position,
- nucleotide => $nucleotide
);
=head1 DESCRIPTION
This class represents information about a BindingMatrixFrequencies, containing the position
and nucleotide. A BindingMatrixFrequencies is always associated to a BindingMatrix
=head1 SEE ALSO
Bio::EnsEMBL::Funcgen::DBSQL::BindingMatrixFrequenciesAdaptor
Bio::EnsEMBL::Funcgen::DBSQL::BindingMatrix
Bio::EnsEMBL::Funcgen::MotifFeature
=cut
package Bio::EnsEMBL::Funcgen::BindingMatrixFrequencies;
use strict;
use warnings;
use Bio::EnsEMBL::Utils::Scalar qw( assert_ref check_ref );
use Bio::EnsEMBL::Utils::Argument qw( rearrange );
use Bio::EnsEMBL::Utils::Exception qw( throw deprecate);
use Bio::EnsEMBL::Funcgen::Sequencing::MotifTools qw( parse_matrix_line
reverse_complement_matrix );
use base qw( Bio::EnsEMBL::Funcgen::Storable );
=head2 new
Arg [-name] : Scalar - Name of matrix
Arg [-analysis] : Bio::EnsEMBL::Analysis - analysis describing how the matrix was obtained
Arg [-source] : String (Mandatory) - A string describing the source of the matrix, i.e. SELEX
Arg [-threshold] : Scalar (optional) - Numeric minimum relative affinity for binding sites of this matrix
Arg [-description]: Scalar (optional) - Descriptiom of matrix
Example : my $matrix = Bio::EnsEMBL::Funcgen::BindingMatrixFrequencies->new(
- binding_matrix => $binding_matrix,
- position => $position,
- nucleotide => $nucleotide
);
Description: Constructor method for BindingMatrixFrequencies class
Returntype : Bio::EnsEMBL::Funcgen::BindingMatrixFrequencies
Exceptions : Throws if name or/and type not defined
Caller : General
Status : Medium risk
=cut
sub new {
my $caller = shift;
my $obj_class = ref($caller) || $caller;
my $self = $obj_class->SUPER::new(@_);
my ( $position, $nucleotide, $frequency, $binding_matrix )
= rearrange(
[ 'POSITION', 'NUCLEOTIDE', 'FREQUENCY', 'BINDING_MATRIX' ], @_ );
throw('Must supply a -position parameter') if !defined $position;
throw('Must supply a -nucleotide parameter') if !defined $nucleotide;
throw('Must supply a -frequency parameter') if !defined $frequency;
if ($binding_matrix) {
assert_ref( $binding_matrix, 'Bio::EnsEMBL::Funcgen::BindingMatrix',
'BindingMatrix' );
}
$self->{position} = $position;
$self->{nucleotide} = $nucleotide;
$self->{frequency} = $frequency;
$self->{binding_matrix} = $binding_matrix;
return $self;
}
=head2 get_BindingMatrix
Example : my $binding_matrix = $bmf->get_BindingMatrix();
Description: Getter for the BindingMatrix object
Returntype : Bio::EnsEMBL::Funcgen::BindingMatrix
Exceptions : None
Caller : General
Status : Stable
=cut
sub get_BindingMatrix { return shift->{binding_matrix}; }
=head2 position
Example : my $position = $bmf->position();
Description: Getter for the position attribute
Returntype : Integer
Exceptions : None
Caller : General
Status : Stable
=cut
sub position { return shift->{position}; }
=head2 nucleotide
Example : my $nucleotide = $bmf->nucleotide();
Description: Getter for the nucleotide attribute
Returntype : String
Exceptions : None
Caller : General
Status : Stable
=cut
sub nucleotide { return shift->{nucleotide}; }
=head2 frequency
Example : my $frequency = $bmf->frequency();
Description: Getter for the frequency attribute
Returntype : Integer
Exceptions : None
Caller : General
Status : Stable
=cut
sub frequency { return shift->{frequency}; }
1;
| Ensembl/ensembl-funcgen | modules/Bio/EnsEMBL/Funcgen/BindingMatrixFrequencies.pm | Perl | apache-2.0 | 5,736 |
package Search::Elasticsearch::Role::Is_Sync;
$Search::Elasticsearch::Role::Is_Sync::VERSION = '1.17';
use Moo::Role;
use namespace::clean;
1;
# ABSTRACT: A role to mark classes which should be used with other sync classes
__END__
=pod
=encoding UTF-8
=head1 NAME
Search::Elasticsearch::Role::Is_Sync - A role to mark classes which should be used with other sync classes
=head1 VERSION
version 1.17
=head1 AUTHOR
Clinton Gormley <drtech@cpan.org>
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2014 by Elasticsearch BV.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
=cut
| gitpan/Search-Elasticsearch | lib/Search/Elasticsearch/Role/Is_Sync.pm | Perl | apache-2.0 | 641 |
use utf8;
package Bio::EnsEMBL::RNAseqDB::Schema::Result::Experiment;
# Created by DBIx::Class::Schema::Loader
# DO NOT MODIFY THE FIRST PART OF THIS FILE
=head1 NAME
Bio::EnsEMBL::RNAseqDB::Schema::Result::Experiment
=cut
use strict;
use warnings;
use base 'DBIx::Class::Core';
=head1 TABLE: C<experiment>
=cut
__PACKAGE__->table("experiment");
=head1 ACCESSORS
=head2 experiment_id
data_type: 'integer'
extra: {unsigned => 1}
is_auto_increment: 1
is_nullable: 0
=head2 study_id
data_type: 'integer'
extra: {unsigned => 1}
is_foreign_key: 1
is_nullable: 0
=head2 experiment_sra_acc
data_type: 'char'
is_nullable: 1
size: 12
=head2 experiment_private_acc
data_type: 'char'
is_nullable: 1
size: 12
=head2 title
data_type: 'text'
is_nullable: 1
=head2 metasum
data_type: 'char'
is_nullable: 1
size: 32
=head2 date
data_type: 'timestamp'
datetime_undef_if_invalid: 1
default_value: current_timestamp
is_nullable: 1
=head2 status
data_type: 'enum'
default_value: 'ACTIVE'
extra: {list => ["ACTIVE","RETIRED"]}
is_nullable: 1
=cut
__PACKAGE__->add_columns(
"experiment_id",
{
data_type => "integer",
extra => { unsigned => 1 },
is_auto_increment => 1,
is_nullable => 0,
},
"study_id",
{
data_type => "integer",
extra => { unsigned => 1 },
is_foreign_key => 1,
is_nullable => 0,
},
"experiment_sra_acc",
{ data_type => "char", is_nullable => 1, size => 12 },
"experiment_private_acc",
{ data_type => "char", is_nullable => 1, size => 12 },
"title",
{ data_type => "text", is_nullable => 1 },
"metasum",
{ data_type => "char", is_nullable => 1, size => 32 },
"date",
{
data_type => "timestamp",
datetime_undef_if_invalid => 1,
default_value => \"current_timestamp",
is_nullable => 1,
},
"status",
{
data_type => "enum",
default_value => "ACTIVE",
extra => { list => ["ACTIVE", "RETIRED"] },
is_nullable => 1,
},
);
=head1 PRIMARY KEY
=over 4
=item * L</experiment_id>
=back
=cut
__PACKAGE__->set_primary_key("experiment_id");
=head1 UNIQUE CONSTRAINTS
=head2 C<experiment_private_acc>
=over 4
=item * L</experiment_private_acc>
=back
=cut
__PACKAGE__->add_unique_constraint("experiment_private_acc", ["experiment_private_acc"]);
=head2 C<experiment_sra_acc>
=over 4
=item * L</experiment_sra_acc>
=back
=cut
__PACKAGE__->add_unique_constraint("experiment_sra_acc", ["experiment_sra_acc"]);
=head2 C<metasum>
=over 4
=item * L</metasum>
=back
=cut
__PACKAGE__->add_unique_constraint("metasum", ["metasum"]);
=head1 RELATIONS
=head2 runs
Type: has_many
Related object: L<Bio::EnsEMBL::RNAseqDB::Schema::Result::Run>
=cut
__PACKAGE__->has_many(
"runs",
"Bio::EnsEMBL::RNAseqDB::Schema::Result::Run",
{ "foreign.experiment_id" => "self.experiment_id" },
{ cascade_copy => 0, cascade_delete => 0 },
);
=head2 study
Type: belongs_to
Related object: L<Bio::EnsEMBL::RNAseqDB::Schema::Result::Study>
=cut
__PACKAGE__->belongs_to(
"study",
"Bio::EnsEMBL::RNAseqDB::Schema::Result::Study",
{ study_id => "study_id" },
{ is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" },
);
# Created by DBIx::Class::Schema::Loader v0.07047 @ 2017-12-05 09:59:58
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:RzXPBNWXEkB8IUpp6cZzAQ
# You can replace this text with custom code or comments, and it will be preserved on regeneration
1;
| MatBarba/vb-rnaseqdb | lib/Bio/EnsEMBL/RNAseqDB/Schema/Result/Experiment.pm | Perl | apache-2.0 | 3,462 |
#
# Ensembl module for Bio::EnsEMBL::DBSQL::Funcgen::ProbeFeatureAdaptor
#
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2020] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=head1 NAME
Bio::EnsEMBL::DBSQL::Funcgen::ProbeFeatureAdaptor - A database adaptor for fetching and
storing ProbeFeature objects.
=head1 SYNOPSIS
my $ofa = $db->get_ProbeFeatureAdaptor();
my $features = $ofa->fetch_all_by_Probe($probe);
$features = $ofa->fetch_all_by_Slice_arrayname($slice, 'Array-1', 'Array-2');
=head1 DESCRIPTION
The ProbeFeatureAdaptor is a database adaptor for storing and retrieving
ProbeFeature objects.
=head1 SEE ALSO
Bio::EnsEMBL::Funcgen::ProbeFeature
=cut
package Bio::EnsEMBL::Funcgen::DBSQL::ProbeFeatureAdaptor;
use strict;
use warnings;
use Bio::EnsEMBL::Utils::Exception qw( throw deprecate );
use Bio::EnsEMBL::Funcgen::ProbeFeature;
use Bio::EnsEMBL::Funcgen::DBSQL::BaseFeatureAdaptor;#DBI sql_types import
use base qw(Bio::EnsEMBL::Funcgen::DBSQL::BaseFeatureAdaptor);
my $true_final_clause = ' ORDER BY pf.seq_region_id, pf.seq_region_start, pf.probe_feature_id';
my $final_clause = $true_final_clause;
=head2 fetch_all_by_Probe
Arg [1] : Bio::EnsEMBL::Funcgen::Probe
Example : my $features = $ofa->fetch_all_by_Probe($probe);
Description: Fetchs all features that a given probe creates.
Returntype : Listref of Bio::EnsEMBL::PasteFeature objects
Exceptions : Throws if argument is not a stored Probe object
Caller : Probe->get_all_ProbeFeatures()
Status : At Risk
=cut
sub fetch_all_by_Probe {
my ($self, $probe) = @_;
if (! (ref($probe) && $probe->isa('Bio::EnsEMBL::Funcgen::Probe'))) {
throw('fetch_all_by_Probe requires a Bio::EnsEMBL::Funcgen::Probe object');
}
if ( !defined $probe->dbID() ) {
throw('fetch_all_by_Probe requires a stored Bio::EnsEMBL::Funcgen::Probe object');
}
return $self->fetch_all_by_probe_id($probe->dbID);
}
=head2 fetch_all_by_probe_id
Arg [1] : int - Probe dbID
Example : my @features = @{$ofa->fetch_all_by_Probe_id($pid)};
Description: Fetchs all features that a given probe creates.
Returntype : Listref of Bio::EnsEMBL::PasteFeature objects
Exceptions : Throws if argument not defined
Caller : Probe->get_all_ProbeFeatures()
Status : At Risk
=cut
sub fetch_all_by_probe_id {
my ($self, $pid) = @_;
if ( ! defined $pid ) {
throw('Need to specify a probe _id');
}
my $constraint = " pf.probe_id=$pid";
$final_clause = ' GROUP by pf.probe_feature_id '.$final_clause;
my $features = $self->generic_fetch($constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
=head2 fetch_all_by_probeset_name
Arg [1] : String - probeset name
Arg [2] : ARRAYREF (optional) - Bio::EnsEMBL::CoordSystem objects
Example : my $features = $ofa->fetch_all_by_probeset('Set-1');
Description: Fetchs all features that a given probeset creates.
Returntype : Listref of Bio::EnsEMBL::ProbeFeature objects
Exceptions : Throws if no probeset argument
Caller : General
Status : At Risk - add vendor/class to this?
=cut
sub fetch_all_by_probeset_name {
my $self = shift;
my $probe_set_name = shift;
if (! $probe_set_name) {
throw('fetch_all_by_probeset requires a probe set name argument');
}
$self->_tables(
[
[ 'probe_set', 'ps' ],
[ 'probe', 'p' ]
]
);
my $constraint = join ' and ', (
'ps.name = ?',
'ps.probe_set_id = p.probe_set_id',
'pf.probe_id = p.probe_id',
);
$final_clause = ' GROUP by pf.probe_feature_id ' . $final_clause;
$self->bind_param_generic_fetch(
$probe_set_name,
SQL_VARCHAR
);
my $features = $self->generic_fetch($constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
# Replacement for
# https://github.com/Ensembl/ensembl-webcode/blob/release/95/modules/EnsEMBL/Web/Factory/Feature.pm#L154
sub fetch_all_by_array_name_probe_name {
my $self = shift;
my $array_name = shift;
my $probe_name = shift;
if (! $array_name) {
throw('fetch_all_by_array_name_probe_name requires a probe set name argument');
}
if (! $probe_name) {
throw('fetch_all_by_array_name_probe_name requires a probe name argument');
}
$self->_tables(
[
[ 'array', 'a' ],
[ 'array_chip', 'ac' ],
[ 'probe', 'p' ]
]
);
my $constraint = join ' and ', (
'a.name = ?',
'p.name = ?',
'a.array_id = ac.array_id ',
'ac.array_chip_id = p.array_chip_id ',
'p.probe_id = pf.probe_id',
);
$final_clause = ' GROUP by pf.probe_feature_id ' . $final_clause;
$self->bind_param_generic_fetch(
$array_name,
SQL_VARCHAR
);
$self->bind_param_generic_fetch(
$probe_name,
SQL_VARCHAR
);
my $features = $self->generic_fetch($constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
sub fetch_all_by_array_chip_name_probe_name {
my $self = shift;
my $array_chip_name = shift;
my $probe_name = shift;
if (! $array_chip_name) {
throw('fetch_all_by_array_chip_name_probe_name requires an array chip name argument');
}
if (! $probe_name) {
throw('fetch_all_by_array_chip_name_probe_name requires a probe name argument');
}
$self->_tables(
[
[ 'array_chip', 'ac' ],
[ 'probe', 'p' ]
]
);
my $constraint = join ' and ', (
'ac.name = ?',
'p.name = ?',
'ac.array_chip_id = p.array_chip_id ',
'p.probe_id = pf.probe_id',
);
$final_clause = ' GROUP by pf.probe_feature_id ' . $final_clause;
$self->bind_param_generic_fetch(
$array_chip_name,
SQL_VARCHAR
);
$self->bind_param_generic_fetch(
$probe_name,
SQL_VARCHAR
);
my $features = $self->generic_fetch($constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
sub fetch_all_by_array_name_probeset_name {
my $self = shift;
my $array_name = shift;
my $probe_set_name = shift;
if (! $array_name) {
throw('fetch_all_by_probeset requires a probe set name argument');
}
if (! $probe_set_name) {
throw('fetch_all_by_probeset requires a probe set name argument');
}
$self->_tables(
[
[ 'array', 'a' ],
[ 'array_chip', 'ac' ],
[ 'probe_set', 'ps' ],
[ 'probe', 'p' ]
]
);
my $constraint = join ' and ', (
'a.name = ?',
'ps.name = ?',
'a.array_id = ac.array_id ',
'ac.array_chip_id = ps.array_chip_id ',
'ps.probe_set_id = p.probe_set_id',
'pf.probe_id = p.probe_id',
);
$final_clause = ' GROUP by pf.probe_feature_id ' . $final_clause;
$self->bind_param_generic_fetch(
$array_name,
SQL_VARCHAR
);
$self->bind_param_generic_fetch(
$probe_set_name,
SQL_VARCHAR
);
my $features = $self->generic_fetch($constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
sub fetch_all_by_array_chip_name_probeset_name {
my $self = shift;
my $array_chip_name = shift;
my $probe_set_name = shift;
if (! $array_chip_name) {
throw('fetch_all_by_array_chip_name_probeset_name requires an array chip name argument');
}
if (! $probe_set_name) {
throw('fetch_all_by_array_chip_name_probeset_name requires a probe set name argument');
}
$self->_tables(
[
[ 'array_chip', 'ac' ],
[ 'probe_set', 'ps' ],
[ 'probe', 'p' ]
]
);
my $constraint = join ' and ', (
'ac.name = ?',
'ps.name = ?',
'ac.array_chip_id = ps.array_chip_id ',
'ps.probe_set_id = p.probe_set_id',
'pf.probe_id = p.probe_id',
);
$final_clause = ' GROUP by pf.probe_feature_id ' . $final_clause;
$self->bind_param_generic_fetch(
$array_chip_name,
SQL_VARCHAR
);
$self->bind_param_generic_fetch(
$probe_set_name,
SQL_VARCHAR
);
my $features = $self->generic_fetch($constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
=head2 fetch_all_by_ProbeSet
Arg [1] : Bio::EnsEMBL::Funcgen::ProbeSet
Arg [2] : ARRAYREF (optional) - Bio::EnsEMBL::CoordSystem objects
Example : my @features = @{$probe_feature_adaptor->fetch_all_by_ProbeSet($pset)};
Description: Fetches all ProbeFeatures from a given ProbeSet.
Returntype : ARRAYREF of Bio::EnsEMBL::Funcgen::ProbeFeature objects
Exceptions : Throws if no probeset argument
Caller : General
=cut
sub fetch_all_by_ProbeSet {
my $self = shift;
my $probe_set = shift;
$self->db->is_stored_and_valid('Bio::EnsEMBL::Funcgen::ProbeSet', $probe_set);
$self->_tables([[ 'probe', 'p' ]]);
my $constraint = ' pf.probe_id = p.probe_id and p.probe_set_id = ? ';
$final_clause = ' GROUP by pf.probe_feature_id ' . $final_clause;
$self->bind_param_generic_fetch(
$probe_set->dbID,
SQL_INTEGER
);
my $features = $self->generic_fetch($constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
=head2 fetch_all_by_Slice_array_vendor
Arg [1] : Bio::EnsEMBL::Slice
Arg [2] : string - array name e.g. HG-U133A
Arg [3] : string - vendor e.g. AFFY
Example : my $slice = $sa->fetch_by_region('chromosome', '1');
my $features = $ofa->fetch_by_Slice_array_vendor($slice, $array_name, $vendor_name);
Description: Retrieves a list of features on a given slice that are created
by probes from the specified array.
Returntype : Listref of Bio::EnsEMBL::Funcgen::ProbeFeature objects
Exceptions : Throws if no array name is provided
Caller : Used by web
Status : At Risk
=cut
sub fetch_all_by_Slice_array_vendor {
my ($self, $slice, $array, $vendor) = @_;
if(! ($array && $vendor)){
throw('You must provide and array name and a vendor name');
}
$self->_tables([['array', 'a'], ['array_chip', 'ac'], [ 'probe', 'p' ]]);
#Need to protect against SQL injection here due to text params
#my $constraint = ' a.name=? and a.vendor=? and a.array_id=ac.array_id and ac.array_chip_id=p.array_chip_id and pf.probe_id = p.probe_id';
my $constraint = ' a.name= \'' . $array . '\' and a.vendor= \'' . $vendor . '\' and a.array_id=ac.array_id and ac.array_chip_id=p.array_chip_id and pf.probe_id = p.probe_id';
$final_clause = ' GROUP by pf.probe_feature_id '.$final_clause;
#$self->bind_param_generic_fetch($array, SQL_VARCHAR);
#$self->bind_param_generic_fetch($vendor, SQL_VARCHAR);
my $features = $self->SUPER::fetch_all_by_Slice_constraint($slice, $constraint);
$self->reset_true_tables;
$final_clause = $true_final_clause;
return $features;
}
=head2 _true_tables
Args : None
Example : None
Description: Returns the names and aliases of the tables to use for queries.
Returntype : List of listrefs of strings
Exceptions : None
Caller : Internal
Status : At Risk
=cut
sub _true_tables {
return ([ 'probe_feature', 'pf' ]);
}
=head2 fetch_all_by_transcript_stable_id
Arg [1] : string - transcript stable id
Example : my $probeset_list = $probeset_adaptor->fetch_all_by_transcript_stable_id('ENST00000489935');
Description: Fetches all probesets that have been mapped to this transcript by the
probe2transcript step in the probemapping pipeline.
Returntype : Arrayref
Caller : General
=cut
sub fetch_all_by_transcript_stable_id {
my $self = shift;
my $transcript_stable_id = shift;
my $probe_feature_transcript_mappings = $self->db->get_ProbeFeatureTranscriptMappingAdaptor->fetch_all_by_transcript_stable_id($transcript_stable_id);
if (! defined $probe_feature_transcript_mappings) {
return [];
}
my @probe_features_mapped_to_transcript;
foreach my $current_probeset_transcript_mapping (@$probe_feature_transcript_mappings) {
push @probe_features_mapped_to_transcript,
$self->fetch_by_dbID($current_probeset_transcript_mapping->probe_feature_id);
}
return \@probe_features_mapped_to_transcript;
}
=head2 _columns
Args : None
Example : None
Description: PROTECTED implementation of superclass abstract method.
Returns a list of columns to use for queries.
Returntype : List of strings
Exceptions : None
Caller : Internal
Status : At Risk
=cut
sub _columns {
return qw(
pf.probe_feature_id pf.seq_region_id
pf.seq_region_start pf.seq_region_end
pf.seq_region_strand pf.probe_id
pf.analysis_id pf.mismatches
pf.cigar_line pf.hit_id
pf.source
);
}
=head2 _final_clause
Args : None
Example : None
Description: PROTECTED implementation of superclass abstract method.
Returns an ORDER BY clause. Sorting by probe_feature_id would be
enough to eliminate duplicates, but sorting by location might
make fetching features on a slice faster.
Returntype : String
Exceptions : None
Caller : generic_fetch
Status : At Risk
=cut
sub _final_clause {
return $final_clause;
}
=head2 _objs_from_sth
Arg [1] : DBI statement handle object
Example : None
Description: PROTECTED implementation of superclass abstract method.
Creates ProbeFeature objects from an executed DBI statement
handle.
Returntype : Listref of Bio::EnsEMBL::ProbeFeature objects
Exceptions : None
Caller : Internal
Status : At Risk
=cut
sub _objs_from_sth {
my ($self, $sth, $mapper, $dest_slice) = @_;
#For EFG this has to use a dest_slice from core/dnaDB whether specified or not.
#So if it not defined then we need to generate one derived from the species_name and schema_build of the feature we're retrieving.
# This code is ugly because caching is used to improve speed
my $sa = $self->db->dnadb->get_SliceAdaptor;
$sa = $dest_slice->adaptor->db->get_SliceAdaptor() if($dest_slice);#don't really need this if we're using DNADBSliceAdaptor?
#Some of this in now probably overkill as we'll always be using the DNADB as the slice DB
#Hence it should always be on the same coord system, unless we're projecting
my $aa = $self->db->get_AnalysisAdaptor();
my @features;
my (%analysis_hash, %slice_hash, %sr_name_hash, %sr_cs_hash);
my (
$probe_feature_id, $seq_region_id,
$seq_region_start, $seq_region_end,
$seq_region_strand, $mismatches,
$probe_id, $analysis_id,
$probe_name, $cigar_line,
$probeset_id, $hit_id,
$source
);
$sth->bind_columns(
\$probe_feature_id, \$seq_region_id,
\$seq_region_start, \$seq_region_end,
\$seq_region_strand, \$probe_id,
\$analysis_id, \$mismatches,
\$cigar_line, \$hit_id,
\$source
);
my ($asm_cs, $cmp_cs, $asm_cs_name, $asm_cs_vers ,$cmp_cs_name, $cmp_cs_vers);
if ($mapper) {
$asm_cs = $mapper->assembled_CoordSystem();
$cmp_cs = $mapper->component_CoordSystem();
$asm_cs_name = $asm_cs->name();
$asm_cs_vers = $asm_cs->version();
$cmp_cs_name = $cmp_cs->name();
$cmp_cs_vers = $cmp_cs->version();
}
my ($dest_slice_start, $dest_slice_end, $dest_slice_strand);
my ($dest_slice_length, $dest_slice_sr_name);
if ($dest_slice) {
$dest_slice_start = $dest_slice->start();
$dest_slice_end = $dest_slice->end();
$dest_slice_strand = $dest_slice->strand();
$dest_slice_length = $dest_slice->length();
$dest_slice_sr_name = $dest_slice->seq_region_name();
}
#This has already been done by
#build seq_region_cache based on slice
#$self->build_seq_region_cache_by_Slice($slice);
my $last_pfid;
FEATURE: while ( $sth->fetch() ) {
#Need to build a slice adaptor cache here?
#Would only ever want to do this if we enable mapping between assemblies??
#Or if we supported the mapping between cs systems for a given schema_build, which would have to be handled by the core api
#This is only required due to multiple records being returned
#From nr probe entries due to being present on multiple ArrayChips
#Group instead?
next if($last_pfid && ($last_pfid == $probe_feature_id));
$last_pfid = $probe_feature_id;
# Get the analysis object
my $analysis = $analysis_hash{$analysis_id} ||= $aa->fetch_by_dbID($analysis_id);
# Get the slice object
my $slice = $slice_hash{'ID:'.$seq_region_id};
if (!$slice) {
$slice = $sa->fetch_by_seq_region_id($seq_region_id);
if(! $slice){
warn "Cannot get slice for seq_region_id $seq_region_id for probe_feature $probe_feature_id";
}
$slice_hash{'ID:'.$seq_region_id} = $slice;
$sr_name_hash{$seq_region_id} = $slice->seq_region_name();
$sr_cs_hash{$seq_region_id} = $slice->coord_system();
}
#need to check once more here as it may not be in the DB,
#i.e. a supercontig(non-versioned) may have been deleted between releases
my $sr_name = $sr_name_hash{$seq_region_id};
my $sr_cs = $sr_cs_hash{$seq_region_id};
# Remap the feature coordinates to another coord system if a mapper was provided
if ($mapper) {
throw("Not yet implmented mapper, check equals are Funcgen calls too!");
($sr_name, $seq_region_start, $seq_region_end, $seq_region_strand)
= $mapper->fastmap($sr_name, $seq_region_start, $seq_region_end, $seq_region_strand, $sr_cs);
# Skip features that map to gaps or coord system boundaries
next FEATURE if !defined $sr_name;
# Get a slice in the coord system we just mapped to
if ( $asm_cs == $sr_cs || ( $cmp_cs != $sr_cs && $asm_cs->equals($sr_cs) ) ) {
$slice = $slice_hash{"NAME:$sr_name:$cmp_cs_name:$cmp_cs_vers"}
||= $sa->fetch_by_region($cmp_cs_name, $sr_name, undef, undef, undef, $cmp_cs_vers);
} else {
$slice = $slice_hash{"NAME:$sr_name:$asm_cs_name:$asm_cs_vers"}
||= $sa->fetch_by_region($asm_cs_name, $sr_name, undef, undef, undef, $asm_cs_vers);
}
}
# If a destination slice was provided convert the coords
# If the destination slice starts at 1 and is forward strand, nothing needs doing
if ($dest_slice) {
unless ($dest_slice_start == 1 && $dest_slice_strand == 1) {
if ($dest_slice_strand == 1) {
$seq_region_start = $seq_region_start - $dest_slice_start + 1;
$seq_region_end = $seq_region_end - $dest_slice_start + 1;
} else {
my $tmp_seq_region_start = $seq_region_start;
$seq_region_start = $dest_slice_end - $seq_region_end + 1;
$seq_region_end = $dest_slice_end - $tmp_seq_region_start + 1;
$seq_region_strand *= -1;
}
}
# Throw away features off the end of the requested slice
next FEATURE if $seq_region_end < 1 || $seq_region_start > $dest_slice_length
|| ( $dest_slice_sr_name ne $sr_name );
$slice = $dest_slice;
}
push @features, Bio::EnsEMBL::Funcgen::ProbeFeature->new_fast
({
'start' => $seq_region_start,
'end' => $seq_region_end,
'strand' => $seq_region_strand,
'slice' => $slice,
'analysis' => $analysis,#we should lazy load this from analysis adaptor cache?
'adaptor' => $self,
'dbID' => $probe_feature_id,
'mismatchcount' => $mismatches,
'cigar_string' => $cigar_line,
'probe_id' => $probe_id,
'hit_id' => $hit_id,
'source' => $source,
# #Do these need to be private?
# '_probe_set_id' => $probeset_id,#Used for linking feature glyphs
# '_probe_name' => $probe_name,#?? There can be >1. Is this for array design purposes?
} );
}
return \@features;
}
=head2 store
Args : List of Bio::EnsEMBL::Funcgen::ProbeFeature objects
Example : $ofa->store(@features);
Description: Stores given ProbeFeature objects in the database. Should only
be called once per feature because no checks are made for
duplicates. Sets dbID and adaptor on the objects that it stores.
Returntype : None
Exceptions : Throws if a list of ProbeFeature objects is not provided or if
an analysis is not attached to any of the objects
Caller : General
Status : At Risk
=cut
sub store{
my ($self, @ofs) = @_;
if (scalar(@ofs) == 0) {
throw('Must call store with a list of ProbeFeature objects');
}
my $sth = $self->prepare("
INSERT INTO probe_feature (
seq_region_id, seq_region_start,
seq_region_end, seq_region_strand,
probe_id, analysis_id,
mismatches, cigar_line, hit_id, source
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
my $db = $self->db();
my $analysis_adaptor = $db->get_AnalysisAdaptor();
FEATURE: foreach my $of (@ofs) {
if( ! ref $of || ! $of->isa('Bio::EnsEMBL::Funcgen::ProbeFeature') ) {
throw('Feature must be an ProbeFeature object');
}
if ( $of->is_stored($db) ) {
warn('ProbeFeature [' . $of->dbID() . '] is already stored in the database');
next FEATURE;
}
if ( !defined $of->analysis() ) {
throw('An analysis must be attached to the ProbeFeature objects to be stored.');
}
# Store the analysis if it has not been stored yet
if ( !$of->analysis->is_stored($db) ) {
$analysis_adaptor->store( $of->analysis() );
}
my $seq_region_id;
($of, $seq_region_id) = $self->_pre_store($of);
$sth->bind_param( 1, $seq_region_id, SQL_INTEGER);
$sth->bind_param( 2, $of->start(), SQL_INTEGER);
$sth->bind_param( 3, $of->end(), SQL_INTEGER);
$sth->bind_param( 4, $of->strand(), SQL_TINYINT);
$sth->bind_param( 5, $of->probe_id(), SQL_INTEGER);
$sth->bind_param( 6, $of->analysis->dbID(), SQL_INTEGER);
$sth->bind_param( 7, $of->mismatchcount(), SQL_TINYINT);
$sth->bind_param( 8, $of->cigar_string(), SQL_VARCHAR);
$sth->bind_param( 9, $of->hit_id(), SQL_VARCHAR);
$sth->bind_param(10, $of->source(), SQL_VARCHAR);
$sth->execute();
$of->dbID( $self->last_insert_id );
$of->adaptor($self);
}
#No need to return this really as the dbID and adaptor has been
#updated in the passed arrays of features via the object
#reference
return \@ofs
}
1;
| Ensembl/ensembl-funcgen | modules/Bio/EnsEMBL/Funcgen/DBSQL/ProbeFeatureAdaptor.pm | Perl | apache-2.0 | 23,223 |
package Parakeet::Generator::List;
use strict;
use warnings;
use utf8;
use v5.12;
use Parakeet::Xml;
use Misc::DmUtil::Data qw(notEmpty);
# Build
sub build
{
my $this = shift;
my $log = $this->{log};
$log->debug("Start");
my @all = @{$this->{content}};
$log->debug("all.size=[".(scalar @all)."]");
my @batches;
# split into batches
while (@all)
{
my @batch = ($this->{perPage} > 0 ? splice @all, 0, $this->{perPage} : splice @all);
push @batches, \@batch;
}
$log->debug("batches.size=[".(scalar @batches)."]");
my $globalCount = 0;
for (my $page = 0; $page < @batches; ++$page)
{
$log->debug("page=[$page]");
my $pageNumber = $page + 1;
my $batch = $batches[$page];
my $body = "";
# Create title
$body .= "title: ".$this->{title};
if ($page > 0)
{
$body .= " - Page $pageNumber";
}
$body .= "\n";
$body .= "markup: xml\n";
# End header
$body .= "---\n";
# Prev/next result page navigation
my %nav;
my $pagedNav = "";
if (@batches > 1)
{
$log->debug("Want page navigation");
$pagedNav .= '<div class="pk-paged-nav">';
if ($page > 0)
{
my $prevAddress = $this->pageAddress($page - 1);
$pagedNav .= '<span class="pk-paged-nav-prev">« <pk:a pk:href="';
$pagedNav .= $prevAddress->asString();
$pagedNav .= '">Previous</pk:a></span>';
$nav{prev} = { address => $prevAddress, title => "Previous results" };
}
if ($page < @batches - 1)
{
my $nextAddress = $this->pageAddress($page + 1);
$pagedNav .= '<span class="pk-paged-nav-next"><pk:a pk:href="';
$pagedNav .= $nextAddress->asString();
$pagedNav .= '">Next</pk:a> »</span>';
$nav{next} = { address => $nextAddress, title => "Next results" };
}
$pagedNav .= '</div>';
}
$body .= $pagedNav;
$body .= "<div class=\"pk-contentlist\">";
# content in batch
foreach my $content (@{$batch})
{
my $address = $content->address()->asString();
my $key = $content->key();
my $title = $content->title();
my $titleHtml = Parakeet::Xml::escape($title);
$log->debug("key=[".$content->key()."], title=[$title], titleHtml=[$titleHtml], address=[$address]");
++$globalCount;
$log->debug("globalCount=[$globalCount]");
my $number = $this->{number} ? "$globalCount. " : "";
$body .= '<section><div class="pk-contentlist-item">';
#my $focusImage = $content->focusImage();
#if ($focusImage)
#{
# $body .= '<div class="pk-contentlist-item-image">';
# $body .= "<pk:image><pk:imageBody pk:src=\"".$focusImage->address()."\" pk:alt=\"\"/></pk:image>";
# $body .= '</div>';
#}
$body .= '<div class="pk-contentlist-item-title">';
# title
$body .= '<pk:a pk:href="';
$body .= $address;
$body .= '" class="pk-link-silent" title="';
$body .= $titleHtml;
$body .= '">';
$body .= '<h2>'.$number.$titleHtml.'</h2>';
$body .= '</pk:a></div>';
# summary
if ($this->{summary} < 1 || $globalCount <= $this->{summary})
{
my $summaryContent;
if ($content->type() eq "page")
{
$summaryContent = "<pk:summaryInclude pk:src=\"".$content->address()."\" />";
}
if (notEmpty($summaryContent))
{
$body .= '<div class="pk-contentlist-item-preview">';
$body .= $summaryContent;
$body .= '</div>';
}
}
# main link
$body .= '<div class="pk-contentlist-item-link"><pk:a pk:href="';
$body .= $address;
$body .= '" title="';
$body .= $titleHtml;
$body .= '">'.Parakeet::Xml::escape($this->{readLinkText}).'</pk:a></div>';
my $published = $content->publishedTime();
if ($published)
{
$body .= "<div class=\"pk-contentlist-item-date\">".$published->toHtmlString(time => 0)."</div>";
}
$body .= '</div></section>';
}
$body .= "</div>";
$body .= $pagedNav;
my $obj = Parakeet::Content::get($this->pageAddress($page));
$log->info("Created content [".$obj->key()."]");
if ($this->{feed})
{
$obj->feedSet($this->{feed});
}
push @{$this->{generated}}, $obj;
if (@{$this->{generated}} > 1)
{
$obj->parentSet($this->{generated}[0]);
}
$log->debug("Body:\n$body");
my $file = $obj->inputFileAbs();
$log->info("Writing to file [$file]");
my $r = Misc::DmUtil::File::writeFileUtf8($file, $body, ifDifferent => 1);
unless ($r)
{
$log->error("Failed to write input file [$file]");
return 0;
}
if ($r->{wrote})
{
$log->info("Wrote new file to [$file]");
}
else
{
$log->info("No change on file [$file]");
}
}
return 1;
} # end of 'build()'
# Return first generated content
sub firstGeneratedContent
{
return shift()->{generated}[0];
} # end of 'firstGenerated()'
# Create object
sub new
{
my $class = shift;
my %arg = @_;
my $this = {};
bless $this, $class;
# create log
my $log = $this->{log} = Misc::DmUtil::Log::find(%arg, id => $arg{key});
# required arguments
foreach my $i (qw(content path title))
{
unless (notEmpty($arg{$i}))
{
$log->fatal("No [$i] supplied");
}
$this->{$i} = $arg{$i};
}
$this->{generated} //= [];
$this->{feed} = $arg{feed};
$this->{number} = $arg{number} // 0;
$this->{perPage} = $arg{perPage} // 5;
$this->{readLinkText} = $arg{readLinkText} // "Read";
$this->{summary} = $arg{summary} // -1;
return $this;
} # end of 'new()'
# Return address for page number
sub pageAddress
{
my $this = shift;
my $num = shift;
my $log = $this->{log};
my $p = "auto:".$this->{path}.($num == 0 ? "" : "-".($num + 1)).".page";
$log->debug("p=[$p]");
return new Parakeet::Address($p);
} # end of 'pageAddress()'
1;
| duncanmartin/parakeet | lib/Parakeet/Generator/List.pm | Perl | bsd-2-clause | 6,371 |
package App::Netdisco::Worker::Plugin::PortName;
use Dancer ':syntax';
use App::Netdisco::Worker::Plugin;
use aliased 'App::Netdisco::Worker::Status';
use App::Netdisco::Transport::SNMP;
use App::Netdisco::Util::Port ':all';
register_worker({ phase => 'check' }, sub {
my ($job, $workerconf) = @_;
return Status->error('Missing device (-d).') unless defined $job->device;
return Status->error('Missing port (-p).') unless defined $job->port;
return Status->error('Missing name (-e).') unless defined $job->subaction;
vars->{'port'} = get_port($job->device, $job->port)
or return Status->error(sprintf "Unknown port name [%s] on device %s",
$job->port, $job->device);
return Status->done('PortName is able to run');
});
register_worker({ phase => 'main', driver => 'snmp' }, sub {
my ($job, $workerconf) = @_;
my ($device, $pn, $data) = map {$job->$_} qw/device port extra/;
# update pseudo devices directly in database
unless ($device->is_pseudo()) {
# snmp connect using rw community
my $snmp = App::Netdisco::Transport::SNMP->writer_for($device)
or return Status->defer("failed to connect to $device to update alias");
my $iid = get_iid($snmp, vars->{'port'})
or return Status->error("Failed to get port ID for [$pn] from $device");
my $rv = $snmp->set_i_alias($data, $iid);
if (!defined $rv) {
return Status->error(sprintf 'Failed to set [%s] alias to [%s] on $device: %s',
$pn, $data, ($snmp->error || ''));
}
# confirm the set happened
$snmp->clear_cache;
my $state = ($snmp->i_alias($iid) || '');
if (ref {} ne ref $state or $state->{$iid} ne $data) {
return Status->error("Verify of [$pn] alias failed on $device");
}
}
# update netdisco DB
vars->{'port'}->update({name => $data});
return Status->done("Updated [$pn] alias on [$device] to [$data]");
});
true;
| netdisco/netdisco | lib/App/Netdisco/Worker/Plugin/PortName.pm | Perl | bsd-3-clause | 1,937 |
/* xml_generation.pl : Document -> XML translation
*
* Copyright (C) 2001-2005 Binding Time Limited
* Copyright (C) 2005, 2006 John Fletcher
*
* Current Release: $Revision: 1.2 $
*
* TERMS AND CONDITIONS:
*
* This program is offered free of charge, as unsupported source code. You may
* use it, copy it, distribute it, modify it or sell it without restriction,
* but entirely at your own risk.
*/
:- ensure_loaded( xml_utilities ).
/* document_generation( +Format, +Document ) is a DCG generating Document
* as a list of character codes. Format is true|false defining whether layouts,
* to provide indentation, should be added between the element content of
* the resultant "string". Note that formatting is disabled for elements that
* are interspersed with pcdata/1 terms, such as XHTML's 'inline' elements.
* Also, Format is over-ridden, for an individual element, by an explicit
* 'xml:space'="preserve" attribute.
*/
document_generation( Format, xml(Attributes, Document) ) -->
document_generation_body( Attributes, Format, Document ).
document_generation_body( [], Format, Document ) -->
generation( Document, "", Format, [], _Format1 ).
document_generation_body( Attributes, Format, Document ) -->
{ Attributes = [_|_],
xml_declaration_attributes_valid( Attributes )
},
"<?xml",
generated_attributes( Attributes, Format, Format0 ),
"?>",
indent( true, [] ),
generation( Document, "", Format0, [], _Format1 ).
generation( [], _Prefix, Format, _Indent, Format ) --> [].
generation( [Term|Terms], Prefix, Format0, Indent, Format ) -->
generation( Term, Prefix, Format0, Indent, Format1 ),
generation( Terms, Prefix, Format1, Indent, Format ).
generation( doctype(Name, External), _Prefix, Format, [], Format ) -->
"<!DOCTYPE ",
generated_name( Name ),
generated_external_id( External ),
">".
generation( instructions(Target,Process), _Prefix, Format, Indent, Format ) -->
indent( Format, Indent ),
"<?", generated_name(Target), " ", chars( Process ) ,"?>".
generation( pcdata(Chars), _Prefix, Format0, _Indent, Format1 ) -->
pcdata_generation( Chars ),
{pcdata_format( Chars, Format0, Format1 )}.
generation( comment( Comment ), _Prefix, Format, Indent, Format ) -->
indent( Format, Indent ),
"<!--", chars( Comment ), "-->".
generation( namespace(URI, Prefix, element(Name, Atts, Content)),
_Prefix0, Format, Indent, Format ) -->
indent( Format, Indent ),
"<", generated_prefixed_name( Prefix, Name ),
generated_prefixed_attributes( Prefix, URI, Atts, Format, Format1 ),
generated_content( Content, Format1, Indent, Prefix, Name ).
generation( element(Name, Atts, Content), Prefix, Format, Indent, Format ) -->
indent( Format, Indent ),
"<", generated_prefixed_name( Prefix, Name ),
generated_attributes( Atts, Format, Format1 ),
generated_content( Content, Format1, Indent, Prefix, Name ).
generation( cdata(CData), _Prefix, Format, Indent, Format ) -->
indent( Format, Indent ),
"<![CDATA[", cdata_generation(CData), "]]>".
generated_attributes( [], Format, Format ) --> [].
generated_attributes( [Name=Value|Attributes], Format0, Format ) -->
{( Name == 'xml:space',
Value="preserve" ->
Format1 = false
; otherwise ->
Format1 = Format0
)},
" ",
generated_name( Name ),
"=""",
quoted_string( Value ),
"""",
generated_attributes( Attributes, Format1, Format ).
generated_prefixed_name( [], Name ) -->
generated_name( Name ).
generated_prefixed_name( Prefix, Name ) -->
{Prefix = [_|_]},
chars( Prefix ), ":",
generated_name( Name ).
generated_content( [], _Format, _Indent, _Prefix, _Namespace ) -->
" />". % Leave an extra space for XHTML output.
generated_content( [H|T], Format, Indent, Prefix, Namespace ) -->
">",
generation( H, Prefix, Format, [0' |Indent], Format1 ),
generation( T, Prefix, Format1, [0' |Indent], Format2 ),
indent( Format2, Indent ),
"</", generated_prefixed_name( Prefix, Namespace ), ">".
generated_prefixed_attributes( [_|_Prefix], _URI, Atts, Format0, Format ) -->
generated_attributes( Atts, Format0, Format ).
generated_prefixed_attributes( [], URI, Atts, Format0, Format ) -->
{atom_codes( URI, Namespace ),
findall( Attr, (member(Attr, Atts), \+ Attr=(xmlns=_Val)), Atts1 )
},
generated_attributes( [xmlns=Namespace|Atts1], Format0, Format ).
generated_name( Name, Plus, Minus ) :-
atom_codes( Name, Chars ),
append( Chars, Minus, Plus ).
generated_external_id( local ) --> "".
generated_external_id( local(Literals) ) --> " [",
generated_doctype_literals( Literals ), "
]".
generated_external_id( system(URL) ) -->
" SYSTEM """,
chars( URL ),
"""".
generated_external_id( system(URL,Literals) ) -->
" SYSTEM """,
chars( URL ),
""" [",
generated_doctype_literals( Literals ), "
]".
generated_external_id( public(URN,URL) ) -->
" PUBLIC """,
chars( URN ),
""" """,
chars( URL ),
"""".
generated_external_id( public(URN,URL,Literals) ) -->
" PUBLIC """,
chars( URN ),
""" """,
chars( URL ),
""" [",
generated_doctype_literals( Literals ), "
]".
generated_doctype_literals( [] ) --> "".
generated_doctype_literals( [dtd_literal(String)|Literals] ) --> "
<!", cdata_generation( String ), ">",
generated_doctype_literals( Literals ).
/* quoted_string( +Chars ) is a DCG representing Chars, a list of character
* codes, as a legal XML attribute string. Any leading or trailing layout
* characters are removed. &, " and < characters are replaced by &, "
* and < respectively, .
*/
quoted_string( Raw, Plus, Minus ) :-
quoted_string1( Raw, NoLeadingLayouts ),
quoted_string2( NoLeadingLayouts, Layout, Layout, Plus, Minus ).
quoted_string1( [], [] ).
quoted_string1( [Char|Chars], NoLeadingLayouts ) :-
( Char > 32 ->
NoLeadingLayouts = [Char|Chars]
; otherwise ->
quoted_string1( Chars, NoLeadingLayouts )
).
quoted_string2( [], _LayoutPlus, _LayoutMinus, List, List ).
quoted_string2( [Char|Chars], LayoutPlus, LayoutMinus, Plus, Minus ) :-
( Char =< " " ->
Plus = Plus1,
LayoutMinus = [Char|LayoutMinus1],
LayoutPlus = LayoutPlus1
; Char =< 127 ->
Plus = LayoutPlus,
pcdata_7bit( Char, LayoutMinus, Plus1 ),
LayoutPlus1 = LayoutMinus1
; legal_xml_unicode( Char ) ->
Plus = LayoutPlus,
number_codes( Char, Codes ),
pcdata_8bits_plus( Codes, LayoutMinus, Plus1 ),
LayoutPlus1 = LayoutMinus1
; otherwise ->
LayoutPlus = LayoutPlus1,
LayoutMinus = LayoutMinus1,
Plus = Plus1
),
quoted_string2( Chars, LayoutPlus1, LayoutMinus1, Plus1, Minus ).
indent( false, _Indent ) --> [].
indent( true, Indent ) -->
"
", chars( Indent ).
/* pcdata_generation( +Chars ) is a DCG representing Chars, a list of character
* codes as legal XML "Parsed character data" (PCDATA) string. Any codes
* which cannot be represented by a 7-bit character are replaced by their
* decimal numeric character entity e.g. code 160 (non-breaking space) is
* represented as  . Any character codes disallowed by the XML
* specification are not encoded.
*/
pcdata_generation( [], Plus, Plus ).
pcdata_generation( [Char|Chars], Plus, Minus ) :-
( Char =< 127 ->
pcdata_7bit( Char, Plus, Mid )
; legal_xml_unicode( Char ) ->
number_codes( Char, Codes ),
pcdata_8bits_plus( Codes, Plus, Mid )
; otherwise ->
Plus = Mid
),
pcdata_generation( Chars, Mid, Minus ).
/* pcdata_7bit(+Char) represents the ascii character set in its
* simplest format, using the character entities & " < and >
* which are common to both XML and HTML. The numeric entity ' is used in
* place of ', because browsers don't recognize it in HTML.
*/
pcdata_7bit( 0 ) --> "".
pcdata_7bit( 1 ) --> "".
pcdata_7bit( 2 ) --> "".
pcdata_7bit( 3 ) --> "".
pcdata_7bit( 4 ) --> "".
pcdata_7bit( 5 ) --> "".
pcdata_7bit( 6 ) --> "".
pcdata_7bit( 7 ) --> "".
pcdata_7bit( 8 ) --> "".
pcdata_7bit( 9 ) --> [9].
pcdata_7bit( 10 ) --> [10].
pcdata_7bit( 11 ) --> "".
pcdata_7bit( 12 ) --> "".
pcdata_7bit( 13 ) --> [13].
pcdata_7bit( 14 ) --> "".
pcdata_7bit( 15 ) --> "".
pcdata_7bit( 16 ) --> "".
pcdata_7bit( 17 ) --> "".
pcdata_7bit( 18 ) --> "".
pcdata_7bit( 19 ) --> "".
pcdata_7bit( 20 ) --> "".
pcdata_7bit( 21 ) --> "".
pcdata_7bit( 22 ) --> "".
pcdata_7bit( 23 ) --> "".
pcdata_7bit( 24 ) --> "".
pcdata_7bit( 25 ) --> "".
pcdata_7bit( 26 ) --> "".
pcdata_7bit( 27 ) --> "".
pcdata_7bit( 28 ) --> "".
pcdata_7bit( 29 ) --> "".
pcdata_7bit( 30 ) --> "".
pcdata_7bit( 31 ) --> "".
pcdata_7bit( 32 ) --> " ".
pcdata_7bit( 33 ) --> "!".
pcdata_7bit( 34 ) --> """.
pcdata_7bit( 35 ) --> "#".
pcdata_7bit( 36 ) --> "$".
pcdata_7bit( 37 ) --> "%".
pcdata_7bit( 38 ) --> "&".
pcdata_7bit( 39 ) --> "'".
pcdata_7bit( 40 ) --> "(".
pcdata_7bit( 41 ) --> ")".
pcdata_7bit( 42 ) --> "*".
pcdata_7bit( 43 ) --> "+".
pcdata_7bit( 44 ) --> ",".
pcdata_7bit( 45 ) --> "-".
pcdata_7bit( 46 ) --> ".".
pcdata_7bit( 47 ) --> "/".
pcdata_7bit( 48 ) --> "0".
pcdata_7bit( 49 ) --> "1".
pcdata_7bit( 50 ) --> "2".
pcdata_7bit( 51 ) --> "3".
pcdata_7bit( 52 ) --> "4".
pcdata_7bit( 53 ) --> "5".
pcdata_7bit( 54 ) --> "6".
pcdata_7bit( 55 ) --> "7".
pcdata_7bit( 56 ) --> "8".
pcdata_7bit( 57 ) --> "9".
pcdata_7bit( 58 ) --> ":".
pcdata_7bit( 59 ) --> ";".
pcdata_7bit( 60 ) --> "<".
pcdata_7bit( 61 ) --> "=".
pcdata_7bit( 62 ) --> ">".
pcdata_7bit( 63 ) --> "?".
pcdata_7bit( 64 ) --> "@".
pcdata_7bit( 65 ) --> "A".
pcdata_7bit( 66 ) --> "B".
pcdata_7bit( 67 ) --> "C".
pcdata_7bit( 68 ) --> "D".
pcdata_7bit( 69 ) --> "E".
pcdata_7bit( 70 ) --> "F".
pcdata_7bit( 71 ) --> "G".
pcdata_7bit( 72 ) --> "H".
pcdata_7bit( 73 ) --> "I".
pcdata_7bit( 74 ) --> "J".
pcdata_7bit( 75 ) --> "K".
pcdata_7bit( 76 ) --> "L".
pcdata_7bit( 77 ) --> "M".
pcdata_7bit( 78 ) --> "N".
pcdata_7bit( 79 ) --> "O".
pcdata_7bit( 80 ) --> "P".
pcdata_7bit( 81 ) --> "Q".
pcdata_7bit( 82 ) --> "R".
pcdata_7bit( 83 ) --> "S".
pcdata_7bit( 84 ) --> "T".
pcdata_7bit( 85 ) --> "U".
pcdata_7bit( 86 ) --> "V".
pcdata_7bit( 87 ) --> "W".
pcdata_7bit( 88 ) --> "X".
pcdata_7bit( 89 ) --> "Y".
pcdata_7bit( 90 ) --> "Z".
pcdata_7bit( 91 ) --> "[".
pcdata_7bit( 92 ) --> [92].
pcdata_7bit( 93 ) --> "]".
pcdata_7bit( 94 ) --> "^".
pcdata_7bit( 95 ) --> "_".
pcdata_7bit( 96 ) --> "`".
pcdata_7bit( 97 ) --> "a".
pcdata_7bit( 98 ) --> "b".
pcdata_7bit( 99 ) --> "c".
pcdata_7bit( 100 ) --> "d".
pcdata_7bit( 101 ) --> "e".
pcdata_7bit( 102 ) --> "f".
pcdata_7bit( 103 ) --> "g".
pcdata_7bit( 104 ) --> "h".
pcdata_7bit( 105 ) --> "i".
pcdata_7bit( 106 ) --> "j".
pcdata_7bit( 107 ) --> "k".
pcdata_7bit( 108 ) --> "l".
pcdata_7bit( 109 ) --> "m".
pcdata_7bit( 110 ) --> "n".
pcdata_7bit( 111 ) --> "o".
pcdata_7bit( 112 ) --> "p".
pcdata_7bit( 113 ) --> "q".
pcdata_7bit( 114 ) --> "r".
pcdata_7bit( 115 ) --> "s".
pcdata_7bit( 116 ) --> "t".
pcdata_7bit( 117 ) --> "u".
pcdata_7bit( 118 ) --> "v".
pcdata_7bit( 119 ) --> "w".
pcdata_7bit( 120 ) --> "x".
pcdata_7bit( 121 ) --> "y".
pcdata_7bit( 122 ) --> "z".
pcdata_7bit( 123 ) --> "{".
pcdata_7bit( 124 ) --> "|".
pcdata_7bit( 125 ) --> "}".
pcdata_7bit( 126 ) --> "~".
pcdata_7bit( 127 ) --> "".
pcdata_8bits_plus( Codes ) -->
"&#", chars( Codes ), ";".
/* pcdata_format( +Chars, +Format0, ?Format1 ) holds when Format0 and Format1
* are the statuses of XML formatting before and after Chars - which may be
* null.
*/
pcdata_format( [], Format, Format ).
pcdata_format( [_Char|_Chars], _Format, false ).
/* cdata_generation( +Chars ) is a DCG representing Chars, a list of character
* codes as a legal XML CDATA string. Any character codes disallowed by the XML
* specification are not encoded.
*/
cdata_generation( [] ) --> "".
cdata_generation( [Char|Chars] ) -->
( {legal_xml_unicode( Char )}, !, [Char]
| ""
),
cdata_generation( Chars ).
legal_xml_unicode( 9 ).
legal_xml_unicode( 10 ).
legal_xml_unicode( 13 ).
legal_xml_unicode( Code ) :-
Code >= 32,
Code =< 55295.
legal_xml_unicode( Code ) :-
Code >= 57344,
Code =< 65533.
legal_xml_unicode( Code ) :-
Code >= 65536,
Code =< 1114111.
| kishoredbn/barrelfish | usr/eclipseclp/Contrib/xml_generation.pl | Perl | mit | 12,338 |
package Paws::Health::DescribeAffectedEntitiesResponse;
use Moose;
has Entities => (is => 'ro', isa => 'ArrayRef[Paws::Health::AffectedEntity]', traits => ['NameInRequest'], request_name => 'entities' );
has NextToken => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'nextToken' );
has _request_id => (is => 'ro', isa => 'Str');
### main pod documentation begin ###
=head1 NAME
Paws::Health::DescribeAffectedEntitiesResponse
=head1 ATTRIBUTES
=head2 Entities => ArrayRef[L<Paws::Health::AffectedEntity>]
The entities that match the filter criteria.
=head2 NextToken => Str
If the results of a search are large, only a portion of the results are
returned, and a C<nextToken> pagination token is returned in the
response. To retrieve the next batch of results, reissue the search
request and include the returned token. When all results have been
returned, the response does not contain a pagination token value.
=head2 _request_id => Str
=cut
1; | ioanrogers/aws-sdk-perl | auto-lib/Paws/Health/DescribeAffectedEntitiesResponse.pm | Perl | apache-2.0 | 995 |
package Google::Ads::AdWords::v201406::TemplateElementField::Type;
use strict;
use warnings;
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406'};
# derivation by restriction
use base qw(
SOAP::WSDL::XSD::Typelib::Builtin::string);
1;
__END__
=pod
=head1 NAME
=head1 DESCRIPTION
Perl data type class for the XML Schema defined simpleType
TemplateElementField.Type from the namespace https://adwords.google.com/api/adwords/cm/v201406.
Possible field types of template element fields.
This clase is derived from
SOAP::WSDL::XSD::Typelib::Builtin::string
. SOAP::WSDL's schema implementation does not validate data, so you can use it exactly
like it's base type.
# Description of restrictions not implemented yet.
=head1 METHODS
=head2 new
Constructor.
=head2 get_value / set_value
Getter and setter for the simpleType's value.
=head1 OVERLOADING
Depending on the simple type's base type, the following operations are overloaded
Stringification
Numerification
Boolification
Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information.
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| gitpan/GOOGLE-ADWORDS-PERL-CLIENT | lib/Google/Ads/AdWords/v201406/TemplateElementField/Type.pm | Perl | apache-2.0 | 1,138 |
package #
Date::Manip::Offset::off103;
# Copyright (c) 2008-2014 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
# This file was automatically generated. Any changes to this file will
# be lost the next time 'tzdata' is run.
# Generated on: Fri Nov 21 11:03:45 EST 2014
# Data version: tzdata2014j
# Code version: tzcode2014j
# This module contains data from the zoneinfo time zone database. The original
# data was obtained from the URL:
# ftp://ftp.iana.orgtz
use strict;
use warnings;
require 5.010000;
our ($VERSION);
$VERSION='6.48';
END { undef $VERSION; }
our ($Offset,%Offset);
END {
undef $Offset;
undef %Offset;
}
$Offset = '+04:31:19';
%Offset = (
1 => [
'europe/moscow',
],
);
1;
| nriley/Pester | Source/Manip/Offset/off103.pm | Perl | bsd-2-clause | 851 |
#!env perl
use v5.12;
use Device::WebIO;
use Device::WebIO::Firmata;
use Time::HiRes 'sleep';
use constant STEP_INC => 16;
use constant PIN => 11;
my $PORT = shift or die "Need port to connect to\n";
my $webio = Device::WebIO->new;
my $firmata = Device::WebIO::Firmata->new({
port => $PORT,
});
$webio->register( 'foo', $firmata );
my $MAX_VALUE = $webio->pwm_max_int( 'foo', PIN );
my $do_increase_value = 1;
my $value = 0;
while( 1 ) {
if( $do_increase_value ) {
$value += STEP_INC;
if( $value >= $MAX_VALUE ) {
$value = $MAX_VALUE;
$do_increase_value = 0;
}
}
else {
$value -= STEP_INC;
if( $value <= 0 ) {
$value = 0;
$do_increase_value = 1;
}
}
$webio->pwm_output_int( 'foo', PIN, $value );
sleep 0.1;
}
| gitpan/Device-WebIO-Firmata | examples/pwm_fade.pl | Perl | bsd-2-clause | 844 |
package CoGeX::Result::ListConnector;
use strict;
use warnings;
use base 'DBIx::Class::Core';
#use CoGeX;
=head1 NAME
CoGeX::Result::ListConnector
=head1 SYNOPSIS
This object uses the DBIx::Class to define an interface to the C<list_connector> table in the CoGe database.
The C<list_connector> table is used to associate C<experiment,genome,feature> records with C<list> records.
=head1 DESCRIPTION
Has columns:
C<list_connector_id> (Primary Key)
Type: INT, Default: yes, Nullable: no, Size: 11
Primary identification key for table.
C<parent_id>
Type: INT, Default: "", Nullable: no, Size: 11
Key for identifying the record in the C<list> table.
C<child_id>
Type: INT, Default: "", Nullable: no, Size: 11
Key for identifying the record in the C<experiment,genome,feature> table.
C<child_type>
Type: TINYINT, Default: "", Nullable: no, Size: 1
Child type indicator.
Belongs to CCoGeX::Result::Genome> via C<child_id>
Belongs to CCoGeX::Result::Experiment> via C<child_id>
Belongs to CCoGeX::Result::Feature> via C<child_id>
Belongs to CCoGeX::Result::List> via C<child_id> -- for a list of lists!
Belongs to CCoGeX::Result::List> via C<list_id> -- parent list
=head1 USAGE
use CoGeX;
=head1 METHODS
=cut
my $node_types = CoGeX::node_types();
__PACKAGE__->table("list_connector");
__PACKAGE__->add_columns(
"list_connector_id",
{ data_type => "INT", default_value => 1, is_nullable => 0, size => 11 },
"parent_id",
{ data_type => "INT", default_value => "", is_nullable => 0, size => 11 },
"child_id",
{ data_type => "INT", default_value => "", is_nullable => 0, size => 11 },
"child_type",
{ data_type => "TINYINT", default_value => "", is_nullable => 0, size => 1 },
);
__PACKAGE__->set_primary_key("list_connector_id");
__PACKAGE__->belongs_to("experiment" => "CoGeX::Result::Experiment", "child_id");
__PACKAGE__->belongs_to("genome" => "CoGeX::Result::Genome", "child_id", {
join=>['genomic_sequence_type', 'organism'],
prefetch=>['genomic_sequence_type', 'organism'],
});
__PACKAGE__->belongs_to("feature" => "CoGeX::Result::Feature", "child_id");
__PACKAGE__->belongs_to("child_list" => "CoGeX::Result::List", {'foreign.list_id' => 'self.child_id'}); # a list of lists
__PACKAGE__->belongs_to("parent_list" => "CoGeX::Result::List", {'foreign.list_id' => 'self.parent_id' } ); # parent list of a genome/experiment/feature/list
################################################ subroutine header begin ##
=head2 type
Usage :
Purpose : Alias to the child_type() method.
Returns : See child_type()
Argument : None
Throws :
Comments :
See Also :
=cut
################################################## subroutine header end ##
sub type
{
return shift->child_type();
}
################################################ subroutine header begin ##
=head2 is_*
Usage :
Purpose :
Returns :
Argument : None
Throws :
Comments :
See Also :
=cut
################################################## subroutine header end ##
sub is_list
{
return shift->child_type() == $node_types->{list};
}
sub is_genome
{
return shift->child_type() == $node_types->{genome};
}
sub is_feature
{
return shift->child_type() == $node_types->{feature};
}
sub is_experiment
{
return shift->child_type() == $node_types->{experiment};
}
################################################ subroutine header begin ##
=head2 child
Usage :
Purpose :
Returns :
Argument : None
Throws :
Comments :
See Also :
=cut
################################################## subroutine header end ##
sub child
{
my $self = shift;
if ($self->is_experiment) {
return $self->experiment;
}
elsif ($self->is_genome) {
return $self->genome;
}
elsif ($self->is_feature) {
return $self->feature;
}
elsif ($self->is_list) {
return $self->child_list;
}
else {
warn "unknown child type " . $self->child_type;
}
return;
}
1;
=head1 AUTHORS
Matt Bomhoff
=head1 COPYRIGHT
This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the
LICENSE file included with this module.
=head1 SEE ALSO
=cut
| asherkhb/coge | modules/Database/lib/CoGeX/Result/ListConnector.pm | Perl | bsd-2-clause | 4,219 |
#! /usr/bin/env perl
use Getopt::Long;
GetOptions ("input|i=s" => \$input, # string
"help|h" => \$help); # flag
#Create help and usage statement
sub help{
print "Usage: perl parseRelatedness.pl -i <README.sample_cryptic_relations>
Options:
\n\n";
die;
}
#Create subroutine to validate inputs
sub validateInput{
($name,$value) = @_;
if(!$value){
print "\n$name is not defined in your input\n\n";
help();
die
}
}
# Look for help flag
if($help){help()}
#Ensure all required parameters are set
validateInput("input",$input);
open(OUT, ">cryptic.json") or die "Can't open the output file: cryptic.json\n\n";
open(FILE,"$input") or die "Can't open the input file: $input\n\n";
while(<FILE>){
chomp;
#Skip the blank & extra lines from file
next if ($. < 4);
#Get the column Headers
if($. == 4){
$_ =~ s/ /_/g;
@HEADERS = split("\t",$_);
} else{
#These are the lines that actually contain data
@line = split("\t", $_ );
@jsonLine = ();
for ($i=0; $i<@line; $i++){
#For strings, the values need to be in quotes
if($i<4){$newLine = ' "'.@line[$i].'"'}else{$newLine=@line[$i]}
$jsonLine=' "'. @HEADERS[$i] . '":'. $newLine;
push (@jsonLine,$jsonLine);
}
$jsonLine =join(',', @jsonLine);
print OUT "{".$jsonLine."}\n";
}
}
close OUT;
close FILE; | Steven-N-Hart/VariantDB_Challenge | submissions/StevenNHart/MongoDB_Sharded/scripts/parseRelatedness.pl | Perl | mit | 1,327 |
package DDG::Spice::Editor;
use utf8;
use DDG::Spice;
use URI::Escape;
use Encode;
primary_example_queries "python syntax highlighter";
secondary_example_queries "python scratchpad", "javascript syntax highlighter";
description "Show a text editor with sintax highlighting";
name "Editor";
source "http://ace.c9.io/";
code_url "https://github.com/duckduckgo/zeroclickinfo-spice/blob/master/lib/DDG/Spice/Editor.pm";
topics "programming";
category "software";
attribution github => ['https://github.com/jmg','Juan Manuel García'],
email => ['jmg.utn@gmail.com','Juan Manuel García'];
triggers startend => 'web editor', 'online editor', 'syntax highlighter', 'syntax highlighting', 'code viewer', 'scratchpad', 'scratch pad';
spice call_type => 'self';
my @supported_languages = ("javascript", "python");
my %supported_languages = map { $_ => 1 } @supported_languages;
handle remainder => sub {
foreach my $param (0, 1) {
my $lan = $_[$param];
if ($lan && exists($supported_languages{lc $lan})) {
return $lan;
}
}
return;
};
1;
| timeanddate/zeroclickinfo-spice | lib/DDG/Spice/Editor.pm | Perl | apache-2.0 | 1,098 |
package JobDB::JobStages;
use strict;
use warnings;
1;
# this class is a stub, this file will not be automatically regenerated
# all work in this module will be saved
| paczian/MG-RAST | src/MGRAST/lib/JobDB/JobStages.pm | Perl | bsd-2-clause | 171 |
# Copyright (c) 2009 Philip Taylor
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
package Font::EOTWrapper;
use strict;
use warnings;
use Font::TTF::Font;
use Encode;
use constant TTEMBED_SUBSET => 0x00000001;
use constant TTEMBED_TTCOMPRESSED => 0x00000004;
use constant TTEMBED_XORENCRYPTDATA => 0x10000000;
use constant DEFAULT_CHARSET => 0x01;
sub convert {
my ($in_fn, $out_fn) = @_;
my $font_data = do {
open my $fh, $in_fn or die "Failed to open $in_fn: $!";
binmode $fh;
local $/;
<$fh>
};
my $font = Font::TTF::Font->open($in_fn) or die "Failed to open $in_fn: $!";
open my $out, '>', $out_fn or die "Failed to open $out_fn: $!";
binmode $out;
$font->{name}->read if $font->{name};
my $os2 = $font->{'OS/2'};
$os2->read;
my $rootString = '';
my $header = '';
$header .= pack V => length($font_data);
$header .= pack V => 0x00020001;
$header .= pack V => TTEMBED_SUBSET;
$header .= pack C10 => map $os2->{$_}, qw(bFamilyType bSerifStyle bWeight bProportion bContrast bStrokeVariation bArmStyle bLetterform bMidline bXheight);
$header .= pack C => DEFAULT_CHARSET;
$header .= pack C => (($os2->{fsSelection} & 1) ? 1 : 0);
$header .= pack V => $os2->{usWeightClass};
$header .= pack v => $os2->{fsType};
$header .= pack v => 0x504C;
$header .= pack VVVV => map $os2->{$_}, qw(ulUnicodeRange1 ulUnicodeRange2 ulUnicodeRange3 ulUnicodeRange4);
$header .= pack VV => map $os2->{$_}, qw(ulCodePageRange1 ulCodePageRange2);
$header .= pack V => $font->{head}{checkSumAdjustment};
$header .= pack VVVV => 0, 0, 0, 0;
$header .= pack v => 0;
$header .= pack 'v/a*' => encode 'utf-16le' => $font->{name}->find_name(1); # family name
$header .= pack v => 0;
$header .= pack 'v/a*' => encode 'utf-16le' => $font->{name}->find_name(2); # style name
$header .= pack v => 0;
$header .= pack 'v/a*' => encode 'utf-16le' => $font->{name}->find_name(5); # version name
$header .= pack v => 0;
$header .= pack 'v/a*' => encode 'utf-16le' => $font->{name}->find_name(4); # full name
$header .= pack v => 0;
$header .= pack 'v/a*' => encode 'utf-16le' => $rootString;
$out->print(pack V => 4 + length($header) + length($font_data));
$out->print($header);
$out->print($font_data);
$font->release;
}
sub extract {
my ($in_fn, $out_fn) = @_;
my $eot_data = do {
open my $fh, $in_fn or die "Failed to open $in_fn: $!";
binmode $fh;
local $/;
<$fh>
};
die "Error: EOT too small" if length $eot_data < 16;
my ($eot_size, $font_data_size, $version, $flags) = unpack VVVV => substr $eot_data, 0, 16;
die "Error: Invalid EOTSize ($eot_size, should be ".(length $eot_data).")" if $eot_size != length $eot_data;
die "Error: Invalid Version ($version)" if not ($version == 0x00020000 or $version == 0x00020001 or $version == 0x00020002);
die "Error: Can't handle compressed fonts" if $flags & TTEMBED_TTCOMPRESSED;
# Skip the header fields
my $rest = substr $eot_data, 16+66;
my ($family_name, $style_name, $version_name, $full_name, $rest2) = unpack 'v/a* xx v/a* xx v/a* xx v/a* a*' => $rest;
my $font_data;
if ($version == 0x00020000) { # not 0x00010000 - spec is wrong (http://lists.w3.org/Archives/Public/www-font/2009JulSep/0862.html)
$font_data = $rest2;
} elsif ($version == 0x00020001) {
my ($root, $data) = unpack 'xx v/a* a*' => $rest2;
$font_data = $data;
} elsif ($version == 0x00020002) {
my ($root, $root_checksum, $eudc_codepage, $signature, $eudc_flags, $eudc_font, $data)
= unpack 'xx v/a* V V xx v/a* V v/a* a*' => $rest2;
$font_data = $data;
}
if ($flags & TTEMBED_XORENCRYPTDATA) {
$font_data ^= ("\x50" x length $font_data);
}
open my $fh, '>', $out_fn or die "Failed to open $out_fn: $!";
binmode $fh;
print $fh $font_data;
}
# sub rootStringChecksum {
# my $s = 0;
# $s += $_ for unpack 'C*', $_[0];
# return $s ^ 0x50475342;
# }
1;
| caiguanhao/grunt-ziti | vendor/font-optimizer/Font/EOTWrapper.pm | Perl | mit | 5,147 |
#------------------------------------------------------------------------------
# File: fi.pm
#
# Description: ExifTool Finnish language translations
#
# Notes: This file generated automatically by Image::ExifTool::TagInfoXML
#------------------------------------------------------------------------------
package Image::ExifTool::Lang::fi;
use strict;
use vars qw($VERSION);
$VERSION = '1.02';
%Image::ExifTool::Lang::fi::Translate = (
'AEAperture' => 'AE-aukko',
'AEBBracketValue' => 'AEB-haarukointiarvo',
'AEBXv' => 'AEB-valotuksen korjaus',
'AEExposureTime' => 'AE-valotusaika',
'AEInfo' => 'Automaattivalotustiedot',
'AELock' => {
Description => 'AE-lukitus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'AELockButton' => 'AE-lukituspainike',
'AEMeteringMode' => 'AE-valotuksen mittaustapa',
'AEMeteringSegments' => 'AE-mittaussegmentit',
'AEProgramMode' => 'AE-ohjelmatapa',
'AESetting' => 'AE-asetus',
'AEXv' => 'AE-valotuksen korjaus',
'AF-CPrioritySelection' => 'AF-C -esivalinnat',
'AF-OnForMB-D10' => 'AF-ON -painike (MB-D10)',
'AF-SPrioritySelection' => 'AF-S -esivalinnat',
'AFActivation' => 'AF-aktivointi',
'AFAdjustment' => 'AF-säätö',
'AFAperture' => 'AF-aukko',
'AFArea' => 'AF-alue',
'AFAreaHeight' => 'AF-alueen korkeus',
'AFAreaIllumination' => 'AF-alueen valaisu',
'AFAreaMode' => 'AF-aluetarkennus',
'AFAreaModeSetting' => 'AF-aluemittaustavan asetus',
'AFAreaWidth' => 'AF-alueen leveys',
'AFAreas' => 'AF-alueet',
'AFAssist' => 'AF-apu',
'AFAssistLamp' => {
PrintConv => {
'Disabled and Not Required' => 'Deaktivoitu eikä tarpeen',
'Disabled but Required' => 'Deaktivoitu mutta tarpeen',
'Enabled but Not Used' => 'Aktivoitu muttei käytetty',
'Fired' => 'Lauennut',
},
},
'AFDefocus' => 'AF-defokus (poikkeama polttopisteestä)',
'AFFineTune' => 'AF-hienosäätö',
'AFImageHeight' => 'AF-kuvan korkeus',
'AFImageWidth' => 'AF-kuvan leveys',
'AFInfo' => 'Automaattitarkennustiedot',
'AFInfo2' => 'AF-tiedot',
'AFInfo2Version' => 'AF-tietojen versio',
'AFIntegrationTime' => 'AF-integrointiaika',
'AFMode' => 'AF-muoto',
'AFPoint' => {
Description => 'AF-piste',
PrintConv => {
'Bottom Center' => 'Alhaalla keskellä',
'Bottom Left' => 'Alavasemmalla',
'Bottom Right' => 'Alaoikealla',
'Center' => 'Keskellä',
'Center Left' => 'Keskellä vasemmalla',
'Center Right' => 'Keskellä oikealla',
'Far Left/Right of Center' => 'Kaukana vasemmalla/keskioikealla',
'Far Left/Right of Center/Bottom' => 'Kaukana vasemmalla/keskioikealla/alhaalla',
'Near Left/Right of Center' => 'Hieman vasemmalla/keskioikealla',
'Near Upper/Left' => 'Hieman ylhäällä/vasemmalla',
'Top Center' => 'Ylhäällä keskellä',
'Top Left' => 'Ylävasemmalla',
'Top Near-left' => 'Hieman ylävasemmalla',
'Top Near-right' => 'Hieman yläoikealla',
'Top Right' => 'Yläoikealla',
'Upper Left' => 'Ylävasemmalla',
'Upper Right' => 'Yläoikealla',
},
},
'AFPointIllumination' => 'AF -pistevalaisu',
'AFPointMode' => 'AF-pistetapa',
'AFPointSelected' => {
Description => 'Valittu AF-piste',
PrintConv => {
'Auto' => 'Automaattinen',
'Automatic Tracking AF' => 'Automaattiseuranta-AF',
'Bottom' => 'Alas',
'Center' => 'Keskelle',
'Face Detect AF' => 'Kasvojentunnistus-AF',
'Fixed Center' => 'Kiinteästi keskustaan',
'Left' => 'Vasemmalle',
'Lower-left' => 'Alavasemmalle',
'Lower-right' => 'Alaoikealle',
'Mid-left' => 'Keskivasemmalle',
'Mid-right' => 'Keskioikealle',
'Right' => 'Oikealle',
'Top' => 'Ylös',
'Upper-left' => 'Ylävasemmalle',
'Upper-right' => 'Yläoikealle',
},
},
'AFPointSelected2' => 'Valittu AF-piste 2',
'AFPointSelection' => 'AF-pistevalinnat',
'AFPoints' => 'AF-pisteet',
'AFPointsInFocus' => {
Description => 'Tarkennuksen AF-pisteet',
PrintConv => {
'Bottom-center' => 'Alakeski',
'Bottom-left' => 'Alavasen',
'Bottom-right' => 'Alaoikea',
'Center' => 'Keski',
'Fixed Center or Multiple' => 'Kiinteästi keskellä tai useita',
'Left' => 'Vasen',
'None' => 'Ei yhtään',
'Right' => 'Oikea',
'Top-center' => 'Yläkeski',
'Top-left' => 'Yläoikea',
'Top-right' => 'Yläoikea',
},
},
'AFPointsSelected' => 'Valitut AF-pisteet',
'AFPointsUsed' => 'Käytetyt AF-pisteet',
'AFPredictor' => 'Ennakoiva AF',
'AFResponse' => 'Käytetty AF',
'AFResult' => 'AF-tulos',
'AFSearch' => {
Description => 'AF-haku',
PrintConv => {
'Not Ready' => 'Ei valmis',
'Ready' => 'Valmis',
},
},
'ARMIdentifier' => 'ARM-tunnistin',
'ARMVersion' => 'ARM-versio',
'AToB0' => 'A - B0',
'AToB1' => 'A - B1',
'AToB2' => 'A - B2',
'AccessoryType' => 'Lisälaitetyyppi',
'ActionAdvised' => {
Description => 'Suositettava toiminto',
PrintConv => {
'Object Kill' => 'Objektin tuhonta',
'Object Reference' => 'Objektiviite',
'Object Replace' => 'Objektin korvaus',
'Ojbect Append' => 'Objektiliitäntä',
},
},
'ActiveArea' => 'Aktiivialue',
'ActiveD-Lighting' => 'Aktiivinen D-Lighting',
'ActiveD-LightingMode' => 'Aktivoitu D-Lighting-tapa',
'AdjustmentMode' => 'Säätötapa',
'AdvancedRaw' => 'Edistynyt RAW',
'AdvancedSceneMode' => {
Description => 'Edistynyt näkymätapa',
PrintConv => {
'Auto' => 'Automaattinen',
'Creative' => 'Luova',
'Indoor/Architecture/Objects/HDR B&W' => 'Sisällä/arkkitehtuuri/kohteet',
'Normal' => 'Normaali',
'Outdoor/Illuminations/Flower/HDR Art' => 'Ulkona/valaistukset/kukka',
},
},
'AlphaByteCount' => 'Alfa-tavujen määrä',
'AlphaChannelsNames' => 'Alfa-kanavien nimet',
'AlphaDataDiscard' => {
Description => 'Alfa-data hylätty',
PrintConv => {
'Flexbits Discarded' => 'FlexBits hylätty',
'Full Resolution' => 'Täysi resoluutio',
'HighPass Frequency Data Discarded' => 'Ylipäästötaajuusdata hylätty',
'Highpass and LowPass Frequency Data Discarded' => 'Yli- ja alipäästötaajuusdata hylätty',
},
},
'AlphaOffset' => 'Alfa-siirtymä',
'AnalogBalance' => 'Analoginen tasapaino',
'AntiAliasStrength' => 'Kameran anti-alias -suotimen suhteellinen vahvuus',
'Aperture' => 'Aukko',
'ApertureRingUse' => 'Himmenninrenkaan käyttö',
'ApertureValue' => 'Aukkoarvo',
'ApplicationRecordVersion' => 'Sovellustietueen versio',
'ArtFilter' => 'Taidesuodin',
'Artist' => 'Kuvan luonut henkilö',
'AsShotICCProfile' => 'Kuin kuvatessa -ICC-profiili',
'AsShotNeutral' => 'Kuin kuvatessa -neutraali',
'AsShotPreProfileMatrix' => 'Kuin kuvatessa -pre-profiilimatriisi',
'AsShotProfileName' => 'Kuin kuvatessa -profiilin nimi',
'AsShotWhiteXY' => 'Kuin kuvatessa -valkoinen X-Y',
'Audio' => {
Description => 'Ääni',
PrintConv => {
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'AudioDuration' => 'Audion kesto',
'AudioOutcue' => 'Audion lopetus',
'AudioSamplingRate' => 'Audion näytetaajuus',
'AudioSamplingResolution' => 'Audion näyteresoluutio',
'AudioType' => {
Description => 'Audiotyyppi',
PrintConv => {
'Mono Actuality' => 'Aktuaalisuus (monoaudio (1 kanava))',
'Mono Music' => 'Musiikki, itsensä välittämä (monoaudio (1 kanava))',
'Mono Question and Answer Session' => 'Kysymys- ja vastausistunto (monoaudio (1 kanava))',
'Mono Raw Sound' => 'Raakaääni (monoaudio (1 kanava))',
'Mono Response to a Question' => 'Vastaus kysymykseen (monoaudio (1 kanava))',
'Mono Scener' => 'Kohtaus (monoaudio (1 kanava))',
'Mono Voicer' => 'Ihmisääni (monoaudio (1 kanava))',
'Mono Wrap' => 'Pakkaus (monoaudio (1 kanava))',
'Stereo Actuality' => 'Aktuaalisuus (stereoaudio (2 kanavaa))',
'Stereo Music' => 'Musiikki, itsensä välittämä (stereomono (2 kanavaa))',
'Stereo Question and Answer Session' => 'Kysymys- ja vastausistunto (stereoaudio (2 kanavaa))',
'Stereo Raw Sound' => 'Raakaääni (stereoaudio (2 kanavaa))',
'Stereo Response to a Question' => 'Vastaus kysymykseen (stereoaudio (2 kanavaa))',
'Stereo Scener' => 'Kohtaus (stereoaudio (2 kanavaa))',
'Stereo Voicer' => 'Ihmisääni (stereoaudio (2 kanavaa))',
'Stereo Wrap' => 'Pakkaus (stereoaudio (2 kanavaa))',
'Text Only' => 'Vain teksti (ei objektidataa)',
},
},
'Author' => 'Tekijä',
'AutoAperture' => 'Himmenninrengas A:ssa',
'AutoBracket' => 'Automaattihaarukointi',
'AutoBracketSet' => 'Haarukointisarja',
'AutoBracketing' => {
Description => 'Automaattinen haarukointi',
PrintConv => {
'No flash & flash' => 'Ei salamaa & Salama',
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'AutoDistortionControl' => 'Automaattinen vääristymäkorjaus',
'AutoExposureBracketing' => 'Automaattinen valotuksen haarukointi',
'AutoFP' => 'Automaattinen FP',
'AutoFocus' => {
Description => 'Automaattitarkennus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'AutoISO' => {
Description => 'Automaatti-ISO',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'AutoRedEye' => 'Automaattinen punasilmien esto',
'AutoRotate' => 'Automaattinen kuvankierto',
'AuxiliaryLens' => 'Lisälinssi',
'AvApertureSetting' => 'Av-aukkoasetus',
'BToA0' => 'B - A0',
'BToA1' => 'B - A1',
'BToA2' => 'B - A2',
'BWMode' => {
Description => 'M/V-muoto',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'BackgroundColor' => 'Taustaväri',
'BackgroundColorIndicator' => 'Taustavärin ilmaisin',
'BackgroundColorValue' => 'Taustavärin arvo',
'BadFaxLines' => 'Huonot faksirivit',
'BaseExposureCompensation' => 'Valotuksen perussäätö',
'BaseISO' => 'Perus-ISO',
'BaselineExposure' => 'Valotuksen perusta',
'BaselineNoise' => 'Kohinan perusta',
'BaselineSharpness' => 'Terävyyden perusta',
'BatteryLevel' => 'Pariston varaus',
'BatteryOrder' => 'Paristojärjestys',
'BayerGreenSplit' => 'Bayer Green Split -suodin',
'Beep' => 'Äänimerkki',
'BestQualityScale' => 'Parhaan laadun asteikko',
'BestShotMode' => {
Description => 'Parhaan kuvan tapa',
PrintConv => {
'Off' => 'Pois',
},
},
'BitDepth' => 'Bittisyvyys',
'BitsPerComponent' => 'Bittejä per komponentti',
'BitsPerExtendedRunLength' => 'Bittejä per jatkettu jakson pituus',
'BitsPerPixel' => 'Bittejä per pikseli',
'BitsPerRunLength' => 'Bittejä per jakson pituus',
'BitsPerSample' => 'Bittejä per näyte',
'BlackLevel' => 'Mustan taso',
'BlackLevel2' => 'Mustan taso 2',
'BlackLevelDeltaH' => 'Mustan tason Delta H',
'BlackLevelDeltaV' => 'Mustan tason Delta V',
'BlackLevelRepeatDim' => 'Mustan tason toiston dimensio',
'BlackMaskBottomBorder' => 'Mustan maskin alareuna',
'BlackMaskLeftBorder' => 'Mustan maskin vasen reuna',
'BlackMaskRightBorder' => 'Mustan maskin oikea reuna',
'BlackMaskTopBorder' => 'Mustan maskin yläreuna',
'BlackPoint' => 'Musta piste',
'BlueBalance' => 'Sinitasapaino',
'BlueMatrixColumn' => 'Sinisen matriisin sarake',
'BlueTRC' => 'Sinisen toonin toistokäyrä',
'BlueX' => 'Sininen X',
'BlueY' => 'Sininen Y',
'BlurWarning' => {
Description => 'Tärinävaroitus',
PrintConv => {
'Blur Warning' => 'Tärinävaroitus',
'None' => 'Ei mitään',
},
},
'BodyFirmwareVersion' => 'Rungon laiteohjelmistoversio',
'BorderID' => 'Kehyksen ID',
'BorderLocation' => 'Kehyksen sijainti',
'BorderName' => 'Kehyksen nimi',
'BorderType' => 'Kehyksen tyyppi',
'BordersVersion' => 'Kehysten versio',
'BracketMode' => 'Haarukointitapa',
'BracketSequence' => 'Haarukointijärjestys',
'BracketShotNumber' => 'Haarukoinnin otosnumero',
'BracketStep' => 'Haarukointiväli',
'BracketValue' => 'Haarukointiarvo',
'Brightness' => 'Kirkkaus',
'BrightnessData' => 'Kirkkausdata',
'BrightnessValue' => 'Kirkkausarvo',
'BulbDuration' => 'Aikavalotuksen kesto',
'BurstMode' => {
Description => 'Sarjatapa',
PrintConv => {
'Infinite' => 'Ääretön',
'Off' => 'Pois',
'On' => 'Matala/korkea laatu',
'Unlimited' => 'Rajaton',
},
},
'By-line' => 'Tekijä',
'By-lineTitle' => 'Tekijän ammattinimike',
'CCDScanMode' => {
Description => 'CCD-skannaustapa',
PrintConv => {
'Interlaced' => 'Lomitettu',
'Progressive' => 'Progressiivinen',
},
},
'CFALayout' => {
Description => 'CFA-sommitelma',
PrintConv => {
'Even columns offset down 1/2 row' => 'Horjahtanut sommitelma A: parilliset sarakkeet siirtyneet alas 1/2 riviä',
'Even columns offset up 1/2 row' => 'Horjahtanut sommitelma B: parilliset sarakkeet osiirtyneet ylös 1/2 riviä',
'Even rows offset left 1/2 column' => 'Horjahtanut sommitelma D: parilliset rivit siirtyneet vasemmalle 1/2 saraketta',
'Even rows offset right 1/2 column' => 'Horjahtanut sommitelma C: parilliset rivit siirtyneet oikealle 1/2 saraketta',
'Rectangular' => 'Suorakulmainen (tai neliömäinen) sommitelma',
},
},
'CFAPattern' => 'CFA-kuvio',
'CFAPattern2' => 'CFA-kuvio 2',
'CFAPlaneColor' => 'CFA-tasoväri',
'CFARepeatPatternDim' => 'Toistuvan CFA-kuvion laajuus',
'CLModeShootingSpeed' => 'Hidas jatkuva kuvaus (CL)',
'CMContrast' => 'CM:n kontrasti',
'CMExposureCompensation' => 'CM:n valotuksen säätö',
'CMHue' => 'CM:n sävy',
'CMMFlags' => 'CMM-liput',
'CMSaturation' => 'CM:n värikylläisyys',
'CMSharpness' => 'CM:n terävyys',
'CMWhiteBalance' => 'CM:n valkotasapaino',
'CMWhiteBalanceComp' => 'CM:n valkotasapainon säätö',
'CMWhiteBalanceGrayPoint' => 'CM:n valkotasapainon harmaapiste',
'CMYKEquivalent' => 'CMYK-vastaava',
'CPUFirmwareVersion' => 'CPU-laiteohjelmistoversio',
'CalibrationDateTime' => 'Kalibroinnin päiväysaika',
'CalibrationIlluminant1' => {
Description => 'Valaistuksen kalibrointi 1',
PrintConv => {
'Unknown' => 'Tuntematon',
},
},
'CalibrationIlluminant2' => {
Description => 'Valaistuksen kalibrointi 2',
PrintConv => {
'Unknown' => 'Tuntematon',
},
},
'CameraCalibration1' => 'Kameran kalibrointi 1',
'CameraCalibration2' => 'Kameran kalibrointi 2',
'CameraCalibrationSig' => 'Kameran kalibrointitunniste',
'CameraID' => 'Kameran ID',
'CameraISO' => 'Kamera-ISO',
'CameraOwner' => 'Kameran omistaja',
'CameraParameters' => 'Kameran parametrit',
'CameraSerialNumber' => 'Kameran rungon nro',
'CameraSettings' => 'Kameran asetukset',
'CameraSettingsVersion' => 'Kamera-asetusten versio',
'CameraTemperature' => 'Kameran lämpötila',
'CameraType' => 'Kameratyyppi',
'CameraType2' => 'Kameratyyppi 2',
'CanonAFInfo' => 'AF-info',
'CanonAFInfo2' => 'AF-info (2)',
'CanonFileInfo' => 'Tiedostoinfo',
'CanonFileLength' => 'Tiedoston pituus',
'CanonFirmwareVersion' => 'Laiteohjelmiston versio',
'CanonFlags' => 'Canon-liput',
'CanonImageType' => 'Kuvatyyppi',
'CanonModelID' => 'Mallin ID',
'Caption-Abstract' => 'Seloste/Kuvaus',
'CaptureConditionsPAR' => 'PAR-kuvausolosuhteet',
'CaptureDeviceFID' => 'Kuvauslaitteen FID',
'CasioImageSize' => 'Casion kuvakoko',
'Category' => 'Kategoria',
'CellLength' => 'Kennon pituus',
'CellWidth' => 'Kennon leveys',
'CenterAFArea' => 'Keskialueen AF',
'CharTarget' => 'Kirjainmerkin kohde',
'CharacterSet' => 'Merkistö',
'ChromaBlurRadius' => 'Kromaattisen sumeuden säde',
'ChromaticAdaptation' => 'Kromaattinen adaptaatio',
'Chromaticity' => 'Kromaattisuus',
'City' => 'Kaupunki',
'ClassifyState' => 'Luokitustila',
'CleanFaxData' => 'Poista faksidata',
'ClipPath' => 'Leikepolku',
'CodedCharacterSet' => 'Koodattu merkistö',
'ColorAberrationControl' => 'Väripoikkeaman hallinta',
'ColorAdjustment' => 'Värien säätö',
'ColorAdjustmentMode' => {
Description => 'Värin säätötapa',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'ColorBalance' => 'Väritasapaino',
'ColorBalanceAdj' => 'Väritasapainon säätö',
'ColorBalanceBlue' => 'Väritasapaino sininen',
'ColorBalanceGreen' => 'Väritasapaino vihreä',
'ColorBalanceRed' => 'Väritasapaino punainen',
'ColorBoostData' => 'Väritehostusdata',
'ColorBoostLevel' => 'Väritehostustaso',
'ColorBoostType' => 'Väritehostustyyppi',
'ColorBooster' => 'Väritehostus',
'ColorCalibrationMatrix' => 'Värien kalibrointimatriisitaulukko',
'ColorCharacterization' => 'Värin luonnehdinta',
'ColorCompensationFilter' => 'Värikorjailusuodin',
'ColorControl' => 'Värisäätö',
'ColorEffect' => {
Description => 'Väriefekti',
PrintConv => {
'Black & White' => 'Musta & Valkoinen',
'Cool' => 'Viileä',
'Off' => 'Pois',
'Sepia' => 'Seepia',
'Warm' => 'Lämmin',
},
},
'ColorFilter' => {
Description => 'Värisuodin',
PrintConv => {
'Off' => 'Pois',
},
},
'ColorGain' => 'Värien vahvistus',
'ColorHue' => 'Värisävy',
'ColorInfo' => 'Väritiedot',
'ColorMap' => 'Värikartta',
'ColorMatrix' => 'Värimatriisi',
'ColorMatrix1' => 'Värimatriisi 1',
'ColorMatrix2' => 'Värimatriisi 2',
'ColorMatrixNumber' => 'Värimatriisin numero',
'ColorMode' => {
Description => 'Värimuoto',
PrintConv => {
'Autumn Leaves' => 'Syksyn lehdet',
'B & W' => 'M & V',
'B&W' => 'M&V',
'Black & White' => 'Heleät värit',
'Chrome' => 'Kellastunut',
'Clear' => 'Selkeä',
'Deep' => 'Syvä',
'Evening' => 'Ilta',
'Landscape' => 'Maisema',
'Light' => 'Valoisa',
'Natural' => 'Luonnollinen',
'Natural color' => 'Luonnonvalo',
'Natural sRGB' => 'Luonnollinen sRGB',
'Natural+ sRGB' => 'Luonnollinen+ sRGB',
'Neutral' => 'Neutraali',
'Night Portrait' => 'Yön muotokuva',
'Night Scene' => 'Yönäkymä',
'Night View' => 'Iltanäkymä',
'Night View/Portrait' => 'Yönäkymä',
'Normal' => 'Normaali',
'Off' => 'Pois',
'Portrait' => 'Muotokuva',
'Sepia' => 'Seepia',
'Solarization' => 'Solarisaatio',
'Standard' => 'Vakio',
'Sunset' => 'Auringonlasku',
'Vivid' => 'Heleät värit',
'Vivid color' => 'Heleä väri',
},
},
'ColorMoireReduction' => 'Värimoareen vaimennus',
'ColorPalette' => 'Väripaletti',
'ColorProfile' => 'Väriprofiili',
'ColorRepresentation' => 'Väriesitys',
'ColorReproduction' => 'Värientoisto',
'ColorResponseUnit' => 'Värin vasteyksikkö',
'ColorSamplersResource' => 'Värinäytteenotinresurssit',
'ColorSequence' => 'Värien esitys',
'ColorSpace' => {
Description => 'Väriavaruus',
PrintConv => {
'ICC Profile' => 'ICC-profiili',
'Uncalibrated' => 'Kalibroimaton',
'Wide Gamut RGB' => 'Laaja Gamut RVB',
},
},
'ColorTable' => 'Väritaulukko',
'ColorTemperature' => 'Värilämpötila',
'ColorTone' => 'Värisävy',
'ColorToneFaithful' => 'Kohdeuskollinen värisävy',
'ColorToneLandscape' => 'Maisemakuvan värisävy',
'ColorToneNeutral' => 'Neutraali värisävy',
'ColorTonePortrait' => 'Muotokuvan värisävy',
'ColorToneStandard' => 'Vakiovärisävy',
'ColorType' => 'Värityyppi',
'ColorantOrder' => 'Väriainejärjestys',
'ColorantTable' => 'Väriainetaulukko',
'ColorimetricReference' => 'Kolorimetrinen referenssi',
'Comment' => 'Kommentti',
'ComponentsConfiguration' => 'Kunkin komponentin tarkoitus',
'CompressedBitsPerPixel' => 'Kuvan pakkausmuoto',
'CompressedImageSize' => 'Pakatun kuvan koko',
'Compression' => 'Pakkausskeema',
'CompressionRatio' => 'Pakkaussuhde',
'ConnectionSpaceIlluminant' => 'Yhteystilan valaistus',
'ConsecutiveBadFaxLines' => 'Peräkkäiset huonot faksirivit',
'Contact' => 'Kontakti',
'ContentLocationCode' => 'Sisällön sijaintikoodi',
'ContentLocationName' => 'Sisällön sijaintinimi',
'ContinuousBracketing' => 'Jatkuva haarukointi',
'Contrast' => {
Description => 'Kontrasti',
PrintConv => {
'Film Simulation' => 'Filminsimulaatio',
'High' => 'Korkea',
'Low' => 'Matala',
'Medium High' => 'Korkeahko',
'Medium Low' => 'Matalahko',
'Normal' => 'Vakio',
},
},
'ContrastAdjustment' => 'Kontrastin säätö',
'ContrastCurve' => 'Kontrastikäyrä',
'ContrastFaithful' => 'Kohdeuskollinen kontrasti',
'ContrastLandscape' => 'Maisemakuvan kontrasti',
'ContrastMonochrome' => 'Yksivärikuvan kontrasti',
'ContrastNeutral' => 'Neutraali kontrasti',
'ContrastPortrait' => 'Muotokuvan kontrasti',
'ContrastSetting' => 'Kontrastiasetus',
'ContrastStandard' => 'Vakiokontrasti',
'ControlMode' => 'Ohjaustapa',
'ConversionLens' => {
Description => 'Objektiivilisäke',
PrintConv => {
'Macro' => 'Makro',
'Off' => 'Pois',
'Telephoto' => 'Tele',
'Wide' => 'Laajakulma',
},
},
'Converter' => 'Konvertteri',
'Copyright' => 'Profiilin copyright',
'CopyrightFlag' => 'Copyright-lippu',
'CopyrightNotice' => 'Tekijänoikeusilmoitus',
'CoringFilter' => 'Ydinsuodin',
'CoringValues' => 'Ydinsuodatusarvot',
'Country-PrimaryLocationCode' => 'ISO-maakoodi',
'Country-PrimaryLocationName' => 'Maa',
'CreateDate' => 'Digitaalisen datan luonnin päiväys ja aika',
'CreationDate' => 'Luontipäivä',
'CreativeStyle' => {
Description => 'Luova tyyli',
PrintConv => {
'Autumn Leaves' => 'Syksyn lehdet',
'B&W' => 'M&V',
'Clear' => 'Selkeä',
'Deep' => 'Syvä',
'Landscape' => 'Maisema',
'Light' => 'Valoisa',
'Neutral' => 'Neutraali',
'Night View/Portrait' => 'Yönäkymä',
'Portrait' => 'Muotokuva',
'Sepia' => 'Seepia',
'Standard' => 'Vakio',
'Sunset' => 'Auringonlasku',
'Vivid' => 'Heleät värit',
},
},
'CreatorAddress' => 'Tekijä - Osoite',
'CreatorCity' => 'Tekijä - Kaupunki',
'CreatorCountry' => 'Tekijä - Maa',
'CreatorPostalCode' => 'Tekijä - Postinumero',
'CreatorRegion' => 'Tekijä - Valtio/Provinssi',
'CreatorWorkEmail' => 'Tekijä - email(it)',
'CreatorWorkTelephone' => 'Tekijä - Puhelinnumero(t)',
'CreatorWorkURL' => 'Tekijä - Web-sivusto(t)',
'Credit' => 'Tarjoaja',
'CropBottom' => 'Rajaus alhaalta',
'CropData' => 'Rajausdata',
'CropLeft' => 'Rajaus vasemmalta',
'CropOutputHeight' => 'Rajaustuloksen korkeus',
'CropOutputPixels' => 'Rajaustulokset pikselit',
'CropOutputResolution' => 'Rajaustuloksen resoluutio',
'CropOutputScale' => 'Rajaustuloksen mittasuhteet',
'CropOutputWidth' => 'Rajaustuloksen leveys',
'CropRight' => 'Rajaus oikealta',
'CropScaledResolution' => 'Rajauksen skaalausresoluutio',
'CropSourceResolution' => 'Rajauslähteen resoluutio',
'CropTop' => 'Rajaus ylhäältä',
'CurrentICCProfile' => 'Nykyinen ICC-profiili',
'CurrentPreProfileMatrix' => 'Nykyinen pre-profiilimatriisi',
'Curves' => 'Käyrät',
'Custom1' => 'Mukautus 1',
'Custom2' => 'Mukautus 2',
'Custom3' => 'Mukautus 3',
'Custom4' => 'Mukautus 4',
'CustomRendered' => {
Description => 'Mukautettu kuvankäsittely',
PrintConv => {
'Custom' => 'Mukautettu käsittely',
'Normal' => 'Normaali käsittely',
},
},
'CustomSaturation' => 'Mukautettu värikylläisyys',
'D-LightingHQColorBoost' => 'D-Lighting HQ -väritehostus',
'D-LightingHQHighlight' => 'D-Lighting HQ -valoalue',
'D-LightingHQSelected' => 'Valittu D-Lighting HQ',
'D-LightingHQShadow' => 'D-Lighting HQ -varjoalue',
'D-LightingHSAdjustment' => 'D-Lighting HS -säätö',
'D-LightingHSColorBoost' => 'D-Lighting HS -väritehostus',
'DECPosition' => 'DEC-sijainti',
'DNGBackwardVersion' => 'Edellinen DNG-versio',
'DNGVersion' => 'DNG-versio',
'DSPFirmwareVersion' => 'DSP-laiteohjelmistoversio',
'DataDump' => 'Datadumppi',
'DataImprint' => 'Datan sisällytys',
'DataType' => 'Mattaus',
'Date' => 'Päiväys',
'DateCreated' => 'Luontipäiväys',
'DateImprint' => 'Päiväysleima',
'DateSent' => 'Lähetyspäivä',
'DateStampMode' => 'Päiväysleiman muoto',
'DateTime' => 'Päiväysaika',
'DateTimeOriginal' => 'Alkuperäisen datan luonnin päiväys ja aika',
'DealerIDNumber' => 'Myyjän ID-numero',
'DefaultCropOrigin' => 'Oletusrajauksen alkuperä',
'DefaultCropSize' => 'Oletusrajauskoko',
'DefaultScale' => 'Oletusasteikko',
'DeletedImageCount' => 'Poistettujen kuvien määrä',
'Description' => 'Deskriptio',
'Destination' => 'Kohde',
'DestinationCity' => 'Kohdepaikkakunta',
'DestinationCityCode' => 'Kohdepaikkakoodi',
'DestinationDST' => {
Description => 'Kohteen kesäaika (DST)',
PrintConv => {
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'DevelopmentDynamicRange' => 'Dynamiikka-alueen kehitys',
'DeviceAttributes' => 'Laiteattribuutit',
'DeviceManufacturer' => 'Laitteen valmistaja',
'DeviceMfgDesc' => 'Laitteen valmistajan kuvaus',
'DeviceModel' => 'Laitteen malli',
'DeviceModelDesc' => 'Laitemallin kuvaus',
'DeviceSettingDescription' => 'Laiteasetusten kuvaus',
'DigitalCreationDate' => 'Digitalisointipäiväys',
'DigitalCreationTime' => 'Digitalisointiaika',
'DigitalDEEHighlightAdj' => 'Digitaalinen DEE -vaalean pään säätö',
'DigitalDEEShadowAdj' => 'Digitaalinen DEE-varjonsäätö',
'DigitalDEEThreshold' => 'Digitaalinen DEE-kynnys',
'DigitalEffectsName' => 'Digitaalisten efektien nimi',
'DigitalEffectsType' => 'Digitaalisten efektien tyyppi',
'DigitalEffectsVersion' => 'Digitaalisten efektien versio',
'DigitalGEM' => 'Digitaalinen GEM',
'DigitalGain' => 'Digitaalinen vahvistus',
'DigitalICE' => 'Digitaalinen ICE',
'DigitalROC' => 'Digitaalinen ROC',
'DigitalZoom' => 'Digitaalinen zoom',
'DigitalZoomOn' => {
Description => 'Digitaalinen zoom',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'DigitalZoomRatio' => 'Digitaalinen zoomaussuhde',
'DirectoryIndex' => 'Kansioindeksi',
'DirectoryNumber' => 'Kansion numero',
'DisplayAperture' => 'Aukon näyttö',
'DisplayedUnitsX' => 'Vaakaresoluution yksikkö',
'DisplayedUnitsY' => 'Pystyresoluution yksikkö',
'DistortionCorrection' => 'Vääristymäkorjaus',
'DocumentHistory' => 'Dokumentin historia',
'DocumentName' => 'Dokumentin nimi',
'DocumentNotes' => 'Dokumentin huomautukset',
'DotRange' => 'Pisteiden määrä',
'DriveMode' => 'Kuvaustapa',
'DriveMode2' => 'Kuvaustapa 2',
'DustRemovalData' => 'Pölynpoistodata',
'DynamicAFArea' => 'Dynaamisen alueen AF',
'DynamicRange' => {
Description => 'Dynamiikka-alue',
PrintConv => {
'Standard' => 'Vakio',
'Wide' => 'Laaja',
},
},
'DynamicRangeExpansion' => {
Description => 'Dynamiikka-alueen laajennus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'DynamicRangeOptimizer' => {
Description => 'Dynamiikka-alueen optimointi',
PrintConv => {
'Advanced Auto' => 'Edistynyt automatiikka',
'Advanced Lv1' => 'Edistynyt taso 1',
'Advanced Lv2' => 'Edistynyt taso 2',
'Advanced Lv3' => 'Edistynyt taso 3',
'Advanced Lv4' => 'Edistynyt taso 4',
'Advanced Lv5' => 'Edistynyt taso 5',
'Off' => 'Pois',
'Standard' => 'Vakio',
},
},
'DynamicRangeSetting' => {
Description => 'Dynamiikka-alueen säätö',
PrintConv => {
'Film Simulation' => 'Filminsimulaatio',
'Standard (100%)' => 'Vakio (100%)',
'Wide1 (230%)' => 'Laaja 1 (230%)',
'Wide2 (400%)' => 'Laaja 2 (400%)',
},
},
'E-DialInProgram' => 'Säätökiekko ohjelmassa',
'EVStepInfo' => 'EV-askeltiedot',
'EVStepSize' => 'EV-askeleen koko',
'EVSteps' => 'EV-askeleet',
'EasyExposureCompensation' => 'Valotuksen pikakorjaus',
'EasyMode' => 'Helppo tapa',
'EdgeNoiseReduction' => 'Reunakohinan vaimennus',
'EditStatus' => 'Editoinnin tila',
'EditTagArray' => 'Muokkaa tagiryhmää',
'EditorialUpdate' => {
Description => 'Sisällön päivitys',
PrintConv => {
'Additional language' => 'Lisäkielet',
},
},
'EffectiveLV' => 'Tehollinen valoarvo (LV)',
'EffectiveMaxAperture' => 'Suurin tehollinen aukko',
'Encoder' => 'Kooderi',
'EncodingProcess' => 'Koodausmetodi',
'EndPoints' => 'Loppupisteet',
'EnhanceDarkTones' => 'Tummien sävyjen parantelu',
'Enhancement' => {
Description => 'Parantelu',
PrintConv => {
'Blue' => 'Sininen',
'Flesh Tones' => 'Lihanvärinen',
'Green' => 'Vihreä',
'Off' => 'Pois',
'Red' => 'Punainen',
},
},
'EnhancerValues' => 'Korjainarvot',
'EnvelopeNumber' => 'Pakkauksen numero',
'EnvelopePriority' => {
Description => 'Pakkauksen prioriteetti',
PrintConv => {
'0 (reserved)' => '0 (varattu tulevaan käyttöön)',
'1 (most urgent)' => '1 (hyvin kiireellinen)',
'5 (normal urgency)' => '5 (normaali kiireellisyys)',
'8 (least urgent)' => '8 (lievän kiireellinen)',
'9 (user-defined priority)' => '9 (käyttäjän määrittämä prioriteetti)',
},
},
'EnvelopeRecordVersion' => 'Pakkaustietueen versio',
'EpsonImageHeight' => 'Epson-kuvan korkeus',
'EpsonImageWidth' => 'Epson-kuvan leveys',
'EpsonSoftware' => 'Epson-ohjelmisto',
'Equipment' => 'Välineistön IFD-osoitin',
'EquipmentVersion' => 'Välineistöversio',
'ExcursionTolerance' => {
Description => 'Toleranssin ekskursio',
PrintConv => {
'Allowed' => 'Voi toteutua',
'Not Allowed' => 'Ei sallittu (oletus)',
},
},
'ExifCameraInfo' => 'Exif-kameratiedot',
'ExifImageHeight' => 'Kuvan korkeus',
'ExifImageWidth' => 'Kuvan leveys',
'ExifVersion' => 'Exif-versio',
'ExitPupilPosition' => 'Lähtöpupillin sijainti',
'ExpandFilm' => 'Filmilaajennus',
'ExpandFilterLens' => 'Suodinlinssilaajennus',
'ExpandFlashLamp' => 'Salamavalolaajennus',
'ExpandLens' => 'Objektiivilaajennus',
'ExpandScanner' => 'Skannerilaajennus',
'ExpandSoftware' => 'Ohjelmistolaajennus',
'ExpirationDate' => 'Päättymispäiväys',
'ExpirationTime' => 'Päättymisaika',
'Exposure' => 'Valotus',
'ExposureBracketStepSize' => 'Valotuksen haarukointiväli',
'ExposureBracketValue' => 'Valotushaarukoinnin arvo',
'ExposureCompensation' => 'Valotuksen korjaus',
'ExposureDelayMode' => 'Valotuksen viivetila',
'ExposureDifference' => 'Valotusero',
'ExposureIndex' => 'Valotusindeksi',
'ExposureMode' => {
Description => 'Valotustapa',
PrintConv => {
'Aperture Priority' => 'Aukon esivalinta',
'Aperture-priority AE' => 'Aukon esivalinta AE',
'Auto' => 'Automaattinen',
'Auto bracket' => 'Automaattihaarukointi',
'Landscape' => 'Maisema',
'Manual' => 'Manuaalinen',
'Night Scene / Twilight' => 'Yönäkymä',
'Program' => 'Ohjelma',
'Program AE' => 'Ohjelma-AE',
'Program-shift' => 'Ohjelma-siirto',
'Shutter Priority' => 'Ajan esivalinta',
'Shutter speed priority AE' => 'Ajan esivalinta AE',
'n/a' => 'Ei asetettu',
},
},
'ExposureProgram' => {
Description => 'Valotusohjelma',
PrintConv => {
'Action (High speed)' => 'Toimintaohjelma (painotettu suljinnopeutta)',
'Aperture-priority AE' => 'Aukon esivalinta',
'Creative (Slow speed)' => 'Luova ohjelma (painotettu syväterävyyttä)',
'Landscape' => 'Maisemamoodi (maisemakuviin terävällä taustalla)',
'Manual' => 'Manuaalinen',
'Not Defined' => 'Ei määritetty',
'Portrait' => 'Muotokuvamoodi (lähikuviin epäterävällä taustalla)',
'Program AE' => 'Normaali ohjelma',
'Shutter speed priority AE' => 'Ajan esivalinta',
},
},
'ExposureTime' => 'Valotusaika',
'ExposureTime2' => 'Valotusaika 2',
'ExposureWarning' => {
Description => 'Valotusvaroitus',
PrintConv => {
'Bad exposure' => 'Valotusvirhe',
'Good' => 'OK',
},
},
'ExtendedWBDetect' => {
Description => 'Laajennettu valkotas. tunnistus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'Extender' => 'Konvertteri',
'ExtenderFirmwareVersion' => 'Konvertterin laiteohjelmistoversio',
'ExtenderModel' => 'Konvertterimalli',
'ExtenderSerialNumber' => 'Konvertterin sarjanumero',
'ExternalFlash' => 'Ulkoinen salama',
'ExternalFlashAE1' => 'Ulkoinen salama AE 1?',
'ExternalFlashAE1_0' => 'Ulkoinen salama AE 1 (0)?',
'ExternalFlashAE2' => 'Ulkoinen salama AE 2?',
'ExternalFlashAE2_0' => 'Ulkoinen salama AE 2 (0)?',
'ExternalFlashBounce' => {
Description => 'Ulkoisen salaman heijastus',
PrintConv => {
'Bounce or Off' => 'Heijastus tai pois',
'Direct' => 'Suora',
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'ExternalFlashExposureComp' => 'Ulkoisen salaman valotuksen säätö',
'ExternalFlashFlags' => 'Ulkoisen salaman liput',
'ExternalFlashGuideNumber' => 'Ulkoisen salaman ohjeluku?',
'ExternalFlashMode' => 'Ulkoisen salaman tapa',
'ExternalFlashZoom' => 'Ulkoisen salaman zoom',
'ExtraSamples' => 'Lisänäytteet',
'FNumber' => 'Aukkoarvo',
'Face1Position' => 'Kasvojen 1 sijainti',
'Face2Position' => 'Kasvojen 2 sijainti',
'Face3Position' => 'Kasvojen 3 sijainti',
'Face4Position' => 'Kasvojen 4 sijainti',
'Face5Position' => 'Kasvojen 5 sijainti',
'Face6Position' => 'Kasvojen 6 sijainti',
'Face7Position' => 'Kasvojen 7 sijainti',
'Face8Position' => 'Kasvojen 8 sijainti',
'Face9Position' => 'Kasvojen 9 sijainti',
'FaceDetect' => 'Kasvojen tunnistus',
'FacePositions' => 'Kasvojen sijainnit',
'FacesDetected' => 'Tunnistetut kasvot',
'FaxRecvParams' => 'Faxin vastaanottoparametrit',
'FaxRecvTime' => 'Faxin vastaanottoaika',
'FaxSubAddress' => 'Faxin alaosoite',
'FileFormat' => 'Tiedostomuoto',
'FileIndex' => 'Tiedostoindeksi',
'FileInfo' => 'Tiedostoinfot',
'FileInfoVersion' => 'Tiedostoinfojen versio',
'FileNumber' => 'Tiedoston numero',
'FileNumberMemory' => 'Tiedostonumeromuisti',
'FileNumberSequence' => 'Tiedostojen numerojärjestys',
'FileSize' => 'Tiedoston koko',
'FileSource' => {
Description => 'Tiedoston lähde',
PrintConv => {
'Digital Camera' => 'Digitaalikamera',
'Film Scanner' => 'Filmiskanneri',
'Reflection Print Scanner' => 'Heijastava skanneri',
},
},
'FileType' => 'Tiedostotyyppi',
'Filename' => 'Tiedostonimi',
'FillOrder' => 'Täyttöjärjestys',
'FilmCategory' => 'Filmiluokka',
'FilmGencode' => 'Filmin gencode',
'FilmMode' => {
Description => 'Filmitila',
PrintConv => {
'Dynamic (B&W)' => 'Dynaaminen (M&V)',
'Dynamic (color)' => 'Dynaaminen (väri)',
'F0/Standard (PROVIA)' => 'F0/vakio',
'F1/Studio Portrait' => 'F1/studiomuotokuva',
'F1a/Studio Portrait Enhanced Saturation' => 'F1a/studiomuotokuva laajennettu värikylläisyys',
'F1b/Studio Portrait Smooth Skin Tone (ASTIA)' => 'F1b/studiomuotokuva pehmeä ihonväri',
'F1c/Studio Portrait Increased Sharpness' => 'F1c/studiomuotokuva lisätty terävyys',
'F3/Studio Portrait Ex' => 'F3/studiomuotokuva Ex',
'Nature (color)' => 'Luonnollinen (väri)',
'Nostalgic' => 'Nostalginen väri',
'Smooth (B&W)' => 'Pehmeä (M&V)',
'Smooth (color)' => 'Pehmeä (väri)',
'Standard (B&W)' => 'Vakio (M&V)',
'Standard (color)' => 'Vakio (väri)',
'Vibrant' => 'Eloisa väri',
},
},
'FilmProductCode' => 'Filmin tuotekoodi',
'FilmType' => 'Filmityyppi',
'Filter' => 'Suodin',
'FilterEffect' => 'Suodinefekti',
'FilterEffectMonochrome' => 'Yksivärisuodintehoste',
'Firmware' => 'Laiteohjelmisto',
'FirmwareDate' => 'Laiteohjelmiston päiväys',
'FirmwareID' => 'Laiteohjelmiston ID',
'FirmwareRevision' => 'Laiteohjelmiston revisio',
'FirmwareVersion' => 'Laiteohjelmiston versio',
'FixtureIdentifier' => 'Ominaisuuden tunnistin',
'Flash' => {
Description => 'Salama',
PrintConv => {
'Auto, Did not fire' => 'Salama ei lauennut, automaattimoodi',
'Auto, Did not fire, Red-eye reduction' => 'Automaattinen, salama ei lauennut, punasilmien esto',
'Auto, Fired' => 'Salama lauennut, automaattimoodi',
'Auto, Fired, Red-eye reduction' => 'Salama lauennut, automaattimoodi, punasilmien estomoodi',
'Auto, Fired, Red-eye reduction, Return detected' => 'Salama lauennut, automaattimoodi, heijastusvalo havaittu, punasilmien estomoodi',
'Auto, Fired, Red-eye reduction, Return not detected' => 'Salama lauennut, automaattimoodi, heijastusvaloa ei havaittu, punasilmien estomoodi',
'Auto, Fired, Return detected' => 'Salama lauennut, automaattimoodi. heijastusvalo havaittu',
'Auto, Fired, Return not detected' => 'Salama lauennut, automaattimoodi, heijastusvaloa ei havaittu',
'Fired' => 'Salama lauennut',
'Fired, Red-eye reduction' => 'Salama lauennut, punasilmien estomoodi',
'Fired, Red-eye reduction, Return detected' => 'Salama lauennut, punasilmien estomoodi, heijastusvalo havaittu',
'Fired, Red-eye reduction, Return not detected' => 'Salama lauennut, punasilmien estomoodi, heijastusvaloa ei havaittu',
'Fired, Return detected' => 'Strobo-salaman heijastus havaittu',
'Fired, Return not detected' => 'Strobo-salaman heijastusta ei havaittu',
'No Flash' => 'Salama ei lauennut',
'No flash function' => 'Ei salamatoimintoa',
'Off, Did not fire' => 'Salama ei lauennut, pakkosalamatila',
'Off, Did not fire, Return not detected' => 'Pois, salama ei lauennut, heijastusta ei havaittu',
'Off, No flash function' => 'Pois, ei salamatoimintoa',
'Off, Red-eye reduction' => 'Pois, punasilmien esto',
'On, Did not fire' => 'Päällä, salama ei lauennut',
'On, Fired' => 'Salama lauennut, pakkosalamatila',
'On, Red-eye reduction' => 'Salama lauennut, pakkosalamatila, punasilmien estomoodi',
'On, Red-eye reduction, Return detected' => 'Salama lauennut, pakkosalamatila, punasilmien estomoodi, heijastusvalo havaittu',
'On, Red-eye reduction, Return not detected' => 'Salama lauennut, pakkosalamatila, punasilmien estomoodi, heijastusvaloa ei havaittu',
'On, Return detected' => 'Salama lauennut, pakkosalamatila, heijastusvalo havaittu',
'On, Return not detected' => 'Salama lauennut, pakkosalamatila, heijastusvaloa ei havaittu',
},
},
'FlashActivity' => 'Salaman toiminta',
'FlashBias' => 'Salaman muutos',
'FlashChargeLevel' => 'Salaman varaustila',
'FlashCompensation' => 'Salaman säätö',
'FlashControlMode' => 'Salaman ohjaustapa',
'FlashDevice' => 'Salamalaite',
'FlashDistance' => 'Salamaetäisyys',
'FlashEnergy' => 'Salaman teho',
'FlashExposureBracketValue' => 'Salamavalotuksen haarukoinnin arvo',
'FlashExposureComp' => 'Salaman kirkkauden säätö',
'FlashFired' => {
Description => 'Salama lauennut',
PrintConv => {
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'FlashFirmwareVersion' => 'Salaman laiteohjelmistoversio',
'FlashFocalLength' => 'Salaman polttoväli',
'FlashGuideNumber' => 'Salaman ohjeluku',
'FlashInfoVersion' => 'Salaman tietojen versio',
'FlashIntensity' => {
Description => 'Salaman teho',
PrintConv => {
'High' => 'Korkea',
'Low' => 'Matala',
'Normal' => 'Normaali',
'Strong' => 'Voimakas',
'Weak' => 'Heikko',
},
},
'FlashMetering' => 'Salamamittaus',
'FlashMeteringSegments' => 'Salaman mittaussegmentit',
'FlashMode' => {
Description => 'Salamatapa',
PrintConv => {
'Auto' => 'Automaattinen',
'Did Not Fire' => 'Ei lauennut',
'Disabled' => 'Deaktivoitu',
'Fired, Commander Mode' => 'Lauennut, pakkotapa',
'Fired, External' => 'Lauennut, ulkoinen',
'Fired, Manual' => 'Lauennut, manuaalinen',
'Fired, TTL Mode' => 'Lauennut, TTL-tapa',
'Force' => 'Pakkotapa',
'Not Ready' => 'Ei valmis',
'Off' => 'Pois (3)',
'On' => 'Päällä (2)',
'Red eye' => 'Punasilmien esto',
},
},
'FlashModel' => {
Description => 'Salaman malli',
PrintConv => {
'None' => 'Ei mitään',
},
},
'FlashOptions' => 'Salamavalinnat',
'FlashOutput' => 'Salaman teho',
'FlashRemoteControl' => 'Salaman kaukosäätö',
'FlashSerialNumber' => 'Salaman sarjanumero',
'FlashSetting' => 'Salaman asetus',
'FlashShutterSpeed' => 'Suljinaika salamakuvauksessa',
'FlashStatus' => 'Salaman tila',
'FlashSyncSpeed' => 'Salaman täsmäysaika',
'FlashType' => {
Description => 'Salamatyyppi',
PrintConv => {
'E-System' => 'E-järjestelmä',
'None' => 'Ei mitään',
'Simple E-System' => 'Yksinkertainen E-järjestelmä',
},
},
'FlashWarning' => 'Salamavaroitus',
'FlashpixVersion' => 'Tuettu Flashpix-versio',
'FlickerReduce' => {
Description => 'Värinän vaimennus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'FlipHorizontal' => 'Kiepautus vaakatasossa',
'FocalLength' => 'Polttoväli',
'FocalLengthIn35mmFormat' => 'Polttoväli 35 mm filmikoolla',
'FocalPlaneDiagonal' => 'Polttopistetason lävistäjä',
'FocalPlaneResolutionUnit' => {
Description => 'Polttopistetason resoluutioyksikkö',
PrintConv => {
'None' => 'Ei mitään',
'inches' => 'Tuuma',
'um' => 'µm (mikrometri)',
},
},
'FocalPlaneXResolution' => 'Polttopistetason vaakaresoluutio',
'FocalPlaneXSize' => 'Polttopistetason leveys',
'FocalPlaneYResolution' => 'Polttopistetason pystyresoluutio',
'FocalPlaneYSize' => 'Polttopistetason korkeus',
'FocalType' => 'Objektiivityyppi',
'Focus' => 'Tarkennusesivalinta',
'FocusArea' => 'Tarkennusalue',
'FocusAreaSelection' => 'Tarkennusalueen valinta',
'FocusContinuous' => 'Jatkuva tarkennus',
'FocusDistanceLower' => 'Lähitarkennus',
'FocusDistanceUpper' => 'Kaukotarkennus',
'FocusMode' => {
Description => 'Tarkennustapa',
PrintConv => {
'Auto' => 'Automaattinen',
'Manual' => 'Manuaalinen',
},
},
'FocusMode2' => 'Tarkennustapa',
'FocusPixel' => 'Tarkennuspikseli',
'FocusPosition' => 'Polttopisteen paikka',
'FocusProcess' => 'Tarkennusprosessi',
'FocusRange' => {
Description => 'Tarkennusalue',
PrintConv => {
'Macro' => 'Makro',
'Normal' => 'Normaali',
},
},
'FocusSetting' => 'Tarkennusasetus',
'FocusStepCount' => 'Tarkennusaskelmäärä',
'FocusWarning' => {
Description => 'Tarkennusvaroitus',
PrintConv => {
'Good' => 'OK',
'Out of focus' => 'Epätarkka',
},
},
'FolderName' => 'Kansion nimi',
'ForwardMatrix1' => 'Eteenpäin-matriisi 1',
'ForwardMatrix2' => 'Eteenpäin-matriisi 2',
'FrameHeight' => 'Ruudun korkeus',
'FrameNumber' => 'Ruudun numero',
'FrameWidth' => 'Ruudun leveys',
'FreeByteCounts' => 'Vapaiden tavujen määrät',
'FreeMemoryCardImages' => 'Muistikortilla tilaa',
'FreeOffsets' => 'Vapaat siirtymät',
'FujiFlashMode' => {
Description => 'Salamatila',
PrintConv => {
'External' => 'Ulkoinen salama',
'Off' => 'Pois',
'On' => 'Päällä',
'Red-eye reduction' => 'Punasilmäisyyden vähennys',
},
},
'GEMInfo' => 'GEM-tiedot',
'GEModel' => 'Malli',
'GIFVersion' => 'GIF-versio',
'GPSAltitude' => 'Korkeus',
'GPSAltitudeRef' => {
Description => 'Viitekorkeus',
PrintConv => {
'Above Sea Level' => 'Merenpinnan korkeus',
'Below Sea Level' => 'Merenpinnan viitekorkeus (negatiivinen arvo)',
},
},
'GPSAreaInformation' => 'GPS-alueen nimi',
'GPSDOP' => 'Mittaustarkkuus',
'GPSDateStamp' => 'GPS-päiväys',
'GPSDestBearing' => 'Kohteen suuntima',
'GPSDestBearingRef' => {
Description => 'Kohteen suuntiman viite',
PrintConv => {
'Magnetic North' => 'Magneettinen suunta',
'True North' => 'Todellinen suunta',
},
},
'GPSDestDistance' => 'Etäisyys kohteeseen',
'GPSDestDistanceRef' => {
Description => 'Viite etäisyydelle kohteeseen',
PrintConv => {
'Kilometers' => 'Kilometriä',
'Miles' => 'Mailia',
'Nautical Miles' => 'Solmua',
},
},
'GPSDestLatitude' => 'Kohteen leveysaste',
'GPSDestLatitudeRef' => {
Description => 'Kohteen leveysasteen viite',
PrintConv => {
'North' => 'Pohjoista leveyttä',
'South' => 'Eteläistä leveyttä',
},
},
'GPSDestLongitude' => 'Kohteen pituusaste',
'GPSDestLongitudeRef' => {
Description => 'Kohteen pituusasteen viite',
PrintConv => {
'East' => 'Itäistä pituutta',
'West' => 'Läntistä pituutta',
},
},
'GPSDifferential' => {
Description => 'GPS-differentiaalikorjaus',
PrintConv => {
'Differential Corrected' => 'Differentiaalikorjausta käytetty',
'No Correction' => 'Mittaus ilman differentiaalikorjausta',
},
},
'GPSImgDirection' => 'Kuvan´ suunta',
'GPSImgDirectionRef' => {
Description => 'Kuvan suunnan viite',
PrintConv => {
'Magnetic North' => 'Magneettinen suunta',
'True North' => 'Todellinen suunta',
},
},
'GPSLatitude' => 'Leveysaste',
'GPSLatitudeRef' => {
Description => 'Pohjoista tai eteläistä leveyttä',
PrintConv => {
'North' => 'Pohjoista leveyttä',
'South' => 'Eteläistä leveyttä',
},
},
'GPSLongitude' => 'Pituusaste',
'GPSLongitudeRef' => {
Description => 'Itäistä tai läntistä pituutta',
PrintConv => {
'East' => 'Itäistä pituutta',
'West' => 'Läntistä pituutta',
},
},
'GPSMapDatum' => 'Käytetty geodeettinen karttadata',
'GPSMeasureMode' => {
Description => 'GPS-mittaustapa',
PrintConv => {
'2-Dimensional Measurement' => '2-ulotteinen mittaus',
'3-Dimensional Measurement' => '3-ulotteinen mittaus',
},
},
'GPSProcessingMethod' => 'GPS-prosessointimetodin nimi',
'GPSSatellites' => 'Mittaukseen käytetyt GPS-satelliitit',
'GPSSpeed' => 'GPS-vastaanottimen nopeus',
'GPSSpeedRef' => {
Description => 'Nopeusyksikkö',
PrintConv => {
'km/h' => 'Kilometriä per tunti',
'knots' => 'Solmua',
'mph' => 'Mailia per tunti',
},
},
'GPSStatus' => {
Description => 'GPS-vastaanottimen tila',
PrintConv => {
'Measurement Active' => 'Mittaus aktiivinen',
'Measurement Void' => 'Mittaus virheellinen',
},
},
'GPSTimeStamp' => 'GPS-aika (atomikello)',
'GPSTrack' => 'Liikkeen suunta',
'GPSTrackRef' => {
Description => 'Liikkeen suunnan viite',
PrintConv => {
'Magnetic North' => 'Magneettinen suunta',
'True North' => 'Todellinen suunta',
},
},
'GPSVersionID' => 'GPS-tagin versio',
'GainBase' => 'Perusvahvistus',
'GainControl' => {
Description => 'Herkkyyden säätö',
PrintConv => {
'High gain down' => 'Suuri valoisuuden vähennys',
'High gain up' => 'Suuri valoisuuden lisäys',
'Low gain down' => 'Pieni valoisuuden vähennys',
'Low gain up' => 'Pieni valoisuuden lisäys',
'None' => 'Ei mitään',
},
},
'GammaCompensatedValue' => 'Kompensoidun gamman arvo',
'GeoTiffAsciiParams' => 'Geo-ASCII -parametrien tagi',
'GeoTiffDirectory' => 'Geo-avain -hakemiston tagi',
'GeoTiffDoubleParams' => 'Geo-kaksoisparametrien tagi',
'Gradation' => 'Porrastus',
'GrayPoint' => 'Harmaapiste',
'GrayResponseCurve' => 'Harmaan vastekäyrä',
'GrayResponseUnit' => {
Description => 'Harmaan vasteyksikkö',
PrintConv => {
'0.0001' => 'Numero edustaa yksikön tuhannesosia',
'0.001' => 'Numero edustaa yksikön sadasosia',
'0.1' => 'Numero edustaa yksikön kymmenyksiä',
'1e-05' => 'Numero edustaa yksikön kymmenestuhannesosia',
'1e-06' => 'Numero edustaa yksikön sadastuhannesosia',
},
},
'GrayScale' => 'Harmaa-asteikko',
'GrayTRC' => 'Harmaan toonin toistokäyrä',
'GreenMatrixColumn' => 'Vihreän matriisin sarake',
'GreenTRC' => 'Vihreän toonin toistokäyrä',
'GreenX' => 'Vihreä X',
'GreenY' => 'Vihreä Y',
'GridDisplay' => 'Ristikko',
'HCUsage' => 'HC-käyttö',
'HalftoneHints' => 'Puolisävyviitteet',
'Headline' => 'Otsikko',
'HighISONoiseReduction' => {
Description => 'Korkean ISO-tason kohinan vaimennus',
PrintConv => {
'High' => 'Korkea',
'Low' => 'Matala',
'Minimal' => 'Minimaalinen',
'Normal' => 'Normaali',
'Off' => 'Pois',
},
},
'Highlight' => 'Valoalue',
'HighlightData' => 'Valoalueen data',
'HighlightProtection' => 'Valoalueen suojaus',
'HometownCity' => 'Kotiseutu',
'HometownCityCode' => 'Kotiseutukoodi',
'HometownDST' => {
Description => 'Kotiseudun kesäaika (DST)',
PrintConv => {
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'HostComputer' => 'Isäntätietokone',
'Hue' => 'Sävy',
'HueAdjustment' => 'Värisävyn säätö',
'HueSetting' => 'Sävyn asetus',
'HuffmanTable' => 'Huffman-taulukko',
'ICCProfile' => 'ICC-profiili',
'ICC_Profile' => 'ICC-syötteen väriprofiili',
'IPTC-NAA' => 'IPTC-NAA -metadata',
'IPTCBitsPerSample' => 'Bittien määrä per näyte',
'IPTCData' => 'IPTC-data',
'IPTCDigest' => 'IPTC-yhteenveto',
'IPTCImageHeight' => 'Viivojen määrä',
'IPTCImageRotation' => {
Description => 'Kuvan kierto',
PrintConv => {
'0' => 'Ei kiertoa',
'180' => '180 asteen kierto',
'270' => '270 asteen kierto',
'90' => '90 asteen kierto',
},
},
'IPTCImageWidth' => 'Pikseleitä per viiva',
'IPTCPictureNumber' => 'Kuvan numero',
'IPTCPixelHeight' => 'Pikselikoko suorassa kulmassa skannaussuuntaan',
'IPTCPixelWidth' => 'Pikselikoko skannaussuunnassa',
'ISO' => 'ISO-herkkyys',
'ISOAuto' => 'Automaattinen ISO',
'ISODisplay' => 'ISO-näyttö',
'ISOExpansion' => 'ISO-laajennus',
'ISOFloor' => 'ISO-alaraja',
'ISOInfo' => 'ISO-tiedot',
'ISOSelection' => 'ISO-valinta',
'ISOSetting' => 'ISO-asetus',
'ISOValue' => 'ISO-arvo',
'IT8Header' => 'IT8-ylätunniste',
'Illumination' => 'Näytön valaisu',
'ImageAdjustment' => 'Kuvan säätö',
'ImageAreaOffset' => 'Kuva-alueen siirtymä',
'ImageAuthentication' => {
Description => 'Kuvan aitoustodennus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'ImageBoundary' => 'Kuvan rajat',
'ImageByteCount' => 'Kuvan tavumäärä',
'ImageColorIndicator' => 'Kuvan värin ilmaisin',
'ImageColorValue' => 'Kuvan värin arvo',
'ImageCount' => 'Kuvamäärä',
'ImageData' => 'Kuvadata',
'ImageDataDiscard' => {
Description => 'Kuvadatan hylkäys',
PrintConv => {
'Flexbits Discarded' => 'FlexBits hylätty',
'Full Resolution' => 'Täysi resoluutio',
'HighPass Frequency Data Discarded' => 'Ylipäästötaajuusdata hylätty',
'Highpass and LowPass Frequency Data Discarded' => 'Yli- ja alipäästötaajuusdata hylätty',
},
},
'ImageDataSize' => 'Kuvadatan koko',
'ImageDepth' => 'Kuvan syvyys',
'ImageDescription' => 'Kuvan otsake',
'ImageDustOff' => 'Kuvan pölynpoisto',
'ImageEditCount' => 'Kuvan prosessointimäärä',
'ImageHeight' => 'Kuvan korkeus',
'ImageHistory' => 'Kuvahistoria',
'ImageID' => 'Kuvan ID',
'ImageInfo' => 'Kuvatiedot',
'ImageLayer' => 'Kuvataso',
'ImageNumber' => 'Tiedostonumero',
'ImageOffset' => 'Kuvan siirtrymä',
'ImageOptimization' => 'Kuvan optimointi',
'ImageOrientation' => {
Description => 'Kuvan suunta',
PrintConv => {
'Landscape' => 'Vaakakuva',
'Portrait' => 'Pystykuva',
'Square' => 'Neliömäinen',
},
},
'ImagePrintStatus' => 'Kuvan tulostuksen tila',
'ImageProcessing' => 'Kuvan prosessointi',
'ImageProcessingVersion' => 'Kuvaprosessoinnin versio',
'ImageQuality' => 'Kuvan laatu',
'ImageQuality2' => 'Kuvan laatu 2',
'ImageReview' => 'Kuvan tarkastelu',
'ImageReviewTime' => 'Kuvan katseluaika',
'ImageRotationStatus' => 'Kuvan kierron tila',
'ImageSize' => 'Kuvakoko',
'ImageSourceData' => 'Kuvan lähdedata',
'ImageSourceEK' => 'EK-kuvalähde',
'ImageStabilization' => {
Description => 'Kuvanvakautus',
PrintConv => {
'Best Shot' => 'Paras kuva',
'Off' => 'Pois',
'On' => 'Päällä',
'On, Mode 1' => 'Päällä, tapa 1',
'On, Mode 2' => 'Päällä, tapa 2',
},
},
'ImageTone' => {
Description => 'Kuvamuoto',
PrintConv => {
'Bleach Bypass' => 'Bleach bypass -esivalotus',
'Bright' => 'Kirkas',
'Landscape' => 'Maisema',
'Monochrome' => 'Yksivärinen',
'Muted' => 'Vaimennettu',
'Natural' => 'Luonnollinen',
'Portrait' => 'Muotokuva',
'Reversal Film' => 'Kääntöfilmi',
'Vibrant' => 'Eloisa',
},
},
'ImageType' => 'Sivu',
'ImageUniqueID' => 'Kuvan uniikki ID',
'ImageWidth' => 'Kuvan leveys',
'Indexed' => 'Indeksoitu',
'InkNames' => 'Musteiden nimet',
'InkSet' => 'Mustesarja',
'IntellectualGenre' => 'Intellektuaalinen genre',
'IntelligentAuto' => 'Intelligentti automatiikka',
'IntergraphMatrix' => 'Intergraph-matriisi -tagi',
'Interlace' => 'Lomitus',
'InternalFlash' => {
Description => 'Sisäinen salama',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'InternalFlashAE1' => 'Sisäinen salama AE 1?',
'InternalFlashAE1_0' => 'Sisäinen salama AE 1 (0)?',
'InternalFlashAE2' => 'Sisäinen salama AE 2?',
'InternalFlashAE2_0' => 'Sisäinen salama AE 2 (0)?',
'InternalFlashMode' => 'Sisäisen salaman tapa',
'InternalFlashStrength' => 'Sisäisen salaman teho',
'InternalFlashTable' => 'Sisäisen salaman taulukko',
'InternalSerialNumber' => 'Sisäinen sarjanumero',
'InteropIndex' => {
Description => 'Interoperabiliteetin identifiointi',
PrintConv => {
'R03 - DCF option file (Adobe RGB)' => 'R03: DCF-valintatiedosto (Adobe RGB)',
'R98 - DCF basic file (sRGB)' => 'R98: DCF-perustiedosto (sRGB)',
'THM - DCF thumbnail file' => 'THM: DCF-näytekuvatiedosto',
},
},
'InteropVersion' => 'Interoperabiliteetin versio',
'IntervalLength' => 'Ajastusvälin pituus',
'IntervalMode' => 'Ajastettu kuvaustapa',
'IntervalNumber' => 'Ajastuksen numero',
'JFIFVersion' => 'JFIF-versio',
'JPEGACTables' => 'JPEG:n AC-taulukot',
'JPEGDCTables' => 'JPEG:n DC-taulukot',
'JPEGLosslessPredictors' => 'JPEG:n häviöttömät prediktorit',
'JPEGPointTransforms' => 'JPEG:n pistemuunnot',
'JPEGProc' => 'JPEG-proc',
'JPEGQTables' => 'JPEG:n Q-taulukot',
'JPEGQuality' => {
Description => 'JPEG-laatu',
PrintConv => {
'Extra Fine' => 'Erityishieno',
'Fine' => 'Hieno',
'Standard' => 'Normaali',
'n/a' => 'Ei asetettu',
},
},
'JPEGRestartInterval' => 'JPEG:n uudelleenaloitusväli',
'JPEGTables' => 'JPEG-taulukot',
'JobID' => 'Työn ID',
'Keyword' => 'Avainsana',
'Keywords' => 'Avainsana',
'LCDIllumination' => 'LCD:n valaisu',
'Language' => 'Kieli',
'LanguageIdentifier' => 'Kielen tunnistin',
'LastFileNumber' => 'Viimeinen tiedostonumero',
'LeafData' => 'Leaf-data',
'Lens' => 'Objektiivi',
'LensApertureRange' => 'Objektiivin aukkoalue',
'LensDataVersion' => 'Objektiividatan versio',
'LensDistortionParams' => 'Linssivääristymän parametrit',
'LensFStops' => 'Objektiivin aukkoarvot',
'LensFirmwareVersion' => 'Objektiivin laiteohjelmistoversio',
'LensID' => 'Objektiivin ID',
'LensIDNumber' => 'Objektiivin ID-numero',
'LensInfo' => 'Objektiivin tiedot',
'LensSerialNumber' => 'Objektiivin sarjanumero',
'LensTemperature' => 'Objektiivin lämpötila',
'LensType' => 'Objektiivityyppi',
'LightCondition' => 'Valaistusolot',
'LightReading' => 'Valolukema',
'LightSource' => {
Description => 'Valonlähde',
PrintConv => {
'Cloudy' => 'Pilvinen',
'Cool White Fluorescent' => 'Viileä valkoinen loistelamppu (W 3900 - 4500K)',
'Day White Fluorescent' => 'Valkoinen päivänvaloloistelamppu (N 4600 - 5400K)',
'Daylight' => 'Päivänvalo',
'Daylight Fluorescent' => 'Päivänvaloloistelamppu (D 5700 - 7100K)',
'Fine Weather' => 'Pilvetön',
'Flash' => 'Salama',
'Fluorescent' => 'Loistevalo',
'ISO Studio Tungsten' => 'ISO studiokeinovalo (hehkulamppu)',
'Other' => 'Muu valonlähde',
'Shade' => 'Varjo',
'Standard Light A' => 'Standardivalo A',
'Standard Light B' => 'Standardivalo B',
'Standard Light C' => 'Standardivalo C',
'Tungsten (Incandescent)' => 'Keinovalo (hehkulamppu)',
'Unknown' => 'Tuntematon',
'White Fluorescent' => 'Lämmin valkoinen loistelamppu (WW 3200 - 3700K)',
},
},
'LightSourceSpecial' => {
Description => 'Erikoisvalonlähde',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'LinearResponseLimit' => 'Lineaarisen vasteen raja',
'LinearizationTable' => 'Linearisaatiotaulukko',
'LiveViewAF' => 'Suoranäyttö-AF',
'LocalizedCameraModel' => 'Lokalisoitu kameramalli',
'Location' => 'Sijainti',
'LongExposureNoiseReduction' => {
Description => 'Pitkien valotusten kohinan vaimennus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
'n/a' => 'Ei asetettu',
},
},
'LookupTable' => 'Hakutaulukko',
'Luminance' => 'Luminanssi',
'MB-D10BatteryType' => 'MB-D10 -paristotyyppi',
'MB-D80Batteries' => 'MB-D80 -paristot',
'MCUVersion' => 'MCU-versio',
'Macro' => {
Description => 'Makro',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
'n/a' => 'Ei asetettu',
},
},
'MacroMode' => {
Description => 'Makrotapa',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
'Super Macro' => 'Supermakro',
'Tele-Macro' => 'Telemakro',
},
},
'Magnification' => 'Suurennus',
'Make' => 'Valmistaja',
'MakeAndModel' => 'Valmistaja ja malli',
'MakerNote' => 'DNG-erityistiedot',
'MakerNoteOffset' => 'Valmistajatietojen siirtymä',
'MakerNoteSafety' => {
Description => 'Valmistatietojen turvallisuus',
PrintConv => {
'Safe' => 'Turvallinen',
'Unsafe' => 'Turvaton',
},
},
'MakerNoteType' => 'Valmistajatietojen tyyppi',
'MakerNoteVersion' => 'Valmistajatietojen versio',
'ManometerPressure' => 'Manometrin ilmaisema paine',
'ManualFlash' => 'Manuaalinen salama',
'ManualFlashOutput' => 'Salaman käsisäätö',
'ManualFocusDistance' => 'Manuaalinen etäisyydensäätö',
'ManufactureDate' => 'Valmistuspäiväys',
'MaskedAreas' => 'Maskilliset alueet',
'MasterDocumentID' => 'Alkuperäisdokumentin ID',
'MasterGain' => 'Yleisvahvistus',
'Matteing' => 'Mattaus',
'MaxAperture' => 'Suurin aukko',
'MaxApertureAtCurrentFocal' => 'Suurin aukko nykyisellä polttovälillä',
'MaxApertureAtMaxFocal' => 'Suurin aukko pisimmällä polttovälillä',
'MaxApertureAtMinFocal' => 'Suurin aukko lyhimmällä polttovälillä',
'MaxApertureValue' => 'Objektiivin maksimiaukko',
'MaxFocalLength' => 'Pisin polttoväli',
'MaxSampleValue' => 'Näytteen maksimiarvo',
'MaximumDensityRange' => 'Tiheyden maksimilaajuus',
'MeasuredEV' => 'Mitattu EV',
'MeasurementBacking' => 'Mittaustuenta',
'MeasurementFlare' => 'Hajavalomittaus',
'MeasurementGeometry' => 'Mittausgeometria',
'MeasurementIlluminant' => 'Valaistusmittaus',
'MeasurementObserver' => 'Mittauksen tarkkailija',
'MediaBlackPoint' => 'Median musta piste',
'MediaWhitePoint' => 'Median valkoinen piste',
'Medium' => 'Keskikokoa',
'MetadataNumber' => 'Metadatan määrä',
'Metering' => 'Valonmittaus',
'MeteringMode' => {
Description => 'Valonmittaustapa',
PrintConv => {
'Average' => 'Keskiarvo',
'Center-weighted average' => 'Keskustapainotteinen keskiarvo',
'Multi-segment' => 'Monisegmenttimittaus',
'Multi-spot' => 'Monipiste',
'Other' => 'Muu',
'Partial' => 'Osa-alue',
'Pattern+AF' => 'Kuvio + AF',
'Spot' => 'Pistemittaus',
'Spot+Highlight control' => 'Pistemittaus + valoalueen säätö',
'Spot+Shadow control' => 'Pistemittaus + varjoalueen säätö',
'Unknown' => 'Tuntematon',
},
},
'MeteringTime' => 'Mittausaika',
'MinAperture' => 'Pienin aukko',
'MinFocalLength' => 'Lyhin polttoväli',
'MinSampleValue' => 'Näytteen minimiarvo',
'MinoltaCameraSettings2' => 'Kameran asetukset 2',
'MinoltaCameraSettings5D' => 'Kameran asetukset (5D)',
'MinoltaCameraSettings7D' => 'Kamera-asetukset (7D)',
'MinoltaMakerNote' => 'Minolta-valmistajatiedot',
'MinoltaQuality' => {
Description => 'Kuvakoko',
PrintConv => {
'Economy' => 'Taloudellinen',
'Extra fine' => 'Erityishieno',
'Fine' => 'Hieno',
'Standard' => 'Normaali',
'Super Fine' => 'Superhieno',
},
},
'Model' => 'Malli',
'Model2' => 'Kuvasyötelaitteen malli (2)',
'ModelAndVersion' => 'Malli ja versio',
'ModelTiePoint' => 'Sidospistemalli-tagi',
'ModelTransform' => 'Muuntomalli-tagi',
'ModelingFlash' => 'Mallinnussalama',
'ModifiedDigitalGain' => 'Modifioitu digitaalinen vahvistus',
'ModifiedInfo' => 'Modifioidut tiedot',
'ModifiedParamFlag' => 'Modifioitu parametrilippu',
'ModifiedPictureStyle' => 'Modifioitu kuvan tyyli',
'ModifiedSaturation' => {
Description => 'Modifoitu värikylläisyys',
PrintConv => {
'CM1 (Red Enhance)' => 'CM1 (punaisen parantelu)',
'CM2 (Green Enhance)' => 'CM2 (vihreän parantelu)',
'CM3 (Blue Enhance)' => 'CM3 (sinisen parantelu)',
'CM4 (Skin Tones)' => 'CM4 (ihonvärin parantelu)',
'Off' => 'Pois',
},
},
'ModifiedSensorBlueLevel' => 'Modifioitu anturin sinitaso',
'ModifiedSensorRedLevel' => 'Modifioitu anturin punataso',
'ModifiedSharpness' => 'Modifioitu terävyys',
'ModifiedToneCurve' => 'Modifioitu sävykäyrä',
'ModifiedWhiteBalance' => 'Modifioitu valkotasapaino',
'ModifiedWhiteBalanceBlue' => 'Modifioitu valkotasapainon sininen',
'ModifiedWhiteBalanceRed' => 'Modifioitu valkotasapainon punainen',
'ModifyDate' => 'Tiedostomuutoksen päiväys ja aika',
'MultiExposure' => 'Monivalotusdata',
'MultiExposureAutoGain' => 'Monivalotuksen automaattivalotus',
'MultiExposureMode' => 'Monivalotustapa',
'MultiExposureShots' => 'Monivalotusotoksia',
'MultiExposureVersion' => 'Monivalotusdatan versio',
'MultiSample' => 'Moninäyte',
'MultiSelector' => 'Monivalitsin',
'MultipleExposureSet' => 'Monivalotus',
'MyColorMode' => 'Oma värimuoto',
'NDFilter' => 'ND-suodin',
'NEFLinearizationTable' => 'Linearisaatiotaulukko',
'NamedColor2' => 'Nimetty väri 2',
'NativeDisplayInfo' => 'Paikallisen näytön tiedot',
'NativeResolutionUnit' => 'Paikallisen resoluution yksikkö',
'NativeXResolution' => 'Paikallinen vaakaresoluutio',
'NativeYResolution' => 'Paikallinen pystyresoluutio',
'NikonCaptureData' => 'Nikon Capture -data',
'NikonCaptureOffsets' => 'Nikon Capture -siirtymät',
'NikonCaptureOutput' => 'Nikon Capture -tuotos',
'NikonCaptureVersion' => 'Nikon Capture -versio',
'NikonICCProfile' => 'Nikon ICC-profiilin osoitin',
'NoMemoryCard' => 'Ei muistikorttia',
'Noise' => 'Kohina',
'NoiseFilter' => 'Kohinasuodin',
'NoiseReduction' => {
Description => 'Kohinan vähennys',
PrintConv => {
'High (+1)' => '+1 (korkea)',
'Highest (+2)' => '+2 (korkein)',
'Low' => 'Matala',
'Low (-1)' => '-1 (matala)',
'Lowest (-2)' => '-2 (matalin)',
'Normal' => 'Vakio',
'Off' => 'Pois',
'On' => 'Päällä',
'Standard' => '±0 (vakio)',
},
},
'NoiseReductionApplied' => 'Suoritettu kohinan vähennys',
'NoiseReductionData' => 'Kohinanvaimennusdata',
'NoiseReductionIntensity' => 'Kohinanvaimennuksen voimakkuus',
'NoiseReductionMethod' => 'Kohinanvaimennusmetodi',
'NoiseReductionSharpness' => 'Kohinanvaimennuksen terävyys',
'NumIndexEntries' => 'Indeksimerkintöjen määrä',
'NumberOfChannels' => 'Kanavien määrä',
'NumberofInks' => 'Musteiden numerot',
'OPIProxy' => 'OPI-välipalvelin',
'ObjectAttributeReference' => 'Intellektuaalinen genre',
'ObjectCycle' => {
Description => 'Objektin sykli',
PrintConv => {
'Both Morning and Evening' => 'Molempina',
'Evening' => 'Iltaisin',
'Morning' => 'Aamuisin',
},
},
'ObjectDistance' => 'Kohteen etäisyys',
'ObjectName' => 'Nimike',
'ObjectPreviewData' => 'Objektidatan esikatseludata',
'ObjectPreviewFileFormat' => 'Objektidatan esikatselun tiedostomuoto',
'ObjectPreviewFileVersion' => 'Objektidatan esikatselun tiedostomuodon versio',
'ObjectTypeReference' => 'Objektyypin viiteryhmä',
'OffsetSchema' => 'Siirtymäskeema',
'OlympusImageHeight' => 'Kuvan korkeus',
'OlympusImageWidth' => 'Kuvan leveys',
'OneTouchWB' => {
Description => 'Pikavalkotasapaino',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
'On (Preset)' => 'Päällä (esiasetus)',
},
},
'OpticalZoomCode' => 'Optisen zoomin koodi',
'OpticalZoomMode' => {
Description => 'Optinen zoomaustapa',
PrintConv => {
'Extended' => 'Laajennettu',
'Standard' => 'Vakio',
},
},
'OpticalZoomOn' => {
Description => 'Optinen zoom',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'Opto-ElectricConvFactor' => 'Optoelektrinen muuntokerroin',
'OrderNumber' => 'Valokuva-CD:n ostotilausnumero',
'Orientation' => {
Description => 'Kuvan suunta',
PrintConv => {
'Horizontal (normal)' => '0° (ylä/vasen)',
'Mirror horizontal' => '0° (ylä/oikea)',
'Mirror horizontal and rotate 270 CW' => '90° myötäpäivään (vasen/ylä)',
'Mirror horizontal and rotate 90 CW' => '90° vastapäivään (oikea/ala)',
'Mirror vertical' => '180° (ala/vasen)',
'Rotate 180' => '180° (ala/oikea)',
'Rotate 270 CW' => '90° myötäpäivään (vasen/ala)',
'Rotate 90 CW' => '90° vastapäivään (oikea/ylä)',
},
},
'OriginalDecisionDataOffset' => 'Alkuperäisen ratkaisudatan siirtymä',
'OriginalRawFileData' => 'Originaali raw-tiedoston data',
'OriginalRawFileDigest' => 'Alkuperäisen raw-tiedoston tiivistelmä',
'OriginalRawFileName' => 'Originaali raw-tiedoston nimi',
'OriginalTransmissionReference' => 'Tehtävän tunnistin',
'OriginatingProgram' => 'Luontiohjelma',
'OutputImageHeight' => 'Tuotoskuvan korkeus',
'OutputImageWidth' => 'Tuotoskuvan leveys',
'OutputResolution' => 'Tuotoksen resoluutio',
'OutputResponse' => 'Tuotosvaste',
'OwnerID' => 'Omistajan ID',
'OwnerName' => 'Omistajan nimi',
'Padding' => 'Täyte',
'PageName' => 'Sivun nimi',
'PageNumber' => 'Sivunumero',
'PanasonicExifVersion' => 'Panasonic-exif -versio',
'PanasonicRawVersion' => 'Panasonic-RAW:n versio',
'PanasonicTitle' => 'Otsikko',
'PanoramaDirection' => 'Panoraaman suunta',
'PanoramaMode' => 'Panoraamatapa',
'PentaxImageSize' => {
Description => 'Pentax-kuvakoko',
PrintConv => {
'2304x1728 or 2592x1944' => '2304 x 1728 tai 2592 x 1944',
'2560x1920 or 2304x1728' => '2560 x 1920 tai 2304 x 1728',
'2816x2212 or 2816x2112' => '2816 x 2212 tai 2816 x 2112',
'3008x2008 or 3040x2024' => '3008 x 2008 tai 3040 x 2024',
'Full' => 'Täysi',
},
},
'PentaxVersion' => 'Pentax-versio',
'People' => 'Ihmiset',
'PeripheralLighting' => 'Oheislaitevalaistus',
'PeripheralLightingSetting' => 'Oheislaitevalaistuksen asetus',
'PeripheralLightingValue' => 'Oheislaitevalaistuksen arvo',
'PhotoEffect' => 'Valokuvaefekti',
'PhotoEffects' => 'Valokuvaefektit',
'PhotoEffectsBlue' => 'Valokuvaefekti sininen',
'PhotoEffectsData' => 'Valokuvaefektidata',
'PhotoEffectsGreen' => 'Valokuvaefekti vihreä',
'PhotoEffectsRed' => 'Valokuvaefekti punainen',
'PhotoEffectsType' => 'Valokuvaefektityyppi',
'PhotometricInterpretation' => {
Description => 'Pikseliskeema',
PrintConv => {
'BlackIsZero' => 'Musta on nolla',
'Color Filter Array' => 'CFA (värisuodinmatriisi)',
'Pixar LogL' => 'CIE Log2(L) (Log-luminanssi)',
'Pixar LogLuv' => 'CIE Log2(L)(u\',v\') (Log-luminanssi ja -krominanssi)',
'RGB Palette' => 'Väripaletti',
'Transparency Mask' => 'Läpinäkyvyysmaski',
'WhiteIsZero' => 'Valkoinen on nolla',
},
},
'PhotoshopBGRThumbnail' => 'Photoshopin BRG-näytekuva',
'PhotoshopFormat' => 'Photoshop-muoto',
'PhotoshopQuality' => 'Photoshop-laatu',
'PictInfo' => 'Kuvatiedot',
'PictureControl' => 'Kuvan optimointi',
'PictureControlActive' => 'Kuvan käsittely aktivoitu',
'PictureControlAdjust' => 'Kuvan optimoinnin säätö',
'PictureControlBase' => 'Kuvan perusoptimointi',
'PictureControlData' => 'Kuvan käsittely',
'PictureControlMode' => 'Kuvan käsittelytapa',
'PictureControlName' => 'Kuvan optimoinnin nimi',
'PictureControlQuickAdjust' => 'Kuvan optimoinnin pikasäätö',
'PictureControlVersion' => 'Kuvan optimoinnin versio',
'PictureFinish' => 'Kuvan viimeistely',
'PictureMode' => {
Description => 'Kuvausohjelma',
PrintConv => {
'Anti-blur' => 'Epätarkkuden vähennys',
'Aperture-priority AE' => 'Aukon esivalinta AE',
'Auto' => 'Automaattinen',
'Beach' => 'Hiekkaranta',
'Beach & Snow' => 'Hiekkaranta & Lumi',
'Fireworks' => 'Ilotulitus',
'Flower' => 'Kukka',
'Landscape' => 'Maisema',
'Macro' => 'Lähikuva (Kukka)',
'Manual' => 'Manuaalinen',
'Museum' => 'Museo',
'Natural Light' => 'Luonnonvalo',
'Natural Light & Flash' => 'Luonnonvalo & Salama',
'Night Scene' => 'Yö',
'Party' => 'Juhlat',
'Portrait' => 'Muotokuva',
'Program AE' => 'Automaattinen valotusohjelma',
'Shutter speed priority AE' => 'Ajan esivalinta AE',
'Snow' => 'Lumi',
'Sports' => 'Urheilu',
'Sunset' => 'Auringonlasku',
'Text' => 'Teksti',
'Underwater' => 'Veden alla',
},
},
'PictureMode2' => 'Kuvamuoto 2',
'PictureModeBWFilter' => {
Description => 'BW-suodin -kuvamuoto',
PrintConv => {
'Green' => 'Vihreä',
'Neutral' => 'Neutraali',
'Orange' => 'Oranssi',
'Red' => 'Punainen',
'Yellow' => 'Keltainen',
'n/a' => 'E.s.',
},
},
'PictureModeContrast' => 'Kontrastinen kuvamuoto',
'PictureModeHue' => 'Sävykäs kuvamuoto?',
'PictureModeSaturation' => 'Värikylläinen kuvamuoto',
'PictureModeSharpness' => 'Terävä kuvamuoto',
'PictureModeTone' => {
Description => 'Vivahteikas kuvamuoto',
PrintConv => {
'Blue' => 'Sininen',
'Green' => 'Vihreä',
'Neutral' => 'Neutraali',
'Purple' => 'Violetti',
'Sepia' => 'Seepia',
'n/a' => 'E.s.',
},
},
'PictureStyle' => 'Kuvan tyyli',
'PixelAspectRatio' => 'Pikselien kokosuhde',
'PixelFormat' => 'Pikseliformaatti',
'PixelIntensityRange' => 'Pikseli-intensiteetin alue',
'PixelScale' => 'Pikseliasteikkomalli-tagi',
'PlanarConfiguration' => {
Description => 'Kuvadatan järjestys',
PrintConv => {
'Chunky' => 'Lohkoformaatti (lomitettu)',
'Planar' => 'Tasoformaatti',
},
},
'PlaybackMenusTime' => 'Toistovalikkojen aika',
'PowerSource' => 'Virtalähde',
'PreCaptureFrames' => 'Esiasetetut kehykset',
'Predictor' => {
Description => 'Prediktori',
PrintConv => {
'Horizontal differencing' => 'Horisontaalinen differointi',
'None' => 'Prediktioskeemaa ei käytetty ennen koodausta',
},
},
'Preview' => 'Esikatselu',
'Preview0' => 'Esikatselu 0',
'Preview1' => 'Esikatselu 1',
'Preview2' => 'Esikatselu 2',
'PreviewApplicationName' => 'Sovelluksen nimen esikatselu',
'PreviewApplicationVersion' => 'Sovellusversion esikatselu',
'PreviewColorSpace' => {
Description => 'Väriavaruuden esikatselu',
PrintConv => {
'Unknown' => 'Tuntematon',
},
},
'PreviewDateTime' => 'Päiväyksen ja ajan esikatselu',
'PreviewImage' => 'Kuvan esikatselu',
'PreviewImageBorders' => 'Kuvan reunojen esikatselu',
'PreviewImageData' => 'Kuvadatan tarkastelu',
'PreviewImageLength' => 'Kuvan pituuden esikatselu',
'PreviewImageSize' => 'Kuvakoon esikatselu',
'PreviewImageStart' => 'Esikatselukuvan alku',
'PreviewImageValid' => {
Description => 'Kelvollinen esikatselukuva',
PrintConv => {
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'PreviewSettingsDigest' => 'Asetustiivistelmän esikatselu',
'PreviewSettingsName' => 'Asetusten nimen esikatselu',
'PrimaryAFPoint' => 'Ensisijainen AF-piste',
'PrimaryChromaticities' => 'Päävärien kromaattisuudet',
'PrimaryPlatform' => 'Primaari alusta',
'PrintQuality' => 'Tulostuslaatu',
'ProcessingInfo' => 'Prosessointitiedot',
'ProcessingSoftware' => 'Prosessointiohjelmisto',
'ProductID' => 'Tuotteen ID',
'ProfileCMMType' => 'CMM-tyypin profiili',
'ProfileCalibrationSig' => 'Profiilin kalibrointitunniste',
'ProfileClass' => 'Profiilin luokka',
'ProfileConnectionSpace' => 'Profiilin yhteystila',
'ProfileCopyright' => 'Profiilin copyright',
'ProfileCreator' => 'Profiilin luoja',
'ProfileDateTime' => 'Profiilin päiväysaika',
'ProfileDescription' => 'Profiilin kuvaus',
'ProfileDescriptionML' => 'Monikieliprofiilin kuvaus',
'ProfileEmbedPolicy' => {
Description => 'Profiilin upotusmenetelmä',
PrintConv => {
'Allow Copying' => 'Salli kopiointi',
'Embed if Used' => 'Upota jos käytössä',
'Never Embed' => 'Älä koskaan upota',
'No Restrictions' => 'Ei rajoituksia',
},
},
'ProfileFileSignature' => 'Profiilidatan tunniste',
'ProfileHueSatMapData1' => 'Profiilin Sävy Värik. -kartan data 1',
'ProfileHueSatMapData2' => 'Profiilin Sävy Värik. -kartan data 2',
'ProfileID' => 'Profiilin ID',
'ProfileLookTableData' => 'Profiilin hakutaulukon data',
'ProfileName' => 'Profiilin nimi',
'ProfileSequenceDesc' => 'Profiilisarjan kuvaus',
'ProfileToneCurve' => 'Profiilin toonin käyrä',
'ProfileVersion' => 'Profiilin versio',
'ProgramISO' => 'Ohjelma-ISO',
'ProgramLine' => 'Valotusohjelma',
'ProgramMode' => 'Ohjelman muoto',
'ProgramShift' => 'Ohjelmasiirto',
'ProgramVersion' => 'Ohjelmaversio',
'ProgressiveScans' => 'Progressiiviset skannaukset',
'Province-State' => 'Provinssi/Valtio',
'Quality' => {
Description => 'Laatu',
PrintConv => {
'Best' => 'Paras',
'Better' => 'Parempi',
'Compressed RAW' => 'Pakattu RAW',
'Compressed RAW + JPEG' => 'Pakattu RAW + JPEG',
'Economy' => 'Taloudellinen',
'Extra Fine' => 'Erityishieno',
'Fine' => 'Hieno',
'Good' => 'Hyvä',
'Normal' => 'Normaali',
'Standard' => 'Vakio',
'Super Fine' => 'Superhieno',
'n/a' => 'Ei asetettu',
},
},
'QualityMode' => {
Description => 'Kuvalaatu',
PrintConv => {
'Economy' => 'Taloudellinen',
'Fine' => 'Hieno',
'Normal' => 'Normaali',
},
},
'QuantizationMethod' => {
Description => 'Kvantisointimetodi',
PrintConv => {
'AP Domestic Analogue' => 'AP domestinen analogia',
'Color Space Specific' => 'Erityisväriavaruus',
'Compression Method Specific' => 'Erityispakkausmetodi',
'Gamma Compensated' => 'Kompensoitu gamma',
'IPTC Ref B' => 'IPTC ref "B"',
'Linear Density' => 'Lineaarinen tiheys',
'Linear Dot Percent' => 'Lineaarinen pisteprosentti',
'Linear Reflectance/Transmittance' => 'Lineaarinen heijastavuus/läpäisevyys',
},
},
'QuickAdjust' => 'Pikasäätö',
'QuickShot' => {
Description => 'Pikakuvaus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'ROCInfo' => 'ROC-tiedot',
'RangeFinder' => 'Alue-etsin',
'RasterPadding' => 'Rasteritäyte',
'RasterizedCaption' => 'Rasteroitu seloste',
'Rating' => 'Arvostelu',
'RawDataOffset' => 'RAW-datan siirtymä',
'RawDataUniqueID' => 'Raw-datan uniikki ID',
'RawDevColorSpace' => 'Väriavaruus',
'RawDevContrastValue' => 'Kontrastiarvo',
'RawDevEditStatus' => {
Description => 'Editointitila',
PrintConv => {
'Edited (Landscape)' => 'Studio (maisema)',
'Edited (Portrait)' => 'Studio (muotokuva)',
'Original' => 'Alkuperäinen',
},
},
'RawDevEngine' => {
Description => 'Moottori',
PrintConv => {
'Advanced High Speed' => 'Edistynyt suurnopeus',
'High Function' => 'Hyvä suorituskyky',
'High Speed' => 'Suurnopeus',
},
},
'RawDevExposureBiasValue' => 'Valotuksen korjausarvo',
'RawDevGrayPoint' => 'Harmaapiste',
'RawDevMemoryColorEmphasis' => 'Muistivärin korostus',
'RawDevNoiseReduction' => 'Kohinasuodin (ISO-tehostus)',
'RawDevSaturationEmphasis' => 'Värikylläisyyden korostus',
'RawDevSettings' => 'Kohinanvaimennus',
'RawDevSharpnessValue' => 'Kontrastiarvo',
'RawDevVersion' => 'RAW-kehityksen versio',
'RawDevWBFineAdjustment' => 'Valkotasapainon hienosäätö',
'RawDevWhiteBalanceValue' => 'Valkotasapainon arvo',
'RawImageCenter' => 'RAW-kuvan keskusta',
'RawImageDigest' => 'RAW-kuvan tiivistelmä',
'RawImageHeight' => 'Kuvan korkeus',
'RawImageSize' => 'RAW-kuvakoko',
'RawImageWidth' => 'Kuvan leveys',
'RawInfoVersion' => 'RAW Info -versio',
'RecognizedFace1Age' => 'Tunnistettujen kasvojen 1 ikä',
'RecognizedFace1Name' => 'Tunnistettujen kasvojen 1 nimi',
'RecognizedFace1Position' => 'Tunnistettujen kasvojen 1 sijainti',
'RecognizedFace2Age' => 'Tunnistettujen kasvojen 2 ikä',
'RecognizedFace2Name' => 'Tunnistettujen kasvojen 2 nimi',
'RecognizedFace2Position' => 'Tunnistettujen kasvojen 2 sijainti',
'RecognizedFace3Age' => 'Tunnistettujen kasvojen 2 ikä',
'RecognizedFace3Name' => 'Tunnistettujen kasvojen 3 nimi',
'RecognizedFace3Position' => 'Tunnistettujen kasvojen 3 sijainti',
'RecognizedFaceFlags' => 'Tunnistettujen kasvojen liput',
'RecordMode' => {
Description => 'Tallennustapa',
PrintConv => {
'Aperture Priority' => 'Aukon esivalinta',
'Best Shot' => 'Paras kuva',
'Manual' => 'Manuaalinen',
'Movie' => 'Elokuva',
'Movie (19)' => 'Elokuva (19)',
'Program AE' => 'AE-ohjelma',
'Shutter Priority' => 'Ajan esivalinta',
'YouTube Movie' => 'YouTube-elokuva',
},
},
'RecordShutterRelease' => {
Description => 'Laukaisujen tallennus',
PrintConv => {
'Press start, press stop' => 'Aloitus painaen, lopetus painaen',
'Record while down' => 'Tallennus laukaisin alhaalla',
},
},
'RecordingMode' => 'Tallennustapa',
'RedBalance' => 'Punatasapaino',
'RedEyeCorrection' => 'Punasilmäkorjaus',
'RedEyeData' => 'Punasilmädata',
'RedMatrixColumn' => 'Punaisen matriisin sarake',
'RedTRC' => 'Punaisen toonin toistokäyrä',
'RedX' => 'Punainen X',
'RedY' => 'Punainen Y',
'ReductionMatrix1' => 'Reduktiomatriisi 1',
'ReductionMatrix2' => 'Reduktiomatriisi 2',
'ReferenceBlackWhite' => 'Musta ja valkoinen viitearvopari',
'ReferenceDate' => 'Viitepäiväys',
'ReferenceNumber' => 'Viitenumero',
'ReferenceService' => 'Viitepalvelu',
'RelatedImageFileFormat' => 'Kuvatiedoston muoto',
'RelatedImageHeight' => 'Kuvan korkeus',
'RelatedImageWidth' => 'Kuvan leveys',
'RelatedSoundFile' => 'Asiaan liittyvä audiotiedosto',
'ReleaseButtonToUseDial' => 'Käytä valitsinta vapauttaen painike',
'ReleaseDate' => 'Julkaisupäiväys',
'ReleaseMode' => 'Laukaisutapa',
'ReleaseTime' => 'Julkaisuaika',
'RemoteOnDuration' => 'Kaukolaukaisin',
'RenderingIntent' => 'Muokkausmenetelmä',
'Resaved' => {
Description => 'Tallennus uudelleen',
PrintConv => {
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'ResolutionMode' => 'Resoluutiomuoto',
'ResolutionUnit' => 'X- ja Y-resoluution yksikkö',
'RetouchHistory' => 'Korjailuhistoria',
'ReverseIndicators' => 'Käänteiset ilmaisimet',
'RevisionNumber' => 'Revision numero',
'RollGuidElements' => 'Guid-elementtien vieritys',
'Rotation' => {
Description => 'Kierto',
PrintConv => {
'Horizontal (normal)' => 'Vaakatasossa (normaali)',
'Rotate 270 CW' => 'Kierto 90° VP',
'Rotate 90 CW' => 'Kierto 90° MP',
},
},
'RowInterleaveFactor' => 'Rivin lomitusfaktori',
'RowsPerStrip' => 'Rivien määrä per strippi',
'SBAExposureRecord' => 'SBA-valotuksen tallennus',
'SBAInputImageBitDepth' => 'SBA-syötekuvan bittisyvyys',
'SBAInputImageColorspace' => 'SBA-syötekuvan väriavaruus',
'SMaxSampleValue' => 'S-maksimiminäytteen arvo',
'SMinSampleValue' => 'S-miniminäytteen arvo',
'SRFocalLength' => 'Vakain (SR) eri polttoväleillä',
'SRResult' => 'Kuvanvakain',
'SampleFormat' => 'Näyteformaatti',
'SampleStructure' => {
Description => 'Näytteiden rakenne',
PrintConv => {
'CompressionDependent' => 'Määritetty pakkaustoiminnon yhteydessä',
'Orthogonal4-2-2Sampling' => 'Toisistaan riippumattomat näytetaajuuksin suhteessa 4:2:2:(4)',
'OrthogonalConstangSampling' => 'Toisistaan riippumattomat samoin suhteellisin näytetaajuuksin kussakin komponentissa',
},
},
'SamplesPerPixel' => 'Komponenttien määrä',
'SanyoQuality' => {
Description => 'Sanyo-laatu',
PrintConv => {
'Fine/High' => 'Hieno/korkea',
'Fine/Low' => 'Hieno/matala',
'Fine/Medium' => 'Hieno/keskilaatu',
'Fine/Medium High' => 'Hieno/korkeahko',
'Fine/Medium Low' => 'Hieno/matalahko',
'Fine/Super High' => 'Hieno/superkorkea',
'Fine/Very High' => 'Hieno/hyvin korkea',
'Fine/Very Low' => 'Hieno/hyvin matala',
'Normal/High' => 'Normaali/korkea',
'Normal/Low' => 'Normaali/matala',
'Normal/Medium' => 'Normaali/keskilaatu',
'Normal/Medium High' => 'Normaali/korkeahko',
'Normal/Medium Low' => 'Normaali/matalahko',
'Normal/Super High' => 'Normaali/superkorkea',
'Normal/Very High' => 'Normaali/hyvin korkea',
'Normal/Very Low' => 'Normaali/hyvin matala',
'Super Fine/High' => 'Superhieno/korkea',
'Super Fine/Low' => 'Superhieno/matala',
'Super Fine/Medium' => 'Superhieno/keskilaatu',
'Super Fine/Medium High' => 'Superhieno/korkeahko',
'Super Fine/Medium Low' => 'Superhieno/matalahko',
'Super Fine/Super High' => 'Superhieno/superkorkea',
'Super Fine/Very High' => 'Superhieno/hyvin korkea',
'Super Fine/Very Low' => 'Superhieno/hyvin matala',
},
},
'SanyoThumbnail' => 'Sanyo-näytekuva',
'Saturation' => {
Description => 'Värikylläisyys',
PrintConv => {
'Film Simulation' => 'Filminsimulaatio',
'High' => 'Korkea',
'Low' => 'Matala',
'Medium High' => 'Korkeahko',
'Medium Low' => 'Matalahko',
'None (B&W)' => 'Ei mitään (M&V)',
'Normal' => 'Vakio',
},
},
'SaturationFaithful' => 'Kohdeuskollinen värikylläisyys',
'SaturationLandscape' => 'Maisemakuvan värikylläisyys',
'SaturationNeutral' => 'Neutraali värikylläisyys',
'SaturationPortrait' => 'Muotokuvan värikylläisyys',
'SaturationSetting' => 'Värikylläisyyden sasetus',
'SaturationStandard' => 'Vakiovärikylläisyys',
'ScanImageEnhancer' => {
Description => 'Skannauskuvan parantelu',
PrintConv => {
'Off' => 'Pois',
},
},
'ScanningDirection' => {
Description => 'Skannaussuunta',
PrintConv => {
'Bottom-Top, L-R' => 'Alhaalta ylös, vasemmalta oikealle',
'Bottom-Top, R-L' => 'Alhaalta ylös, oikealta vasemmalle',
'L-R, Bottom-Top' => 'Vasemmalta oikealle, alhaalta ylös',
'L-R, Top-Bottom' => 'Vasemmalta oikealle, ylhäältä alas',
'R-L, Bottom-Top' => 'Oikealta vasemmalle, alhaalta ylös',
'R-L, Top-Bottom' => 'Oikealta vasemmalle, ylhäältä alas',
'Top-Bottom, L-R' => 'Ylhäältä alas, vasemmalta oikealle',
'Top-Bottom, R-L' => 'Ylhäältä alas, oikealta vasemmalle',
},
},
'Scene' => 'Näyttämö',
'SceneArea' => 'Näkymäalue?',
'SceneAssist' => 'Näkymä-avustaja',
'SceneCaptureType' => {
Description => 'Kuvatun näkymän tyyppi',
PrintConv => {
'Landscape' => 'Maisema',
'Night' => 'Yönäkymä',
'Portrait' => 'Muotokuva',
'Standard' => 'Standardi',
},
},
'SceneDetect' => 'Kohtauksen tunnistus',
'SceneMode' => {
Description => 'Näkymän muoto',
PrintConv => {
'2 in 1' => '2 1:ssä',
'Auction' => 'Huutokauppa',
'Auto' => 'Automaattinen',
'Available Light' => 'Vallitseva valo',
'Beach' => 'Hiekkaranta',
'Beach & Snow' => 'Hiekkaranta&Lumi',
'Behind Glass' => 'Lasin takaa',
'Candle' => 'Kynttilä',
'Children' => 'Lapset',
'Cuisine' => 'Ateria',
'Digital Image Stabilization' => 'Digitaalinen kuvanvakautus',
'Documents' => 'Dokumentit',
'Face Portrait' => 'Kasvokuva',
'Fireworks' => 'Ilotulitus',
'Food' => 'Ateria',
'High Key' => 'High key -yläsävykuva',
'Indoor' => 'Sisäkuva',
'Landscape' => 'Maisema',
'Landscape+Portrait' => 'Maisema+muotokuva',
'Low Key' => 'Low key -alasävykuva',
'Macro' => 'Makro',
'Movie' => 'Elokuva',
'Museum' => 'Museo',
'My Mode' => 'Oma tapa',
'Nature Macro' => 'Luontomakro',
'Night Portrait' => 'Yön muotokuva',
'Night Scene' => 'Iltanäkymä',
'Night View/Portrait' => 'Iltanäkymä/Yön muotokuva',
'Night+Portrait' => 'Yö+muotokuva',
'Normal' => 'Normaali',
'Panorama' => 'Panoraama',
'Pet' => 'Lemmikki',
'Portrait' => 'Muotokuva',
'Self Portrait' => 'Omakuva',
'Self Portrait+Self Timer' => 'Omakuva+itselaukaisin',
'Self Protrait+Timer' => 'Omakuva+itselaukaisin',
'Shoot & Select' => 'Kuvaa & Valitse',
'Shoot & Select1' => 'Kuvaus&valinta 1',
'Shoot & Select2' => 'Kuvaus&valinta 2',
'Shooting Guide' => 'Kuvausopas',
'Smile Shot' => 'Hymykuva',
'Snow' => 'Lumi',
'Sport' => 'Urheilu',
'Sports' => 'Urheilutapahtuma',
'Standard' => 'Vakio',
'Sunset' => 'Auringonlasku',
'Super Macro' => 'Supermakro',
'Text' => 'Teksti',
'Underwater Macro' => 'Veden alla makro',
'Underwater Snapshot' => 'Veden alla tilannekuva',
'Underwater Wide1' => 'Veden alla laaja 1',
'Underwater Wide2' => 'Veden alla laaja 2',
'Vivid' => 'Heleä',
},
},
'SceneSelect' => {
Description => 'Näkymän valinta',
PrintConv => {
'Lamp' => 'Lamppu',
'Night' => 'Yö',
'Off' => 'Pois',
'Sport' => 'Urheilu',
'User 1' => 'Käyttäjä 1',
'User 2' => 'Käyttäjä 2',
},
},
'SceneType' => {
Description => 'Näkymätyyppi',
PrintConv => {
'Directly photographed' => 'Suoraan otettu valokuva',
},
},
'SecurityClassification' => {
Description => 'Turvallisuusluokitus',
PrintConv => {
'Confidential' => 'Luottamuksellinen',
'Restricted' => 'Rajoitettu',
'Secret' => 'Salainen',
'Top Secret' => 'Huippusalainen',
'Unclassified' => 'Ei luokiteltu',
},
},
'SelfTimer' => {
Description => 'Itselaukaisin',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'SelfTimerMode' => 'Itselaukaisumoodi',
'SelfTimerShotCount' => 'Itselaukaisimen otosmäärä',
'SelfTimerTime' => 'Itselaukaisimen viive',
'SensingMethod' => {
Description => 'Mittausmetodi',
PrintConv => {
'Color sequential area' => 'Peräkkäisvärialueen anturi',
'Color sequential linear' => 'Peräkkäisvärien lineaarianturi',
'Monochrome area' => 'Monokromialueen anturi',
'Monochrome linear' => 'Monokromilineaarinen anturi',
'Not defined' => 'Ei määritetty',
'One-chip color area' => 'Yhden chipin värialueen anturi',
'Three-chip color area' => 'Kolmen chipin värialueen anturi',
'Trilinear' => 'Trilineaarinen anturi',
'Two-chip color area' => 'Kahden chipin värialueen anturi',
},
},
'SensitivityAdjust' => 'Herkkyyden asetus',
'SensitivitySteps' => 'Herkkyysaskeleet',
'SensorBlueLevel' => 'Anturin sinitaso',
'SensorBottomBorder' => 'Anturin alareuna',
'SensorHeight' => 'Anturin korkeus',
'SensorLeftBorder' => 'Anturin vasen reuna',
'SensorPixelSize' => 'Anturin pikselikoko',
'SensorRedLevel' => 'Anturin punataso',
'SensorRightBorder' => 'Anturin oikea reuna',
'SensorTemperature' => 'Anturin lämpötila',
'SensorTopBorder' => 'Anturin yläreuna',
'SensorWidth' => 'Anturin leveys',
'Sequence' => 'Järjestys',
'SequenceNumber' => 'Järjestysnumero',
'SequenceShotInterval' => {
Description => 'Sarjakuvauksen taajuus',
PrintConv => {
'10 frames/s' => '10 ruutua/s',
'15 frames/s' => '15 ruutua/s',
'20 frames/s' => '20 ruutua/s',
'5 frames/s' => '5 ruutua/s',
},
},
'SequentialShot' => {
Description => 'Sarjakuvaus',
PrintConv => {
'Adjust Exposure' => 'Valotuksen säätö',
'Best' => 'Paras',
'None' => 'Ei mitään',
'Standard' => 'Vakio',
},
},
'SerialNumber' => 'Sarjanumero',
'SerialNumberFormat' => 'Sarjanumeron muoto',
'ServiceIdentifier' => 'Palvelun tunnistin',
'ShadingCompensation' => {
Description => 'Varjostumakorjaus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'Shadow' => 'Varjo',
'ShadowProtection' => 'Varjoalueen suojaus ',
'ShadowScale' => 'Varjoasteikko',
'Sharpness' => {
Description => 'Terävyys',
PrintConv => {
'Film Simulation' => 'Filminsimulaatio',
'Hard' => 'Kova',
'Hard2' => 'Kova 2',
'Medium Hard' => 'Kovahko',
'Medium Soft' => 'Pehmeähkö',
'Normal' => 'Vakio',
'Soft' => 'Pehmeä',
'Soft2' => 'Pehmeä 2',
'n/a' => 'E.s.',
},
},
'SharpnessFactor' => 'Terävöintikerroin',
'SharpnessFaithful' => 'Kohdeuskollinen terävyys',
'SharpnessFreqTable' => 'Terävyyden taajuustaulukko',
'SharpnessFrequency' => 'Terävyystaajuus',
'SharpnessLandscape' => 'Maisemakuvan terävyys',
'SharpnessMonochrome' => 'Yksivärikuvan terävyys',
'SharpnessNeutral' => 'Neutraali terävyys',
'SharpnessPortrait' => 'Muotokuvan terävyys',
'SharpnessSetting' => 'Terävyysasetus',
'SharpnessStandard' => 'Vakioterävyys',
'SharpnessTable' => 'Terävyystaulukko',
'ShootingInfoDisplay' => 'Kuvaustietojen näyttö',
'ShootingMode' => 'IR-kauko-ohjaus',
'ShortDocumentID' => 'Lyhyt dokumentin ID',
'ShortOwnerName' => 'Omistajan lyhyt nimi',
'ShotInfoVersion' => 'Otostietojen versio',
'ShutterCount' => 'Laukaisumäärä',
'ShutterReleaseButtonAE-L' => 'Laukaisin AE-L',
'ShutterSpeedValue' => 'Suljinnopeuden arvo',
'SimilarityIndex' => 'Yhtäläisyysindeksi',
'Site' => 'Sivusto',
'SlaveFlashMeteringSegments' => 'Orjasalaman mittaussegmentit',
'SlowShutter' => 'Hidas suljin',
'SlowSync' => {
Description => 'Hidas suljin',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'Software' => 'Ohjelmisto',
'SoftwareVersion' => 'Ohjelmistoversio',
'Source' => 'Lähde',
'SourceImageDirectory' => 'Lähdekuvan kansio',
'SourceImageFileName' => 'Lähdekuvan tiedostonimi',
'SourceImageVolumeName' => 'Lähdekuvan taltion nimi',
'SpatialFrequencyResponse' => 'Spatiaalisen taajuuden vaste',
'SpecialInstructions' => 'Ohjeet',
'SpecialMode' => 'Erikoistapa',
'SpectralSensitivity' => 'Spektraalinen herkkyys',
'SpotFocusPointX' => 'Pistetarkennuksen piste X',
'SpotFocusPointY' => 'Pistetarkennuksen piste Y',
'SpotMeteringMode' => 'Pistemittaustapa',
'StorageMethod' => 'Tallennusmetodi',
'StraightenAngle' => 'Kuvan suoristus',
'StripByteCounts' => 'Tavuja per pakattu strippi',
'StripOffsets' => 'Kuvadatan sijainti',
'Sub-location' => 'Sijainti',
'SubSecTime' => 'DateTime sekunnin murto-osina',
'SubSecTimeDigitized' => 'DateTimeDigitized sekunnin murto-osina',
'SubSecTimeOriginal' => 'DateTimeOriginal sekunnin murto-osina',
'SubTileBlockSize' => 'Alalaattalohkon koko',
'Subject' => 'Aihe',
'SubjectArea' => 'Kohdealue',
'SubjectDistance' => 'Kohteen etäisyys',
'SubjectDistanceRange' => {
Description => 'Objektiivin tarkennusetäisyys',
PrintConv => {
'Close' => 'Lähikuva',
'Distant' => 'Etäkuva',
'Macro' => 'Makro',
'Unknown' => 'Tuntematon',
},
},
'SubjectLocation' => 'Kohteen sijainti',
'SubjectProgram' => 'Kuvausohjelma',
'SubjectReference' => 'Aiheen koodi',
'SuperMacro' => {
Description => 'Supermakro',
PrintConv => {
'Off' => 'Pois',
'On (1)' => 'Päällä (1)',
'On (2)' => 'Päällä (2)',
},
},
'SupplementalCategories' => 'Täydentävä kategoria',
'SupplementalType' => {
Description => 'Lisäystyyppi',
PrintConv => {
'Main Image' => 'Ei asetettu',
'Rasterized Caption' => 'Rasteroitu seloste',
'Reduced Resolution Image' => 'Alennetun resoluution kuva',
},
},
'SvISOSetting' => 'Sv-ISO-asetus',
'T4Options' => 'Lisätyt täytebitit',
'T6Options' => 'T6-valinnat',
'TIFF-EPStandardID' => 'TIFF/EP-standardin ID',
'TargetAperture' => 'Tavoiteaukko',
'TargetExposureTime' => 'Tavoitevalotusaika',
'TargetPrinter' => 'Kohdetulostin',
'Technology' => {
Description => 'Teknologia',
PrintConv => {
'Digital Camera' => 'Digitaalikamera',
'Dye Sublimation Printer' => 'Lämpösublimaatiotulostin',
'Electrophotographic Printer' => 'Lasertulostin',
'Electrostatic Printer' => 'Sähköstaattinen tulostin',
'Film Scanner' => 'Filmiskanneri',
'Film Writer' => 'Filmitulostin',
'Flexography' => 'Fleksografia',
'Gravure' => 'Syväpaino',
'Ink Jet Printer' => 'Mustesuihkutulostin',
'Offset Lithography' => 'Offsetlitografia',
'Photo CD' => 'Valokuva-CD',
'Photo Image Setter' => 'Valokuvaimagesetteri',
'Photographic Paper Printer' => 'Valokuvapaperitulostin',
'Projection Television' => 'Projektiotelevisio',
'Reflective Scanner' => 'Heijastusskanneri',
'Silkscreen' => 'Silkkipaino',
'Thermal Wax Printer' => 'Lämpövahatulostin',
'Video Camera' => 'Videokamera',
'Video Monitor' => 'Videomonitori',
},
},
'Text' => 'Teksti',
'TextInfo' => 'Tekstitiedot',
'TextStamp' => {
Description => 'Tekstileimasin',
PrintConv => {
'Off' => 'Päällä',
},
},
'Thresholding' => 'Kynnystys',
'ThumbnailImage' => 'Näytekuva',
'ThumbnailImageValidArea' => 'Näytekuvan kelpaava alue',
'TileByteCounts' => 'Ruutujen tavumäärät',
'TileDepth' => 'Ruudun syvyys',
'TileLength' => 'Ruudun pituus',
'TileOffsets' => 'Ruutusiirtymät',
'TileWidth' => 'Otsikon leveys',
'Time' => 'Aika',
'TimeCreated' => 'Luontiaika',
'TimeSent' => 'Lähetysaika',
'TimeSincePowerOn' => 'Virran päälläoloaika',
'TimeStamp' => 'Aikaleima',
'TimeZone' => 'Aikavyöhyke',
'TimeZoneOffset' => 'Aikavyöhykkeen siirtymä',
'TimerFunctionButton' => 'Ajastustoimintopainike',
'Title' => 'Otsikko',
'ToneComp' => 'Sävykorjailu',
'ToneCurve' => 'Sävykäyrä',
'ToneCurveMatching' => 'Sävykäyrän täsmäys',
'ToneCurveTable' => 'Sävykäyrätaulukko',
'ToneCurves' => 'Sävykäyrät',
'ToningEffect' => 'Sävytysefekti',
'ToningEffectMonochrome' => 'Yksivärisävytysefekti',
'ToningSaturation' => 'Sävykylläisyys',
'TransferFunction' => 'Muuntotoiminto',
'TransferRange' => 'Siirtonopeus',
'Transform' => 'Muunna',
'Transformation' => {
Description => 'Muunto',
PrintConv => {
'Mirror horizontal' => 'Peilaa vaakasuunnassa',
'Mirror horizontal and rotate 270 CW' => 'Peilaa vaakasuunnassa ja kierrä 270° myötäpäivään',
'Mirror horizontal and rotate 90 CW' => 'Peilaa vaakasuunnassa ja kierrä 90° myötäpäivään',
'Mirror vertical' => 'Peilaa pystysuunnassa',
'Rotate 180' => 'Kierrä 180°',
'Rotate 270 CW' => 'Kierrä 90° myötäpäivään',
'Rotate 90 CW' => 'Kierrä 90° myötäpäivään',
},
},
'TransparencyIndicator' => 'Läpinäkyvyyden ilmaisin',
'TravelDay' => 'Matkapäivä',
'TvExposureTimeSetting' => 'Tv-valotusaikaasetus',
'Type' => 'Tyyppi',
'Uncompressed' => {
Description => 'Pakkaamaton',
PrintConv => {
'No' => 'Ei',
'Yes' => 'Kyllä',
},
},
'UniqueCameraModel' => 'Uniikki kameramalli',
'UniqueDocumentID' => 'Uniikin dokumentin ID',
'Unknown' => 'Tuntematon',
'Unsharp1Color' => 'Terävöinti 1 -väri',
'Unsharp1HaloWidth' => 'Terävöinti 1 -halolaajuus',
'Unsharp1Intensity' => 'Terävöinti 1 -voimakkuus',
'Unsharp1Threshold' => 'Terävöinti 1 -kynnys',
'Unsharp2Color' => 'Terävöinti 2 -väri',
'Unsharp2HaloWidth' => 'Terävöinti 2 -halolaajuus',
'Unsharp2Intensity' => 'Terävöinti 2 -voimakkuus',
'Unsharp2Threshold' => 'Terävöinti 2 -kynnys',
'Unsharp3Color' => 'Terävöinti 3 -väri',
'Unsharp3HaloWidth' => 'Terävöinti 3 -halolaajuus',
'Unsharp3Intensity' => 'Terävöinti 3 -voimakkuus',
'Unsharp3Threshold' => 'Terävöinti 3 -kynnys',
'Unsharp4Color' => 'Terävöinti 4 -väri',
'Unsharp4HaloWidth' => 'Terävöinti 4 -halolaajuus',
'Unsharp4Intensity' => 'Terävöinti 4 -voimakkuus',
'Unsharp4Threshold' => 'Terävöinti 4 -kynnys',
'UnsharpCount' => 'Terävöintimäärä',
'UnsharpData' => 'Terävöintidata',
'UnsharpMask' => 'Epäterävä maski',
'Urgency' => {
Description => 'Kiireellisyys',
PrintConv => {
'0 (reserved)' => '0 (varattu tulevaan käyttöön)',
'1 (most urgent)' => '1 (hyvin kiireellinen)',
'5 (normal urgency)' => '5 (normaali kiirellisyys)',
'8 (least urgent)' => '8 (lievän kiireellinen)',
'9 (user-defined priority)' => '9 (varattu tulevaan käyttöön)',
},
},
'UserComment' => 'Käyttäjän kommentti',
'UserSelectGroupTitle' => 'Käyttäjän valitseman ryhmän otsikko',
'VRDOffset' => 'VRD-siirtymä',
'VRInfo' => 'Kuvanvakaimen tiedot',
'VRInfoVersion' => 'VR- (kuvanvakain) tietojen versio',
'ValidAFPoints' => 'Kelpaavat AF-pisteet',
'VariProgram' => 'Kuvausohjelma',
'Version' => 'Versio',
'VibrationReduction' => 'Kuvanvakautus',
'VideoCardGamma' => 'Grafiikkakortin gamma',
'ViewfinderWarning' => 'Etsinvaroitus',
'ViewingCondDesc' => 'Katseluolojen kuvaus',
'VignetteControl' => {
Description => 'Vinjetoinnin korjaus',
PrintConv => {
'High' => 'Korkea',
'Low' => 'Matala',
'Normal' => 'Normaali',
'Off' => 'Pois',
},
},
'VignetteControlIntensity' => 'Vinjetoinnin korjauksen voimakkuus',
'VoiceMemo' => {
Description => 'Äänen tallennus',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'WBAdjData' => 'Valkotaspainon säätödata',
'WBBlueLevel' => 'Valkotas. sinisen taso',
'WBBracketMode' => 'Valkotasapaino-haarukointitapa',
'WBBracketValueAB' => 'Valkotasapainon AB-haarukointiarvo',
'WBBracketValueGM' => 'Valkotasapainon GM-haarukointiarvo',
'WBGreenLevel' => 'Vihreän taso',
'WBMode' => {
Description => 'Valkotasapainotila',
PrintConv => {
'Auto' => 'Automaattinen',
},
},
'WBRedLevel' => 'Valkotas. punaisen taso',
'WBShiftAB' => 'Valkotas. säätö keltainen/sininen',
'WBShiftGM' => 'Valkotas. säätö vihreä/magenta',
'WB_RBLevels' => 'Valkotasapaino punainen/sininen',
'WB_RBLevelsAuto' => 'Valkotas. RB-tasot, automatiikka',
'WB_RBLevelsCoolWhiteFluor' => 'Valkotas. RB-tasot, viileän valk. loistel.',
'WB_RBLevelsDayWhiteFluor' => 'Valkotas. RB-tasot, valk. päivänvaloloistel.',
'WB_RBLevelsDaylightFluor' => 'Valkotas. RB-tasot, päivänvaloloistel.',
'WB_RBLevelsEveningSunlight' => 'Valkotas. RB-tasot, ilta-aurinko',
'WB_RBLevelsFineWeather' => 'Valkotas. RB-tasot, kaunis sää',
'WB_RBLevelsShade' => 'Valkotas. RB-tasot, varjo',
'WB_RBLevelsTungsten' => 'Valkotas. RB-tasot, hehkulamppu',
'WB_RBLevelsUsed' => 'Käytetyt valkotas. RB-tasot',
'WB_RBLevelsWhiteFluorescent' => 'Valkotas. RB-tasot, valk. loistelamppu',
'WB_RGGBLevelsCloudy' => 'Valkotasapainon RGGB-tasojen pilvinen',
'WB_RGGBLevelsDaylight' => 'Valkotasapainon RGGB-tasojen päivänvalo',
'WB_RGGBLevelsFlash' => 'Valkotasapainon RGGB-tasojen salama',
'WB_RGGBLevelsFluorescentD' => 'Valkotasapainon RGGB-tasojen loistelamppu D',
'WB_RGGBLevelsFluorescentN' => 'Valkotasapainon RGGB-tasojen loistelamppu N',
'WB_RGGBLevelsFluorescentW' => 'Valkotasapainon RGGB-tasojen loistelamppu W',
'WB_RGGBLevelsShade' => 'Valkotasapainon RGGB-tasojen varjo',
'WB_RGGBLevelsTungsten' => 'Valkotasapainon RGGB-tasojen hehkulamppu',
'Watermark' => 'Vesileima',
'WatermarkType' => 'Vesileiman tyyppi',
'WhiteBalance' => {
Description => 'Valkotasapaino',
PrintConv => {
'Auto' => 'Automaattinen',
'Cloudy' => 'Pilvinen',
'Custom' => 'Mukautus',
'Custom2' => 'Mukautus 2',
'Custom3' => 'Mukautus 3',
'Custom4' => 'Mukautus 4',
'Day White Fluorescent' => 'Valkoinen päivänvaloloistelamppu',
'Daylight' => 'Auringonvalo',
'Daylight Fluorescent' => 'Päivänvaloloistelamppu',
'Flash' => 'Salama',
'Incandescent' => 'Hehkulamppu',
'Living Room Warm White Fluorescent' => 'Asuinhuoneen lämmin valkoinen loistelamppu',
'Manual' => 'Manuaalinen',
'Warm White Fluorescent' => 'Lämmin valkoinen loistelamppu',
'White Fluorescent' => 'Valkoinen loistelamppu',
},
},
'WhiteBalance2' => {
Description => 'Valkotasapaino',
PrintConv => {
'3000K (Tungsten light)' => '3000 K (hehkulamppu)',
'3600K (Tungsten light-like)' => '3600 K (hehkulamppumainen valo)',
'4000K (Cool white fluorescent)' => '4000 K (viileän valkoinen loistelamppu)',
'4500K (Neutral white fluorescent)' => '4500 K (neutraali valkoinen loistelamppu)',
'5300K (Fine Weather)' => '5300 K (kaunis sää)',
'6000K (Cloudy)' => '6000 K (pilvinen)',
'6600K (Daylight fluorescent)' => '6600 K (päivänvaloloistelamppu)',
'7500K (Fine Weather with Shade)' => '7500 K (kaunis sää ja varjoja)',
'Auto' => 'Automaattinen',
'Custom WB 1' => 'Mukautettu valkotasapaino 1',
'Custom WB 2' => 'Mukautettu valkotasapaino 2',
'Custom WB 2900K' => 'Mukautettu valkotasapaino 2900 K',
'Custom WB 3' => 'Mukautettu valkotasapaino 3',
'Custom WB 4' => 'Mukautettu valkotasapaino 4',
'Custom WB 5400K' => 'Mukautettu valkotasapaino 5400 K',
'Custom WB 8000K' => 'Mukautettu valkotasapaino 8000 K',
},
},
'WhiteBalanceAdj' => 'Väritasapainon säätö',
'WhiteBalanceBias' => 'Valkotasapainon korjaus',
'WhiteBalanceBlue' => 'Valkotasapaino sininen',
'WhiteBalanceBracket' => 'Valkotasapainon haarukointi',
'WhiteBalanceBracketing' => 'Valkotasapainohaarukointi',
'WhiteBalanceComp' => 'Valkotasapainon säätö',
'WhiteBalanceFineTune' => 'Valkotasapainon hienosäätö',
'WhiteBalanceMatching' => 'Valkotasapainon täsmäys',
'WhiteBalanceMode' => {
Description => 'Valkotasapainon muoto',
PrintConv => {
'Auto (Cloudy)' => 'Automaattinen (pilvinen)',
'Auto (Day White Fluorescent)' => 'Automaattinen (valkoinen päivänvaloloistelamppu)',
'Auto (Daylight Fluorescent)' => 'Automaattinen (päivänvaloloistelamppu)',
'Auto (Daylight)' => 'Automaattinen (auringonvalo)',
'Auto (Flash)' => 'Automaattinen (salama)',
'Auto (Shade)' => 'Automaattinen (varjo)',
'Auto (Tungsten)' => 'Automaattinen (hehkulamppu)',
'Auto (White Fluorescent)' => 'Automaattinen (valkoinen loistelamppu)',
'Unknown' => 'Automaattinen (ei tunnistettu)',
'User-Selected' => 'Itse valittu',
},
},
'WhiteBalanceRed' => 'Valkotasapaino punainen',
'WhiteBalanceSet' => 'Asetettu valkotasapaino',
'WhiteBalanceTable' => 'Valkotasapainotaulukko',
'WhiteBalanceTemperature' => 'Valkotaspainon lämpötila',
'WhiteBoard' => 'Valkoinen pohja',
'WhiteLevel' => 'Valkoinen taso',
'WhitePoint' => 'Valkoinen piste',
'WhitePointX' => 'Valkoinen piste X',
'WhitePointY' => 'Valkoinen piste Y',
'Wide' => 'Laaja',
'WideFocusZone' => 'Laaja-alatarkennuksen alue',
'WideRange' => {
Description => 'Laaja alue',
PrintConv => {
'Off' => 'Pois',
'On' => 'Päällä',
},
},
'WorldTimeLocation' => {
Description => 'Maailmanaikasijainti',
PrintConv => {
'Destination' => 'Kohde',
'Home' => 'Koti',
'Hometown' => 'Kotiseutu',
},
},
'Writer-Editor' => 'Selosteen/Kuvatekstin kirjoittaja',
'X3FillLight' => 'X3-täytevalo',
'XClipPathUnits' => 'X-leikepolkuyksiköt',
'XMP' => 'XMP-metadata',
'XPosition' => 'X-sijainti',
'XResolution' => 'Kuvan vaakaresoluutio',
'YCbCrCoefficients' => 'Väriavaruuden muunnon matriisikertoimet',
'YCbCrPositioning' => 'Y:n ja C:n sijoitus',
'YCbCrSubSampling' => 'Suhteen Y - C subsamplaus',
'YClipPathUnits' => 'Y-leikepolkuyksiköt',
'YPosition' => 'Y-sijainti',
'YResolution' => 'Kuvan pystyresoluutio',
'ZoneMatching' => {
Description => 'Yli/alivalotuksen esto',
PrintConv => {
'High Key' => 'Yläsävykuva',
'ISO Setting Used' => 'Pois (käytetty ISO-asetusta)',
'Low Key' => 'Alasävykuva',
},
},
'Zoom' => 'Zoom-objektiivi',
'ZoomSourceWidth' => 'Zoomauksen lähtökoko',
'ZoomStepCount' => 'Zoom-askelmäärä',
'ZoomTargetWidth' => 'Zoomauksen loppukoko',
);
1; # end
__END__
=head1 NAME
Image::ExifTool::Lang::fi.pm - ExifTool Finnish language translations
=head1 DESCRIPTION
This file is used by Image::ExifTool to generate localized tag descriptions
and values.
=head1 AUTHOR
Copyright 2003-2015, Phil Harvey (phil at owl.phy.queensu.ca)
This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=head1 ACKNOWLEDGEMENTS
Thanks to Jens Duttke and Jarkko ME<auml>kineva for providing this
translation.
=head1 SEE ALSO
L<Image::ExifTool(3pm)|Image::ExifTool>,
L<Image::ExifTool::TagInfoXML(3pm)|Image::ExifTool::TagInfoXML>
=cut
| mudasobwa/exifice | vendor/Image-ExifTool-10.02/lib/Image/ExifTool/Lang/fi.pm | Perl | mit | 110,744 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
0035
0665
06F5
07C5
096B
09EB
0A6B
0AEB
0B6B
0BEB
0C6B
0CEB
0D6B
0E55
0ED5
0F25
1045
1095
136D
17E5
17F5
1815
194B
19D5
1A85
1A95
1B55
1BB5
1C45
1C55
2075
2085
2164
2174
2464
2478
248C
24F9
277A
2784
278E
3025
3224
3284
3405
382A
4E94
4F0D
A625
A6EA
A8D5
A905
A9D5
AA55
ABF5
FF15
1010B
10143
10148
1014F
1015F
10173
10321
104A5
10E64
11056
1106B
110F5
1113B
111D5
116C5
12403
1240A
12410
12419
12422
12427
12431
12439
1244D
12454 12455
1D364
1D7D3
1D7DD
1D7E7
1D7F1
1D7FB
1F106
20121
END
| Dokaponteam/ITF_Project | xampp/perl/lib/unicore/lib/Nv/5.pl | Perl | mit | 1,071 |
line1=Opcje konfigurowalne,11
display_max=Maksymalna liczba wy¶wietlanych u¿ytkowników lub grup,0
threshold_pc=Próg procentowy wykorzystanego limitu quota, od którego pod¶wietlaæ,3,Nie pokazuj
pc_show=Pokazuj procent wykorzystania limitu,1,2-Twardego i miêkkiego,1-Tylko twardego,0-Tylko miêkkiego
sort_mode=Sortuj u¿ytkowników i grupy wed³ug,1,0-Bloków u¿ytych,2-Nazwy,1-Kolejno¶ci z repquota,3-Twardego limitu bloków,4-Miêkkiego limitu bloków,5-Procentu u¿ycia z twardego limitu,6-Procentu u¿ycia z miêkkiego limitu
block_mode=Pokazuj quoty w ,1,1-Kilobajtach (je¶li mo¿liwe),0-Blokach
hide_uids=Pokazywaæ usuniêtych u¿ytkowników?,1,0-Tak,1-Nie
line1.1=Wiadomo¶ci e-mail w sprawie quota,11
email_msg=Wiadomo¶æ do u¿ytkowników przekraczaj±cych limit quoty,9,80,5,\t
email_subject=Temat wiadomo¶ci do u¿ytkowników,3,Domy¶lnie
gemail_msg=Wiadomo¶æ do grup przekraczaj±cych limity quoty,9,80,5,\t
gemail_subject=Temat wiadomo¶ci do grup,3,Domy¶lnie
line2=Konfiguracja systemu,11
show_grace=Pokazywaæ czasy ulgi je¶li dostêpne?,1,1-Tak,0-Nie
user_repquota_command=Polecenie wy¶wietlaj±ce u¿ytkowników w systemie plików,0
group_repquota_command=Polecenie wy¶wietlaj±ce grupy w systemie plików,0
user_edquota_command=Polecenie do zmiany quota u¿ytkownika,0
group_edquota_command=Polecenie do zmiany quota grupy,0
user_setquota_command=Polecenie do ustawienia quota u¿ytkownika,3,Brak
group_setquota_command=Polecenie do ustawienia quota grupy,3,Brak
user_quota_command=Polecenie do sprawdzenia quota u¿ytkownika,0
group_quota_command=Polecenie do sprawdzenia quota grupy,0
user_copy_command=Polecenie do skopiowania quota u¿ytkownika,0
group_copy_command=Polecenie do skopiowania quota grupy,0
user_quotaon_command=Polecenie do w³±czenia quota u¿ytkowników,0
group_quotaon_command=Polecenie do w³±czenia quota grup,0
user_quotaoff_command=Polecenie do wy³±czenia quota u¿ytkowników,0
group_quotaoff_command=Polecenie do wy³±czenia quota grup,0
quotacheck_command=Polecenie do naliczenia quota,0
user_grace_command=Polecenie do zmiany czasu ulgi dla u¿ytkowników,0
group_grace_command=Polecenie do zmiany czasu ulgi dla grup,0
| HasClass0/webmin | quota/config.info.pl | Perl | bsd-3-clause | 2,131 |
package File::CheckTree;
use 5.006;
use Cwd;
use Exporter;
use File::Spec;
use warnings;
use strict;
use if $] > 5.017, 'deprecate';
our $VERSION = '4.42';
our @ISA = qw(Exporter);
our @EXPORT = qw(validate);
=head1 NAME
File::CheckTree - run many filetest checks on a tree
=head1 SYNOPSIS
use File::CheckTree;
$num_warnings = validate( q{
/vmunix -e || die
/boot -e || die
/bin cd
csh -ex
csh !-ug
sh -ex
sh !-ug
/usr -d || warn "What happened to $file?\n"
});
=head1 DESCRIPTION
The validate() routine takes a single multiline string consisting of
directives, each containing a filename plus a file test to try on it.
(The file test may also be a "cd", causing subsequent relative filenames
to be interpreted relative to that directory.) After the file test
you may put C<|| die> to make it a fatal error if the file test fails.
The default is C<|| warn>. The file test may optionally have a "!' prepended
to test for the opposite condition. If you do a cd and then list some
relative filenames, you may want to indent them slightly for readability.
If you supply your own die() or warn() message, you can use $file to
interpolate the filename.
Filetests may be bunched: "-rwx" tests for all of C<-r>, C<-w>, and C<-x>.
Only the first failed test of the bunch will produce a warning.
The routine returns the number of warnings issued.
=head1 AUTHOR
File::CheckTree was derived from lib/validate.pl which was
written by Larry Wall.
Revised by Paul Grassie <F<grassie@perl.com>> in 2002.
=head1 HISTORY
File::CheckTree used to not display fatal error messages.
It used to count only those warnings produced by a generic C<|| warn>
(and not those in which the user supplied the message). In addition,
the validate() routine would leave the user program in whatever
directory was last entered through the use of "cd" directives.
These bugs were fixed during the development of perl 5.8.
The first fixed version of File::CheckTree was 4.2.
=cut
my $Warnings;
sub validate {
my ($starting_dir, $file, $test, $cwd, $oldwarnings);
$starting_dir = cwd;
$cwd = "";
$Warnings = 0;
foreach my $check (split /\n/, $_[0]) {
my ($testlist, @testlist);
# skip blanks/comments
next if $check =~ /^\s*#/ || $check =~ /^\s*$/;
# Todo:
# should probably check for invalid directives and die
# but earlier versions of File::CheckTree did not do this either
# split a line like "/foo -r || die"
# so that $file is "/foo", $test is "-r || die"
# (making special allowance for quoted filenames).
if ($check =~ m/^\s*"([^"]+)"\s+(.*?)\s*$/ or
$check =~ m/^\s*'([^']+)'\s+(.*?)\s*$/ or
$check =~ m/^\s*(\S+?)\s+(\S.*?)\s*$/)
{
($file, $test) = ($1,$2);
}
else {
die "Malformed line: '$check'";
};
# change a $test like "!-ug || die" to "!-Z || die",
# capturing the bundled tests (e.g. "ug") in $2
if ($test =~ s/ ^ (!?-) (\w{2,}) \b /$1Z/x) {
$testlist = $2;
# split bundled tests, e.g. "ug" to 'u', 'g'
@testlist = split(//, $testlist);
}
else {
# put in placeholder Z for stand-alone test
@testlist = ('Z');
}
# will compare these two later to stop on 1st warning w/in a bundle
$oldwarnings = $Warnings;
foreach my $one (@testlist) {
# examples of $test: "!-Z || die" or "-w || warn"
my $this = $test;
# expand relative $file to full pathname if preceded by cd directive
$file = File::Spec->catfile($cwd, $file)
if $cwd && !File::Spec->file_name_is_absolute($file);
# put filename in after the test operator
$this =~ s/(-\w\b)/$1 "\$file"/g;
# change the "-Z" representing a bundle with the $one test
$this =~ s/-Z/-$one/;
# if it's a "cd" directive...
if ($this =~ /^cd\b/) {
# add "|| die ..."
$this .= ' || die "cannot cd to $file\n"';
# expand "cd" directive with directory name
$this =~ s/\bcd\b/chdir(\$cwd = '$file')/;
}
else {
# add "|| warn" as a default disposition
$this .= ' || warn' unless $this =~ /\|\|/;
# change a generic ".. || die" or ".. || warn"
# to call valmess instead of die/warn directly
# valmess will look up the error message from %Val_Message
$this =~ s/ ^ ( (\S+) \s+ \S+ ) \s* \|\| \s* (die|warn) \s* $
/$1 || valmess('$3', '$2', \$file)/x;
}
{
# count warnings, either from valmess or '-r || warn "my msg"'
# also, call any pre-existing signal handler for __WARN__
my $orig_sigwarn = $SIG{__WARN__};
local $SIG{__WARN__} = sub {
++$Warnings;
if ( $orig_sigwarn ) {
$orig_sigwarn->(@_);
}
else {
warn "@_";
}
};
# do the test
eval $this;
# re-raise an exception caused by a "... || die" test
if (my $err = $@) {
# in case of any cd directives, return from whence we came
if ($starting_dir ne cwd) {
chdir($starting_dir) || die "$starting_dir: $!";
}
die $err;
}
}
# stop on 1st warning within a bundle of tests
last if $Warnings > $oldwarnings;
}
}
# in case of any cd directives, return from whence we came
if ($starting_dir ne cwd) {
chdir($starting_dir) || die "chdir $starting_dir: $!";
}
return $Warnings;
}
my %Val_Message = (
'r' => "is not readable by uid $>.",
'w' => "is not writable by uid $>.",
'x' => "is not executable by uid $>.",
'o' => "is not owned by uid $>.",
'R' => "is not readable by you.",
'W' => "is not writable by you.",
'X' => "is not executable by you.",
'O' => "is not owned by you.",
'e' => "does not exist.",
'z' => "does not have zero size.",
's' => "does not have non-zero size.",
'f' => "is not a plain file.",
'd' => "is not a directory.",
'l' => "is not a symbolic link.",
'p' => "is not a named pipe (FIFO).",
'S' => "is not a socket.",
'b' => "is not a block special file.",
'c' => "is not a character special file.",
'u' => "does not have the setuid bit set.",
'g' => "does not have the setgid bit set.",
'k' => "does not have the sticky bit set.",
'T' => "is not a text file.",
'B' => "is not a binary file."
);
sub valmess {
my ($disposition, $test, $file) = @_;
my $ferror;
if ($test =~ / ^ (!?) -(\w) \s* $ /x) {
my ($neg, $ftype) = ($1, $2);
$ferror = "$file $Val_Message{$ftype}";
if ($neg eq '!') {
$ferror =~ s/ is not / should not be / ||
$ferror =~ s/ does not / should not / ||
$ferror =~ s/ not / /;
}
}
else {
$ferror = "Can't do $test $file.\n";
}
die "$ferror\n" if $disposition eq 'die';
warn "$ferror\n";
}
1;
| liuyangning/WX_web | xampp/perl/lib/File/CheckTree.pm | Perl | mit | 7,734 |
#!/usr/bin/perl -w
#
# found here: http://www.derose.net/steve/utilities/SHELLUTILS/makeGraphvizFromDirTree
#
# Make a Graphviz dot file for your file system
#
# deroses
#
# Notes on graphviz syntax:
# // comment
# "node1" -> "node2";
# "node1" -- "node2";
# node [ a=v, a=v];
# "nodename" [props];
# Some attributes/properties:
# shape, sides, orientation, color, fillcolor, fontcolor, fontname,
# fontsize, height, label, style, toplabel, URL,
#
use strict;
use Getopt::Long;
my $version = "2010-09-12";
my $docvs = 0;
my $doFiles = 0;
my $quiet = 0;
my $verbose = 0;
# Process options
#
Getopt::Long::Configure ("ignore_case");
my $result = GetOptions(
"cvs" => \$docvs,
"f" => \$doFiles,
"h|help|?" => sub {
system "perldoc makeGraphvizFromDirTree"; exit;
},
"q|quiet!" => \$quiet,
"v|verbose+" => \$verbose,
"version" => sub {
die "Version of $version, by Steven J. DeRose.\n";
}
);
($result) || die "Bad options.\n";
###############################################################################
my $file = $ARGV[0];
(-d $file) || die "Couldn't find directory '$file'.\n";
my %namesUsed = ();
print "// " . glob($file) . "\n";
print "
// GraphViz dot file for '$file', generated by dirtree.
digraph file_system {
//rankdir=LR;
size=\"8,11\";
";
my $depth = 0;
dirTraverse("$file/");
print "}\n";
exit;
sub dirTraverse() {
my $theDir = $_[0];
my $shortDir = $theDir;
if (substr($shortDir,length($shortDir)-1,1) eq "/") { chop($shortDir); }
$shortDir =~ s/.*\///;
$depth += 3;
#print "\n";
#print "// entering dirtraverse for '$theDir'\n";
my $cmd = "ls -dF $theDir" . "*";
#print " command is '$cmd'\n";
my @subdirs = `$cmd`;
my $sd;
#print "// ls got: " . scalar @subdirs . " items.\n";
#print "subdirs now " . join(", ", @subdirs) . "\n";
# Issue the dot file definition of the arc
foreach my $sd (@subdirs) {
chomp($sd);
my $isDir = (substr($sd,length($sd)-1,1) eq "/") ? 1:0;
if ($isDir or $doFiles) {
my $c = index($sd,"CVS");
if ($c > -1 and $c == length($sd)-4) { next; }
my $shortName = $sd;
chop($shortName); # nuke the slash
$shortName =~ s/.*\///;
if ($namesUsed{$shortName}) {
#$shortName .= "(" . int(rand(1000)) . ")";
}
print " " x $depth;
($isDir) || print "\"$shortName\" [ color=red ]; ";
print "\"$shortDir\" -> \"$shortName\";\n";
$namesUsed{$sd} = $shortName;
}
}
# Recurse for each subdirectory
my $i = 0;
foreach my $sd (@subdirs) {
chomp($sd);
$i++;
my $isDir = (substr($sd,length($sd)-1,1) eq "/") ? 1:0;
if ($isDir) {
my $c = index($sd,"CVS");
if ($c > -1 and $c == length($sd)-4) { next; }
#print " " x $depth;
#print "// Recursing on '$sd' ($i of " . scalar @subdirs . ")\n";
dirTraverse("$sd");
}
else {
#print "// No traverse for '$sd'\n";
}
}
$depth -= 3;
} # dirTraverse
###############################################################################
sub showUsage() {
print "
=head1 Usage
dirtree [dir]
Make a 'dot' file for Graphviz, showing your directory structure.
The dot file is written to stdout.
See http://www.graphviz.org/Gallery.php
=head1 Options
=over
-q suppresses most messages.
-f include files, not just directories (different color)
-cvs include CVS directories (normally omitted)
=back
=head1 Ownership
This work by Steven J. DeRose is licensed under a Creative Commons
Attribution-Share Alike 3.0 Unported License. For further information on
this license, see http://creativecommons.org/licenses/by-sa/3.0/.
The author's present email is sderose at acm.org.
For the most recent version, see http://www.derose.net/steve/utilities/.
=cut
";
}
| onaclov2000/prettydirprint | print_tree.pl | Perl | mit | 3,781 |
use strict;
package SGN::Controller::AJAX::HighDimensionalPhenotypes;
use Moose;
use Data::Dumper;
use File::Temp qw | tempfile |;
# use File::Slurp;
use File::Spec qw | catfile|;
use File::Basename qw | basename |;
use File::Copy;
use CXGN::Dataset;
use CXGN::Dataset::File;
use CXGN::Tools::Run;
use CXGN::Tools::List qw/distinct evens/;
use Cwd qw(cwd);
use JSON::XS;
use List::Util qw(shuffle);
use CXGN::AnalysisModel::GetModel;
use CXGN::UploadFile;
use DateTime;
use CXGN::Phenotypes::StorePhenotypes;
use CXGN::Phenotypes::HighDimensionalPhenotypesSearch;
use CXGN::Phenotypes::HighDimensionalPhenotypesRelationshipMatrix;
BEGIN { extends 'Catalyst::Controller::REST' }
__PACKAGE__->config(
default => 'application/json',
stash_key => 'rest',
map => { 'application/json' => 'JSON', 'text/html' => 'JSON' },
);
sub high_dimensional_phenotypes_nirs_upload_verify : Path('/ajax/highdimensionalphenotypes/nirs_upload_verify') : ActionClass('REST') { }
sub high_dimensional_phenotypes_nirs_upload_verify_POST : Args(0) {
my $self = shift;
my $c = shift;
print STDERR Dumper $c->req->params();
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my @success_status;
my @error_status;
my @warning_status;
my $parser = CXGN::Phenotypes::ParseUpload->new();
my $validate_type = "spreadsheet nirs";
my $metadata_file_type = "nirs spreadsheet";
my $subdirectory = "spreadsheet_phenotype_upload";
my $timestamp_included;
my $protocol_id = $c->req->param('upload_nirs_spreadsheet_protocol_id');
my $protocol_name = $c->req->param('upload_nirs_spreadsheet_protocol_name');
my $protocol_desc = $c->req->param('upload_nirs_spreadsheet_protocol_desc');
my $protocol_device_type = $c->req->param('upload_nirs_spreadsheet_protocol_device_type');
if ($protocol_id && $protocol_name) {
$c->stash->{rest} = {error => ["Please give a protocol name or select a previous protocol, not both!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_name || !$protocol_desc)) {
$c->stash->{rest} = {error => ["Please give a protocol name and description, or select a previous protocol!"]};
$c->detach();
}
if ($protocol_name && !$protocol_device_type) {
$c->stash->{rest} = {error => ["Please give a NIRS device type to save a new protocol!"]};
$c->detach();
}
my $high_dim_nirs_protocol_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_nirs_protocol', 'protocol_type')->cvterm_id();
my $high_dim_nirs_protocol_prop_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_protocol_properties', 'protocol_property')->cvterm_id();
if ($protocol_id) {
my $protocol_prop_json = decode_json $schema->resultset('NaturalDiversity::NdProtocolprop')->search({nd_protocol_id=>$protocol_id, type_id=>$high_dim_nirs_protocol_prop_cvterm_id})->first->value;
$protocol_device_type = $protocol_prop_json->{device_type};
}
my $data_level = $c->req->param('upload_nirs_spreadsheet_data_level') || 'tissue_samples';
my $upload = $c->req->upload('upload_nirs_spreadsheet_file_input');
my $upload_original_name = $upload->filename();
my $upload_tempfile = $upload->tempname;
my $time = DateTime->now();
my $timestamp = $time->ymd()."_".$time->hms();
my $uploader = CXGN::UploadFile->new({
tempfile => $upload_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_with_path = $uploader->archive();
my $md5 = $uploader->get_md5($archived_filename_with_path);
if (!$archived_filename_with_path) {
push @error_status, "Could not save file $upload_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_original_name saved in archive.";
}
unlink $upload_tempfile;
my $archived_image_zipfile_with_path;
my $nd_protocol_filename;
my $validate_file = $parser->validate($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $protocol_id, $nd_protocol_filename);
if (!$validate_file) {
push @error_status, "Archived file not valid: $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($validate_file == 1){
push @success_status, "File valid: $upload_original_name.";
} else {
if ($validate_file->{'error'}) {
push @error_status, $validate_file->{'error'};
}
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
## Set metadata
my %phenotype_metadata;
$phenotype_metadata{'archived_file'} = $archived_filename_with_path;
$phenotype_metadata{'archived_file_type'} = $metadata_file_type;
$phenotype_metadata{'operator'} = $user_name;
$phenotype_metadata{'date'} = $timestamp;
my $parsed_file = $parser->parse($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $nd_protocol_filename);
if (!$parsed_file) {
push @error_status, "Error parsing file $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file->{'error'}) {
push @error_status, $parsed_file->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my %parsed_data;
my @plots;
my @wavelengths;
if (scalar(@error_status) == 0) {
if ($parsed_file && !$parsed_file->{'error'}) {
%parsed_data = %{$parsed_file->{'data'}};
@plots = @{$parsed_file->{'units'}};
@wavelengths = @{$parsed_file->{'variables'}};
push @success_status, "File data successfully parsed.";
}
}
my @filter_input;
while (my ($stock_name, $o) = each %parsed_data) {
my $device_id = $o->{nirs}->{device_id};
my $comments = $o->{nirs}->{comments};
my $spectras = $o->{nirs}->{spectra};
foreach my $spectra (@$spectras) {
push @filter_input, {
"observationUnitId" => $stock_name,
"device_type" => $protocol_device_type,
"nirs_spectra" => $spectra,
};
}
}
my $nirs_dir = $c->tempfiles_subdir('/nirs_files');
my $tempfile_string = $c->tempfile( TEMPLATE => 'nirs_files/fileXXXX');
my $filter_json_filepath = $c->config->{basepath}."/".$tempfile_string."_input_json";
my $output_csv_filepath = $c->config->{basepath}."/".$tempfile_string."_output.csv";
my $output_raw_csv_filepath = $c->config->{basepath}."/".$tempfile_string."_output_raw.csv";
my $output_outliers_filepath = $c->config->{basepath}."/".$tempfile_string."_output_outliers.csv";
my $output_plot_filepath_string = $tempfile_string."_output_plot.png";
my $output_plot_filepath = $c->config->{basepath}."/".$output_plot_filepath_string;
my $json = JSON->new->utf8->canonical();
my $filter_data_input_json = $json->encode(\@filter_input);
open(my $F, '>', $filter_json_filepath);
print STDERR Dumper $filter_json_filepath;
print $F $filter_data_input_json;
close($F);
my $cmd_s = "Rscript ".$c->config->{basepath} . "/R/Nirs/nirs_upload_filter_aggregate.R '$filter_json_filepath' '$output_csv_filepath' '$output_raw_csv_filepath' '$output_plot_filepath' '$output_outliers_filepath' ";
print STDERR $cmd_s;
my $cmd_status = system($cmd_s);
my $parsed_file_agg = $parser->parse($validate_type, $output_csv_filepath, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $nd_protocol_filename);
if (!$parsed_file_agg) {
push @error_status, "Error parsing aggregated file.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file_agg->{'error'}) {
push @error_status, $parsed_file_agg->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my %parsed_data_agg;
my @plots_agg;
my @wavelengths_agg;
if (scalar(@error_status) == 0) {
if ($parsed_file_agg && !$parsed_file_agg->{'error'}) {
%parsed_data_agg = %{$parsed_file_agg->{'data'}};
@plots_agg = @{$parsed_file_agg->{'units'}};
@wavelengths_agg = @{$parsed_file_agg->{'variables'}};
push @success_status, "Aggregated file data successfully parsed.";
}
}
my $pheno_dir = $c->tempfiles_subdir('/delete_nd_experiment_ids');
my $temp_file_nd_experiment_id = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'delete_nd_experiment_ids/fileXXXX');
my $store_phenotypes = CXGN::Phenotypes::StorePhenotypes->new({
basepath=>$c->config->{basepath},
dbhost=>$c->config->{dbhost},
dbname=>$c->config->{dbname},
dbuser=>$c->config->{dbuser},
dbpass=>$c->config->{dbpass},
temp_file_nd_experiment_id=>$temp_file_nd_experiment_id,
bcs_schema=>$schema,
metadata_schema=>$metadata_schema,
phenome_schema=>$phenome_schema,
user_id=>$user_id,
stock_list=>\@plots_agg,
trait_list=>[],
values_hash=>\%parsed_data_agg,
has_timestamps=>0,
metadata_hash=>\%phenotype_metadata
});
my $warning_status;
my ($verified_warning, $verified_error) = $store_phenotypes->verify();
if ($verified_error) {
push @error_status, $verified_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($verified_warning) {
push @warning_status, $verified_warning;
}
push @success_status, "Aggregated file data verified. Plot names and trait names are valid.";
# print STDERR Dumper \@success_status;
# print STDERR Dumper \@warning_status;
# print STDERR Dumper \@error_status;
# print STDERR Dumper $output_plot_filepath_string;
$c->stash->{rest} = {success => \@success_status, warning => \@warning_status, error => \@error_status, figure => $output_plot_filepath_string};
}
sub high_dimensional_phenotypes_nirs_upload_store : Path('/ajax/highdimensionalphenotypes/nirs_upload_store') : ActionClass('REST') { }
sub high_dimensional_phenotypes_nirs_upload_store_POST : Args(0) {
my $self = shift;
my $c = shift;
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my @success_status;
my @error_status;
my @warning_status;
my $parser = CXGN::Phenotypes::ParseUpload->new();
my $validate_type = "spreadsheet nirs";
my $metadata_file_type = "nirs spreadsheet";
my $subdirectory = "spreadsheet_phenotype_upload";
my $timestamp_included;
my $protocol_id = $c->req->param('upload_nirs_spreadsheet_protocol_id');
my $protocol_name = $c->req->param('upload_nirs_spreadsheet_protocol_name');
my $protocol_desc = $c->req->param('upload_nirs_spreadsheet_protocol_desc');
my $protocol_device_type = $c->req->param('upload_nirs_spreadsheet_protocol_device_type');
if ($protocol_id && $protocol_name) {
$c->stash->{rest} = {error => ["Please give a protocol name or select a previous protocol, not both!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_name || !$protocol_desc)) {
$c->stash->{rest} = {error => ["Please give a protocol name and description, or select a previous protocol!"]};
$c->detach();
}
if ($protocol_name && !$protocol_device_type) {
$c->stash->{rest} = {error => ["Please give a NIRS device type to save a new protocol!"]};
$c->detach();
}
my $high_dim_nirs_protocol_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_nirs_protocol', 'protocol_type')->cvterm_id();
my $high_dim_nirs_protocol_prop_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_protocol_properties', 'protocol_property')->cvterm_id();
if ($protocol_id) {
my $protocol_prop_json = decode_json $schema->resultset('NaturalDiversity::NdProtocolprop')->search({nd_protocol_id=>$protocol_id, type_id=>$high_dim_nirs_protocol_prop_cvterm_id})->first->value;
$protocol_device_type = $protocol_prop_json->{device_type};
}
my $data_level = $c->req->param('upload_nirs_spreadsheet_data_level') || 'tissue_samples';
my $upload = $c->req->upload('upload_nirs_spreadsheet_file_input');
my $upload_original_name = $upload->filename();
my $upload_tempfile = $upload->tempname;
my $time = DateTime->now();
my $timestamp = $time->ymd()."_".$time->hms();
my $uploader = CXGN::UploadFile->new({
tempfile => $upload_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_with_path = $uploader->archive();
my $md5 = $uploader->get_md5($archived_filename_with_path);
if (!$archived_filename_with_path) {
push @error_status, "Could not save file $upload_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_original_name saved in archive.";
}
unlink $upload_tempfile;
my $archived_image_zipfile_with_path;
my $nd_protocol_filename;
my $validate_file = $parser->validate($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $protocol_id, $nd_protocol_filename);
if (!$validate_file) {
push @error_status, "Archived file not valid: $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($validate_file == 1){
push @success_status, "File valid: $upload_original_name.";
} else {
if ($validate_file->{'error'}) {
push @error_status, $validate_file->{'error'};
}
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my $parsed_file = $parser->parse($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $nd_protocol_filename);
if (!$parsed_file) {
push @error_status, "Error parsing file $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file->{'error'}) {
push @error_status, $parsed_file->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my %parsed_data;
my @plots;
my @wavelengths;
if (scalar(@error_status) == 0) {
if ($parsed_file && !$parsed_file->{'error'}) {
%parsed_data = %{$parsed_file->{'data'}};
@plots = @{$parsed_file->{'units'}};
@wavelengths = @{$parsed_file->{'variables'}};
push @success_status, "File data successfully parsed.";
}
}
my @filter_input;
while (my ($stock_name, $o) = each %parsed_data) {
my $device_id = $o->{nirs}->{device_id};
my $comments = $o->{nirs}->{comments};
my $spectras = $o->{nirs}->{spectra};
foreach my $spectra (@$spectras) {
push @filter_input, {
"observationUnitId" => $stock_name,
"device_type" => $protocol_device_type,
"nirs_spectra" => $spectra
};
}
}
my $dir = $c->tempfiles_subdir('/nirs_files');
my $tempfile = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'nirs_files/fileXXXX');
my $filter_json_filepath = $tempfile."_input_json";
my $output_csv_filepath = $tempfile."_output.csv";
my $output_raw_csv_filepath = $tempfile."_output_raw.csv";
my $output_outliers_filepath = $tempfile."_output_outliers.csv";
my $tempfile_string = $c->tempfile( TEMPLATE => 'nirs_files/fileXXXX');
my $output_plot_filepath_string = $tempfile_string."_output_plot.png";
my $output_plot_filepath = $c->config->{basepath}."/".$output_plot_filepath_string;
my $json = JSON->new->utf8->canonical();
my $filter_data_input_json = $json->encode(\@filter_input);
open(my $F, '>', $filter_json_filepath);
print STDERR Dumper $filter_json_filepath;
print $F $filter_data_input_json;
close($F);
my $cmd_s = "Rscript ".$c->config->{basepath} . "/R/Nirs/nirs_upload_filter_aggregate.R '$filter_json_filepath' '$output_csv_filepath' '$output_raw_csv_filepath' '$output_plot_filepath' '$output_outliers_filepath' ";
print STDERR $cmd_s;
my $cmd_status = system($cmd_s);
my %parsed_data_agg;
# Just use one of the spectra:
#while (my ($stock_name, $o) = each %parsed_data) {
# my $spectras = $o->{nirs}->{spectra};
# $parsed_data_agg{$stock_name}->{nirs}->{device_type} = $o->{nirs}->{device_type};
# $parsed_data_agg{$stock_name}->{nirs}->{spectra} = $spectras->[0];
#}
my $agg_file_name = basename($output_csv_filepath);
my $uploader_agg = CXGN::UploadFile->new({
tempfile => $output_csv_filepath,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $agg_file_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_agg_filename_with_path = $uploader->archive();
my $md5_agg = $uploader_agg->get_md5($archived_agg_filename_with_path);
if (!$archived_agg_filename_with_path) {
push @error_status, "Could not save file $agg_file_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $agg_file_name saved in archive.";
}
unlink $output_csv_filepath;
# Using aggregated spectra:
my $parsed_file_agg = $parser->parse($validate_type, $archived_agg_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $nd_protocol_filename);
if (!$parsed_file_agg) {
push @error_status, "Error parsing aggregated file.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file_agg->{'error'}) {
push @error_status, $parsed_file_agg->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my @plots_agg;
my @wavelengths_agg;
if (scalar(@error_status) == 0) {
if ($parsed_file_agg && !$parsed_file_agg->{'error'}) {
%parsed_data_agg = %{$parsed_file_agg->{'data'}};
@plots_agg = @{$parsed_file_agg->{'units'}};
@wavelengths_agg = @{$parsed_file_agg->{'variables'}};
push @success_status, "Aggregated file data successfully parsed.";
}
}
if (!$protocol_id) {
my %nirs_protocol_prop = (
device_type => $protocol_device_type,
header_column_names => \@wavelengths_agg,
header_column_details => {}
);
my $protocol = $schema->resultset('NaturalDiversity::NdProtocol')->create({
name => $protocol_name,
type_id => $high_dim_nirs_protocol_cvterm_id,
nd_protocolprops => [{type_id => $high_dim_nirs_protocol_prop_cvterm_id, value => encode_json \%nirs_protocol_prop}]
});
$protocol_id = $protocol->nd_protocol_id();
my $desc_q = "UPDATE nd_protocol SET description=? WHERE nd_protocol_id=?;";
my $dbh = $schema->storage->dbh()->prepare($desc_q);
$dbh->execute($protocol_desc, $protocol_id);
}
my %parsed_data_agg_coalesced;
while (my ($stock_name, $o) = each %parsed_data_agg) {
my $device_id = $o->{nirs}->{device_id};
my $comments = $o->{nirs}->{comments};
my $spectras = $o->{nirs}->{spectra};
$parsed_data_agg_coalesced{$stock_name}->{nirs}->{protocol_id} = $protocol_id;
$parsed_data_agg_coalesced{$stock_name}->{nirs}->{device_type} = $protocol_device_type;
$parsed_data_agg_coalesced{$stock_name}->{nirs}->{device_id} = $device_id;
$parsed_data_agg_coalesced{$stock_name}->{nirs}->{comments} = $comments;
$parsed_data_agg_coalesced{$stock_name}->{nirs}->{spectra} = $spectras->[0];
}
## Set metadata
my %phenotype_metadata;
$phenotype_metadata{'archived_file'} = $archived_agg_filename_with_path;
$phenotype_metadata{'archived_file_type'} = $metadata_file_type;
$phenotype_metadata{'operator'} = $user_name;
$phenotype_metadata{'date'} = $timestamp;
my $pheno_dir = $c->tempfiles_subdir('/delete_nd_experiment_ids');
my $temp_file_nd_experiment_id = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'delete_nd_experiment_ids/fileXXXX');
my $store_phenotypes = CXGN::Phenotypes::StorePhenotypes->new({
basepath=>$c->config->{basepath},
dbhost=>$c->config->{dbhost},
dbname=>$c->config->{dbname},
dbuser=>$c->config->{dbuser},
dbpass=>$c->config->{dbpass},
temp_file_nd_experiment_id=>$temp_file_nd_experiment_id,
bcs_schema=>$schema,
metadata_schema=>$metadata_schema,
phenome_schema=>$phenome_schema,
user_id=>$user_id,
stock_list=>\@plots_agg,
trait_list=>[],
values_hash=>\%parsed_data_agg_coalesced,
has_timestamps=>0,
metadata_hash=>\%phenotype_metadata
});
my $warning_status;
my ($verified_warning, $verified_error) = $store_phenotypes->verify();
if ($verified_error) {
push @error_status, $verified_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($verified_warning) {
push @warning_status, $verified_warning;
}
push @success_status, "Aggregated file data verified. Plot names and trait names are valid.";
my ($stored_phenotype_error, $stored_phenotype_success) = $store_phenotypes->store();
if ($stored_phenotype_error) {
push @error_status, $stored_phenotype_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status};
$c->detach();
}
if ($stored_phenotype_success) {
push @success_status, $stored_phenotype_success;
}
push @success_status, "Metadata saved for archived file.";
my $bs = CXGN::BreederSearch->new( { dbh=>$c->dbc->dbh, dbname=>$c->config->{dbname}, } );
my $refresh = $bs->refresh_matviews($c->config->{dbhost}, $c->config->{dbname}, $c->config->{dbuser}, $c->config->{dbpass}, 'fullview', 'concurrent', $c->config->{basepath});
$c->stash->{rest} = {success => \@success_status, error => \@error_status, figure => $output_plot_filepath_string, nd_protocol_id => $protocol_id};
}
sub high_dimensional_phenotypes_transcriptomics_upload_verify : Path('/ajax/highdimensionalphenotypes/transcriptomics_upload_verify') : ActionClass('REST') { }
sub high_dimensional_phenotypes_transcriptomics_upload_verify_POST : Args(0) {
my $self = shift;
my $c = shift;
print STDERR Dumper $c->req->params();
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my @success_status;
my @error_status;
my @warning_status;
my $parser = CXGN::Phenotypes::ParseUpload->new();
my $validate_type = "highdimensionalphenotypes spreadsheet transcriptomics";
my $metadata_file_type = "transcriptomics spreadsheet";
my $subdirectory = "spreadsheet_phenotype_upload";
my $timestamp_included;
my $protocol_id = $c->req->param('upload_transcriptomics_spreadsheet_protocol_id');
my $protocol_name = $c->req->param('upload_transcriptomics_spreadsheet_protocol_name');
my $protocol_desc = $c->req->param('upload_transcriptomics_spreadsheet_protocol_desc');
my $protocol_unit = $c->req->param('upload_transcriptomics_spreadsheet_protocol_unit');
my $protocol_genome_version = $c->req->param('upload_transcriptomics_spreadsheet_protocol_genome');
my $protocol_genome_annotation_version = $c->req->param('upload_transcriptomics_spreadsheet_protocol_annotation');
if ($protocol_id && $protocol_name) {
$c->stash->{rest} = {error => ["Please give a protocol name or select a previous protocol, not both!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_name || !$protocol_desc || !$protocol_unit || !$protocol_genome_version || !$protocol_genome_annotation_version)) {
$c->stash->{rest} = {error => ["Please give a protocol name, description, unit, genome and annotation version, or select a previous protocol!"]};
$c->detach();
}
my $high_dim_transcriptomics_protocol_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_transcriptomics_protocol', 'protocol_type')->cvterm_id();
my $high_dim_transcriptomics_protocol_prop_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_protocol_properties', 'protocol_property')->cvterm_id();
my $data_level = $c->req->param('upload_transcriptomics_spreadsheet_data_level') || 'tissue_samples';
my $upload = $c->req->upload('upload_transcriptomics_spreadsheet_file_input');
my $transcript_metadata_upload = $c->req->upload('upload_transcriptomics_transcript_metadata_spreadsheet_file_input');
my $upload_original_name = $upload->filename();
my $upload_tempfile = $upload->tempname;
my $time = DateTime->now();
my $timestamp = $time->ymd()."_".$time->hms();
my $uploader = CXGN::UploadFile->new({
tempfile => $upload_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_with_path = $uploader->archive();
my $md5 = $uploader->get_md5($archived_filename_with_path);
if (!$archived_filename_with_path) {
push @error_status, "Could not save file $upload_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_original_name saved in archive.";
}
unlink $upload_tempfile;
my $upload_transcripts_original_name = $transcript_metadata_upload->filename();
my $upload_transcripts_tempfile = $transcript_metadata_upload->tempname;
my $uploader_transcripts = CXGN::UploadFile->new({
tempfile => $upload_transcripts_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_transcripts_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_transcripts_with_path = $uploader_transcripts->archive();
my $md5_transcripts = $uploader_transcripts->get_md5($archived_filename_transcripts_with_path);
if (!$archived_filename_transcripts_with_path) {
push @error_status, "Could not save file $upload_transcripts_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_transcripts_original_name saved in archive.";
}
unlink $upload_transcripts_tempfile;
my $archived_image_zipfile_with_path;
my $validate_file = $parser->validate($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $protocol_id, $archived_filename_transcripts_with_path);
if (!$validate_file) {
push @error_status, "Archived file not valid: $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($validate_file == 1){
push @success_status, "File valid: $upload_original_name.";
} else {
if ($validate_file->{'error'}) {
push @error_status, $validate_file->{'error'};
}
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
## Set metadata
my %phenotype_metadata;
$phenotype_metadata{'archived_file'} = $archived_filename_with_path;
$phenotype_metadata{'archived_file_type'} = $metadata_file_type;
$phenotype_metadata{'operator'} = $user_name;
$phenotype_metadata{'date'} = $timestamp;
my $parsed_file = $parser->parse($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $archived_filename_transcripts_with_path);
if (!$parsed_file) {
push @error_status, "Error parsing file $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file->{'error'}) {
push @error_status, $parsed_file->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my %parsed_data;
my @plots;
my @transcripts;
my %transcripts_details;
if (scalar(@error_status) == 0) {
if ($parsed_file && !$parsed_file->{'error'}) {
%parsed_data = %{$parsed_file->{'data'}};
@plots = @{$parsed_file->{'units'}};
@transcripts = @{$parsed_file->{'variables'}};
%transcripts_details = %{$parsed_file->{'variables_desc'}};
push @success_status, "File data successfully parsed.";
}
}
my $dir = $c->tempfiles_subdir('/delete_nd_experiment_ids');
my $temp_file_nd_experiment_id = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'delete_nd_experiment_ids/fileXXXX');
my $store_phenotypes = CXGN::Phenotypes::StorePhenotypes->new({
basepath=>$c->config->{basepath},
dbhost=>$c->config->{dbhost},
dbname=>$c->config->{dbname},
dbuser=>$c->config->{dbuser},
dbpass=>$c->config->{dbpass},
temp_file_nd_experiment_id=>$temp_file_nd_experiment_id,
bcs_schema=>$schema,
metadata_schema=>$metadata_schema,
phenome_schema=>$phenome_schema,
user_id=>$user_id,
stock_list=>\@plots,
trait_list=>[],
values_hash=>\%parsed_data,
has_timestamps=>0,
metadata_hash=>\%phenotype_metadata
});
my $warning_status;
my ($verified_warning, $verified_error) = $store_phenotypes->verify();
if ($verified_error) {
push @error_status, $verified_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($verified_warning) {
push @warning_status, $verified_warning;
}
push @success_status, "File data verified. Plot names and trait names are valid.";
# print STDERR Dumper \@success_status;
# print STDERR Dumper \@warning_status;
# print STDERR Dumper \@error_status;
# print STDERR Dumper $output_plot_filepath_string;
$c->stash->{rest} = {success => \@success_status, warning => \@warning_status, error => \@error_status};
}
sub high_dimensional_phenotypes_transcriptomics_upload_store : Path('/ajax/highdimensionalphenotypes/transcriptomics_upload_store') : ActionClass('REST') { }
sub high_dimensional_phenotypes_transcriptomics_upload_store_POST : Args(0) {
my $self = shift;
my $c = shift;
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my @success_status;
my @error_status;
my @warning_status;
my $parser = CXGN::Phenotypes::ParseUpload->new();
my $validate_type = "highdimensionalphenotypes spreadsheet transcriptomics";
my $metadata_file_type = "transcriptomics spreadsheet";
my $subdirectory = "spreadsheet_phenotype_upload";
my $timestamp_included;
my $protocol_id = $c->req->param('upload_transcriptomics_spreadsheet_protocol_id');
my $protocol_name = $c->req->param('upload_transcriptomics_spreadsheet_protocol_name');
my $protocol_desc = $c->req->param('upload_transcriptomics_spreadsheet_protocol_desc');
my $protocol_unit = $c->req->param('upload_transcriptomics_spreadsheet_protocol_unit');
my $protocol_genome_version = $c->req->param('upload_transcriptomics_spreadsheet_protocol_genome');
my $protocol_genome_annotation_version = $c->req->param('upload_transcriptomics_spreadsheet_protocol_annotation');
if ($protocol_id && $protocol_name) {
$c->stash->{rest} = {error => ["Please give a protocol name or select a previous protocol, not both!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_name || !$protocol_desc || !$protocol_unit || !$protocol_genome_version || !$protocol_genome_annotation_version)) {
$c->stash->{rest} = {error => ["Please give a protocol name, description, unit, genome and annotation version, or select a previous protocol!"]};
$c->detach();
}
my $high_dim_transcriptomics_protocol_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_transcriptomics_protocol', 'protocol_type')->cvterm_id();
my $high_dim_transcriptomics_protocol_prop_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_protocol_properties', 'protocol_property')->cvterm_id();
my $data_level = $c->req->param('upload_transcriptomics_spreadsheet_data_level') || 'tissue_samples';
my $upload = $c->req->upload('upload_transcriptomics_spreadsheet_file_input');
my $transcript_metadata_upload = $c->req->upload('upload_transcriptomics_transcript_metadata_spreadsheet_file_input');
my $upload_original_name = $upload->filename();
my $upload_tempfile = $upload->tempname;
my $time = DateTime->now();
my $timestamp = $time->ymd()."_".$time->hms();
my $uploader = CXGN::UploadFile->new({
tempfile => $upload_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_with_path = $uploader->archive();
my $md5 = $uploader->get_md5($archived_filename_with_path);
if (!$archived_filename_with_path) {
push @error_status, "Could not save file $upload_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_original_name saved in archive.";
}
unlink $upload_tempfile;
my $upload_transcripts_original_name = $transcript_metadata_upload->filename();
my $upload_transcripts_tempfile = $transcript_metadata_upload->tempname;
my $uploader_transcripts = CXGN::UploadFile->new({
tempfile => $upload_transcripts_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_transcripts_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_transcripts_with_path = $uploader_transcripts->archive();
my $md5_transcripts = $uploader_transcripts->get_md5($archived_filename_transcripts_with_path);
if (!$archived_filename_transcripts_with_path) {
push @error_status, "Could not save file $upload_transcripts_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_transcripts_original_name saved in archive.";
}
unlink $upload_transcripts_tempfile;
my $archived_image_zipfile_with_path;
my $validate_file = $parser->validate($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $protocol_id, $archived_filename_transcripts_with_path);
if (!$validate_file) {
push @error_status, "Archived file not valid: $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($validate_file == 1){
push @success_status, "File valid: $upload_original_name.";
} else {
if ($validate_file->{'error'}) {
push @error_status, $validate_file->{'error'};
}
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my $parsed_file = $parser->parse($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $archived_filename_transcripts_with_path);
if (!$parsed_file) {
push @error_status, "Error parsing file $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file->{'error'}) {
push @error_status, $parsed_file->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my %parsed_data;
my @plots;
my @transcripts;
my %transcripts_details;
if (scalar(@error_status) == 0) {
if ($parsed_file && !$parsed_file->{'error'}) {
%parsed_data = %{$parsed_file->{'data'}};
@plots = @{$parsed_file->{'units'}};
@transcripts = @{$parsed_file->{'variables'}};
%transcripts_details = %{$parsed_file->{'variables_desc'}};
push @success_status, "File data successfully parsed.";
}
}
if (!$protocol_id) {
my %transcriptomics_protocol_prop = (
expression_unit => $protocol_unit,
genome_version => $protocol_genome_version,
annotation_version => $protocol_genome_annotation_version,
header_column_names => \@transcripts,
header_column_details => \%transcripts_details
);
my $protocol = $schema->resultset('NaturalDiversity::NdProtocol')->create({
name => $protocol_name,
type_id => $high_dim_transcriptomics_protocol_cvterm_id,
nd_protocolprops => [{type_id => $high_dim_transcriptomics_protocol_prop_cvterm_id, value => encode_json \%transcriptomics_protocol_prop}]
});
$protocol_id = $protocol->nd_protocol_id();
my $desc_q = "UPDATE nd_protocol SET description=? WHERE nd_protocol_id=?;";
my $dbh = $schema->storage->dbh()->prepare($desc_q);
$dbh->execute($protocol_desc, $protocol_id);
}
my %parsed_data_agg_coalesced;
while (my ($stock_name, $o) = each %parsed_data) {
my $device_id = $o->{transcriptomics}->{device_id};
my $comments = $o->{transcriptomics}->{comments};
my $spectras = $o->{transcriptomics}->{transcripts};
$parsed_data_agg_coalesced{$stock_name}->{transcriptomics} = $spectras->[0];
$parsed_data_agg_coalesced{$stock_name}->{transcriptomics}->{protocol_id} = $protocol_id;
$parsed_data_agg_coalesced{$stock_name}->{transcriptomics}->{device_id} = $device_id;
$parsed_data_agg_coalesced{$stock_name}->{transcriptomics}->{comments} = $comments;
}
## Set metadata
my %phenotype_metadata;
$phenotype_metadata{'archived_file'} = $archived_filename_with_path;
$phenotype_metadata{'archived_file_type'} = $metadata_file_type;
$phenotype_metadata{'operator'} = $user_name;
$phenotype_metadata{'date'} = $timestamp;
my $pheno_dir = $c->tempfiles_subdir('/delete_nd_experiment_ids');
my $temp_file_nd_experiment_id = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'delete_nd_experiment_ids/fileXXXX');
my $store_phenotypes = CXGN::Phenotypes::StorePhenotypes->new({
basepath=>$c->config->{basepath},
dbhost=>$c->config->{dbhost},
dbname=>$c->config->{dbname},
dbuser=>$c->config->{dbuser},
dbpass=>$c->config->{dbpass},
temp_file_nd_experiment_id=>$temp_file_nd_experiment_id,
bcs_schema=>$schema,
metadata_schema=>$metadata_schema,
phenome_schema=>$phenome_schema,
user_id=>$user_id,
stock_list=>\@plots,
trait_list=>[],
values_hash=>\%parsed_data_agg_coalesced,
has_timestamps=>0,
metadata_hash=>\%phenotype_metadata
});
my $warning_status;
my ($verified_warning, $verified_error) = $store_phenotypes->verify();
if ($verified_error) {
push @error_status, $verified_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($verified_warning) {
push @warning_status, $verified_warning;
}
push @success_status, "File data verified. Plot names and trait names are valid.";
my ($stored_phenotype_error, $stored_phenotype_success) = $store_phenotypes->store();
if ($stored_phenotype_error) {
push @error_status, $stored_phenotype_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status};
$c->detach();
}
if ($stored_phenotype_success) {
push @success_status, $stored_phenotype_success;
}
push @success_status, "Metadata saved for archived file.";
my $bs = CXGN::BreederSearch->new({ dbh=>$c->dbc->dbh, dbname=>$c->config->{dbname} });
my $refresh = $bs->refresh_matviews($c->config->{dbhost}, $c->config->{dbname}, $c->config->{dbuser}, $c->config->{dbpass}, 'fullview', 'concurrent', $c->config->{basepath});
$c->stash->{rest} = {success => \@success_status, error => \@error_status, nd_protocol_id => $protocol_id};
}
sub high_dimensional_phenotypes_metabolomics_upload_verify : Path('/ajax/highdimensionalphenotypes/metabolomics_upload_verify') : ActionClass('REST') { }
sub high_dimensional_phenotypes_metabolomics_upload_verify_POST : Args(0) {
my $self = shift;
my $c = shift;
print STDERR Dumper $c->req->params();
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my @success_status;
my @error_status;
my @warning_status;
my $parser = CXGN::Phenotypes::ParseUpload->new();
my $validate_type = "highdimensionalphenotypes spreadsheet metabolomics";
my $metadata_file_type = "metabolomics spreadsheet";
my $subdirectory = "spreadsheet_phenotype_upload";
my $timestamp_included;
my $protocol_id = $c->req->param('upload_metabolomics_spreadsheet_protocol_id');
my $protocol_name = $c->req->param('upload_metabolomics_spreadsheet_protocol_name');
my $protocol_desc = $c->req->param('upload_metabolomics_spreadsheet_protocol_desc');
my $protocol_equipment_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_equipment_type');
my $protocol_equipment_desc = $c->req->param('upload_metabolomics_spreadsheet_protocol_equipment_description');
my $protocol_data_process_desc = $c->req->param('upload_metabolomics_spreadsheet_protocol_data_process_description');
my $protocol_phenotype_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_phenotype_type');
my $protocol_phenotype_units = $c->req->param('upload_metabolomics_spreadsheet_protocol_phenotype_units');
my $protocol_chromatography_system_brand = $c->req->param('upload_metabolomics_spreadsheet_protocol_chromatography_system_brand');
my $protocol_chromatography_column_brand = $c->req->param('upload_metabolomics_spreadsheet_protocol_chromatography_column_brand');
my $protocol_ms_brand = $c->req->param('upload_metabolomics_spreadsheet_protocol_ms_brand');
my $protocol_ms_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_ms_type');
my $protocol_ms_instrument_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_ms_instrument_type');
my $protocol_ms_ion_mode = $c->req->param('upload_metabolomics_spreadsheet_protocol_ion_mode');
if ($protocol_id && $protocol_name) {
$c->stash->{rest} = {error => ["Please give a protocol name or select a previous protocol, not both!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_name || !$protocol_desc)) {
$c->stash->{rest} = {error => ["Please give a protocol name and description, or select a previous protocol!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_equipment_type || !$protocol_equipment_desc || !$protocol_data_process_desc || !$protocol_phenotype_type || !$protocol_phenotype_units)) {
$c->stash->{rest} = {error => ["Please give all protocol equipment descriptions, or select a previous protocol!"]};
$c->detach();
}
if (!$protocol_id && $protocol_equipment_type eq 'MS' && (!$protocol_chromatography_system_brand || !$protocol_chromatography_column_brand || !$protocol_ms_brand || !$protocol_ms_type || !$protocol_ms_instrument_type || !$protocol_ms_ion_mode)) {
$c->stash->{rest} = {error => ["If defining a MS protocol please give all information fields!"]};
$c->detach();
}
my $high_dim_metabolomics_protocol_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_metabolomics_protocol', 'protocol_type')->cvterm_id();
my $high_dim_metabolomics_protocol_prop_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_protocol_properties', 'protocol_property')->cvterm_id();
my $data_level = $c->req->param('upload_metabolomics_spreadsheet_data_level') || 'tissue_samples';
my $upload = $c->req->upload('upload_metabolomics_spreadsheet_file_input');
my $metabolite_details_upload = $c->req->upload('upload_metabolomics_metabolite_details_spreadsheet_file_input');
my $upload_original_name = $upload->filename();
my $upload_tempfile = $upload->tempname;
my $time = DateTime->now();
my $timestamp = $time->ymd()."_".$time->hms();
my $uploader = CXGN::UploadFile->new({
tempfile => $upload_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_with_path = $uploader->archive();
my $md5 = $uploader->get_md5($archived_filename_with_path);
if (!$archived_filename_with_path) {
push @error_status, "Could not save file $upload_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_original_name saved in archive.";
}
unlink $upload_tempfile;
my $upload_transcripts_original_name = $metabolite_details_upload->filename();
my $upload_transcripts_tempfile = $metabolite_details_upload->tempname;
my $uploader_transcripts = CXGN::UploadFile->new({
tempfile => $upload_transcripts_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_transcripts_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_transcripts_with_path = $uploader_transcripts->archive();
my $md5_transcripts = $uploader_transcripts->get_md5($archived_filename_transcripts_with_path);
if (!$archived_filename_transcripts_with_path) {
push @error_status, "Could not save file $upload_transcripts_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_transcripts_original_name saved in archive.";
}
unlink $upload_transcripts_tempfile;
my $archived_image_zipfile_with_path;
my $validate_file = $parser->validate($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $protocol_id, $archived_filename_transcripts_with_path);
if (!$validate_file) {
push @error_status, "Archived file not valid: $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($validate_file == 1){
push @success_status, "File valid: $upload_original_name.";
} else {
if ($validate_file->{'error'}) {
push @error_status, $validate_file->{'error'};
}
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
## Set metadata
my %phenotype_metadata;
$phenotype_metadata{'archived_file'} = $archived_filename_with_path;
$phenotype_metadata{'archived_file_type'} = $metadata_file_type;
$phenotype_metadata{'operator'} = $user_name;
$phenotype_metadata{'date'} = $timestamp;
my $parsed_file = $parser->parse($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $archived_filename_transcripts_with_path);
if (!$parsed_file) {
push @error_status, "Error parsing file $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file->{'error'}) {
push @error_status, $parsed_file->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my %parsed_data;
my @plots;
my @metabolites;
if (scalar(@error_status) == 0) {
if ($parsed_file && !$parsed_file->{'error'}) {
%parsed_data = %{$parsed_file->{'data'}};
@plots = @{$parsed_file->{'units'}};
@metabolites = @{$parsed_file->{'variables'}};
push @success_status, "File data successfully parsed.";
}
}
my $dir = $c->tempfiles_subdir('/delete_nd_experiment_ids');
my $temp_file_nd_experiment_id = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'delete_nd_experiment_ids/fileXXXX');
my $store_phenotypes = CXGN::Phenotypes::StorePhenotypes->new({
basepath=>$c->config->{basepath},
dbhost=>$c->config->{dbhost},
dbname=>$c->config->{dbname},
dbuser=>$c->config->{dbuser},
dbpass=>$c->config->{dbpass},
temp_file_nd_experiment_id=>$temp_file_nd_experiment_id,
bcs_schema=>$schema,
metadata_schema=>$metadata_schema,
phenome_schema=>$phenome_schema,
user_id=>$user_id,
stock_list=>\@plots,
trait_list=>[],
values_hash=>\%parsed_data,
has_timestamps=>0,
metadata_hash=>\%phenotype_metadata
});
my $warning_status;
my ($verified_warning, $verified_error) = $store_phenotypes->verify();
if ($verified_error) {
push @error_status, $verified_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($verified_warning) {
push @warning_status, $verified_warning;
}
push @success_status, "File data verified. Plot names and trait names are valid.";
# print STDERR Dumper \@success_status;
# print STDERR Dumper \@warning_status;
# print STDERR Dumper \@error_status;
# print STDERR Dumper $output_plot_filepath_string;
$c->stash->{rest} = {success => \@success_status, warning => \@warning_status, error => \@error_status};
}
sub high_dimensional_phenotypes_metabolomics_upload_store : Path('/ajax/highdimensionalphenotypes/metabolomics_upload_store') : ActionClass('REST') { }
sub high_dimensional_phenotypes_metabolomics_upload_store_POST : Args(0) {
my $self = shift;
my $c = shift;
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my @success_status;
my @error_status;
my @warning_status;
my $parser = CXGN::Phenotypes::ParseUpload->new();
my $validate_type = "highdimensionalphenotypes spreadsheet metabolomics";
my $metadata_file_type = "metabolomics spreadsheet";
my $subdirectory = "spreadsheet_phenotype_upload";
my $timestamp_included;
my $protocol_id = $c->req->param('upload_metabolomics_spreadsheet_protocol_id');
my $protocol_name = $c->req->param('upload_metabolomics_spreadsheet_protocol_name');
my $protocol_desc = $c->req->param('upload_metabolomics_spreadsheet_protocol_desc');
my $protocol_equipment_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_equipment_type');
my $protocol_equipment_desc = $c->req->param('upload_metabolomics_spreadsheet_protocol_equipment_description');
my $protocol_data_process_desc = $c->req->param('upload_metabolomics_spreadsheet_protocol_data_process_description');
my $protocol_phenotype_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_phenotype_type');
my $protocol_phenotype_units = $c->req->param('upload_metabolomics_spreadsheet_protocol_phenotype_units');
my $protocol_chromatography_system_brand = $c->req->param('upload_metabolomics_spreadsheet_protocol_chromatography_system_brand');
my $protocol_chromatography_column_brand = $c->req->param('upload_metabolomics_spreadsheet_protocol_chromatography_column_brand');
my $protocol_ms_brand = $c->req->param('upload_metabolomics_spreadsheet_protocol_ms_brand');
my $protocol_ms_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_ms_type');
my $protocol_ms_instrument_type = $c->req->param('upload_metabolomics_spreadsheet_protocol_ms_instrument_type');
my $protocol_ms_ion_mode = $c->req->param('upload_metabolomics_spreadsheet_protocol_ion_mode');
if ($protocol_id && $protocol_name) {
$c->stash->{rest} = {error => ["Please give a protocol name or select a previous protocol, not both!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_name || !$protocol_desc)) {
$c->stash->{rest} = {error => ["Please give a protocol name and description, or select a previous protocol!"]};
$c->detach();
}
if (!$protocol_id && (!$protocol_equipment_type || !$protocol_equipment_desc || !$protocol_data_process_desc || !$protocol_phenotype_type || !$protocol_phenotype_units)) {
$c->stash->{rest} = {error => ["Please give all protocol equipment descriptions, or select a previous protocol!"]};
$c->detach();
}
if (!$protocol_id && $protocol_equipment_type eq 'MS' && (!$protocol_chromatography_system_brand || !$protocol_chromatography_column_brand || !$protocol_ms_brand || !$protocol_ms_type || !$protocol_ms_instrument_type || !$protocol_ms_ion_mode)) {
$c->stash->{rest} = {error => ["If defining a MS protocol please give all information fields!"]};
$c->detach();
}
my $high_dim_metabolomics_protocol_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_metabolomics_protocol', 'protocol_type')->cvterm_id();
my $high_dim_metabolomics_protocol_prop_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'high_dimensional_phenotype_protocol_properties', 'protocol_property')->cvterm_id();
my $data_level = $c->req->param('upload_metabolomics_spreadsheet_data_level') || 'tissue_samples';
my $upload = $c->req->upload('upload_metabolomics_spreadsheet_file_input');
my $metabolite_details_upload = $c->req->upload('upload_metabolomics_metabolite_details_spreadsheet_file_input');
my $upload_original_name = $upload->filename();
my $upload_tempfile = $upload->tempname;
my $time = DateTime->now();
my $timestamp = $time->ymd()."_".$time->hms();
my $uploader = CXGN::UploadFile->new({
tempfile => $upload_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_with_path = $uploader->archive();
my $md5 = $uploader->get_md5($archived_filename_with_path);
if (!$archived_filename_with_path) {
push @error_status, "Could not save file $upload_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_original_name saved in archive.";
}
unlink $upload_tempfile;
my $upload_transcripts_original_name = $metabolite_details_upload->filename();
my $upload_transcripts_tempfile = $metabolite_details_upload->tempname;
my $uploader_transcripts = CXGN::UploadFile->new({
tempfile => $upload_transcripts_tempfile,
subdirectory => $subdirectory,
archive_path => $c->config->{archive_path},
archive_filename => $upload_transcripts_original_name,
timestamp => $timestamp,
user_id => $user_id,
user_role => $user_type
});
my $archived_filename_transcripts_with_path = $uploader_transcripts->archive();
my $md5_transcripts = $uploader_transcripts->get_md5($archived_filename_transcripts_with_path);
if (!$archived_filename_transcripts_with_path) {
push @error_status, "Could not save file $upload_transcripts_original_name in archive.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
} else {
push @success_status, "File $upload_transcripts_original_name saved in archive.";
}
unlink $upload_transcripts_tempfile;
my $archived_image_zipfile_with_path;
my $validate_file = $parser->validate($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $protocol_id, $archived_filename_transcripts_with_path);
if (!$validate_file) {
push @error_status, "Archived file not valid: $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($validate_file == 1){
push @success_status, "File valid: $upload_original_name.";
} else {
if ($validate_file->{'error'}) {
push @error_status, $validate_file->{'error'};
}
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my $parsed_file = $parser->parse($validate_type, $archived_filename_with_path, $timestamp_included, $data_level, $schema, $archived_image_zipfile_with_path, $user_id, $c, $protocol_id, $archived_filename_transcripts_with_path);
if (!$parsed_file) {
push @error_status, "Error parsing file $upload_original_name.";
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($parsed_file->{'error'}) {
push @error_status, $parsed_file->{'error'};
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
my %parsed_data;
my @plots;
my @metabolites;
my %metabolites_details;
if (scalar(@error_status) == 0) {
if ($parsed_file && !$parsed_file->{'error'}) {
%parsed_data = %{$parsed_file->{'data'}};
@plots = @{$parsed_file->{'units'}};
@metabolites = @{$parsed_file->{'variables'}};
%metabolites_details = %{$parsed_file->{'variables_desc'}};
push @success_status, "File data successfully parsed.";
}
}
if (!$protocol_id) {
my %metabolomics_protocol_prop = (
header_column_names => \@metabolites,
header_column_details => %metabolites_details,
equipment_type => $protocol_equipment_type,
equipment_description => $protocol_equipment_desc,
data_process_description => $protocol_data_process_desc,
phenotype_type => $protocol_phenotype_type,
phenotype_units => $protocol_phenotype_units
);
if ($protocol_equipment_type eq 'MS') {
$metabolomics_protocol_prop{chromatography_system_brand} = $protocol_chromatography_system_brand;
$metabolomics_protocol_prop{chromatography_column_brand} = $protocol_chromatography_column_brand;
$metabolomics_protocol_prop{ms_brand} = $protocol_ms_brand;
$metabolomics_protocol_prop{ms_type} = $protocol_ms_type;
$metabolomics_protocol_prop{ms_instrument_type} = $protocol_ms_instrument_type;
$metabolomics_protocol_prop{ms_ion_mode} = $protocol_ms_ion_mode;
}
my $protocol = $schema->resultset('NaturalDiversity::NdProtocol')->create({
name => $protocol_name,
type_id => $high_dim_metabolomics_protocol_cvterm_id,
nd_protocolprops => [{type_id => $high_dim_metabolomics_protocol_prop_cvterm_id, value => encode_json \%metabolomics_protocol_prop}]
});
$protocol_id = $protocol->nd_protocol_id();
my $desc_q = "UPDATE nd_protocol SET description=? WHERE nd_protocol_id=?;";
my $dbh = $schema->storage->dbh()->prepare($desc_q);
$dbh->execute($protocol_desc, $protocol_id);
}
my %parsed_data_agg;
while (my ($stock_name, $o) = each %parsed_data) {
my $device_id = $o->{metabolomics}->{device_id};
my $comments = $o->{metabolomics}->{comments};
my $spectras = $o->{metabolomics}->{metabolites};
$parsed_data_agg{$stock_name}->{metabolomics} = $spectras->[0];
$parsed_data_agg{$stock_name}->{metabolomics}->{protocol_id} = $protocol_id;
$parsed_data_agg{$stock_name}->{metabolomics}->{device_id} = $device_id;
$parsed_data_agg{$stock_name}->{metabolomics}->{comments} = $comments;
}
## Set metadata
my %phenotype_metadata;
$phenotype_metadata{'archived_file'} = $archived_filename_with_path;
$phenotype_metadata{'archived_file_type'} = $metadata_file_type;
$phenotype_metadata{'operator'} = $user_name;
$phenotype_metadata{'date'} = $timestamp;
my $pheno_dir = $c->tempfiles_subdir('/delete_nd_experiment_ids');
my $temp_file_nd_experiment_id = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'delete_nd_experiment_ids/fileXXXX');
my $store_phenotypes = CXGN::Phenotypes::StorePhenotypes->new({
basepath=>$c->config->{basepath},
dbhost=>$c->config->{dbhost},
dbname=>$c->config->{dbname},
dbuser=>$c->config->{dbuser},
dbpass=>$c->config->{dbpass},
temp_file_nd_experiment_id=>$temp_file_nd_experiment_id,
bcs_schema=>$schema,
metadata_schema=>$metadata_schema,
phenome_schema=>$phenome_schema,
user_id=>$user_id,
stock_list=>\@plots,
trait_list=>[],
values_hash=>\%parsed_data_agg,
has_timestamps=>0,
metadata_hash=>\%phenotype_metadata
});
my $warning_status;
my ($verified_warning, $verified_error) = $store_phenotypes->verify();
if ($verified_error) {
push @error_status, $verified_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status };
$c->detach();
}
if ($verified_warning) {
push @warning_status, $verified_warning;
}
push @success_status, "File data verified. Plot names and trait names are valid.";
my ($stored_phenotype_error, $stored_phenotype_success) = $store_phenotypes->store();
if ($stored_phenotype_error) {
push @error_status, $stored_phenotype_error;
$c->stash->{rest} = {success => \@success_status, error => \@error_status};
$c->detach();
}
if ($stored_phenotype_success) {
push @success_status, $stored_phenotype_success;
}
push @success_status, "Metadata saved for archived file.";
my $bs = CXGN::BreederSearch->new({ dbh=>$c->dbc->dbh, dbname=>$c->config->{dbname} });
my $refresh = $bs->refresh_matviews($c->config->{dbhost}, $c->config->{dbname}, $c->config->{dbuser}, $c->config->{dbpass}, 'fullview', 'concurrent', $c->config->{basepath});
$c->stash->{rest} = {success => \@success_status, error => \@error_status, nd_protocol_id => $protocol_id};
}
sub high_dimensional_phenotypes_download_file : Path('/ajax/highdimensionalphenotypes/download_file') : ActionClass('REST') { }
sub high_dimensional_phenotypes_download_file_POST : Args(0) {
my $self = shift;
my $c = shift;
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my $people_schema = $c->dbic_schema("CXGN::People::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my $error;
my $dataset_id = $c->req->param('dataset_id');
my $nd_protocol_id = $c->req->param('nd_protocol_id');
my $high_dimensional_phenotype_type = $c->req->param('high_dimensional_phenotype_type');
my $high_dimensional_download_type = $c->req->param('download_file_type');
my $query_associated_stocks = $c->req->param('query_associated_stocks') eq 'yes' ? 1 : 0;
my $ds = CXGN::Dataset->new({
people_schema => $people_schema,
schema => $schema,
sp_dataset_id => $dataset_id,
});
my $high_dimensional_phenotype_identifier_list = [];
my ($data_matrix, $identifier_metadata, $identifier_names) = $ds->retrieve_high_dimensional_phenotypes(
$nd_protocol_id,
$high_dimensional_phenotype_type,
$query_associated_stocks,
$high_dimensional_phenotype_identifier_list
);
if ($data_matrix->{error}) {
$c->stash->{rest} = {error => $data_matrix->{error}};
$c->detach();
}
# print STDERR Dumper $data_matrix;
# print STDERR Dumper $identifier_metadata;
# print STDERR Dumper $identifier_names;
if ($data_matrix->{error}) {
$c->stash->{rest} = {error => $data_matrix->{error}};
$c->detach();
}
my $dir = $c->tempfiles_subdir('/high_dimensional_phenotypes_download');
my $download_file_link = $c->tempfile( TEMPLATE => 'high_dimensional_phenotypes_download/downloadXXXX');
$download_file_link .= '.csv';
my $download_file_tempfile = $c->config->{basepath}."/".$download_file_link;
open(my $F, ">", $download_file_tempfile) || die "Can't open file ".$download_file_tempfile;
if ($high_dimensional_phenotype_type eq 'NIRS') {
#Old NIRS data were loaded without the protocol identifer_names saved
if (!$identifier_names || scalar(@$identifier_names) == 0) {
my @stock_ids = keys %$data_matrix;
my @ids = keys %{$data_matrix->{$stock_ids[0]}->{spectra}};
my @ids_stripped;
foreach (@ids) {
my $s = substr $_, 1;
push @ids_stripped, $s;
}
$identifier_names = \@ids_stripped;
}
my @identifier_names_sorted = sort { $a <=> $b } @$identifier_names;
if ($high_dimensional_download_type eq 'data_matrix') {
my @header = ('stock_id', @identifier_names_sorted);
my $header_string = join ',', @header;
print $F $header_string."\n";
while ( my ($stock_id, $o) = each %$data_matrix) {
my $spectra = $o->{spectra};
if ($spectra) {
my @row = ($stock_id);
foreach (@identifier_names_sorted) {
push @row, $spectra->{"X$_"};
}
my $line = join ',', @row;
print $F $line."\n";
}
}
}
elsif ($high_dimensional_download_type eq 'identifier_metadata') {
my $header_string = 'spectra';
print $F $header_string."\n";
foreach (@identifier_names_sorted) {
print $F "X$_\n";
}
}
}
elsif ($high_dimensional_phenotype_type eq 'Transcriptomics') {
my @identifier_names_sorted = sort @$identifier_names;
if ($high_dimensional_download_type eq 'data_matrix') {
my @header = ('stock_id', @identifier_names_sorted);
my $header_string = join ',', @header;
print $F $header_string."\n";
while ( my ($stock_id, $o) = each %$data_matrix) {
my $spectra = $o->{transcriptomics};
if ($spectra) {
my @row = ($stock_id);
foreach (@identifier_names_sorted) {
push @row, $spectra->{$_};
}
my $line = join ',', @row;
print $F $line."\n";
}
}
}
elsif ($high_dimensional_download_type eq 'identifier_metadata') {
my $header_string = 'transcript_name,chromosome,start_position,end_position,gene_description,notes';
print $F $header_string."\n";
foreach (@identifier_names_sorted) {
my $chromosome = $identifier_metadata->{$_}->{chr};
my $start_position = $identifier_metadata->{$_}->{start};
my $end_position = $identifier_metadata->{$_}->{end};
my $gene_description = $identifier_metadata->{$_}->{gene_desc};
my $notes = $identifier_metadata->{$_}->{notes};
print $F "$_,$chromosome,$start_position,$end_position,$gene_description,$notes\n";
}
}
}
elsif ($high_dimensional_phenotype_type eq 'Metabolomics') {
my @identifier_names_sorted = sort @$identifier_names;
if ($high_dimensional_download_type eq 'data_matrix') {
my @header = ('stock_id', @identifier_names_sorted);
my $header_string = join ',', @header;
print $F $header_string."\n";
while ( my ($stock_id, $o) = each %$data_matrix) {
my $spectra = $o->{metabolomics};
if ($spectra) {
my @row = ($stock_id);
foreach (@identifier_names_sorted) {
push @row, $spectra->{$_};
}
my $line = join ',', @row;
print $F $line."\n";
}
}
}
elsif ($high_dimensional_download_type eq 'identifier_metadata') {
my $header_string = 'metabolite_name,inchi_key,compound_name';
print $F $header_string."\n";
foreach (@identifier_names_sorted) {
my $inchi = $identifier_metadata->{$_}->{inchi_key};
my $compound = $identifier_metadata->{$_}->{compound_name};
print $F "$_,$inchi,$compound\n";
}
}
}
close($F);
$c->stash->{rest} = {download_file_link => $download_file_link, error => $error};
}
sub high_dimensional_phenotypes_download_relationship_matrix_file : Path('/ajax/highdimensionalphenotypes/download_relationship_matrix_file') : ActionClass('REST') { }
sub high_dimensional_phenotypes_download_relationship_matrix_file_POST : Args(0) {
my $self = shift;
my $c = shift;
my $schema = $c->dbic_schema("Bio::Chado::Schema");
my $metadata_schema = $c->dbic_schema("CXGN::Metadata::Schema");
my $phenome_schema = $c->dbic_schema("CXGN::Phenome::Schema");
my $people_schema = $c->dbic_schema("CXGN::People::Schema");
my ($user_id, $user_name, $user_type) = _check_user_login($c);
my $error;
my $dataset_id = $c->req->param('dataset_id');
my $nd_protocol_id = $c->req->param('nd_protocol_id');
my $high_dimensional_phenotype_type = $c->req->param('high_dimensional_phenotype_type');
my $query_associated_stocks = $c->req->param('query_associated_stocks') eq 'yes' ? 1 : 0;
my $ds = CXGN::Dataset->new({
people_schema => $people_schema,
schema => $schema,
sp_dataset_id => $dataset_id,
});
my $dir = $c->tempfiles_subdir('/high_dimensional_phenotypes_relationship_matrix_download');
my $temp_data_file = $c->config->{basepath}."/".$c->tempfile( TEMPLATE => 'high_dimensional_phenotypes_relationship_matrix_download/downloadXXXX');
my $download_file_link = $c->tempfile( TEMPLATE => 'high_dimensional_phenotypes_relationship_matrix_download/downloadXXXX');
$download_file_link .= '.csv';
my $download_file_tempfile = $c->config->{basepath}."/".$download_file_link;
my ($relationship_matrix_data, $data_matrix, $identifier_metadata, $identifier_names) = $ds->retrieve_high_dimensional_phenotypes_relationship_matrix(
$nd_protocol_id,
$high_dimensional_phenotype_type,
$query_associated_stocks,
$temp_data_file,
$download_file_tempfile
);
# print STDERR Dumper $relationship_matrix_data;
# print STDERR Dumper $data_matrix;
# print STDERR Dumper $identifier_metadata;
# print STDERR Dumper $identifier_names;
$c->stash->{rest} = {download_file_link => $download_file_link, error => $error};
}
sub _check_user_login {
my $c = shift;
my $user_id;
my $user_name;
my $user_role;
my $session_id = $c->req->param("sgn_session_id");
if ($session_id){
my $dbh = $c->dbc->dbh;
my @user_info = CXGN::Login->new($dbh)->query_from_cookie($session_id);
if (!$user_info[0]){
$c->stash->{rest} = {error=>'You must be logged in to do this!'};
$c->detach();
}
$user_id = $user_info[0];
$user_role = $user_info[1];
my $p = CXGN::People::Person->new($dbh, $user_id);
$user_name = $p->get_username;
} else{
if (!$c->user){
$c->stash->{rest} = {error=>'You must be logged in to do this!'};
$c->detach();
}
$user_id = $c->user()->get_object()->get_sp_person_id();
$user_name = $c->user()->get_object()->get_username();
$user_role = $c->user->get_object->get_user_type();
}
if ($user_role ne 'submitter' && $user_role ne 'curator') {
$c->stash->{rest} = {error=>'You do not have permission in the database to do this! Please contact us.'};
$c->detach();
}
return ($user_id, $user_name, $user_role);
}
1;
| solgenomics/sgn | lib/SGN/Controller/AJAX/HighDimensionalPhenotypes.pm | Perl | mit | 77,154 |
%query: hbal_tree(i,o).
/* motivated by P59 of Hett */
hbal_tree(zero,nil).
hbal_tree(s(zero),t(x,nil,nil)).
hbal_tree(s(s(X)),t(x,L,R)) :- distr(s(X),X,DL,DR),
hbal_tree(DL,L), hbal_tree(DR,R).
distr(D1,_,D1,D1).
distr(D1,D2,D1,D2).
distr(D1,D2,D2,D1). | ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Logic_Programming/SGST06/hbal_tree.pl | Perl | mit | 258 |
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw(say);
sub factorial {
my $n = shift;
if ($n < 1) {
return 1;
}
return $n * factorial($n - 1);
}
sub gauss {
my $n = shift;
# n (n + 1) / 2
return ($n * ($n + 1))/2;
}
sub prompt {
say "introduce number";
my $number = <STDIN>;
chomp $number;
return $number;
}
while(1) {
say "select an action";
my $action = <STDIN>;
if ($action =~ m/factorial/i) {
say factorial prompt;
} elsif ($action =~ m/sum/i) {
say gauss prompt;
} elsif ($action =~ m/exit/i) {
last;
}else{
say "invalid action (factorial, sum, exit)";
}
}
| leofigy/bbox | dummy/factoguass.pl | Perl | mit | 688 |
package PHPBB::Git;
use strict;
use warnings;
sub commits_in_branch($) {
my ($branch) = @_;
my @commits_in_branch = ();
open CMD, qq/git log --pretty=oneline "$branch" |/;
while (<CMD>) {
my @parts = split ' ', $_, 2;
my $sha = $parts[0];
push @commits_in_branch, $sha;
}
close CMD;
@commits_in_branch;
}
sub shortlog($) {
my ($branch) = @_;
my @commits_in_branch = ();
my %meta = ();
open CMD, qq/git log --pretty=oneline "$branch" |/;
while (<CMD>) {
my @parts = split ' ', $_, 2;
my $sha = $parts[0];
push @commits_in_branch, $sha;
$meta{$sha} = $parts[1];
}
close CMD;
(\@commits_in_branch, \%meta);
}
sub head_commit($) {
my ($branch) = @_;
my $head_commit;
open CMD, qq/git log --pretty=oneline -1 "$branch" |/;
while (<CMD>) {
my @parts = split ' ';
$head_commit = $parts[0];
}
close CMD;
$head_commit;
}
sub determine_base {
my ($branch, $prefix, $branch_commits) = @_;
my @branch_commits;
unless (defined $prefix) {
$prefix = '';
}
if (defined $branch_commits) {
@branch_commits = @{$branch_commits};
} else {
@branch_commits = commits_in_branch($branch);
}
# Important: base list should be arranged in the same order
# in which merges are done.
my @bases = qw/develop-olympus develop/;
my %base_commits = ();
for my $base (@bases) {
my @commits = commits_in_branch($prefix . $base);
my %commits_hash = ();
for (@commits) {
$commits_hash{$_} = 1;
}
$base_commits{$base} = \%commits_hash;
}
for my $sha (@branch_commits) {
for my $base (@bases) {
if ($base_commits{$base}->{$sha}) {
return $prefix . $base;
}
}
}
undef;
}
1;
| p/phpbb-tools | lib/PHPBB/Git.pm | Perl | mit | 1,930 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.