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 |
|---|---|---|---|---|---|
# !!!!!!! 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';
4E00 9FFF
END
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/unicore/lib/Blk/CJK.pl | Perl | mit | 433 |
package Net::Simplify::CardToken;
=head1 NAME
Net::Simplify::CardToken - A Simplify Commerce CardToken object
=head1 SYNOPSIS
use Net::Simplify;
$Net::Simplify::public_key = 'YOUR PUBLIC KEY';
$Net::Simplify::private_key = 'YOUR PRIVATE KEY';
# Create a new CardToken.
my $card_token = Net::Simplify::CardToken->create{ {...});
# Retrieve a CardToken given its ID.
my $card_token = Net::Simplify::CardToken->find('a7e41');
=head1 DESCRIPTION
=head2 METHODS
=head3 create(%params, $auth)
Creates a C<Net::Simplify::CardToken> object. The parameters are:
=over 4
=item C<%params>
Hash map containing initial values for the object. Valid keys are:
=over 4
=item callback
The URL callback for the cardtoken
=item card.addressCity
City of the cardholder. [max length: 50, min length: 2]
=item card.addressCountry
Country code (ISO-3166-1-alpha-2 code) of residence of the cardholder. [max length: 2, min length: 2]
=item card.addressLine1
Address of the cardholder. [max length: 255]
=item card.addressLine2
Address of the cardholder if needed. [max length: 255]
=item card.addressState
State code (USPS code) of residence of the cardholder. [max length: 2, min length: 2]
=item card.addressZip
Postal code of the cardholder. The postal code size is between 5 and 9 in length and only contain numbers or letters. [max length: 9, min length: 3]
=item card.cvc
CVC security code of the card. This is the code on the back of the card. Example: 123
=item card.expMonth
Expiration month of the card. Format is MM. Example: January = 01 [min value: 1, max value: 12] (B<required>)
=item card.expYear
Expiration year of the card. Format is YY. Example: 2013 = 13 [max value: 99] (B<required>)
=item card.name
Name as appears on the card. [max length: 50, min length: 2]
=item card.number
Card number as it appears on the card. [max length: 19, min length: 13] (B<required>)
=item key
Key used to create the card token.
=back
=item C<$auth>
Authentication object for accessing the API. If no value is passed the global keys
C<$Net::Simplify::public_key> and C<$Net::Simplify::private_key> are used.
=back
=head3 find($id, $auth)
Retrieve a C<Net::Simplify::CardToken> object from the API. Parameters are:
=over 4
=item C<$id>
Identifier of the object to retrieve.
=item C<$auth>
Authentication object for accessing the API. If no value is passed the global keys
C<$Net::Simplify::public_key> and C<$Net::Simplify::private_key> are used.
=back
=head1 SEE ALSO
L<Net::Simplify>,
L<Net::Simplify::Domain>,
L<Net::Simplify::DomainList>,
L<Net::Simplify::Authentication>,
L<Net::Simplify::ApiException>,
L<http://www.simplify.com>
=head1 VERSION
1.1.0
=head1 LICENSE
Copyright (c) 2013, 2014 MasterCard International Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
Neither the name of the MasterCard International Incorporated nor the names of its
contributors may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
=head1 SEE ALSO
=cut
use 5.006;
use strict;
use warnings FATAL => 'all';
use Net::Simplify::Domain;
use Net::Simplify::DomainList;
our @ISA = qw(Net::Simplify::Domain);
sub create {
my ($class, $params, $auth) = @_;
$auth = Net::Simplify::SimplifyApi->get_authentication($auth);
my $result = Net::Simplify::SimplifyApi->send_api_request("cardToken", 'create', $params, $auth);
$class->SUPER::new($result, $auth);
}
sub find {
my ($class, $id, $auth) = @_;
$auth = Net::Simplify::SimplifyApi->get_authentication($auth);
my $result = Net::Simplify::SimplifyApi->send_api_request("cardToken", 'find', { id => $id }, $auth);
$class->SUPER::new($result, $auth);
}
1;
| gitpan/simplifycommerce-sdk-perl-testing | lib/Net/Simplify/CardToken.pm | Perl | bsd-3-clause | 4,998 |
If you read this file _as_is_, just ignore the funny characters you
see. It is written in the POD format (see perlpod manpage) which is
specially designed to be readable as is.
=head1 NAME
perlos2 - Perl under OS/2, DOS, Win0.3*, Win0.95 and WinNT.
=head1 SYNOPSIS
One can read this document in the following formats:
man perlos2
view perl perlos2
explorer perlos2.html
info perlos2
to list some (not all may be available simultaneously), or it may
be read I<as is>: either as F<README.os2>, or F<pod/perlos2.pod>.
To read the F<.INF> version of documentation (B<very> recommended)
outside of OS/2, one needs an IBM's reader (may be available on IBM
ftp sites (?) (URL anyone?)) or shipped with PC DOS 7.0 and IBM's
Visual Age C++ 3.5.
A copy of a Win* viewer is contained in the "Just add OS/2 Warp" package
ftp://ftp.software.ibm.com/ps/products/os2/tools/jaow/jaow.zip
in F<?:\JUST_ADD\view.exe>. This gives one an access to EMX's
F<.INF> docs as well (text form is available in F</emx/doc> in
EMX's distribution). There is also a different viewer named xview.
Note that if you have F<lynx.exe> or F<netscape.exe> installed, you can follow WWW links
from this document in F<.INF> format. If you have EMX docs installed
correctly, you can follow library links (you need to have C<view emxbook>
working by setting C<EMXBOOK> environment variable as it is described
in EMX docs).
=cut
Contents (This may be a little bit obsolete)
perlos2 - Perl under OS/2, DOS, Win0.3*, Win0.95 and WinNT.
NAME
SYNOPSIS
DESCRIPTION
- Target
- Other OSes
- Prerequisites
- Starting Perl programs under OS/2 (and DOS and...)
- Starting OS/2 (and DOS) programs under Perl
Frequently asked questions
- "It does not work"
- I cannot run external programs
- I cannot embed perl into my program, or use perl.dll from my
- `` and pipe-open do not work under DOS.
- Cannot start find.exe "pattern" file
INSTALLATION
- Automatic binary installation
- Manual binary installation
- Warning
Accessing documentation
- OS/2 .INF file
- Plain text
- Manpages
- HTML
- GNU info files
- PDF files
- LaTeX docs
BUILD
- The short story
- Prerequisites
- Getting perl source
- Application of the patches
- Hand-editing
- Making
- Testing
- Installing the built perl
- a.out-style build
Build FAQ
- Some / became \ in pdksh.
- 'errno' - unresolved external
- Problems with tr or sed
- Some problem (forget which ;-)
- Library ... not found
- Segfault in make
- op/sprintf test failure
Specific (mis)features of OS/2 port
- setpriority, getpriority
- system()
- extproc on the first line
- Additional modules:
- Prebuilt methods:
- Prebuilt variables:
- Misfeatures
- Modifications
- Identifying DLLs
- Centralized management of resources
Perl flavors
- perl.exe
- perl_.exe
- perl__.exe
- perl___.exe
- Why strange names?
- Why dynamic linking?
- Why chimera build?
ENVIRONMENT
- PERLLIB_PREFIX
- PERL_BADLANG
- PERL_BADFREE
- PERL_SH_DIR
- USE_PERL_FLOCK
- TMP or TEMP
Evolution
- Text-mode filehandles
- Priorities
- DLL name mangling: pre 5.6.2
- DLL name mangling: 5.6.2 and beyond
- DLL forwarder generation
- Threading
- Calls to external programs
- Memory allocation
- Threads
BUGS
AUTHOR
SEE ALSO
=head1 DESCRIPTION
=head2 Target
The target is to make OS/2 one of the best supported platform for
using/building/developing Perl and I<Perl applications>, as well as
make Perl the best language to use under OS/2. The secondary target is
to try to make this work under DOS and Win* as well (but not B<too> hard).
The current state is quite close to this target. Known limitations:
=over 5
=item *
Some *nix programs use fork() a lot; with the mostly useful flavors of
perl for OS/2 (there are several built simultaneously) this is
supported; but some flavors do not support this (e.g., when Perl is
called from inside REXX). Using fork() after
I<use>ing dynamically loading extensions would not work with I<very> old
versions of EMX.
=item *
You need a separate perl executable F<perl__.exe> (see L</perl__.exe>)
if you want to use PM code in your application (as Perl/Tk or OpenGL
Perl modules do) without having a text-mode window present.
While using the standard F<perl.exe> from a text-mode window is possible
too, I have seen cases when this causes degradation of the system stability.
Using F<perl__.exe> avoids such a degradation.
=item *
There is no simple way to access WPS objects. The only way I know
is via C<OS2::REXX> and C<SOM> extensions (see L<OS2::REXX>, L<SOM>).
However, we do not have access to
convenience methods of Object-REXX. (Is it possible at all? I know
of no Object-REXX API.) The C<SOM> extension (currently in alpha-text)
may eventually remove this shortcoming; however, due to the fact that
DII is not supported by the C<SOM> module, using C<SOM> is not as
convenient as one would like it.
=back
Please keep this list up-to-date by informing me about other items.
=head2 Other OSes
Since OS/2 port of perl uses a remarkable EMX environment, it can
run (and build extensions, and - possibly - be built itself) under any
environment which can run EMX. The current list is DOS,
DOS-inside-OS/2, Win0.3*, Win0.95 and WinNT. Out of many perl flavors,
only one works, see L<"perl_.exe">.
Note that not all features of Perl are available under these
environments. This depends on the features the I<extender> - most
probably RSX - decided to implement.
Cf. L</Prerequisites>.
=head2 Prerequisites
=over 6
=item EMX
EMX runtime is required (may be substituted by RSX). Note that
it is possible to make F<perl_.exe> to run under DOS without any
external support by binding F<emx.exe>/F<rsx.exe> to it, see C<emxbind>. Note
that under DOS for best results one should use RSX runtime, which
has much more functions working (like C<fork>, C<popen> and so on). In
fact RSX is required if there is no VCPI present. Note the
RSX requires DPMI. Many implementations of DPMI are known to be very
buggy, beware!
Only the latest runtime is supported, currently C<0.9d fix 03>. Perl may run
under earlier versions of EMX, but this is not tested.
One can get different parts of EMX from, say
ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/emx+gcc/
http://hobbes.nmsu.edu/h-browse.php?dir=/pub/os2/dev/emx/v0.9d/
The runtime component should have the name F<emxrt.zip>.
B<NOTE>. When using F<emx.exe>/F<rsx.exe>, it is enough to have them on your path. One
does not need to specify them explicitly (though this
emx perl_.exe -de 0
will work as well.)
=item RSX
To run Perl on DPMI platforms one needs RSX runtime. This is
needed under DOS-inside-OS/2, Win0.3*, Win0.95 and WinNT (see
L<"Other OSes">). RSX would not work with VCPI
only, as EMX would, it requires DMPI.
Having RSX and the latest F<sh.exe> one gets a fully functional
B<*nix>-ish environment under DOS, say, C<fork>, C<``> and
pipe-C<open> work. In fact, MakeMaker works (for static build), so one
can have Perl development environment under DOS.
One can get RSX from, say
http://cd.textfiles.com/hobbesos29804/disk1/EMX09C/
ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/emx+gcc/contrib/
Contact the author on C<rainer@mathematik.uni-bielefeld.de>.
The latest F<sh.exe> with DOS hooks is available in
http://www.ilyaz.org/software/os2/
as F<sh_dos.zip> or under similar names starting with C<sh>, C<pdksh> etc.
=item HPFS
Perl does not care about file systems, but the perl library contains
many files with long names, so to install it intact one needs a file
system which supports long file names.
Note that if you do not plan to build the perl itself, it may be
possible to fool EMX to truncate file names. This is not supported,
read EMX docs to see how to do it.
=item pdksh
To start external programs with complicated command lines (like with
pipes in between, and/or quoting of arguments), Perl uses an external
shell. With EMX port such shell should be named F<sh.exe>, and located
either in the wired-in-during-compile locations (usually F<F:/bin>),
or in configurable location (see L<"PERL_SH_DIR">).
For best results use EMX pdksh. The standard binary (5.2.14 or later) runs
under DOS (with L</RSX>) as well, see
http://www.ilyaz.org/software/os2/
=back
=head2 Starting Perl programs under OS/2 (and DOS and...)
Start your Perl program F<foo.pl> with arguments C<arg1 arg2 arg3> the
same way as on any other platform, by
perl foo.pl arg1 arg2 arg3
If you want to specify perl options C<-my_opts> to the perl itself (as
opposed to your program), use
perl -my_opts foo.pl arg1 arg2 arg3
Alternately, if you use OS/2-ish shell, like CMD or 4os2, put
the following at the start of your perl script:
extproc perl -S -my_opts
rename your program to F<foo.cmd>, and start it by typing
foo arg1 arg2 arg3
Note that because of stupid OS/2 limitations the full path of the perl
script is not available when you use C<extproc>, thus you are forced to
use C<-S> perl switch, and your script should be on the C<PATH>. As a plus
side, if you know a full path to your script, you may still start it
with
perl ../../blah/foo.cmd arg1 arg2 arg3
(note that the argument C<-my_opts> is taken care of by the C<extproc> line
in your script, see L<C<extproc> on the first line>).
To understand what the above I<magic> does, read perl docs about C<-S>
switch - see L<perlrun>, and cmdref about C<extproc>:
view perl perlrun
man perlrun
view cmdref extproc
help extproc
or whatever method you prefer.
There are also endless possibilities to use I<executable extensions> of
4os2, I<associations> of WPS and so on... However, if you use
*nixish shell (like F<sh.exe> supplied in the binary distribution),
you need to follow the syntax specified in L<perlrun/"Command Switches">.
Note that B<-S> switch supports scripts with additional extensions
F<.cmd>, F<.btm>, F<.bat>, F<.pl> as well.
=head2 Starting OS/2 (and DOS) programs under Perl
This is what system() (see L<perlfunc/system>), C<``> (see
L<perlop/"I/O Operators">), and I<open pipe> (see L<perlfunc/open>)
are for. (Avoid exec() (see L<perlfunc/exec>) unless you know what you
do).
Note however that to use some of these operators you need to have a
sh-syntax shell installed (see L<"Pdksh">,
L<"Frequently asked questions">), and perl should be able to find it
(see L<"PERL_SH_DIR">).
The cases when the shell is used are:
=over
=item 1
One-argument system() (see L<perlfunc/system>), exec() (see L<perlfunc/exec>)
with redirection or shell meta-characters;
=item 2
Pipe-open (see L<perlfunc/open>) with the command which contains redirection
or shell meta-characters;
=item 3
Backticks C<``> (see L<perlop/"I/O Operators">) with the command which contains
redirection or shell meta-characters;
=item 4
If the executable called by system()/exec()/pipe-open()/C<``> is a script
with the "magic" C<#!> line or C<extproc> line which specifies shell;
=item 5
If the executable called by system()/exec()/pipe-open()/C<``> is a script
without "magic" line, and C<$ENV{EXECSHELL}> is set to shell;
=item 6
If the executable called by system()/exec()/pipe-open()/C<``> is not
found (is not this remark obsolete?);
=item 7
For globbing (see L<perlfunc/glob>, L<perlop/"I/O Operators">)
(obsolete? Perl uses builtin globbing nowadays...).
=back
For the sake of speed for a common case, in the above algorithms
backslashes in the command name are not considered as shell metacharacters.
Perl starts scripts which begin with cookies
C<extproc> or C<#!> directly, without an intervention of shell. Perl uses the
same algorithm to find the executable as F<pdksh>: if the path
on C<#!> line does not work, and contains C</>, then the directory
part of the executable is ignored, and the executable
is searched in F<.> and on C<PATH>. To find arguments for these scripts
Perl uses a different algorithm than F<pdksh>: up to 3 arguments are
recognized, and trailing whitespace is stripped.
If a script
does not contain such a cooky, then to avoid calling F<sh.exe>, Perl uses
the same algorithm as F<pdksh>: if C<$ENV{EXECSHELL}> is set, the
script is given as the first argument to this command, if not set, then
C<$ENV{COMSPEC} /c> is used (or a hardwired guess if C<$ENV{COMSPEC}> is
not set).
When starting scripts directly, Perl uses exactly the same algorithm as for
the search of script given by B<-S> command-line option: it will look in
the current directory, then on components of C<$ENV{PATH}> using the
following order of appended extensions: no extension, F<.cmd>, F<.btm>,
F<.bat>, F<.pl>.
Note that Perl will start to look for scripts only if OS/2 cannot start the
specified application, thus C<system 'blah'> will not look for a script if
there is an executable file F<blah.exe> I<anywhere> on C<PATH>. In
other words, C<PATH> is essentially searched twice: once by the OS for
an executable, then by Perl for scripts.
Note also that executable files on OS/2 can have an arbitrary extension,
but F<.exe> will be automatically appended if no dot is present in the name.
The workaround is as simple as that: since F<blah.> and F<blah> denote the
same file (at list on FAT and HPFS file systems), to start an executable residing in file F<n:/bin/blah> (no
extension) give an argument C<n:/bin/blah.> (dot appended) to system().
Perl will start PM programs from VIO (=text-mode) Perl process in a
separate PM session;
the opposite is not true: when you start a non-PM program from a PM
Perl process, Perl would not run it in a separate session. If a separate
session is desired, either ensure
that shell will be used, as in C<system 'cmd /c myprog'>, or start it using
optional arguments to system() documented in C<OS2::Process> module. This
is considered to be a feature.
=head1 Frequently asked questions
=head2 "It does not work"
Perl binary distributions come with a F<testperl.cmd> script which tries
to detect common problems with misconfigured installations. There is a
pretty large chance it will discover which step of the installation you
managed to goof. C<;-)>
=head2 I cannot run external programs
=over 4
=item *
Did you run your programs with C<-w> switch? See
L<Starting OSE<sol>2 (and DOS) programs under Perl>.
=item *
Do you try to run I<internal> shell commands, like C<`copy a b`>
(internal for F<cmd.exe>), or C<`glob a*b`> (internal for ksh)? You
need to specify your shell explicitly, like C<`cmd /c copy a b`>,
since Perl cannot deduce which commands are internal to your shell.
=back
=head2 I cannot embed perl into my program, or use F<perl.dll> from my
program.
=over 4
=item Is your program EMX-compiled with C<-Zmt -Zcrtdll>?
Well, nowadays Perl DLL should be usable from a differently compiled
program too... If you can run Perl code from REXX scripts (see
L<OS2::REXX>), then there are some other aspect of interaction which
are overlooked by the current hackish code to support
differently-compiled principal programs.
If everything else fails, you need to build a stand-alone DLL for
perl. Contact me, I did it once. Sockets would not work, as a lot of
other stuff.
=item Did you use L<ExtUtils::Embed>?
Some time ago I had reports it does not work. Nowadays it is checked
in the Perl test suite, so grep F<./t> subdirectory of the build tree
(as well as F<*.t> files in the F<./lib> subdirectory) to find how it
should be done "correctly".
=back
=head2 C<``> and pipe-C<open> do not work under DOS.
This may a variant of just L<"I cannot run external programs">, or a
deeper problem. Basically: you I<need> RSX (see L</Prerequisites>)
for these commands to work, and you may need a port of F<sh.exe> which
understands command arguments. One of such ports is listed in
L</Prerequisites> under RSX. Do not forget to set variable
C<L<"PERL_SH_DIR">> as well.
DPMI is required for RSX.
=head2 Cannot start C<find.exe "pattern" file>
The whole idea of the "standard C API to start applications" is that
the forms C<foo> and C<"foo"> of program arguments are completely
interchangeable. F<find> breaks this paradigm;
find "pattern" file
find pattern file
are not equivalent; F<find> cannot be started directly using the above
API. One needs a way to surround the doublequotes in some other
quoting construction, necessarily having an extra non-Unixish shell in
between.
Use one of
system 'cmd', '/c', 'find "pattern" file';
`cmd /c 'find "pattern" file'`
This would start F<find.exe> via F<cmd.exe> via C<sh.exe> via
C<perl.exe>, but this is a price to pay if you want to use
non-conforming program.
=head1 INSTALLATION
=head2 Automatic binary installation
The most convenient way of installing a binary distribution of perl is via perl installer
F<install.exe>. Just follow the instructions, and 99% of the
installation blues would go away.
Note however, that you need to have F<unzip.exe> on your path, and
EMX environment I<running>. The latter means that if you just
installed EMX, and made all the needed changes to F<Config.sys>,
you may need to reboot in between. Check EMX runtime by running
emxrev
Binary installer also creates a folder on your desktop with some useful
objects. If you need to change some aspects of the work of the binary
installer, feel free to edit the file F<Perl.pkg>. This may be useful
e.g., if you need to run the installer many times and do not want to
make many interactive changes in the GUI.
B<Things not taken care of by automatic binary installation:>
=over 15
=item C<PERL_BADLANG>
may be needed if you change your codepage I<after> perl installation,
and the new value is not supported by EMX. See L<"PERL_BADLANG">.
=item C<PERL_BADFREE>
see L<"PERL_BADFREE">.
=item F<Config.pm>
This file resides somewhere deep in the location you installed your
perl library, find it out by
perl -MConfig -le "print $INC{'Config.pm'}"
While most important values in this file I<are> updated by the binary
installer, some of them may need to be hand-edited. I know no such
data, please keep me informed if you find one. Moreover, manual
changes to the installed version may need to be accompanied by an edit
of this file.
=back
B<NOTE>. Because of a typo the binary installer of 5.00305
would install a variable C<PERL_SHPATH> into F<Config.sys>. Please
remove this variable and put C<L</PERL_SH_DIR>> instead.
=head2 Manual binary installation
As of version 5.00305, OS/2 perl binary distribution comes split
into 11 components. Unfortunately, to enable configurable binary
installation, the file paths in the zip files are not absolute, but
relative to some directory.
Note that the extraction with the stored paths is still necessary
(default with unzip, specify C<-d> to pkunzip). However, you
need to know where to extract the files. You need also to manually
change entries in F<Config.sys> to reflect where did you put the
files. Note that if you have some primitive unzipper (like
C<pkunzip>), you may get a lot of warnings/errors during
unzipping. Upgrade to C<(w)unzip>.
Below is the sample of what to do to reproduce the configuration on my
machine. In F<VIEW.EXE> you can press C<Ctrl-Insert> now, and
cut-and-paste from the resulting file - created in the directory you
started F<VIEW.EXE> from.
For each component, we mention environment variables related to each
installation directory. Either choose directories to match your
values of the variables, or create/append-to variables to take into
account the directories.
=over 3
=item Perl VIO and PM executables (dynamically linked)
unzip perl_exc.zip *.exe *.ico -d f:/emx.add/bin
unzip perl_exc.zip *.dll -d f:/emx.add/dll
(have the directories with C<*.exe> on PATH, and C<*.dll> on
LIBPATH);
=item Perl_ VIO executable (statically linked)
unzip perl_aou.zip -d f:/emx.add/bin
(have the directory on PATH);
=item Executables for Perl utilities
unzip perl_utl.zip -d f:/emx.add/bin
(have the directory on PATH);
=item Main Perl library
unzip perl_mlb.zip -d f:/perllib/lib
If this directory is exactly the same as the prefix which was compiled
into F<perl.exe>, you do not need to change
anything. However, for perl to find the library if you use a different
path, you need to
C<set PERLLIB_PREFIX> in F<Config.sys>, see L<"PERLLIB_PREFIX">.
=item Additional Perl modules
unzip perl_ste.zip -d f:/perllib/lib/site_perl/5.16.2/
Same remark as above applies. Additionally, if this directory is not
one of directories on @INC (and @INC is influenced by C<PERLLIB_PREFIX>), you
need to put this
directory and subdirectory F<./os2> in C<PERLLIB> or C<PERL5LIB>
variable. Do not use C<PERL5LIB> unless you have it set already. See
L<perl/"ENVIRONMENT">.
B<[Check whether this extraction directory is still applicable with
the new directory structure layout!]>
=item Tools to compile Perl modules
unzip perl_blb.zip -d f:/perllib/lib
Same remark as for F<perl_ste.zip>.
=item Manpages for Perl and utilities
unzip perl_man.zip -d f:/perllib/man
This directory should better be on C<MANPATH>. You need to have a
working F<man> to access these files.
=item Manpages for Perl modules
unzip perl_mam.zip -d f:/perllib/man
This directory should better be on C<MANPATH>. You need to have a
working man to access these files.
=item Source for Perl documentation
unzip perl_pod.zip -d f:/perllib/lib
This is used by the C<perldoc> program (see L<perldoc>), and may be used to
generate HTML documentation usable by WWW browsers, and
documentation in zillions of other formats: C<info>, C<LaTeX>,
C<Acrobat>, C<FrameMaker> and so on. [Use programs such as
F<pod2latex> etc.]
=item Perl manual in F<.INF> format
unzip perl_inf.zip -d d:/os2/book
This directory should better be on C<BOOKSHELF>.
=item Pdksh
unzip perl_sh.zip -d f:/bin
This is used by perl to run external commands which explicitly
require shell, like the commands using I<redirection> and I<shell
metacharacters>. It is also used instead of explicit F</bin/sh>.
Set C<PERL_SH_DIR> (see L<"PERL_SH_DIR">) if you move F<sh.exe> from
the above location.
B<Note.> It may be possible to use some other sh-compatible shell (untested).
=back
After you installed the components you needed and updated the
F<Config.sys> correspondingly, you need to hand-edit
F<Config.pm>. This file resides somewhere deep in the location you
installed your perl library, find it out by
perl -MConfig -le "print $INC{'Config.pm'}"
You need to correct all the entries which look like file paths (they
currently start with C<f:/>).
=head2 B<Warning>
The automatic and manual perl installation leave precompiled paths
inside perl executables. While these paths are overwriteable (see
L<"PERLLIB_PREFIX">, L<"PERL_SH_DIR">), some people may prefer
binary editing of paths inside the executables/DLLs.
=head1 Accessing documentation
Depending on how you built/installed perl you may have (otherwise
identical) Perl documentation in the following formats:
=head2 OS/2 F<.INF> file
Most probably the most convenient form. Under OS/2 view it as
view perl
view perl perlfunc
view perl less
view perl ExtUtils::MakeMaker
(currently the last two may hit a wrong location, but this may improve
soon). Under Win* see L<"SYNOPSIS">.
If you want to build the docs yourself, and have I<OS/2 toolkit>, run
pod2ipf > perl.ipf
in F</perllib/lib/pod> directory, then
ipfc /inf perl.ipf
(Expect a lot of errors during the both steps.) Now move it on your
BOOKSHELF path.
=head2 Plain text
If you have perl documentation in the source form, perl utilities
installed, and GNU groff installed, you may use
perldoc perlfunc
perldoc less
perldoc ExtUtils::MakeMaker
to access the perl documentation in the text form (note that you may get
better results using perl manpages).
Alternately, try running pod2text on F<.pod> files.
=head2 Manpages
If you have F<man> installed on your system, and you installed perl
manpages, use something like this:
man perlfunc
man 3 less
man ExtUtils.MakeMaker
to access documentation for different components of Perl. Start with
man perl
Note that dot (F<.>) is used as a package separator for documentation
for packages, and as usual, sometimes you need to give the section - C<3>
above - to avoid shadowing by the I<less(1) manpage>.
Make sure that the directory B<above> the directory with manpages is
on our C<MANPATH>, like this
set MANPATH=c:/man;f:/perllib/man
for Perl manpages in C<f:/perllib/man/man1/> etc.
=head2 HTML
If you have some WWW browser available, installed the Perl
documentation in the source form, and Perl utilities, you can build
HTML docs. Cd to directory with F<.pod> files, and do like this
cd f:/perllib/lib/pod
pod2html
After this you can direct your browser the file F<perl.html> in this
directory, and go ahead with reading docs, like this:
explore file:///f:/perllib/lib/pod/perl.html
Alternatively you may be able to get these docs prebuilt from CPAN.
=head2 GNU C<info> files
Users of Emacs would appreciate it very much, especially with
C<CPerl> mode loaded. You need to get latest C<pod2texi> from C<CPAN>,
or, alternately, the prebuilt info pages.
=head2 F<PDF> files
for C<Acrobat> are available on CPAN (may be for slightly older version of
perl).
=head2 C<LaTeX> docs
can be constructed using C<pod2latex>.
=head1 BUILD
Here we discuss how to build Perl under OS/2.
=head2 The short story
Assume that you are a seasoned porter, so are sure that all the necessary
tools are already present on your system, and you know how to get the Perl
source distribution. Untar it, change to the extract directory, and
gnupatch -p0 < os2\diff.configure
sh Configure -des -D prefix=f:/perllib
make
make test
make install
make aout_test
make aout_install
This puts the executables in f:/perllib/bin. Manually move them to the
C<PATH>, manually move the built F<perl*.dll> to C<LIBPATH> (here for
Perl DLL F<*> is a not-very-meaningful hex checksum), and run
make installcmd INSTALLCMDDIR=d:/ir/on/path
Assuming that the C<man>-files were put on an appropriate location,
this completes the installation of minimal Perl system. (The binary
distribution contains also a lot of additional modules, and the
documentation in INF format.)
What follows is a detailed guide through these steps.
=head2 Prerequisites
You need to have the latest EMX development environment, the full
GNU tool suite (gawk renamed to awk, and GNU F<find.exe>
earlier on path than the OS/2 F<find.exe>, same with F<sort.exe>, to
check use
find --version
sort --version
). You need the latest version of F<pdksh> installed as F<sh.exe>.
Check that you have B<BSD> libraries and headers installed, and -
optionally - Berkeley DB headers and libraries, and crypt.
Possible locations to get the files:
ftp://ftp.uni-heidelberg.de/pub/os2/unix/
http://hobbes.nmsu.edu/h-browse.php?dir=/pub/os2
http://cd.textfiles.com/hobbesos29804/disk1/DEV32/
http://cd.textfiles.com/hobbesos29804/disk1/EMX09C/
It is reported that the following archives contain enough utils to
build perl: F<gnufutil.zip>, F<gnusutil.zip>, F<gnututil.zip>, F<gnused.zip>,
F<gnupatch.zip>, F<gnuawk.zip>, F<gnumake.zip>, F<gnugrep.zip>, F<bsddev.zip> and
F<ksh527rt.zip> (or a later version). Note that all these utilities are
known to be available from LEO:
ftp://crydee.sai.msu.ru/pub/comp/os/os2/leo/gnu/
Note also that the F<db.lib> and F<db.a> from the EMX distribution
are not suitable for multi-threaded compile (even single-threaded
flavor of Perl uses multi-threaded C RTL, for
compatibility with XFree86-OS/2). Get a corrected one from
http://www.ilyaz.org/software/os2/db_mt.zip
If you have I<exactly the same version of Perl> installed already,
make sure that no copies or perl are currently running. Later steps
of the build may fail since an older version of F<perl.dll> loaded into
memory may be found. Running C<make test> becomes meaningless, since
the test are checking a previous build of perl (this situation is detected
and reported by F<lib/os2_base.t> test). Do not forget to unset
C<PERL_EMXLOAD_SEC> in environment.
Also make sure that you have F</tmp> directory on the current drive,
and F<.> directory in your C<LIBPATH>. One may try to correct the
latter condition by
set BEGINLIBPATH .\.
if you use something like F<CMD.EXE> or latest versions of
F<4os2.exe>. (Setting BEGINLIBPATH to just C<.> is ignored by the
OS/2 kernel.)
Make sure your gcc is good for C<-Zomf> linking: run C<omflibs>
script in F</emx/lib> directory.
Check that you have link386 installed. It comes standard with OS/2,
but may be not installed due to customization. If typing
link386
shows you do not have it, do I<Selective install>, and choose C<Link
object modules> in I<Optional system utilities/More>. If you get into
link386 prompts, press C<Ctrl-C> to exit.
=head2 Getting perl source
You need to fetch the latest perl source (including developers
releases). With some probability it is located in
http://www.cpan.org/src/
http://www.cpan.org/src/unsupported
If not, you may need to dig in the indices to find it in the directory
of the current maintainer.
Quick cycle of developers release may break the OS/2 build time to
time, looking into
http://www.cpan.org/ports/os2/
may indicate the latest release which was publicly released by the
maintainer. Note that the release may include some additional patches
to apply to the current source of perl.
Extract it like this
tar vzxf perl5.00409.tar.gz
You may see a message about errors while extracting F<Configure>. This is
because there is a conflict with a similarly-named file F<configure>.
Change to the directory of extraction.
=head2 Application of the patches
You need to apply the patches in F<./os2/diff.*> like this:
gnupatch -p0 < os2\diff.configure
You may also need to apply the patches supplied with the binary
distribution of perl. It also makes sense to look on the
perl5-porters mailing list for the latest OS/2-related patches (see
L<http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/>). Such
patches usually contain strings C</os2/> and C<patch>, so it makes
sense looking for these strings.
=head2 Hand-editing
You may look into the file F<./hints/os2.sh> and correct anything
wrong you find there. I do not expect it is needed anywhere.
=head2 Making
sh Configure -des -D prefix=f:/perllib
C<prefix> means: where to install the resulting perl library. Giving
correct prefix you may avoid the need to specify C<PERLLIB_PREFIX>,
see L<"PERLLIB_PREFIX">.
I<Ignore the message about missing C<ln>, and about C<-c> option to
tr>. The latter is most probably already fixed, if you see it and can trace
where the latter spurious warning comes from, please inform me.
Now
make
At some moment the built may die, reporting a I<version mismatch> or
I<unable to run F<perl>>. This means that you do not have F<.> in
your LIBPATH, so F<perl.exe> cannot find the needed F<perl67B2.dll> (treat
these hex digits as line noise). After this is fixed the build
should finish without a lot of fuss.
=head2 Testing
Now run
make test
All tests should succeed (with some of them skipped). If you have the
same version of Perl installed, it is crucial that you have C<.> early
in your LIBPATH (or in BEGINLIBPATH), otherwise your tests will most
probably test the wrong version of Perl.
Some tests may generate extra messages similar to
=over 4
=item A lot of C<bad free>
in database tests related to Berkeley DB. I<This should be fixed already.>
If it persists, you may disable this warnings, see L<"PERL_BADFREE">.
=item Process terminated by SIGTERM/SIGINT
This is a standard message issued by OS/2 applications. *nix
applications die in silence. It is considered to be a feature. One can
easily disable this by appropriate sighandlers.
However the test engine bleeds these message to screen in unexpected
moments. Two messages of this kind I<should> be present during
testing.
=back
To get finer test reports, call
perl t/harness
The report with F<io/pipe.t> failing may look like this:
Failed Test Status Wstat Total Fail Failed List of failed
------------------------------------------------------------
io/pipe.t 12 1 8.33% 9
7 tests skipped, plus 56 subtests skipped.
Failed 1/195 test scripts, 99.49% okay. 1/6542 subtests failed, 99.98% okay.
The reasons for most important skipped tests are:
=over 8
=item F<op/fs.t>
=over 4
=item 18
Checks C<atime> and C<mtime> of C<stat()> - unfortunately, HPFS
provides only 2sec time granularity (for compatibility with FAT?).
=item 25
Checks C<truncate()> on a filehandle just opened for write - I do not
know why this should or should not work.
=back
=item F<op/stat.t>
Checks C<stat()>. Tests:
=over 4
=item 4
Checks C<atime> and C<mtime> of C<stat()> - unfortunately, HPFS
provides only 2sec time granularity (for compatibility with FAT?).
=back
=back
=head2 Installing the built perl
If you haven't yet moved C<perl*.dll> onto LIBPATH, do it now.
Run
make install
It would put the generated files into needed locations. Manually put
F<perl.exe>, F<perl__.exe> and F<perl___.exe> to a location on your
PATH, F<perl.dll> to a location on your LIBPATH.
Run
make installcmd INSTALLCMDDIR=d:/ir/on/path
to convert perl utilities to F<.cmd> files and put them on
PATH. You need to put F<.EXE>-utilities on path manually. They are
installed in C<$prefix/bin>, here C<$prefix> is what you gave to
F<Configure>, see L</Making>.
If you use C<man>, either move the installed F<*/man/> directories to
your C<MANPATH>, or modify C<MANPATH> to match the location. (One
could have avoided this by providing a correct C<manpath> option to
F<./Configure>, or editing F<./config.sh> between configuring and
making steps.)
=head2 C<a.out>-style build
Proceed as above, but make F<perl_.exe> (see L<"perl_.exe">) by
make perl_
test and install by
make aout_test
make aout_install
Manually put F<perl_.exe> to a location on your PATH.
B<Note.> The build process for C<perl_> I<does not know> about all the
dependencies, so you should make sure that anything is up-to-date,
say, by doing
make perl_dll
first.
=head1 Building a binary distribution
[This section provides a short overview only...]
Building should proceed differently depending on whether the version of perl
you install is already present and used on your system, or is a new version
not yet used. The description below assumes that the version is new, so
installing its DLLs and F<.pm> files will not disrupt the operation of your
system even if some intermediate steps are not yet fully working.
The other cases require a little bit more convoluted procedures. Below I
suppose that the current version of Perl is C<5.8.2>, so the executables are
named accordingly.
=over
=item 1.
Fully build and test the Perl distribution. Make sure that no tests are
failing with C<test> and C<aout_test> targets; fix the bugs in Perl and
the Perl test suite detected by these tests. Make sure that C<all_test>
make target runs as clean as possible. Check that F<os2/perlrexx.cmd>
runs fine.
=item 2.
Fully install Perl, including C<installcmd> target. Copy the generated DLLs
to C<LIBPATH>; copy the numbered Perl executables (as in F<perl5.8.2.exe>)
to C<PATH>; copy C<perl_.exe> to C<PATH> as C<perl_5.8.2.exe>. Think whether
you need backward-compatibility DLLs. In most cases you do not need to install
them yet; but sometime this may simplify the following steps.
=item 3.
Make sure that C<CPAN.pm> can download files from CPAN. If not, you may need
to manually install C<Net::FTP>.
=item 4.
Install the bundle C<Bundle::OS2_default>
perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_1
This may take a couple of hours on 1GHz processor (when run the first time).
And this should not be necessarily a smooth procedure. Some modules may not
specify required dependencies, so one may need to repeat this procedure several
times until the results stabilize.
perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_2
perl5.8.2 -MCPAN -e "install Bundle::OS2_default" < nul |& tee 00cpan_i_3
Even after they stabilize, some tests may fail.
Fix as many discovered bugs as possible. Document all the bugs which are not
fixed, and all the failures with unknown reasons. Inspect the produced logs
F<00cpan_i_1> to find suspiciously skipped tests, and other fishy events.
Keep in mind that I<installation> of some modules may fail too: for example,
the DLLs to update may be already loaded by F<CPAN.pm>. Inspect the C<install>
logs (in the example above F<00cpan_i_1> etc) for errors, and install things
manually, as in
cd $CPANHOME/.cpan/build/Digest-MD5-2.31
make install
Some distributions may fail some tests, but you may want to install them
anyway (as above, or via C<force install> command of C<CPAN.pm> shell-mode).
Since this procedure may take quite a long time to complete, it makes sense
to "freeze" your CPAN configuration by disabling periodic updates of the
local copy of CPAN index: set C<index_expire> to some big value (I use 365),
then save the settings
CPAN> o conf index_expire 365
CPAN> o conf commit
Reset back to the default value C<1> when you are finished.
=item 5.
When satisfied with the results, rerun the C<installcmd> target. Now you
can copy C<perl5.8.2.exe> to C<perl.exe>, and install the other OMF-build
executables: C<perl__.exe> etc. They are ready to be used.
=item 6.
Change to the C<./pod> directory of the build tree, download the Perl logo
F<CamelGrayBig.BMP>, and run
( perl2ipf > perl.ipf ) |& tee 00ipf
ipfc /INF perl.ipf |& tee 00inf
This produces the Perl docs online book C<perl.INF>. Install in on
C<BOOKSHELF> path.
=item 7.
Now is the time to build statically linked executable F<perl_.exe> which
includes newly-installed via C<Bundle::OS2_default> modules. Doing testing
via C<CPAN.pm> is going to be painfully slow, since it statically links
a new executable per XS extension.
Here is a possible workaround: create a toplevel F<Makefile.PL> in
F<$CPANHOME/.cpan/build/> with contents being (compare with L<Making
executables with a custom collection of statically loaded extensions>)
use ExtUtils::MakeMaker;
WriteMakefile NAME => 'dummy';
execute this as
perl_5.8.2.exe Makefile.PL <nul |& tee 00aout_c1
make -k all test <nul |& 00aout_t1
Again, this procedure should not be absolutely smooth. Some C<Makefile.PL>'s
in subdirectories may be buggy, and would not run as "child" scripts. The
interdependency of modules can strike you; however, since non-XS modules
are already installed, the prerequisites of most modules have a very good
chance to be present.
If you discover some glitches, move directories of problematic modules to a
different location; if these modules are non-XS modules, you may just ignore
them - they are already installed; the remaining, XS, modules you need to
install manually one by one.
After each such removal you need to rerun the C<Makefile.PL>/C<make> process;
usually this procedure converges soon. (But be sure to convert all the
necessary external C libraries from F<.lib> format to F<.a> format: run one of
emxaout foo.lib
emximp -o foo.a foo.lib
whichever is appropriate.) Also, make sure that the DLLs for external
libraries are usable with with executables compiled without C<-Zmtd> options.
When you are sure that only a few subdirectories
lead to failures, you may want to add C<-j4> option to C<make> to speed up
skipping subdirectories with already finished build.
When you are satisfied with the results of tests, install the build C libraries
for extensions:
make install |& tee 00aout_i
Now you can rename the file F<./perl.exe> generated during the last phase
to F<perl_5.8.2.exe>; place it on C<PATH>; if there is an inter-dependency
between some XS modules, you may need to repeat the C<test>/C<install> loop
with this new executable and some excluded modules - until the procedure
converges.
Now you have all the necessary F<.a> libraries for these Perl modules in the
places where Perl builder can find it. Use the perl builder: change to an
empty directory, create a "dummy" F<Makefile.PL> again, and run
perl_5.8.2.exe Makefile.PL |& tee 00c
make perl |& tee 00p
This should create an executable F<./perl.exe> with all the statically loaded
extensions built in. Compare the generated F<perlmain.c> files to make sure
that during the iterations the number of loaded extensions only increases.
Rename F<./perl.exe> to F<perl_5.8.2.exe> on C<PATH>.
When it converges, you got a functional variant of F<perl_5.8.2.exe>; copy it
to C<perl_.exe>. You are done with generation of the local Perl installation.
=item 8.
Make sure that the installed modules are actually installed in the location
of the new Perl, and are not inherited from entries of @INC given for
inheritance from the older versions of Perl: set C<PERLLIB_582_PREFIX> to
redirect the new version of Perl to a new location, and copy the installed
files to this new location. Redo the tests to make sure that the versions of
modules inherited from older versions of Perl are not needed.
Actually, the log output of L<pod2ipf(1)> during the step 6 gives a very detailed
info about which modules are loaded from which place; so you may use it as
an additional verification tool.
Check that some temporary files did not make into the perl install tree.
Run something like this
pfind . -f "!(/\.(pm|pl|ix|al|h|a|lib|txt|pod|imp|bs|dll|ld|bs|inc|xbm|yml|cgi|uu|e2x|skip|packlist|eg|cfg|html|pub|enc|all|ini|po|pot)$/i or /^\w+$/") | less
in the install tree (both top one and F<sitelib> one).
Compress all the DLLs with F<lxlite>. The tiny F<.exe> can be compressed with
C</c:max> (the bug only appears when there is a fixup in the last 6 bytes of a
page (?); since the tiny executables are much smaller than a page, the bug
will not hit). Do not compress C<perl_.exe> - it would not work under DOS.
=item 9.
Now you can generate the binary distribution. This is done by running the
test of the CPAN distribution C<OS2::SoftInstaller>. Tune up the file
F<test.pl> to suit the layout of current version of Perl first. Do not
forget to pack the necessary external DLLs accordingly. Include the
description of the bugs and test suite failures you could not fix. Include
the small-stack versions of Perl executables from Perl build directory.
Include F<perl5.def> so that people can relink the perl DLL preserving
the binary compatibility, or can create compatibility DLLs. Include the diff
files (C<diff -pu old new>) of fixes you did so that people can rebuild your
version. Include F<perl5.map> so that one can use remote debugging.
=item 10.
Share what you did with the other people. Relax. Enjoy fruits of your work.
=item 11.
Brace yourself for thanks, bug reports, hate mail and spam coming as result
of the previous step. No good deed should remain unpunished!
=back
=head1 Building custom F<.EXE> files
The Perl executables can be easily rebuilt at any moment. Moreover, one can
use the I<embedding> interface (see L<perlembed>) to make very customized
executables.
=head2 Making executables with a custom collection of statically loaded extensions
It is a little bit easier to do so while I<decreasing> the list of statically
loaded extensions. We discuss this case only here.
=over
=item 1.
Change to an empty directory, and create a placeholder <Makefile.PL>:
use ExtUtils::MakeMaker;
WriteMakefile NAME => 'dummy';
=item 2.
Run it with the flavor of Perl (F<perl.exe> or F<perl_.exe>) you want to
rebuild.
perl_ Makefile.PL
=item 3.
Ask it to create new Perl executable:
make perl
(you may need to manually add C<PERLTYPE=-DPERL_CORE> to this commandline on
some versions of Perl; the symptom is that the command-line globbing does not
work from OS/2 shells with the newly-compiled executable; check with
.\perl.exe -wle "print for @ARGV" *
).
=item 4.
The previous step created F<perlmain.c> which contains a list of newXS() calls
near the end. Removing unnecessary calls, and rerunning
make perl
will produce a customized executable.
=back
=head2 Making executables with a custom search-paths
The default perl executable is flexible enough to support most usages.
However, one may want something yet more flexible; for example, one may want
to find Perl DLL relatively to the location of the EXE file; or one may want
to ignore the environment when setting the Perl-library search patch, etc.
If you fill comfortable with I<embedding> interface (see L<perlembed>), such
things are easy to do repeating the steps outlined in L<Making
executables with a custom collection of statically loaded extensions>, and
doing more comprehensive edits to main() of F<perlmain.c>. The people with
little desire to understand Perl can just rename main(), and do necessary
modification in a custom main() which calls the renamed function in appropriate
time.
However, there is a third way: perl DLL exports the main() function and several
callbacks to customize the search path. Below is a complete example of a
"Perl loader" which
=over
=item 1.
Looks for Perl DLL in the directory C<$exedir/../dll>;
=item 2.
Prepends the above directory to C<BEGINLIBPATH>;
=item 3.
Fails if the Perl DLL found via C<BEGINLIBPATH> is different from what was
loaded on step 1; e.g., another process could have loaded it from C<LIBPATH>
or from a different value of C<BEGINLIBPATH>. In these cases one needs to
modify the setting of the system so that this other process either does not
run, or loads the DLL from C<BEGINLIBPATH> with C<LIBPATHSTRICT=T> (available
with kernels after September 2000).
=item 4.
Loads Perl library from C<$exedir/../dll/lib/>.
=item 5.
Uses Bourne shell from C<$exedir/../dll/sh/ksh.exe>.
=back
For best results compile the C file below with the same options as the Perl
DLL. However, a lot of functionality will work even if the executable is not
an EMX applications, e.g., if compiled with
gcc -Wall -DDOSISH -DOS2=1 -O2 -s -Zomf -Zsys perl-starter.c -DPERL_DLL_BASENAME=\"perl312F\" -Zstack 8192 -Zlinker /PM:VIO
Here is the sample C file:
#define INCL_DOS
#define INCL_NOPM
/* These are needed for compile if os2.h includes os2tk.h, not os2emx.h */
#define INCL_DOSPROCESS
#include <os2.h>
#include "EXTERN.h"
#define PERL_IN_MINIPERLMAIN_C
#include "perl.h"
static char *me;
HMODULE handle;
static void
die_with(char *msg1, char *msg2, char *msg3, char *msg4)
{
ULONG c;
char *s = " error: ";
DosWrite(2, me, strlen(me), &c);
DosWrite(2, s, strlen(s), &c);
DosWrite(2, msg1, strlen(msg1), &c);
DosWrite(2, msg2, strlen(msg2), &c);
DosWrite(2, msg3, strlen(msg3), &c);
DosWrite(2, msg4, strlen(msg4), &c);
DosWrite(2, "\r\n", 2, &c);
exit(255);
}
typedef ULONG (*fill_extLibpath_t)(int type, char *pre, char *post, int replace, char *msg);
typedef int (*main_t)(int type, char *argv[], char *env[]);
typedef int (*handler_t)(void* data, int which);
#ifndef PERL_DLL_BASENAME
# define PERL_DLL_BASENAME "perl"
#endif
static HMODULE
load_perl_dll(char *basename)
{
char buf[300], fail[260];
STRLEN l, dirl;
fill_extLibpath_t f;
ULONG rc_fullname;
HMODULE handle, handle1;
if (_execname(buf, sizeof(buf) - 13) != 0)
die_with("Can't find full path: ", strerror(errno), "", "");
/* XXXX Fill 'me' with new value */
l = strlen(buf);
while (l && buf[l-1] != '/' && buf[l-1] != '\\')
l--;
dirl = l - 1;
strcpy(buf + l, basename);
l += strlen(basename);
strcpy(buf + l, ".dll");
if ( (rc_fullname = DosLoadModule(fail, sizeof fail, buf, &handle)) != 0
&& DosLoadModule(fail, sizeof fail, basename, &handle) != 0 )
die_with("Can't load DLL ", buf, "", "");
if (rc_fullname)
return handle; /* was loaded with short name; all is fine */
if (DosQueryProcAddr(handle, 0, "fill_extLibpath", (PFN*)&f))
die_with(buf, ": DLL exports no symbol ", "fill_extLibpath", "");
buf[dirl] = 0;
if (f(0 /*BEGINLIBPATH*/, buf /* prepend */, NULL /* append */,
0 /* keep old value */, me))
die_with(me, ": prepending BEGINLIBPATH", "", "");
if (DosLoadModule(fail, sizeof fail, basename, &handle1) != 0)
die_with(me, ": finding perl DLL again via BEGINLIBPATH", "", "");
buf[dirl] = '\\';
if (handle1 != handle) {
if (DosQueryModuleName(handle1, sizeof(fail), fail))
strcpy(fail, "???");
die_with(buf, ":\n\tperl DLL via BEGINLIBPATH is different: \n\t",
fail,
"\n\tYou may need to manipulate global BEGINLIBPATH and LIBPATHSTRICT"
"\n\tso that the other copy is loaded via BEGINLIBPATH.");
}
return handle;
}
int
main(int argc, char **argv, char **env)
{
main_t f;
handler_t h;
me = argv[0];
/**/
handle = load_perl_dll(PERL_DLL_BASENAME);
if (DosQueryProcAddr(handle, 0, "Perl_OS2_handler_install", (PFN*)&h))
die_with(PERL_DLL_BASENAME, ": DLL exports no symbol ", "Perl_OS2_handler_install", "");
if ( !h((void *)"~installprefix", Perlos2_handler_perllib_from)
|| !h((void *)"~dll", Perlos2_handler_perllib_to)
|| !h((void *)"~dll/sh/ksh.exe", Perlos2_handler_perl_sh) )
die_with(PERL_DLL_BASENAME, ": Can't install @INC manglers", "", "");
if (DosQueryProcAddr(handle, 0, "dll_perlmain", (PFN*)&f))
die_with(PERL_DLL_BASENAME, ": DLL exports no symbol ", "dll_perlmain", "");
return f(argc, argv, env);
}
=head1 Build FAQ
=head2 Some C</> became C<\> in pdksh.
You have a very old pdksh. See L</Prerequisites>.
=head2 C<'errno'> - unresolved external
You do not have MT-safe F<db.lib>. See L</Prerequisites>.
=head2 Problems with tr or sed
reported with very old version of tr and sed.
=head2 Some problem (forget which ;-)
You have an older version of F<perl.dll> on your LIBPATH, which
broke the build of extensions.
=head2 Library ... not found
You did not run C<omflibs>. See L</Prerequisites>.
=head2 Segfault in make
You use an old version of GNU make. See L</Prerequisites>.
=head2 op/sprintf test failure
This can result from a bug in emx sprintf which was fixed in 0.9d fix 03.
=head1 Specific (mis)features of OS/2 port
=head2 C<setpriority>, C<getpriority>
Note that these functions are compatible with *nix, not with the older
ports of '94 - 95. The priorities are absolute, go from 32 to -95,
lower is quicker. 0 is the default priority.
B<WARNING>. Calling C<getpriority> on a non-existing process could lock
the system before Warp3 fixpak22. Starting with Warp3, Perl will use
a workaround: it aborts getpriority() if the process is not present.
This is not possible on older versions C<2.*>, and has a race
condition anyway.
=head2 C<system()>
Multi-argument form of C<system()> allows an additional numeric
argument. The meaning of this argument is described in
L<OS2::Process>.
When finding a program to run, Perl first asks the OS to look for executables
on C<PATH> (OS/2 adds extension F<.exe> if no extension is present).
If not found, it looks for a script with possible extensions
added in this order: no extension, F<.cmd>, F<.btm>,
F<.bat>, F<.pl>. If found, Perl checks the start of the file for magic
strings C<"#!"> and C<"extproc ">. If found, Perl uses the rest of the
first line as the beginning of the command line to run this script. The
only mangling done to the first line is extraction of arguments (currently
up to 3), and ignoring of the path-part of the "interpreter" name if it can't
be found using the full path.
E.g., C<system 'foo', 'bar', 'baz'> may lead Perl to finding
F<C:/emx/bin/foo.cmd> with the first line being
extproc /bin/bash -x -c
If F</bin/bash.exe> is not found, then Perl looks for an executable F<bash.exe> on
C<PATH>. If found in F<C:/emx.add/bin/bash.exe>, then the above system() is
translated to
system qw(C:/emx.add/bin/bash.exe -x -c C:/emx/bin/foo.cmd bar baz)
One additional translation is performed: instead of F</bin/sh> Perl uses
the hardwired-or-customized shell (see C<L<"PERL_SH_DIR">>).
The above search for "interpreter" is recursive: if F<bash> executable is not
found, but F<bash.btm> is found, Perl will investigate its first line etc.
The only hardwired limit on the recursion depth is implicit: there is a limit
4 on the number of additional arguments inserted before the actual arguments
given to system(). In particular, if no additional arguments are specified
on the "magic" first lines, then the limit on the depth is 4.
If Perl finds that the found executable is of PM type when the
current session is not, it will start the new process in a separate session of
necessary type. Call via C<OS2::Process> to disable this magic.
B<WARNING>. Due to the described logic, you need to explicitly
specify F<.com> extension if needed. Moreover, if the executable
F<perl5.6.1> is requested, Perl will not look for F<perl5.6.1.exe>.
[This may change in the future.]
=head2 C<extproc> on the first line
If the first chars of a Perl script are C<"extproc ">, this line is treated
as C<#!>-line, thus all the switches on this line are processed (twice
if script was started via cmd.exe). See L<perlrun/DESCRIPTION>.
=head2 Additional modules:
L<OS2::Process>, L<OS2::DLL>, L<OS2::REXX>, L<OS2::PrfDB>, L<OS2::ExtAttr>. These
modules provide access to additional numeric argument for C<system>
and to the information about the running process,
to DLLs having functions with REXX signature and to the REXX runtime, to
OS/2 databases in the F<.INI> format, and to Extended Attributes.
Two additional extensions by Andreas Kaiser, C<OS2::UPM>, and
C<OS2::FTP>, are included into C<ILYAZ> directory, mirrored on CPAN.
Other OS/2-related extensions are available too.
=head2 Prebuilt methods:
=over 4
=item C<File::Copy::syscopy>
used by C<File::Copy::copy>, see L<File::Copy>.
=item C<DynaLoader::mod2fname>
used by C<DynaLoader> for DLL name mangling.
=item C<Cwd::current_drive()>
Self explanatory.
=item C<Cwd::sys_chdir(name)>
leaves drive as it is.
=item C<Cwd::change_drive(name)>
changes the "current" drive.
=item C<Cwd::sys_is_absolute(name)>
means has drive letter and is_rooted.
=item C<Cwd::sys_is_rooted(name)>
means has leading C<[/\\]> (maybe after a drive-letter:).
=item C<Cwd::sys_is_relative(name)>
means changes with current dir.
=item C<Cwd::sys_cwd(name)>
Interface to cwd from EMX. Used by C<Cwd::cwd>.
=item C<Cwd::sys_abspath(name, dir)>
Really really odious function to implement. Returns absolute name of
file which would have C<name> if CWD were C<dir>. C<Dir> defaults to the
current dir.
=item C<Cwd::extLibpath([type])>
Get current value of extended library search path. If C<type> is
present and positive, works with C<END_LIBPATH>, if negative, works
with C<LIBPATHSTRICT>, otherwise with C<BEGIN_LIBPATH>.
=item C<Cwd::extLibpath_set( path [, type ] )>
Set current value of extended library search path. If C<type> is
present and positive, works with <END_LIBPATH>, if negative, works
with C<LIBPATHSTRICT>, otherwise with C<BEGIN_LIBPATH>.
=item C<OS2::Error(do_harderror,do_exception)>
Returns C<undef> if it was not called yet, otherwise bit 1 is
set if on the previous call do_harderror was enabled, bit
2 is set if on previous call do_exception was enabled.
This function enables/disables error popups associated with
hardware errors (Disk not ready etc.) and software exceptions.
I know of no way to find out the state of popups I<before> the first call
to this function.
=item C<OS2::Errors2Drive(drive)>
Returns C<undef> if it was not called yet, otherwise return false if errors
were not requested to be written to a hard drive, or the drive letter if
this was requested.
This function may redirect error popups associated with hardware errors
(Disk not ready etc.) and software exceptions to the file POPUPLOG.OS2 at
the root directory of the specified drive. Overrides OS2::Error() specified
by individual programs. Given argument undef will disable redirection.
Has global effect, persists after the application exits.
I know of no way to find out the state of redirection of popups to the disk
I<before> the first call to this function.
=item OS2::SysInfo()
Returns a hash with system information. The keys of the hash are
MAX_PATH_LENGTH, MAX_TEXT_SESSIONS, MAX_PM_SESSIONS,
MAX_VDM_SESSIONS, BOOT_DRIVE, DYN_PRI_VARIATION,
MAX_WAIT, MIN_SLICE, MAX_SLICE, PAGE_SIZE,
VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION,
MS_COUNT, TIME_LOW, TIME_HIGH, TOTPHYSMEM, TOTRESMEM,
TOTAVAILMEM, MAXPRMEM, MAXSHMEM, TIMER_INTERVAL,
MAX_COMP_LENGTH, FOREGROUND_FS_SESSION,
FOREGROUND_PROCESS
=item OS2::BootDrive()
Returns a letter without colon.
=item C<OS2::MorphPM(serve)>, C<OS2::UnMorphPM(serve)>
Transforms the current application into a PM application and back.
The argument true means that a real message loop is going to be served.
OS2::MorphPM() returns the PM message queue handle as an integer.
See L<"Centralized management of resources"> for additional details.
=item C<OS2::Serve_Messages(force)>
Fake on-demand retrieval of outstanding PM messages. If C<force> is false,
will not dispatch messages if a real message loop is known to
be present. Returns number of messages retrieved.
Dies with "QUITing..." if WM_QUIT message is obtained.
=item C<OS2::Process_Messages(force [, cnt])>
Retrieval of PM messages until window creation/destruction.
If C<force> is false, will not dispatch messages if a real message loop
is known to be present.
Returns change in number of windows. If C<cnt> is given,
it is incremented by the number of messages retrieved.
Dies with "QUITing..." if WM_QUIT message is obtained.
=item C<OS2::_control87(new,mask)>
the same as L<_control87(3)> of EMX. Takes integers as arguments, returns
the previous coprocessor control word as an integer. Only bits in C<new> which
are present in C<mask> are changed in the control word.
=item OS2::get_control87()
gets the coprocessor control word as an integer.
=item C<OS2::set_control87_em(new=MCW_EM,mask=MCW_EM)>
The variant of OS2::_control87() with default values good for
handling exception mask: if no C<mask>, uses exception mask part of C<new>
only. If no C<new>, disables all the floating point exceptions.
See L<"Misfeatures"> for details.
=item C<OS2::DLLname([how [, \&xsub]])>
Gives the information about the Perl DLL or the DLL containing the C
function bound to by C<&xsub>. The meaning of C<how> is: default (2):
full name; 0: handle; 1: module name.
=back
(Note that some of these may be moved to different libraries -
eventually).
=head2 Prebuilt variables:
=over 4
=item $OS2::emx_rev
numeric value is the same as _emx_rev of EMX, a string value the same
as _emx_vprt (similar to C<0.9c>).
=item $OS2::emx_env
same as _emx_env of EMX, a number similar to 0x8001.
=item $OS2::os_ver
a number C<OS_MAJOR + 0.001 * OS_MINOR>.
=item $OS2::is_aout
true if the Perl library was compiled in AOUT format.
=item $OS2::can_fork
true if the current executable is an AOUT EMX executable, so Perl can
fork. Do not use this, use the portable check for
$Config::Config{dfork}.
=item $OS2::nsyserror
This variable (default is 1) controls whether to enforce the contents
of $^E to start with C<SYS0003>-like id. If set to 0, then the string
value of $^E is what is available from the OS/2 message file. (Some
messages in this file have an C<SYS0003>-like id prepended, some not.)
=back
=head2 Misfeatures
=over 4
=item *
Since L<flock(3)> is present in EMX, but is not functional, it is
emulated by perl. To disable the emulations, set environment variable
C<USE_PERL_FLOCK=0>.
=item *
Here is the list of things which may be "broken" on
EMX (from EMX docs):
=over 4
=item *
The functions L<recvmsg(3)>, L<sendmsg(3)>, and L<socketpair(3)> are not
implemented.
=item *
L<sock_init(3)> is not required and not implemented.
=item *
L<flock(3)> is not yet implemented (dummy function). (Perl has a workaround.)
=item *
L<kill(3)>: Special treatment of PID=0, PID=1 and PID=-1 is not implemented.
=item *
L<waitpid(3)>:
WUNTRACED
Not implemented.
waitpid() is not implemented for negative values of PID.
=back
Note that C<kill -9> does not work with the current version of EMX.
=item *
See L<"Text-mode filehandles">.
=item *
Unix-domain sockets on OS/2 live in a pseudo-file-system C</sockets/...>.
To avoid a failure to create a socket with a name of a different form,
C<"/socket/"> is prepended to the socket name (unless it starts with this
already).
This may lead to problems later in case the socket is accessed via the
"usual" file-system calls using the "initial" name.
=item *
Apparently, IBM used a compiler (for some period of time around '95?) which
changes FP mask right and left. This is not I<that> bad for IBM's
programs, but the same compiler was used for DLLs which are used with
general-purpose applications. When these DLLs are used, the state of
floating-point flags in the application is not predictable.
What is much worse, some DLLs change the floating point flags when in
_DLLInitTerm() (e.g., F<TCP32IP>). This means that even if you do not I<call>
any function in the DLL, just the act of loading this DLL will reset your
flags. What is worse, the same compiler was used to compile some HOOK DLLs.
Given that HOOK dlls are executed in the context of I<all> the applications
in the system, this means a complete unpredictability of floating point
flags on systems using such HOOK DLLs. E.g., F<GAMESRVR.DLL> of B<DIVE>
origin changes the floating point flags on each write to the TTY of a VIO
(windowed text-mode) applications.
Some other (not completely debugged) situations when FP flags change include
some video drivers (?), and some operations related to creation of the windows.
People who code B<OpenGL> may have more experience on this.
Perl is generally used in the situation when all the floating-point
exceptions are ignored, as is the default under EMX. If they are not ignored,
some benign Perl programs would get a C<SIGFPE> and would die a horrible death.
To circumvent this, Perl uses two hacks. They help against I<one> type of
damage only: FP flags changed when loading a DLL.
One of the hacks is to disable floating point exceptions on Perl startup (as
is the default with EMX). This helps only with compile-time-linked DLLs
changing the flags before main() had a chance to be called.
The other hack is to restore FP flags after a call to dlopen(). This helps
against similar damage done by DLLs _DLLInitTerm() at runtime. Currently
no way to switch these hacks off is provided.
=back
=head2 Modifications
Perl modifies some standard C library calls in the following ways:
=over 9
=item C<popen>
C<my_popen> uses F<sh.exe> if shell is required, cf. L<"PERL_SH_DIR">.
=item C<tmpnam>
is created using C<TMP> or C<TEMP> environment variable, via
C<tempnam>.
=item C<tmpfile>
If the current directory is not writable, file is created using modified
C<tmpnam>, so there may be a race condition.
=item C<ctermid>
a dummy implementation.
=item C<stat>
C<os2_stat> special-cases F</dev/tty> and F</dev/con>.
=item C<mkdir>, C<rmdir>
these EMX functions do not work if the path contains a trailing C</>.
Perl contains a workaround for this.
=item C<flock>
Since L<flock(3)> is present in EMX, but is not functional, it is
emulated by perl. To disable the emulations, set environment variable
C<USE_PERL_FLOCK=0>.
=back
=head2 Identifying DLLs
All the DLLs built with the current versions of Perl have ID strings
identifying the name of the extension, its version, and the version
of Perl required for this DLL. Run C<bldlevel DLL-name> to find this
info.
=head2 Centralized management of resources
Since to call certain OS/2 API one needs to have a correctly initialized
C<Win> subsystem, OS/2-specific extensions may require getting C<HAB>s and
C<HMQ>s. If an extension would do it on its own, another extension could
fail to initialize.
Perl provides a centralized management of these resources:
=over
=item C<HAB>
To get the HAB, the extension should call C<hab = perl_hab_GET()> in C. After
this call is performed, C<hab> may be accessed as C<Perl_hab>. There is
no need to release the HAB after it is used.
If by some reasons F<perl.h> cannot be included, use
extern int Perl_hab_GET(void);
instead.
=item C<HMQ>
There are two cases:
=over
=item *
the extension needs an C<HMQ> only because some API will not work otherwise.
Use C<serve = 0> below.
=item *
the extension needs an C<HMQ> since it wants to engage in a PM event loop.
Use C<serve = 1> below.
=back
To get an C<HMQ>, the extension should call C<hmq = perl_hmq_GET(serve)> in C.
After this call is performed, C<hmq> may be accessed as C<Perl_hmq>.
To signal to Perl that HMQ is not needed any more, call
C<perl_hmq_UNSET(serve)>. Perl process will automatically morph/unmorph itself
into/from a PM process if HMQ is needed/not-needed. Perl will automatically
enable/disable C<WM_QUIT> message during shutdown if the message queue is
served/not-served.
B<NOTE>. If during a shutdown there is a message queue which did not disable
WM_QUIT, and which did not process the received WM_QUIT message, the
shutdown will be automatically cancelled. Do not call C<perl_hmq_GET(1)>
unless you are going to process messages on an orderly basis.
=item Treating errors reported by OS/2 API
There are two principal conventions (it is useful to call them C<Dos*>
and C<Win*> - though this part of the function signature is not always
determined by the name of the API) of reporting the error conditions
of OS/2 API. Most of C<Dos*> APIs report the error code as the result
of the call (so 0 means success, and there are many types of errors).
Most of C<Win*> API report success/fail via the result being
C<TRUE>/C<FALSE>; to find the reason for the failure one should call
WinGetLastError() API.
Some C<Win*> entry points also overload a "meaningful" return value
with the error indicator; having a 0 return value indicates an error.
Yet some other C<Win*> entry points overload things even more, and 0
return value may mean a successful call returning a valid value 0, as
well as an error condition; in the case of a 0 return value one should
call WinGetLastError() API to distinguish a successful call from a
failing one.
By convention, all the calls to OS/2 API should indicate their
failures by resetting $^E. All the Perl-accessible functions which
call OS/2 API may be broken into two classes: some die()s when an API
error is encountered, the other report the error via a false return
value (of course, this does not concern Perl-accessible functions
which I<expect> a failure of the OS/2 API call, having some workarounds
coded).
Obviously, in the situation of the last type of the signature of an OS/2
API, it is must more convenient for the users if the failure is
indicated by die()ing: one does not need to check $^E to know that
something went wrong. If, however, this solution is not desirable by
some reason, the code in question should reset $^E to 0 before making
this OS/2 API call, so that the caller of this Perl-accessible
function has a chance to distinguish a success-but-0-return value from
a failure. (One may return undef as an alternative way of reporting
an error.)
The macros to simplify this type of error propagation are
=over
=item C<CheckOSError(expr)>
Returns true on error, sets $^E. Expects expr() be a call of
C<Dos*>-style API.
=item C<CheckWinError(expr)>
Returns true on error, sets $^E. Expects expr() be a call of
C<Win*>-style API.
=item C<SaveWinError(expr)>
Returns C<expr>, sets $^E from WinGetLastError() if C<expr> is false.
=item C<SaveCroakWinError(expr,die,name1,name2)>
Returns C<expr>, sets $^E from WinGetLastError() if C<expr> is false,
and die()s if C<die> and $^E are true. The message to die is the
concatenated strings C<name1> and C<name2>, separated by C<": "> from
the contents of $^E.
=item C<WinError_2_Perl_rc>
Sets C<Perl_rc> to the return value of WinGetLastError().
=item C<FillWinError>
Sets C<Perl_rc> to the return value of WinGetLastError(), and sets $^E
to the corresponding value.
=item C<FillOSError(rc)>
Sets C<Perl_rc> to C<rc>, and sets $^E to the corresponding value.
=back
=item Loading DLLs and ordinals in DLLs
Some DLLs are only present in some versions of OS/2, or in some
configurations of OS/2. Some exported entry points are present only
in DLLs shipped with some versions of OS/2. If these DLLs and entry
points were linked directly for a Perl executable/DLL or from a Perl
extensions, this binary would work only with the specified
versions/setups. Even if these entry points were not needed, the
I<load> of the executable (or DLL) would fail.
For example, many newer useful APIs are not present in OS/2 v2; many
PM-related APIs require DLLs not available on floppy-boot setup.
To make these calls fail I<only when the calls are executed>, one
should call these API via a dynamic linking API. There is a subsystem
in Perl to simplify such type of calls. A large number of entry
points available for such linking is provided (see C<entries_ordinals>
- and also C<PMWIN_entries> - in F<os2ish.h>). These ordinals can be
accessed via the APIs:
CallORD(), DeclFuncByORD(), DeclVoidFuncByORD(),
DeclOSFuncByORD(), DeclWinFuncByORD(), AssignFuncPByORD(),
DeclWinFuncByORD_CACHE(), DeclWinFuncByORD_CACHE_survive(),
DeclWinFuncByORD_CACHE_resetError_survive(),
DeclWinFunc_CACHE(), DeclWinFunc_CACHE_resetError(),
DeclWinFunc_CACHE_survive(), DeclWinFunc_CACHE_resetError_survive()
See the header files and the C code in the supplied OS/2-related
modules for the details on usage of these functions.
Some of these functions also combine dynaloading semantic with the
error-propagation semantic discussed above.
=back
=head1 Perl flavors
Because of idiosyncrasies of OS/2 one cannot have all the eggs in the
same basket (though EMX environment tries hard to overcome this
limitations, so the situation may somehow improve). There are 4
executables for Perl provided by the distribution:
=head2 F<perl.exe>
The main workhorse. This is a chimera executable: it is compiled as an
C<a.out>-style executable, but is linked with C<omf>-style dynamic
library F<perl.dll>, and with dynamic CRT DLL. This executable is a
VIO application.
It can load perl dynamic extensions, and it can fork().
B<Note.> Keep in mind that fork() is needed to open a pipe to yourself.
=head2 F<perl_.exe>
This is a statically linked C<a.out>-style executable. It cannot
load dynamic Perl extensions. The executable supplied in binary
distributions has a lot of extensions prebuilt, thus the above restriction is
important only if you use custom-built extensions. This executable is a VIO
application.
I<This is the only executable with does not require OS/2.> The
friends locked into C<M$> world would appreciate the fact that this
executable runs under DOS, Win0.3*, Win0.95 and WinNT with an
appropriate extender. See L<"Other OSes">.
=head2 F<perl__.exe>
This is the same executable as F<perl___.exe>, but it is a PM
application.
B<Note.> Usually (unless explicitly redirected during the startup)
STDIN, STDERR, and STDOUT of a PM
application are redirected to F<nul>. However, it is possible to I<see>
them if you start C<perl__.exe> from a PM program which emulates a
console window, like I<Shell mode> of Emacs or EPM. Thus it I<is
possible> to use Perl debugger (see L<perldebug>) to debug your PM
application (but beware of the message loop lockups - this will not
work if you have a message queue to serve, unless you hook the serving
into the getc() function of the debugger).
Another way to see the output of a PM program is to run it as
pm_prog args 2>&1 | cat -
with a shell I<different> from F<cmd.exe>, so that it does not create
a link between a VIO session and the session of C<pm_porg>. (Such a link
closes the VIO window.) E.g., this works with F<sh.exe> - or with Perl!
open P, 'pm_prog args 2>&1 |' or die;
print while <P>;
The flavor F<perl__.exe> is required if you want to start your program without
a VIO window present, but not C<detach>ed (run C<help detach> for more info).
Very useful for extensions which use PM, like C<Perl/Tk> or C<OpenGL>.
Note also that the differences between PM and VIO executables are only
in the I<default> behaviour. One can start I<any> executable in
I<any> kind of session by using the arguments C</fs>, C</pm> or
C</win> switches of the command C<start> (of F<CMD.EXE> or a similar
shell). Alternatively, one can use the numeric first argument of the
C<system> Perl function (see L<OS2::Process>).
=head2 F<perl___.exe>
This is an C<omf>-style executable which is dynamically linked to
F<perl.dll> and CRT DLL. I know no advantages of this executable
over C<perl.exe>, but it cannot fork() at all. Well, one advantage is
that the build process is not so convoluted as with C<perl.exe>.
It is a VIO application.
=head2 Why strange names?
Since Perl processes the C<#!>-line (cf.
L<perlrun/DESCRIPTION>, L<perlrun/Command Switches>,
L<perldiag/"No Perl script found in input">), it should know when a
program I<is a Perl>. There is some naming convention which allows
Perl to distinguish correct lines from wrong ones. The above names are
almost the only names allowed by this convention which do not contain
digits (which have absolutely different semantics).
=head2 Why dynamic linking?
Well, having several executables dynamically linked to the same huge
library has its advantages, but this would not substantiate the
additional work to make it compile. The reason is the complicated-to-developers
but very quick and convenient-to-users "hard" dynamic linking used by OS/2.
There are two distinctive features of the dyna-linking model of OS/2:
first, all the references to external functions are resolved at the compile time;
second, there is no runtime fixup of the DLLs after they are loaded into memory.
The first feature is an enormous advantage over other models: it avoids
conflicts when several DLLs used by an application export entries with
the same name. In such cases "other" models of dyna-linking just choose
between these two entry points using some random criterion - with predictable
disasters as results. But it is the second feature which requires the build
of F<perl.dll>.
The address tables of DLLs are patched only once, when they are
loaded. The addresses of the entry points into DLLs are guaranteed to be
the same for all the programs which use the same DLL. This removes the
runtime fixup - once DLL is loaded, its code is read-only.
While this allows some (significant?) performance advantages, this makes life
much harder for developers, since the above scheme makes it impossible
for a DLL to be "linked" to a symbol in the F<.EXE> file. Indeed, this
would need a DLL to have different relocations tables for the
(different) executables which use this DLL.
However, a dynamically loaded Perl extension is forced to use some symbols
from the perl
executable, e.g., to know how to find the arguments to the functions:
the arguments live on the perl
internal evaluation stack. The solution is to put the main code of
the interpreter into a DLL, and make the F<.EXE> file which just loads
this DLL into memory and supplies command-arguments. The extension DLL
cannot link to symbols in F<.EXE>, but it has no problem linking
to symbols in the F<.DLL>.
This I<greatly> increases the load time for the application (as well as
complexity of the compilation). Since interpreter is in a DLL,
the C RTL is basically forced to reside in a DLL as well (otherwise
extensions would not be able to use CRT). There are some advantages if
you use different flavors of perl, such as running F<perl.exe> and
F<perl__.exe> simultaneously: they share the memory of F<perl.dll>.
B<NOTE>. There is one additional effect which makes DLLs more wasteful:
DLLs are loaded in the shared memory region, which is a scarse resource
given the 512M barrier of the "standard" OS/2 virtual memory. The code of
F<.EXE> files is also shared by all the processes which use the particular
F<.EXE>, but they are "shared in the private address space of the process";
this is possible because the address at which different sections
of the F<.EXE> file are loaded is decided at compile-time, thus all the
processes have these sections loaded at same addresses, and no fixup
of internal links inside the F<.EXE> is needed.
Since DLLs may be loaded at run time, to have the same mechanism for DLLs
one needs to have the address range of I<any of the loaded> DLLs in the
system to be available I<in all the processes> which did not load a particular
DLL yet. This is why the DLLs are mapped to the shared memory region.
=head2 Why chimera build?
Current EMX environment does not allow DLLs compiled using Unixish
C<a.out> format to export symbols for data (or at least some types of
data). This forces C<omf>-style compile of F<perl.dll>.
Current EMX environment does not allow F<.EXE> files compiled in
C<omf> format to fork(). fork() is needed for exactly three Perl
operations:
=over 4
=item *
explicit fork() in the script,
=item *
C<open FH, "|-">
=item *
C<open FH, "-|">, in other words, opening pipes to itself.
=back
While these operations are not questions of life and death, they are
needed for a lot of
useful scripts. This forces C<a.out>-style compile of
F<perl.exe>.
=head1 ENVIRONMENT
Here we list environment variables with are either OS/2- and DOS- and
Win*-specific, or are more important under OS/2 than under other OSes.
=head2 C<PERLLIB_PREFIX>
Specific for EMX port. Should have the form
path1;path2
or
path1 path2
If the beginning of some prebuilt path matches F<path1>, it is
substituted with F<path2>.
Should be used if the perl library is moved from the default
location in preference to C<PERL(5)LIB>, since this would not leave wrong
entries in @INC. For example, if the compiled version of perl looks for @INC
in F<f:/perllib/lib>, and you want to install the library in
F<h:/opt/gnu>, do
set PERLLIB_PREFIX=f:/perllib/lib;h:/opt/gnu
This will cause Perl with the prebuilt @INC of
f:/perllib/lib/5.00553/os2
f:/perllib/lib/5.00553
f:/perllib/lib/site_perl/5.00553/os2
f:/perllib/lib/site_perl/5.00553
.
to use the following @INC:
h:/opt/gnu/5.00553/os2
h:/opt/gnu/5.00553
h:/opt/gnu/site_perl/5.00553/os2
h:/opt/gnu/site_perl/5.00553
.
=head2 C<PERL_BADLANG>
If 0, perl ignores setlocale() failing. May be useful with some
strange I<locale>s.
=head2 C<PERL_BADFREE>
If 0, perl would not warn of in case of unwarranted free(). With older
perls this might be
useful in conjunction with the module DB_File, which was buggy when
dynamically linked and OMF-built.
Should not be set with newer Perls, since this may hide some I<real> problems.
=head2 C<PERL_SH_DIR>
Specific for EMX port. Gives the directory part of the location for
F<sh.exe>.
=head2 C<USE_PERL_FLOCK>
Specific for EMX port. Since L<flock(3)> is present in EMX, but is not
functional, it is emulated by perl. To disable the emulations, set
environment variable C<USE_PERL_FLOCK=0>.
=head2 C<TMP> or C<TEMP>
Specific for EMX port. Used as storage place for temporary files.
=head1 Evolution
Here we list major changes which could make you by surprise.
=head2 Text-mode filehandles
Starting from version 5.8, Perl uses a builtin translation layer for
text-mode files. This replaces the efficient well-tested EMX layer by
some code which should be best characterized as a "quick hack".
In addition to possible bugs and an inability to follow changes to the
translation policy with off/on switches of TERMIO translation, this
introduces a serious incompatible change: before sysread() on
text-mode filehandles would go through the translation layer, now it
would not.
=head2 Priorities
C<setpriority> and C<getpriority> are not compatible with earlier
ports by Andreas Kaiser. See C<"setpriority, getpriority">.
=head2 DLL name mangling: pre 5.6.2
With the release 5.003_01 the dynamically loadable libraries
should be rebuilt when a different version of Perl is compiled. In particular,
DLLs (including F<perl.dll>) are now created with the names
which contain a checksum, thus allowing workaround for OS/2 scheme of
caching DLLs.
It may be possible to code a simple workaround which would
=over
=item *
find the old DLLs looking through the old @INC;
=item *
mangle the names according to the scheme of new perl and copy the DLLs to
these names;
=item *
edit the internal C<LX> tables of DLL to reflect the change of the name
(probably not needed for Perl extension DLLs, since the internally coded names
are not used for "specific" DLLs, they used only for "global" DLLs).
=item *
edit the internal C<IMPORT> tables and change the name of the "old"
F<perl????.dll> to the "new" F<perl????.dll>.
=back
=head2 DLL name mangling: 5.6.2 and beyond
In fact mangling of I<extension> DLLs was done due to misunderstanding
of the OS/2 dynaloading model. OS/2 (effectively) maintains two
different tables of loaded DLL:
=over
=item Global DLLs
those loaded by the base name from C<LIBPATH>; including those
associated at link time;
=item specific DLLs
loaded by the full name.
=back
When resolving a request for a global DLL, the table of already-loaded
specific DLLs is (effectively) ignored; moreover, specific DLLs are
I<always> loaded from the prescribed path.
There is/was a minor twist which makes this scheme fragile: what to do
with DLLs loaded from
=over
=item C<BEGINLIBPATH> and C<ENDLIBPATH>
(which depend on the process)
=item F<.> from C<LIBPATH>
which I<effectively> depends on the process (although C<LIBPATH> is the
same for all the processes).
=back
Unless C<LIBPATHSTRICT> is set to C<T> (and the kernel is after
2000/09/01), such DLLs are considered to be global. When loading a
global DLL it is first looked in the table of already-loaded global
DLLs. Because of this the fact that one executable loaded a DLL from
C<BEGINLIBPATH> and C<ENDLIBPATH>, or F<.> from C<LIBPATH> may affect
I<which> DLL is loaded when I<another> executable requests a DLL with
the same name. I<This> is the reason for version-specific mangling of
the DLL name for perl DLL.
Since the Perl extension DLLs are always loaded with the full path,
there is no need to mangle their names in a version-specific ways:
their directory already reflects the corresponding version of perl,
and @INC takes into account binary compatibility with older version.
Starting from C<5.6.2> the name mangling scheme is fixed to be the
same as for Perl 5.005_53 (same as in a popular binary release). Thus
new Perls will be able to I<resolve the names> of old extension DLLs
if @INC allows finding their directories.
However, this still does not guarantee that these DLL may be loaded.
The reason is the mangling of the name of the I<Perl DLL>. And since
the extension DLLs link with the Perl DLL, extension DLLs for older
versions would load an older Perl DLL, and would most probably
segfault (since the data in this DLL is not properly initialized).
There is a partial workaround (which can be made complete with newer
OS/2 kernels): create a forwarder DLL with the same name as the DLL of
the older version of Perl, which forwards the entry points to the
newer Perl's DLL. Make this DLL accessible on (say) the C<BEGINLIBPATH> of
the new Perl executable. When the new executable accesses old Perl's
extension DLLs, they would request the old Perl's DLL by name, get the
forwarder instead, so effectively will link with the currently running
(new) Perl DLL.
This may break in two ways:
=over
=item *
Old perl executable is started when a new executable is running has
loaded an extension compiled for the old executable (ouph!). In this
case the old executable will get a forwarder DLL instead of the old
perl DLL, so would link with the new perl DLL. While not directly
fatal, it will behave the same as new executable. This beats the whole
purpose of explicitly starting an old executable.
=item *
A new executable loads an extension compiled for the old executable
when an old perl executable is running. In this case the extension
will not pick up the forwarder - with fatal results.
=back
With support for C<LIBPATHSTRICT> this may be circumvented - unless
one of DLLs is started from F<.> from C<LIBPATH> (I do not know
whether C<LIBPATHSTRICT> affects this case).
B<REMARK>. Unless newer kernels allow F<.> in C<BEGINLIBPATH> (older
do not), this mess cannot be completely cleaned. (It turns out that
as of the beginning of 2002, F<.> is not allowed, but F<.\.> is - and
it has the same effect.)
B<REMARK>. C<LIBPATHSTRICT>, C<BEGINLIBPATH> and C<ENDLIBPATH> are
not environment variables, although F<cmd.exe> emulates them on C<SET
...> lines. From Perl they may be accessed by
L<Cwd::extLibpath|/Cwd::extLibpath([type])> and
L<Cwd::extLibpath_set|/Cwd::extLibpath_set( path [, type ] )>.
=head2 DLL forwarder generation
Assume that the old DLL is named F<perlE0AC.dll> (as is one for
5.005_53), and the new version is 5.6.1. Create a file
F<perl5shim.def-leader> with
LIBRARY 'perlE0AC' INITINSTANCE TERMINSTANCE
DESCRIPTION '@#perl5-porters@perl.org:5.006001#@ Perl module for 5.00553 -> Perl 5.6.1 forwarder'
CODE LOADONCALL
DATA LOADONCALL NONSHARED MULTIPLE
EXPORTS
modifying the versions/names as needed. Run
perl -wnle "next if 0../EXPORTS/; print qq( \"$1\") if /\"(\w+)\"/" perl5.def >lst
in the Perl build directory (to make the DLL smaller replace perl5.def
with the definition file for the older version of Perl if present).
cat perl5shim.def-leader lst >perl5shim.def
gcc -Zomf -Zdll -o perlE0AC.dll perl5shim.def -s -llibperl
(ignore multiple C<warning L4085>).
=head2 Threading
As of release 5.003_01 perl is linked to multithreaded C RTL
DLL. If perl itself is not compiled multithread-enabled, so will not be perl's
malloc(). However, extensions may use multiple thread on their own
risk.
This was needed to compile C<Perl/Tk> for XFree86-OS/2 out-of-the-box, and
link with DLLs for other useful libraries, which typically are compiled
with C<-Zmt -Zcrtdll>.
=head2 Calls to external programs
Due to a popular demand the perl external program calling has been
changed wrt Andreas Kaiser's port. I<If> perl needs to call an
external program I<via shell>, the F<f:/bin/sh.exe> will be called, or
whatever is the override, see L<"PERL_SH_DIR">.
Thus means that you need to get some copy of a F<sh.exe> as well (I
use one from pdksh). The path F<F:/bin> above is set up automatically during
the build to a correct value on the builder machine, but is
overridable at runtime,
B<Reasons:> a consensus on C<perl5-porters> was that perl should use
one non-overridable shell per platform. The obvious choices for OS/2
are F<cmd.exe> and F<sh.exe>. Having perl build itself would be impossible
with F<cmd.exe> as a shell, thus I picked up C<sh.exe>. This assures almost
100% compatibility with the scripts coming from *nix. As an added benefit
this works as well under DOS if you use DOS-enabled port of pdksh
(see L</Prerequisites>).
B<Disadvantages:> currently F<sh.exe> of pdksh calls external programs
via fork()/exec(), and there is I<no> functioning exec() on
OS/2. exec() is emulated by EMX by an asynchronous call while the caller
waits for child completion (to pretend that the C<pid> did not change). This
means that 1 I<extra> copy of F<sh.exe> is made active via fork()/exec(),
which may lead to some resources taken from the system (even if we do
not count extra work needed for fork()ing).
Note that this a lesser issue now when we do not spawn F<sh.exe>
unless needed (metachars found).
One can always start F<cmd.exe> explicitly via
system 'cmd', '/c', 'mycmd', 'arg1', 'arg2', ...
If you need to use F<cmd.exe>, and do not want to hand-edit thousands of your
scripts, the long-term solution proposed on p5-p is to have a directive
use OS2::Cmd;
which will override system(), exec(), C<``>, and
C<open(,'...|')>. With current perl you may override only system(),
readpipe() - the explicit version of C<``>, and maybe exec(). The code
will substitute the one-argument call to system() by
C<CORE::system('cmd.exe', '/c', shift)>.
If you have some working code for C<OS2::Cmd>, please send it to me,
I will include it into distribution. I have no need for such a module, so
cannot test it.
For the details of the current situation with calling external programs,
see L<Starting OSE<sol>2 (and DOS) programs under Perl>. Set us mention a couple
of features:
=over 4
=item *
External scripts may be called by their basename. Perl will try the same
extensions as when processing B<-S> command-line switch.
=item *
External scripts starting with C<#!> or C<extproc > will be executed directly,
without calling the shell, by calling the program specified on the rest of
the first line.
=back
=head2 Memory allocation
Perl uses its own malloc() under OS/2 - interpreters are usually malloc-bound
for speed, but perl is not, since its malloc is lightning-fast.
Perl-memory-usage-tuned benchmarks show that Perl's malloc is 5 times quicker
than EMX one. I do not have convincing data about memory footprint, but
a (pretty random) benchmark showed that Perl's one is 5% better.
Combination of perl's malloc() and rigid DLL name resolution creates
a special problem with library functions which expect their return value to
be free()d by system's free(). To facilitate extensions which need to call
such functions, system memory-allocation functions are still available with
the prefix C<emx_> added. (Currently only DLL perl has this, it should
propagate to F<perl_.exe> shortly.)
=head2 Threads
One can build perl with thread support enabled by providing C<-D usethreads>
option to F<Configure>. Currently OS/2 support of threads is very
preliminary.
Most notable problems:
=over 4
=item C<COND_WAIT>
may have a race condition (but probably does not due to edge-triggered
nature of OS/2 Event semaphores). (Needs a reimplementation (in terms of chaining
waiting threads, with the linked list stored in per-thread structure?)?)
=item F<os2.c>
has a couple of static variables used in OS/2-specific functions. (Need to be
moved to per-thread structure, or serialized?)
=back
Note that these problems should not discourage experimenting, since they
have a low probability of affecting small programs.
=head1 BUGS
This description is not updated often (since 5.6.1?), see F<./os2/Changes>
for more info.
=cut
OS/2 extensions
~~~~~~~~~~~~~~~
I include 3 extensions by Andreas Kaiser, OS2::REXX, OS2::UPM, and OS2::FTP,
into my ftp directory, mirrored on CPAN. I made
some minor changes needed to compile them by standard tools. I cannot
test UPM and FTP, so I will appreciate your feedback. Other extensions
there are OS2::ExtAttr, OS2::PrfDB for tied access to EAs and .INI
files - and maybe some other extensions at the time you read it.
Note that OS2 perl defines 2 pseudo-extension functions
OS2::Copy::copy and DynaLoader::mod2fname (many more now, see
L<Prebuilt methods>).
The -R switch of older perl is deprecated. If you need to call a REXX code
which needs access to variables, include the call into a REXX compartment
created by
REXX_call {...block...};
Two new functions are supported by REXX code,
REXX_eval 'string';
REXX_eval_with 'string', REXX_function_name => \&perl_sub_reference;
If you have some other extensions you want to share, send the code to
me. At least two are available: tied access to EA's, and tied access
to system databases.
=head1 AUTHOR
Ilya Zakharevich, cpan@ilyaz.org
=head1 SEE ALSO
perl(1).
=cut
| efortuna/AndroidSDKClone | ndk_experimental/prebuilt/linux-x86_64/lib/perl5/5.16.2/pod/perlos2.pod | Perl | apache-2.0 | 92,706 |
=pod
=head1 NAME
UI, UI_METHOD,
UI_new, UI_new_method, UI_free, UI_add_input_string, UI_dup_input_string,
UI_add_verify_string, UI_dup_verify_string, UI_add_input_boolean,
UI_dup_input_boolean, UI_add_info_string, UI_dup_info_string,
UI_add_error_string, UI_dup_error_string, UI_construct_prompt,
UI_add_user_data, UI_get0_user_data, UI_get0_result, UI_process,
UI_ctrl, UI_set_default_method, UI_get_default_method, UI_get_method,
UI_set_method, UI_OpenSSL, - user interface
=head1 SYNOPSIS
#include <openssl/ui.h>
typedef struct ui_st UI;
typedef struct ui_method_st UI_METHOD;
UI *UI_new(void);
UI *UI_new_method(const UI_METHOD *method);
void UI_free(UI *ui);
int UI_add_input_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize);
int UI_dup_input_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize);
int UI_add_verify_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize, const char *test_buf);
int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize, const char *test_buf);
int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
const char *ok_chars, const char *cancel_chars,
int flags, char *result_buf);
int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
const char *ok_chars, const char *cancel_chars,
int flags, char *result_buf);
int UI_add_info_string(UI *ui, const char *text);
int UI_dup_info_string(UI *ui, const char *text);
int UI_add_error_string(UI *ui, const char *text);
int UI_dup_error_string(UI *ui, const char *text);
char *UI_construct_prompt(UI *ui_method,
const char *object_desc, const char *object_name);
void *UI_add_user_data(UI *ui, void *user_data);
void *UI_get0_user_data(UI *ui);
const char *UI_get0_result(UI *ui, int i);
int UI_process(UI *ui);
int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)());
void UI_set_default_method(const UI_METHOD *meth);
const UI_METHOD *UI_get_default_method(void);
const UI_METHOD *UI_get_method(UI *ui);
const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth);
UI_METHOD *UI_OpenSSL(void);
=head1 DESCRIPTION
UI stands for User Interface, and is general purpose set of routines to
prompt the user for text-based information. Through user-written methods
(see L<ui_create(3)>), prompting can be done in any way
imaginable, be it plain text prompting, through dialog boxes or from a
cell phone.
All the functions work through a context of the type UI. This context
contains all the information needed to prompt correctly as well as a
reference to a UI_METHOD, which is an ordered vector of functions that
carry out the actual prompting.
The first thing to do is to create a UI with UI_new() or UI_new_method(),
then add information to it with the UI_add or UI_dup functions. Also,
user-defined random data can be passed down to the underlying method
through calls to UI_add_user_data. The default UI method doesn't care
about these data, but other methods might. Finally, use UI_process()
to actually perform the prompting and UI_get0_result() to find the result
to the prompt.
A UI can contain more than one prompt, which are performed in the given
sequence. Each prompt gets an index number which is returned by the
UI_add and UI_dup functions, and has to be used to get the corresponding
result with UI_get0_result().
The functions are as follows:
UI_new() creates a new UI using the default UI method. When done with
this UI, it should be freed using UI_free().
UI_new_method() creates a new UI using the given UI method. When done with
this UI, it should be freed using UI_free().
UI_OpenSSL() returns the built-in UI method (note: not the default one,
since the default can be changed. See further on). This method is the
most machine/OS dependent part of OpenSSL and normally generates the
most problems when porting.
UI_free() removes a UI from memory, along with all other pieces of memory
that's connected to it, like duplicated input strings, results and others.
If B<ui> is NULL nothing is done.
UI_add_input_string() and UI_add_verify_string() add a prompt to the UI,
as well as flags and a result buffer and the desired minimum and maximum
sizes of the result, not counting the final NUL character. The given
information is used to prompt for information, for example a password,
and to verify a password (i.e. having the user enter it twice and check
that the same string was entered twice). UI_add_verify_string() takes
and extra argument that should be a pointer to the result buffer of the
input string that it's supposed to verify, or verification will fail.
UI_add_input_boolean() adds a prompt to the UI that's supposed to be answered
in a boolean way, with a single character for yes and a different character
for no. A set of characters that can be used to cancel the prompt is given
as well. The prompt itself is divided in two, one part being the
descriptive text (given through the I<prompt> argument) and one describing
the possible answers (given through the I<action_desc> argument).
UI_add_info_string() and UI_add_error_string() add strings that are shown at
the same time as the prompt for extra information or to show an error string.
The difference between the two is only conceptual. With the builtin method,
there's no technical difference between them. Other methods may make a
difference between them, however.
The flags currently supported are B<UI_INPUT_FLAG_ECHO>, which is relevant for
UI_add_input_string() and will have the users response be echoed (when
prompting for a password, this flag should obviously not be used, and
B<UI_INPUT_FLAG_DEFAULT_PWD>, which means that a default password of some
sort will be used (completely depending on the application and the UI
method).
UI_dup_input_string(), UI_dup_verify_string(), UI_dup_input_boolean(),
UI_dup_info_string() and UI_dup_error_string() are basically the same
as their UI_add counterparts, except that they make their own copies
of all strings.
UI_construct_prompt() is a helper function that can be used to create
a prompt from two pieces of information: an description and a name.
The default constructor (if there is none provided by the method used)
creates a string "Enter I<description> for I<name>:". With the
description "pass phrase" and the file name "foo.key", that becomes
"Enter pass phrase for foo.key:". Other methods may create whatever
string and may include encodings that will be processed by the other
method functions.
UI_add_user_data() adds a piece of memory for the method to use at any
time. The builtin UI method doesn't care about this info. Note that several
calls to this function doesn't add data, it replaces the previous blob
with the one given as argument.
UI_get0_user_data() retrieves the data that has last been given to the
UI with UI_add_user_data().
UI_get0_result() returns a pointer to the result buffer associated with
the information indexed by I<i>.
UI_process() goes through the information given so far, does all the printing
and prompting and returns.
UI_ctrl() adds extra control for the application author. For now, it
understands two commands: B<UI_CTRL_PRINT_ERRORS>, which makes UI_process()
print the OpenSSL error stack as part of processing the UI, and
B<UI_CTRL_IS_REDOABLE>, which returns a flag saying if the used UI can
be used again or not.
UI_set_default_method() changes the default UI method to the one given.
UI_get_default_method() returns a pointer to the current default UI method.
UI_get_method() returns the UI method associated with a given UI.
UI_set_method() changes the UI method associated with a given UI.
=head1 COPYRIGHT
Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| openweave/openweave-core | third_party/openssl/openssl/doc/crypto/UI_new.pod | Perl | apache-2.0 | 8,175 |
#!/usr/bin/perl
# Visits every directory, calls make clean, and then removes the Makefile
#
# Written by Tomofumi Yuki, 11/21 2014
#
my $TARGET_DIR = ".";
if ($#ARGV != 0) {
printf("usage perl clean.pl target-dir\n");
exit(1);
}
if ($#ARGV == 0) {
$TARGET_DIR = $ARGV[0];
}
my @categories = ('linear-algebra/blas',
'linear-algebra/kernels',
'linear-algebra/solvers',
'datamining',
'stencils',
'medley');
foreach $cat (@categories) {
my $target = $TARGET_DIR.'/'.$cat;
opendir DIR, $target or die "directory $target not found.\n";
while (my $dir = readdir DIR) {
next if ($dir=~'^\..*');
next if (!(-d $target.'/'.$dir));
my $targetDir = $target.'/'.$dir;
my $command = "cd $targetDir; make clean; rm -f Makefile";
print($command."\n");
system($command);
}
closedir DIR;
}
my $cfgFile = $TARGET_DIR.'/'.'config.mk';
if (-e $cfgFile) {
unlink $cfgFile;
}
| pauloapanucci/pc-cholesky | utilities/clean.pl | Perl | mit | 1,031 |
#!/usr/bin/perl
@list = ('', 'ZMACRO', 'NMACRO', 'TMACRO', '1', '+1', '1 2', '1,2',
'foo', 'foo bar', '%', '+foo', '<<');
@tests = ('token', 'empty');
print ";Testname=test; Arguments=-fbin -oiftoken.txt; Files=stdout stderr iftoken.txt"
print "%define ZMACRO\n";
print "%define NMACRO 1\n";
print "%define TMACRO 1 2\n";
foreach $x (@list) {
print "\tdb 'N \"$x\":'\n";
foreach $t (@tests) {
print "%if$t $x\n";
print "\tdb ' $t'\n";
print "%else\n";
print "\tdb ' n$t'\n";
print "%endif\n";
}
print "\tdb 10\n";
print "\tdb 'C \"$x\":'\n";
foreach $t (@tests) {
print "%if$t $x ; With a comment!\n";
print "\tdb ' $t'\n";
print "%else\n";
print "\tdb ' n$t'\n";
print "%endif\n";
}
print "\tdb 10\n";
}
| endlessm/chromium-browser | third_party/nasm/test/iftoken.pl | Perl | bsd-3-clause | 753 |
#============================================================= -*-Perl-*-
#
# Template::Exception
#
# DESCRIPTION
# Module implementing a generic exception class used for error handling
# in the Template Toolkit.
#
# AUTHOR
# Andy Wardley <abw@wardley.org>
#
# COPYRIGHT
# Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
#
# This module is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
#========================================================================
package Template::Exception;
use strict;
use warnings;
use constant TYPE => 0;
use constant INFO => 1;
use constant TEXT => 2;
use overload q|""| => "as_string", fallback => 1;
our $VERSION = 2.70;
#------------------------------------------------------------------------
# new($type, $info, \$text)
#
# Constructor method used to instantiate a new Template::Exception
# object. The first parameter should contain the exception type. This
# can be any arbitrary string of the caller's choice to represent a
# specific exception. The second parameter should contain any
# information (i.e. error message or data reference) relevant to the
# specific exception event. The third optional parameter may be a
# reference to a scalar containing output text from the template
# block up to the point where the exception was thrown.
#------------------------------------------------------------------------
sub new {
my ($class, $type, $info, $textref) = @_;
bless [ $type, $info, $textref ], $class;
}
#------------------------------------------------------------------------
# type()
# info()
# type_info()
#
# Accessor methods to return the internal TYPE and INFO fields.
#------------------------------------------------------------------------
sub type {
$_[0]->[ TYPE ];
}
sub info {
$_[0]->[ INFO ];
}
sub type_info {
my $self = shift;
@$self[ TYPE, INFO ];
}
#------------------------------------------------------------------------
# text()
# text(\$pretext)
#
# Method to return the text referenced by the TEXT member. A text
# reference may be passed as a parameter to supercede the existing
# member. The existing text is added to the *end* of the new text
# before being stored. This facility is provided for template blocks
# to gracefully de-nest when an exception occurs and allows them to
# reconstruct their output in the correct order.
#------------------------------------------------------------------------
sub text {
my ($self, $newtextref) = @_;
my $textref = $self->[ TEXT ];
if ($newtextref) {
$$newtextref .= $$textref if $textref && $textref ne $newtextref;
$self->[ TEXT ] = $newtextref;
return '';
}
elsif ($textref) {
return $$textref;
}
else {
return '';
}
}
#------------------------------------------------------------------------
# as_string()
#
# Accessor method to return a string indicating the exception type and
# information.
#------------------------------------------------------------------------
sub as_string {
my $self = shift;
return $self->[ TYPE ] . ' error - ' . $self->[ INFO ];
}
#------------------------------------------------------------------------
# select_handler(@types)
#
# Selects the most appropriate handler for the exception TYPE, from
# the list of types passed in as parameters. The method returns the
# item which is an exact match for TYPE or the closest, more
# generic handler (e.g. foo being more generic than foo.bar, etc.)
#------------------------------------------------------------------------
sub select_handler {
my ($self, @options) = @_;
my $type = $self->[ TYPE ];
my %hlut;
@hlut{ @options } = (1) x @options;
while ($type) {
return $type if $hlut{ $type };
# strip .element from the end of the exception type to find a
# more generic handler
$type =~ s/\.?[^\.]*$//;
}
return undef;
}
1;
__END__
=head1 NAME
Template::Exception - Exception handling class module
=head1 SYNOPSIS
use Template::Exception;
my $exception = Template::Exception->new($type, $info);
$type = $exception->type;
$info = $exception->info;
($type, $info) = $exception->type_info;
print $exception->as_string();
$handler = $exception->select_handler(\@candidates);
=head1 DESCRIPTION
The C<Template::Exception> module defines an object class for
representing exceptions within the template processing life cycle.
Exceptions can be raised by modules within the Template Toolkit, or
can be generated and returned by user code bound to template
variables.
Exceptions can be raised in a template using the C<THROW> directive,
[% THROW user.login 'no user id: please login' %]
or by calling the L<throw()|Template::Context#throw()> method on the current
L<Template::Context> object,
$context->throw('user.passwd', 'Incorrect Password');
$context->throw('Incorrect Password'); # type 'undef'
or from Perl code by calling C<die()> with a C<Template::Exception> object,
die (Template::Exception->new('user.denied', 'Invalid User ID'));
or by simply calling C<die()> with an error string. This is
automagically caught and converted to an exception of 'C<undef>'
type (that's the literal string 'C<undef>' rather than Perl's
undefined value) which can then be handled in the usual way.
die "I'm sorry Dave, I can't do that";
Each exception is defined by its type and a information component
(e.g. error message). The type can be any identifying string and may
contain dotted components (e.g. 'C<foo>', 'C<foo.bar>', 'C<foo.bar.baz>').
Exception types are considered to be hierarchical such that 'C<foo.bar>'
would be a specific type of the more general 'C<foo>' type.
=head1 METHODS
=head2 type()
Returns the exception type.
=head2 info()
Returns the exception information.
=head1 AUTHOR
Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
=head1 COPYRIGHT
Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=head1 SEE ALSO
L<Template>, L<Template::Context>
=cut
# Local Variables:
# mode: perl
# perl-indent-level: 4
# indent-tabs-mode: nil
# End:
#
# vim: expandtab shiftwidth=4:
| Dokaponteam/ITF_Project | xampp/perl/vendor/lib/Template/Exception.pm | Perl | mit | 6,402 |
require 5;
use 5.008;
## Anything before 5.8.0 is GIMPY!
## This module is to be use()'d only by Pod::Simple::Transcode
package Pod::Simple::TranscodeSmart;
use strict;
use Pod::Simple;
require Encode;
sub is_dumb {0}
sub is_smart {1}
sub all_encodings {
return Encode::->encodings(':all');
}
sub encoding_is_available {
return Encode::resolve_alias($_[1]);
}
sub encmodver {
return "Encode.pm v" .($Encode::VERSION || '?');
}
sub make_transcoder {
my($e) = $_[1];
die "WHAT ENCODING!?!?" unless $e;
my $x;
return sub {
foreach $x (@_) {
$x = Encode::decode($e, $x);
}
return;
};
}
1;
| leighpauls/k2cro4 | third_party/cygwin/lib/perl5/vendor_perl/5.10/Pod/Simple/TranscodeSmart.pm | Perl | bsd-3-clause | 631 |
#!/usr/bin/perl
# This Perl script tweaks GDB sources to be more useful for Doxygen.
while (<>) {
# Allow "/* * " as an equivalent to "/** ", better for Emacs compat.
s/\/\* \* /\/** /sg;
# Manually expand macro seen in structs and such.
s/ENUM_BITFIELD[ \t]*\((.*?)\)/__extension__ enum $1/sg;
print;
}
| armoredsoftware/protocol | measurer/gdb-7.9/gdb/doc/filter-params.pl | Perl | bsd-3-clause | 326 |
package Archive::Zip::Member;
# A generic member of an archive
use strict;
use vars qw( $VERSION @ISA );
BEGIN {
$VERSION = '1.48';
@ISA = qw( Archive::Zip );
if ($^O eq 'MSWin32') {
require Win32;
require Encode;
Encode->import(qw{ decode_utf8 });
}
}
use Archive::Zip qw(
:CONSTANTS
:MISC_CONSTANTS
:ERROR_CODES
:PKZIP_CONSTANTS
:UTILITY_METHODS
);
use Time::Local ();
use Compress::Raw::Zlib qw( Z_OK Z_STREAM_END MAX_WBITS );
use File::Path;
use File::Basename;
# Unix perms for default creation of files/dirs.
use constant DEFAULT_DIRECTORY_PERMISSIONS => 040755;
use constant DEFAULT_FILE_PERMISSIONS => 0100666;
use constant DIRECTORY_ATTRIB => 040000;
use constant FILE_ATTRIB => 0100000;
# Returns self if successful, else undef
# Assumes that fh is positioned at beginning of central directory file header.
# Leaves fh positioned immediately after file header or EOCD signature.
sub _newFromZipFile {
my $class = shift;
my $self = Archive::Zip::ZipFileMember->_newFromZipFile(@_);
return $self;
}
sub newFromString {
my $class = shift;
my ($stringOrStringRef, $fileName);
if (ref($_[0]) eq 'HASH') {
$stringOrStringRef = $_[0]->{string};
$fileName = $_[0]->{zipName};
} else {
($stringOrStringRef, $fileName) = @_;
}
my $self =
Archive::Zip::StringMember->_newFromString($stringOrStringRef, $fileName);
return $self;
}
sub newFromFile {
my $class = shift;
my ($fileName, $zipName);
if (ref($_[0]) eq 'HASH') {
$fileName = $_[0]->{fileName};
$zipName = $_[0]->{zipName};
} else {
($fileName, $zipName) = @_;
}
my $self =
Archive::Zip::NewFileMember->_newFromFileNamed($fileName, $zipName);
return $self;
}
sub newDirectoryNamed {
my $class = shift;
my ($directoryName, $newName);
if (ref($_[0]) eq 'HASH') {
$directoryName = $_[0]->{directoryName};
$newName = $_[0]->{zipName};
} else {
($directoryName, $newName) = @_;
}
my $self =
Archive::Zip::DirectoryMember->_newNamed($directoryName, $newName);
return $self;
}
sub new {
my $class = shift;
my $self = {
'lastModFileDateTime' => 0,
'fileAttributeFormat' => FA_UNIX,
'versionMadeBy' => 20,
'versionNeededToExtract' => 20,
'bitFlag' => ($Archive::Zip::UNICODE ? 0x0800 : 0),
'compressionMethod' => COMPRESSION_STORED,
'desiredCompressionMethod' => COMPRESSION_STORED,
'desiredCompressionLevel' => COMPRESSION_LEVEL_NONE,
'internalFileAttributes' => 0,
'externalFileAttributes' => 0, # set later
'fileName' => '',
'cdExtraField' => '',
'localExtraField' => '',
'fileComment' => '',
'crc32' => 0,
'compressedSize' => 0,
'uncompressedSize' => 0,
'isSymbolicLink' => 0,
'password' => undef, # password for encrypted data
'crc32c' => -1, # crc for decrypted data
@_
};
bless($self, $class);
$self->unixFileAttributes($self->DEFAULT_FILE_PERMISSIONS);
return $self;
}
sub _becomeDirectoryIfNecessary {
my $self = shift;
$self->_become('Archive::Zip::DirectoryMember')
if $self->isDirectory();
return $self;
}
# Morph into given class (do whatever cleanup I need to do)
sub _become {
return bless($_[0], $_[1]);
}
sub versionMadeBy {
shift->{'versionMadeBy'};
}
sub fileAttributeFormat {
my $self = shift;
if (@_) {
$self->{fileAttributeFormat} =
(ref($_[0]) eq 'HASH') ? $_[0]->{format} : $_[0];
} else {
return $self->{fileAttributeFormat};
}
}
sub versionNeededToExtract {
shift->{'versionNeededToExtract'};
}
sub bitFlag {
my $self = shift;
# Set General Purpose Bit Flags according to the desiredCompressionLevel setting
if ( $self->desiredCompressionLevel == 1
|| $self->desiredCompressionLevel == 2) {
$self->{'bitFlag'} = DEFLATING_COMPRESSION_FAST;
} elsif ($self->desiredCompressionLevel == 3
|| $self->desiredCompressionLevel == 4
|| $self->desiredCompressionLevel == 5
|| $self->desiredCompressionLevel == 6
|| $self->desiredCompressionLevel == 7) {
$self->{'bitFlag'} = DEFLATING_COMPRESSION_NORMAL;
} elsif ($self->desiredCompressionLevel == 8
|| $self->desiredCompressionLevel == 9) {
$self->{'bitFlag'} = DEFLATING_COMPRESSION_MAXIMUM;
}
if ($Archive::Zip::UNICODE) {
$self->{'bitFlag'} |= 0x0800;
}
$self->{'bitFlag'};
}
sub password {
my $self = shift;
$self->{'password'} = shift if @_;
$self->{'password'};
}
sub compressionMethod {
shift->{'compressionMethod'};
}
sub desiredCompressionMethod {
my $self = shift;
my $newDesiredCompressionMethod =
(ref($_[0]) eq 'HASH') ? shift->{compressionMethod} : shift;
my $oldDesiredCompressionMethod = $self->{'desiredCompressionMethod'};
if (defined($newDesiredCompressionMethod)) {
$self->{'desiredCompressionMethod'} = $newDesiredCompressionMethod;
if ($newDesiredCompressionMethod == COMPRESSION_STORED) {
$self->{'desiredCompressionLevel'} = 0;
$self->{'bitFlag'} &= ~GPBF_HAS_DATA_DESCRIPTOR_MASK
if $self->uncompressedSize() == 0;
} elsif ($oldDesiredCompressionMethod == COMPRESSION_STORED) {
$self->{'desiredCompressionLevel'} = COMPRESSION_LEVEL_DEFAULT;
}
}
return $oldDesiredCompressionMethod;
}
sub desiredCompressionLevel {
my $self = shift;
my $newDesiredCompressionLevel =
(ref($_[0]) eq 'HASH') ? shift->{compressionLevel} : shift;
my $oldDesiredCompressionLevel = $self->{'desiredCompressionLevel'};
if (defined($newDesiredCompressionLevel)) {
$self->{'desiredCompressionLevel'} = $newDesiredCompressionLevel;
$self->{'desiredCompressionMethod'} = (
$newDesiredCompressionLevel
? COMPRESSION_DEFLATED
: COMPRESSION_STORED
);
}
return $oldDesiredCompressionLevel;
}
sub fileName {
my $self = shift;
my $newName = shift;
if (defined $newName) {
$newName =~ s{[\\/]+}{/}g; # deal with dos/windoze problems
$self->{'fileName'} = $newName;
}
return $self->{'fileName'};
}
sub lastModFileDateTime {
my $modTime = shift->{'lastModFileDateTime'};
$modTime =~ m/^(\d+)$/; # untaint
return $1;
}
sub lastModTime {
my $self = shift;
return _dosToUnixTime($self->lastModFileDateTime());
}
sub setLastModFileDateTimeFromUnix {
my $self = shift;
my $time_t = shift;
$self->{'lastModFileDateTime'} = _unixToDosTime($time_t);
}
sub internalFileAttributes {
shift->{'internalFileAttributes'};
}
sub externalFileAttributes {
shift->{'externalFileAttributes'};
}
# Convert UNIX permissions into proper value for zip file
# Usable as a function or a method
sub _mapPermissionsFromUnix {
my $self = shift;
my $mode = shift;
my $attribs = $mode << 16;
# Microsoft Windows Explorer needs this bit set for directories
if ($mode & DIRECTORY_ATTRIB) {
$attribs |= 16;
}
return $attribs;
# TODO: map more MS-DOS perms
}
# Convert ZIP permissions into Unix ones
#
# This was taken from Info-ZIP group's portable UnZip
# zipfile-extraction program, version 5.50.
# http://www.info-zip.org/pub/infozip/
#
# See the mapattr() function in unix/unix.c
# See the attribute format constants in unzpriv.h
#
# XXX Note that there's one situation that is not implemented
# yet that depends on the "extra field."
sub _mapPermissionsToUnix {
my $self = shift;
my $format = $self->{'fileAttributeFormat'};
my $attribs = $self->{'externalFileAttributes'};
my $mode = 0;
if ($format == FA_AMIGA) {
$attribs = $attribs >> 17 & 7; # Amiga RWE bits
$mode = $attribs << 6 | $attribs << 3 | $attribs;
return $mode;
}
if ($format == FA_THEOS) {
$attribs &= 0xF1FFFFFF;
if (($attribs & 0xF0000000) != 0x40000000) {
$attribs &= 0x01FFFFFF; # not a dir, mask all ftype bits
} else {
$attribs &= 0x41FFFFFF; # leave directory bit as set
}
}
if ( $format == FA_UNIX
|| $format == FA_VAX_VMS
|| $format == FA_ACORN
|| $format == FA_ATARI_ST
|| $format == FA_BEOS
|| $format == FA_QDOS
|| $format == FA_TANDEM) {
$mode = $attribs >> 16;
return $mode if $mode != 0 or not $self->localExtraField;
# warn("local extra field is: ", $self->localExtraField, "\n");
# XXX This condition is not implemented
# I'm just including the comments from the info-zip section for now.
# Some (non-Info-ZIP) implementations of Zip for Unix and
# VMS (and probably others ??) leave 0 in the upper 16-bit
# part of the external_file_attributes field. Instead, they
# store file permission attributes in some extra field.
# As a work-around, we search for the presence of one of
# these extra fields and fall back to the MSDOS compatible
# part of external_file_attributes if one of the known
# e.f. types has been detected.
# Later, we might implement extraction of the permission
# bits from the VMS extra field. But for now, the work-around
# should be sufficient to provide "readable" extracted files.
# (For ASI Unix e.f., an experimental remap from the e.f.
# mode value IS already provided!)
}
# PKWARE's PKZip for Unix marks entries as FA_MSDOS, but stores the
# Unix attributes in the upper 16 bits of the external attributes
# field, just like Info-ZIP's Zip for Unix. We try to use that
# value, after a check for consistency with the MSDOS attribute
# bits (see below).
if ($format == FA_MSDOS) {
$mode = $attribs >> 16;
}
# FA_MSDOS, FA_OS2_HPFS, FA_WINDOWS_NTFS, FA_MACINTOSH, FA_TOPS20
$attribs = !($attribs & 1) << 1 | ($attribs & 0x10) >> 4;
# keep previous $mode setting when its "owner"
# part appears to be consistent with DOS attribute flags!
return $mode if ($mode & 0700) == (0400 | $attribs << 6);
$mode = 0444 | $attribs << 6 | $attribs << 3 | $attribs;
return $mode;
}
sub unixFileAttributes {
my $self = shift;
my $oldPerms = $self->_mapPermissionsToUnix;
my $perms;
if (@_) {
$perms = (ref($_[0]) eq 'HASH') ? $_[0]->{attributes} : $_[0];
if ($self->isDirectory) {
$perms &= ~FILE_ATTRIB;
$perms |= DIRECTORY_ATTRIB;
} else {
$perms &= ~DIRECTORY_ATTRIB;
$perms |= FILE_ATTRIB;
}
$self->{externalFileAttributes} =
$self->_mapPermissionsFromUnix($perms);
}
return $oldPerms;
}
sub localExtraField {
my $self = shift;
if (@_) {
$self->{localExtraField} =
(ref($_[0]) eq 'HASH') ? $_[0]->{field} : $_[0];
} else {
return $self->{localExtraField};
}
}
sub cdExtraField {
my $self = shift;
if (@_) {
$self->{cdExtraField} = (ref($_[0]) eq 'HASH') ? $_[0]->{field} : $_[0];
} else {
return $self->{cdExtraField};
}
}
sub extraFields {
my $self = shift;
return $self->localExtraField() . $self->cdExtraField();
}
sub fileComment {
my $self = shift;
if (@_) {
$self->{fileComment} =
(ref($_[0]) eq 'HASH')
? pack('C0a*', $_[0]->{comment})
: pack('C0a*', $_[0]);
} else {
return $self->{fileComment};
}
}
sub hasDataDescriptor {
my $self = shift;
if (@_) {
my $shouldHave = shift;
if ($shouldHave) {
$self->{'bitFlag'} |= GPBF_HAS_DATA_DESCRIPTOR_MASK;
} else {
$self->{'bitFlag'} &= ~GPBF_HAS_DATA_DESCRIPTOR_MASK;
}
}
return $self->{'bitFlag'} & GPBF_HAS_DATA_DESCRIPTOR_MASK;
}
sub crc32 {
shift->{'crc32'};
}
sub crc32String {
sprintf("%08x", shift->{'crc32'});
}
sub compressedSize {
shift->{'compressedSize'};
}
sub uncompressedSize {
shift->{'uncompressedSize'};
}
sub isEncrypted {
shift->{'bitFlag'} & GPBF_ENCRYPTED_MASK;
}
sub isTextFile {
my $self = shift;
my $bit = $self->internalFileAttributes() & IFA_TEXT_FILE_MASK;
if (@_) {
my $flag = (ref($_[0]) eq 'HASH') ? shift->{flag} : shift;
$self->{'internalFileAttributes'} &= ~IFA_TEXT_FILE_MASK;
$self->{'internalFileAttributes'} |=
($flag ? IFA_TEXT_FILE : IFA_BINARY_FILE);
}
return $bit == IFA_TEXT_FILE;
}
sub isBinaryFile {
my $self = shift;
my $bit = $self->internalFileAttributes() & IFA_TEXT_FILE_MASK;
if (@_) {
my $flag = shift;
$self->{'internalFileAttributes'} &= ~IFA_TEXT_FILE_MASK;
$self->{'internalFileAttributes'} |=
($flag ? IFA_BINARY_FILE : IFA_TEXT_FILE);
}
return $bit == IFA_BINARY_FILE;
}
sub extractToFileNamed {
my $self = shift;
# local FS name
my $name = (ref($_[0]) eq 'HASH') ? $_[0]->{name} : $_[0];
$self->{'isSymbolicLink'} = 0;
# Check if the file / directory is a symbolic link or not
if ($self->{'externalFileAttributes'} == 0xA1FF0000) {
$self->{'isSymbolicLink'} = 1;
$self->{'newName'} = $name;
my ($status, $fh) = _newFileHandle($name, 'r');
my $retval = $self->extractToFileHandle($fh);
$fh->close();
} else {
#return _writeSymbolicLink($self, $name) if $self->isSymbolicLink();
my ($status, $fh);
if ($^O eq 'MSWin32' && $Archive::Zip::UNICODE) {
$name = decode_utf8(Win32::GetFullPathName($name));
mkpath_win32($name);
Win32::CreateFile($name);
($status, $fh) = _newFileHandle(Win32::GetANSIPathName($name), 'w');
} else {
mkpath(dirname($name)); # croaks on error
($status, $fh) = _newFileHandle($name, 'w');
}
return _ioError("Can't open file $name for write") unless $status;
my $retval = $self->extractToFileHandle($fh);
$fh->close();
chmod($self->unixFileAttributes(), $name)
or return _error("Can't chmod() ${name}: $!");
utime($self->lastModTime(), $self->lastModTime(), $name);
return $retval;
}
}
sub mkpath_win32 {
my $path = shift;
use File::Spec;
my ($volume, @path) = File::Spec->splitdir($path);
$path = File::Spec->catfile($volume, shift @path);
pop @path;
while (@path) {
$path = File::Spec->catfile($path, shift @path);
Win32::CreateDirectory($path);
}
}
sub _writeSymbolicLink {
my $self = shift;
my $name = shift;
my $chunkSize = $Archive::Zip::ChunkSize;
#my ( $outRef, undef ) = $self->readChunk($chunkSize);
my $fh;
my $retval = $self->extractToFileHandle($fh);
my ($outRef, undef) = $self->readChunk(100);
}
sub isSymbolicLink {
my $self = shift;
if ($self->{'externalFileAttributes'} == 0xA1FF0000) {
$self->{'isSymbolicLink'} = 1;
} else {
return 0;
}
1;
}
sub isDirectory {
return 0;
}
sub externalFileName {
return undef;
}
# The following are used when copying data
sub _writeOffset {
shift->{'writeOffset'};
}
sub _readOffset {
shift->{'readOffset'};
}
sub writeLocalHeaderRelativeOffset {
shift->{'writeLocalHeaderRelativeOffset'};
}
sub wasWritten { shift->{'wasWritten'} }
sub _dataEnded {
shift->{'dataEnded'};
}
sub _readDataRemaining {
shift->{'readDataRemaining'};
}
sub _inflater {
shift->{'inflater'};
}
sub _deflater {
shift->{'deflater'};
}
# Return the total size of my local header
sub _localHeaderSize {
my $self = shift;
{
use bytes;
return SIGNATURE_LENGTH +
LOCAL_FILE_HEADER_LENGTH +
length($self->fileName()) +
length($self->localExtraField());
}
}
# Return the total size of my CD header
sub _centralDirectoryHeaderSize {
my $self = shift;
{
use bytes;
return SIGNATURE_LENGTH +
CENTRAL_DIRECTORY_FILE_HEADER_LENGTH +
length($self->fileName()) +
length($self->cdExtraField()) +
length($self->fileComment());
}
}
# DOS date/time format
# 0-4 (5) Second divided by 2
# 5-10 (6) Minute (0-59)
# 11-15 (5) Hour (0-23 on a 24-hour clock)
# 16-20 (5) Day of the month (1-31)
# 21-24 (4) Month (1 = January, 2 = February, etc.)
# 25-31 (7) Year offset from 1980 (add 1980 to get actual year)
# Convert DOS date/time format to unix time_t format
# NOT AN OBJECT METHOD!
sub _dosToUnixTime {
my $dt = shift;
return time() unless defined($dt);
my $year = (($dt >> 25) & 0x7f) + 80;
my $mon = (($dt >> 21) & 0x0f) - 1;
my $mday = (($dt >> 16) & 0x1f);
my $hour = (($dt >> 11) & 0x1f);
my $min = (($dt >> 5) & 0x3f);
my $sec = (($dt << 1) & 0x3e);
# catch errors
my $time_t =
eval { Time::Local::timelocal($sec, $min, $hour, $mday, $mon, $year); };
return time() if ($@);
return $time_t;
}
# Note, this is not exactly UTC 1980, it's 1980 + 12 hours and 1
# minute so that nothing timezoney can muck us up.
my $safe_epoch = 315576060;
# convert a unix time to DOS date/time
# NOT AN OBJECT METHOD!
sub _unixToDosTime {
my $time_t = shift;
unless ($time_t) {
_error("Tried to add member with zero or undef value for time");
$time_t = $safe_epoch;
}
if ($time_t < $safe_epoch) {
_ioError("Unsupported date before 1980 encountered, moving to 1980");
$time_t = $safe_epoch;
}
my ($sec, $min, $hour, $mday, $mon, $year) = localtime($time_t);
my $dt = 0;
$dt += ($sec >> 1);
$dt += ($min << 5);
$dt += ($hour << 11);
$dt += ($mday << 16);
$dt += (($mon + 1) << 21);
$dt += (($year - 80) << 25);
return $dt;
}
sub head {
my ($self, $mode) = (@_, 0);
use bytes;
return pack LOCAL_FILE_HEADER_FORMAT,
$self->versionNeededToExtract(),
$self->{'bitFlag'},
$self->desiredCompressionMethod(),
$self->lastModFileDateTime(),
$self->hasDataDescriptor()
? (0,0,0) # crc, compr & uncompr all zero if data descriptor present
: (
$self->crc32(),
$mode
? $self->_writeOffset() # compressed size
: $self->compressedSize(), # may need to be re-written later
$self->uncompressedSize(),
),
length($self->fileName()),
length($self->localExtraField());
}
# Write my local header to a file handle.
# Stores the offset to the start of the header in my
# writeLocalHeaderRelativeOffset member.
# Returns AZ_OK on success.
sub _writeLocalFileHeader {
my $self = shift;
my $fh = shift;
my $signatureData = pack(SIGNATURE_FORMAT, LOCAL_FILE_HEADER_SIGNATURE);
$self->_print($fh, $signatureData)
or return _ioError("writing local header signature");
my $header = $self->head(1);
$self->_print($fh, $header) or return _ioError("writing local header");
# Check for a valid filename or a filename equal to a literal `0'
if ($self->fileName() || $self->fileName eq '0') {
$self->_print($fh, $self->fileName())
or return _ioError("writing local header filename");
}
if ($self->localExtraField()) {
$self->_print($fh, $self->localExtraField())
or return _ioError("writing local extra field");
}
return AZ_OK;
}
sub _writeCentralDirectoryFileHeader {
my $self = shift;
my $fh = shift;
my $sigData =
pack(SIGNATURE_FORMAT, CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE);
$self->_print($fh, $sigData)
or return _ioError("writing central directory header signature");
my ($fileNameLength, $extraFieldLength, $fileCommentLength);
{
use bytes;
$fileNameLength = length($self->fileName());
$extraFieldLength = length($self->cdExtraField());
$fileCommentLength = length($self->fileComment());
}
my $header = pack(
CENTRAL_DIRECTORY_FILE_HEADER_FORMAT,
$self->versionMadeBy(),
$self->fileAttributeFormat(),
$self->versionNeededToExtract(),
$self->bitFlag(),
$self->desiredCompressionMethod(),
$self->lastModFileDateTime(),
$self->crc32(), # these three fields should have been updated
$self->_writeOffset(), # by writing the data stream out
$self->uncompressedSize(), #
$fileNameLength,
$extraFieldLength,
$fileCommentLength,
0, # {'diskNumberStart'},
$self->internalFileAttributes(),
$self->externalFileAttributes(),
$self->writeLocalHeaderRelativeOffset());
$self->_print($fh, $header)
or return _ioError("writing central directory header");
if ($fileNameLength) {
$self->_print($fh, $self->fileName())
or return _ioError("writing central directory header signature");
}
if ($extraFieldLength) {
$self->_print($fh, $self->cdExtraField())
or return _ioError("writing central directory extra field");
}
if ($fileCommentLength) {
$self->_print($fh, $self->fileComment())
or return _ioError("writing central directory file comment");
}
return AZ_OK;
}
# This writes a data descriptor to the given file handle.
# Assumes that crc32, writeOffset, and uncompressedSize are
# set correctly (they should be after a write).
# Further, the local file header should have the
# GPBF_HAS_DATA_DESCRIPTOR_MASK bit set.
sub _writeDataDescriptor {
my $self = shift;
my $fh = shift;
my $header = pack(
SIGNATURE_FORMAT . DATA_DESCRIPTOR_FORMAT,
DATA_DESCRIPTOR_SIGNATURE,
$self->crc32(),
$self->_writeOffset(), # compressed size
$self->uncompressedSize());
$self->_print($fh, $header)
or return _ioError("writing data descriptor");
return AZ_OK;
}
# Re-writes the local file header with new crc32 and compressedSize fields.
# To be called after writing the data stream.
# Assumes that filename and extraField sizes didn't change since last written.
sub _refreshLocalFileHeader {
my $self = shift;
my $fh = shift;
my $here = $fh->tell();
$fh->seek($self->writeLocalHeaderRelativeOffset() + SIGNATURE_LENGTH,
IO::Seekable::SEEK_SET)
or return _ioError("seeking to rewrite local header");
my $header = $self->head(1);
$self->_print($fh, $header)
or return _ioError("re-writing local header");
$fh->seek($here, IO::Seekable::SEEK_SET)
or return _ioError("seeking after rewrite of local header");
return AZ_OK;
}
sub readChunk {
my $self = shift;
my $chunkSize = (ref($_[0]) eq 'HASH') ? $_[0]->{chunkSize} : $_[0];
if ($self->readIsDone()) {
$self->endRead();
my $dummy = '';
return (\$dummy, AZ_STREAM_END);
}
$chunkSize = $Archive::Zip::ChunkSize if not defined($chunkSize);
$chunkSize = $self->_readDataRemaining()
if $chunkSize > $self->_readDataRemaining();
my $buffer = '';
my $outputRef;
my ($bytesRead, $status) = $self->_readRawChunk(\$buffer, $chunkSize);
return (\$buffer, $status) unless $status == AZ_OK;
$buffer && $self->isEncrypted and $buffer = $self->_decode($buffer);
$self->{'readDataRemaining'} -= $bytesRead;
$self->{'readOffset'} += $bytesRead;
if ($self->compressionMethod() == COMPRESSION_STORED) {
$self->{'crc32'} = $self->computeCRC32($buffer, $self->{'crc32'});
}
($outputRef, $status) = &{$self->{'chunkHandler'}}($self, \$buffer);
$self->{'writeOffset'} += length($$outputRef);
$self->endRead()
if $self->readIsDone();
return ($outputRef, $status);
}
# Read the next raw chunk of my data. Subclasses MUST implement.
# my ( $bytesRead, $status) = $self->_readRawChunk( \$buffer, $chunkSize );
sub _readRawChunk {
my $self = shift;
return $self->_subclassResponsibility();
}
# A place holder to catch rewindData errors if someone ignores
# the error code.
sub _noChunk {
my $self = shift;
return (\undef, _error("trying to copy chunk when init failed"));
}
# Basically a no-op so that I can have a consistent interface.
# ( $outputRef, $status) = $self->_copyChunk( \$buffer );
sub _copyChunk {
my ($self, $dataRef) = @_;
return ($dataRef, AZ_OK);
}
# ( $outputRef, $status) = $self->_deflateChunk( \$buffer );
sub _deflateChunk {
my ($self, $buffer) = @_;
my ($status) = $self->_deflater()->deflate($buffer, my $out);
if ($self->_readDataRemaining() == 0) {
my $extraOutput;
($status) = $self->_deflater()->flush($extraOutput);
$out .= $extraOutput;
$self->endRead();
return (\$out, AZ_STREAM_END);
} elsif ($status == Z_OK) {
return (\$out, AZ_OK);
} else {
$self->endRead();
my $retval = _error('deflate error', $status);
my $dummy = '';
return (\$dummy, $retval);
}
}
# ( $outputRef, $status) = $self->_inflateChunk( \$buffer );
sub _inflateChunk {
my ($self, $buffer) = @_;
my ($status) = $self->_inflater()->inflate($buffer, my $out);
my $retval;
$self->endRead() unless $status == Z_OK;
if ($status == Z_OK || $status == Z_STREAM_END) {
$retval = ($status == Z_STREAM_END) ? AZ_STREAM_END : AZ_OK;
return (\$out, $retval);
} else {
$retval = _error('inflate error', $status);
my $dummy = '';
return (\$dummy, $retval);
}
}
sub rewindData {
my $self = shift;
my $status;
# set to trap init errors
$self->{'chunkHandler'} = $self->can('_noChunk');
# Work around WinZip bug with 0-length DEFLATED files
$self->desiredCompressionMethod(COMPRESSION_STORED)
if $self->uncompressedSize() == 0;
# assume that we're going to read the whole file, and compute the CRC anew.
$self->{'crc32'} = 0
if ($self->compressionMethod() == COMPRESSION_STORED);
# These are the only combinations of methods we deal with right now.
if ( $self->compressionMethod() == COMPRESSION_STORED
and $self->desiredCompressionMethod() == COMPRESSION_DEFLATED) {
($self->{'deflater'}, $status) = Compress::Raw::Zlib::Deflate->new(
'-Level' => $self->desiredCompressionLevel(),
'-WindowBits' => -MAX_WBITS(), # necessary magic
'-Bufsize' => $Archive::Zip::ChunkSize,
@_
); # pass additional options
return _error('deflateInit error:', $status)
unless $status == Z_OK;
$self->{'chunkHandler'} = $self->can('_deflateChunk');
} elsif ($self->compressionMethod() == COMPRESSION_DEFLATED
and $self->desiredCompressionMethod() == COMPRESSION_STORED) {
($self->{'inflater'}, $status) = Compress::Raw::Zlib::Inflate->new(
'-WindowBits' => -MAX_WBITS(), # necessary magic
'-Bufsize' => $Archive::Zip::ChunkSize,
@_
); # pass additional options
return _error('inflateInit error:', $status)
unless $status == Z_OK;
$self->{'chunkHandler'} = $self->can('_inflateChunk');
} elsif ($self->compressionMethod() == $self->desiredCompressionMethod()) {
$self->{'chunkHandler'} = $self->can('_copyChunk');
} else {
return _error(
sprintf(
"Unsupported compression combination: read %d, write %d",
$self->compressionMethod(),
$self->desiredCompressionMethod()));
}
$self->{'readDataRemaining'} =
($self->compressionMethod() == COMPRESSION_STORED)
? $self->uncompressedSize()
: $self->compressedSize();
$self->{'dataEnded'} = 0;
$self->{'readOffset'} = 0;
return AZ_OK;
}
sub endRead {
my $self = shift;
delete $self->{'inflater'};
delete $self->{'deflater'};
$self->{'dataEnded'} = 1;
$self->{'readDataRemaining'} = 0;
return AZ_OK;
}
sub readIsDone {
my $self = shift;
return ($self->_dataEnded() or !$self->_readDataRemaining());
}
sub contents {
my $self = shift;
my $newContents = shift;
if (defined($newContents)) {
# change our type and call the subclass contents method.
$self->_become('Archive::Zip::StringMember');
return $self->contents(pack('C0a*', $newContents)); # in case of Unicode
} else {
my $oldCompression =
$self->desiredCompressionMethod(COMPRESSION_STORED);
my $status = $self->rewindData(@_);
if ($status != AZ_OK) {
$self->endRead();
return $status;
}
my $retval = '';
while ($status == AZ_OK) {
my $ref;
($ref, $status) = $self->readChunk($self->_readDataRemaining());
# did we get it in one chunk?
if (length($$ref) == $self->uncompressedSize()) {
$retval = $$ref;
} else {
$retval .= $$ref
}
}
$self->desiredCompressionMethod($oldCompression);
$self->endRead();
$status = AZ_OK if $status == AZ_STREAM_END;
$retval = undef unless $status == AZ_OK;
return wantarray ? ($retval, $status) : $retval;
}
}
sub extractToFileHandle {
my $self = shift;
my $fh = (ref($_[0]) eq 'HASH') ? shift->{fileHandle} : shift;
_binmode($fh);
my $oldCompression = $self->desiredCompressionMethod(COMPRESSION_STORED);
my $status = $self->rewindData(@_);
$status = $self->_writeData($fh) if $status == AZ_OK;
$self->desiredCompressionMethod($oldCompression);
$self->endRead();
return $status;
}
# write local header and data stream to file handle
sub _writeToFileHandle {
my $self = shift;
my $fh = shift;
my $fhIsSeekable = shift;
my $offset = shift;
return _error("no member name given for $self")
if $self->fileName() eq '';
$self->{'writeLocalHeaderRelativeOffset'} = $offset;
$self->{'wasWritten'} = 0;
# Determine if I need to write a data descriptor
# I need to do this if I can't refresh the header
# and I don't know compressed size or crc32 fields.
my $headerFieldsUnknown = (
($self->uncompressedSize() > 0)
and ($self->compressionMethod() == COMPRESSION_STORED
or $self->desiredCompressionMethod() == COMPRESSION_DEFLATED));
my $shouldWriteDataDescriptor =
($headerFieldsUnknown and not $fhIsSeekable);
$self->hasDataDescriptor(1)
if ($shouldWriteDataDescriptor);
$self->{'writeOffset'} = 0;
my $status = $self->rewindData();
($status = $self->_writeLocalFileHeader($fh))
if $status == AZ_OK;
($status = $self->_writeData($fh))
if $status == AZ_OK;
if ($status == AZ_OK) {
$self->{'wasWritten'} = 1;
if ($self->hasDataDescriptor()) {
$status = $self->_writeDataDescriptor($fh);
} elsif ($headerFieldsUnknown) {
$status = $self->_refreshLocalFileHeader($fh);
}
}
return $status;
}
# Copy my (possibly compressed) data to given file handle.
# Returns C<AZ_OK> on success
sub _writeData {
my $self = shift;
my $writeFh = shift;
# If symbolic link, just create one if the operating system is Linux, Unix, BSD or VMS
# TODO: Add checks for other operating systems
if ($self->{'isSymbolicLink'} == 1 && $^O eq 'linux') {
my $chunkSize = $Archive::Zip::ChunkSize;
my ($outRef, $status) = $self->readChunk($chunkSize);
symlink $$outRef, $self->{'newName'};
} else {
return AZ_OK if ($self->uncompressedSize() == 0);
my $status;
my $chunkSize = $Archive::Zip::ChunkSize;
while ($self->_readDataRemaining() > 0) {
my $outRef;
($outRef, $status) = $self->readChunk($chunkSize);
return $status if ($status != AZ_OK and $status != AZ_STREAM_END);
if (length($$outRef) > 0) {
$self->_print($writeFh, $$outRef)
or return _ioError("write error during copy");
}
last if $status == AZ_STREAM_END;
}
}
return AZ_OK;
}
# Return true if I depend on the named file
sub _usesFileNamed {
return 0;
}
# ##############################################################################
#
# Decrypt section
#
# H.Merijn Brand (Tux) 2011-06-28
#
# ##############################################################################
# This code is derived from the crypt source of unzip-6.0 dated 05 Jan 2007
# Its license states:
#
# --8<---
# Copyright (c) 1990-2007 Info-ZIP. All rights reserved.
# See the accompanying file LICENSE, version 2005-Feb-10 or later
# (the contents of which are also included in (un)zip.h) for terms of use.
# If, for some reason, all these files are missing, the Info-ZIP license
# also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
#
# crypt.c (full version) by Info-ZIP. Last revised: [see crypt.h]
# The main encryption/decryption source code for Info-Zip software was
# originally written in Europe. To the best of our knowledge, it can
# be freely distributed in both source and object forms from any country,
# including the USA under License Exception TSU of the U.S. Export
# Administration Regulations (section 740.13(e)) of 6 June 2002.
# NOTE on copyright history:
# Previous versions of this source package (up to version 2.8) were
# not copyrighted and put in the public domain. If you cannot comply
# with the Info-Zip LICENSE, you may want to look for one of those
# public domain versions.
#
# This encryption code is a direct transcription of the algorithm from
# Roger Schlafly, described by Phil Katz in the file appnote.txt. This
# file (appnote.txt) is distributed with the PKZIP program (even in the
# version without encryption capabilities).
# -->8---
# As of January 2000, US export regulations were amended to allow export
# of free encryption source code from the US. As of June 2002, these
# regulations were further relaxed to allow export of encryption binaries
# associated with free encryption source code. The Zip 2.31, UnZip 5.52
# and Wiz 5.02 archives now include full crypto source code. As of the
# Zip 2.31 release, all official binaries include encryption support; the
# former "zcr" archives ceased to exist.
# (Note that restrictions may still exist in other countries, of course.)
# For now, we just support the decrypt stuff
# All below methods are supposed to be private
# use Data::Peek;
my @keys;
my @crct = do {
my $xor = 0xedb88320;
my @crc = (0) x 1024;
# generate a crc for every 8-bit value
foreach my $n (0 .. 255) {
my $c = $n;
$c = $c & 1 ? $xor ^ ($c >> 1) : $c >> 1 for 1 .. 8;
$crc[$n] = _revbe($c);
}
# generate crc for each value followed by one, two, and three zeros */
foreach my $n (0 .. 255) {
my $c = ($crc[($crc[$n] >> 24) ^ 0] ^ ($crc[$n] << 8)) & 0xffffffff;
$crc[$_ * 256 + $n] = $c for 1 .. 3;
}
map { _revbe($crc[$_]) } 0 .. 1023;
};
sub _crc32 {
my ($c, $b) = @_;
return ($crct[($c ^ $b) & 0xff] ^ ($c >> 8));
} # _crc32
sub _revbe {
my $w = shift;
return (($w >> 24) +
(($w >> 8) & 0xff00) +
(($w & 0xff00) << 8) +
(($w & 0xff) << 24));
} # _revbe
sub _update_keys {
use integer;
my $c = shift; # signed int
$keys[0] = _crc32($keys[0], $c);
$keys[1] = (($keys[1] + ($keys[0] & 0xff)) * 0x08088405 + 1) & 0xffffffff;
my $keyshift = $keys[1] >> 24;
$keys[2] = _crc32($keys[2], $keyshift);
} # _update_keys
sub _zdecode ($) {
my $c = shift;
my $t = ($keys[2] & 0xffff) | 2;
_update_keys($c ^= ((($t * ($t ^ 1)) >> 8) & 0xff));
return $c;
} # _zdecode
sub _decode {
my $self = shift;
my $buff = shift;
$self->isEncrypted or return $buff;
my $pass = $self->password;
defined $pass or return "";
@keys = (0x12345678, 0x23456789, 0x34567890);
_update_keys($_) for unpack "C*", $pass;
# DDumper { uk => [ @keys ] };
my $head = substr $buff, 0, 12, "";
my @head = map { _zdecode($_) } unpack "C*", $head;
my $x =
$self->{externalFileAttributes}
? ($self->{lastModFileDateTime} >> 8) & 0xff
: $self->{crc32} >> 24;
$head[-1] == $x or return ""; # Password fail
# Worth checking ...
$self->{crc32c} = (unpack LOCAL_FILE_HEADER_FORMAT, pack "C*", @head)[3];
# DHexDump ($buff);
$buff = pack "C*" => map { _zdecode($_) } unpack "C*" => $buff;
# DHexDump ($buff);
return $buff;
} # _decode
1;
| weipinghe/elasticsearch | dev-tools/src/main/resources/license-check/lib/Archive/Zip/Member.pm | Perl | apache-2.0 | 37,440 |
#!/usr/bin/env perl
=head1 NAME
add_blast.pl -- add number of blast matches to primers.txt
=head1 SYNOPSIS
B<add_blast.pl> <all_primers.txt and blastn outfmt 7 file(s)>
Run blast locally using output format 7.
blastn -db ucsc.hg19.fasta -evalue 0.05 -max_target_seqs 15 -outfmt 7 -task blastn -query <sample.all_primers.fa> -out <sample.all_primers.blastn7.txt>
=cut
#############################################################################
=head1 REQUIRES
Cwd,
FileHandle,
File::Basename,
File::Spec,
Getopt::Long,
Pod::Usage,
#Common,
=cut
use Cwd qw/abs_path/;
use FileHandle;
use File::Basename;
use File::Spec;
use FindBin;
use Getopt::Long;
require Pod::Usage;
use strict;
use warnings; no warnings 'once';
#############################################################################
### CONSTANTS
my $PROGRAM = $0;
$PROGRAM =~ s;^.*/;;;
my $VERSION = '$Revision: 1.2 $';
$VERSION =~ s/^\$Revision: //;
$VERSION =~ s/\$$//;
$VERSION = 0 unless $VERSION;
$VERSION = sprintf "%3.1f", $VERSION/10;
#############################################################################
=head1 DESCRIPTION
Add number of blast matches to all_primers.txt files. The all_primers.txt files
are created by call_primers.pl. Blast should be run using a command such as:
blastn -db ucsc.hg19.fasta -evalue 0.01 -max_target_seqs 25 -outfmt 7 -task blastn -query <sample.all_primers.fa> -out <sample.all_primers.blastn7.txt>
=cut
#############################################################################
=head1 OPTIONS
=over 4
=item B<--outdir> <dir>
Directory to save output files. Default is same location as input
primer file.
=item B<--dbug>
Print debugging messages.
=back
=cut
sub setup {
Pod::Usage::pod2usage(-verbose => 1) unless @ARGV;
my $man = 0;
my $help = 0;
Getopt::Long::Configure('pass_through');
Getopt::Long::GetOptions('help|?' => \$help, man => \$man);
Pod::Usage::pod2usage(-verbose => 1,
-exitstatus => 0) if $help;
Pod::Usage::pod2usage(-verbose => 2,
-exitstatus => 0) if $man;
my $p = {
OUTDIR => 0,
FORCE => 0,
DBUG => 0,
};
Getopt::Long::Configure('no_pass_through');
Getopt::Long::GetOptions(
'version' => sub { print "$PROGRAM, version $VERSION\n\n";
Pod::Usage::pod2usage(-verbose => 0,
-exitstatus => 0) },
'outdir=s' => \$$p{OUTDIR},
'force' => \$$p{FORCE},
'dbug' => \$$p{DBUG},
) || die "\n";
@ARGV || die "Need all_primers.txt and blast file(s)\n";
my @blastfiles = grep(/blast/i, @ARGV);
@blastfiles || die "No blast files\n";
my @primerfiles = grep(/primers.txt/i, @ARGV);
@primerfiles || die "No primer files\n";
my $infiles = pair_inputfiles(\@blastfiles, \@primerfiles);
($infiles, $p);
}
sub pair_inputfiles {
my $blastfiles = shift;
my $primerfiles = shift;
my %infile;
foreach my $input (['primers', $primerfiles],
['blast', $blastfiles]) {
my $tag = $$input[0];
my $filelist = $$input[1];
foreach my $fname (@$filelist) {
my $base = basename($fname);
$base =~ s/\.all_primers.*$//;
$infile{$base}{$tag} = $fname;
}
}
my $num = 0;
my $tot = keys %infile;
foreach my $k (keys %infile) {
my @have = keys %{ $infile{$k} };
if (scalar(@have)==2) { $num++; }
else {
warn "$k only have @have\n";
delete $infile{$k}
}
}
warn scalar(keys %infile)." paired input files\n";
return \%infile;
}
################################################################################
### MAIN PROGRAM
my ($infiles, $p) = setup();
my %dbsnp;
foreach my $base (sort keys %$infiles) {
my $pfile = $$infiles{$base}{primers};
my $bfile = $$infiles{$base}{blast};
my $blastnums = parse_blast($bfile);
add_blastnums($pfile, $blastnums, $p);
}
##############################################################################
sub add_blastnums {
my $pfile = shift;
my $blastnums = shift;
my $outfile = $pfile;
$outfile =~ s/\.txt$//;
$outfile .= ".blast_counts.txt";
if ($$p{OUTDIR}) {
my $base = basename($outfile);
$outfile = File::Spec->catfile($$p{OUTDIR}, $base);
}
warn "Writing $outfile\n";
my $ofh = new FileHandle ">$outfile" or die ">$outfile: $!";
my $fh = new FileHandle "$pfile" or die ">$pfile: $!";
my $head = $fh->getline;
my @fields = split(/\t/, $head);
my @outfields;
foreach my $f (@fields) {
push(@outfields, $f);
if ($f =~ /num_snps/) {
push(@outfields, 'num_blast_hits_left');
push(@outfields, 'num_blast_hits_right');
}
}
print $ofh join("\t", @outfields);
foreach my $l ($fh->getlines) {
my @v = split(/\t/, $l);
my %d = map { $_=>shift @v } @fields;
my $pname = join("_", $d{target_name}, $d{segment},
$d{primer_num}.$d{template_strand});
foreach my $side ('_left', '_right') {
$d{'num_blast_hits'.$side} = $$blastnums{$pname.$side}{hits};
}
my @row = map { defined($d{$_}) ? $d{$_} : '' } @outfields;
print $ofh join("\t", @row);
}
$fh->close;
$ofh->close;
}
sub parse_blast {
my $bfile = shift;
my $fh = new FileHandle $bfile or die "$bfile: $!";
my %bcounts;
my $pname = '';
foreach my $l (<$fh>) {
if ($l =~ /^# Query: (\S+)/) {
$pname = $1;
} elsif ($l =~ /^# (\d+) hits found/) {
$bcounts{$pname}{hits} = $1 if $pname;
$pname = '';
}
}
$fh->close;
return \%bcounts;
}
#-----------------------------------------------------------------------------
sub rev_complement {
my $seq = shift;
$seq =~ tr/ATCGatcg/TAGCtagc/;
$seq = reverse($seq);
return $seq;
}
sub enumdate {
my $long = shift;
my ($se,$mi,$hr,$day,$mo,$yr) = localtime(time);
my $enumdate = sprintf "%04d%02d%02d", $yr+1900, $mo+1, $day;
unless ($long) { $enumdate =~ s/^..//; }
($enumdate);
}
| eulaf/cardio_padlock | scripts/add_blast.pl | Perl | mit | 6,242 |
#!/usr/bin/perl
=head1 NAME
WWW::Shopify - Main object representing acess to a particular Shopify store.
=cut
=head1 DISCLAIMER
WWW::Shopify is my first official CPAN module, so please bear with me as I try to sort out all the bugs, and deal with the unfamiliar CPAN infrastructure. Don't expect this to work out of the box as of yet, I'm still learning exactly how things are working. Hence some version problems I've been having.
Thanks for your understanding.
=cut
=head1 DESCRIPTION
WWW::Shopify represents a way to grab and upload data to a particular shopify store.
All that's required is the access token for a particular app, its url, and the API key, or altenratively, if you have a private app, you can substitue the app password for the api key.
If you want to use make a private app, use WWW::Shopify::Private. If you want to make a public app, use WWW::Shopify::Public.
=cut
=head1 EXAMPLES
In order to get a list of all products, we can do the following:
# Here we instantiate a copy of the public API object, with all the necessary fields.
my $SA = new WWW::Shopify::Public($ShopURL, $APIKey, $AccessToken);
# Here we call get_all, OO style, and specify the entity we want to get.
my @Products = $SA->get_all('Product');
In this way, we can get and modify all the different types of shopify stuffs.
If you don't want to be using a public app, and just want to make a private app, it's just as easy:
# Here we instantiate a copy of the private API object this time, which means we don't need an access token, we just need a password.
my $sa = new WWW::Shopify::Private($shop_url, $api_key, $password);
my @Products = $SA->get_all('Product');
Easy enough.
To insert a Webhook, we'd do the following.
my $webhook = new WWW::Shopify::Model::Webhook({topic => "orders/create", address => $URL, format => "json"});
$SA->create($Webhook);
And that's all there is to it. To delete all the webhooks in a store, we'd do:
my @Webhooks = $SA->get_all('Webhook');
for (@Webhooks) {
$SA->delete($_);
}
Very easy.
=cut
use strict;
use warnings;
use LWP::UserAgent;
package WWW::Shopify;
our $VERSION = '0.99999';
use WWW::Shopify::Exception;
use WWW::Shopify::Field;
use Module::Find;
use WWW::Shopify::URLHandler;
use WWW::Shopify::Query;
use WWW::Shopify::Login;
# Make sure we include all our models so that when people call the model, we actually know what they're talking about.
BEGIN { eval(join("\n", map { "require $_;" } findallmod WWW::Shopify::Model)); }
package WWW::Shopify;
use Date::Parse;
=head1 METHODS
=head2 new($shop_url, [$email, $pass])
Creates a new shop, without using the actual API, uses automated form submission to log in.
=cut
sub new {
my ($package, $shop_url, $email, $password) = @_;
die new WWW::Shopify::Exception("Can't create a shop without a shop url.") unless $shop_url;
my $ua = LWP::UserAgent->new( ssl_opts => {'SSL_version' => 'TLSv12' } );
$ua->cookie_jar({ });
$ua->timeout(30);
$ua->agent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.5 Safari/537.22");
$package = "WWW::Shopify::Login" if $package eq "WWW::Shopify";
my $self = bless { _shop_url => $shop_url, _ua => $ua, _url_handler => undef, _api_calls => 0, _sleep_for_limit => 0, _last_timestamp => undef }, $package;
$self->url_handler(new WWW::Shopify::URLHandler($self));
$self->login_admin($email, $password) if defined $email && defined $password;
return $self;
}
sub api_calls { $_[0]->{_api_calls} = $_[1] if defined $_[1]; return $_[0]->{_api_calls}; }
sub url_handler { $_[0]->{_url_handler} = $_[1] if defined $_[1]; return $_[0]->{_url_handler}; }
sub sleep_for_limit { $_[0]->{_sleep_for_limit} = $_[1] if defined $_[1]; return $_[0]->{_sleep_for_limit}; }
sub last_timestamp { $_[0]->{_last_timestamp} = $_[1] if defined $_[1]; return $_[0]->{_last_timestamp}; }
=head2 encode_url($url)
Basic url encoding, works the same for public apps or logged-in apps.
=cut
sub encode_url { return "https://" . $_[0]->shop_url . $_[1]; }
=head2 ua([$new_ua])
Gets/sets the user agent we're using to access shopify's api. By default we use LWP::UserAgent, with a timeout of 5 seconds.
PLEASE NOTE: At the very least, with LWP::UserAgent, at least, on my system, I had to force the SSL layer of the agent to use TLSv12, using the line
LWP::UserAgent->new( ssl_opts => { SSL_version => 'TLSv12' } );
Otherwise, Shopify does some very weird stuff, and some very weird errors are spit out. Just FYI.
=cut
sub ua { $_[0]->{_ua} = $_[1] if defined $_[1]; return $_[0]->{_ua}; }
=head2 shop_url([$shop_url])
Gets/sets the shop url that we're going to be making calls to.
=cut
# Modifiable Attributes
sub shop_url { $_[0]->{_shop_url} = $_[1] if defined $_[1]; return $_[0]->{_shop_url}; }
sub translate_model($) {
return $_[1] if $_[1] =~ m/WWW::Shopify::Model/;
return "WWW::Shopify::Model::" . $_[1];
}
sub PULLING_ITEM_LIMIT { return 250; }
#sub CALL_LIMIT_REFRESH { return 60*5; }
#sub CALL_LIMIT_MAX { return 500; }
sub CALL_LIMIT_MAX { return 40; }
sub CALL_LIMIT_LEAK_TIME { return 1; }
sub CALL_LIMIT_LEAK_RATE { return 2; }
sub get_url { return $_[0]->url_handler->get_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
sub post_url { return $_[0]->url_handler->post_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
sub put_url { return $_[0]->url_handler->put_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
sub delete_url { return $_[0]->url_handler->delete_url($_[1], $_[2], $_[3], $_[4], $_[5]); }
use Data::Dumper;
sub use_url {
my ($self, $type, $url, @args) = @_;
my $method = lc($type) . "_url";
my ($decoded, $response);
$url = $self->encode_url($url);
eval {
if ($self->sleep_for_limit) {
do {
eval { ($decoded, $response) = $self->$method($url, @args); };
if (my $exp = $@) {
die $exp if !ref($exp) || ref($exp) ne 'WWW::Shopify::Exception::CallLimit';
sleep(1);
}
} while (!$response);
} else {
($decoded, $response) = $self->$method($url, @args);
}
};
if (my $exp = $@) {
print STDERR Dumper($exp->error) if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} > 1;
die $exp;
}
print STDERR uc($type) . " " . $response->request->uri . "\n" if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} == 1;
print STDERR Dumper($response) if $ENV{'SHOPIFY_LOG'} && $ENV{'SHOPIFY_LOG'} > 1;
$self->last_timestamp(DateTime->from_epoch( epoch => str2time($response->header('Date'))) );
return ($decoded, $response);
}
use Devel::StackTrace;
sub resolve_trailing_url {
my ($self, $package, $action, $parent) = @_;
my $method = lc($action) . "_through_parent";
if ($package->$method && (!$parent || !$parent->is_shop || $package ne "WWW::Shopify::Model::Metafield")) {
die new WWW::Shopify::Exception("Cannot get, no parent specified.") unless $parent;
return "/admin/" . $parent->plural . "/" . $parent->id . "/" . $package->plural;
}
return "/admin/" . $package->plural;
}
sub get_all_limit {
my ($self, $package, $specs) = @_;
$package = $self->translate_model($package);
$specs->{"limit"} = PULLING_ITEM_LIMIT unless exists $specs->{"limit"};
return () if ($specs->{limit} == 0);
return $self->get_shop if $package->is_shop;
my $url = $self->resolve_trailing_url($package, "get", $specs->{parent}) . ".json";
my ($decoded, $response) = $self->use_url('get', $url, $specs);
my @return = map { my $object = $package->from_json($_, $self); $object->associated_parent($specs->{parent}); $object; } @{$decoded->{$package->plural}};
return @return;
}
=head2 get_all($self, $package, $filters)
Gets up to 249 * CALL_LIMIT objects (currently 124750) from Shopify at once. Goes in a loop until it's got everything. Performs a count first to see where it's at.
@products = $sa->get_all("Product")
If you don't want this behaviour, use the limit filter.
=cut
use POSIX qw/ceil/;
use List::Util qw(min);
sub get_all {
my ($self, $package, $specs) = @_;
# We copy our specs so that we don't modify the original hash. Doesn't have to be a deep copy.
$specs = {%$specs} if $specs;
$package = $self->translate_model($package);
$self->validate_item($package);
return $self->get_shop if $package->is_shop;
return $self->get_all_limit($package, $specs) if ((defined $specs->{"limit"} && $specs->{"limit"} <= PULLING_ITEM_LIMIT) || !$package->countable());
my @return;
eval {
$specs->{page} = 1;
my @chunk;
do {
@chunk = $self->get_all_limit($package, $specs);
push(@return, @chunk);
$specs->{page}++;
} while (int(@chunk) == $specs->{limit});
};
if (my $exception = $@) {
$exception->extra(\@return) if ref($exception) && $exception->isa('WWW::Shopify::Exception::CallLimit');
die $exception;
}
return @return if wantarray;
return $return[0];
}
=head2 get_shop($self)
Returns the actual shop object.
my $shop = $sa->get_shop;
=cut
sub get_shop {
my ($self) = @_;
my $package = 'WWW::Shopify::Model::Shop';
my ($decoded, $response) = $self->use_url('get', "/admin/" . $package->singular() . ".json");
my $object = $package->from_json($decoded->{$package->singular()}, $self);
return $object;
}
=head2 get_timestamp($self)
Uses a call to Shopify to determine the DateTime on the shopify server. This can be used to synchronize things without worrying about the
local clock being out of sync with Shopify.
=cut
sub get_timestamp {
my ($self) = @_;
my $ua = $self->ua;
my ($decoded, $response) = $self->use_url('get', "/admin/shop.json");
my $date = $response->header('Date');
my $time = str2time($date);
return DateTime->from_epoch( epoch => $time );
}
=head2 get_count($self, $package, $filters)
Gets the item count from the shopify store. So if we wanted to count all our orders, we'd do:
my $order = $sa->get_count('Order', { status => "any" });
It's as easy as that. Keep in mind not all items are countable (who the hell knows why); a glaring exception is assets. Either check the shopify docs, or grep for the sub "countable".
=cut
sub get_count {
my ($self, $package, $specs) = @_;
$package = $self->translate_model($package);
$self->validate_item($package);
die "Cannot count $package." unless $package->countable();
my ($decoded, $response) = $self->use_url('get', $self->resolve_trailing_url($package, "get", $specs->{parent}) . "/count.json", $specs);
return $decoded->{'count'};
}
=head2 get($self, $package, $id)
Gets the item from the shopify store. Returns it in local (classed up) form. In order to get an order for example:
my $order = $sa->get('Order', 142345);
It's as easy as that. If we don't retrieve anything, we return undef.
=cut
sub get {
my ($self, $package, $id, $specs) = @_;
$package = $self->translate_model($package);
$self->validate_item($package);
# We have a special case for asssets, for some arbitrary reason.
my ($decoded, $response);
eval {
if ($package !~ m/Asset/) {
($decoded, $response) = $self->use_url('get', $self->resolve_trailing_url($package, "get", $specs->{parent}) . "/$id.json");
} else {
die new WWW::Shopify::Exception("MUST have a parent with assets.") unless $specs->{parent};
($decoded, $response) = $self->use_url('get', "/admin/themes/" . $specs->{parent}->id . "/assets.json", {'asset[key]' => $id, theme_id => $specs->{parent}->id});
}
};
if (my $exp = $@) {
return undef if ref($exp) && $exp->isa("WWW::Shopify::Exception::NotFound");
die $exp;
}
my $class = $package->from_json($decoded->{$package->singular()}, $self);
# Wow, this is straight up stupid that sometimes we don't get a 404.
return undef unless $class;
$class->associated_parent($specs->{parent});
return $class;
}
=head2 search($self, $package, $item, { query => $query })
Searches for the item from the shopify store. Not all items are searchable, check the API docs, or grep this module's source code and look for the "searchable" sub.
A popular thing to search for is customers by email, you can do so like the following:
my $customer = $sa->search("Customer", { query => "email:me@example.com" });
=cut
sub search {
my ($self, $package, $specs) = @_;
$package = $self->translate_model($package);
die new WWW::Shopify::Exception("Unable to search $package; it is not marked as searchable in Shopify's API.") unless $package->searchable;
die new WWW::Shopify::Exception("Must have a query to search.") unless $specs && $specs->{query};
$self->validate_item($package);
my ($decoded, $response) = $self->use_url('get', $self->resolve_trailing_url($package, "get", $specs->{parent}) . "/search.json", $specs);
my @return = ();
foreach my $element (@{$decoded->{$package->plural()}}) {
my $class = $package->from_json($element, $self);
$class->associated_parent($specs->{parent}) if $specs->{parent};
push(@return, $class);
}
return @return if wantarray;
return $return[0] if int(@return) > 0;
return undef;
}
=head2 create($self, $item)
Creates the item on the shopify store. Not all items are creatable, check the API docs, or grep this module's source code and look for the "creatable" sub.
=cut
use List::Util qw(first);
use HTTP::Request::Common;
sub create {
my ($self, $item, $options) = @_;
$self->validate_item(ref($item));
my $specs = {};
my $missing = first { !exists $item->{$_} } $item->creation_minimal;
die new WWW::Shopify::Exception("Missing minimal creation member: $missing in " . ref($item)) if $missing;
die new WWW::Shopify::Exception(ref($item) . " requires you to login with an admin account.") if $item->needs_login && !$self->logged_in_admin;
$specs = $item->to_json();
my ($decoded, $response) = $self->use_url($item->create_method, $self->resolve_trailing_url(ref($item), "create", $item->associated_parent) . ".json", {$item->singular() => $specs}, $item->needs_login);
my $element = $decoded->{$item->singular};
my $object = ref($item)->from_json($element, $self);
$object->associated_parent($item->associated_parent);
return $object;
}
=head2 update($self, $item)
Updates the item from the shopify store. Not all items are updatable, check the API docs, or grep this module's source code and look for the "updatable" sub.
=cut
sub update {
my ($self, $class) = @_;
$self->validate_item(ref($class));
my %mods = map { $_ => 1 } $class->update_fields;
my $vars = $class->to_json();
$vars = { $class->singular => {map { $_ => $vars->{$_} } grep { exists $mods{$_} } keys(%$vars)} };
my ($decoded, $response);
if (ref($class) =~ m/Asset/) {
my $url = $self->resolve_trailing_url(ref($class), "update", $class->associated_parent) . ".json";
($decoded, $response) = $self->use_url($class->update_method, $url, $vars);
}
else {
($decoded, $response) = $self->use_url($class->update_method, $self->resolve_trailing_url($class, "update", $class->associated_parent) . "/" . $class->id . ".json", $vars);
}
my $element = $decoded->{$class->singular()};
my $object = ref($class)->from_json($element, $self);
$object->associated_parent($class->associated_parent);
return $object;
}
=head2 delete($self, $item)
Deletes the item from the shopify store. Not all items are deletable, check the API docs, or grep this module's source code and look for the "deletable" sub.
=cut
sub delete {
my ($self, $class) = @_;
$self->validate_item(ref($class));
if (ref($class) =~ m/Asset/) {
my $url = $self->resolve_trailing_url(ref($class), "delete", $class->associated_parent) . ".json?asset[key]=" . $class->key;
$self->use_url($class->delete_method, $url);
}
else {
$self->use_url($class->delete_method, $self->resolve_trailing_url($class, "delete", $class->associated_parent) . "/" . $class->id . ".json");
}
return 1;
}
# For simple things like activating, enabling, disabling, that are a simple post to a custom URL.
# Sometimes returns an object, sometimes returns a 1.
use List::Util qw(first);
sub custom_action {
my ($self, $object, $action) = @_;
die new WWW::Shopify::Exception("You can't $action " . $object->plural . ".") unless defined $object && first { $_ eq $action } $object->actions;
my $id = $object->id;
my $url = $self->resolve_trailing_url($object, $action, $object->associated_parent) . "/$id/$action.json";
my ($decoded, $response) = $self->use_url('post', $url, {$object->singular() => $object->to_json});
return 1 if !$decoded;
my $element = $decoded->{$object->singular()};
$object = ref($object)->from_json($element, $self);
return $object;
}
=head2 activate($self, $charge), disable($self, $discount), enable($self, $discount), open($self, $order), close($self, $order), cancel($self, $order)
Special actions that do what they say.
=cut
sub activate { return $_[0]->custom_action($_[1], "activate"); }
sub disable { return $_[0]->custom_action($_[1], "disable"); }
sub enable { return $_[0]->custom_action($_[1], "enable"); }
sub open { return $_[0]->custom_action($_[1], "open"); }
sub close { return $_[0]->custom_action($_[1], "close"); }
sub cancel { return $_[0]->custom_action($_[1], "cancel"); }
sub approve { return $_[0]->custom_action($_[1], "approve"); }
sub remove { return $_[0]->custom_action($_[1], "remove"); }
sub spam { return $_[0]->custom_action($_[1], "spam"); }
sub not_spam { return $_[0]->custom_action($_[1], "not_spam"); }
=head2 login_admin($self, $email, $password)
Logs you in to the shop as an admin, allowing you to create and manipulate discount codes, as well as upload files into user-space (not theme space).
Doens't get around the API call limit, unfortunately.
=cut
use HTTP::Request::Common;
sub login_admin {
my ($self, $username, $password) = @_;
return 1 if $self->{last_login_check} && (time - $self->{last_login_check}) < 1000;
my $ua = $self->ua;
die new WWW::Shopify::Exception("Unable to login as admin without a cookie jar.") unless defined $ua->cookie_jar;
my $res = $ua->get("https://" . $self->shop_url . "/admin/auth/login");
die new WWW::Shopify::Exception("Unable to get login page.") unless $res->is_success;
die new WWW::Shopify::Exception("Unable to find authenticity token.") unless $res->decoded_content =~ m/name="authenticity_token".*?value="(\S+)"/ms;
my $authenticity_token = $1;
my $req = POST "https://" . $self->shop_url . "/admin/auth/login", [
login => $username,
password => $password,
remember => 1,
commit => "Sign In",
authenticity_token => $authenticity_token
];
$res = $ua->request($req);
die new WWW::Shopify::Exception("Unable to complete request: " . $res->decoded_content) unless $res->is_success || $res->code == 302;
die new WWW::Shopify::Exception("Unable to login: $1.") if $res->decoded_content =~ m/class="status system-error">(.*?)<\/div>/;
$self->{last_login_check} = time;
$self->{authenticity_token} = $authenticity_token;
$res = $self->ua->request(GET "https://" . $self->shop_url . "/admin");
die new WWW::Shopify::Exception($res) unless $res->decoded_content =~ m/meta content="(.*?)" name="csrf-token"/;
$self->{authenticity_token} = $1;
$ua->default_header('X-CSRF-Token' => $self->{authenticity_token});
return 1;
}
=head2 logged_in_admin($self)
Determines whether or not you're logged in to the Shopify store as an admin.
=cut
sub logged_in_admin {
my ($self) = @_;
return undef unless $self->{authenticity_token};
return 1 if $self->{last_login_check} && (time - $self->{last_login_check}) < 1000;
my $ua = $self->ua;
return undef unless $ua->cookie_jar;
my $res = $ua->get('https://' . $self->shop_url . '/admin/discounts/count.json');
return undef unless $res->is_success;
$self->{last_login_check} = time;
return 1;
}
sub is_valid { eval { $_[0]->get_shop; }; return undef if ($@); return 1; }
sub handleize {
my ($self, $handle) = @_;
$handle = $self if !ref($self);
$handle = lc($handle);
$handle =~ s/\s/-/g;
$handle =~ s/[^a-z0-9\-]//g;
$handle =~ s/\-+/-/g;
return $handle;
}
=head2 create_private_app()
Automates a form submission to generate a private app. Returns a WWW::Shopify::Private with the appropriate credentials. Must be logged in.
=cut
use WWW::Shopify::Private;
use List::Util qw(first);
sub create_private_app {
my ($self) = @_;
my $app = $self->create(new WWW::Shopify::Model::APIClient({}));
my @permissions = $self->get_all("APIPermission");
my $permission = first { $_->api_client->api_key eq $app->api_key } @permissions;
return new WWW::Shopify::Private($self->shop_url, $app->api_key, $permission->access_token);
}
=head2 delete_private_app($private_api)
Removes a private app. Must be logged in.
=cut
sub delete_private_app {
my ($self, $api) = @_;
my @apps = $self->get_all("APIPermission");
my $app = first { $_->api_client && $_->api_client->api_key eq $api->api_key } @apps;
die new WWW::Shopify::Exception("Can't find app with api key " . $api->api_key) unless $app;
return $self->delete(new WWW::Shopify::Model::APIClient({ id => $app->api_client->id }));
}
# Internal methods.
sub validate_item {
eval { die unless $_[1]; $_[1]->is_item; };
die new WWW::Shopify::Exception($_[1] . " is not an item!") if ($@);
die new WWW::Shopify::Exception($_[1] . " requires you to login with an admin account.") if $_[1]->needs_login && !$_[0]->logged_in_admin;
}
=head2 upload_files($self, @image_paths)
Requires log in. Uploads an array of files/images into the shop's non-theme file/image management system by automating a form submission.
$sa->login_admin("email", "password");
$sa->upload_files("image1.jpg", "image2.jpg");
Gets around the issue that this is not actually exposed to the API.
=cut
sub upload_files {
my ($self, @images) = @_;
die new WWW::Shopify::Exception("Uploading files/images requires you to login with an admin account.") unless $self->logged_in_admin;
foreach my $path (@images) {
die new WWW::Shopify::Exception("Unable to determine extension type.") unless $path =~ m/\.(\w{2,4})$/;
my $req = POST "https://" . $self->shop_url . "/admin/files.json",
Content_Type => "form-data",
Accept => "application/json",
Content => [authenticity_token => $self->{authenticity_token}, "file[file]" => [$path]];
my $res = $self->ua->request($req);
die new WWW::Shopify::Exception("Error uploading $path.") unless $res->is_success;
}
return int(@images);
}
=cut
=head1 EXPORTED FUNCTIONS
The functions below are exported as part of the package.
=cut
=head2 calc_webhook_signature($shared_secret, $request_body)
Calculates the webhook_signature based off the shared secret and request body passed in.
=cut
=head2 verify_webhook($shared_secret, $request_body)
Shopify webhook authentication. ALMOST the same as login authentication, but, of course, because this is shopify they've got a different system. 'Cause you know, one's not good enough.
Follows this: http://wiki.shopify.com/Verifying_Webhooks.
=cut
use Exporter 'import';
our @EXPORT_OK = qw(verify_webhook verify_login verify_proxy calc_webhook_signature calc_login_signature calc_proxy_signature handleize);
use Digest::MD5 'md5_hex';
use Digest::SHA qw(hmac_sha256_hex hmac_sha256_base64);
use MIME::Base64;
sub calc_webhook_signature {
my ($shared_secret, $request_body) = @_;
my $calc_signature = hmac_sha256_base64((defined $request_body) ? $request_body : "", $shared_secret);
while (length($calc_signature) % 4) { $calc_signature .= '='; }
return $calc_signature;
}
sub verify_webhook {
my ($x_shopify_hmac_sha256, $request_body, $shared_secret) = @_;
return undef unless $x_shopify_hmac_sha256;
return $x_shopify_hmac_sha256 eq calc_webhook_signature($shared_secret, $request_body);
}
=head2 calc_login_signature($shared_secret, $%params)
Calculates the login signature based on the shared secret and parmaeter hash passed in.
=cut
=head2 verify_login($shared_secret, $%params)
Shopify app dashboard verification (when someone clicks Login on the app dashboard).
This one was kinda random, 'cause they say it's like a webhook, but it's actually like legacy auth.
Also, they don't have a code parameter. For whatever reason.
=cut
sub calc_login_signature {
my ($shared_secret, $params) = @_;
return md5_hex($shared_secret . join("", map { "$_=" . $params->{$_} } (sort(grep { $_ ne "signature" } keys(%$params)))));
}
sub verify_login {
my ($shared_secret, $params) = @_;
return undef unless $params->{signature};
return calc_login_signature($shared_secret, $params) eq $params->{signature};
}
=head2 calc_proxy_signature($shared_secret, $%params)
Based on shared secret/hash of parameters passed in, calculates the proxy signature.
=cut
=head2 verify_proxy($shared_secret, %$params)
This is SLIGHTLY different from the above two. For, as far as I can tell, no reason.
=cut
sub calc_proxy_signature {
my ($shared_secret, $params) = @_;
return hmac_sha256_hex(join("", sort(map {
my $p = $params->{$_};
"$_=" . (ref($p) eq "ARRAY" ? join("$_=", @$p) : $p);
} (grep { $_ ne "signature" } keys(%$params)))), $shared_secret);
}
sub verify_proxy {
my ($shared_secret, $params) = @_;
return undef unless $params->{signature};
return calc_proxy_signature($shared_secret, $params) eq $params->{signature};
}
=head1 SEE ALSO
L<WWW::Shopify::Public>, L<WWW::Shopify::Private>, L<WWW::Shopify::Test>, L<WWW::Shopify::Item>, L<WWW::Shopify::Common::DBIx>
=head1 AUTHOR
Adam Harrison (adamdharrison@gmail.com)
=head1 LICENSE
Copyright (C) 2014 Adam Harrison
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;
| gitpan/WWW-Shopify | lib/WWW/Shopify.pm | Perl | mit | 26,291 |
#------------------------------------------------------------------------------
# File: Pentax.pm
#
# Description: Pentax/Asahi EXIF maker notes tags
#
# Revisions: 11/25/2003 - P. Harvey Created
# 02/10/2004 - P. Harvey Completely re-done
# 02/16/2004 - W. Smith Updated (see ref 3)
# 11/10/2004 - P. Harvey Added support for Asahi cameras
# 01/10/2005 - P. Harvey Added LensType with values from ref 4
# 03/30/2005 - P. Harvey Added new tags from ref 5
# 10/04/2005 - P. Harvey Added MOV tags
# 10/22/2007 - P. Harvey Got my new K10D! (more new tags to decode)
# 11/03/2010 - P. Harvey Got my new K-5! (a gold mine of new tags to discover!)
#
# References: 1) Image::MakerNotes::Pentax
# 2) http://johnst.org/sw/exiftags/ (Asahi cameras)
# 3) Wayne Smith private communication (Optio 550)
# 4) http://kobe1995.jp/~kaz/astro/istD.html
# 5) John Francis (http://www.panix.com/~johnf/raw/index.html) (ist-D/ist-DS)
# 6) http://www.cybercom.net/~dcoffin/dcraw/
# 7) Douglas O'Brien private communication (*istD, K10D)
# 8) Denis Bourez private communication
# 9) Kazumichi Kawabata private communication
# 10) David Buret private communication (*istD)
# 11) http://forums.dpreview.com/forums/read.asp?forum=1036&message=17465929
# 12) Derby Chang private communication
# 13) http://homepage3.nifty.com/kamisaka/makernote/makernote_pentax.htm (2007/02/28)
# 14) Ger Vermeulen private communication (Optio S6)
# 15) Barney Garrett private communication (Samsung GX-1S)
# 16) Axel Kellner private communication (K10D)
# 17) Cvetan Ivanov private communication (K100D)
# 18) http://gvsoft.homedns.org/exif/makernote-pentax-type3.html
# 19) Dave Nicholson private communication (K10D)
# 20) Bogdan and yeryry (http://www.cpanforum.com/posts/8037)
# 21) Peter (*istD, http://www.cpanforum.com/posts/8078)
# 22) Bozi (K10D, http://www.cpanforum.com/posts/8480)
# 23) Akos Szalkai (https://rt.cpan.org/Ticket/Display.html?id=43743)
# 24) Albert Bogner private communication
# 25) Niels Kristian Bech Jensen private communication
# 26) http://u88.n24.queensu.ca/exiftool/forum/index.php/topic,3444.0.html
# 27) http://u88.n24.queensu.ca/exiftool/forum/index.php/topic,3833.0.html
# 28) Klaus Homeister http://u88.n24.queensu.ca/exiftool/forum/index.php/topic,4803.0.html
# 29) Louis Granboulan private communication (K-5II)
# 30) http://u88.n24.queensu.ca/exiftool/forum/index.php?topic=5433
# 31) Iliah Borg private communication (LibRaw)
# JD) Jens Duttke private communication
#
# Notes: See POD documentation at the bottom of this file
#------------------------------------------------------------------------------
package Image::ExifTool::Pentax;
use strict;
use vars qw($VERSION %pentaxLensTypes);
use Image::ExifTool::Exif;
use Image::ExifTool::HP;
$VERSION = '2.99';
sub CryptShutterCount($$);
sub PrintFilter($$$);
# pentax lens type codes (ref 4)
# The first number gives the lens series, and the 2nd gives the model number
# Series numbers: K=1; A=2; F=3; FAJ=4; DFA=4,7; FA=3,4,5,6; FA*=5,6;
# DA=3,4,7; DA*=7,8; FA645=11; DFA645=13; Q=21
%pentaxLensTypes = (
Notes => q{
The first number gives the series of the lens, and the second identifies the
lens model. Note that newer series numbers may not always be properly
identified by cameras running older firmware versions. Decimal values have
been added to differentiate lenses which would otherwise have the same
LensType, and are used by the Composite LensID tag when attempting to
identify the specific lens model.
},
OTHER => sub {
my ($val, $inv, $conv) = @_;
return undef if $inv;
# *istD may report a series number of 4 for series 7 lenses
$val =~ s/^4 /7 / and $$conv{$val} and return "$$conv{$val} ($_[0])";
# cameras that don't recognize SDM lenses (eg. older K10 firmware)
# may report series 7 instead of 8
$val =~ s/^7 /8 / and $$conv{$val} and return "$$conv{$val} ? ($_[0])";
# there seems to some inconsistency between FA and DFA lenses for the 645D...
($val =~ s/^11 /13 / or $val =~ s/^13 /11 /) and $$conv{$val} and return "$$conv{$val} ? ($_[0])";
return undef;
},
'0 0' => 'M-42 or No Lens', #17
'1 0' => 'K or M Lens',
'2 0' => 'A Series Lens', #7 (from smc PENTAX-A 400mm F5.6)
'3 0' => 'Sigma', # (includes 'Sigma 30mm F1.4 EX DC' - PH)
# (and 'Sigma 105mm F2.8 EX DG Macro', ref 24)
# (and 'Sigma 18-50mm F2.8 EX Macro')
# (and 'Sigma 180mm F4.5 EX DG Macro')
# (and 'Sigma 70mm F2.8 EX DG Macro')
# (and 'Sigma 50-500mm F4-6.3 DG APO')
'3 17' => 'smc PENTAX-FA SOFT 85mm F2.8',
'3 18' => 'smc PENTAX-F 1.7X AF ADAPTER',
'3 19' => 'smc PENTAX-F 24-50mm F4',
'3 20' => 'smc PENTAX-F 35-80mm F4-5.6',
'3 21' => 'smc PENTAX-F 80-200mm F4.7-5.6',
'3 22' => 'smc PENTAX-F FISH-EYE 17-28mm F3.5-4.5',
'3 23' => 'smc PENTAX-F 100-300mm F4.5-5.6 or Sigma Lens',
'3 23.1' => 'Sigma AF 28-300mm F3.5-5.6 DL IF', #JD
'3 23.2' => 'Sigma AF 28-300mm F3.5-6.3 DG IF Macro', #JD
'3 23.3' => 'Tokina 80-200mm F2.8 ATX-Pro', #Exiv2
'3 24' => 'smc PENTAX-F 35-135mm F3.5-4.5',
'3 25' => 'smc PENTAX-F 35-105mm F4-5.6 or Sigma or Tokina Lens',
'3 25.1' => 'Sigma AF 28-300mm F3.5-5.6 DL IF', #11
'3 25.2' => 'Sigma 55-200mm F4-5.6 DC', #JD
'3 25.3' => 'Sigma AF 28-300mm F3.5-6.3 DL IF', #Exiv2
'3 25.4' => 'Sigma AF 28-300mm F3.5-6.3 DG IF Macro', #JD
'3 25.5' => 'Tokina 80-200mm F2.8 ATX-Pro', #12
'3 26' => 'smc PENTAX-F* 250-600mm F5.6 ED[IF]',
'3 27' => 'smc PENTAX-F 28-80mm F3.5-4.5 or Tokina Lens',
'3 27.1' => 'Tokina AT-X Pro AF 28-70mm F2.6-2.8', #JD
'3 28' => 'smc PENTAX-F 35-70mm F3.5-4.5 or Tokina Lens',
'3 28.1' => 'Tokina 19-35mm F3.5-4.5 AF', #12
'3 28.2' => 'Tokina AT-X AF 400mm F5.6', #25
'3 29' => 'PENTAX-F 28-80mm F3.5-4.5 or Sigma or Tokina Lens',
'3 29.1' => 'Sigma AF 18-125mm F3.5-5.6 DC', #11
'3 29.2' => 'Tokina AT-X PRO 28-70mm F2.6-2.8', #22
'3 30' => 'PENTAX-F 70-200mm F4-5.6',
'3 31' => 'smc PENTAX-F 70-210mm F4-5.6 or Tokina or Takumar Lens',
'3 31.1' => 'Tokina AF 730 75-300mm F4.5-5.6',
'3 31.2' => 'Takumar-F 70-210mm F4-5.6', #JD
'3 32' => 'smc PENTAX-F 50mm F1.4',
'3 33' => 'smc PENTAX-F 50mm F1.7',
'3 34' => 'smc PENTAX-F 135mm F2.8 [IF]',
'3 35' => 'smc PENTAX-F 28mm F2.8',
'3 36' => 'Sigma 20mm F1.8 EX DG Aspherical RF',
'3 38' => 'smc PENTAX-F* 300mm F4.5 ED[IF]',
'3 39' => 'smc PENTAX-F* 600mm F4 ED[IF]',
'3 40' => 'smc PENTAX-F Macro 100mm F2.8',
'3 41' => 'smc PENTAX-F Macro 50mm F2.8 or Sigma Lens', #4
'3 41.1' => 'Sigma 50mm F2.8 Macro', #16
'3 42' => 'Sigma 300mm F2.8 EX DG APO IF', #27
'3 44' => 'Sigma or Tamron Lens (3 44)',
'3 44.1' => 'Sigma AF 10-20mm F4-5.6 EX DC', #JD
'3 44.2' => 'Sigma 12-24mm F4.5-5.6 EX DG', #12 (added "-5.6", ref 29)
'3 44.3' => 'Sigma 17-70mm F2.8-4.5 DC Macro', #(Bart Hickman)
'3 44.4' => 'Sigma 18-50mm F3.5-5.6 DC', #4
'3 44.5' => 'Tamron 35-90mm F4 AF', #12
'3 46' => 'Sigma or Samsung Lens (3 46)',
'3 46.1' => 'Sigma APO 70-200mm F2.8 EX',
'3 46.2' => 'Sigma EX APO 100-300mm F4 IF', #JD
'3 46.3' => 'Samsung/Schneider D-XENON 50-200mm F4-5.6 ED', #29
'3 50' => 'smc PENTAX-FA 28-70mm F4 AL',
'3 51' => 'Sigma 28mm F1.8 EX DG Aspherical Macro',
'3 52' => 'smc PENTAX-FA 28-200mm F3.8-5.6 AL[IF] or Tamron Lens',
'3 52.1' => 'Tamron AF LD 28-200mm F3.8-5.6 [IF] Aspherical (171D)', #JD
'3 53' => 'smc PENTAX-FA 28-80mm F3.5-5.6 AL',
'3 247' => 'smc PENTAX-DA FISH-EYE 10-17mm F3.5-4.5 ED[IF]',
'3 248' => 'smc PENTAX-DA 12-24mm F4 ED AL[IF]',
'3 250' => 'smc PENTAX-DA 50-200mm F4-5.6 ED',
'3 251' => 'smc PENTAX-DA 40mm F2.8 Limited',
'3 252' => 'smc PENTAX-DA 18-55mm F3.5-5.6 AL',
'3 253' => 'smc PENTAX-DA 14mm F2.8 ED[IF]',
'3 254' => 'smc PENTAX-DA 16-45mm F4 ED AL',
'3 255' => 'Sigma Lens (3 255)',
'3 255.1' => 'Sigma 18-200mm F3.5-6.3 DC', #8
'3 255.2' => 'Sigma DL-II 35-80mm F4-5.6', #12
'3 255.3' => 'Sigma DL Zoom 75-300mm F4-5.6', #12
'3 255.4' => 'Sigma DF EX Aspherical 28-70mm F2.8', #12
'3 255.5' => 'Sigma AF Tele 400mm F5.6 Multi-coated', #JD
'3 255.6' => 'Sigma 24-60mm F2.8 EX DG', #PH
'3 255.7' => 'Sigma 70-300mm F4-5.6 Macro', #JD
'3 255.8' => 'Sigma 55-200mm F4-5.6 DC', #JD
'3 255.9' => 'Sigma 18-50mm F2.8 EX DC', #JD (also Macro version - PH)
'4 1' => 'smc PENTAX-FA SOFT 28mm F2.8',
'4 2' => 'smc PENTAX-FA 80-320mm F4.5-5.6',
'4 3' => 'smc PENTAX-FA 43mm F1.9 Limited',
'4 6' => 'smc PENTAX-FA 35-80mm F4-5.6',
'4 12' => 'smc PENTAX-FA 50mm F1.4', #17
'4 15' => 'smc PENTAX-FA 28-105mm F4-5.6 [IF]',
'4 16' => 'Tamron AF 80-210mm F4-5.6 (178D)', #13
'4 19' => 'Tamron SP AF 90mm F2.8 (172E)',
'4 20' => 'smc PENTAX-FA 28-80mm F3.5-5.6',
'4 21' => 'Cosina AF 100-300mm F5.6-6.7', #20
'4 22' => 'Tokina 28-80mm F3.5-5.6', #13
'4 23' => 'smc PENTAX-FA 20-35mm F4 AL',
'4 24' => 'smc PENTAX-FA 77mm F1.8 Limited',
'4 25' => 'Tamron SP AF 14mm F2.8', #13
'4 26' => 'smc PENTAX-FA Macro 100mm F3.5 or Cosina Lens',
'4 26.1' => 'Cosina 100mm F3.5 Macro', #JD
'4 27' => 'Tamron AF 28-300mm F3.5-6.3 LD Aspherical[IF] Macro (185D/285D)',
'4 28' => 'smc PENTAX-FA 35mm F2 AL',
'4 29' => 'Tamron AF 28-200mm F3.8-5.6 LD Super II Macro (371D)', #JD
'4 34' => 'smc PENTAX-FA 24-90mm F3.5-4.5 AL[IF]',
'4 35' => 'smc PENTAX-FA 100-300mm F4.7-5.8',
# '4 36' => 'Tamron AF70-300mm F4-5.6 LD Macro', # both 572D and A17 (Di) - ref JD
'4 36' => 'Tamron AF 70-300mm F4-5.6 LD Macro 1:2', #25
'4 37' => 'Tamron SP AF 24-135mm F3.5-5.6 AD AL (190D)', #13
'4 38' => 'smc PENTAX-FA 28-105mm F3.2-4.5 AL[IF]',
'4 39' => 'smc PENTAX-FA 31mm F1.8 AL Limited',
'4 41' => 'Tamron AF 28-200mm Super Zoom F3.8-5.6 Aspherical XR [IF] Macro (A03)',
'4 43' => 'smc PENTAX-FA 28-90mm F3.5-5.6',
'4 44' => 'smc PENTAX-FA J 75-300mm F4.5-5.8 AL',
'4 45' => 'Tamron Lens (4 45)',
'4 45.1' => 'Tamron 28-300mm F3.5-6.3 Ultra zoom XR',
'4 45.2' => 'Tamron AF 28-300mm F3.5-6.3 XR Di LD Aspherical [IF] Macro', #JD
'4 46' => 'smc PENTAX-FA J 28-80mm F3.5-5.6 AL',
'4 47' => 'smc PENTAX-FA J 18-35mm F4-5.6 AL',
#'4 49' => 'Tamron SP AF 28-75mm F2.8 XR Di (A09)',
'4 49' => 'Tamron SP AF 28-75mm F2.8 XR Di LD Aspherical [IF] Macro', #25
'4 51' => 'smc PENTAX-D FA 50mm F2.8 Macro',
'4 52' => 'smc PENTAX-D FA 100mm F2.8 Macro',
'4 55' => 'Samsung/Schneider D-XENOGON 35mm F2', #29
'4 56' => 'Samsung/Schneider D-XENON 100mm F2.8 Macro', #Alan Robinson
'4 75' => 'Tamron SP AF 70-200mm F2.8 Di LD [IF] Macro (A001)', #JD
'4 214' => 'smc PENTAX-DA 35mm F2.4 AL', #PH
'4 229' => 'smc PENTAX-DA 18-55mm F3.5-5.6 AL II', #JD
'4 230' => 'Tamron SP AF 17-50mm F2.8 XR Di II', #20
'4 231' => 'smc PENTAX-DA 18-250mm F3.5-6.3 ED AL [IF]', #21
'4 237' => 'Samsung/Schneider D-XENOGON 10-17mm F3.5-4.5', #JD
'4 239' => 'Samsung/Schneider D-XENON 12-24mm F4 ED AL [IF]', #23
'4 242' => 'smc PENTAX-DA* 16-50mm F2.8 ED AL [IF] SDM (SDM unused)', #Pietu Pohjalainen
'4 243' => 'smc PENTAX-DA 70mm F2.4 Limited', #JD
'4 244' => 'smc PENTAX-DA 21mm F3.2 AL Limited', #9
'4 245' => 'Samsung/Schneider D-XENON 50-200mm F4-5.6', #15
'4 246' => 'Samsung/Schneider D-XENON 18-55mm F3.5-5.6', #15
'4 247' => 'smc PENTAX-DA FISH-EYE 10-17mm F3.5-4.5 ED[IF]', #10
'4 248' => 'smc PENTAX-DA 12-24mm F4 ED AL [IF]', #10
'4 249' => 'Tamron XR DiII 18-200mm F3.5-6.3 (A14)',
'4 250' => 'smc PENTAX-DA 50-200mm F4-5.6 ED', #8
'4 251' => 'smc PENTAX-DA 40mm F2.8 Limited', #9
'4 252' => 'smc PENTAX-DA 18-55mm F3.5-5.6 AL', #8
'4 253' => 'smc PENTAX-DA 14mm F2.8 ED[IF]',
'4 254' => 'smc PENTAX-DA 16-45mm F4 ED AL',
'5 1' => 'smc PENTAX-FA* 24mm F2 AL[IF]',
'5 2' => 'smc PENTAX-FA 28mm F2.8 AL',
'5 3' => 'smc PENTAX-FA 50mm F1.7',
'5 4' => 'smc PENTAX-FA 50mm F1.4',
'5 5' => 'smc PENTAX-FA* 600mm F4 ED[IF]',
'5 6' => 'smc PENTAX-FA* 300mm F4.5 ED[IF]',
'5 7' => 'smc PENTAX-FA 135mm F2.8 [IF]',
'5 8' => 'smc PENTAX-FA Macro 50mm F2.8',
'5 9' => 'smc PENTAX-FA Macro 100mm F2.8',
'5 10' => 'smc PENTAX-FA* 85mm F1.4 [IF]',
'5 11' => 'smc PENTAX-FA* 200mm F2.8 ED[IF]',
'5 12' => 'smc PENTAX-FA 28-80mm F3.5-4.7',
'5 13' => 'smc PENTAX-FA 70-200mm F4-5.6',
'5 14' => 'smc PENTAX-FA* 250-600mm F5.6 ED[IF]',
'5 15' => 'smc PENTAX-FA 28-105mm F4-5.6',
'5 16' => 'smc PENTAX-FA 100-300mm F4.5-5.6',
'5 98' => 'smc PENTAX-FA 100-300mm F4.5-5.6', #JD (pre-production? - PH)
'6 1' => 'smc PENTAX-FA* 85mm F1.4 [IF]',
'6 2' => 'smc PENTAX-FA* 200mm F2.8 ED[IF]',
'6 3' => 'smc PENTAX-FA* 300mm F2.8 ED[IF]',
'6 4' => 'smc PENTAX-FA* 28-70mm F2.8 AL',
'6 5' => 'smc PENTAX-FA* 80-200mm F2.8 ED[IF]',
'6 6' => 'smc PENTAX-FA* 28-70mm F2.8 AL',
'6 7' => 'smc PENTAX-FA* 80-200mm F2.8 ED[IF]',
'6 8' => 'smc PENTAX-FA 28-70mm F4AL',
'6 9' => 'smc PENTAX-FA 20mm F2.8',
'6 10' => 'smc PENTAX-FA* 400mm F5.6 ED[IF]',
'6 13' => 'smc PENTAX-FA* 400mm F5.6 ED[IF]',
'6 14' => 'smc PENTAX-FA* Macro 200mm F4 ED[IF]',
'7 0' => 'smc PENTAX-DA 21mm F3.2 AL Limited', #13
'7 58' => 'smc PENTAX-D FA Macro 100mm F2.8 WR', #PH - this bit of information cost me $600 ;)
'7 75' => 'Tamron SP AF 70-200mm F2.8 Di LD [IF] Macro (A001)', #(Anton Bondar)
'7 201' => 'smc Pentax-DA L 50-200mm F4-5.6 ED WR', #(Bruce Rusk)
'7 202' => 'smc PENTAX-DA L 18-55mm F3.5-5.6 AL WR', #29
'7 203' => 'HD PENTAX-DA 55-300mm F4-5.8 ED WR', #29
'7 204' => 'HD PENTAX-DA 15mm F4 ED AL Limited', #forum5318
'7 205' => 'HD PENTAX-DA 35mm F2.8 Macro Limited', #29
'7 206' => 'HD PENTAX-DA 70mm F2.4 Limited', #29
'7 207' => 'HD PENTAX-DA 21mm F3.2 ED AL Limited', #forum5327
'7 208' => 'HD PENTAX-DA 40mm F2.8 Limited', #PH
'7 212' => 'smc PENTAX-DA 50mm F1.8', #PH
'7 213' => 'smc PENTAX-DA 40mm F2.8 XS', #PH
'7 214' => 'smc PENTAX-DA 35mm F2.4 AL', #PH
'7 216' => 'smc PENTAX-DA L 55-300mm F4-5.8 ED', #PH
'7 217' => 'smc PENTAX-DA 50-200mm F4-5.6 ED WR', #JD
'7 218' => 'smc PENTAX-DA 18-55mm F3.5-5.6 AL WR', #JD
'7 220' => 'Tamron SP AF 10-24mm F3.5-4.5 Di II LD Aspherical [IF]', #24
'7 221' => 'smc PENTAX-DA L 50-200mm F4-5.6 ED', #Ar't
'7 222' => 'smc PENTAX-DA L 18-55mm F3.5-5.6', #PH (tag 0x003f -- was '7 229' in LensInfo of one test image)
'7 223' => 'Samsung/Schneider D-XENON 18-55mm F3.5-5.6 II', #PH
'7 224' => 'smc PENTAX-DA 15mm F4 ED AL Limited', #JD
'7 225' => 'Samsung/Schneider D-XENON 18-250mm F3.5-6.3', #8/PH
'7 226' => 'smc PENTAX-DA* 55mm F1.4 SDM (SDM unused)', #PH (NC)
'7 227' => 'smc PENTAX-DA* 60-250mm F4 [IF] SDM (SDM unused)', #PH (NC)
'7 228' => 'Samsung 16-45mm F4 ED', #29
'7 229' => 'smc PENTAX-DA 18-55mm F3.5-5.6 AL II', #JD
'7 230' => 'Tamron AF 17-50mm F2.8 XR Di-II LD (Model A16)', #JD
'7 231' => 'smc PENTAX-DA 18-250mm F3.5-6.3 ED AL [IF]', #JD
'7 233' => 'smc PENTAX-DA 35mm F2.8 Macro Limited', #JD
'7 234' => 'smc PENTAX-DA* 300mm F4 ED [IF] SDM (SDM unused)', #19 (NC)
'7 235' => 'smc PENTAX-DA* 200mm F2.8 ED [IF] SDM (SDM unused)', #PH (NC)
'7 236' => 'smc PENTAX-DA 55-300mm F4-5.8 ED', #JD
'7 238' => 'Tamron AF 18-250mm F3.5-6.3 Di II LD Aspherical [IF] Macro', #JD
'7 241' => 'smc PENTAX-DA* 50-135mm F2.8 ED [IF] SDM (SDM unused)', #PH
'7 242' => 'smc PENTAX-DA* 16-50mm F2.8 ED AL [IF] SDM (SDM unused)', #19
'7 243' => 'smc PENTAX-DA 70mm F2.4 Limited', #PH
'7 244' => 'smc PENTAX-DA 21mm F3.2 AL Limited', #16
'8 0' => 'Sigma 50-150mm F2.8 II APO EX DC HSM', #forum2997
'8 3' => 'Sigma AF 18-125mm F3.5-5.6 DC', #29
'8 4' => 'Sigma 50mm F1.4 EX DG HSM', #Artur private communication
'8 7' => 'Sigma 24-70mm F2.8 IF EX DG HSM', #Exiv2
'8 8' => 'Sigma 18-250mm F3.5-6.3 DC OS HSM', #27
'8 11' => 'Sigma 10-20mm F3.5 EX DC HSM', #27
'8 12' => 'Sigma 70-300mm F4-5.6 DG OS', #forum3382
'8 13' => 'Sigma 120-400mm F4.5-5.6 APO DG OS HSM', #26
'8 14' => 'Sigma 17-70mm F2.8-4.0 DC Macro OS HSM', #(Hubert Meier)
'8 15' => 'Sigma 150-500mm F5-6.3 APO DG OS HSM', #26
'8 16' => 'Sigma 70-200mm F2.8 EX DG Macro HSM II', #26
'8 17' => 'Sigma 50-500mm F4.5-6.3 DG OS HSM', #(Heike Herrmann) (also APO, ref 26)
'8 18' => 'Sigma 8-16mm F4.5-5.6 DC HSM', #forum2998
'8 21' => 'Sigma 17-50mm F2.8 EX DC OS HSM', #26
'8 22' => 'Sigma 85mm F1.4 EX DG HSM', #26
'8 23' => 'Sigma 70-200mm F2.8 APO EX DG OS HSM', #27
'8 25' => 'Sigma 17-50mm F2.8 EX DC HSM', #Exiv2
'8 27' => 'Sigma 18-200mm F3.5-6.3 II DC HSM', #27
'8 28' => 'Sigma 18-250mm F3.5-6.3 DC Macro HSM', #27
'8 29' => 'Sigma 35mm F1.4 DG HSM', #27
'8 30' => 'Sigma 17-70mm F2.8-4 DC Macro HSM Contemporary', #27
'8 31' => 'Sigma 18-35mm F1.8 DC HSM', #27
'8 32' => 'Sigma 30mm F1.4 DC HSM | A', #27
'8 34' => 'Sigma 18-300mm F3.5-6.3 DC Macro HSM', #25
'8 59' => 'HD PENTAX-D FA 150-450mm F4.5-5.6 ED DC AW', #29
'8 60' => 'HD PENTAX-D FA* 70-200mm F2.8 ED DC AW', #29
'8 62' => 'HD PENTAX-D FA 24-70mm F2.8 ED SDM WR', #PH
'8 198' => 'smc PENTAX-DA L 18-50mm F4-5.6 DC WR RE', #29
'8 199' => 'HD PENTAX-DA 18-50mm F4-5.6 DC WR RE', #29
'8 200' => 'HD PENTAX-DA 16-85mm F3.5-5.6 ED DC WR', #29
'8 209' => 'HD PENTAX-DA 20-40mm F2.8-4 ED Limited DC WR', #29
'8 210' => 'smc PENTAX-DA 18-270mm F3.5-6.3 ED SDM', #Helmut Schutz
'8 211' => 'HD PENTAX-DA 560mm F5.6 ED AW', #PH
'8 215' => 'smc PENTAX-DA 18-135mm F3.5-5.6 ED AL [IF] DC WR', #PH
'8 226' => 'smc PENTAX-DA* 55mm F1.4 SDM', #JD
'8 227' => 'smc PENTAX-DA* 60-250mm F4 [IF] SDM', #JD
'8 232' => 'smc PENTAX-DA 17-70mm F4 AL [IF] SDM', #JD
'8 234' => 'smc PENTAX-DA* 300mm F4 ED [IF] SDM', #19
'8 235' => 'smc PENTAX-DA* 200mm F2.8 ED [IF] SDM', #JD
'8 241' => 'smc PENTAX-DA* 50-135mm F2.8 ED [IF] SDM', #JD
'8 242' => 'smc PENTAX-DA* 16-50mm F2.8 ED AL [IF] SDM', #JD
'8 255' => 'Sigma Lens (8 255)',
'8 255.1' => 'Sigma 70-200mm F2.8 EX DG Macro HSM II', #JD
'8 255.2' => 'Sigma 150-500mm F5-6.3 DG APO [OS] HSM', #JD (non-OS version has same type, ref 29)
'8 255.3' => 'Sigma 50-150mm F2.8 II APO EX DC HSM', #forum2997
'8 255.4' => 'Sigma 4.5mm F2.8 EX DC HSM Circular Fisheye', #PH
'8 255.5' => 'Sigma 50-200mm F4-5.6 DC OS', #26
'8 255.6' => 'Sigma 24-70mm F2.8 EX DG HSM', #29
#
# 645 lenses
#
'9 0' => '645 Manual Lens', #PH (NC)
'10 0' => '645 A Series Lens', #PH
'11 1' => 'smc PENTAX-FA 645 75mm F2.8', #PH
'11 2' => 'smc PENTAX-FA 645 45mm F2.8', #PH
'11 3' => 'smc PENTAX-FA* 645 300mm F4 ED [IF]', #PH
'11 4' => 'smc PENTAX-FA 645 45-85mm F4.5', #PH
'11 5' => 'smc PENTAX-FA 645 400mm F5.6 ED [IF]', #PH
'11 7' => 'smc PENTAX-FA 645 Macro 120mm F4', #PH
'11 8' => 'smc PENTAX-FA 645 80-160mm F4.5', #PH
'11 9' => 'smc PENTAX-FA 645 200mm F4 [IF]', #PH
'11 10' => 'smc PENTAX-FA 645 150mm F2.8 [IF]', #PH
'11 11' => 'smc PENTAX-FA 645 35mm F3.5 AL [IF]', #PH
'11 12' => 'smc PENTAX-FA 645 300mm F5.6 ED [IF]', #29
'11 14' => 'smc PENTAX-FA 645 55-110mm F5.6', #PH
'11 16' => 'smc PENTAX-FA 645 33-55mm F4.5 AL', #PH
'11 17' => 'smc PENTAX-FA 645 150-300mm F5.6 ED [IF]', #PH
'11 21' => 'HD PENTAX-D FA 645 35mm F3.5 AL [IF]', #29
'13 18' => 'smc PENTAX-D FA 645 55mm F2.8 AL [IF] SDM AW', #PH
'13 19' => 'smc PENTAX-D FA 645 25mm F4 AL [IF] SDM AW', #PH
'13 20' => 'HD PENTAX-D FA 645 90mm F2.8 ED AW SR', #PH
'13 253' => 'HD PENTAX-DA 645 28-45mm F4.5 ED AW SR', #Dominique Schrekling email
# missing:
# 'smc PENTAX-DA 645 25mm F4.0 AL SDM AW [IF]' ? different than D FA version?
#
# Q-mount lenses (21=auto focus lens, 22=manual focus)
#
'21 0' => 'Pentax Q Manual Lens', #PH
'21 1' => '01 Standard Prime 8.5mm F1.9', #PH
'21 2' => '02 Standard Zoom 5-15mm F2.8-4.5', #PH
'22 3' => '03 Fish-eye 3.2mm F5.6', #PH
'22 4' => '04 Toy Lens Wide 6.3mm F7.1', #PH
'22 5' => '05 Toy Lens Telephoto 18mm F8', #PH
'21 6' => '06 Telephoto Zoom 15-45mm F2.8', #PH
'21 7' => '07 Mount Shield 11.5mm F9', #PH (NC)
'21 8' => '08 Wide Zoom 3.8-5.9mm F3.7-4', #PH (NC)
);
# Pentax model ID codes - PH
my %pentaxModelID = (
0x0000d => 'Optio 330/430',
0x12926 => 'Optio 230',
0x12958 => 'Optio 330GS',
0x12962 => 'Optio 450/550',
0x1296c => 'Optio S',
0x12971 => 'Optio S V1.01',
0x12994 => '*ist D',
0x129b2 => 'Optio 33L',
0x129bc => 'Optio 33LF',
0x129c6 => 'Optio 33WR/43WR/555',
0x129d5 => 'Optio S4',
0x12a02 => 'Optio MX',
0x12a0c => 'Optio S40',
0x12a16 => 'Optio S4i',
0x12a34 => 'Optio 30',
0x12a52 => 'Optio S30',
0x12a66 => 'Optio 750Z',
0x12a70 => 'Optio SV',
0x12a75 => 'Optio SVi',
0x12a7a => 'Optio X',
0x12a8e => 'Optio S5i',
0x12a98 => 'Optio S50',
0x12aa2 => '*ist DS',
0x12ab6 => 'Optio MX4',
0x12ac0 => 'Optio S5n',
0x12aca => 'Optio WP',
0x12afc => 'Optio S55',
0x12b10 => 'Optio S5z',
0x12b1a => '*ist DL',
0x12b24 => 'Optio S60',
0x12b2e => 'Optio S45',
0x12b38 => 'Optio S6',
0x12b4c => 'Optio WPi', #13
0x12b56 => 'BenQ DC X600',
0x12b60 => '*ist DS2',
0x12b62 => 'Samsung GX-1S',
0x12b6a => 'Optio A10',
0x12b7e => '*ist DL2',
0x12b80 => 'Samsung GX-1L',
0x12b9c => 'K100D',
0x12b9d => 'K110D',
0x12ba2 => 'K100D Super', #JD
0x12bb0 => 'Optio T10/T20',
0x12be2 => 'Optio W10',
0x12bf6 => 'Optio M10',
0x12c1e => 'K10D',
0x12c20 => 'Samsung GX10',
0x12c28 => 'Optio S7',
0x12c2d => 'Optio L20',
0x12c32 => 'Optio M20',
0x12c3c => 'Optio W20',
0x12c46 => 'Optio A20',
0x12c78 => 'Optio E30',
0x12c7d => 'Optio E35',
0x12c82 => 'Optio T30',
0x12c8c => 'Optio M30',
0x12c91 => 'Optio L30',
0x12c96 => 'Optio W30',
0x12ca0 => 'Optio A30',
0x12cb4 => 'Optio E40',
0x12cbe => 'Optio M40',
0x12cc3 => 'Optio L40',
0x12cc5 => 'Optio L36',
0x12cc8 => 'Optio Z10',
0x12cd2 => 'K20D',
0x12cd4 => 'Samsung GX20', #8
0x12cdc => 'Optio S10',
0x12ce6 => 'Optio A40',
0x12cf0 => 'Optio V10',
0x12cfa => 'K200D',
0x12d04 => 'Optio S12',
0x12d0e => 'Optio E50',
0x12d18 => 'Optio M50',
0x12d22 => 'Optio L50',
0x12d2c => 'Optio V20',
0x12d40 => 'Optio W60',
0x12d4a => 'Optio M60',
0x12d68 => 'Optio E60/M90',
0x12d72 => 'K2000',
0x12d73 => 'K-m',
0x12d86 => 'Optio P70',
0x12d90 => 'Optio L70',
0x12d9a => 'Optio E70',
0x12dae => 'X70',
0x12db8 => 'K-7',
0x12dcc => 'Optio W80',
0x12dea => 'Optio P80',
0x12df4 => 'Optio WS80',
0x12dfe => 'K-x',
0x12e08 => '645D',
0x12e12 => 'Optio E80',
0x12e30 => 'Optio W90',
0x12e3a => 'Optio I-10',
0x12e44 => 'Optio H90',
0x12e4e => 'Optio E90',
0x12e58 => 'X90',
0x12e6c => 'K-r',
0x12e76 => 'K-5',
0x12e8a => 'Optio RS1000/RS1500',
0x12e94 => 'Optio RZ10',
0x12e9e => 'Optio LS1000',
0x12ebc => 'Optio WG-1 GPS',
0x12ed0 => 'Optio S1',
0x12ee4 => 'Q',
0x12ef8 => 'K-01',
0x12f0c => 'Optio RZ18',
0x12f16 => 'Optio VS20',
0x12f2a => 'Optio WG-2 GPS',
0x12f48 => 'Optio LS465',
0x12f52 => 'K-30',
0x12f5c => 'X-5',
0x12f66 => 'Q10',
0x12f70 => 'K-5 II',
0x12f71 => 'K-5 II s', #forum4515
0x12f7a => 'Q7',
0x12f84 => 'MX-1',
0x12f8e => 'WG-3 GPS',
0x12f98 => 'WG-3',
0x12fa2 => 'WG-10',
0x12fb6 => 'K-50',
0x12fc0 => 'K-3', #29
0x12fca => 'K-500',
0x12fe8 => 'WG-4', # (Ricoh)
0x12fde => 'WG-4 GPS', # (Ricoh)
0x13006 => 'WG-20', # (Ricoh)
0x13010 => '645Z',
0x1301a => 'K-S1',
0x13024 => 'K-S2', #29 (Ricoh)
0x1302e => 'Q-S1',
0x13056 => 'WG-30', # (Ricoh)
0x1307e => 'WG-30W', # (Ricoh)
0x13088 => 'WG-5 GPS', # (Ricoh)
0x1309c => 'K-3 II', #29 (Ricoh)
);
# Pentax city codes - (PH, Optio WP)
my %pentaxCities = (
0 => 'Pago Pago',
1 => 'Honolulu',
2 => 'Anchorage',
3 => 'Vancouver',
4 => 'San Francisco',
5 => 'Los Angeles',
6 => 'Calgary',
7 => 'Denver',
8 => 'Mexico City',
9 => 'Chicago',
10 => 'Miami',
11 => 'Toronto',
12 => 'New York',
13 => 'Santiago',
14 => 'Caracus',
15 => 'Halifax',
16 => 'Buenos Aires',
17 => 'Sao Paulo',
18 => 'Rio de Janeiro',
19 => 'Madrid',
20 => 'London',
21 => 'Paris',
22 => 'Milan',
23 => 'Rome',
24 => 'Berlin',
25 => 'Johannesburg',
26 => 'Istanbul',
27 => 'Cairo',
28 => 'Jerusalem',
29 => 'Moscow',
30 => 'Jeddah',
31 => 'Tehran',
32 => 'Dubai',
33 => 'Karachi',
34 => 'Kabul',
35 => 'Male',
36 => 'Delhi',
37 => 'Colombo',
38 => 'Kathmandu',
39 => 'Dacca',
40 => 'Yangon',
41 => 'Bangkok',
42 => 'Kuala Lumpur',
43 => 'Vientiane',
44 => 'Singapore',
45 => 'Phnom Penh',
46 => 'Ho Chi Minh',
47 => 'Jakarta',
48 => 'Hong Kong',
49 => 'Perth',
50 => 'Beijing',
51 => 'Shanghai',
52 => 'Manila',
53 => 'Taipei',
54 => 'Seoul',
55 => 'Adelaide',
56 => 'Tokyo',
57 => 'Guam',
58 => 'Sydney',
59 => 'Noumea',
60 => 'Wellington',
61 => 'Auckland',
62 => 'Lima',
63 => 'Dakar',
64 => 'Algiers',
65 => 'Helsinki',
66 => 'Athens',
67 => 'Nairobi',
68 => 'Amsterdam',
69 => 'Stockholm',
70 => 'Lisbon', #14
71 => 'Copenhagen', #25
72 => 'Warsaw',
73 => 'Prague',
74 => 'Budapest',
);
# digital filter tag information (ref PH, K-5)
# (also see %filterSettings below for decoding of filter parameters)
my %digitalFilter = (
Format => 'undef[17]',
RawConv => '($val!~/^\\0/ or $$self{OPTIONS}{Unknown}) ? join(" ",unpack("Cc*",$val)) : undef',
SeparateTable => 'DigitalFilter',
ValueConvInv => q{
return "\0" x 17 if $val eq "0";
$val = pack("Cc*", $val=~/[-+]?\d+/g);
length($val)==17 or warn("Expecting 17 values\n"), return undef;
return $val;
},
PrintConv => {
OTHER => \&PrintFilter, # this routine actually converts all values
0 => 'Off',
1 => 'Base Parameter Adjust',
2 => 'Soft Focus',
3 => 'High Contrast',
4 => 'Color Filter',
5 => 'Extract Color',
6 => 'Monochrome',
7 => 'Slim',
9 => 'Fisheye',
10 => 'Toy Camera',
11 => 'Retro',
12 => 'Pastel',
13 => 'Water Color',
14 => 'HDR',
16 => 'Miniature',
17 => 'Starburst',
18 => 'Posterization',
19 => 'Sketch Filter',
20 => 'Shading', # (Q)
21 => 'Invert Color', # (Q)
23 => 'Tone Expansion', #Forum5247
254 => 'Custom Filter',
},
);
# digital filter setting names and conversions (ref PH, K-5)
# Note: names must be unique for writing
my %filterSettings = (
1 => ['Brightness', '%+d'], # BPA (-8-+8)
2 => ['Saturation', '%+d'], # BPA (-3-+3)
3 => ['Hue', '%+d'], # BPA (-3-+3)
4 => ['Contrast', '%+d'], # BPA (-3-+3)
5 => ['Sharpness', '%+d'], # BPA (-3-+3)
6 => ['SoftFocus', '%d'], # Soft Focus/Custom (1-3)
7 => ['ShadowBlur', { 0=>'Off',1=>'On' }], # Soft Focus
8 => ['HighContrast', '%d'], # High Contrast/Custom (1-5)
9 => ['Color', { 1=>'Red',2=>'Magenta',3=>'Blue',4=>'Cyan',5=>'Green',6=>'Yellow' }], # Color Filter
10 => ['Density', { 1=>'Light',2=>'Standard',3=>'Dark' }], # Color Filter
11 => ['ExtractedColor',{ 0=>'Off',1=>'Red',2=>'Magenta',3=>'Blue',4=>'Cyan',5=>'Green',6=>'Yellow' }], # ExtractColor [x2]
12 => ['ColorRange', '%+d'], # ExtractColor [x2] (-2-+2)
13 => ['FilterEffect', { 0=>'Off',1=>'Red',2=>'Green',3=>'Blue',4=>'Infrared'}], # Monochrome
14 => ['ToningBA', '%+d'], # Monochrome (-3-+3)
15 => ['InvertColor', { 0=>'Off',1=>'On' }], # Custom/Invert Color
16 => ['Slim', '%+d'], # Slim (-8-+8)
17 => ['EffectDensity', { 1=>'Sparse',2=>'Normal',3=>'Dense' }], # Starburst
18 => ['Size', { 1=>'Small',2=>'Medium',3=>'Large' }], # Starburst
19 => ['Angle', { 0=>'0deg',2=>'30deg',3=>'45deg',4=>'60deg'}], # Starburst (1 is unused)
20 => ['Fisheye', { 1=>'Weak',2=>'Medium',3=>'Strong' }], # Fisheye
21 => ['DistortionType', '%d'], # Custom (1-3)
22 => ['DistortionLevel',{0=>'Off',1=>'Weak',2=>'Medium',3=>'Strong' }], #Custom
23 => ['ShadingType', '%d'], # Custom/Shading (1-6)
24 => ['ShadingLevel', '%+d'], # Custom/Shading (-3-+3)
25 => ['Shading', '%d'], # Toy Camera (1-3)
26 => ['Blur', '%d'], # Toy Camera (1-3)
27 => ['ToneBreak', { 0=>'Off',1=>'Red',2=>'Green',3=>'Blue',4=>'Yellow'}], # Toy Camera/Custom
28 => ['Toning', '%+d'], # Retro (-3-+3)
29 => ['FrameComposite',{ 0=>'None',1=>'Thin',2=>'Medium',3=>'Thick' }], # Retro
30 => ['PastelStrength',{ 1=>'Weak',2=>'Medium',3=>'Strong' }], # Pastel
31 => ['Intensity', '%d'], # Water Color (1-3)
32 => ['Saturation2', { 0=>'Off',1=>'Low',2=>'Medium',3=>'High' }], # Water Color
33 => ['HDR', { 1=>'Weak',2=>'Medium',3=>'Strong' }], # HDR
# (34 missing)
35 => ['FocusPlane', '%+d'], # Miniature (-3-+3)
36 => ['FocusWidth', { 1=>'Narrow',2=>'Middle',3=>'Wide' }], # Miniature
37 => ['PlaneAngle', { 0=>'Horizontal',1=>'Vertical',2=>'Positive slope',3=>'Negative slope' }], # Miniature
38 => ['Blur2', '%d'], # Miniature (1-3)
39 => ['Shape', { 1=>'Cross',2=>'Star',3=>'Snowflake',4=>'Heart',5=>'Note'}], # Starburst
40 => ['Posterization', '%d'], # Posterization (1-5)
41 => ['Contrast2', { 1=>'Low',2=>'Medium',3=>'High'}], # Sketch Filter
42 => ['ScratchEffect', { 0=>'Off',1=>'On' }], # Sketch Filter
45 => ['ToneExpansion', { 1=>'Low',2=>'Medium',3=>'High' }], # Tone Expansion (ref Forum5247)
);
# decoding for Pentax Firmware ID tags - PH
my %pentaxFirmwareID = (
# the first 2 numbers are the firmware version, I'm not sure what the second 2 mean
# Note: the byte order may be different for some models
# which give, for example, version 0.01 instead of 1.00
ValueConv => sub {
my $val = shift;
return $val unless length($val) == 4;
# (value is encrypted by toggling all bits)
my @a = map { $_ ^ 0xff } unpack("C*",$val);
return sprintf('%d %.2d %.2d %.2d', @a);
},
ValueConvInv => sub {
my $val = shift;
my @a = $val=~/\b\d+\b/g;
return $val unless @a == 4;
@a = map { ($_ & 0xff) ^ 0xff } @a;
return pack("C*", @a);
},
PrintConv => '$val=~tr/ /./; $val',
PrintConvInv => '$val=~s/^(\d+)\.(\d+)\.(\d+)\.(\d+)/$1 $2 $3 $4/ ? $val : undef',
);
# convert 16 or 77 metering segment values to approximate LV equivalent - PH
my %convertMeteringSegments = (
PrintConv => sub { join ' ', map(
{ $_==255 ? 'n/a' : $_==0 ? '0' : sprintf '%.1f', $_ / 8 - 6 } split(' ',$_[0])
) },
PrintConvInv => sub { join ' ', map(
{ /^n/i ? 255 : $_==0 ? '0' : int(($_ + 6) * 8 + 0.5) } split(' ',$_[0])
) },
);
# lens code conversions
my %lensCode = (
Unknown => 1,
PrintConv => 'sprintf("0x%.2x", $val)',
PrintConvInv => 'hex($val)',
);
# conversions for tags 0x0053-0x005a
my %colorTemp = (
Writable => 'undef',
Count => 4,
ValueConv => sub {
my $val = shift;
return $val unless length $val == 4;
my @a = unpack 'nCC', $val;
$a[0] = 53190 - $a[0];
$a[1] = ($a[2] & 0x0f); $a[1] -= 16 if $a[1] >= 8;
$a[2] = ($a[2] >> 4); $a[2] -= 16 if $a[2] >= 8;
return "@a";
},
ValueConvInv => sub {
my $val = shift;
my @a = split ' ', $val;
return undef unless @a == 3;
return pack 'nCC', 53190 - $a[0], 0, ($a[1] & 0x0f) + (($a[2] & 0x0f) << 4);
},
PrintConv => sub {
$_ = shift;
s/ ([1-9])/ +$1/g;
s/ 0/ 0/g;
return $_;
},
PrintConvInv => '$val',
);
# conversions for KelvinWB tags
my %kelvinWB = (
Format => 'int16u[4]',
ValueConv => sub {
my @a = split ' ', shift;
(53190 - $a[0]) . ' ' . $a[1] . ' ' . ($a[2] / 8192) . ' ' . ($a[3] / 8192);
},
ValueConvInv => sub {
my @a = split ' ', shift;
(53190 - $a[0]) . ' ' . $a[1] . ' ' . int($a[2]*8192+0.5) . ' ' . int($a[3]*8192+0.5);
},
);
# common attributes for writable BinaryData directories
my %binaryDataAttrs = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FIRST_ENTRY => 0,
);
# Pentax makernote tags
%Image::ExifTool::Pentax::Main = (
WRITE_PROC => \&Image::ExifTool::Exif::WriteExif,
CHECK_PROC => \&Image::ExifTool::Exif::CheckExif,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
WRITABLE => 1,
0x0000 => { #5
Name => 'PentaxVersion',
Writable => 'int8u',
Count => 4,
PrintConv => '$val=~tr/ /./; $val',
PrintConvInv => '$val=~tr/./ /; $val',
# 0.1.0.3 - PENTAX Optio E40
# 3.0.0.0 - K10D
# 3.1.0.0 - Optio A40/S10/L36/L40/M40/V10
# 3.1.2.0 - Optio Z10
# 4.0.2.0 - Optio E50
# 4.1.0.0 - Optio S12
# 4.1.1.0 - Optio M50
# 4.1.2.0 - K20D, K200D
# 4.2.0.0 - Optio L50/V20
# 4.2.1.0 - Optio E60/M90
# 4.2.2.0 - Optio W60
# 4.2.3.0 - Optio M60
# 4.4.0.1 - K-m, K2000
# 4.5.0.0 - Optio E70/L70
# 4.5.0.0 - Optio P70
# 4.6.0.0 - Optio E80/E90/W80
# 5.0.0.0 - K-7, Optio P80/WS80
# 5.1.0.0 - K-x
# 5.2.0.0 - Optio I-10
# 5.3.0.0 - Optio H90
# 5.3.2.0 - Optio W90
# 6.0.0.0 - K-r, 645D
# 6.1.3.0 - Optio LS1000/RS1000/RS1500/RZ10
# 7.0.0.0 - K-5
# 7.1.0.0 - Optio WG-1GPS/WG-10
# 7.2.0.0 - Optio S1
# 8.0.0.0 - Q
# 8.0.1.0 - Optio RZ18
# 8.0.4.0 - Optio VS20
# 8.1.0.0 - Optio LS465/WG-2GPS
# 9.0.0.0 - K-01
# 9.1.2.0 - X-5
# 10.0.0.0 - K-30, K-50, K-500, K-5 II
# 10.0.2.0 - Q10
# 10.2.0.0 - WG-3
# 10.2.1.0 - MX-1
# 10.4.1.0 - WG-3 GPS
# 10.6.1.0 - Q-S1, Q7
# 11.0.0.0 - K-3
# 11.2.1.0 - 645Z
# 11.3.0.0 - K-S1
# 11.5.0.0 - K-S2
# 11.6.1.0 - K-3 II
},
0x0001 => { #PH
Name => 'PentaxModelType',
Writable => 'int16u',
# (values of 0-5 seem to group models into 6 categories, ref 13)
},
0x0002 => { #PH
Name => 'PreviewImageSize',
Groups => { 2 => 'Image' },
Writable => 'int16u',
Count => 2,
PrintConv => '$val =~ tr/ /x/; $val',
PrintConvInv => '$val =~ tr/x/ /; $val',
},
0x0003 => { #PH
Name => 'PreviewImageLength',
OffsetPair => 0x0004, # point to associated offset
DataTag => 'PreviewImage',
Groups => { 2 => 'Image' },
Writable => 'int32u',
Protected => 2,
},
0x0004 => { #PH
Name => 'PreviewImageStart',
IsOffset => 2, # code to use original base
Protected => 2,
OffsetPair => 0x0003, # point to associated byte count
DataTag => 'PreviewImage',
Groups => { 2 => 'Image' },
Writable => 'int32u',
},
0x0005 => { #13
Name => 'PentaxModelID',
Writable => 'int32u',
PrintHex => 1,
SeparateTable => 1,
DataMember => 'PentaxModelID',
RawConv => '$$self{PentaxModelID} = $val',
PrintConv => \%pentaxModelID,
},
0x0006 => { #5
# Note: Year is int16u in MM byte ordering regardless of EXIF byte order
Name => 'Date',
Groups => { 2 => 'Time' },
Notes => 'changing either Date or Time will affect ShutterCount decryption',
Writable => 'undef',
Count => 4,
Shift => 'Time',
DataMember => 'PentaxDate',
RawConv => '$$self{PentaxDate} = $val', # save to decrypt ShutterCount
ValueConv => 'length($val)==4 ? sprintf("%.4d:%.2d:%.2d",unpack("nC2",$val)) : "Unknown ($val)"',
ValueConvInv => q{
$val =~ s/(\d) .*/$1/; # remove Time
my @v = split /:/, $val;
return pack("nC2",$v[0],$v[1],$v[2]);
},
},
0x0007 => { #5
Name => 'Time',
Groups => { 2 => 'Time' },
Writable => 'undef',
Count => 3,
Shift => 'Time',
DataMember => 'PentaxTime',
RawConv => '$$self{PentaxTime} = $val', # save to decrypt ShutterCount
ValueConv => 'length($val)>=3 ? sprintf("%.2d:%.2d:%.2d",unpack("C3",$val)) : "Unknown ($val)"',
ValueConvInv => q{
$val =~ s/^[0-9:]+ (\d)/$1/; # remove Date
return pack("C3",split(/:/,$val));
},
},
0x0008 => { #2
Name => 'Quality',
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
0 => 'Good',
1 => 'Better',
2 => 'Best',
3 => 'TIFF', #5
4 => 'RAW', #5
5 => 'Premium', #PH (K20D)
7 => 'RAW (pixel shift enabled)', #forum6536 (K-3 II)
65535 => 'n/a', #PH (Q MOV video)
},
},
0x0009 => { #3
Name => 'PentaxImageSize',
Groups => { 2 => 'Image' },
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
0 => '640x480',
1 => 'Full', #PH - this can mean 2048x1536 or 2240x1680 or ... ?
2 => '1024x768',
3 => '1280x960', #PH (Optio WP)
4 => '1600x1200',
5 => '2048x1536',
8 => '2560x1920 or 2304x1728', #PH (Optio WP) or #14
9 => '3072x2304', #PH (Optio M30)
10 => '3264x2448', #13
19 => '320x240', #PH (Optio WP)
20 => '2288x1712', #13
21 => '2592x1944',
22 => '2304x1728 or 2592x1944', #2 or #14
23 => '3056x2296', #13
25 => '2816x2212 or 2816x2112', #13 or #14
27 => '3648x2736', #PH (Optio A20)
29 => '4000x3000', #PH (X70)
30 => '4288x3216', #PH (Optio RS1000)
31 => '4608x3456', #PH (Optio RZ18)
129 => '1920x1080', #PH (Optio RZ10)
135 => '4608x2592', #PH (Q10 stretch filter)
257 => '3216x3216', #PH (Optio RZ10)
'0 0' => '2304x1728', #13
'4 0' => '1600x1200', #PH (Optio MX4)
'5 0' => '2048x1536', #13
'8 0' => '2560x1920', #13
'32 2' => '960x640', #7
'33 2' => '1152x768', #7
'34 2' => '1536x1024', #7
'35 1' => '2400x1600', #7
'36 0' => '3008x2008 or 3040x2024', #PH
'37 0' => '3008x2000', #13
# 65535 - seen for an X-5 panorama (PH)
},
},
0x000b => { #3
Name => 'PictureMode',
Writable => 'int16u',
Count => -1,
Notes => q{
1 or 2 values. Decimal values differentiate Optio 555 modes which are
different from other models
},
ValueConv => '(IsInt($val) and $val < 4 and $$self{Model} =~ /Optio 555\b/) ? $val + 0.1 : $val',
ValueConvInv => 'int $val',
PrintConvColumns => 2,
PrintConv => [{
0 => 'Program', #PH
0.1 => 'Av', #PH (Optio 555)
1 => 'Shutter Speed Priority', #JD
1.1 => 'M', #PH (Optio 555)
2 => 'Program AE', #13
2.1 => 'Tv', #PH (Optio 555)
3 => 'Manual', #13
3.1 => 'USER', #PH (Optio 555)
5 => 'Portrait',
6 => 'Landscape',
8 => 'Sport', #PH
9 => 'Night Scene',
# 10 "full mode"? #13
11 => 'Soft', #PH
12 => 'Surf & Snow',
13 => 'Candlelight', #13
14 => 'Autumn',
15 => 'Macro',
17 => 'Fireworks',
18 => 'Text',
19 => 'Panorama', #PH
20 => '3-D', #PH (Optio 555)
21 => 'Black & White', #PH (Optio 555)
22 => 'Sepia', #PH (Optio 555)
23 => 'Red', #PH (Optio 555)
24 => 'Pink', #PH (Optio 555)
25 => 'Purple', #PH (Optio 555)
26 => 'Blue', #PH (Optio 555)
27 => 'Green', #PH (Optio 555)
28 => 'Yellow', #PH (Optio 555)
30 => 'Self Portrait', #PH
31 => 'Illustrations', #13
33 => 'Digital Filter', #13
35 => 'Night Scene Portrait', #25
37 => 'Museum', #PH
38 => 'Food', #PH
39 => 'Underwater', #25
40 => 'Green Mode', #PH
49 => 'Light Pet', #PH
50 => 'Dark Pet', #PH
51 => 'Medium Pet', #PH
53 => 'Underwater', #PH
54 => 'Candlelight', #PH
55 => 'Natural Skin Tone', #PH
56 => 'Synchro Sound Record', #PH
58 => 'Frame Composite', #14
59 => 'Report', #25
60 => 'Kids', #13
61 => 'Blur Reduction', #13
63 => 'Panorama 2', #PH (X-5)
65 => 'Half-length Portrait', #JD
66 => 'Portrait 2', #PH (LS645)
74 => 'Digital Microscope', #PH (WG-4)
75 => 'Blue Sky', #PH (LS465)
80 => 'Miniature', #PH (VS20)
81 => 'HDR', #PH (LS465)
83 => 'Fisheye', #PH (VS20)
85 => 'Digital Filter 4', #PH (WG-5)
221 => 'P', #PH (Optio 555)
255=> 'PICT', #PH (Optio 555)
}],
},
0x000c => { #PH
Name => 'FlashMode',
Writable => 'int16u',
Count => -1,
PrintHex => 1,
PrintConv => [{
0x000 => 'Auto, Did not fire',
0x001 => 'Off, Did not fire',
0x002 => 'On, Did not fire', #19
0x003 => 'Auto, Did not fire, Red-eye reduction',
0x005 => 'On, Did not fire, Wireless (Master)', #19
0x100 => 'Auto, Fired',
0x102 => 'On, Fired',
0x103 => 'Auto, Fired, Red-eye reduction',
0x104 => 'On, Red-eye reduction',
0x105 => 'On, Wireless (Master)', #19
0x106 => 'On, Wireless (Control)', #19
0x108 => 'On, Soft',
0x109 => 'On, Slow-sync',
0x10a => 'On, Slow-sync, Red-eye reduction',
0x10b => 'On, Trailing-curtain Sync',
},{ #19 (AF-540FGZ flash)
0x000 => 'n/a - Off-Auto-Aperture', #19
0x03f => 'Internal',
0x100 => 'External, Auto',
0x23f => 'External, Flash Problem', #JD
0x300 => 'External, Manual',
0x304 => 'External, P-TTL Auto',
0x305 => 'External, Contrast-control Sync', #JD
0x306 => 'External, High-speed Sync',
0x30c => 'External, Wireless',
0x30d => 'External, Wireless, High-speed Sync',
}],
},
0x000d => [ #2
{
Name => 'FocusMode',
# (can't test for "PENTAX" because MOV videos don't have Make)
Condition => '$$self{Make} !~ /^Asahi/',
Notes => 'Pentax models',
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => { #PH
0 => 'Normal',
1 => 'Macro',
2 => 'Infinity',
3 => 'Manual',
4 => 'Super Macro', #JD
5 => 'Pan Focus',
16 => 'AF-S (Focus-priority)', #17
17 => 'AF-C (Focus-priority)', #17
18 => 'AF-A (Focus-priority)', #PH (educated guess)
32 => 'Contrast-detect (Focus-priority)', #PH (K-5)
33 => 'Tracking Contrast-detect (Focus-priority)', #PH (K-5)
# bit 8 indicates release priority
272 => 'AF-S (Release-priority)', #PH (K-5,K-3)
273 => 'AF-C (Release-priority)', #PH (K-5,K-3)
274 => 'AF-A (Release-priority)', #PH (K-3)
288 => 'Contrast-detect (Release-priority)', #PH (K-01)
},
},{
Name => 'FocusMode',
Writable => 'int16u',
Notes => 'Asahi models',
PrintConv => { #2
0 => 'Normal',
1 => 'Macro (1)',
2 => 'Macro (2)',
3 => 'Infinity',
},
},
],
0x000e => [{ #7
Name => 'AFPointSelected',
Condition => '$$self{Model} !~ /K-3\b/',
Writable => 'int16u',
Notes => 'all models but the K-3',
PrintConvColumns => 2,
PrintConv => [{
# 0 - Contrast-detect AF? - PH (K-5)
0xffff => 'Auto',
0xfffe => 'Fixed Center',
0xfffd => 'Automatic Tracking AF', #JD
0xfffc => 'Face Detect AF', #JD
0xfffb => 'AF Select', #PH (Q select from 25-areas)
0 => 'None', #PH (Q in manual focus mode)
1 => 'Upper-left',
2 => 'Top',
3 => 'Upper-right',
4 => 'Left',
5 => 'Mid-left',
6 => 'Center',
7 => 'Mid-right',
8 => 'Right',
9 => 'Lower-left',
10 => 'Bottom',
11 => 'Lower-right',
},
# (second number exists for K-5II(s) is usually 0, but is 1 for AF.C with
# AFPointMode=='Select' and extended tracking focus points are enabled in the settings)
],
},{
Name => 'AFPointSelected',
Writable => 'int16u',
Notes => 'K-3',
PrintConvColumns => 2,
PrintConv => [{
# 0 - Contrast-detect AF? - PH (K-5)
0xffff => 'Auto',
0xfffe => 'Fixed Center',
0xfffd => 'Automatic Tracking AF', #JD
0xfffc => 'Face Detect AF', #JD
0xfffb => 'AF Select', #PH (Q select from 25-areas)
# AF pattern: (ref forum5422)
# 01 02 03 04 05
# 06 07 08 09 10
# 11 12 13 14 15 16 17
# 18 19 20 21 22
# 23 24 25 26 27
0 => 'None',
1 => 'Top-left',
2 => 'Top Near-left',
3 => 'Top',
4 => 'Top Near-right',
5 => 'Top-right',
6 => 'Upper-left',
7 => 'Upper Near-left',
8 => 'Upper-middle',
9 => 'Upper Near-right',
10 => 'Upper-right',
11 => 'Far Left',
12 => 'Left',
13 => 'Near-left',
14 => 'Center',
15 => 'Near-right',
16 => 'Right',
17 => 'Far Right',
18 => 'Lower-left',
19 => 'Lower Near-left',
20 => 'Lower-middle',
21 => 'Lower Near-right',
22 => 'Lower-right',
23 => 'Bottom-left',
24 => 'Bottom Near-left',
25 => 'Bottom',
26 => 'Bottom Near-right',
27 => 'Bottom-right',
#forum5892
257 => 'Zone Select Top-left',
258 => 'Zone Select Top Near-left',
259 => 'Zone Select Top',
260 => 'Zone Select Top Near-right',
261 => 'Zone Select Top-right',
262 => 'Zone Select Upper-left',
263 => 'Zone Select Upper Near-left',
264 => 'Zone Select Upper-middle',
265 => 'Zone Select Upper Near-right',
266 => 'Zone Select Upper-right',
267 => 'Zone Select Far Left',
268 => 'Zone Select Left',
269 => 'Zone Select Near-left',
270 => 'Zone Select Center',
271 => 'Zone Select Near-right',
272 => 'Zone Select Right',
273 => 'Zone Select Far Right',
274 => 'Zone Select Lower-left',
275 => 'Zone Select Lower Near-left',
276 => 'Zone Select Lower-middle',
277 => 'Zone Select Lower Near-right',
278 => 'Zone Select Lower-right',
279 => 'Zone Select Bottom-left',
280 => 'Zone Select Bottom Near-left',
281 => 'Zone Select Bottom',
282 => 'Zone Select Bottom Near-right',
283 => 'Zone Select Bottom-right',
},{ #forum5892
0 => 'Single Point',
1 => 'Expanded Area 9-point (S)',
3 => 'Expanded Area 25-point (M)',
5 => 'Expanded Area 27-point (L)',
}],
}],
0x000f => [{ #PH
Name => 'AFPointsInFocus',
Condition => '$$self{Model} !~ /K-3\b/',
Notes => 'models other than the K-3',
Writable => 'int16u',
PrintHex => 1,
PrintConv => {
0xffff => 'None',
0 => 'Fixed Center or Multiple', #PH/14
1 => 'Top-left',
2 => 'Top-center',
3 => 'Top-right',
4 => 'Left',
5 => 'Center',
6 => 'Right',
7 => 'Bottom-left',
8 => 'Bottom-center',
9 => 'Bottom-right',
},
},{ #PH
Name => 'AFPointsInFocus',
Writable => 'int32u',
Notes => 'K-3 only',
PrintHex => 1,
PrintConv => {
0 => '(none)',
BITMASK => {
0 => 'Top-left',
1 => 'Top Near-left',
2 => 'Top',
3 => 'Top Near-right',
4 => 'Top-right',
5 => 'Upper-left',
6 => 'Upper Near-left',
7 => 'Upper-middle',
8 => 'Upper Near-right',
9 => 'Upper-right',
10 => 'Far Left',
11 => 'Left',
12 => 'Near-left',
13 => 'Center',
14 => 'Near-right',
15 => 'Right',
16 => 'Far Right',
17 => 'Lower-left',
18 => 'Lower Near-left',
19 => 'Lower-middle',
20 => 'Lower Near-right',
21 => 'Lower-right',
22 => 'Bottom-left',
23 => 'Bottom Near-left',
24 => 'Bottom',
25 => 'Bottom Near-right',
26 => 'Bottom-right',
},
},
}],
0x0010 => { #PH
Name => 'FocusPosition',
Writable => 'int16u',
Notes => 'related to focus distance but affected by focal length',
},
0x0012 => { #PH
Name => 'ExposureTime',
Writable => 'int32u',
Priority => 0,
ValueConv => '$val * 1e-5',
ValueConvInv => '$val * 1e5',
# value may be 0xffffffff in Bulb mode (ref JD)
PrintConv => '$val > 42949 ? "Unknown (Bulb)" : Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => '$val=~/(unknown|bulb)/i ? $val : Image::ExifTool::Exif::ConvertFraction($val)',
},
0x0013 => { #PH
Name => 'FNumber',
Writable => 'int16u',
Priority => 0,
ValueConv => '$val / 10',
ValueConvInv => '$val * 10',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
# ISO Tag - Entries confirmed by W. Smith 12 FEB 04
0x0014 => {
Name => 'ISO',
Writable => 'int16u',
Notes => 'may be different than EXIF:ISO, which can round to the nearest full stop',
PrintConvColumns => 4,
PrintConv => {
# 1/3 EV step values
3 => 50,
4 => 64,
5 => 80,
6 => 100,
7 => 125, #PH
8 => 160, #PH
9 => 200,
10 => 250,
11 => 320, #PH
12 => 400,
13 => 500,
14 => 640,
15 => 800,
16 => 1000,
17 => 1250,
18 => 1600, #PH
19 => 2000, #PH
20 => 2500, #PH
21 => 3200, #PH
22 => 4000,
23 => 5000,
24 => 6400, #PH
25 => 8000, #PH
26 => 10000, #PH
27 => 12800, #PH
28 => 16000, #PH
29 => 20000, #PH
30 => 25600, #PH
31 => 32000, #PH
32 => 40000, #PH
33 => 51200, #PH
34 => 64000, #PH (NC)
35 => 80000, #PH (NC)
36 => 102400, #27
37 => 128000, #PH (NC)
38 => 160000, #PH (NC)
39 => 204800, #27
# Optio 330/430 (oddball)
50 => 50, #PH
100 => 100, #PH
200 => 200, #PH
400 => 400, #PH
800 => 800, #PH
1600 => 1600, #PH
3200 => 3200, #PH
# 1/2 EV step values
258 => 50, #PH (NC)
259 => 70, #PH (NC)
260 => 100, #19
261 => 140, #19
262 => 200, #19
263 => 280, #19
264 => 400, #19
265 => 560, #19
266 => 800, #19
267 => 1100, #19
268 => 1600, #19
269 => 2200, #PH
270 => 3200, #PH
271 => 4500, #PH
272 => 6400, #PH
273 => 9000, #PH
274 => 12800, #PH
275 => 18000, #PH
276 => 25600, #PH
277 => 36000, #PH
278 => 51200, #PH
# 65534 Auto? (Q/Q10/Q7 MOV) PH
# 65535 Auto? (K-01 MP4) PH
},
},
0x0015 => { #PH
Name => 'LightReading',
Format => 'int16s', # (because I may have seen negative numbers)
Writable => 'int16u',
# ranges from 0-12 for my Optio WP - PH
Notes => q{
calibrated differently for different models. For the Optio WP, add 6 to get
approximate Light Value. May not be valid for some models, eg. Optio S
},
},
0x0016 => { #PH
Name => 'ExposureCompensation',
Writable => 'int16u',
ValueConv => '($val - 50) / 10',
ValueConvInv => 'int($val * 10 + 50.5)',
PrintConv => '$val ? sprintf("%+.1f", $val) : 0',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
0x0017 => { #3
Name => 'MeteringMode',
Writable => 'int16u',
PrintConv => {
0 => 'Multi-segment',
1 => 'Center-weighted average',
2 => 'Spot',
# have seen value of 16 for E70
},
},
0x0018 => { #PH
Name => 'AutoBracketing',
Writable => 'int16u',
Count => -1,
Notes => q{
1 or 2 values: exposure bracket step in EV, then extended bracket if
available. Extended bracket values are printed as 'WB-BA', 'WB-GM',
'Saturation', 'Sharpness', 'Contrast', 'Hue' or 'HighLowKey' followed by
'+1', '+2' or '+3' for step size
},
# 1=.3ev, 2=.7, 3=1.0, ... 10=.5ev, 11=1.5, ...
ValueConv => [ '$val<10 ? $val/3 : $val-9.5' ],
ValueConvInv => [ 'abs($val-int($val)-.5)>0.05 ? int($val*3+0.5) : int($val+10)' ],
PrintConv => sub {
my @v = split(' ', shift);
$v[0] = sprintf('%.1f', $v[0]) if $v[0];
if ($v[1]) {
my %s = (1=>'WB-BA',2=>'WB-GM',3=>'Saturation',4=>'Sharpness',
5=>'Contrast',6=>'Hue',7=>'HighLowKey');
my $t = $v[1] >> 8;
$v[1] = sprintf('%s+%d', $s{$t} || "Unknown($t)", $v[1] & 0xff);
} elsif (defined $v[1]) {
$v[1] = 'No Extended Bracket',
}
return join(' EV, ', @v);
},
PrintConvInv => sub {
my @v = split(/, ?/, shift);
$v[0] =~ s/ ?EV//i;
if ($v[1]) {
my %s = ('WB-BA'=>1,'WB-GM'=>2,'Saturation'=>3,'Sharpness'=>4,
'Contrast'=>5,'Hue'=>6,'HighLowKey'=>7);
if ($v[1] =~ /^No\b/i) {
$v[1] = 0;
} elsif ($v[1] =~ /Unknown\((\d+)\)\+(\d+)/i) {
$v[1] = ($1 << 8) + $2;
} elsif ($v[1] =~ /([\w-]+)\+(\d+)/ and $s{$1}) {
$v[1] = ($s{$1} << 8) + $2;
} else {
warn "Bad extended bracket\n";
}
}
return "@v";
},
},
0x0019 => { #3
Name => 'WhiteBalance',
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
0 => 'Auto',
1 => 'Daylight',
2 => 'Shade',
3 => 'Fluorescent', #2
4 => 'Tungsten',
5 => 'Manual',
6 => 'Daylight Fluorescent', #13
7 => 'Day White Fluorescent', #13
8 => 'White Fluorescent', #13
9 => 'Flash', #13
10 => 'Cloudy', #13
11 => 'Warm White Fluorescent', #PH (K-3)
14 => 'Multi Auto', #PH (K-3)
15 => 'Color Temperature Enhancement', #PH
17 => 'Kelvin', #PH
0xfffe => 'Unknown', #13
0xffff => 'User-Selected', #13
},
},
0x001a => { #5
Name => 'WhiteBalanceMode',
Writable => 'int16u',
PrintConv => {
1 => 'Auto (Daylight)',
2 => 'Auto (Shade)',
3 => 'Auto (Flash)',
4 => 'Auto (Tungsten)',
6 => 'Auto (Daylight Fluorescent)', #19 (NC)
7 => 'Auto (Day White Fluorescent)', #17 (K100D guess)
8 => 'Auto (White Fluorescent)', #17 (K100D guess)
10 => 'Auto (Cloudy)', #17 (K100D guess)
# 0xfffd observed in K100D (ref 17)
0xfffe => 'Unknown', #PH (you get this when shooting night sky shots)
0xffff => 'User-Selected',
},
},
0x001b => { #6
Name => 'BlueBalance',
Writable => 'int16u',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + 0.5)',
},
0x001c => { #6
Name => 'RedBalance',
Writable => 'int16u',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + 0.5)',
},
0x001d => [
# Would be nice if there was a general way to determine units for FocalLength...
{
# Optio 30, 33WR, 43WR, 450, 550, 555, 750Z, X
Name => 'FocalLength',
Condition => '$self->{Model} =~ /^PENTAX Optio (30|33WR|43WR|450|550|555|750Z|X)\b/',
Writable => 'int32u',
Priority => 0,
ValueConv => '$val / 10',
ValueConvInv => '$val * 10',
PrintConv => 'sprintf("%.1f mm",$val)',
PrintConvInv => '$val=~s/\s*mm//;$val',
},
{
# K100D, Optio 230, 330GS, 33L, 33LF, A10, M10, MX, MX4, S, S30,
# S4, S4i, S5i, S5n, S5z, S6, S45, S50, S55, S60, SV, Svi, W10, WP,
# *ist D, DL, DL2, DS, DS2
# (Note: the Optio S6 seems to report the minimum focal length - PH)
Name => 'FocalLength',
Writable => 'int32u',
Priority => 0,
ValueConv => '$val / 100',
ValueConvInv => '$val * 100',
PrintConv => 'sprintf("%.1f mm",$val)',
PrintConvInv => '$val=~s/\s*mm//;$val',
},
],
0x001e => { #3
Name => 'DigitalZoom',
Writable => 'int16u',
ValueConv => '$val / 100', #14
ValueConvInv => '$val * 100', #14
},
0x001f => {
Name => 'Saturation',
Writable => 'int16u',
Count => -1,
Notes => '1 or 2 values',
PrintConvColumns => 2,
PrintConv => [{ # the *istD has pairs of values - PH
0 => '-2 (low)', #PH
1 => '0 (normal)', #PH
2 => '+2 (high)', #PH
3 => '-1 (med low)', #2
4 => '+1 (med high)', #2
5 => '-3 (very low)', #PH
6 => '+3 (very high)', #PH (NC)
7 => '-4 (minimum)', #PH (NC)
8 => '+4 (maximum)', #PH (K-5)
65535 => 'None', #PH (Monochrome)
}],
},
0x0020 => {
Name => 'Contrast',
Writable => 'int16u',
Count => -1,
Notes => '1 or 2 values',
PrintConvColumns => 2,
PrintConv => [{ # the *istD has pairs of values - PH
0 => '-2 (low)', #PH
1 => '0 (normal)', #PH
2 => '+2 (high)', #PH
3 => '-1 (med low)', #2
4 => '+1 (med high)', #2
5 => '-3 (very low)', #PH
6 => '+3 (very high)', #PH (NC)
7 => '-4 (minimum)', #PH (NC)
8 => '+4 (maximum)', #PH (K-5)
65535 => 'n/a', # got this for a Backlight Silhouette - PH (Q)
}],
},
0x0021 => {
Name => 'Sharpness',
Writable => 'int16u',
Count => -1,
Notes => '1 or 2 values',
PrintConvColumns => 2,
PrintConv => [{ # the *istD has pairs of values - PH
0 => '-2 (soft)', #PH
1 => '0 (normal)', #PH
2 => '+2 (hard)', #PH
3 => '-1 (med soft)', #2
4 => '+1 (med hard)', #2
5 => '-3 (very soft)', #(NC)
6 => '+3 (very hard)', #(NC)
7 => '-4 (minimum)', #PH (NC)
8 => '+4 (maximum)', #PH (NC)
}],
},
0x0022 => { #PH
Name => 'WorldTimeLocation',
Groups => { 2 => 'Time' },
Writable => 'int16u',
PrintConv => {
0 => 'Hometown',
1 => 'Destination',
},
},
0x0023 => { #PH
Name => 'HometownCity',
Groups => { 2 => 'Time' },
Writable => 'int16u',
SeparateTable => 'City',
PrintConv => \%pentaxCities,
},
0x0024 => { #PH
Name => 'DestinationCity',
Groups => { 2 => 'Time' },
Writable => 'int16u',
SeparateTable => 'City',
PrintConv => \%pentaxCities,
},
0x0025 => { #PH
Name => 'HometownDST',
Groups => { 2 => 'Time' },
Writable => 'int16u',
PrintConv => { 0 => 'No', 1 => 'Yes' },
},
0x0026 => { #PH
Name => 'DestinationDST',
Groups => { 2 => 'Time' },
Writable => 'int16u',
PrintConv => { 0 => 'No', 1 => 'Yes' },
},
0x0027 => { #PH
Name => 'DSPFirmwareVersion',
Writable => 'undef',
# - for K10D, this comes from 4 bytes at offset 0x1c in the firmware file
%pentaxFirmwareID,
},
0x0028 => { #PH
Name => 'CPUFirmwareVersion',
Writable => 'undef',
# - for K10D, this comes from 4 bytes at offset 0x83fbf8 in firmware file
%pentaxFirmwareID,
},
0x0029 => { #5
Name => 'FrameNumber',
# - one report that this has a value of 84 for the first image with a *istDS
# - another report that file number 4 has frameNumber 154 for *istD, and
# that framenumber jumped at about 9700 to around 26000
# - with *istDS firmware 2.0, this tag was removed and ShutterCount was added
Writable => 'int32u',
},
# 0x002b - definitely exposure related somehow - PH
0x002d => [{ #PH
Name => 'EffectiveLV',
Condition => '$format eq "int16u"',
Notes => 'camera-calculated light value, but includes exposure compensation',
Writable => 'int16u',
Format => 'int16s', # (negative values are valid even though Pentax writes int16u)
ValueConv => '$val/1024',
ValueConvInv => '$val * 1024',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},{
Name => 'EffectiveLV',
Condition => '$format eq "int32u"',
Writable => 'int32u',
Format => 'int32s',
ValueConv => '$val/1024',
ValueConvInv => '$val * 1024',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
}],
0x0032 => { #13
Name => 'ImageEditing',
Writable => 'undef',
Format => 'int8u',
Count => 4,
PrintConv => {
'0 0' => 'None', #PH
'0 0 0 0' => 'None',
'0 0 0 4' => 'Digital Filter',
'1 0 0 0' => 'Resized', #PH (K-5)
'2 0 0 0' => 'Cropped', #PH
# note: doesn't apply to digital filters applied when picture is taken
'4 0 0 0' => 'Digital Filter 4', #PH (K10D, Ricoh WG-5)
'6 0 0 0' => 'Digital Filter 6', #PH (K-5)
'8 0 0 0' => 'Red-eye Correction', #PH (WG-10)
'16 0 0 0' => 'Frame Synthesis?',
},
},
0x0033 => { #PH (K110D/K100D/K-m)
Name => 'PictureMode',
Writable => 'int8u',
Count => 3,
Relist => [ [0, 1], 2 ], # join values 0 and 1 for PrintConv
PrintConvColumns => 2,
PrintConv => [{
# Program dial modes (from K110D)
'0 0' => 'Program', # (also on K10D, custom settings: Program Line 1, e-dial in Program 3, 4 or 5)
'0 1' => 'Hi-speed Program', #19 (K10D, custom settings: Program Line 2, e-dial in Program 3, 4 or 5)
'0 2' => 'DOF Program', #19 (K10D, custom settings: Program Line 3, e-dial in Program 3, 4 or 5)
'0 3' => 'MTF Program', #19 (K10D, custom settings: Program Line 4, e-dial in Program 3, 4 or 5)
'0 4' => 'Standard', #13
'0 5' => 'Portrait',
'0 6' => 'Landscape',
'0 7' => 'Macro',
'0 8' => 'Sport',
'0 9' => 'Night Scene Portrait',
'0 10' => 'No Flash',
# SCN modes (menu-selected) (from K100D)
'0 11' => 'Night Scene',
'0 12' => 'Surf & Snow',
'0 13' => 'Text',
'0 14' => 'Sunset',
'0 15' => 'Kids',
'0 16' => 'Pet',
'0 17' => 'Candlelight',
'0 18' => 'Museum',
'0 19' => 'Food',
'0 20' => 'Stage Lighting',
'0 21' => 'Night Snap',
'0 23' => 'Blue Sky', # (Q)
'0 24' => 'Sunset', # (Q)
'0 26' => 'Night Scene HDR', # (Q)
'0 27' => 'HDR', # (Q)
'0 28' => 'Quick Macro', # (Q)
'0 29' => 'Forest', # (Q)
'0 30' => 'Backlight Silhouette', # (Q)
# AUTO PICT modes (auto-selected)
'1 4' => 'Auto PICT (Standard)', #13
'1 5' => 'Auto PICT (Portrait)', #7 (K100D)
'1 6' => 'Auto PICT (Landscape)', # K110D
'1 7' => 'Auto PICT (Macro)', #13
'1 8' => 'Auto PICT (Sport)', #13
# *istD modes (ref 7)
'2 0' => 'Program (HyP)', #13 (K-5 Normal program line - PH)
'2 1' => 'Hi-speed Program (HyP)', #19 (K10D, custom settings: Program Line 2, e-dial in Program 1, 2)
'2 2' => 'DOF Program (HyP)', #19 (K10D, custom settings: Program Line 3, e-dial in Program 1, 2)
'2 3' => 'MTF Program (HyP)', #19 (K10D, custom settings: Program Line 4, e-dial in Program 1, 2)
'2 22' => 'Shallow DOF (HyP)', #PH (K-5)
'3 0' => 'Green Mode', #16
'4 0' => 'Shutter Speed Priority',
'5 0' => 'Aperture Priority',
'6 0' => 'Program Tv Shift',
'7 0' => 'Program Av Shift', #19
'8 0' => 'Manual',
'9 0' => 'Bulb',
'10 0' => 'Aperture Priority, Off-Auto-Aperture',
'11 0' => 'Manual, Off-Auto-Aperture',
'12 0' => 'Bulb, Off-Auto-Aperture',
# extra K10D modes (ref 16)
'13 0' => 'Shutter & Aperture Priority AE',
'15 0' => 'Sensitivity Priority AE',
'16 0' => 'Flash X-Sync Speed AE',
'18 0' => 'Auto Program (Normal)', #PH (K-5)
'18 1' => 'Auto Program (Hi-speed)', #PH (NC)
'18 2' => 'Auto Program (DOF)', #PH (K-5)
'18 3' => 'Auto Program (MTF)', #PH (NC)
'18 22' => 'Auto Program (Shallow DOF)', #PH (NC)
'20 22' => 'Blur Control', #PH (Q)
'254 0' => 'Video', #PH (K-7,K-5)
'255 0' => 'Video (Auto Aperture)', #PH (K-5)
'255 4' => 'Video (4)', #PH (K-x,K-01)
},{
# EV step size (ref 19)
0 => '1/2 EV steps',
1 => '1/3 EV steps',
}],
},
0x0034 => { #7/PH
Name => 'DriveMode',
Writable => 'int8u',
Count => 4,
PrintConv => [{
0 => 'Single-frame', # (also Interval Shooting for K-01 - PH)
1 => 'Continuous', # (K-5 Hi)
2 => 'Continuous (Lo)', #PH (K-5)
3 => 'Burst', #PH (K20D)
4 => 'Continuous (Medium)', #PH (K-3)
255 => 'Video', #PH (K-x)
},{
0 => 'No Timer',
1 => 'Self-timer (12 s)',
2 => 'Self-timer (2 s)',
15 => 'Video', #PH (Q MOV)
16 => 'Mirror Lock-up', # (K-5)
255 => 'n/a', #PH (K-x)
},{
0 => 'Shutter Button', # (also computer remote control - PH)
1 => 'Remote Control (3 s delay)', #19
2 => 'Remote Control', #19
4 => 'Remote Continuous Shooting', # (K-5)
},{
0x00 => 'Single Exposure',
0x01 => 'Multiple Exposure',
0x0f => 'Interval Movie', #PH (K-01)
0x10 => 'HDR', #PH (645D)
0x20 => 'HDR Strong 1', #PH (NC) (K-5)
0x30 => 'HDR Strong 2', #PH (K-5)
0x40 => 'HDR Strong 3', #PH (K-5)
0xe0 => 'HDR Auto', #PH (K-5)
0xff => 'Video', #PH (K-x)
}],
},
0x0035 => { #PH
Name => 'SensorSize',
Format => 'int16u',
Count => 2,
Notes => 'includes masked pixels',
# values for various models (not sure why this is in 2um increments):
# 11894 7962 (K10D,K-m) 12012 7987 (*istDS,K100D,K110D) 12012 8019 (*istD),
# 12061 7988 (K-5) 12053 8005 (K-r,K-x) 14352 9535 (K20D,K-7)
# 22315 16711 (645) 12080 8008 (K-01)
ValueConv => 'my @a=split(" ",$val); $_/=500 foreach @a; join(" ",@a)',
ValueConvInv => 'my @a=split(" ",$val); $_*=500 foreach @a; join(" ",@a)',
PrintConv => 'sprintf("%.3f x %.3f mm", split(" ",$val))',
PrintConvInv => '$val=~s/\s*mm$//; $val=~s/\s*x\s*/ /; $val',
},
0x0037 => { #13
Name => 'ColorSpace',
Writable => 'int16u',
PrintConv => {
0 => 'sRGB',
1 => 'Adobe RGB',
},
},
0x0038 => { #5 (PEF only)
Name => 'ImageAreaOffset',
Writable => 'int16u',
Count => 2,
},
0x0039 => { #PH
Name => 'RawImageSize',
Writable => 'int16u',
Count => 2,
PrintConv => '$_=$val;s/ /x/;$_',
},
0x003c => { #7/PH
Name => 'AFPointsInFocus',
# not writable because I'm not decoding these 4 bytes fully:
# Nibble pattern: XSSSYUUU
# X = unknown (AF focused flag?, 0 or 1)
# SSS = selected AF point bitmask (0x000 or 0x7ff if unused)
# Y = unknown (observed 0,6,7,b,e, always 0 if SSS is 0x000 or 0x7ff)
# UUU = af points used
Format => 'int32u',
Notes => '*istD only',
ValueConv => '$val & 0x7ff', # ignore other bits for now
PrintConvColumns => 2,
PrintConv => {
0 => '(none)',
BITMASK => {
0 => 'Upper-left',
1 => 'Top',
2 => 'Upper-right',
3 => 'Left',
4 => 'Mid-left',
5 => 'Center',
6 => 'Mid-right',
7 => 'Right',
8 => 'Lower-left',
9 => 'Bottom',
10 => 'Lower-right',
},
},
},
0x003d => { #31
Name => 'DataScaling',
Writable => 'int16u',
# divide by the second value of Pentax_0x0201 (WhitePoint), usually
# 8192, to get the floating point normalization factor.
# One of the examples of how this tag can be used is calculation of
# baseline exposure compensation (Adobe-style) for a PEF:
# log2(Pentax_0x007e)-14-0.5+log2(Pentax_0x003d)-13
# or
# log2(Pentax_0x007e*(Pentax_0x003d/(2^13))/(2^14))-0.5
# where
# makernotes:Pentax_0x003d/(2^13) is the normalization factor. (ref 31)
# - 8192 for most images, but occasionally 11571 for K100D/K110D,
# and 8289 or 8456 for the K-x (ref PH)
},
0x003e => { #PH
Name => 'PreviewImageBorders',
Writable => 'int8u',
Count => 4,
Notes => 'top, bottom, left, right',
},
0x003f => { #PH
Name => 'LensRec',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensRec' },
},
0x0040 => { #PH
Name => 'SensitivityAdjust',
Writable => 'int16u',
ValueConv => '($val - 50) / 10',
ValueConvInv => '$val * 10 + 50',
PrintConv => '$val ? sprintf("%+.1f", $val) : 0',
PrintConvInv => '$val',
},
0x0041 => { #19
Name => 'ImageEditCount',
Writable => 'int16u',
},
0x0047 => { #PH
Name => 'CameraTemperature', # (chassis temperature, ref forum6677)
Writable => 'int8s',
PrintConv => '"$val C"',
PrintConvInv => '$val=~s/ ?c$//i; $val',
},
0x0048 => { #19
Name => 'AELock',
Writable => 'int16u',
PrintConv => {
0 => 'Off',
1 => 'On',
},
},
0x0049 => { #13
Name => 'NoiseReduction',
Writable => 'int16u',
PrintConv => { 0 => 'Off', 1 => 'On' },
},
0x004d => [{ #PH
Name => 'FlashExposureComp',
Condition => '$count == 1',
Writable => 'int32s',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + ($val > 0 ? 0.5 : -0.5))',
PrintConv => '$val ? sprintf("%+.1f", $val) : 0',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},{ #PH (K-3)
Name => 'FlashExposureComp',
Writable => 'int8s',
Count => 2, # (don't know what the 2nd number is for)
ValueConv => [ '$val / 6' ],
ValueConvInv => [ '$val / 6' ],
PrintConv => [ '$val ? sprintf("%+.1f", $val) : 0' ],
PrintConvInv => [ 'Image::ExifTool::Exif::ConvertFraction($val)' ],
}],
0x004f => { #PH
Name => 'ImageTone', # (Called CustomImageMode in K20D manual)
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
0 => 'Natural',
1 => 'Bright',
2 => 'Portrait', # (K20D/K200D)
3 => 'Landscape', # (K20D)
4 => 'Vibrant', # (K20D)
5 => 'Monochrome', # (K20D)
6 => 'Muted', # (645D)
7 => 'Reversal Film', # (645D) (Ricoh WG-5 "Slide Film")
8 => 'Bleach Bypass', # (K-5)
9 => 'Radiant', # (Q)
},
},
0x0050 => { #PH
Name => 'ColorTemperature',
Writable => 'int16u',
RawConv => '$val ? $val : undef',
ValueConv => '53190 - $val',
ValueConvInv => '53190 - $val',
},
# 0x0053-0x005a - not in JPEG images - PH
0x0053 => { #28
Name => 'ColorTempDaylight',
%colorTemp,
Notes => '0x0053-0x005a are 3 numbers: Kelvin, shift AB, shift GM',
},
0x0054 => { Name => 'ColorTempShade', %colorTemp }, #28
0x0055 => { Name => 'ColorTempCloudy', %colorTemp }, #28
0x0056 => { Name => 'ColorTempTungsten', %colorTemp }, #28
0x0057 => { Name => 'ColorTempFluorescentD', %colorTemp }, #28
0x0058 => { Name => 'ColorTempFluorescentN', %colorTemp }, #28
0x0059 => { Name => 'ColorTempFluorescentW', %colorTemp }, #28
0x005a => { Name => 'ColorTempFlash', %colorTemp }, #28
0x005c => [{ #PH
Name => 'ShakeReductionInfo',
Condition => '$count == 4', # (2 bytes for the K-3)
Format => 'undef', # (written as int8u) - do this just to save time converting the value
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::SRInfo' },
},{
Name => 'ShakeReductionInfo',
Format => 'undef', # (written as int8u) - do this just to save time converting the value
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::SRInfo2' },
}],
0x005d => { #JD/PH
# (used by all Pentax DSLR's except *istD and *istDS until firmware 2.0 - PH)
# Observed values for the first shot of a new K10D are: 81 [PH], 181 [19],
# 246 [7], and 209 [18 (one of the first 20 shots)], so there must be a number
# of test images shot in the factory. (But my new K-5 started at 1 - PH)
# This count includes shutter actuations even if they don't result in a
# recorded image (eg. manual white balance frame or digital preview), but
# does not include actuations due to Live View or video recording - PH
Name => 'ShutterCount',
Writable => 'undef',
Count => 4,
Notes => q{
Note: May be reset by servicing! Also, does not include shutter actuations
for live view or video recording
},
# raw value is a big-endian 4-byte integer, encrypted using Date and Time
RawConv => 'length($val) == 4 ? unpack("N",$val) : undef',
RawConvInv => q{
my $val = Image::ExifTool::Pentax::CryptShutterCount($val,$self);
return pack('N', $val);
},
ValueConv => \&CryptShutterCount,
ValueConvInv => '$val',
},
# 0x005e -
0x0060 => { #PH (K-5)
Name => 'FaceInfo',
Format => 'undef', # (written as int8u)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::FaceInfo' },
},
0x0062 => { #forum4803
Name => 'RawDevelopmentProcess',
Condition => '$$self{Make} =~ /^(PENTAX|RICOH)/', # rules out Kodak, which also use this tag
Writable => 'int16u',
PrintConv => {
1 => '1 (K10D,K200D,K2000,K-m)',
3 => '3 (K20D)',
4 => '4 (K-7)',
5 => '5 (K-x)',
6 => '6 (645D)',
7 => '7 (K-r)',
8 => '8 (K-5,K-5II,K-5IIs)',
9 => '9 (Q)',
10 => '10 (K-01,K-30)',
11 => '11 (Q10)',
12 => '12 (MX-1)',
13 => '13 (K-3,K-3II)',
14 => '14 (645Z)',
15 => '15 (K-S1,K-S2)', #PH
},
},
0x0067 => { #PH (K-5)
Name => 'Hue',
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
0 => -2,
1 => 'Normal',
2 => 2,
3 => -1,
4 => 1,
5 => -3,
6 => 3,
7 => -4,
8 => 4,
65535 => 'None', # (Monochrome)
},
},
# 0x0067 - int16u: 1 [and 65535 in Monochrome] (K20D,K200D) - PH
0x0068 => { #PH
Name => 'AWBInfo',
Format => 'undef', # (written as int8u)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::AWBInfo' },
},
0x0069 => { #PH (K20D, K-5, K-01 highlights only)
Name => 'DynamicRangeExpansion',
Notes => q{
called highlight correction by Pentax for the K20D, K-5, K-01 and maybe
other models
},
Writable => 'undef',
Format => 'int8u',
Count => 4,
PrintConv => [{
0 => 'Off',
1 => 'On',
},{
0 => 0,
1 => 'Enabled', # (K-01)
2 => 'Auto', # (K-01)
}],
},
0x006b => { #PH (K-5)
Name => 'TimeInfo',
Format => 'undef', # (written as int8u)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::TimeInfo' },
},
0x006c => { #PH (K-5)
Name => 'HighLowKeyAdj',
Description => 'High/Low Key Adj',
Writable => 'int16s',
Count => 2,
PrintConvColumns => 3,
PrintConv => {
'-4 0' => -4,
'-3 0' => -3,
'-2 0' => -2,
'-1 0' => -1,
'0 0' => 0,
'1 0' => 1,
'2 0' => 2,
'3 0' => 3,
'4 0' => 4,
},
},
0x006d => { #PH (K-5)
Name => 'ContrastHighlight',
Writable => 'int16s',
Count => 2,
PrintConvColumns => 3,
PrintConv => {
'-4 0' => -4,
'-3 0' => -3,
'-2 0' => -2,
'-1 0' => -1,
'0 0' => 0,
'1 0' => 1,
'2 0' => 2,
'3 0' => 3,
'4 0' => 4,
},
},
0x006e => { #PH (K-5)
Name => 'ContrastShadow',
Writable => 'int16s',
Count => 2,
PrintConvColumns => 3,
PrintConv => {
'-4 0' => -4,
'-3 0' => -3,
'-2 0' => -2,
'-1 0' => -1,
'0 0' => 0,
'1 0' => 1,
'2 0' => 2,
'3 0' => 3,
'4 0' => 4,
},
},
0x006f => { #PH (K-5)
Name => 'ContrastHighlightShadowAdj',
Description => 'Contrast Highlight/Shadow Adj',
Writable => 'int8u',
PrintConv => {
0 => 'Off',
1 => 'On',
},
},
0x0070 => { #PH (K-5)
Name => 'FineSharpness',
Writable => 'int8u',
Count => -1, # 1 for K20/K200, 2 for K-5
PrintConv => [{
0 => 'Off',
1 => 'On',
},{
0 => 'Normal',
2 => 'Extra fine',
}],
},
0x0071 => { #PH (K20D,K-x)
Name => 'HighISONoiseReduction',
Format => 'int8u',
PrintConv => [{
0 => 'Off',
1 => 'Weakest',
2 => 'Weak', # (called "Low" by K-x)
3 => 'Strong', # (called "High" by K-x)
4 => 'Medium',
255 => 'Auto', # (K-5)
},{
0 => 'Inactive',
1 => 'Active',
2 => 'Active (Weak)', # (K-5)
3 => 'Active (Strong)', # (K-5)
4 => 'Active (Medium)', # (K-5)
},{ # Start ISO level for NR (K-x)
48 => 'ISO>400',
56 => 'ISO>800',
64 => 'ISO>1600',
72 => 'ISO>3200',
}],
},
0x0072 => { #JD (K20D)
Name => 'AFAdjustment',
Writable => 'int16s',
},
0x0073 => { #PH (K-5)
Name => 'MonochromeFilterEffect',
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
65535 => 'None',
1 => 'Green',
2 => 'Yellow',
3 => 'Orange',
4 => 'Red',
5 => 'Magenta',
6 => 'Blue',
7 => 'Cyan',
8 => 'Infrared',
},
},
0x0074 => { #PH (K-5)
Name => 'MonochromeToning',
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
65535 => 'None',
0 => -4,
1 => -3,
2 => -2,
3 => -1,
4 => 0,
5 => 1,
6 => 2,
7 => 3,
8 => 4,
},
},
0x0076 => { #PH (K-5)
Name => 'FaceDetect',
Writable => 'int8u',
Count => 2,
# the Optio S12 writes this but not the FacesDetected tag, so get FacesDetected from here
DataMember => 'FacesDetected',
RawConv => '$val =~ / (\d+)/ and $$self{FacesDetected} = $1; $val',
# (the K-3 reports "On" even in phase-detect focus modes)
PrintConv => [
'$val ? "On ($val faces max)" : "Off"',
'"$val faces detected"',
],
PrintConvInv => [
'$val =~ /(\d+)/ ? $1 : 0',
'$val =~ /(\d+)/ ? $1 : 0',
],
},
0x0077 => { #PH (K-5)
# set by taking a picture with face detect AF,
# but it isn't reset until camera is turned off? - PH
Name => 'FaceDetectFrameSize',
Writable => 'int16u',
Count => 2,
},
# 0x0078 - int16u[2]: '0 0' (K-5,K-7,K-r,K-x)
0x0079 => { #PH
Name => 'ShadowCorrection',
Writable => 'int8u',
Count => -1,
PrintConvColumns => 2,
PrintConv => {
# (1 value for K-m/K2000, 2 for 645D)
0 => 'Off',
1 => 'On',
2 => 'Auto 2', # (NC, WG-3)
'0 0' => 'Off',
'1 1' => 'Weak',
'1 2' => 'Normal',
'1 3' => 'Strong',
'2 4' => 'Auto', # (K-01)
},
},
0x007a => { #PH
Name => 'ISOAutoParameters',
Writable => 'int8u',
Count => 2,
PrintConv => {
'1 0' => 'Slow',
'2 0' => 'Standard',
'3 0' => 'Fast',
},
},
0x007b => { #PH (K-5)
Name => 'CrossProcess',
Writable => 'int8u',
PrintConvColumns => 2,
PrintConv => {
0 => 'Off',
1 => 'Random',
2 => 'Preset 1',
3 => 'Preset 2',
4 => 'Preset 3',
33 => 'Favorite 1',
34 => 'Favorite 2',
35 => 'Favorite 3',
},
},
0x007d => { #PH
Name => 'LensCorr',
Format => 'undef', # (written as int8u)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensCorr' },
},
0x007e => { #31
Name => 'WhiteLevel', # (with black level already subtracted)
Writable => 'int32u',
# 15859,15860,15864,15865,16315 (K-5 PEF/DNG only) - PH
# 3934, 3935 (Q DNG) - PH
},
0x007f => { #PH (K-5)
Name => 'BleachBypassToning',
Writable => 'int16u',
PrintConvColumns => 2,
PrintConv => {
65535 => 'Off',
1 => 'Green',
2 => 'Yellow',
3 => 'Orange',
4 => 'Red',
5 => 'Magenta',
6 => 'Purple',
7 => 'Blue',
8 => 'Cyan',
},
},
0x0080 => { #PH (Q)
Name => 'AspectRatio',
PrintConv => {
0 => '4:3',
1 => '3:2',
2 => '16:9',
3 => '1:1',
},
},
# 0x0081 - int8u: 0 (Q)
0x0082 => {
Name => 'BlurControl',
Writable => 'int8u',
Count => 4,
PrintConv => [
{
0 => 'Off',
1 => 'Low',
2 => 'Medium',
3 => 'High',
},
undef, # 0 with BlurControl is Off, seen 0,1,3 when on (related to subject distance?)
undef, # 0 with BlurControl Off, 45 when on
undef, # always 0
],
},
# 0x0083 - int8u: 0 (Q DNG)
# 0x0084 - int8u: 0 (Q)
0x0085 => { #PH
Name => 'HDR',
Format => 'int8u',
Count => 4,
PrintConv => [{ # (K-01,K-3)
0 => 'Off',
1 => 'HDR Auto',
2 => 'HDR 1',
3 => 'HDR 2',
4 => 'HDR 3',
},{ # (K-01)
0 => 'Auto-align Off',
1 => 'Auto-align On',
},{
# not sure about this - PH
# - you can set HDR "Exposure Bracket Value" with the K-3
# - guessed from imaging-resource K-3 samples K3OUTBHDR_A{1,2,3}
0 => 'n/a',
4 => '1 EV',
8 => '2 EV',
12 => '3 EV', # (get this from K-01, but can't set EV)
},
# (4th number is always 0)
],
},
# 0x0086 - int8u: 0, 111[Sport,Pet] (Q) - related to Tracking FocusMode?
# 0x0087 - int8u: 0 (Q)
0x0088 => { #PH
Name => 'NeutralDensityFilter',
Writable => 'int8u',
PrintConv => { 0 => 'Off', 1 => 'On' },
},
0x008b => { #PH (LS465)
Name => 'ISO',
Priority => 0,
Writable => 'int32u',
},
0x0200 => { #5
Name => 'BlackPoint',
Writable => 'int16u',
Count => 4,
},
0x0201 => { #5
# (this doesn't change for different fixed white balances in JPEG images: Daylight,
# Tungsten, Kelvin, etc -- always "8192 8192 8192 8192", but it varies for these in
# RAW images, all images in Auto, for different Manual WB settings, and for images
# taken via Pentax Remote Assistant) - PH
Name => 'WhitePoint',
Writable => 'int16u',
Count => 4,
},
# 0x0202: int16u[4]: all 0's in all my samples
0x0203 => { #JD (not really sure what these mean)
Name => 'ColorMatrixA',
Writable => 'int16s',
Count => 9,
ValueConv => 'join(" ",map({ $_/8192 } split(" ",$val)))',
ValueConvInv => 'join(" ",map({ int($_*8192 + ($_<0?-0.5:0.5)) } split(" ",$val)))',
PrintConv => 'join(" ",map({sprintf("%.5f",$_)} split(" ",$val)))',
PrintConvInv => '"$val"',
},
0x0204 => { #JD
Name => 'ColorMatrixB',
Writable => 'int16s',
Count => 9,
ValueConv => 'join(" ",map({ $_/8192 } split(" ",$val)))',
ValueConvInv => 'join(" ",map({ int($_*8192 + ($_<0?-0.5:0.5)) } split(" ",$val)))',
PrintConv => 'join(" ",map({sprintf("%.5f",$_)} split(" ",$val)))',
PrintConvInv => '"$val"',
},
0x0205 => [{ #19
Name => 'CameraSettings',
# size: *istD/*istDs/K100D/K110D=16, K-m/K2000=14, K-7/K-x=19,
# K200D/K20D/K-5/645D=20, K-r=21, K10D=22, K-01=25
Condition => '$count < 25', # (not valid for the K-01)
SubDirectory => {
TagTable => 'Image::ExifTool::Pentax::CameraSettings',
ByteOrder => 'BigEndian',
},
},{
Name => 'CameraSettingsUnknown',
SubDirectory => {
TagTable => 'Image::ExifTool::Pentax::CameraSettingsUnknown',
ByteOrder => 'BigEndian',
},
}],
0x0206 => [{ #PH
Name => 'AEInfo',
# size: *istD/*istDs/K100D/K110D=14, K10D/K200D/K20D=16, K-m/K2000=20,
# K-7/K-x=24, K-5/K-r/645D=25
Condition => '$count <= 25 and $count != 21 and $$self{AEInfoSize} = $count',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::AEInfo' },
},{
Name => 'AEInfo2',
# size: K-01=21
Condition => '$count == 21',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::AEInfo2' },
},{
Name => 'AEInfo3',
# size: K-30=48
Condition => '$count == 48',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::AEInfo3' },
},{
Name => 'AEInfoUnknown',
# size: Q/Q10=34
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::AEInfoUnknown' },
}],
0x0207 => [ #PH
{
Name => 'LensInfo',
# the *ist series (and Samsung GX-1) always use the old format, and all
# other models but the K100D, K110D and K100D Super always use the newer
# format, and for the K110D/K110D we expect ff or 00 00 at byte 20 if
# it is the old format.)
Condition => q{
$$self{Model}=~/(\*ist|GX-1[LS])/ or
($$self{Model}=~/(K100D|K110D)/ and $$valPt=~/^.{20}(\xff|\0\0)/s)
},
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensInfo' },
},{
Name => 'LensInfo',
Condition => '$count != 90 and $count != 91 and $count != 80 and $count != 128',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensInfo2' },
},{
Name => 'LensInfo', # 645D
Condition => '$count == 90',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensInfo3' },
},{
Name => 'LensInfo', # K-r, K-5, K-5II
Condition => '$count == 91',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensInfo4' },
},{
Name => 'LensInfo', # K-01, K-30, K-50, K-500, K-3, K-3II
Condition => '$count == 80 or $count == 128',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensInfo5' },
}
],
0x0208 => [ #PH
{
Name => 'FlashInfo',
Condition => '$count == 27',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::FlashInfo' },
},
{
Name => 'FlashInfoUnknown',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::FlashInfoUnknown' },
},
],
0x0209 => { #PH
Name => 'AEMeteringSegments',
Format => 'int8u',
Count => -1,
Notes => q{
measurements from each of the 16 AE metering segments for models such as the
K10D, 77 metering segments for models such as the K-5, and 4050 metering
segments for the K-3, converted to LV
},
%convertMeteringSegments,
# 16 metering segment 77 metering segment
# locations (ref JD, K10D) locations (ref PH, K-5)
# +-------------------------+
# | 14 | +----------------------------------+
# | +---+---+---+---+ | | 0 1 2 3 4 5 6 7 8 9 10 |
# | | 5 | 3/1\ 2| 4 | | | 11 12 13 14 15 16 17 18 19 20 21 |
# | +-+-+-+-+ - +-+-+-+-+ | | 22 23 24 25 26 27 28 29 30 31 32 |
# +--+ 9 | 7 ||0|| 6 | 8 +--+ | 33 34 35 36 37 38 39 40 41 42 43 |
# | +-+-+-+-+ - +-+-+-+-+ | | 44 45 46 47 48 49 50 51 52 53 54 |
# | |13 |11\ /10|12 | | | 55 56 57 58 59 60 61 62 63 64 65 |
# | +---+---+---+---+ | | 66 67 68 69 70 71 72 73 74 75 76 |
# | 15 | +----------------------------------+
# +-------------------------+
},
0x020a => { #PH/JD/19
Name => 'FlashMeteringSegments',
Format => 'int8u',
Count => -1,
%convertMeteringSegments,
},
0x020b => { #PH/JD/19
Name => 'SlaveFlashMeteringSegments',
Format => 'int8u',
Count => -1,
Notes => 'used in wireless control mode',
%convertMeteringSegments,
},
0x020d => { #PH
Name => 'WB_RGGBLevelsDaylight',
Writable => 'int16u',
Count => 4,
},
0x020e => { #PH
Name => 'WB_RGGBLevelsShade',
Writable => 'int16u',
Count => 4,
},
0x020f => { #PH
Name => 'WB_RGGBLevelsCloudy',
Writable => 'int16u',
Count => 4,
},
0x0210 => { #PH
Name => 'WB_RGGBLevelsTungsten',
Writable => 'int16u',
Count => 4,
},
0x0211 => { #PH
Name => 'WB_RGGBLevelsFluorescentD',
Writable => 'int16u',
Count => 4,
},
0x0212 => { #PH
Name => 'WB_RGGBLevelsFluorescentN',
Writable => 'int16u',
Count => 4,
},
0x0213 => { #PH
Name => 'WB_RGGBLevelsFluorescentW',
Writable => 'int16u',
Count => 4,
},
0x0214 => { #PH
Name => 'WB_RGGBLevelsFlash',
Writable => 'int16u',
Count => 4,
},
0x0215 => { #PH
Name => 'CameraInfo',
Format => 'undef', # (written as int32u)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::CameraInfo' },
},
0x0216 => { #PH
Name => 'BatteryInfo',
SubDirectory => {
TagTable => 'Image::ExifTool::Pentax::BatteryInfo',
ByteOrder => 'BigEndian', # have seen makernotes changed to little-endian in DNG!
},
},
# 0x021a - undef[1068] (K-5) - ToneMode/Saturation mapping matrices (ref 28)
0x021b => { #19
Name => 'SaturationInfo',
Flags => [ 'Unknown', 'Binary' ],
Writable => 0,
Notes => 'only in PEF and DNG images',
# K10D values with various Saturation settings (ref 19):
# Very Low: 000000022820f9a0fe4000802660f92002e0fee01e402c40f880fb40ffc02b20f52002e0fe401ee0
# Low: 000000022ae0f700fe20ff402840f88001e0fcc021602f60f560fb40fe602d20f48001c0fbc02280
# Med Low: 000000022dc0f420fe20fe002a20f7e000c0fa8024c032c0f220fb20fce02f60f3c000a0f9202640
# Normal: 000000023120f0e0fe00fc802c40f740ffa0f7e028803660ee80fb20fb4031c0f300ff60f6202a80
# Med High: 0000000234e0ed40fde0fae02ea0f680fe60f5002ca03a80ea80fb00f9603480f220fe00f2e02f20
# High: 0000000238c0e960fde0f9203140f5a0fce0f1e031403f00e600fb00f7803760f120fc60ef403460
# Very High:000000023d20e520fdc0f7203420f4c0fb60ee6036404400e120fae0f5403aa0f020fac0eb403a00
},
# 0x021c - undef[18] (K-5)
# 0x021d - undef[18] (K-5)
# 0x021e - undef[8] (K-5, Q)
0x021f => { #JD
Name => 'AFInfo',
SubDirectory => {
# NOTE: Most of these subdirectories are 'undef' format, and as such the
# byte ordering is not changed when changed via the Pentax software (which
# will write a little-endian TIFF on an Intel system). So we must define
# BigEndian byte ordering for any of these which contain multi-byte values. - PH
ByteOrder => 'BigEndian',
TagTable => 'Image::ExifTool::Pentax::AFInfo',
},
},
0x0220 => { #6
Name => 'HuffmanTable',
Flags => [ 'Unknown', 'Binary' ],
Writable => 0,
Notes => 'found in K10D, K20D and K2000D PEF images',
},
0x0221 => { #28
Name => 'KelvinWB',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::KelvinWB' },
},
0x0222 => { #PH
Name => 'ColorInfo',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::ColorInfo' },
},
# 0x0223 - undef[198] (K-5 PEF/DNG only)
0x0224 => { #19
Name => 'EVStepInfo',
Drop => 200, # drop if larger than 200 bytes (40 kB in Pentax Q and Q10)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::EVStepInfo' },
},
0x0226 => { #PH
Name => 'ShotInfo', # (may want to change this later when more is decoded)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::ShotInfo' },
},
0x0227 => { #PH
Name => 'FacePos',
Condition => '$$self{FacesDetected}', # ignore if no faces to decode
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::FacePos' },
},
0x0228 => { #PH
Name => 'FaceSize',
Condition => '$$self{FacesDetected}', # ignore if no faces to decode
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::FaceSize' },
},
0x0229 => { #PH (verified) (K-m, K-x, K-7)
Name => 'SerialNumber',
Writable => 'string',
Notes => 'left blank by some cameras',
},
0x022a => { #PH (K-5)
Name => 'FilterInfo',
SubDirectory => {
TagTable => 'Image::ExifTool::Pentax::FilterInfo',
ByteOrder => 'BigEndian',
},
},
0x022b => { #PH (K-5)
Name => 'LevelInfo',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LevelInfo' },
},
# 0x022c - undef[46] (K-5)
0x022d => { #28
Name => 'WBLevels',
Condition => '$count == 100', # (just to be safe, but no other counts observed)
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::WBLevels' },
},
0x022e => { #PH (K-5 AVI videos)
Name => 'Artist',
Groups => { 2 => 'Author' },
Writable => 'string',
},
0x022f => { #PH (K-5 AVI videos)
Name => 'Copyright',
Groups => { 2 => 'Author' },
Writable => 'string',
},
0x0230 => { #PH (K-x AVI videos)
Name => 'FirmwareVersion',
Notes => 'only in AVI videos',
# this tag only exists in AVI videos, and for the K-x the value of
# this tag is "K-x Ver 1.00", which is the same as the EXIF Software
# tag. I used a different tag name for this because Pentax uses the
# AVI Software tag for a different string, "PENTAX K-x".
Writable => 'string',
},
0x0231 => { #PH (K-5)
Name => 'ContrastDetectAFArea',
Writable => 'int16u',
Count => 4,
Notes => q{
AF area of the most recent contrast-detect focus operation. Coordinates
are left, top, width and height in a 720x480 frame, with Y downwards
},
},
0x0235 => { #PH (K-5)
Name => 'CrossProcessParams',
# (it would be interesting to know exactly what these mean)
Writable => 'undef',
Format => 'int8u',
Count => 10,
},
# 0x0236 - undef[52] (Q)
# 0x0237 - undef[11] possibly related to smart effect setting? (Q)
# 0x0238 - undef[9] (Q)
0x0239 => { #PH
Name => 'LensInfoQ',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensInfoQ' },
},
# 0x023a - undef[10] (Q)
# 0x023b - undef[9] (K-01)
# 01a700500000000000, 91a700500000000000, 41a700500000000000, 002700500000000000
# c00500400000000000, 400500500000000000, 4004ff420100000000, 4087ff480000000000
0x0243 => { #PH
Name => 'PixelShiftInfo',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::PixelShiftInfo' },
},
0x03fe => { #PH
Name => 'DataDump',
Writable => 0,
PrintConv => '\$val',
},
0x03ff => [ #PH
{
Name => 'TempInfo',
Condition => '$$self{Model} =~ /K-(01|3|30|5|50|500)\b/',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::TempInfo' },
},{
Name => 'UnknownInfo',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::UnknownInfo' },
},
],
0x0402 => { #5
Name => 'ToneCurve',
PrintConv => '\$val',
},
0x0403 => { #5
Name => 'ToneCurves',
PrintConv => '\$val',
},
# 0x0404 - undef[2086] (K-5)
0x0405 => { #PH - undef[24200] (K-5 PEF/DNG only), undef[28672] (Q DNG)
Name => 'UnknownBlock',
Writable => 'undef',
Notes => 'large unknown data block in PEF/DNG images but not JPG images',
Flags => [ 'Unknown', 'Binary', 'Drop' ],
},
# 0x0406 - undef[4116] (K-5)
# 0x0407 - undef[3072] (Q DNG)
# 0x0408 - undef[1024] (Q DNG)
0x0e00 => {
Name => 'PrintIM',
Description => 'Print Image Matching',
Writable => 0,
SubDirectory => {
TagTable => 'Image::ExifTool::PrintIM::Main',
},
},
);
# shake reduction information (ref PH)
%Image::ExifTool::Pentax::SRInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'Shake reduction information.',
0 => {
Name => 'SRResult',
PrintConv => { #PH/JD
0 => 'Not stabilized',
BITMASK => {
0 => 'Stabilized',
# have seen 1 and 4 for 0.5 and 0.3 sec exposures with NR on and Bit 0 also set - ref 19
# have seen bits 1,2,3,4 in K-5 AVI videos - PH
6 => 'Not ready',
},
},
},
1 => {
Name => 'ShakeReduction',
PrintConv => {
0 => 'Off',
1 => 'On',
4 => 'Off (4)', # (K20D, K200D, K-7, K-5)
5 => 'On but Disabled', # (K20D, K-5)
# (can be 5 "On but Disabled" for K-5 with HDR [auto-align off only],
# Composition Adjust, DriveMode = Self-timer or Remote, and movie with SR off!)
6 => 'On (Video)', # (K-7)
7 => 'On (7)', #(NC) (K20D, K200D, K-m, K-5)
15 => 'On (15)', # (K20D with Tamron 10-20mm @ 10mm)
39 => 'On (mode 2)', # (K-01) (on during capture and live view)
135 => 'On (135)', # (K-5IIs)
167 => 'On (mode 1)', # (K-01) (on during capture only)
},
},
2 => {
Name => 'SRHalfPressTime',
# (was SR_SWSToSWRTime: SWS=photometering switch, SWR=shutter release switch)
# (from http://www.patentstorm.us/patents/6597867-description.html)
# (here, SR could more accurately mean Shutter Release, not Shake Reduction)
# (not valid for K-01 - PH)
Notes => q{
time from when the shutter button was half pressed to when the shutter was
released, including time for focusing. Not valid for some models
},
# (constant of 60 determined from times: 2sec=127; 3sec=184,197; 4sec=244,249,243,246 - PH)
ValueConv => '$val / 60',
ValueConvInv => 'my $v=$val*60; $v < 255 ? int($v + 0.5) : 255',
PrintConv => 'sprintf("%.2f s",$val) . ($val > 254.5/60 ? " or longer" : "")',
PrintConvInv => '$val=~tr/0-9.//dc; $val',
},
3 => { #JD
Name => 'SRFocalLength',
ValueConv => '$val & 0x01 ? $val * 4 : $val / 2',
ValueConvInv => '$val <= 127 ? int($val) * 2 : int($val / 4) | 0x01',
PrintConv => '"$val mm"',
PrintConvInv => '$val=~s/\s*mm//;$val',
},
);
# shake reduction information for the K-3 (ref PH)
%Image::ExifTool::Pentax::SRInfo2 = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'Shake reduction information for the K-3.',
0 => {
Name => 'SRResult',
Unknown => 1,
PrintConv => { BITMASK => {
# Bit 0 - have seen this set in a few Pentax samples - PH
# Bit 6 - usually set when SR is Off, and occasionally when On - PH
# Bit 7 - set when AA simulation is on - PH
}},
},
1 => {
Name => 'ShakeReduction',
PrintConv => { #forum5425
0 => 'Off', # (NC for K-3)
1 => 'On', # (NC for K-3)
4 => 'Off (AA simulation off)',
5 => 'On but Disabled', # (NC for K-3)
6 => 'On (Video)', # (NC for K-3)
7 => 'On (AA simulation off)',
12 => 'Off (AA simulation type 1)', # (AA linear motion)
15 => 'On (AA simulation type 1)', # (AA linear motion)
20 => 'Off (AA simulation type 2)', # (AA circular motion)
23 => 'On (AA simulation type 2)', # (AA circular motion)
},
},
);
# face detection information (ref PH, K-5)
%Image::ExifTool::Pentax::FaceInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
DATAMEMBER => [ 0 ],
0 => {
Name => 'FacesDetected',
RawConv => '$$self{FacesDetected} = $val',
},
2 => {
Name => 'FacePosition',
Notes => q{
X/Y coordinates of the center of the main face in percent of frame size,
with positive Y downwards
},
Format => 'int8u[2]',
},
);
# automatic white balance settings (ref PH, K-5)
%Image::ExifTool::Pentax::AWBInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# 0 - always 1?
# (data ends here for the K20D, K200D, K-x and K-7)
0 => {
Name => 'WhiteBalanceAutoAdjustment',
PrintConv => {
0 => 'Off',
1 => 'On',
},
},
1 => { # (exists only for K-5)
Name => 'TungstenAWB',
PrintConv => {
0 => 'Subtle Correction',
1 => 'Strong Correction',
},
},
);
# world time settings (ref PH, K-5)
%Image::ExifTool::Pentax::TimeInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Time' },
0.1 => {
Name => 'WorldTimeLocation',
Mask => 0x01,
PrintConv => {
0x00 => 'Hometown',
0x01 => 'Destination',
},
},
0.2 => {
Name => 'HometownDST',
Mask => 0x02,
PrintConv => {
0x00 => 'No',
0x02 => 'Yes',
},
},
0.3 => {
Name => 'DestinationDST',
Mask => 0x04,
PrintConv => {
0x00 => 'No',
0x04 => 'Yes',
},
},
2 => {
Name => 'HometownCity',
SeparateTable => 'City',
PrintConv => \%pentaxCities,
},
3 => {
Name => 'DestinationCity',
SeparateTable => 'City',
PrintConv => \%pentaxCities,
},
);
# lens distortion correction (ref PH, K-5)
%Image::ExifTool::Pentax::LensCorr = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => {
Name => 'DistortionCorrection',
PrintConv => { 0 => 'Off', 1 => 'On' },
},
1 => {
Name => 'ChromaticAberrationCorrection',
PrintConv => { 0 => 'Off', 1 => 'On' },
},
2 => {
Name => 'PeripheralIlluminationCorr',
PrintConv => { 0 => 'Off', 1 => 'On' },
},
3 => {
Name => 'DiffractionCorrection',
PrintConv => { 0 => 'Off', 16 => 'On' },
},
);
# camera settings (ref 19)
%Image::ExifTool::Pentax::CameraSettings = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
PRIORITY => 0,
NOTES => 'Camera settings information written by Pentax DSLR cameras.',
0 => {
Name => 'PictureMode2',
PrintConv => {
0 => 'Scene Mode', #PH
1 => 'Auto PICT', #PH (NC)
2 => 'Program AE',
3 => 'Green Mode',
4 => 'Shutter Speed Priority',
5 => 'Aperture Priority',
6 => 'Program Tv Shift', #PH
7 => 'Program Av Shift',
8 => 'Manual', #PH
9 => 'Bulb', #PH
10 => 'Aperture Priority, Off-Auto-Aperture', #PH (NC)
11 => 'Manual, Off-Auto-Aperture', #PH
12 => 'Bulb, Off-Auto-Aperture', #PH (NC)
13 => 'Shutter & Aperture Priority AE',
15 => 'Sensitivity Priority AE',
16 => 'Flash X-Sync Speed AE', #PH
},
},
1.1 => {
Name => 'ProgramLine',
# only set to other than Normal when in Program AE mode
Mask => 0x03,
PrintConv => {
0 => 'Normal',
1 => 'Hi Speed',
2 => 'Depth',
3 => 'MTF',
},
},
1.2 => { # (K10D, K-5)
Name => 'EVSteps',
Mask => 0x20,
PrintConv => {
0x00 => '1/2 EV Steps',
0x20 => '1/3 EV Steps',
},
},
1.3 => { # (this bit is set for movies with the K-5 - PH)
Name => 'E-DialInProgram',
# always set even when not in Program AE mode
Mask => 0x40,
PrintConv => {
0x00 => 'Tv or Av',
0x40 => 'P Shift',
},
},
1.4 => { # (K10D, K-5)
Name => 'ApertureRingUse',
# always set even Aperture Ring is in A mode
Mask => 0x80,
PrintConv => {
0x00 => 'Prohibited',
0x80 => 'Permitted',
},
},
2 => {
Name => 'FlashOptions',
Notes => 'the camera flash options settings, set even if the flash is off',
Mask => 0xf0,
ValueConv => '$val>>4',
ValueConvInv => '$val<<4',
# Note: These tags correlate with the FlashMode and InternalFlashMode values,
# and match what is displayed by the Pentax software
PrintConv => {
0 => 'Normal', # (this value can occur in Green Mode) - ref 19
1 => 'Red-eye reduction', # (this value can occur in Green Mode) - ref 19
2 => 'Auto', # (this value can occur in other than Green Mode) - ref 19
3 => 'Auto, Red-eye reduction', #PH (this value can occur in other than Green Mode) - ref 19
5 => 'Wireless (Master)',
6 => 'Wireless (Control)',
8 => 'Slow-sync',
9 => 'Slow-sync, Red-eye reduction',
10 => 'Trailing-curtain Sync'
},
},
2.1 => {
Name => 'MeteringMode2',
Mask => 0x0f,
Notes => 'may not be valid for some models, eg. *ist D',
PrintConv => {
0 => 'Multi-segment',
BITMASK => {
0 => 'Center-weighted average',
1 => 'Spot',
},
},
},
3 => {
Name => 'AFPointMode',
Mask => 0xf0,
PrintConv => {
0x00 => 'Auto',
BITMASK => {
4 => 'Select',
5 => 'Fixed Center',
# have seen bit 6 set in pre-production images (firmware 0.20) - PH
},
},
},
3.1 => {
Name => 'FocusMode2',
Mask => 0x0f,
PrintConv => {
0 => 'Manual',
1 => 'AF-S',
2 => 'AF-C',
3 => 'AF-A', #PH
},
},
4 => {
Name => 'AFPointSelected2',
Format => 'int16u',
PrintConv => {
0 => 'Auto',
BITMASK => {
0 => 'Upper-left',
1 => 'Top',
2 => 'Upper-right',
3 => 'Left',
4 => 'Mid-left',
5 => 'Center',
6 => 'Mid-right',
7 => 'Right',
8 => 'Lower-left',
9 => 'Bottom',
10 => 'Lower-right',
},
},
},
6 => {
Name => 'ISOFloor', #PH
# manual ISO or minimum ISO in Auto ISO mode - PH
ValueConv => 'int(100*exp(Image::ExifTool::Pentax::PentaxEv($val-32)*log(2))+0.5)',
ValueConvInv => 'Image::ExifTool::Pentax::PentaxEvInv(log($val/100)/log(2))+32',
},
7 => {
Name => 'DriveMode2',
PrintConv => {
0 => 'Single-frame',
BITMASK => {
0 => 'Continuous', # (K-5 Hi)
1 => 'Continuous (Lo)', #PH (K-5)
2 => 'Self-timer (12 s)', #PH
3 => 'Self-timer (2 s)', #PH
4 => 'Remote Control (3 s delay)',
5 => 'Remote Control',
6 => 'Exposure Bracket', #PH/19
7 => 'Multiple Exposure',
},
},
},
8 => {
Name => 'ExposureBracketStepSize',
# This is set even when Exposure Bracket is Off (and the K10D
# displays Ò---Ó as the step size when you press the EB button) - DaveN
# because the last value is remembered and if you turn Exposure Bracket
# on the step size goes back to what it was before.
PrintConv => {
3 => '0.3',
4 => '0.5',
5 => '0.7',
8 => '1.0', #PH
11 => '1.3',
12 => '1.5',
13 => '1.7', #(NC)
16 => '2.0', #PH
},
},
9 => { #PH/19
Name => 'BracketShotNumber',
PrintHex => 1,
PrintConv => {
0 => 'n/a',
0x02 => '1 of 2', #PH (K-5)
0x12 => '2 of 2', #PH (K-5)
0x03 => '1 of 3',
0x13 => '2 of 3',
0x23 => '3 of 3',
0x05 => '1 of 5',
0x15 => '2 of 5',
0x25 => '3 of 5',
0x35 => '4 of 5',
0x45 => '5 of 5',
},
},
10 => {
Name => 'WhiteBalanceSet',
Mask => 0xf0,
# Not necessarily the white balance used; for example if the custom menu is set to
# "WB when using flash" -> "2 Flash", then this tag reports the camera setting while
# tag 0x0019 reports Flash if the Flash was used.
PrintConv => {
0 => 'Auto',
16 => 'Daylight',
32 => 'Shade',
48 => 'Cloudy',
64 => 'Daylight Fluorescent',
80 => 'Day White Fluorescent',
96 => 'White Fluorescent',
112 => 'Tungsten',
128 => 'Flash',
144 => 'Manual',
# The three Set Color Temperature settings refer to the 3 preset settings which
# can be saved in the menu (see page 123 of the K10D manual)
192 => 'Set Color Temperature 1',
208 => 'Set Color Temperature 2',
224 => 'Set Color Temperature 3',
},
},
10.1 => {
Name => 'MultipleExposureSet',
Mask => 0x0f,
PrintConv => {
0 => 'Off',
1 => 'On',
},
},
13 => {
Name => 'RawAndJpgRecording',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
# this is actually a bit field: - PH
# bit 0=JPEG, bit 2=PEF, bit 3=DNG; high nibble: 0x00=best, 0x20=better, 0x40=good
PrintHex => 1,
PrintConv => {
0x01 => 'JPEG (Best)', #PH
0x04 => 'RAW (PEF, Best)',
0x05 => 'RAW+JPEG (PEF, Best)',
0x08 => 'RAW (DNG, Best)', #PH (NC)
0x09 => 'RAW+JPEG (DNG, Best)', #PH (NC)
0x21 => 'JPEG (Better)', #PH
0x24 => 'RAW (PEF, Better)',
0x25 => 'RAW+JPEG (PEF, Better)', #PH
0x28 => 'RAW (DNG, Better)', #PH
0x29 => 'RAW+JPEG (DNG, Better)', #PH (NC)
0x41 => 'JPEG (Good)',
0x44 => 'RAW (PEF, Good)', #PH (NC)
0x45 => 'RAW+JPEG (PEF, Good)', #PH (NC)
0x48 => 'RAW (DNG, Good)', #PH (NC)
0x49 => 'RAW+JPEG (DNG, Good)',
# have seen values of 0,2,34 for other models (not K10D) - PH
},
},
14.1 => { #PH
Name => 'JpgRecordedPixels',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
Mask => 0x03,
PrintConv => {
0 => '10 MP',
1 => '6 MP',
2 => '2 MP',
},
},
14.2 => { #PH (K-5)
Name => 'LinkAEToAFPoint',
Condition => '$$self{Model} =~ /K-5\b/',
Notes => 'K-5 only',
Mask => 0x01,
PrintConv => {
0x00 => 'Off',
0x01 => 'On',
},
},
14.3 => { #PH (K-5)
Name => 'SensitivitySteps',
Condition => '$$self{Model} =~ /K-5\b/',
Notes => 'K-5 only',
Mask => 0x02,
PrintConv => {
0x00 => '1 EV Steps',
0x02 => 'As EV Steps',
},
},
14.4 => { #PH (K-5)
Name => 'ISOAuto',
Condition => '$$self{Model} =~ /K-5\b/',
Notes => 'K-5 only',
Mask => 0x04,
PrintConv => {
0x00 => 'Off',
0x04 => 'On',
},
},
# 14.5 Mask 0x80 - changes for K-5
16 => {
Name => 'FlashOptions2',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only; set even if the flash is off',
Mask => 0xf0,
# Note: the Normal and Auto values (0x00 to 0x30) do not tags always
# correlate with the FlashMode, InternalFlashMode and FlashOptions values
# however, these values seem to better match the K10D's actual functionality
# (always Auto in Green mode always Normal otherwise if one of the other options
# isn't selected) - ref 19
# (these tags relate closely to InternalFlashMode values - PH)
PrintConv => {
0x00 => 'Normal', # (this value never occurs in Green Mode) - ref 19
0x10 => 'Red-eye reduction', # (this value never occurs in Green Mode) - ref 19
0x20 => 'Auto', # (this value only occurs in Green Mode) - ref 19
0x30 => 'Auto, Red-eye reduction', # (this value only occurs in Green Mode) - ref 19
0x50 => 'Wireless (Master)',
0x60 => 'Wireless (Control)',
0x80 => 'Slow-sync',
0x90 => 'Slow-sync, Red-eye reduction',
0xa0 => 'Trailing-curtain Sync'
},
},
16.1 => {
Name => 'MeteringMode3',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
Mask => 0x0f,
PrintConv => {
0 => 'Multi-segment',
BITMASK => {
0 => 'Center-weighted average',
1 => 'Spot',
},
},
},
# 16 Mask 0x0f - changes when changing EV steps? (K-5)
17.1 => {
Name => 'SRActive',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => q{
K10D only; SR is active only when ShakeReduction is On, DriveMode is not
Remote or Self-timer, and Internal/ExternalFlashMode is not "On, Wireless"
},
Mask => 0x80,
PrintConv => {
0x00 => 'No',
0x80 => 'Yes',
},
},
17.2 => {
Name => 'Rotation',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
Mask => 0x60,
PrintConv => {
0x00 => 'Horizontal (normal)',
0x20 => 'Rotate 180',
0x40 => 'Rotate 90 CW',
0x60 => 'Rotate 270 CW',
},
},
# Bit 0x08 is set on 3 of my 3000 shots to (All 3 were Shutter Priority
# but this may not mean anything with such a small sample) - ref 19
17.3 => {
Name => 'ISOSetting',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
Mask => 0x04,
PrintConv => {
0x00 => 'Manual',
0x04 => 'Auto',
},
},
17.4 => {
Name => 'SensitivitySteps',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
Mask => 0x02,
PrintConv => {
0x00 => '1 EV Steps',
0x02 => 'As EV Steps',
},
},
# 17 Mask 0x08 - changed when changing Auto ISO range (K-5)
18 => {
Name => 'TvExposureTimeSetting',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
ValueConv => 'exp(-Image::ExifTool::Pentax::PentaxEv($val-68)*log(2))',
ValueConvInv => 'Image::ExifTool::Pentax::PentaxEvInv(-log($val)/log(2))+68',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
19 => {
Name => 'AvApertureSetting',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
ValueConv => 'exp(Image::ExifTool::Pentax::PentaxEv($val-68)*log(2)/2)',
ValueConvInv => 'Image::ExifTool::Pentax::PentaxEvInv(log($val)*2/log(2))+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
20 => { #PH
Name => 'SvISOSetting',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only',
# ISO setting for sensitivity-priority mode
# (conversion may not give actual displayed values:)
# 32 => 100, 35 => 125, 36 => 140, 37 => 160,
# 40 => 200, 43 => 250, 44 => 280, 45 => 320,
# 48 => 400, 51 => 500, 52 => 560, 53 => 640,
# 56 => 800, 59 => 1000,60 => 1100,61 => 1250, 64 => 1600
ValueConv => 'int(100*exp(Image::ExifTool::Pentax::PentaxEv($val-32)*log(2))+0.5)',
ValueConvInv => 'Image::ExifTool::Pentax::PentaxEvInv(log($val/100)/log(2))+32',
},
21 => { #PH
Name => 'BaseExposureCompensation',
Condition => '$$self{Model} =~ /(K10D|GX10)\b/',
Notes => 'K10D only; exposure compensation without auto bracketing',
ValueConv => 'Image::ExifTool::Pentax::PentaxEv(64-$val)',
ValueConvInv => '64-Image::ExifTool::Pentax::PentaxEvInv($val)',
PrintConv => '$val ? sprintf("%+.1f", $val) : 0',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
);
# unknown camera settings (K-01)
%Image::ExifTool::Pentax::CameraSettingsUnknown = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'This information has not yet been decoded for models such as the K-01.',
);
# auto-exposure information (ref PH)
%Image::ExifTool::Pentax::AEInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
DATAMEMBER => [ 7 ],
NOTES => 'Auto-exposure information for most Pentax models.',
# instead of /8, should these be PentaxEv(), as in CameraSettings? - PH
0 => {
Name => 'AEExposureTime',
Notes => 'val = 24 * 2**((32-raw)/8)',
ValueConv => '24*exp(-($val-32)*log(2)/8)',
ValueConvInv => '-log($val/24)*8/log(2)+32',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
1 => {
Name => 'AEAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
2 => {
Name => 'AE_ISO',
Notes => 'val = 100 * 2**((raw-32)/8)',
ValueConv => '100*exp(($val-32)*log(2)/8)',
ValueConvInv => 'log($val/100)*8/log(2)+32',
PrintConv => 'int($val + 0.5)',
PrintConvInv => '$val',
},
3 => {
Name => 'AEXv',
Notes => 'val = (raw-64)/8',
ValueConv => '($val-64)/8',
ValueConvInv => '$val * 8 + 64',
},
4 => {
Name => 'AEBXv',
Format => 'int8s',
Notes => 'val = raw / 8',
ValueConv => '$val / 8',
ValueConvInv => '$val * 8',
},
5 => {
Name => 'AEMinExposureTime', #19
Notes => 'val = 24 * 2**((32-raw)/8)',
ValueConv => '24*exp(-($val-32)*log(2)/8)', #JD
ValueConvInv => '-log($val/24)*8/log(2)+32',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
6 => {
Name => 'AEProgramMode',
PrintConvColumns => 2,
PrintConv => {
0 => 'M, P or TAv',
1 => 'Av, B or X',
2 => 'Tv',
3 => 'Sv or Green Mode',
8 => 'Hi-speed Program',
11 => 'Hi-speed Program (P-Shift)', #19
16 => 'DOF Program', #19
19 => 'DOF Program (P-Shift)', #19
24 => 'MTF Program', #19
27 => 'MTF Program (P-Shift)', #19
35 => 'Standard',
43 => 'Portrait',
51 => 'Landscape',
59 => 'Macro',
67 => 'Sport',
75 => 'Night Scene Portrait',
83 => 'No Flash',
91 => 'Night Scene',
# 96 - seen for Pentax Q10
99 => 'Surf & Snow',
104 => 'Night Snap', # (Q)
107 => 'Text',
115 => 'Sunset',
# 116 - seen for Pentax Q (vivid?)
123 => 'Kids',
131 => 'Pet',
139 => 'Candlelight',
144 => 'SCN', # (Q)
160 => 'Program', # (Q)
# 142 - seen for Pentax Q in Program mode
147 => 'Museum',
184 => 'Shallow DOF Program', # (K-5)
216 => 'HDR', # (Q)
},
},
7 => {
Name => 'AEFlags',
Writable => 0,
Hook => '$size > 20 and $varSize += 1',
Notes => 'indices after this are incremented by 1 for some models',
# (this tag can't be unknown because the Hook must be evaluated
# to shift the following offsets if necessary. Instead, ignore
# the return value unless Unknown option used)
RawConv => '$$self{OPTIONS}{Unknown} ? $val : undef',
PrintConv => { #19
# (seems to be the warnings displayed in the viewfinder for several bits)
BITMASK => {
# 0 - seen in extreme low light conditions (e.g. Lens Cap On)
# 1 - seen in 2 cases, Aperture Priority mode, Auto ISO at 100,
# Shutter speed at 1/4000 and aperture opened wider causing under exposure
# 2 - only (but not always) set in Shutter Speed Priority (seems to be when over/under exposed).
# In one case set when auto exposure compensation changed the Tv from 1/250 to 1/80.
# In another case set when external flash was in SB mode so did not fire.
3 => 'AE lock',
4 => 'Flash recommended?', # not 100% sure of this one
# 5 - seen lots...
# 6 - seen lots...
7 => 'Aperture wide open', # mostly true... (Set for all my lenses except for DA* 16-50mm)
},
},
},
# Note: Offsets below shifted by 1 if record size is > 20 bytes
# (implemented by the Hook above)
8 => { #30
Name => 'AEApertureSteps',
Notes => q{
number of steps the aperture has been stopped down from wide open. There
are roughly 8 steps per F-stop for most lenses, or 18 steps for 645D lenses,
but it varies slightly by lens
},
PrintConv => '$val == 255 ? "n/a" : $val',
PrintConvInv => '$val eq "n/a" ? 255 : $val',
},
9 => { #19
Name => 'AEMaxAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
10 => { #19
Name => 'AEMaxAperture2',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
11 => { #19
Name => 'AEMinAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.0f",$val)',
PrintConvInv => '$val',
},
12 => { #19
Name => 'AEMeteringMode',
PrintConv => {
0 => 'Multi-segment',
BITMASK => {
4 => 'Center-weighted average',
5 => 'Spot',
},
},
},
13 => { #30
Name => 'AEWhiteBalance',
Condition => '$$self{AEInfoSize} == 24', # (not thoroughly tested for other sizes)
Notes => 'K7 and Kx',
Mask => 0xf0,
PrintConv => {
0x00 => 'Standard',
0x10 => 'Daylight',
0x20 => 'Shade',
0x30 => 'Cloudy',
0x40 => 'Daylight Fluorescent',
0x50 => 'Day White Fluorescent',
0x60 => 'White Fluorescent',
0x70 => 'Tungsten',
},
},
13.1 => { #30
Name => 'AEMeteringMode2',
Condition => '$$self{AEInfoSize} == 24', # (not thoroughly tested for other sizes)
Notes => 'K7 and Kx, override for an incompatable metering mode setting',
Mask => 0x0f,
PrintConv => {
0 => 'Multi-segment',
BITMASK => {
0 => 'Center-weighted average',
1 => 'Spot',
# 2 - seen for K7 AVI movie
},
},
},
14 => { #19
Name => 'FlashExposureCompSet',
Description => 'Flash Exposure Comp. Setting',
Format => 'int8s',
Notes => q{
reports the camera setting, unlike tag 0x004d which reports 0 in Green mode
or if flash was on but did not fire. Both this tag and 0x004d report the
setting even if the flash is off
},
ValueConv => 'Image::ExifTool::Pentax::PentaxEv($val)',
ValueConvInv => 'Image::ExifTool::Pentax::PentaxEvInv($val)',
PrintConv => '$val ? sprintf("%+.1f", $val) : 0',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
21 => { #30
Name => 'LevelIndicator',
PrintConv => '$val == 90 ? "n/a" : $val',
PrintConvInv => '$val eq "n/a" ? 90 : $val',
},
);
# auto-exposure information for the K-01 (ref PH)
%Image::ExifTool::Pentax::AEInfo2 = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'Auto-exposure information for the K-01.',
# instead of /8, should these be PentaxEv(), as in CameraSettings? - PH
2 => {
Name => 'AEExposureTime',
Notes => 'val = 24 * 2**((32-raw)/8)',
ValueConv => '24*exp(-($val-32)*log(2)/8)',
ValueConvInv => '-log($val/24)*8/log(2)+32',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
3 => {
Name => 'AEAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
4 => {
Name => 'AE_ISO',
Notes => 'val = 100 * 2**((raw-32)/8)',
ValueConv => '100*exp(($val-32)*log(2)/8)',
ValueConvInv => 'log($val/100)*8/log(2)+32',
PrintConv => 'int($val + 0.5)',
PrintConvInv => '$val',
},
5 => {
Name => 'AEXv',
# this is the negative of exposure compensation, not including bracketing
Notes => 'val = (raw-64)/8',
ValueConv => '($val-64)/8',
ValueConvInv => '$val * 8 + 64',
},
6 => {
Name => 'AEBXv',
# this is the negative of auto exposure bracketing compensation
Format => 'int8s',
Notes => 'val = raw / 8',
ValueConv => '$val / 8',
ValueConvInv => '$val * 8',
},
8 => {
Name => 'AEError',
Format => 'int8s',
# this is usually zero except in M exposure mode, but it can be non-zero
# in other modes (eg. if you hit an aperture limit in Tv mode)
ValueConv => '-($val-64)/8', # (negate to make overexposed positive)
ValueConvInv => '-$val * 8 + 64',
},
11 => {
Name => 'AEApertureSteps',
Notes => q{
number of steps the aperture has been stopped down from wide open. There
are roughly 8 steps per F-stop, but it varies slightly by lens
},
PrintConv => '$val == 255 ? "n/a" : $val',
PrintConvInv => '$val eq "n/a" ? 255 : $val',
},
15 => {
Name => 'SceneMode',
PrintConvColumns => 2,
PrintConv => {
0 => 'Off',
1 => 'HDR',
4 => 'Auto PICT',
5 => 'Portrait',
6 => 'Landscape',
7 => 'Macro',
8 => 'Sport',
9 => 'Night Scene Portrait',
10 => 'No Flash',
11 => 'Night Scene',
12 => 'Surf & Snow',
14 => 'Sunset',
15 => 'Kids',
16 => 'Pet',
17 => 'Candlelight',
18 => 'Museum',
20 => 'Food',
21 => 'Stage Lighting',
22 => 'Night Snap',
25 => 'Night Scene HDR',
26 => 'Blue Sky',
27 => 'Forest',
29 => 'Backlight Silhouette',
},
},
16 => {
Name => 'AEMaxAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
17 => {
Name => 'AEMaxAperture2',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
18 => {
Name => 'AEMinAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.0f",$val)',
PrintConvInv => '$val',
},
19 => {
Name => 'AEMinExposureTime',
Notes => 'val = 24 * 2**((32-raw)/8)',
ValueConv => '24*exp(-($val-32)*log(2)/8)',
ValueConvInv => '-log($val/24)*8/log(2)+32',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
);
# auto-exposure information for the K-30 (ref PH)
%Image::ExifTool::Pentax::AEInfo3 = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'Auto-exposure information for the K-3, K-30, K-50 and K-500.',
# instead of /8, should these be PentaxEv(), as in CameraSettings? - PH
16 => {
Name => 'AEExposureTime',
Notes => 'val = 24 * 2**((32-raw)/8)',
ValueConv => '24*exp(-($val-32)*log(2)/8)',
ValueConvInv => '-log($val/24)*8/log(2)+32',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
17 => {
Name => 'AEAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
18 => {
Name => 'AE_ISO',
Notes => 'val = 100 * 2**((raw-32)/8)',
ValueConv => '100*exp(($val-32)*log(2)/8)',
ValueConvInv => 'log($val/100)*8/log(2)+32',
PrintConv => 'int($val + 0.5)',
PrintConvInv => '$val',
},
28 => {
Name => 'AEMaxAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
29 => {
Name => 'AEMaxAperture2',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
30 => {
Name => 'AEMinAperture',
Notes => 'val = 2**((raw-68)/16)',
ValueConv => 'exp(($val-68)*log(2)/16)',
ValueConvInv => 'log($val)*16/log(2)+68',
PrintConv => 'sprintf("%.0f",$val)',
PrintConvInv => '$val',
},
31 => {
Name => 'AEMinExposureTime',
Notes => 'val = 24 * 2**((32-raw)/8)',
ValueConv => '24*exp(-($val-32)*log(2)/8)',
ValueConvInv => '-log($val/24)*8/log(2)+32',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
);
# unknown auto-exposure information (Q, Q10)
%Image::ExifTool::Pentax::AEInfoUnknown = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
);
# lens type
%Image::ExifTool::Pentax::LensRec = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => q{
This record stores the LensType, plus one or two unknown bytes for some
models.
},
0 => {
Name => 'LensType',
Format => 'int8u[2]',
Priority => 0,
ValueConvInv => '$val=~s/\.\d+$//; $val',
PrintConv => \%pentaxLensTypes,
SeparateTable => 1,
},
3 => { #PH
Name => 'ExtenderStatus',
Notes => 'not valid if a non-AF lens is used',
PrintConv => { 0 => 'Not attached', 1 => 'Attached' },
},
# this is a binaryData table because some cameras add an extra
# byte or two here (typically zeros)...
);
# lens information (ref PH)
%Image::ExifTool::Pentax::LensInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
IS_SUBDIR => [ 3 ],
NOTES => 'Pentax lens information structure for models such as the *istD.',
0 => {
Name => 'LensType',
Format => 'int8u[2]',
Priority => 0,
ValueConvInv => '$val=~s/\.\d+$//; $val',
PrintConv => \%pentaxLensTypes,
SeparateTable => 1,
},
3 => {
Name => 'LensData',
Format => 'undef[17]',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensData' },
},
);
# lens information for newer models (ref PH)
%Image::ExifTool::Pentax::LensInfo2 = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
IS_SUBDIR => [ 4 ],
NOTES => 'Pentax lens information structure for models such as the K10D and K20D.',
0 => {
Name => 'LensType',
Format => 'int8u[4]',
Priority => 0,
ValueConv => q{
my @v = split(' ',$val);
$v[0] &= 0x0f;
$v[1] = $v[2] * 256 + $v[3]; # (always high byte first)
return "$v[0] $v[1]";
},
# just fill in the missing bits/bytes with zeros...
ValueConvInv => q{
my @v = split(' ',$val);
return undef unless @v == 2;
$v[2] = ($v[1] >> 8) & 0xff;
$v[3] = $v[1] & 0xff;
$v[1] = 0;
return "@v";
},
PrintConv => \%pentaxLensTypes,
SeparateTable => 1,
},
4 => {
Name => 'LensData',
Format => 'undef[17]',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensData' },
},
);
# lens information for 645D (ref PH)
%Image::ExifTool::Pentax::LensInfo3 = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
IS_SUBDIR => [ 13 ],
NOTES => 'Pentax lens information structure for 645D.',
1 => {
Name => 'LensType',
Format => 'int8u[4]',
Priority => 0,
ValueConv => q{
my @v = split(' ',$val);
$v[0] &= 0x0f;
$v[1] = $v[2] * 256 + $v[3]; # (always high byte first)
return "$v[0] $v[1]";
},
# just fill in the missing bits/bytes with zeros...
ValueConvInv => q{
my @v = split(' ',$val);
return undef unless @v == 2;
$v[2] = ($v[1] >> 8) & 0xff;
$v[3] = $v[1] & 0xff;
$v[1] = 0;
return "@v";
},
PrintConv => \%pentaxLensTypes,
SeparateTable => 1,
},
13 => {
Name => 'LensData',
Format => 'undef[17]',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensData' },
},
);
# lens information for K-5, K-r, etc (ref PH)
%Image::ExifTool::Pentax::LensInfo4 = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
IS_SUBDIR => [ 12 ],
NOTES => 'Pentax lens information structure for models such as the K-5 and K-r.',
1 => {
Name => 'LensType',
Format => 'int8u[4]',
Priority => 0,
ValueConv => q{
my @v = split(' ',$val);
$v[0] &= 0x0f;
$v[1] = $v[2] * 256 + $v[3]; # (always high byte first)
return "$v[0] $v[1]";
},
# just fill in the missing bits/bytes with zeros...
ValueConvInv => q{
my @v = split(' ',$val);
return undef unless @v == 2;
$v[2] = ($v[1] >> 8) & 0xff;
$v[3] = $v[1] & 0xff;
$v[1] = 0;
return "@v";
},
PrintConv => \%pentaxLensTypes,
SeparateTable => 1,
},
12 => {
Name => 'LensData',
Format => 'undef[18]',
Condition => '$$self{NewLensData} = 1', # not really a condition, just used to set flag
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensData' },
},
);
# lens information for K-01, K-30, K-50, K-500, K-3, K-3II (ref PH)
%Image::ExifTool::Pentax::LensInfo5 = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
IS_SUBDIR => [ 15 ],
NOTES => 'Pentax lens information structure for the K-01 and newer models.',
1 => {
Name => 'LensType',
Format => 'int8u[5]',
Priority => 0,
ValueConv => q{
my @v = split(' ',$val);
$v[0] &= 0x0f;
$v[1] = $v[3] * 256 + $v[4]; # (always high byte first)
return "$v[0] $v[1]";
},
# just fill in the missing bits/bytes with zeros...
ValueConvInv => q{
my @v = split(' ',$val);
return undef unless @v == 2;
$v[3] = ($v[1] >> 8) & 0xff;
$v[4] = $v[1] & 0xff;
$v[1] = $v[2] = 0;
return "@v";
},
PrintConv => \%pentaxLensTypes,
SeparateTable => 1,
},
15 => {
Name => 'LensData',
Format => 'undef[17]',
SubDirectory => { TagTable => 'Image::ExifTool::Pentax::LensData' },
},
);
# lens data information, including lens codes (ref PH)
%Image::ExifTool::Pentax::LensData = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
DATAMEMBER => [ 12.1 ],
NOTES => q{
Pentax lens data information. Some of these tags require interesting binary
gymnastics to decode them into useful values.
},
# this byte comes from the lens electrical contacts
# (see http://kmp.bdimitrov.de/technology/K-mount/Ka.html)
0.1 => { #JD
Name => 'AutoAperture',
Condition => 'not $$self{NewLensData}',
Notes => 'not valid for the K-r, K-5 or K-5II', #29
Mask => 0x01,
PrintConv => {
0 => 'On',
1 => 'Off',
},
},
0.2 => { #JD
Name => 'MinAperture',
Condition => 'not $$self{NewLensData}',
Notes => 'not valid for the K-r, K-5 or K-5II', #29
Mask => 0x06,
PrintConv => {
0x00 => 22,
0x02 => 32,
0x04 => 45,
0x06 => 16,
},
},
0.3 => { #JD
Name => 'LensFStops',
Condition => 'not $$self{NewLensData}',
Notes => 'not valid for the K-r, K-5 or K-5II', #29
Mask => 0x70,
ValueConv => '5 + (($val >> 4) ^ 0x07) / 2',
ValueConvInv => '((($val - 5) * 2) ^ 0x07) << 4',
},
# 1-16 look like Lens Codes LC0-LC15, ref patent 5617173 and 5999753 [+notes by PH]
1 => { # LC0 = lens kind + version data
Name => 'LensKind',
%lensCode,
},
2 => { # LC1 = lens data (changes with AF setting)
Name => 'LC1',
%lensCode,
},
# LC2 = distance data
3 => { #29
Name => 'MinFocusDistance',
Notes => 'minimum focus distance for the lens',
Mask => 0xf8,
PrintConv => {
0x00 => '0.13-0.19 m', # (plus K or M lenses)
0x08 => '0.20-0.24 m',
0x10 => '0.25-0.28 m',
0x18 => '0.28-0.30 m',
0x20 => '0.35-0.38 m',
0x28 => '0.40-0.45 m',
0x30 => '0.49-0.50 m', # (plus many Sigma lenses)
0x38 => '0.6 m', #PH (NC)
0x40 => '0.7 m', # (plus Sigma 55-200)
0x48 => '0.8-0.9 m', #PH (NC) Tokina 28-70/2.6-2.8
0x50 => '1.0 m', # (plus Sigma 70 macro)
0x58 => '1.1-1.2 m',
0x60 => '1.4-1.5 m',
0x68 => '1.5 m', # Sigma 70-300/4-5.6 macro
0x70 => '2.0 m',
0x78 => '2.0-2.1 m', #PH (NC)
0x80 => '2.1 m', # Sigma 135-400 APO & DG: 2.0-2.2m
0x88 => '2.2-2.9 m', #PH (NC)
0x90 => '3.0 m', # Sigma 50-500 : 1.0-3.0m depending on the focal length
## 50mm, 100mm => 1.0m
## 200mm => 1.1m
## 300mm => 1.5m
## 400mm => 2.2m
## 500mm => 3.0m
0x98 => '4-5 m', #PH (NC)
0xa0 => '5.6 m', # Pentax DA 560
# To check: Sigma 120-400 OS: MFD 1.5m
# To check: Sigma 150-500 OS: MFD 2.2m
# To check: Sigma 50-500 has MFD 50-180cm
# 0xd0 - seen for the Sigma 4.5mm F2.8 EX DC HSM Circular Fisheye (ref PH)
},
},
3.1 => { #29
Name => 'FocusRangeIndex',
Mask => 0x07,
PrintConv => {
7 => '0 (very close)',
6 => '1 (close)',
4 => '2',
5 => '3',
1 => '4',
0 => '5',
2 => '6 (far)',
3 => '7 (very far)',
},
},
4 => { # LC3 = K-value data (AF pulses to displace image by unit length)
Name => 'LC3',
%lensCode,
},
5 => { # LC4 = abberation correction, near distance data
Name => 'LC4',
%lensCode,
},
6 => { # LC5 = light color abberation correction data
Name => 'LC5',
%lensCode,
},
7 => { # LC6 = open abberation data
Name => 'LC6',
%lensCode,
},
8 => { # LC7 = AF minimum actuation condition
Name => 'LC7',
%lensCode,
},
9 => [{ # LC8 = focal length data
Name => 'LensFocalLength',
Notes => 'focal length of lens alone, without adapter', #PH
Priority => 0,
Condition => '$$self{Model} !~ /645Z/', #PH (doesn't work for 645Z)
ValueConv => '10*($val>>2) * 4**(($val&0x03)-2)', #JD
ValueConvInv => q{
my $range = int(log($val/10)/(2*log(2)));
warn("Value out of range") and return undef if $range < 0 or $range > 3;
return $range + (int($val/(10*4**($range-2))+0.5) << 2);
},
PrintConv => 'sprintf("%.1f mm", $val)',
PrintConvInv => '$val=~s/\s*mm//; $val',
},{
Name => 'LC8',
%lensCode,
}],
# the following aperture values change with focal length
10 => { # LC9 = nominal AVmin/AVmax data (open/closed aperture values)
Name => 'NominalMaxAperture',
Mask => 0xf0,
ValueConv => '2**(($val>>4)/4)', #JD
ValueConvInv => '4*log($val)/log(2) << 4',
PrintConv => 'sprintf("%.1f", $val)',
PrintConvInv => '$val',
},
10.1 => { # LC9 = nominal AVmin/AVmax data (open/closed aperture values)
Name => 'NominalMinAperture',
Mask => 0x0f,
ValueConv => '2**(($val+10)/4)', #JD
ValueConvInv => '4*log($val)/log(2) - 10',
PrintConv => 'sprintf("%.0f", $val)',
PrintConvInv => '$val',
},
11 => { # LC10 = mv'/nv' data (full-aperture metering error compensation/marginal lumination compensation)
Name => 'LC10',
%lensCode,
},
12 => { # LC11 = AVC 1/EXP data
Name => 'LC11',
%lensCode,
},
12.1 => {
Name => 'NewLensDataHook',
Hidden => 1,
Hook => '$varSize += 1 if $$self{NewLensData}',
RawConv => 'undef',
},
13 => { # LC12 = mv1 AVminsif data
Name => 'LC12',
Notes => "ID's 13-16 are offset by 1 for the K-r, K-5 and K-5II", #29
%lensCode,
},
# 14 - related to live view for K-5 (normally 3, but 1 or 5 in LV mode)
14.1 => { # LC13 = AVmin (open aperture value) [MaxAperture=(2**((AVmin-1)/32))]
Name => 'MaxAperture',
Condition => '$$self{Model} ne "K-5"',
Notes => 'effective wide open aperture for current focal length',
Mask => 0x7f, # (not sure what the high bit indicates)
# (a value of 1 seems to indicate 'n/a')
RawConv => '$val > 1 ? $val : undef',
ValueConv => '2**(($val-1)/32)',
ValueConvInv => '32*log($val)/log(2) + 1',
PrintConv => 'sprintf("%.1f", $val)',
PrintConvInv => '$val',
},
15 => { # LC14 = UNT_12 UNT_6 data
Name => 'LC14',
%lensCode,
},
16 => { # LC15 = incorporated flash suited END data
Name => 'LC15',
%lensCode,
},
);
# flash information (ref PH)
%Image::ExifTool::Pentax::FlashInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'Flash information tags for the K10D, K20D and K200D.',
0 => {
Name => 'FlashStatus',
PrintHex => 1,
PrintConv => { #19
0x00 => 'Off',
0x01 => 'Off (1)', #PH (K-5)
0x02 => 'External, Did not fire', # 0010
0x06 => 'External, Fired', # 0110
0x08 => 'Internal, Did not fire (0x08)',
0x09 => 'Internal, Did not fire', # 1001
0x0d => 'Internal, Fired', # 1101
},
},
1 => {
Name => 'InternalFlashMode',
PrintHex => 1,
PrintConv => {
0x00 => 'n/a - Off-Auto-Aperture', #19
0x86 => 'Fired, Wireless (Control)', #19
0x95 => 'Fired, Wireless (Master)', #19
0xc0 => 'Fired', # K10D
0xc1 => 'Fired, Red-eye reduction', # *istDS2, K10D
0xc2 => 'Fired, Auto', # K100D, K110D
0xc3 => 'Fired, Auto, Red-eye reduction', #PH
0xc6 => 'Fired, Wireless (Control), Fired normally not as control', #19 (Remote 3s)
0xc8 => 'Fired, Slow-sync', # K10D
0xc9 => 'Fired, Slow-sync, Red-eye reduction', # K10D
0xca => 'Fired, Trailing-curtain Sync', # K10D
0xf0 => 'Did not fire, Normal', #19
0xf1 => 'Did not fire, Red-eye reduction', #19
0xf2 => 'Did not fire, Auto', #19
0xf3 => 'Did not fire, Auto, Red-eye reduction', #19
0xf4 => 'Did not fire, (Unknown 0xf4)', #19
0xf5 => 'Did not fire, Wireless (Master)', #19
0xf6 => 'Did not fire, Wireless (Control)', #19
0xf8 => 'Did not fire, Slow-sync', #19
0xf9 => 'Did not fire, Slow-sync, Red-eye reduction', #19
0xfa => 'Did not fire, Trailing-curtain Sync', #19
},
},
2 => {
Name => 'ExternalFlashMode',
PrintHex => 1,
PrintConv => { #19
0x00 => 'n/a - Off-Auto-Aperture',
0x3f => 'Off',
0x40 => 'On, Auto',
0xbf => 'On, Flash Problem', #JD
0xc0 => 'On, Manual',
0xc4 => 'On, P-TTL Auto',
0xc5 => 'On, Contrast-control Sync', #JD
0xc6 => 'On, High-speed Sync',
0xcc => 'On, Wireless',
0xcd => 'On, Wireless, High-speed Sync',
0xf0 => 'Not Connected', #PH (K-5)
},
},
3 => {
Name => 'InternalFlashStrength',
Notes => 'saved from the most recent flash picture, on a scale of about 0 to 100',
},
4 => 'TTL_DA_AUp',
5 => 'TTL_DA_ADown',
6 => 'TTL_DA_BUp',
7 => 'TTL_DA_BDown',
24.1 => { #19/17
Name => 'ExternalFlashGuideNumber',
Mask => 0x1f,
Notes => 'val = 2**(raw/16 + 4), with a few exceptions',
ValueConv => q{
return 0 unless $val;
$val = -3 if $val == 29; # -3 is stored as 0x1d
return 2**($val/16 + 4);
},
ValueConvInv => q{
return 0 unless $val;
my $raw = int((log($val)/log(2)-4)*16+0.5);
$raw = 29 if $raw < 0; # guide number of 14 gives -3 which is stored as 0x1d
$raw = 31 if $raw > 31; # maximum value is 0x1f
return $raw;
},
PrintConv => '$val ? int($val + 0.5) : "n/a"',
PrintConvInv => '$val=~/^n/ ? 0 : $val',
# observed values for various flash focal lengths/guide numbers:
# AF-540FGZ (ref 19) AF-360FGZ (ref 17)
# 6 => 20mm/21 29 => 20mm/14 (wide angle panel used)
# 16 => 24mm/32 6 => 24mm/21
# 18 => 28mm/35 7 => 28mm/22
# 21 => 35mm/39 10 => 35mm/25
# 24 => 50mm/45 14 => 50mm/30
# 26 => 70mm/50 17 => 70mm/33
# 28 => 85mm/54 19 => 85mm/36
# (I have also seen a value of 31 when both flashes are used together
# in a wired configuration, but I don't know exactly what this means - PH)
},
# 24 - have seen bit 0x80 set when 2 external wired flashes are used - PH
# 24 - have seen bit 0x40 set when wireless high speed sync is used - ref 19
25 => { #19
Name => 'ExternalFlashExposureComp',
PrintConv => {
0 => 'n/a', # Off or Auto Modes
144 => 'n/a (Manual Mode)', # Manual Flash Output
164 => '-3.0',
167 => '-2.5',
168 => '-2.0',
171 => '-1.5',
172 => '-1.0',
175 => '-0.5',
176 => '0.0',
179 => '0.5',
180 => '1.0',
},
},
26 => { #17
Name => 'ExternalFlashBounce',
Notes => 'saved from the most recent external flash picture', #19
PrintConv => {
0 => 'n/a',
16 => 'Direct',
48 => 'Bounce',
},
},
# ? => 'ExternalFlashAOutput',
# ? => 'ExternalFlashBOutput',
);
%Image::ExifTool::Pentax::FlashInfoUnknown = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# 4 - changes with FEC for K-5 - PH
);
# camera manufacture information (ref PH)
%Image::ExifTool::Pentax::CameraInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
FORMAT => 'int32u',
0 => {
Name => 'PentaxModelID',
Priority => 0, # (Optio SVi uses incorrect Optio SV ID here)
SeparateTable => 1,
PrintHex => 1,
PrintConv => \%pentaxModelID,
},
1 => {
Name => 'ManufactureDate',
Groups => { 2 => 'Time' },
Notes => q{
this value, and the values of the tags below, may change if the camera is
serviced
},
ValueConv => q{
$val =~ /^(\d{4})(\d{2})(\d{2})$/ and return "$1:$2:$3";
# Optio A10 and A20 leave "200" off the year
$val =~ /^(\d)(\d{2})(\d{2})$/ and return "200$1:$2:$3";
return "Unknown ($val)";
},
ValueConvInv => '$val=~tr/0-9//dc; $val',
},
2 => {
#(see http://www.pentaxforums.com/forums/pentax-dslr-discussion/25711-k10d-update-model-revision-8-1-yes-no-8.html)
Name => 'ProductionCode', #(previously ModelRevision)
Format => 'int32u[2]',
Note => 'values of 8.x indicate that the camera has been serviced',
ValueConv => '$val=~tr/ /./; $val',
ValueConvInv => '$val=~tr/./ /; $val',
PrintConv => '$val=~/^8\./ ? "$val (camera has been serviced)" : $val',
PrintConvInv => '$val=~s/\s+.*//s; $val',
},
4 => 'InternalSerialNumber',
);
# battery information (ref PH)
%Image::ExifTool::Pentax::BatteryInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# size of data:
# 4 (K-m,K2000=4xAA), 6 (*istD,K10D,K100D,K110D=2xCR-V3/4xAA),
# 7 (K20D=D-LI50, K200D=4xAA), 8 (645D=D-LI90), 10 (K-r pre-production?),
# 14 (K-7=D-LI90, K-r=D-LI109/4xAA, K-x=4xAA), 26 (K-5=D-LI90)
# battery grips available for:
# BG1 (*istD), BG2 (K10D/K20D), BG3 (K200D), BG4 (K-7,K-5)
# no grip available: K-x
0.1 => { #19
Name => 'PowerSource',
Mask => 0x0f,
# have seen the upper bit set (value of 0x82) for the
# *istDS and K100D, but I'm not sure what this means - PH
# I've also seen: 0x42 (K2000), 0xf2 (K-7,K-r,K-5), 0x12,0x22 (K-x) - PH
PrintConv => {
2 => 'Body Battery',
3 => 'Grip Battery',
4 => 'External Power Supply', #PH
},
},
1.1 => [
{
Name => 'BodyBatteryState',
Condition => '$$self{Model} =~ /(\*ist|K100D|K200D|K10D|GX10|K20D|GX20|GX-1[LS]?)\b/',
Notes => '*istD, K100D, K200D, K10D and K20D',
Mask => 0xf0,
PrintConv => { #19
0x10 => 'Empty or Missing',
0x20 => 'Almost Empty',
0x30 => 'Running Low',
0x40 => 'Full',
},
},{
Name => 'BodyBatteryState',
Condition => '$$self{Model} !~ /(K110D|K2000|K-m)\b/',
Notes => 'other models except the K110D, K2000 and K-m',
Mask => 0xf0,
PrintConv => {
0x10 => 'Empty or Missing',
0x20 => 'Almost Empty',
0x30 => 'Running Low',
0x40 => 'Close to Full',
0x50 => 'Full',
},
},{
Name => 'BodyBatteryState',
Notes => 'decoding unknown for other models',
Mask => 0xf0,
ValueConv => '$val >> 4',
ValueConvInv => '$val << 4',
},
],
1.2 => [
{
Name => 'GripBatteryState',
Condition => '$$self{Model} =~ /(K10D|GX10|K20D|GX20)\b/',
Notes => 'K10D and K20D',
Mask => 0x0f,
PrintConv => { #19
0x01 => 'Empty or Missing',
0x02 => 'Almost Empty',
0x03 => 'Running Low',
0x04 => 'Full',
},
},{
Name => 'GripBatteryState',
Notes => 'decoding unknown for other models',
Unknown => 1, # (doesn't appear to be valid for the K-5)
Mask => 0x0f,
},
],
# internal and grip battery voltage Analogue to Digital measurements,
# open circuit and under load
2 => [
{
Name => 'BodyBatteryADNoLoad',
Description => 'Body Battery A/D No Load',
Condition => '$$self{Model} =~ /(K10D|GX10|K20D|GX20)\b/',
Notes => 'roughly calibrated for K10D with a new Pentax battery',
# rough linear calibration drops quickly below 30% - PH
# DVM readings: 8.18V=186, 8.42-8.40V=192 (full), 6.86V=155 (empty)
PrintConv => 'sprintf("%d (%.1fV, %d%%)",$val,$val*8.18/186,($val-155)*100/35)',
PrintConvInv => '$val=~s/ .*//; $val',
},
{
Name => 'BodyBatteryADNoLoad',
Description => 'Body Battery A/D No Load',
Condition => '$$self{Model} =~ /(\*ist|K100D|K200D|GX-1[LS]?)\b/',
},
{
Name => 'BodyBatteryVoltage1', # (static?)
Condition => '$$self{Model} !~ /(K100D|K110D|K2000|K-m|Q\d*)\b/',
Format => 'int16u',
ValueConv => '$val / 100',
ValueConvInv => '$val * 100',
PrintConv => 'sprintf("%.2f V", $val)',
PrintConvInv => '$val =~ s/\s*V$//',
# For my K-5: Min (0%) Max (100%) At Meas
# BodyBatteryVoltage1 6.24 V 7.75 V 7.66 V
# BodyBatteryVoltage2 5.98 V 7.43 V 7.34 V
# BodyBatteryVoltage3 6.41 V 7.93 V 7.84 V
# BodyBatteryVoltage4 6.10 V 7.55 V 7.45 V
# "Meas" open-circuit voltages with DVM: AB=0V, AC=+8.33V, BC=+8.22V
# (terminal "C" is closest to edge of battery)
},
],
3 => [
{
Name => 'BodyBatteryADLoad',
Description => 'Body Battery A/D Load',
Condition => '$$self{Model} =~ /(K10D|GX10|K20D|GX20)\b/',
Notes => 'roughly calibrated for K10D with a new Pentax battery',
# [have seen 187] - PH
PrintConv => 'sprintf("%d (%.1fV, %d%%)",$val,$val*8.18/186,($val-152)*100/34)',
PrintConvInv => '$val=~s/ .*//; $val',
},
{
Name => 'BodyBatteryADLoad',
Description => 'Body Battery A/D Load',
Condition => '$$self{Model} =~ /(\*ist|K100D|K200D)\b/',
},
],
4 => [
{
Name => 'GripBatteryADNoLoad',
Description => 'Grip Battery A/D No Load',
Condition => '$$self{Model} =~ /(\*ist|K10D|GX10|K20D|GX20|GX-1[LS]?)\b/',
},
{
Name => 'BodyBatteryVoltage2', # (less than BodyBatteryVoltage1 -- under load?)
Condition => '$$self{Model} !~ /(K100D|K110D|K2000|K-m|Q\d*)\b/',
Format => 'int16u',
ValueConv => '$val / 100',
ValueConvInv => '$val * 100',
PrintConv => 'sprintf("%.2f V", $val)',
PrintConvInv => '$val =~ s/\s*V$//',
},
],
5 => {
Name => 'GripBatteryADLoad',
Condition => '$$self{Model} =~ /(\*ist|K10D|GX10|K20D|GX20)\b/',
Description => 'Grip Battery A/D Load',
},
6 => {
Name => 'BodyBatteryVoltage3', # (greater than BodyBatteryVoltage1)
Condition => '$$self{Model} =~ /(K-5|K-r|645D)\b/',
Format => 'int16u',
Notes => 'K-5, K-r and 645D only',
ValueConv => '$val / 100',
ValueConvInv => '$val * 100',
PrintConv => 'sprintf("%.2f V", $val)',
PrintConvInv => '$val =~ s/\s*V$//',
},
8 => {
Name => 'BodyBatteryVoltage4', # (between BodyBatteryVoltage1 and BodyBatteryVoltage2)
Condition => '$$self{Model} =~ /(K-5|K-r)\b/',
Format => 'int16u',
Notes => 'K-5 and K-r only',
ValueConv => '$val / 100',
ValueConvInv => '$val * 100',
PrintConv => 'sprintf("%.2f V", $val)',
PrintConvInv => '$val =~ s/\s*V$//',
},
);
# auto focus information
%Image::ExifTool::Pentax::AFInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# AF Info tag names in K10D debugging output - PH:
# SelectArea, InFocusArea, Predictor, Defocus, IntegTime2msStep,
# CalFlag, ContrastFlag, PrecalFlag, SelectSensor
0x00 => { #PH
Name => 'AFPointsUnknown1',
Unknown => 1,
Format => 'int16u',
ValueConv => '$self->Options("Unknown") ? $val : $val & 0x7ff',
ValueConvInv => '$val',
PrintConvColumns => 2,
PrintConv => {
0 => '(none)',
0x07ff => 'All',
0x0777 => 'Central 9 points',
BITMASK => {
0 => 'Upper-left',
1 => 'Top',
2 => 'Upper-right',
3 => 'Left',
4 => 'Mid-left',
5 => 'Center',
6 => 'Mid-right',
7 => 'Right',
8 => 'Lower-left',
9 => 'Bottom',
10 => 'Lower-right',
# (bits 12-15 are flags of some sort)
},
},
},
0x02 => { #PH
Name => 'AFPointsUnknown2',
Unknown => 1,
Format => 'int16u',
ValueConv => '$self->Options("Unknown") ? $val : $val & 0x7ff',
ValueConvInv => '$val',
PrintConvColumns => 2,
PrintConv => {
0 => 'Auto',
BITMASK => {
0 => 'Upper-left',
1 => 'Top',
2 => 'Upper-right',
3 => 'Left',
4 => 'Mid-left',
5 => 'Center',
6 => 'Mid-right',
7 => 'Right',
8 => 'Lower-left',
9 => 'Bottom',
10 => 'Lower-right',
# (bits 12-15 are flags of some sort)
# bit 15 is set for center focus point only if it is vertical
},
},
},
0x04 => { #PH (educated guess - predicted amount to drive lens)
Name => 'AFPredictor',
Format => 'int16s',
},
0x06 => 'AFDefocus', #PH (educated guess - calculated distance from focused)
0x07 => { #PH
# effective exposure time for AF sensors in 2 ms increments
Name => 'AFIntegrationTime',
Notes => 'times less than 2 ms give a value of 0',
ValueConv => '$val * 2',
ValueConvInv => 'int($val / 2)', # (don't round up)
PrintConv => '"$val ms"',
PrintConvInv => '$val=~tr/0-9//dc; $val',
},
# 0x0a - values: 00,05,0d,15,86,8e,a6,ae
0x0b => { #JD
Name => 'AFPointsInFocus',
Condition => '$$self{Model} !~ /K-3\b/',
Notes => q{
models other than the K-3 only. May report two points in focus even though
a single AFPoint has been selected, in which case the selected AFPoint is
the first reported
},
PrintConvColumns => 2,
PrintConv => {
0 => 'None',
1 => 'Lower-left, Bottom',
2 => 'Bottom',
3 => 'Lower-right, Bottom',
4 => 'Mid-left, Center',
5 => 'Center (horizontal)', #PH
6 => 'Mid-right, Center',
7 => 'Upper-left, Top',
8 => 'Top',
9 => 'Upper-right, Top',
10 => 'Right',
11 => 'Lower-left, Mid-left',
12 => 'Upper-left, Mid-left',
13 => 'Bottom, Center',
14 => 'Top, Center',
15 => 'Lower-right, Mid-right',
16 => 'Upper-right, Mid-right',
17 => 'Left',
18 => 'Mid-left',
19 => 'Center (vertical)', #PH
20 => 'Mid-right',
},
},
0x1fd => {
Name => 'AFHold',
Notes => 'decoded only for the K-3 II',
Condition => '$$self{Model} eq "PENTAX K-3 II"',
PrintConv => { 0 => 'Off', 1 => 'Short', 2 => 'Medium', 3 => 'Long' },
},
);
# Kelvin white balance information (ref 28, topic 4834)
%Image::ExifTool::Pentax::KelvinWB = (
%binaryDataAttrs,
FORMAT => 'int16u',
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'White balance Blue/Red gains as a function of color temperature.',
1 => { Name => 'KelvinWB_Daylight', %kelvinWB },
5 => { Name => 'KelvinWB_01', %kelvinWB },
9 => { Name => 'KelvinWB_02', %kelvinWB },
13 => { Name => 'KelvinWB_03', %kelvinWB },
17 => { Name => 'KelvinWB_04', %kelvinWB },
21 => { Name => 'KelvinWB_05', %kelvinWB },
25 => { Name => 'KelvinWB_06', %kelvinWB },
29 => { Name => 'KelvinWB_07', %kelvinWB },
33 => { Name => 'KelvinWB_08', %kelvinWB },
37 => { Name => 'KelvinWB_09', %kelvinWB },
41 => { Name => 'KelvinWB_10', %kelvinWB },
45 => { Name => 'KelvinWB_11', %kelvinWB },
49 => { Name => 'KelvinWB_12', %kelvinWB },
53 => { Name => 'KelvinWB_13', %kelvinWB },
57 => { Name => 'KelvinWB_14', %kelvinWB },
61 => { Name => 'KelvinWB_15', %kelvinWB },
65 => { Name => 'KelvinWB_16', %kelvinWB },
);
# color information - PH
%Image::ExifTool::Pentax::ColorInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
FORMAT => 'int8s',
16 => {
Name => 'WBShiftAB',
Notes => 'positive is a shift toward blue',
},
17 => {
Name => 'WBShiftGM',
Notes => 'positive is a shift toward green',
},
);
# EV step size information - ref 19
%Image::ExifTool::Pentax::EVStepInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
0 => {
Name => 'EVSteps',
PrintConv => {
0 => '1/2 EV Steps',
1 => '1/3 EV Steps',
},
},
1 => {
Name => 'SensitivitySteps',
PrintConv => {
0 => '1 EV Steps',
1 => 'As EV Steps',
},
},
);
# shot information? - ref PH (K-5)
%Image::ExifTool::Pentax::ShotInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# 0: 0xf2/0xf3 (HDR), 0xf0 (otherwise)
1 => { # (presumably this is from an orientation sensor)
Name => 'CameraOrientation',
Condition => '$$self{Model} =~ /K-(5|7|r|x)\b/',
Notes => 'K-5, K-7, K-r and K-x',
PrintHex => 1,
PrintConv => {
0x10 => 'Horizontal (normal)',
0x20 => 'Rotate 180',
0x30 => 'Rotate 90 CW',
0x40 => 'Rotate 270 CW',
0x50 => 'Upwards', # (to the sky)
0x60 => 'Downwards', # (to the ground)
},
},
# 2: 0xd3 (live view), 0xdb (HDR), 0x7b (otherwise)
# 3: 0xff
# 4: 0x64, 0x6a, 0x6f, 0xa4, 0xaa, 0xab, 0xbf
# 5: 0xfe
# 6: 0x0e
# 7: 0x02 (live view), 0x06 (otherwise)
# 8-10: 0x00
);
# face detect positions - ref PH (Optio RZ10)
%Image::ExifTool::Pentax::FacePos = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
FORMAT => 'int16u',
0 => {
Name => 'Face1Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 1 ? undef : $val',
Notes => 'X/Y coordinates of face center in full-sized image',
},
2 => {
Name => 'Face2Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 2 ? undef : $val',
},
4 => {
Name => 'Face3Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 3 ? undef : $val',
},
6 => {
Name => 'Face4Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 4 ? undef : $val',
},
8 => {
Name => 'Face5Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 5 ? undef : $val',
},
10 => {
Name => 'Face6Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 6 ? undef : $val',
},
12 => {
Name => 'Face7Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 7 ? undef : $val',
},
14 => {
Name => 'Face8Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 8 ? undef : $val',
},
16 => {
Name => 'Face9Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 9 ? undef : $val',
},
18 => {
Name => 'Face10Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 10 ? undef : $val',
},
20 => {
Name => 'Face11Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 11 ? undef : $val',
},
22 => {
Name => 'Face12Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 12 ? undef : $val',
},
24 => {
Name => 'Face13Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 13 ? undef : $val',
},
26 => {
Name => 'Face14Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 14 ? undef : $val',
},
28 => {
Name => 'Face15Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 15 ? undef : $val',
},
30 => {
Name => 'Face16Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 16 ? undef : $val',
},
32 => {
Name => 'Face17Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 17 ? undef : $val',
},
34 => {
Name => 'Face18Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 18 ? undef : $val',
},
36 => {
Name => 'Face19Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 19 ? undef : $val',
},
38 => {
Name => 'Face20Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 20 ? undef : $val',
},
40 => {
Name => 'Face21Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 21 ? undef : $val',
},
42 => {
Name => 'Face22Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 22 ? undef : $val',
},
44 => {
Name => 'Face23Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 23 ? undef : $val',
},
46 => {
Name => 'Face24Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 24 ? undef : $val',
},
48 => {
Name => 'Face25Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 25 ? undef : $val',
},
50 => {
Name => 'Face26Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 26 ? undef : $val',
},
52 => {
Name => 'Face27Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 27 ? undef : $val',
},
54 => {
Name => 'Face28Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 28 ? undef : $val',
},
56 => {
Name => 'Face29Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 29 ? undef : $val',
},
58 => {
Name => 'Face30Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 30 ? undef : $val',
},
60 => {
Name => 'Face31Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 31 ? undef : $val',
},
62 => {
Name => 'Face32Position',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 32 ? undef : $val',
},
);
# face detect sizes - ref PH (Optio RZ10)
%Image::ExifTool::Pentax::FaceSize = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
FORMAT => 'int16u',
0 => {
Name => 'Face1Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 1 ? undef : $val',
},
2 => {
Name => 'Face2Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 2 ? undef : $val',
},
4 => {
Name => 'Face3Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 3 ? undef : $val',
},
6 => {
Name => 'Face4Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 4 ? undef : $val',
},
8 => {
Name => 'Face5Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 5 ? undef : $val',
},
10 => {
Name => 'Face6Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 6 ? undef : $val',
},
12 => {
Name => 'Face7Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 7 ? undef : $val',
},
14 => {
Name => 'Face8Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 8 ? undef : $val',
},
16 => {
Name => 'Face9Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 9 ? undef : $val',
},
18 => {
Name => 'Face10Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 10 ? undef : $val',
},
20 => {
Name => 'Face11Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 11 ? undef : $val',
},
22 => {
Name => 'Face12Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 12 ? undef : $val',
},
24 => {
Name => 'Face13Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 13 ? undef : $val',
},
26 => {
Name => 'Face14Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 14 ? undef : $val',
},
28 => {
Name => 'Face15Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 15 ? undef : $val',
},
30 => {
Name => 'Face16Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 16 ? undef : $val',
},
32 => {
Name => 'Face17Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 17 ? undef : $val',
},
34 => {
Name => 'Face18Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 18 ? undef : $val',
},
36 => {
Name => 'Face19Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 19 ? undef : $val',
},
38 => {
Name => 'Face20Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 20 ? undef : $val',
},
40 => {
Name => 'Face21Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 21 ? undef : $val',
},
42 => {
Name => 'Face22Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 22 ? undef : $val',
},
44 => {
Name => 'Face23Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 23 ? undef : $val',
},
46 => {
Name => 'Face24Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 24 ? undef : $val',
},
48 => {
Name => 'Face25Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 25 ? undef : $val',
},
50 => {
Name => 'Face26Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 26 ? undef : $val',
},
52 => {
Name => 'Face27Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 27 ? undef : $val',
},
54 => {
Name => 'Face28Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 28 ? undef : $val',
},
56 => {
Name => 'Face29Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 29 ? undef : $val',
},
58 => {
Name => 'Face30Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 30 ? undef : $val',
},
60 => {
Name => 'Face31Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 31 ? undef : $val',
},
62 => {
Name => 'Face32Size',
Format => 'int16u[2]',
RawConv => '$$self{FacesDetected} < 32 ? undef : $val',
},
);
# digital filter information - ref PH (K-5)
%Image::ExifTool::Pentax::FilterInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
FORMAT => 'int8u',
NOTES => q{
The parameters associated with each type of digital filter are unique, and
these settings are also extracted with the DigitalFilter tag. Information
is not extracted for filters that are "Off" unless the Unknown option is
used.
},
0 => {
Name => 'SourceDirectoryIndex',
Format => 'int16u',
},
2 => {
Name => 'SourceFileIndex',
Format => 'int16u',
},
0x005 => { Name => 'DigitalFilter01', %digitalFilter },
0x016 => { Name => 'DigitalFilter02', %digitalFilter },
0x027 => { Name => 'DigitalFilter03', %digitalFilter },
0x038 => { Name => 'DigitalFilter04', %digitalFilter },
0x049 => { Name => 'DigitalFilter05', %digitalFilter },
0x05a => { Name => 'DigitalFilter06', %digitalFilter },
0x06b => { Name => 'DigitalFilter07', %digitalFilter },
0x07c => { Name => 'DigitalFilter08', %digitalFilter },
0x08d => { Name => 'DigitalFilter09', %digitalFilter },
0x09e => { Name => 'DigitalFilter10', %digitalFilter },
0x0af => { Name => 'DigitalFilter11', %digitalFilter },
0x0c0 => { Name => 'DigitalFilter12', %digitalFilter },
0x0d1 => { Name => 'DigitalFilter13', %digitalFilter },
0x0e2 => { Name => 'DigitalFilter14', %digitalFilter },
0x0f3 => { Name => 'DigitalFilter15', %digitalFilter },
0x104 => { Name => 'DigitalFilter16', %digitalFilter },
0x115 => { Name => 'DigitalFilter17', %digitalFilter },
0x126 => { Name => 'DigitalFilter18', %digitalFilter },
0x137 => { Name => 'DigitalFilter19', %digitalFilter },
0x148 => { Name => 'DigitalFilter20', %digitalFilter },
);
# electronic level information - ref PH (K-5)
%Image::ExifTool::Pentax::LevelInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
FORMAT => 'int8s',
NOTES => q{
Tags decoded from the electronic level information for the K-5. May not be
valid for other models.
},
0 => {
Name => 'LevelOrientation',
Mask => 0x0f,
PrintHex => 0,
PrintConv => {
1 => 'Horizontal (normal)',
2 => 'Rotate 180',
3 => 'Rotate 90 CW',
4 => 'Rotate 270 CW',
9 => 'Horizontal; Off Level',
10 => 'Rotate 180; Off Level',
11 => 'Rotate 90 CW; Off Level',
12 => 'Rotate 270 CW; Off Level',
13 => 'Upwards',
14 => 'Downwards',
},
},
0.1 => {
Name => 'CompositionAdjust',
Mask => 0xf0,
PrintConv => {
0x00 => 'Off',
0x20 => 'Composition Adjust',
0xa0 => 'Composition Adjust + Horizon Correction',
0xc0 => 'Horizon Correction',
},
},
1 => {
Name => 'RollAngle',
Notes => 'converted to degrees of clockwise camera rotation',
ValueConv => '-$val / 2',
ValueConvInv => '-$val * 2',
},
2 => {
Name => 'PitchAngle',
Notes => 'converted to degrees of upward camera tilt',
ValueConv => '-$val / 2',
ValueConvInv => '-$val * 2',
},
# 3,4 - related somehow to horizon correction and composition adjust
# 5,6,7 - (the notes below refer to how the image moves in the LCD monitor)
5 => {
Name => 'CompositionAdjustX',
Notes => 'steps to the right, 1/16 mm per step',
ValueConv => '-$val',
ValueConvInv => '-$val',
},
6 => {
Name => 'CompositionAdjustY',
Notes => 'steps up, 1/16 mm per step',
ValueConv => '-$val',
ValueConvInv => '-$val',
},
7 => {
Name => 'CompositionAdjustRotation',
Notes => 'steps clockwise, 1/8 degree per step',
ValueConv => '-$val / 2',
ValueConvInv => '-$val * 2',
},
);
# white balance RGGB levels (ref 28)
%Image::ExifTool::Pentax::WBLevels = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# 0 - 11 (number of entries in this table)
# 1 - 0
2 => {
Name => 'WB_RGGBLevelsDaylight',
Format => 'int16u[4]',
},
# 10 - 1
11 => {
Name => 'WB_RGGBLevelsShade',
Format => 'int16u[4]',
},
# 19 - 2
20 => {
Name => 'WB_RGGBLevelsCloudy',
Format => 'int16u[4]',
},
# 28 - 3
29 => {
Name => 'WB_RGGBLevelsTungsten',
Format => 'int16u[4]',
},
# 37 - 4
38 => {
Name => 'WB_RGGBLevelsFluorescentD',
Format => 'int16u[4]',
},
# 46 - 5
47 => {
Name => 'WB_RGGBLevelsFluorescentN',
Format => 'int16u[4]',
},
# 55 - 6
56 => {
Name => 'WB_RGGBLevelsFluorescentW',
Format => 'int16u[4]',
},
# 64 - 7
65 => {
Name => 'WB_RGGBLevelsFlash',
Format => 'int16u[4]',
},
# 73 - 8
74 => {
Name => 'WB_RGGBLevelsFluorescentL',
Format => 'int16u[4]',
},
# 82 - 0xfe
83 => {
Name => 'WB_RGGBLevelsUnknown',
Format => 'int16u[4]',
Unknown => 1,
},
# 91 - 0xff
92 => {
Name => 'WB_RGGBLevelsUserSelected',
Format => 'int16u[4]',
},
);
# lens information for Penax Q (ref PH)
# (306 bytes long, I wonder if this contains vignetting information too?)
%Image::ExifTool::Pentax::LensInfoQ = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'More lens information stored by the Pentax Q.',
0x0c => {
Name => 'LensModel',
Format => 'string[30]',
},
0x2a => {
Name => 'LensInfo',
Format => 'string[20]',
ValueConv => '$val=~s/mm/mm /; $val',
ValueConvInv => '$val=~tr/ //d; $val',
}
);
# Pixel shift information for the K-3II (ref PH)
%Image::ExifTool::Pentax::PixelShiftInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => 'Pixel shift information stored by the K-3 II.',
0x00 => {
Name => 'PixelShiftResolution',
PrintConv => { 0 => 'Off', 1 => 'On' },
},
);
# temperature information for some models - PH
%Image::ExifTool::Pentax::TempInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => q{
A number of additional temperature readings are extracted from this 256-byte
binary-data block in images from models such as the K-01, K-3, K-5, K-50 and
K-500. It is currently not known where the corresponding temperature
sensors are located in the camera.
},
# (it would be nice to know where these temperature sensors are located,
# but since according to the manual the Slow Shutter Speed NR Auto mode
# is based on "internal temperature", my guess is that there must be
# at least one on the sensor itself. These temperatures seem to rise
# more quickly than CameraTemperature when shooting video.)
0x0c => {
Name => 'SensorTemperature', #forum6677 (was CameraTemperature2)
Format => 'int16s',
ValueConv => '$val / 10',
ValueConvInv => '$val * 10',
PrintConv => 'sprintf("%.1f C", $val)',
PrintConvInv => '$val=~s/ ?c$//i; $val',
},
0x0e => {
Name => 'SensorTemperature2', #forum6677 (was CameraTemperature3)
Format => 'int16s',
ValueConv => '$val / 10',
ValueConvInv => '$val * 10',
PrintConv => 'sprintf("%.1f C", $val)',
PrintConvInv => '$val=~s/ ?c$//i; $val',
},
0x14 => {
Name => 'CameraTemperature4',
Condition => '$$self{Model} =~ /K-5\b/',
Format => 'int16s',
PrintConv => '"$val C"',
PrintConvInv => '$val=~s/ ?c$//i; $val',
},
0x16 => { # usually the same as CameraTemperature4, but not always
Name => 'CameraTemperature5',
Condition => '$$self{Model} =~ /K-5\b/',
Format => 'int16s',
PrintConv => '"$val C"',
PrintConvInv => '$val=~s/ ?c$//i; $val',
},
# 0x18,0x1a,0x1c,0x1e = int16u[4] BlackPoint - PH
);
# currently unknown info
%Image::ExifTool::Pentax::UnknownInfo = (
%binaryDataAttrs,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# K10D: first 8 bytes seem to be short integers which change with ISO (value
# is usually close to ISO/100) possibly smoothing or gain parameters? - PH
# byte 0-1 - Higher for high color temperatures (red boost or red noise suppression?)
# byte 6-7 - Higher for low color temperatures (blue boost or blue noise suppression?)
# also changing are bytes 10,11,14,15
);
# Pentax type 2 (Casio-like) maker notes (ref 1)
%Image::ExifTool::Pentax::Type2 = (
WRITE_PROC => \&Image::ExifTool::Exif::WriteExif,
CHECK_PROC => \&Image::ExifTool::Exif::CheckExif,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
WRITABLE => 'int16u',
NOTES => q{
These tags are used by the Pentax Optio 330 and 430, and are similar to the
tags used by Casio.
},
0x0001 => {
Name => 'RecordingMode',
PrintConv => {
0 => 'Auto',
1 => 'Night Scene',
2 => 'Manual',
},
},
0x0002 => {
Name => 'Quality',
PrintConv => {
0 => 'Good',
1 => 'Better',
2 => 'Best',
},
},
0x0003 => {
Name => 'FocusMode',
PrintConv => {
2 => 'Custom',
3 => 'Auto',
},
},
0x0004 => {
Name => 'FlashMode',
PrintConv => {
1 => 'Auto',
2 => 'On',
4 => 'Off',
6 => 'Red-eye reduction',
},
},
# Casio 0x0005 is FlashIntensity
# Casio 0x0006 is ObjectDistance
0x0007 => {
Name => 'WhiteBalance',
PrintConv => {
0 => 'Auto',
1 => 'Daylight',
2 => 'Shade',
3 => 'Tungsten',
4 => 'Fluorescent',
5 => 'Manual',
},
},
0x000a => {
Name => 'DigitalZoom',
Writable => 'int32u',
},
0x000b => {
Name => 'Sharpness',
PrintConv => {
0 => 'Normal',
1 => 'Soft',
2 => 'Hard',
},
},
0x000c => {
Name => 'Contrast',
PrintConv => {
0 => 'Normal',
1 => 'Low',
2 => 'High',
},
},
0x000d => {
Name => 'Saturation',
PrintConv => {
0 => 'Normal',
1 => 'Low',
2 => 'High',
},
},
0x0014 => {
Name => 'ISO',
Priority => 0,
PrintConv => {
10 => 100,
16 => 200,
50 => 50, #PH
100 => 100, #PH
200 => 200, #PH
400 => 400, #PH
800 => 800, #PH
1600 => 1600, #PH
3200 => 3200, #PH
# seen 65534 for Q-S1 MOV video - PH
# seen 65535 for K-S1 MOV video - PH
},
},
0x0017 => {
Name => 'ColorFilter',
PrintConv => {
1 => 'Full',
2 => 'Black & White',
3 => 'Sepia',
},
},
# Casio 0x0018 is AFPoint
# Casio 0x0019 is FlashIntensity
0x0e00 => {
Name => 'PrintIM',
Description => 'Print Image Matching',
Writable => 0,
SubDirectory => {
TagTable => 'Image::ExifTool::PrintIM::Main',
},
},
0x1000 => {
Name => 'HometownCityCode',
Writable => 'undef',
Count => 4,
},
0x1001 => { #PH
Name => 'DestinationCityCode',
Writable => 'undef',
Count => 4,
},
);
# ASCII-based maker notes of Optio E20 and E25 - PH
%Image::ExifTool::Pentax::Type4 = (
PROCESS_PROC => \&Image::ExifTool::HP::ProcessHP,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
NOTES => q{
The following few tags are extracted from the wealth of information
available in maker notes of the Optio E20 and E25. These maker notes are
stored as ASCII text in a format very similar to some HP models.
},
'F/W Version' => 'FirmwareVersion',
);
# tags in Pentax QuickTime videos (PH - tests with Optio WP)
# (similar information in Kodak,Minolta,Nikon,Olympus,Pentax and Sanyo videos)
%Image::ExifTool::Pentax::MOV = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
FIRST_ENTRY => 0,
NOTES => 'This information is found in MOV videos from cameras such as the Optio WP.',
0x00 => {
Name => 'Make',
Format => 'string[24]',
},
# (01 00 at offset 0x20)
0x26 => {
Name => 'ExposureTime',
Format => 'int32u',
ValueConv => '$val ? 10 / $val : 0',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
},
0x2a => {
Name => 'FNumber',
Format => 'rational64u',
PrintConv => 'sprintf("%.1f",$val)',
},
0x32 => {
Name => 'ExposureCompensation',
Format => 'rational64s',
PrintConv => '$val ? sprintf("%+.1f", $val) : 0',
},
0x44 => {
Name => 'WhiteBalance',
Format => 'int16u',
PrintConv => {
0 => 'Auto',
1 => 'Daylight',
2 => 'Shade',
3 => 'Fluorescent', #2
4 => 'Tungsten',
5 => 'Manual',
},
},
0x48 => {
Name => 'FocalLength',
Format => 'rational64u',
PrintConv => 'sprintf("%.1f mm",$val)',
},
0xaf => {
Name => 'ISO',
Format => 'int16u',
},
);
# Pentax metadata in AVI videos (PH)
%Image::ExifTool::Pentax::AVI = (
NOTES => 'Pentax-specific RIFF tags found in AVI videos.',
GROUPS => { 0 => 'MakerNotes', 2 => 'Video' },
hymn => {
Name => 'MakerNotes',
SubDirectory => {
TagTable => 'Image::ExifTool::Pentax::Main',
Start => 10,
Base => '$start',
ByteOrder => 'BigEndian',
},
},
);
# Pentax metadata in S1 AVI maker notes (PH)
%Image::ExifTool::Pentax::S1 = (
NOTES => 'Tags extracted from the maker notes of AVI videos from the Optio S1.',
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
0x0000 => { #5
Name => 'MakerNoteVersion',
Writable => 'undef',
Count => 4,
},
);
# Pentax metadata in AVI videos from the RS1000 (PH)
%Image::ExifTool::Pentax::Junk = (
NOTES => 'Tags found in the JUNK chunk of AVI videos from the RS1000.',
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
0x0c => {
Name => 'Model',
Format => 'string[32]',
},
);
# PreviewImage information found in PXTH atom of K-01 MOV videos
%Image::ExifTool::Pentax::PXTH = (
NOTES => 'Tags found in the PXTH atom of MOV videos from the K-01.',
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
0x00 => {
Name => 'PreviewImageLength',
Format => 'int32u',
},
0x04 => {
Name => 'PreviewImage',
Groups => { 2 => 'Preview' },
Format => 'undef[$val{0}]',
Notes => '640-pixel-wide JPEG preview', # (360 pixels high, may depend on aspect ratio)
RawConv => '$self->ValidateImage(\$val,$tag)',
},
);
# information in PENT atom of MOV videos from the Optio WG-2 GPS
%Image::ExifTool::Pentax::PENT = (
NOTES => 'Tags found in the PENT atom of MOV videos from the Optio WG-2 GPS.',
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
0 => {
Name => 'Make',
Format => 'string[24]',
},
0x1a => {
Name => 'Model',
Description => 'Camera Model Name',
Format => 'string[24]',
},
0x38 => { # (NC)
Name => 'ExposureTime',
Format => 'int32u',
ValueConv => '$val ? 10 / $val : 0',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
},
0x3c => {
Name => 'FNumber',
Format => 'rational64u',
PrintConv => 'sprintf("%.1f",$val)',
},
0x44 => { # (NC)
Name => 'ExposureCompensation',
Format => 'rational64s',
PrintConv => '$val ? sprintf("%+.1f", $val) : 0',
},
0x54 => { # (NC)
Name => 'FocalLength',
Format => 'int32u',
PrintConv => '"$val mm"',
},
0x71 => {
Name => 'DateTime1',
Format => 'string[24]',
Groups => { 2 => 'Time' },
},
0x8b => {
Name => 'DateTime2',
Format => 'string[24]',
Groups => { 2 => 'Time' },
},
0xa7 => { # (NC)
Name => 'ISO',
Format => 'int32u',
},
0xc7 => {
Name => 'GPSVersionID',
Format => 'undef[8]',
Groups => { 1 => 'GPS', 2 => 'Location' },
DataMember => 'GPSVersionID',
RawConv => '$$self{GPSVersionID} = ($val=~s/GPS_// ? join(" ",unpack("C*",$val)) : undef)',
PrintConv => '$val =~ tr/ /./; $val',
},
0xcf => {
Name => 'GPSLatitudeRef',
Condition => '$$self{GPSVersionID} and require Image::ExifTool::GPS',
Format => 'string[2]',
Groups => { 1 => 'GPS', 2 => 'Location' },
PrintConv => {
N => 'North',
S => 'South',
},
},
0xd1 => {
Name => 'GPSLatitude',
Condition => '$$self{GPSVersionID}',
Format => 'rational64u[3]',
Groups => { 1 => 'GPS', 2 => 'Location' },
ValueConv => 'Image::ExifTool::GPS::ToDegrees($val)',
PrintConv => 'Image::ExifTool::GPS::ToDMS($self, $val, 1)',
},
0xe9 => {
Name => 'GPSLongitudeRef',
Condition => '$$self{GPSVersionID}',
Format => 'string[2]',
Groups => { 1 => 'GPS', 2 => 'Location' },
PrintConv => {
E => 'East',
W => 'West',
},
},
0xeb => {
Name => 'GPSLongitude',
Condition => '$$self{GPSVersionID}',
Format => 'rational64u[3]',
Groups => { 1 => 'GPS', 2 => 'Location' },
ValueConv => 'Image::ExifTool::GPS::ToDegrees($val)',
PrintConv => 'Image::ExifTool::GPS::ToDMS($self, $val, 1)',
},
0x103 => {
Name => 'GPSAltitudeRef',
Condition => '$$self{GPSVersionID}',
Format => 'int8u',
Groups => { 1 => 'GPS', 2 => 'Location' },
PrintConv => {
0 => 'Above Sea Level',
1 => 'Below Sea Level',
},
},
0x104 => {
Name => 'GPSAltitude',
Condition => '$$self{GPSVersionID}',
Format => 'rational64u',
Groups => { 1 => 'GPS', 2 => 'Location' },
PrintConv => '$val =~ /^(inf|undef)$/ ? $val : "$val m"',
},
0x11c => {
Name => 'GPSTimeStamp',
Condition => '$$self{GPSVersionID}',
Groups => { 1 => 'GPS', 2 => 'Time' },
Format => 'rational64u[3]',
ValueConv => 'Image::ExifTool::GPS::ConvertTimeStamp($val)',
PrintConv => 'Image::ExifTool::GPS::PrintTimeStamp($val)',
},
0x134 => {
Name => 'GPSSatellites',
Condition => '$$self{GPSVersionID}',
Format => 'string[3]',
Groups => { 1 => 'GPS', 2 => 'Location' },
},
0x137 => {
Name => 'GPSStatus',
Condition => '$$self{GPSVersionID}',
Format => 'string[2]',
Groups => { 1 => 'GPS', 2 => 'Location' },
PrintConv => {
A => 'Measurement Active',
V => 'Measurement Void',
},
},
0x139 => {
Name => 'GPSMeasureMode',
Condition => '$$self{GPSVersionID}',
Format => 'string[2]',
Groups => { 1 => 'GPS', 2 => 'Location' },
PrintConv => {
2 => '2-Dimensional Measurement',
3 => '3-Dimensional Measurement',
},
},
0x13b => {
Name => 'GPSMapDatum',
Condition => '$$self{GPSVersionID}',
Format => 'string[7]',
Groups => { 1 => 'GPS', 2 => 'Location' },
},
0x142 => {
Name => 'GPSDateStamp',
Condition => '$$self{GPSVersionID}',
Groups => { 1 => 'GPS', 2 => 'Time' },
Format => 'string[11]',
ValueConv => 'Image::ExifTool::Exif::ExifDate($val)',
},
0x173 => { # (NC)
Name => 'AudioCodecID',
Format => 'string[4]',
},
0x7d3 => {
Name => 'PreviewImage',
Groups => { 2 => 'Preview' },
Format => 'undef[$size-0x7d3]',
Notes => '640x480 JPEG preview image', # (black borders pad to 480 pixels high)
RawConv => '$self->ValidateImage(\$val,$tag)',
},
);
# tags in Pentax Optio RZ18 AVI videos (ref PH)
# (very similar to Olympus::AVI tags)
%Image::ExifTool::Pentax::Junk2 = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
FIRST_ENTRY => 0,
NOTES => 'This information is found in AVI videos from the Optio RZ18.',
0x12 => {
Name => 'Make',
Format => 'string[24]',
},
0x2c => {
Name => 'Model',
Description => 'Camera Model Name',
Format => 'string[24]',
},
0x5e => {
Name => 'FNumber',
Format => 'rational64u',
PrintConv => 'sprintf("%.1f",$val)',
},
0x83 => {
Name => 'DateTime1',
Format => 'string[24]',
Groups => { 2 => 'Time' },
},
0x9d => {
Name => 'DateTime2',
Format => 'string[24]',
Groups => { 2 => 'Time' },
},
0x12b => {
Name => 'ThumbnailWidth',
Format => 'int16u',
},
0x12d => {
Name => 'ThumbnailHeight',
Format => 'int16u',
},
0x12f => {
Name => 'ThumbnailLength',
Format => 'int32u',
},
0x133 => {
Name => 'ThumbnailImage',
Groups => { 2 => 'Preview' },
Format => 'undef[$val{0x12f}]',
Notes => '160x120 JPEG thumbnail image',
RawConv => '$self->ValidateImage(\$val,$tag)',
},
);
#------------------------------------------------------------------------------
# Convert filter settings (ref PH, K-5)
# Inputs: 0) value to convert, 1) flag for inverse conversion, 2) lookup table
# Returns: converted value
sub PrintFilter($$$)
{
my ($val, $inv, $conv) = @_;
my (@vals, @cval, $t, $v);
if (not $inv) {
# forward conversion (reading):
@vals = split ' ',$val;
$t = shift @vals;
push @cval, $$conv{$t} || "Unknown ($t)";
while (@vals) {
$t = shift @vals;
$v = shift @vals;
next unless $t;
last unless defined $v;
my $c = $filterSettings{$t};
if ($c) {
my $c1 = $$c[1];
if (ref $c1) {
$v = $$c1{$v} || "Unknown($v)";
} elsif ($v) {
$v = sprintf $c1, $v;
}
push @cval, "$$c[0]=$v";
} else {
push @cval, "Unknown($t)=$v";
}
}
return @cval ? \@cval : undef;
} else {
# reverse conversion (writing):
@vals = split /,\s*/, $val;
# convert filter name
delete $$conv{OTHER}; # avoid recursion
$v = Image::ExifTool::ReverseLookup(shift(@vals), $conv);
$$conv{OTHER} = \&PrintFilter;
return undef unless defined $v;
push @cval, $v;
# generate a lookup table for the filter setting name
my %settingNames;
$settingNames{$_} = $filterSettings{$_}[0] foreach keys %filterSettings;
# convert filter settings
foreach $v (@vals) {
$v =~ /^(.*)=(.*)$/ or return undef;
($t, $v) = ($1, $2);
# look up settings name
$t = Image::ExifTool::ReverseLookup($t, \%settingNames);
return undef unless defined $t;
if (ref $filterSettings{$t}[1]) {
# look up settings value
$v = Image::ExifTool::ReverseLookup($v, $filterSettings{$t}[1]);
return undef unless defined $v;
} else {
return undef unless Image::ExifTool::IsInt($v);
}
push @cval, $t, $v;
}
push @cval, (0) x (17 - @cval) if @cval < 17; # pad with zeros if necessary
return join(' ', @cval);
}
}
#------------------------------------------------------------------------------
# Convert Pentax hex-based EV (modulo 8) to real number
# Inputs: 0) value to convert
# eg) 0x00 -> 0
# 0x03 -> 0.33333
# 0x04 -> 0.5
# 0x05 -> 0.66666
# 0x08 -> 1 ... etc
sub PentaxEv($)
{
my $val = shift;
if ($val & 0x01) {
my $sign = $val < 0 ? -1 : 1;
my $frac = ($val * $sign) & 0x07;
if ($frac == 0x03) {
$val += $sign * ( 8 / 3 - $frac);
} elsif ($frac == 0x05) {
$val += $sign * (16 / 3 - $frac);
}
}
return $val / 8;
}
#------------------------------------------------------------------------------
# Convert number to Pentax hex-based EV (modulo 8)
# Inputs: 0) number
# Returns: Pentax EV code
sub PentaxEvInv($)
{
my $num = shift;
my $val = $num * 8;
# extra fudging makes sure 0.3 and 0.33333 both round up to 3, etc
my $sign = $num < 0 ? -1 : 1;
my $inum = $num * $sign - int($num * $sign);
if ($inum > 0.29 and $inum < 0.4) {
$val += $sign / 3;
} elsif ($inum > 0.6 and $inum < .71) {
$val -= $sign / 3;
}
return int($val + 0.5 * $sign);
}
#------------------------------------------------------------------------------
# Encrypt or decrypt Pentax ShutterCount (symmetrical encryption) - PH
# Inputs: 0) shutter count value, 1) ExifTool object ref
# Returns: Encrypted or decrypted ShutterCount
sub CryptShutterCount($$)
{
my ($val, $et) = @_;
# Pentax Date and Time values are used in the encryption
return undef unless $$et{PentaxDate} and $$et{PentaxTime} and
length($$et{PentaxDate})==4 and length($$et{PentaxTime})>=3;
# get Date and Time as integers (after padding Time with a null byte)
my $date = unpack('N', $$et{PentaxDate});
my $time = unpack('N', $$et{PentaxTime} . "\0");
return $val ^ $date ^ (0xffffffff - $time);
}
1; # end
__END__
=head1 NAME
Image::ExifTool::Pentax - Pentax/Asahi maker notes tags
=head1 SYNOPSIS
This module is loaded automatically by Image::ExifTool when required.
=head1 DESCRIPTION
This module contains definitions required by Image::ExifTool to interpret
Pentax and Asahi maker notes in EXIF information.
=head1 NOTES
I couldn't find a good source for Pentax maker notes information, but I've
managed to discover a fair bit of information by analyzing sample images
downloaded from the internet, and through tests with my own Optio WP,
K10D, and K-5, and with help provided by other ExifTool users (see
L</ACKNOWLEDGEMENTS>).
The Pentax maker notes are stored in standard EXIF format, but the offsets
used for some of their cameras are wacky. The Optio 330 gives the offset
relative to the offset of the tag in the directory, the Optio WP uses a base
offset in the middle of nowhere, and the Optio 550 uses different (and
totally illogical) bases for different menu entries. Very weird. (It
wouldn't surprise me if Pentax can't read their own maker notes!) Luckily,
there are only a few entries in the maker notes which are large enough to
require offsets, so this doesn't affect much useful information. ExifTool
attempts to make sense of this fiasco by making an assumption about where
the information should be stored to deduce the correct offsets.
=head1 REFERENCES
=over 4
=item L<Image::MakerNotes::Pentax|Image::MakerNotes::Pentax>
=item L<http://johnst.org/sw/exiftags/> (Asahi models)
=item L<http://kobe1995.jp/~kaz/astro/istD.html>
=item L<http://www.cybercom.net/~dcoffin/dcraw/>
=item (...plus lots of testing with my Optio WP, K10D and K-5!)
=back
=head1 ACKNOWLEDGEMENTS
Thanks to Wayne Smith, John Francis, Douglas O'Brien Cvetan Ivanov, Jens
Duttke and Dave Nicholson for help figuring out some Pentax tags, Ger
Vermeulen and Niels Kristian Bech Jensen for contributing print conversion
values for some tags, and everyone who helped contribute to the LensType
values.
=head1 AUTHOR
Copyright 2003-2016, 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 SEE ALSO
L<Image::ExifTool::TagNames/Pentax Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>,
L<Image::Info(3pm)|Image::Info>
=cut
| rizzles/convert | imageprocessor/processorcommand/lib/Image/ExifTool/Pentax.pm | Perl | mit | 211,867 |
#!/usr/bin/perl
$_=lc<>;s/(^|(?<= ))(\S)/uc$2/eg;print
| Lyapunov/coding_game | pearls/mini_perl_5.pl | Perl | mit | 55 |
#!/usr/bin/perl -w
######################################
#
# this script take a BAM file as input and outputs the locus_ID,chr,coord,strand,count,seq_context
#
# parameters include
# MQ mapping quality
# readlength
# fastalen number of nuceltodie context to display
# reference genome fasta file
#
# dependencies include:
# samtools
# bedtools
#
#
#########################################
use strict;
use File::Basename;
# set parameters
my $MQ=10 ; #read miminal mapping quality
my $readlength=50;
my $fastalen=4; #number of nucleotides to grab on eitherside of the last read nculeotide. The total length will be therefore 2*fastlen+1
my $ref="/mnt/idash/Genomics/data_resources/references-and-indexes/hg19/hg19.fa";
my $name=basename($ARGV[0],".bam");
# declare variables
my ($start,$end,$strand);
my ($chr,$coord,$flag,$cnt);
my $bed;
my $fasta;
#########################################
#
# Get help
#
#########################################
if( $ARGV[0] eq '-h' || $ARGV[0] eq '-help')
{
print "USAGE: pipeduct_count.pl [file.bam] \n";
exit;
}
#########################################
#
# count reads per locus
#
#########################################
open (my $rawcount, "samtools view $ARGV[0] | awk '\$5>$MQ' | cut -f 2,3,4 | sort | uniq -c | awk '{print \$3,\$4,\$2,\$1}' | sed 's/ /\t/g' |");
open OUT1, ">$name.cnt";
#open OUT2, ">$name.fa";
#########################################
#
# extract sequence context
#
#########################################
while (<$rawcount>){
chomp;
($chr,$coord,$flag,$cnt)=split;
if ($flag==0){
$start=$coord-$fastalen-1;
$end=$coord+$fastalen;
$strand="+";
}
else {
$start=$coord+$readlength-2-$fastalen;
$end=$coord+$readlength-1+$fastalen;
$strand="-";
}
$bed=$chr."\t".$start."\t".$end."\t"."strand\t1\t".$strand;
$fasta=`echo $bed | sed 's/ /\t/g' | bedtools getfasta -name -s -fi $ref -bed - -fo stdout | tail -n 1`;
$fasta=uc($fasta);
#########################################
#
# print out results
#
#########################################
chomp($fasta);
print OUT1 "$chr:$coord:$strand\t$chr\t$coord\t$strand\t$cnt\t$fasta\n";
#print OUT2 ">$chr:$coord:$strand\n$fasta\n";
}
close OUT1;
#close OUT2;
| oharismendy/TDTSEQ | pipeduct_count.pl | Perl | mit | 2,189 |
{
=head1 NAME
Net::Blogger::Engine::Userland::metaWeblog - UserLand metaWeblog API engine
=head1 SYNOPSIS
my $radio = Blogger->new(engine=>"radio");
$radio->Proxy(PROXY);
$radio->Username(USERNAME);
$radio->Password(PASSWORD);
$radio->metaWeblog()->newPost(
title=>"hello",
description=>"world",
publish=>1,
);
=head1 DESCRIPTION
Implements the UserLand metaWeblog API functionality.
This package is meant to be subclassed. It should not be used on it's own.
=cut
package Net::Blogger::Engine::Userland::metaWeblog;
use strict;
$Net::Blogger::Engine::Userland::metaWeblog::VERSION = '1.0';
@Net::Blogger::Engine::Userland::metaWeblog::ISA = qw ( Exporter Net::Blogger::Engine::Base );
@Net::Blogger::Engine::Userland::metaWeblog::EXPORT = qw ();
@Net::Blogger::Engine::Userland::metaWeblog::EXPORT_OK = qw ();
use Exporter;
use Net::Blogger::Engine::Base;
=head1 OBJECTS METHODS
=head2 $pkg->newPost(\%args)
Valid arguments are :
=over 4
=item *
B<title>
String.
=item *
B<link>
=item *
B<description>
String.
=item *
B<categories>
Array reference.
=item *
B<publish>
Boolean.
=back
Releases prior to Net::Blogger 0.85 accepted a list of arguments
rather than a reference. Version 0.85+ are backwards compatible.
Returns an int, or false.
=head2 $pkg->getRecentPosts(\%args)
Returns the most recent posts
Valid arguments are:
=over
=item numberOfPosts
The maximum number of posts to return
=back
=cut
sub getRecentPosts {
my $self = shift;
my $args = (ref($_[0]) eq "HASH") ? shift : {@_};
my $call = $self->_Client()->call(
"metaWeblog.getRecentPosts",
$self->_Type(string=>$self->BlogId()),
$self->_Type(string=>$self->Username()),
$self->_Type(string=>$self->Password()),
$self->_Type(int=>$args->{'numberOfPosts'}),
);
my @posts = ($call) ? (1,@{$call->result()}) : (0,undef);
return @posts;
};
sub newPost {
my $self = shift;
my $args = (ref($_[0]) eq "HASH") ? shift : {@_};
my $publish = 0;
if (exists $args->{publish}) {
$publish = $args->{publish};
delete $args->{publish};
}
if (($args->{categories}) && (ref($args->{categories}) ne "ARRAY")) {
$self->LastError("Categories must be passed as an array reference.");
return 0;
}
my $call = $self->_Client->call(
"metaWeblog.newPost",
$self->_Type(string=>$self->BlogId()),
$self->_Type(string=>$self->Username()),
$self->_Type(string=>$self->Password()),
$self->_Type(hash=>$args),
$self->_Type(boolean=>$publish),
);
return ($call) ? $call->result() : return 0;
}
=head2 $pkg->newMediaObject(\%args)
Valid argument are :
=over
=item *
B<file>
String. Path to the file you're trying to upload.
If this argument is present the package will try to load I<MIME::Base64>
for automagic encoding.
=item *
B<name>
String. "It may be used to determine the name of the file that stores the object,
or to display it in a list of objects. It determines how the weblog refers to
the object. If the name is the same as an existing object stored in the weblog,
it replaces the existing object." [1]
If a I<file> argument is present and no I<name> argument is defined, this property
will be defined using the I<File::Basename::basename> function.
=item *
B<type>
String. "It indicates the type of the object, it's a standard MIME type,
like audio/mpeg or image/jpeg or video/quicktime." [1]
If a I<file> argument is present and no I<type> argument is defined, the package
will try setting this property using the I<File::MMagic> package.
=item *
B<bits>
Base64-encoded binary value. The content of the object.
If a I<file> argument is present, the package will try setting this property
using the I<MIME::Base64> package.
=back
Releases prior to Net::Blogger 0.85 accepted a list of arguments
rather than a reference. Version 0.85+ are backwards compatible.
Returns a hash reference, or undef.
=cut
sub newMediaObject {
my $self = shift;
my $args = (ref($_[0]) eq "HASH") ? shift : {@_};
#
if ($args->{file}) {
my $pkg = "MIME::Base64";
eval "require $pkg";
if ($@) {
$self->LastError("Failed to load $pkg for automagic encoding, $@");
return undef;
}
open(FILE, $args->{file}) or &{
$self->LastError("Failed to open $args->{file} for reading, $!");
return undef;
};
my $buf = undef;
while (read(FILE, $buf, 60*57)) {
$args->{bits} .= &{$pkg."::encode_base64"}($buf);
}
close FILE;
#
if (! $args->{type}) {
eval "require $pkg";
if ($@) {
$self->LastError("Failed to load $pkg for automagic type checking $@");
return undef;
}
#
my $mm = undef;
eval { $mm = $pkg->new(); };
if ($@) {
$self->LastError("Failed to instantiate $pkg for automagic type checking, $@");
return undef;
}
$args->{type} = $mm->checktype_filename($args->{file});
if (! $args->{type}) {
$self->LastError("Unable to determine file type ");
}
}
#
if (! $args->{name}) {
require "File::Basename";
$args->{name} = File::Basename::basename($args->{file});
}
}
#
else {
foreach ("name","type","bin") {
if (! $args->{$_}) {
$self->LastError("You must define a value for the $_ property.");
return undef;
}
}
}
#
my $call = $self->_Client->call(
"metaWeblog.newMediaObject",
$self->_Type(string=>$self->BlogId()),
$self->_Type(string=>$self->Username()),
$self->_Type(string=>$self->Password()),
$self->_Type(hash=>$args),
);
return ($call) ? $call->result() : undef;
}
=head2 $pkg->editPost(\%args)
=over 4
=item *
B<postid>
Int. I<required>
=item *
B<title>
String.
=item *
B<link>
=item *
B<description>
String.
=item *
B<categories>
Array reference.
=item *
B<publish>
Boolean.
=back
Releases prior to Net::Blogger 0.85 accepted a list of arguments
rather than a reference. Version 0.85+ are backwards compatible.
Returns true or false.
=cut
sub editPost {
my $self = shift;
my $args = (ref($_[0]) eq "HASH") ? shift : {@_};
my $postid = $args->{postid};
if (! $postid) {
$self->LastError("You must specify a postid");
return 0;
}
delete $args->{postid};
if (($args->{categories}) && (ref($args->{categories}) ne "ARRAY")) {
$self->LastError("Categories must be passed as an array reference.");
return 0;
}
my $publish = 0;
if (exists $args->{publish}) {
$publish = $args->{publish};
delete $args->{publish};
}
my $call = $self->_Client->call(
"metaWeblog.editPost",
$postid,
$self->_Type(string=>$self->Username()),
$self->_Type(string=>$self->Password()),
$self->_Type(hash=>$args),
$self->_Type(boolean=>$publish),
);
return ($call) ? $call->result() : undef;
}
=head2 $pkg->getPost(\%args)
Valid arguments are :
=over 4
=item *
B<postid>
Int. I<required>
=back
Releases prior to Net::Blogger 0.85 accepted a list of arguments
rather than a reference. Version 0.85+ are backwards compatible.
Returns a hash reference or undef.
=cut
sub getPost {
my $self = shift;
my $args = (ref($_[0]) eq "HASH") ? shift : {@_};
my $postid = $args->{postid};
if (! $postid) {
$self->LastError("You must specify a postid");
return 0;
}
my $call = $self->_Client->call(
"metaWeblog.getPost",
$postid,
$self->_Type(string=>$self->Username()),
$self->_Type(string=>$self->Password()),
);
return ($call) ? $call->result() : undef;
}
=head2 $pkg->getCategories()
Returns an array reference or undef.
=cut
sub getCategories {
my $self = shift;
if ($self->{'__parent'} eq "Movabletype") {
$self->LastError("This method is not supported by the $self->{'__parent'} engine.");
return undef;
}
my $call = $self->_Client()->call(
"metaWeblog.getCategories",
$self->_Type(string=>$self->BlogId()),
$self->_Type(string=>$self->Username()),
$self->_Type(string=>$self->Password()),
);
return ($call) ? $call->result() : undef;
}
=head1 VERSION
1.0
=head1 DATE
$Date: 2005/03/26 19:29:08 $
=head1 AUTHOR
Aaron Straup Cope
=head1 SEE ALSO
http://www.xmlrpc.com/metaWeblogApi
http://groups.yahoo.com/group/weblog-devel/message/200
=head1 FOOTNOTES
=over
=item [1]
http://www.xmlrpc.com/discuss/msgReader$2393
=back
=head1 LICENSE
Copyright (c) 2002-2005 Aaron Straup Cope. All Rights Reserved.
This is free software, you may use it and distribute it under the
same terms as Perl itself.
=cut
return 1;
}
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/Net/Blogger/Engine/Userland/metaWeblog.pm | Perl | mit | 9,193 |
end_of_file.
% @TODO unbreak
:- expects_dialect(lps).
/* Example from Accord Project:
https://docs.google.com/document/d/1UacA_r2KGcBA2D4voDgGE8jqid-Uh4Dt09AE-shBKR0/edit#
https://www.accordproject.org/
* "Late Delivery and Penalty. In case of delayed delivery
* [{" except for Force Majeure cases,":? forceMajeure}]
* the Seller shall pay to the Buyer for every
* [{penaltyDuration}] of delay penalty amounting to
* [{penaltyPercentage}]% of the total value of the Equipment whose delivery has been delayed.
* Any fractional part of a [{fractionalPart}] is to be considered a full [{fractionalPart}].
* The total amount of penalty shall not however,
* exceed [{capPercentage}]% of the total value of the Equipment involved in late delivery.
* If the delay is more than [{termination}], the Buyer is entitled to terminate this Contract."
*/
% System predicates defining simulation of real time:
:- include(system('date_utils.pl')).
simulatedRealTimeBeginning('2018-04-01').
simulatedRealTimePerCycle(21600). % Each cycle = 21600 seconds = 1/4th of a day.
maxTime(32). % 32 cycles = 8 days.
fluents day/1, penalty/2, delivered/1, force_majeure/1, terminated/1.
events deliver/1.
deliver(Order) initiates delivered(Order).
% For simplicity, the penaltyDuration is assumed to be one day,
% and fractionalPart is assumed to be a fractional part of one day.
%
initially penalty(mydelivery, 0.0).
% Example late delivery.
%
seller(mydelivery, bob).
buyer(mydelivery, alex).
equipment(mydelivery,logicforproblemsolving).
latest_delivery(mydelivery, 2018/4/1).
total_value(mydelivery, 100).
penalty_percentage(mydelivery, 0.20).
percentage_cap(mydelivery, 0.50).
observe deliver(mydelivery) at'2018-04-04T15:00'. % at 15:00.
% you can change the date, and see what happens.
end_of_day(Date2) updates Old to New in penalty(Order, Old) if
latest_delivery(Order, Date1),
not delivered(Order),
real_date_add(Date1,Delay,Date2),
not force_majeure(_),
not terminated(Order),
total_value(Order, Value),
penalty_percentage(Order, PenaltyPercent),
percentage_cap(Order, CapPercent),
New is PenaltyPercent*Value*(Delay+1),
Cap is CapPercent*Value,
New =< Cap.
% If the delay is more than 10 weeks then
% the Buyer is entitled to terminate this Contract.
% Additional rules/clauses are needed to terminate the order if the buyer is entitled to do so
% and the buyer decides to exercise the option.
%
entitled(terminate(Person, Order)) at T if
buyer(Order, Person),
latest_delivery(Order, Date1),
not(delivered(Order)) at T,
Date1 @=< Date2.
/** <examples>
?- go(Timeline).
*/
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_ec/test/lps_user_examples/deliveryDelay.pl | Perl | mit | 2,649 |
#!/usr/bin/env perl
require 5.12.0;
use strict;
use warnings;
use Data::Dumper;
use Getopt::Long;
use Bio::Perl;
use File::Basename;
use File::Temp qw/tempdir/;
use List::Util qw/min max sum/;
use FindBin;
use lib "$FindBin::RealBin/../lib";
use LyveSET qw/logmsg/;
use lib "$FindBin::RealBin/../lib/lib/perl5";
use Number::Range;
use constant reportEvery=>100000;
$0=fileparse $0;
exit main();
sub main{
my $settings={};
GetOptions($settings,qw(help tempdir=s density-window|window=i density-filter=i)) or die $!;
die usage() if($$settings{help});
$$settings{tempdir}||=tempdir("$0XXXXXX",TMPDIR=>1,CLEANUP=>1);
# Ensure that the density filter and density window are >= 1
if(!$$settings{'density-filter'} || $$settings{'density-filter'} < 1){
$$settings{'density-filter'}=1;
}
if(!$$settings{'density-window'} || $$settings{'density-window'} < 1){
$$settings{'density-window'}=1;
}
my($in)=@ARGV;
$in or die "ERROR: need input file\n".usage();
if(!-e $in){
die "ERROR: could not find input file $in";
}
my $sites = sitesToInclude($in,$settings);
if(-s $sites == 0){
die "ERROR: all sites are excluded using the density filter of ".$$settings{'density-filter'}." in a window size ".$$settings{'density-window'};
}
system("bcftools filter -R $sites '$in'"); die if $?;
return 0;
}
sub sitesToInclude{
my($vcf,$settings)=@_;
# Open the vcf
open(my $fp,"zcat $vcf | ") or die "ERROR: could not zcat $vcf: $!";
<$fp>; # skip the header
# save all positions in a hash of arrays
my %pos;
while(my $vcfLine=<$fp>){
next if($vcfLine=~/^#/);
# Save the positional information
my($seq,$pos)=split(/\t/,$vcfLine);
push(@{$pos{$seq}}, $pos);
}
close $fp;
# run filtering on each array and mark positions
my $includedSites="$$settings{tempdir}/regions.tsv";
open(my $includedSitesFh, ">", $includedSites) or die "ERROR writing to $includedSites: $!";
while(my($seq,$posArr) = each(%pos)){
my $filteredPos = densityFilter($posArr,$$settings{'density-filter'},$$settings{'density-window'},$settings);
for my $pos(@$filteredPos){
print $includedSitesFh join("\t",$seq,$pos)."\n";
}
}
close $includedSitesFh;
return $includedSites;
}
# For an array of positions, run the density filter
sub densityFilter{
my($posArr,$densityFilter,$densityWindow, $settings)=@_;
# We will return filtered sites
my @filtered;
my @pos = sort {$a <=> $b} @$posArr;
my $numPos=@pos;
my $windowStartIndex=0;
my $lastPos=$numPos - $densityFilter; # To capture the max value in the for loop
for(my $i=0;$i<$lastPos;$i++){
# Advance ahead the number of sites allowed in the window.
# Is the window size greater than the density-filter-window?
my $maxBound=$pos[$i+$densityFilter - 1];
my $minBound=$pos[$i];
my $window=$maxBound - $minBound;
if($window >= $densityWindow){
push(@filtered,$pos[$i]);
}
}
# Capture the last X sites if they are not within the window size
my $maxBound=$pos[$numPos-1];
my $minBound=$pos[$numPos - $densityFilter - 1];
my $window = $maxBound - $minBound;
if($window >= $densityWindow){
for(my $i=$numPos - $densityFilter;$i<$numPos;$i++){
push(@filtered,$pos[$i]);
}
}
# Sort/unique all positions just in case the two loops
# are overlapping.
@filtered = uniq(@filtered);
@filtered = sort {$a <=> $b} @filtered;
return \@filtered;
}
sub uniq {
my %seen;
return grep { !$seen{$_}++ } @_;
}
sub usage{
"$0: filters a vcf file so that no window has too many sites.
The first three columns of the matrix are contig/pos/ref, and the next columns are all GT.
A site will get filtered if it is upstream a set of sites within
a given window size. That window size is inclusive of start/stop
positions. For example if the window size is 10 and the filter
density is 2, then there cannot be more than 2 sites between
positions 1 and 10. This includes positions 1 and 10.
Usage:
$0 snps.vcf.gz > filtered.vcf
Default is to not filter.
--density-filter 1 Number of sites allowed per window
--density-window 1 Size of the window
"
}
| lskatz/lyve-SET | scripts/densityFilterVcf.pl | Perl | mit | 4,213 |
#!/usr/bin/env perl
#
# Decode IMAP UTF-7 string
#
# VERSION :0.1.0
# DATE :2015-08-01
# AUTHOR :Viktor Szépe <viktor@szepe.net>
# URL :https://github.com/szepeviktor/debian-server-tools
# LICENSE :The MIT License (MIT)
# DEPENDS :apt-get install libencode-imaputf7-perl
# REFS :http://search.cpan.org/~pmakholm/Encode-IMAPUTF7-1.05/
# LOCATION :/usr/local/bin/decode-imap-utf7.pl
use Encode::IMAPUTF7;
use Encode qw/encode decode/;
print decode( 'IMAP-UTF-7', $ARGV[0] );
# apt-get install php5-imap -> imap_utf7_decode()
| djeraseit/debian-server-tools | mail/decode-imap-utf7.pl | Perl | mit | 585 |
=pod
=head1 NAME
UI_new, UI_new_method, UI_free, UI_add_input_string, UI_dup_input_string,
UI_add_verify_string, UI_dup_verify_string, UI_add_input_boolean,
UI_dup_input_boolean, UI_add_info_string, UI_dup_info_string,
UI_add_error_string, UI_dup_error_string, UI_construct_prompt,
UI_add_user_data, UI_get0_user_data, UI_get0_result, UI_process,
UI_ctrl, UI_set_default_method, UI_get_default_method, UI_get_method,
UI_set_method, UI_OpenSSL, ERR_load_UI_strings - New User Interface
=head1 SYNOPSIS
#include <openssl/ui.h>
typedef struct ui_st UI;
typedef struct ui_method_st UI_METHOD;
UI *UI_new(void);
UI *UI_new_method(const UI_METHOD *method);
void UI_free(UI *ui);
int UI_add_input_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize);
int UI_dup_input_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize);
int UI_add_verify_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize, const char *test_buf);
int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
char *result_buf, int minsize, int maxsize, const char *test_buf);
int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
const char *ok_chars, const char *cancel_chars,
int flags, char *result_buf);
int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
const char *ok_chars, const char *cancel_chars,
int flags, char *result_buf);
int UI_add_info_string(UI *ui, const char *text);
int UI_dup_info_string(UI *ui, const char *text);
int UI_add_error_string(UI *ui, const char *text);
int UI_dup_error_string(UI *ui, const char *text);
/* These are the possible flags. They can be or'ed together. */
#define UI_INPUT_FLAG_ECHO 0x01
#define UI_INPUT_FLAG_DEFAULT_PWD 0x02
char *UI_construct_prompt(UI *ui_method,
const char *object_desc, const char *object_name);
void *UI_add_user_data(UI *ui, void *user_data);
void *UI_get0_user_data(UI *ui);
const char *UI_get0_result(UI *ui, int i);
int UI_process(UI *ui);
int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f)());
#define UI_CTRL_PRINT_ERRORS 1
#define UI_CTRL_IS_REDOABLE 2
void UI_set_default_method(const UI_METHOD *meth);
const UI_METHOD *UI_get_default_method(void);
const UI_METHOD *UI_get_method(UI *ui);
const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth);
UI_METHOD *UI_OpenSSL(void);
=head1 DESCRIPTION
UI stands for User Interface, and is general purpose set of routines to
prompt the user for text-based information. Through user-written methods
(see L<ui_create(3)>), prompting can be done in any way
imaginable, be it plain text prompting, through dialog boxes or from a
cell phone.
All the functions work through a context of the type UI. This context
contains all the information needed to prompt correctly as well as a
reference to a UI_METHOD, which is an ordered vector of functions that
carry out the actual prompting.
The first thing to do is to create a UI with UI_new() or UI_new_method(),
then add information to it with the UI_add or UI_dup functions. Also,
user-defined random data can be passed down to the underlying method
through calls to UI_add_user_data. The default UI method doesn't care
about these data, but other methods might. Finally, use UI_process()
to actually perform the prompting and UI_get0_result() to find the result
to the prompt.
A UI can contain more than one prompt, which are performed in the given
sequence. Each prompt gets an index number which is returned by the
UI_add and UI_dup functions, and has to be used to get the corresponding
result with UI_get0_result().
The functions are as follows:
UI_new() creates a new UI using the default UI method. When done with
this UI, it should be freed using UI_free().
UI_new_method() creates a new UI using the given UI method. When done with
this UI, it should be freed using UI_free().
UI_OpenSSL() returns the built-in UI method (note: not the default one,
since the default can be changed. See further on). This method is the
most machine/OS dependent part of OpenSSL and normally generates the
most problems when porting.
UI_free() removes a UI from memory, along with all other pieces of memory
that's connected to it, like duplicated input strings, results and others.
If B<ui> is NULL nothing is done.
UI_add_input_string() and UI_add_verify_string() add a prompt to the UI,
as well as flags and a result buffer and the desired minimum and maximum
sizes of the result. The given information is used to prompt for
information, for example a password, and to verify a password (i.e. having
the user enter it twice and check that the same string was entered twice).
UI_add_verify_string() takes and extra argument that should be a pointer
to the result buffer of the input string that it's supposed to verify, or
verification will fail.
UI_add_input_boolean() adds a prompt to the UI that's supposed to be answered
in a boolean way, with a single character for yes and a different character
for no. A set of characters that can be used to cancel the prompt is given
as well. The prompt itself is divided in two, one part being the
descriptive text (given through the I<prompt> argument) and one describing
the possible answers (given through the I<action_desc> argument).
UI_add_info_string() and UI_add_error_string() add strings that are shown at
the same time as the prompt for extra information or to show an error string.
The difference between the two is only conceptual. With the builtin method,
there's no technical difference between them. Other methods may make a
difference between them, however.
The flags currently supported are UI_INPUT_FLAG_ECHO, which is relevant for
UI_add_input_string() and will have the users response be echoed (when
prompting for a password, this flag should obviously not be used, and
UI_INPUT_FLAG_DEFAULT_PWD, which means that a default password of some
sort will be used (completely depending on the application and the UI
method).
UI_dup_input_string(), UI_dup_verify_string(), UI_dup_input_boolean(),
UI_dup_info_string() and UI_dup_error_string() are basically the same
as their UI_add counterparts, except that they make their own copies
of all strings.
UI_construct_prompt() is a helper function that can be used to create
a prompt from two pieces of information: an description and a name.
The default constructor (if there is none provided by the method used)
creates a string "Enter I<description> for I<name>:". With the
description "pass phrase" and the file name "foo.key", that becomes
"Enter pass phrase for foo.key:". Other methods may create whatever
string and may include encodings that will be processed by the other
method functions.
UI_add_user_data() adds a piece of memory for the method to use at any
time. The builtin UI method doesn't care about this info. Note that several
calls to this function doesn't add data, it replaces the previous blob
with the one given as argument.
UI_get0_user_data() retrieves the data that has last been given to the
UI with UI_add_user_data().
UI_get0_result() returns a pointer to the result buffer associated with
the information indexed by I<i>.
UI_process() goes through the information given so far, does all the printing
and prompting and returns.
UI_ctrl() adds extra control for the application author. For now, it
understands two commands: UI_CTRL_PRINT_ERRORS, which makes UI_process()
print the OpenSSL error stack as part of processing the UI, and
UI_CTRL_IS_REDOABLE, which returns a flag saying if the used UI can
be used again or not.
UI_set_default_method() changes the default UI method to the one given.
UI_get_default_method() returns a pointer to the current default UI method.
UI_get_method() returns the UI method associated with a given UI.
UI_set_method() changes the UI method associated with a given UI.
=head1 SEE ALSO
L<ui_create(3)>, L<ui_compat(3)>
=head1 HISTORY
The UI section was first introduced in OpenSSL 0.9.7.
=head1 AUTHOR
Richard Levitte (richard@levitte.org) for the OpenSSL project
(http://www.openssl.org).
=cut
| vbloodv/blood | extern/openssl.orig/doc/crypto/ui.pod | Perl | mit | 8,170 |
package XrefMapper::ProcessPaired;
use vars '@ISA';
@ISA = qw{ XrefMapper::BasicMapper };
use strict;
use warnings;
use XrefMapper::BasicMapper;
use Cwd;
use DBI;
use File::Basename;
use IPC::Open3;
sub new {
my($class, $mapper) = @_;
my $self ={};
bless $self,$class;
$self->xref($mapper->xref);
$self->verbose($mapper->verbose);
return $self;
}
sub process{
my ($self) = @_;
print "Process Pairs\n" if($self->verbose);
my $object_xref_id;
my $sth = $self->xref->dbc->prepare("select MAX(object_xref_id) from object_xref");
$sth->execute;
$sth->bind_columns(\$object_xref_id);
$sth->fetch;
$object_xref_id++;
$sth->finish;
print "Starting at object_xref of $object_xref_id\n" if($self->verbose);
my $psth = $self->xref->dbc->prepare("select p.accession1, p.accession2 from pairs p");
my $ox_count_sth = $self->xref->dbc->prepare('select count(1) from object_xref ox, xref x where ox.xref_id = x.xref_id and ox.ox_status = "DUMP_OUT" and x.accession = ?');
my $ox_transcript_sth = $self->xref->dbc->prepare('select gtt.transcript_id, ix.query_identity, ix.target_identity from identity_xref ix, object_xref ox, xref x, gene_transcript_translation gtt where ox.object_xref_id = ix.object_xref_id and ox.ox_status = "DUMP_OUT" and ox.xref_id = x.xref_id and gtt.translation_id = ox.ensembl_id and x.accession = ?');
my $ox_translation_sth = $self->xref->dbc->prepare('select gtt.translation_id, ix.query_identity, ix.target_identity from identity_xref ix, object_xref ox, xref x, gene_transcript_translation gtt where ox.object_xref_id = ix.object_xref_id and ox.ox_status = "DUMP_OUT" and ox.xref_id = x.xref_id and gtt.transcript_id = ox.ensembl_id and x.accession = ?');
my $xref_sth = $self->xref->dbc->prepare("select xref_id from xref where accession = ?");
my $ox_insert_sth = $self->xref->dbc->prepare("insert into object_xref (object_xref_id, xref_id, ensembl_id, ensembl_object_type, linkage_type, ox_status) values(?, ?, ?, ?, 'INFERRED_PAIR', 'DUMP_OUT')");
local $ox_insert_sth->{RaiseError}; #catch duplicates
local $ox_insert_sth->{PrintError}; # cut down on error messages
my $ox_get_id_sth = $self->xref->dbc->prepare("select object_xref_id,ox_status from object_xref where xref_id = ? and ensembl_id = ? and ensembl_object_type = ?");
my $ox_update_sth = $self->xref->dbc->prepare('update object_xref set ox_status = "DUMP_OUT", linkage_type = "INFERRED_PAIR" where object_xref_id = ?');
my $xref_update_sth = $self->xref->dbc->prepare('update xref set info_type = "INFERRED_PAIR" where xref_id = ?');
my $ins_dep_ix_sth = $self->xref->dbc->prepare("insert into identity_xref (object_xref_id, query_identity, target_identity) values(?, ?, ?)");
$psth->execute() || die "execute failed";
my ($acc1, $acc2);
$psth->execute();
my $refseq_count = 0;
my %change;
$psth->bind_columns(\$acc1, \$acc2);
while($psth->fetch()){
my $count1;
my $count2;
$ox_count_sth->execute($acc1); # translation alignment
$ox_count_sth->bind_columns(\$count1);
$ox_count_sth->fetch;
$ox_count_sth->execute($acc2); # transcript alignment
$ox_count_sth->bind_columns(\$count2);
$ox_count_sth->fetch;
if(( $count1 and $count2) || (!($count1) and !($count2)) ){
next; # eithr both matched or neither is.
}
if($count1){
#need xref_id for acc2
my $xref_id;
$xref_sth->execute($acc2);
$xref_sth->bind_columns(\$xref_id);
if(!$xref_sth->fetch){
# print "Could not find xref_id for accession $acc2\n";
next;
}
next if(!defined($xref_id));
# print "$acc2\t$xref_id (search using $acc1)\n";
# insert new object_xref
# trap error code. if duplicate then just set linkage_type = "INFERRED_PAIR" and ox_status = "DUMP"
# "maybe" the original failed the cutoff!!! so will have an entry alread but no good.
$ox_transcript_sth->execute($acc1);
my $transcript_id=undef;
my ($q_id,$t_id);
$ox_transcript_sth->bind_columns(\$transcript_id,\$q_id, \$t_id);
while($ox_transcript_sth->fetch){
if(defined($transcript_id)){ # remember not all transcripts have translations.
$object_xref_id++;
$ox_insert_sth->execute($object_xref_id, $xref_id, $transcript_id, "Transcript") ;
if($ox_insert_sth->err){
my $err = $ox_insert_sth->errstr;
if($err =~ /Duplicate/){
$change{"UPDATE"}++;
# duplicate this can happen as it might have failed the cutoff
# find the old object_xref_id and the update the status's
my $old_object_xref_id=undef;
my $status;
$ox_get_id_sth->execute($xref_id, $transcript_id, "Transcript");
$ox_get_id_sth->bind_columns(\$old_object_xref_id, \$status);
$ox_get_id_sth->fetch();
if($status eq "DUMP_OUT"){
print STDERR "Problem status for object_xref_id is DUMP_OUT but this should never happen as it was not found earlier??? (transcript_id = $transcript_id, $xref_id\n";
}
if(!defined($old_object_xref_id)){
die "Duplicate but can't find the original?? xref_id = $xref_id, ensembl_id = $transcript_id, type = Transcript\n";
}
$ox_update_sth->execute($old_object_xref_id)|| die "Could not set update for object_xref_id = $old_object_xref_id";
$xref_update_sth->execute($xref_id)|| die "Could not set update for xref_id = $xref_id";
}
else{
die "Problem loading error is $err\n";
}
}
else{
$ins_dep_ix_sth->execute($object_xref_id, $q_id, $t_id);
$xref_update_sth->execute($xref_id)|| die "Could not set update for xref_id = $xref_id";
$change{"NEW"}++;
}
# print "insert $xref_id transcript $transcript_id ........\n";
$refseq_count++;
}
}
}
elsif($count2){
my $xref_id;
$xref_sth->execute($acc1);
$xref_sth->bind_columns(\$xref_id);
if(!$xref_sth->fetch){
# print "Could not find xref_id for accession $acc1\n";
next;
}
next if(!defined($xref_id));
# print "$acc1\t$xref_id (search using $acc2)\n";
# insert new object_xref
# trap error code. if duplicate then just set linkage_type = "INFERRED_PAIR" and ox_status = "DUMP"
# "maybe" the original failed the cutoff!!! so will have an entry alread but no good.
$ox_translation_sth->execute($acc2);
my $translation_id = undef;
my ($q_id, $t_id);
$ox_translation_sth->bind_columns(\$translation_id, \$q_id, \$t_id);
while($ox_translation_sth->fetch){
if(defined($translation_id)){ # remember not all transcripts ahve translations.
$object_xref_id++;
$ox_insert_sth->execute($object_xref_id, $xref_id, $translation_id, "Translation") ;
if($ox_insert_sth->err){
$change{"UPDATE"}++;
my $err = $ox_insert_sth->errstr;
if($err =~ /Duplicate/){
# duplicate this can happen as it might have failed the cutoff
# find the old object_xref_id and the update the status's
my $old_object_xref_id=undef;
my $status;
$ox_get_id_sth->execute($xref_id, $translation_id, "Translation");
$ox_get_id_sth->bind_columns(\$old_object_xref_id,\$status);
$ox_get_id_sth->fetch();
if($status eq "DUMP_OUT"){
print STDERR "Problem status for object_xref_id is DUMP_OUT but this should never happen as it was not found earlier??? (trasnlation_id = $translation_id, $xref_id\n";
}
if(!defined($old_object_xref_id)){
die "Duplicate but can't find the original?? xref_id = $xref_id, ensembl_id = $translation_id, type = Translation\n";
}
$ox_update_sth->execute($old_object_xref_id)|| die "Could not set update for object_xref_id = $old_object_xref_id";
$xref_update_sth->execute($xref_id)|| die "Could not set update for xref_id = $xref_id";
}
else{
die "Problem loading error is $err\n";
}
}
else{
$ins_dep_ix_sth->execute($object_xref_id, $q_id, $t_id);
$xref_update_sth->execute($xref_id)|| die "Could not set update for xref_id = $xref_id";
$change{"NEW"}++;
}
# print "insert $xref_id translation $translation_id ........\n";
$refseq_count++;
}
}
}
else{
print STDERR "HMMM how did i get here. This should be impossible. [logic error]\n";
}
}
$psth->finish;
$ox_count_sth->finish;
$ox_transcript_sth->finish;
$ox_translation_sth->finish;
$ox_update_sth->finish;
$xref_update_sth->finish;
$xref_sth->finish;
$ins_dep_ix_sth->finish;
foreach my $key (keys %change){
print "\t$key\t".$change{$key}."\n" if($self->verbose);
}
print "$refseq_count new relationships added\n" if($self->verbose);
my $sth_stat = $self->xref->dbc->prepare("insert into process_status (status, date) values('processed_pairs',now())");
$sth_stat->execute();
$sth_stat->finish;
}
1;
| adamsardar/perl-libs-custom | EnsemblAPI/ensembl/misc-scripts/xref_mapping/XrefMapper/ProcessPaired.pm | Perl | apache-2.0 | 8,861 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V10::Common::LogicalUserListInfo;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {rules => $args->{rules}};
# Delete the unassigned fields in this object for a more concise JSON payload
remove_unassigned_fields($self, $args);
bless $self, $class;
return $self;
}
1;
| googleads/google-ads-perl | lib/Google/Ads/GoogleAds/V10/Common/LogicalUserListInfo.pm | Perl | apache-2.0 | 1,018 |
use strict;
use warnings;
package G2P::DBSQL::GenomicFeatureDiseasePublicationAdaptor;
use G2P::DBSQL::BaseAdaptor;
use G2P::GenomicFeatureDiseasePublication;
our @ISA = ('G2P::DBSQL::BaseAdaptor');
my @columns = qw/GFD_publication_id genomic_feature_disease_id publication_id/;
sub store {
my $self = shift;
my $GFD_publication = shift;
my $dbh = $self->{dbh};
my $sth = $dbh->prepare(q{
INSERT INTO genomic_feature_disease_publication (
genomic_feature_disease_id,
publication_id
) VALUES (?,?);
});
$sth->execute(
$GFD_publication->get_GenomicFeatureDisease()->dbID(),
$GFD_publication->get_Publication()->dbID()
);
$sth->finish();
# get dbID
my $dbID = $dbh->last_insert_id(undef, undef, 'genomic_feature_disease_publication', 'GFD_publication_id');
$GFD_publication->{GFD_publication_id} = $dbID;
$GFD_publication->{registry} = $self->{registry};
return $GFD_publication;
}
sub delete {
my $self = shift;
my $GFDP = shift;
my $user = shift;
my $dbh = $self->{dbh};
if (!ref($GFDP) || !$GFDP->isa('G2P::GenomicFeatureDiseasePublication')) {
die ('G2P::GenomicFeatureDiseasePublication arg expected');
}
if (!ref($user) || !$user->isa('G2P::User')) {
die ('G2P::User arg expected');
}
my $sth = $dbh->prepare(q{
DELETE FROM GFD_publication_comment WHERE GFD_publication_id = ?;
});
$sth->execute($GFDP->dbID);
$sth = $dbh->prepare(q{
DELETE FROM genomic_feature_disease_publication WHERE GFD_publication_id = ?;
});
$sth->execute($GFDP->dbID);
$sth->finish();
}
sub fetch_by_dbID {
my $self = shift;
my $GFD_publication_id = shift;
my $constraint = "WHERE GFD_publication_id=$GFD_publication_id";
return $self->_fetch($constraint);
}
sub fetch_by_GFD_id_publication_id {
my $self = shift;
my $GFD_id = shift;
my $publication_id = shift;
my $constraint = "WHERE genomic_feature_disease_id=$GFD_id AND publication_id=$publication_id";
return $self->_fetch($constraint);
}
sub fetch_all_by_GenomicFeatureDisease {
my $self = shift;
my $GFD = shift;
if (!ref($GFD) || !$GFD->isa('G2P::GenomicFeatureDisease')) {
die('G2P::GenomicFeatureDisease arg expected');
}
my $GFD_id = $GFD->dbID;
my $constraint = "WHERE genomic_feature_disease_id=$GFD_id";
return $self->_fetch_all($constraint);
}
sub _fetch_all {
my $self = shift;
my $constraint = shift;
my @gfd_publications = ();
my $query = 'SELECT GFD_publication_id, genomic_feature_disease_id, publication_id FROM genomic_feature_disease_publication';
$query .= " $constraint;";
my $dbh = $self->{dbh};
my $sth = $dbh->prepare($query);
$sth->execute() or die 'Could not execute statement ' . $sth->errstr;
while (my $row = $sth->fetchrow_arrayref()) {
my %gfd_publication;
@gfd_publication{@columns} = @$row;
$gfd_publication{registry} = $self->{registry};
push @gfd_publications, G2P::GenomicFeatureDiseasePublication->new(\%gfd_publication);
}
return \@gfd_publications;
}
sub _fetch {
my $self = shift;
my $constraint = shift;
my @gfd_publications = ();
my $query = 'SELECT GFD_publication_id, genomic_feature_disease_id, publication_id FROM genomic_feature_disease_publication';
$query .= " $constraint;";
my $dbh = $self->{dbh};
my $sth = $dbh->prepare($query);
$sth->execute() or die 'Could not execute statement ' . $sth->errstr;
while (my $row = $sth->fetchrow_arrayref()) {
my %gfd_publication;
@gfd_publication{@columns} = @$row;
$gfd_publication{registry} = $self->{registry};
push @gfd_publications, G2P::GenomicFeatureDiseasePublication->new(\%gfd_publication);
}
return $gfd_publications[0];
}
1;
| at7/gene2phenotype | modules/G2P/DBSQL/GenomicFeatureDiseasePublicationAdaptor.pm | Perl | apache-2.0 | 3,698 |
=head1 LICENSE
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
=head1 NAME
Bio::EnsEMBL::Compara::Production::Analysis::ExtendedGenomeAlignment
=head1 DESCRIPTION
This module creates a new tree for those alignments which contain a segmental duplication. The module will runs treeBest where there are more than 3 sequences in an alignment, otherwise it will run semphy. This module is still under development.
=head1 METHODS
=cut
package Bio::EnsEMBL::Compara::Production::Analysis::ExtendedGenomeAlignment;
use strict;
use warnings;
use Bio::EnsEMBL::Utils::Exception;
use Bio::EnsEMBL::Compara::GenomicAlign;
use Bio::EnsEMBL::Compara::GenomicAlignBlock;
use Bio::EnsEMBL::Compara::GenomicAlignTree;
use Bio::EnsEMBL::Compara::Graph::NewickParser;
use Data::Dumper;
use File::Basename;
=head2 run_analysis
Description: run treebest if more than 3 sequences in the alignment else run
semphy
Returntype : none
Exceptions : throws if the program in not executable or if the results
file doesnt exist
Example :
Status : At risk
=cut
sub run_analysis {
my ($self) = @_;
#find how many sequences are in the mfa file
my $num_sequences = get_num_sequences($self->param('multi_fasta_file'));
#treebest phyml needs at least 4 sequences to run. If I have less than
#4, then run semphy instead.
if ($num_sequences < 4) {
return run_semphy_2x($self);
} else {
return run_treebest_2x($self);
}
}
#Find how many sequences in mfa file
sub get_num_sequences {
my ($mfa) = @_;
my $cnt = 0;
open (my $mfa_fh, '<', $mfa) || throw("Couldn't open $mfa");
while (<$mfa_fh>) {
$cnt++ if (/^>/);
}
close($mfa_fh);
return $cnt;
}
=head2 run_treebest_2x
Arg [1] : none
Description: create and open a commandline for the program treebest
Returntype : none
Exceptions : throws if the program in not executable or if the results
file doesnt exist
Example :
Status : At risk
=cut
sub run_treebest_2x {
my ($self) = @_;
#Check I don't already have a tree
return if ($self->tree_string);
my $tree_file = $self->worker_temp_directory."/output.$$.tree";
#write species tree (with taxon_ids) to file in workdir
my $species_tree_file = $self->worker_temp_directory."/species_tree.$$.tree";
$self->_spurt($species_tree_file, $self->get_taxon_tree);
#Run treebeset
my $command = $self->param('treebest_exe') ." phyml -Snf $species_tree_file " . $self->param('multi_fasta_file') . " | " . $self->param('treebest_exe') . " sdi -rs $species_tree_file - > $tree_file";
print "Running treebest $command\n";
#run treebest to create tree
$self->run_command($command, { die_on_failure => 1, use_bash_pipefail => 1 });
#read in new tree
if (-e $tree_file) {
## Treebest estimated the tree. Overwrite the order of the fasta files and get the tree
my $newick = $self->_slurp($tree_file);
$newick =~ s/[\r\n]+$//;
rearrange_multi_fasta_file($newick, $self->param('multi_fasta_file'));
}
return $tree_file;
}
=head2 run_semphy_2x
Arg [1] : none
Description: create and open a commandline for the program semphy
Returntype : none
Exceptions : throws if the program in not executable or if the results
file doesnt exist
Example :
Status : At risk
=cut
sub run_semphy_2x {
my ($self) = @_;
#Check I don't already have a tree
return if ($self->tree_string);
my $tree_file = $self->worker_temp_directory."/output.$$.tree";
#Run semphy directly
my $command = [$self->param('semphy_exe'), "--treeoutputfile=$tree_file", qw(-a 4 --hky -J -H -S), '--ACGprob=0.300000,0.200000,0.200000', '--sequence='.$self->param('multi_fasta_file')];
#run semphy to create tree
$self->run_command($command, { die_on_failure => 1 });
#read in new tree
if (-e $tree_file) {
## Semphy estimated the tree. Overwrite the order of the fasta files and get the tree
my $newick = $self->_slurp($tree_file);
$newick =~ s/[\r\n]+$//;
rearrange_multi_fasta_file($newick, $self->param('multi_fasta_file'));
}
#print "FINAL tree string $tree_string\n";
return $tree_file;
}
sub rearrange_multi_fasta_file {
my ($tree_string, $mfa_file) = @_;
my (@ordered_leaves) = $tree_string =~ /(seq[^:]+)/g;
my $ordered_names;
for (my $i = 0; $i < @ordered_leaves; $i++) {
my $item;
$item->{name} = ">" . $ordered_leaves[$i];
$item->{leaf} = $ordered_leaves[$i];
push @$ordered_names, $item;
}
my %mfa_data;
open(my $mfa_fh, '<', $mfa_file) || throw("Could not open mfa file <$mfa_file>");
my $name;
my $seq;
while (<$mfa_fh>) {
next if (/^\s*$/);
chomp;
if (/^>/) {
if ($name) {
$mfa_data{$name} = $seq;
$seq = "";
}
$name = $_;
} else {
$seq .= $_;
}
}
$mfa_data{$name} = $seq;
close($mfa_fh);
#overwrite existing mfa file
open($mfa_fh, '>', $mfa_file) || throw("Couldn't open $mfa_file");
foreach my $ordered_name (@$ordered_names) {
#for ancestral
next if (!defined $mfa_data{$ordered_name->{name}});
print $mfa_fh ">".$ordered_name->{leaf} . "\n";
my $seq = $mfa_data{$ordered_name->{name}};
$seq =~ s/(.{80})/$1\n/g;
chomp $seq;
print $mfa_fh $seq,"\n";
}
close $mfa_fh;
}
1;
| Ensembl/ensembl-compara | modules/Bio/EnsEMBL/Compara/Production/Analysis/ExtendedGenomeAlignment.pm | Perl | apache-2.0 | 5,978 |
#
# Copyright 2015 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::vmware::connector::mode::healthhost;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"esx-hostname:s" => { name => 'esx_hostname' },
"filter" => { name => 'filter' },
"scope-datacenter:s" => { name => 'scope_datacenter' },
"scope-cluster:s" => { name => 'scope_cluster' },
"storage-status" => { name => 'storage_status' },
"disconnect-status:s" => { name => 'disconnect_status', default => 'unknown' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if ($self->{output}->is_litteral_status(status => $self->{option_results}->{disconnect_status}) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong disconnect-status status option '" . $self->{option_results}->{disconnect_status} . "'.");
$self->{output}->option_exit();
}
}
sub run {
my ($self, %options) = @_;
$self->{connector} = $options{custom};
$self->{connector}->add_params(params => $self->{option_results},
command => 'healthhost');
$self->{connector}->run();
}
1;
__END__
=head1 MODE
Check health of ESX hosts.
=over 8
=item B<--esx-hostname>
ESX hostname to check.
If not set, we check all ESX.
=item B<--filter>
ESX hostname is a regexp.
=item B<--scope-datacenter>
Search in following datacenter(s) (can be a regexp).
=item B<--scope-cluster>
Search in following cluster(s) (can be a regexp).
=item B<--storage-status>
Check storage(s) status.
=item B<--disconnect-status>
Status if ESX host disconnected (default: 'unknown').
=back
=cut
| s-duret/centreon-plugins | apps/vmware/connector/mode/healthhost.pm | Perl | apache-2.0 | 2,908 |
package Paws::EC2::ElasticGpuHealth;
use Moose;
has Status => (is => 'ro', isa => 'Str', request_name => 'status', traits => ['NameInRequest']);
1;
### main pod documentation begin ###
=head1 NAME
Paws::EC2::ElasticGpuHealth
=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::EC2::ElasticGpuHealth object:
$service_obj->Method(Att1 => { Status => $value, ..., Status => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::EC2::ElasticGpuHealth object:
$result = $service_obj->Method(...);
$result->Att1->Status
=head1 DESCRIPTION
This class has no description
=head1 ATTRIBUTES
=head2 Status => Str
The health status.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::EC2>
=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/EC2/ElasticGpuHealth.pm | Perl | apache-2.0 | 1,281 |
#!/usr/bin/env perl
#Creates text file of identifers conforming to convention in ../../README.md
#Obtains identifiers from EBiSC IMS
use strict;
use warnings;
use Getopt::Long;
use ReseqTrack::EBiSC::IMS;
my ($IMS_user, $IMS_pass, $outfile);
GetOptions("user=s" => \$IMS_user,
"pass=s" => \$IMS_pass,
"outfile=s" => \$outfile,
);
die "missing credentials" if !$IMS_user || !$IMS_pass || !$outfile;
my $IMS = ReseqTrack::EBiSC::IMS->new(
user => $IMS_user,
pass => $IMS_pass,
);
open(my $fh, '>', $outfile) or die "Could not open file '$outfile' $!";
foreach my $line (@{$IMS->find_lines->{objects}}) {
if (defined $$line{validation_status}){
if ($$line{validation_status} eq 'Validated, visible' or $$line{validation_status} eq 'Validated, not visible'){
print $fh $line->{name}, "\t", join('###', @{$line->{alternative_names}}), "\t", $line->{biosamples_id}, "\n";
}
}
}
close($fh); | EMBL-EBI-GCA/gca-tools | literature_mining/scripts/literature_mining.ebisc.pl | Perl | apache-2.0 | 923 |
# PODNAME: Moose::Cookbook::Roles::Comparable_CodeReuse
# ABSTRACT: Using roles for code reuse
__END__
=pod
=encoding UTF-8
=head1 NAME
Moose::Cookbook::Roles::Comparable_CodeReuse - Using roles for code reuse
=head1 VERSION
version 2.1404
=head1 SYNOPSIS
package Eq;
use Moose::Role;
requires 'equal_to';
sub not_equal_to {
my ( $self, $other ) = @_;
not $self->equal_to($other);
}
package Comparable;
use Moose::Role;
with 'Eq';
requires 'compare';
sub equal_to {
my ( $self, $other ) = @_;
$self->compare($other) == 0;
}
sub greater_than {
my ( $self, $other ) = @_;
$self->compare($other) == 1;
}
sub less_than {
my ( $self, $other ) = @_;
$self->compare($other) == -1;
}
sub greater_than_or_equal_to {
my ( $self, $other ) = @_;
$self->greater_than($other) || $self->equal_to($other);
}
sub less_than_or_equal_to {
my ( $self, $other ) = @_;
$self->less_than($other) || $self->equal_to($other);
}
package Printable;
use Moose::Role;
requires 'to_string';
package US::Currency;
use Moose;
with 'Comparable', 'Printable';
has 'amount' => ( is => 'rw', isa => 'Num', default => 0 );
sub compare {
my ( $self, $other ) = @_;
$self->amount <=> $other->amount;
}
sub to_string {
my $self = shift;
sprintf '$%0.2f USD' => $self->amount;
}
=head1 DESCRIPTION
Roles have two primary purposes: as interfaces, and as a means of code
reuse. This recipe demonstrates the latter, with roles that define
comparison and display code for objects.
Let's start with C<Eq>. First, note that we've replaced C<use Moose>
with C<use Moose::Role>. We also have a new sugar function, C<requires>:
requires 'equal_to';
This says that any class which consumes this role must provide an
C<equal_to> method. It can provide this method directly, or by
consuming some other role.
The C<Eq> role defines its C<not_equal_to> method in terms of the
required C<equal_to> method. This lets us minimize the methods that
consuming classes must provide.
The next role, C<Comparable>, builds on the C<Eq> role. We include
C<Eq> in C<Comparable> using C<with>, another new sugar function:
with 'Eq';
The C<with> function takes a list of roles to consume. In our example,
the C<Comparable> role provides the C<equal_to> method required by
C<Eq>. However, it could opt not to, in which case a class that
consumed C<Comparable> would have to provide its own C<equal_to>. In
other words, a role can consume another role I<without> providing any
required methods.
The C<Comparable> role requires a method, C<compare>:
requires 'compare';
The C<Comparable> role also provides a number of other methods, all of
which ultimately rely on C<compare>.
sub equal_to {
my ( $self, $other ) = @_;
$self->compare($other) == 0;
}
sub greater_than {
my ( $self, $other ) = @_;
$self->compare($other) == 1;
}
sub less_than {
my ( $self, $other ) = @_;
$self->compare($other) == -1;
}
sub greater_than_or_equal_to {
my ( $self, $other ) = @_;
$self->greater_than($other) || $self->equal_to($other);
}
sub less_than_or_equal_to {
my ( $self, $other ) = @_;
$self->less_than($other) || $self->equal_to($other);
}
Finally, we define the C<Printable> role. This role exists solely to
provide an interface. It has no methods, just a list of required methods.
In this case, it just requires a C<to_string> method.
An interface role is useful because it defines both a method and a
I<name>. We know that any class which does this role has a
C<to_string> method, but we can also assume that this method has the
semantics we want. Presumably, in real code we would define those
semantics in the documentation for the C<Printable> role. (1)
Finally, we have the C<US::Currency> class which consumes both the
C<Comparable> and C<Printable> roles.
with 'Comparable', 'Printable';
It also defines a regular Moose attribute, C<amount>:
has 'amount' => ( is => 'rw', isa => 'Num', default => 0 );
Finally we see the implementation of the methods required by our
roles. We have a C<compare> method:
sub compare {
my ( $self, $other ) = @_;
$self->amount <=> $other->amount;
}
By consuming the C<Comparable> role and defining this method, we gain
the following methods for free: C<equal_to>, C<greater_than>,
C<less_than>, C<greater_than_or_equal_to> and
C<less_than_or_equal_to>.
Then we have our C<to_string> method:
sub to_string {
my $self = shift;
sprintf '$%0.2f USD' => $self->amount;
}
=head1 CONCLUSION
Roles can be very powerful. They are a great way of encapsulating
reusable behavior, as well as communicating (semantic and interface)
information about the methods our classes provide.
=head1 FOOTNOTES
=over 4
=item (1)
Consider two classes, C<Runner> and C<Process>, both of which define a
C<run> method. If we just require that an object implements a C<run>
method, we still aren't saying anything about what that method
I<actually does>. If we require an object that implements the
C<Executable> role, we're saying something about semantics.
=back
=begin testing
ok( US::Currency->does('Comparable'), '... US::Currency does Comparable' );
ok( US::Currency->does('Eq'), '... US::Currency does Eq' );
ok( US::Currency->does('Printable'), '... US::Currency does Printable' );
my $hundred = US::Currency->new( amount => 100.00 );
isa_ok( $hundred, 'US::Currency' );
ok( $hundred->DOES("US::Currency"), "UNIVERSAL::DOES for class" );
ok( $hundred->DOES("Comparable"), "UNIVERSAL::DOES for role" );
can_ok( $hundred, 'amount' );
is( $hundred->amount, 100, '... got the right amount' );
can_ok( $hundred, 'to_string' );
is( $hundred->to_string, '$100.00 USD',
'... got the right stringified value' );
ok( $hundred->does('Comparable'), '... US::Currency does Comparable' );
ok( $hundred->does('Eq'), '... US::Currency does Eq' );
ok( $hundred->does('Printable'), '... US::Currency does Printable' );
my $fifty = US::Currency->new( amount => 50.00 );
isa_ok( $fifty, 'US::Currency' );
can_ok( $fifty, 'amount' );
is( $fifty->amount, 50, '... got the right amount' );
can_ok( $fifty, 'to_string' );
is( $fifty->to_string, '$50.00 USD', '... got the right stringified value' );
ok( $hundred->greater_than($fifty), '... 100 gt 50' );
ok( $hundred->greater_than_or_equal_to($fifty), '... 100 ge 50' );
ok( !$hundred->less_than($fifty), '... !100 lt 50' );
ok( !$hundred->less_than_or_equal_to($fifty), '... !100 le 50' );
ok( !$hundred->equal_to($fifty), '... !100 eq 50' );
ok( $hundred->not_equal_to($fifty), '... 100 ne 50' );
ok( !$fifty->greater_than($hundred), '... !50 gt 100' );
ok( !$fifty->greater_than_or_equal_to($hundred), '... !50 ge 100' );
ok( $fifty->less_than($hundred), '... 50 lt 100' );
ok( $fifty->less_than_or_equal_to($hundred), '... 50 le 100' );
ok( !$fifty->equal_to($hundred), '... !50 eq 100' );
ok( $fifty->not_equal_to($hundred), '... 50 ne 100' );
ok( !$fifty->greater_than($fifty), '... !50 gt 50' );
ok( $fifty->greater_than_or_equal_to($fifty), '... !50 ge 50' );
ok( !$fifty->less_than($fifty), '... 50 lt 50' );
ok( $fifty->less_than_or_equal_to($fifty), '... 50 le 50' );
ok( $fifty->equal_to($fifty), '... 50 eq 50' );
ok( !$fifty->not_equal_to($fifty), '... !50 ne 50' );
## ... check some meta-stuff
# Eq
my $eq_meta = Eq->meta;
isa_ok( $eq_meta, 'Moose::Meta::Role' );
ok( $eq_meta->has_method('not_equal_to'), '... Eq has_method not_equal_to' );
ok( $eq_meta->requires_method('equal_to'),
'... Eq requires_method not_equal_to' );
# Comparable
my $comparable_meta = Comparable->meta;
isa_ok( $comparable_meta, 'Moose::Meta::Role' );
ok( $comparable_meta->does_role('Eq'), '... Comparable does Eq' );
foreach my $method_name (
qw(
equal_to not_equal_to
greater_than greater_than_or_equal_to
less_than less_than_or_equal_to
)
) {
ok( $comparable_meta->has_method($method_name),
'... Comparable has_method ' . $method_name );
}
ok( $comparable_meta->requires_method('compare'),
'... Comparable requires_method compare' );
# Printable
my $printable_meta = Printable->meta;
isa_ok( $printable_meta, 'Moose::Meta::Role' );
ok( $printable_meta->requires_method('to_string'),
'... Printable requires_method to_string' );
# US::Currency
my $currency_meta = US::Currency->meta;
isa_ok( $currency_meta, 'Moose::Meta::Class' );
ok( $currency_meta->does_role('Comparable'),
'... US::Currency does Comparable' );
ok( $currency_meta->does_role('Eq'), '... US::Currency does Eq' );
ok( $currency_meta->does_role('Printable'),
'... US::Currency does Printable' );
foreach my $method_name (
qw(
amount
equal_to not_equal_to
compare
greater_than greater_than_or_equal_to
less_than less_than_or_equal_to
to_string
)
) {
ok( $currency_meta->has_method($method_name),
'... US::Currency has_method ' . $method_name );
}
=end testing
=head1 AUTHORS
=over 4
=item *
Stevan Little <stevan.little@iinteractive.com>
=item *
Dave Rolsky <autarch@urth.org>
=item *
Jesse Luehrs <doy@tozt.net>
=item *
Shawn M Moore <code@sartak.org>
=item *
יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
=item *
Karen Etheridge <ether@cpan.org>
=item *
Florian Ragwitz <rafl@debian.org>
=item *
Hans Dieter Pearcey <hdp@weftsoar.net>
=item *
Chris Prather <chris@prather.org>
=item *
Matt S Trout <mst@shadowcat.co.uk>
=back
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2006 by Infinity Interactive, Inc..
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
| ray66rus/vndrv | local/lib/perl5/x86_64-linux-thread-multi/Moose/Cookbook/Roles/Comparable_CodeReuse.pod | Perl | apache-2.0 | 10,000 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
=head1 SYNOPSIS
=head1 DESCRIPTION
=head1 METHODS
=cut
package Bio::EnsEMBL::IdMapping::StableIdMapper;
use strict;
use warnings;
no warnings 'uninitialized';
use Bio::EnsEMBL::IdMapping::BaseObject;
our @ISA = qw(Bio::EnsEMBL::IdMapping::BaseObject);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::ScriptUtils qw(inject path_append);
use Bio::EnsEMBL::IdMapping::ScoredMappingMatrix;
use POSIX qw(strftime);
# instance variables
my %debug_mappings;
sub new {
my $caller = shift;
my $class = ref($caller) || $caller;
my $self = $class->SUPER::new(@_);
# inject a StableIdGenerator
#
# If you write your own generators, make sure they extend
# Bio::EnsEMBL::Idmapping::BaseObject and additionally implement these three
# methods: initial_stable_id(), increment_stable_id() and calculate_version().
my $stable_id_generator = $self->conf->param('plugin_stable_id_generator') ||
'Bio::EnsEMBL::IdMapping::StableIdGenerator::EnsemblGeneric';
$self->logger->debug("Using $stable_id_generator to generate stable Ids.\n");
inject($stable_id_generator);
# create a new StableIdGenerator object
my $generator_instance = $stable_id_generator->new(
-LOGGER => $self->logger,
-CONF => $self->conf,
-CACHE => $self->cache
);
$self->stable_id_generator($generator_instance);
return $self;
}
sub generate_mapping_session {
my $self = shift;
# only run this method once
return if ($self->mapping_session_date);
$self->logger->info("Generating new mapping_session...\n");
$self->mapping_session_date(time);
$self->mapping_session_date_fmt(strftime("%Y-%m-%d %T",
localtime($self->mapping_session_date)));
my $s_dba = $self->cache->get_DBAdaptor('source');
my $s_dbh = $s_dba->dbc->db_handle;
my $t_dba = $self->cache->get_DBAdaptor('target');
my $t_dbh = $t_dba->dbc->db_handle;
# check if mapping_session_id was manually set by the configuration
my $mapping_session_id = $self->conf->param('mapping_session_id');
if ($mapping_session_id) {
$self->logger->debug("Using manually configured mapping_session_id $mapping_session_id\n", 1);
} else {
# calculate mapping_session_id from db
my $sql = qq(SELECT MAX(mapping_session_id) FROM mapping_session);
$mapping_session_id = $self->fetch_value_from_db($s_dbh, $sql);
unless ($mapping_session_id) {
$self->logger->debug("No previous mapping_session found.\n", 1);
}
# increment last mapping_session_id
$mapping_session_id++;
$self->logger->debug("Using mapping_session_id $mapping_session_id\n", 1);
}
$self->mapping_session_id($mapping_session_id);
# write old mapping_session table to a file
my $i;
my $fh = $self->get_filehandle('mapping_session.txt', 'tables');
my $sth1 = $s_dbh->prepare("SELECT * FROM mapping_session");
$sth1->execute;
while (my @row = $sth1->fetchrow_array) {
$i++;
print $fh join("\t", @row);
print $fh "\n";
}
$sth1->finish;
# append the new mapping_session to the file
my $release_sql = qq(
SELECT meta_value FROM meta WHERE meta_key = 'schema_version'
);
my $old_release = $self->fetch_value_from_db($s_dbh, $release_sql);
my $new_release = $self->fetch_value_from_db($t_dbh, $release_sql);
my $assembly_sql = qq(
SELECT meta_value FROM meta WHERE meta_key = 'assembly.default'
);
my $old_assembly = $self->fetch_value_from_db($s_dbh, $assembly_sql);
my $new_assembly = $self->fetch_value_from_db($t_dbh, $assembly_sql);
unless ($old_release and $new_release and $old_assembly and $new_assembly) {
$self->logger->warning("Not all data for new mapping_session found:\n", 1);
$self->logger->info("old_release: $old_release, new_release: $new_release");
$self->logger->info("old_assembly: $old_assembly, new_assembly $new_assembly\n", 2);
}
print $fh join("\t",
$mapping_session_id,
$self->conf->param('sourcedbname'),
$self->conf->param('targetdbname'),
$old_release,
$new_release,
$old_assembly,
$new_assembly,
$self->mapping_session_date_fmt);
print $fh "\n";
close($fh);
$self->logger->info("Done writing ".++$i." mapping_session entries.\n\n");
}
sub map_stable_ids {
my $self = shift;
my $mappings = shift;
my $type = shift;
unless ($mappings and
$mappings->isa('Bio::EnsEMBL::IdMapping::MappingList')) {
throw("Need a Bio::EnsEMBL::IdMapping::MappingList of ${type}s.");
}
# generate a new mapping_session and write all mapping_session data to a file
$self->generate_mapping_session;
$self->logger->info("== Stable ID mapping for $type...\n\n", 0, 'stamped');
# check if there are any objects of this type at all
my %all_sources = %{ $self->cache->get_by_name("${type}s_by_id", 'source') };
my %all_targets = %{ $self->cache->get_by_name("${type}s_by_id", 'target') };
unless (scalar(keys %all_sources)) {
$self->logger->info("No cached ${type}s found.\n\n");
return;
}
my %stats = map { $_ => 0 }
qw(mapped_known mapped_novel new lost_known lost_novel);
# create some lookup hashes from the mappings
my %sources_mapped = ();
my %targets_mapped = ();
my %scores_by_target = ();
foreach my $e (@{ $mappings->get_all_Entries }) {
$sources_mapped{$e->source} = $e->target;
$targets_mapped{$e->target} = $e->source;
$scores_by_target{$e->target} = $e->score;
}
# determine starting stable ID for new assignments
my $new_stable_id = $self->stable_id_generator->initial_stable_id($type);
#
# assign mapped and new stable IDs
#
foreach my $tid (keys %all_targets) {
my $t_obj = $all_targets{$tid};
# a mapping exists, assign stable ID accordingly
if (my $sid = $targets_mapped{$tid}) {
my $s_obj = $all_sources{$sid};
# set target's stable ID and created_date
$t_obj->stable_id($s_obj->stable_id);
$t_obj->created_date($s_obj->created_date);
# calculate and set version
my $old_version = $s_obj->version();
my $new_version = $self->stable_id_generator->calculate_version($s_obj, $t_obj) ;
$t_obj->version($new_version);
# change modified_date if version changed
if ($old_version == $new_version) {
$t_obj->modified_date($s_obj->modified_date);
} else {
$t_obj->modified_date($self->mapping_session_date);
# If version changed, score cannot be 1
if ($scores_by_target{$tid} == 1) {
$scores_by_target{$tid} = 0.99;
}
}
# create a stable_id_event entry (not for exons)
unless ( $type eq 'exon' ) {
# Only add events when something changed.
if ( !( $s_obj->stable_id eq $t_obj->stable_id &&
$s_obj->version == $t_obj->version &&
$scores_by_target{$tid} > 0.9999 ) )
{
my $key = join( "\t",
$s_obj->stable_id, $s_obj->version,
$t_obj->stable_id, $t_obj->version,
$self->mapping_session_id, $type,
$scores_by_target{$tid} );
$self->add_stable_id_event( 'new', $key );
}
}
# add to debug hash
push @{ $debug_mappings{$type} }, [ $sid, $tid, $t_obj->stable_id ];
# stats
if ($s_obj->is_known) {
$stats{'mapped_known'}++;
} else {
$stats{'mapped_novel'}++;
}
# no mapping was found, assign a new stable ID
} else {
$t_obj->stable_id($new_stable_id);
$t_obj->version(1);
$t_obj->created_date($self->mapping_session_date);
$t_obj->modified_date($self->mapping_session_date);
# create a stable_id_event entry (not for exons)
unless ($type eq 'exon') {
my $key = join("\t",
'\N',
0,
$t_obj->stable_id,
$t_obj->version,
$self->mapping_session_id,
$type,
0
);
$self->add_stable_id_event('new', $key);
}
# increment the stable Id (to be assigned to the next unmapped object)
$new_stable_id = $self->stable_id_generator->increment_stable_id(
$new_stable_id);
# stats
$stats{'new'}++;
}
}
#
# deletion events for lost sources
#
my $fh;
if ($type eq 'gene' or $type eq 'transcript') {
$fh = $self->get_filehandle("${type}s_lost.txt", 'debug');
}
foreach my $sid (keys %all_sources) {
my $s_obj = $all_sources{$sid};
# no mapping exists, add deletion event
unless ($sources_mapped{$sid}) {
unless ($type eq 'exon') {
my $key = join("\t",
$s_obj->stable_id,
$s_obj->version,
'\N',
0,
$self->mapping_session_id,
$type,
0
);
$self->add_stable_id_event('new', $key);
}
# stats
my $status;
if ($s_obj->is_known) {
$stats{'lost_known'}++;
$status = 'known';
} else {
$stats{'lost_novel'}++;
$status = 'novel';
}
# log lost genes and transcripts (for debug purposes)
#
# The Java app did this with a separate method
# (StableIdMapper.dumpLostGeneAndTranscripts()) which also claims to log
# losses due to merge. Since at that point this data isn't available yet
# the logging can be done much more efficient here
if ($type eq 'gene' or $type eq 'transcript') {
print $fh $s_obj->stable_id, "\t$status\n";
}
}
}
close($fh) if (defined($fh));
#
# write stable IDs to file
#
$self->write_stable_ids_to_file($type, \%all_targets);
# also generate and write stats to file
$self->generate_mapping_stats($type, \%stats);
$self->logger->info("Done.\n\n");
}
sub generate_similarity_events {
my ( $self, $mappings, $scores, $type ) = @_;
# argument checks
unless ( $mappings and
$mappings->isa('Bio::EnsEMBL::IdMapping::MappingList') )
{
throw('Need a gene Bio::EnsEMBL::IdMapping::MappingList.');
}
unless ( $scores and
$scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix') )
{
throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
}
throw("Need a type (gene|transcript|translation).") unless ($type);
my $mapped;
foreach my $e ( @{ $mappings->get_all_Entries } ) {
# create lookup hash for mapped sources and targets; we'll need this
# later
$mapped->{'source'}->{ $e->source } = 1;
$mapped->{'target'}->{ $e->target } = 1;
} ## end foreach my $e ( @{ $mappings...})
#
# similarities for other entries
#
foreach my $dbtype ( keys %$mapped ) {
# note: $dbtype will be either 'source' or 'target'
my $m1 = "get_all_${dbtype}s";
my $m2 = "get_Entries_for_${dbtype}";
foreach my $id ( @{ $scores->$m1 } ) {
# skip if this is a mapped source/target
if ( $mapped->{$dbtype}->{$id} ) { next }
my @entries =
sort { $b->score <=> $a->score } @{ $scores->$m2($id) };
unless (@entries) { next }
# skip if top score < 0.75
my $top_score = $entries[0]->score;
if ( $top_score < 0.75 ) { next }
# add similarities for all entries within 5% of top scorer
while ( my $e = shift(@entries) ) {
if ( $mapped->{'source'}->{$e->source} ) { next ; }
if ( $mapped->{'target'}->{$e->target} ) { next ; }
if ( $e->score > ( $top_score*0.95 ) ) {
my $s_obj =
$self->cache->get_by_key( "${type}s_by_id", 'source',
$e->source );
my $t_obj =
$self->cache->get_by_key( "${type}s_by_id", 'target',
$e->target );
my $key = join( "\t",
$s_obj->stable_id, $s_obj->version,
$t_obj->stable_id, $t_obj->version,
$self->mapping_session_id, $type,
$e->score );
$self->add_stable_id_event( 'similarity', $key );
}
}
} ## end foreach my $id ( @{ $scores...})
} ## end foreach my $dbtype ( keys %$mapped)
} ## end sub generate_similarity_events
sub filter_same_gene_transcript_similarities {
my $self = shift;
my $transcript_scores = shift;
# argument checks
unless ($transcript_scores and
$transcript_scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix of transcripts.');
}
# create a new matrix for the filtered entries
my $filtered_scores = Bio::EnsEMBL::IdMapping::ScoredMappingMatrix->new(
-DUMP_PATH => path_append($self->conf->param('basedir'), 'matrix'),
-CACHE_FILE => 'filtered_transcript_scores.ser',
);
# lookup hash for all target transcripts
my %all_targets = map { $_->stable_id => 1 }
values %{ $self->cache->get_by_name("transcripts_by_id", 'target') };
my $i = 0;
foreach my $e (@{ $transcript_scores->get_all_Entries }) {
my $s_tr = $self->cache->get_by_key('transcripts_by_id', 'source',
$e->source);
my $s_gene = $self->cache->get_by_key('genes_by_transcript_id', 'source',
$e->source);
my $t_gene = $self->cache->get_by_key('genes_by_transcript_id', 'target',
$e->target);
# workaround for caching issue: only gene objects in 'genes_by_id' cache
# have a stable ID assigned
#$t_gene = $self->cache->get_by_key('genes_by_id', 'target', $t_gene->id);
#$self->logger->debug("xxx ".join(":", $s_tr->stable_id, $s_gene->stable_id,
# $t_gene->stable_id)."\n");
# skip if source and target transcript are in same gene, BUT keep events for
# deleted transcripts
if (($s_gene->stable_id eq $t_gene->stable_id) and
$all_targets{$s_tr->stable_id}) {
$i++;
next;
}
$filtered_scores->add_Entry($e);
}
$self->logger->debug("Skipped $i same gene transcript mappings.\n");
return $filtered_scores;
}
sub generate_translation_similarity_events {
my $self = shift;
my $mappings = shift;
my $transcript_scores = shift;
# argument checks
unless ($mappings and
$mappings->isa('Bio::EnsEMBL::IdMapping::MappingList')) {
throw('Need a gene Bio::EnsEMBL::IdMapping::MappingList.');
}
unless ($transcript_scores and
$transcript_scores->isa('Bio::EnsEMBL::IdMapping::ScoredMappingMatrix')) {
throw('Need a Bio::EnsEMBL::IdMapping::ScoredMappingMatrix.');
}
# create a fake translation scoring matrix
my $translation_scores = Bio::EnsEMBL::IdMapping::ScoredMappingMatrix->new(
-DUMP_PATH => path_append($self->conf->param('basedir'), 'matrix'),
-CACHE_FILE => 'translation_scores.ser',
);
foreach my $e (@{ $transcript_scores->get_all_Entries }) {
my $s_tl = $self->cache->get_by_key('transcripts_by_id', 'source',
$e->source)->translation;
my $t_tl = $self->cache->get_by_key('transcripts_by_id', 'target',
$e->target)->translation;
# add an entry to the translation scoring matrix using the score of the
# corresponding transcripts
if ($s_tl and $t_tl) {
$translation_scores->add_score($s_tl->id, $t_tl->id, $e->score);
}
}
# now generate similarity events using this fake scoring matrix
$self->generate_similarity_events($mappings, $translation_scores,
'translation');
}
sub write_stable_ids_to_file {
my $self = shift;
my $type = shift;
my $all_targets = shift;
$self->logger->info("Writing ${type} stable IDs to file...\n");
my $fh = $self->get_filehandle("${type}_stable_id.txt", 'tables');
my @sorted_targets = map { $all_targets->{$_} } sort { $a <=> $b }
keys %$all_targets;
foreach my $obj (@sorted_targets) {
# check for missing created and modified dates
my $created_date = $obj->created_date;
unless ($created_date) {
#$self->logger->debug("Missing created_date for target ".
# $obj->to_string."\n", 1);
$created_date = $self->mapping_session_date;
}
my $modified_date = $obj->modified_date;
unless ($modified_date) {
#$self->logger->debug("Missing modified_date for target ".
# $obj->to_string."\n", 1);
$modified_date = $self->mapping_session_date;
}
my $row = join("\t",
$obj->id,
$obj->stable_id,
$obj->version,
strftime("%Y-%m-%d %T", localtime($created_date)),
strftime("%Y-%m-%d %T", localtime($modified_date)),
);
print $fh "$row\n";
}
close($fh);
$self->logger->info("Done writing ".scalar(@sorted_targets)." entries.\n\n");
}
sub generate_mapping_stats {
my $self = shift;
my $type = shift;
my $stats = shift;
my $result = ucfirst($type)." mapping results:\n\n";
my $fmt1 = "%-10s%-10s%-10s%-10s\n";
my $fmt2 = "%-10s%6.0f %6.0f %4.2f%%\n";
$result .= sprintf($fmt1, qw(TYPE MAPPED LOST PERCENTAGE));
$result .= ('-'x40)."\n";
my $mapped_total = $stats->{'mapped_known'} + $stats->{'mapped_novel'};
my $lost_total = $stats->{'lost_known'} + $stats->{'lost_novel'};
my $known_total = $stats->{'mapped_known'} + $stats->{'lost_known'};
my $novel_total = $stats->{'mapped_novel'} + $stats->{'lost_novel'};
# no split into known and novel for exons
unless ( $type eq 'exon' ) {
$result .= sprintf( $fmt2,
'known',
$stats->{'mapped_known'},
$stats->{'lost_known'},
($known_total ? $stats->{'mapped_known'}/$known_total*100 : 0)
);
$result .= sprintf( $fmt2,
'novel',
$stats->{'mapped_novel'},
$stats->{'lost_novel'},
($novel_total ? $stats->{'mapped_novel'}/$novel_total*100 : 0)
);
} ## end unless ( $type eq 'exon' )
$result .= sprintf($fmt2, 'total', $mapped_total, $lost_total,
$mapped_total/($known_total + $novel_total)*100);
# log result
$self->logger->info($result."\n");
# write result to file
my $fh = $self->get_filehandle("${type}_mapping_stats.txt", 'stats');
print $fh $result;
close($fh);
}
sub dump_debug_mappings {
my $self = shift;
foreach my $type (keys %debug_mappings) {
$self->logger->debug("Writing $type mappings to debug/${type}_mappings.txt...\n");
my $fh = $self->get_filehandle("${type}_mappings.txt", 'debug');
foreach my $row (@{ $debug_mappings{$type} }) {
print $fh join("\t", @$row);
print $fh "\n";
}
close($fh);
$self->logger->debug("Done.\n");
}
}
sub write_stable_id_events {
my $self = shift;
my $event_type = shift;
throw("Need an event type (new|similarity).") unless ($event_type);
$self->logger->debug("Writing $event_type stable_id_events to file...\n");
my $fh = $self->get_filehandle("stable_id_event_${event_type}.txt", 'tables');
my $i = 0;
foreach my $event (@{ $self->get_all_stable_id_events($event_type) }) {
print $fh "$event\n";
$i++;
}
close($fh);
$self->logger->debug("Done writing $i entries.\n");
}
sub add_stable_id_event {
my ($self, $type, $event) = @_;
# argument check
throw("Need an event type (new|similarity).") unless ($type);
$self->{'stable_id_events'}->{$type}->{$event} = 1;
}
sub get_all_stable_id_events {
my ($self, $type) = @_;
# argument check
throw("Need an event type (new|similarity).") unless ($type);
return [ keys %{ $self->{'stable_id_events'}->{$type} } ];
}
sub mapping_session_id {
my $self = shift;
$self->{'_mapping_session_id'} = shift if (@_);
return $self->{'_mapping_session_id'};
}
sub mapping_session_date {
my $self = shift;
$self->{'_mapping_session_date'} = shift if (@_);
return $self->{'_mapping_session_date'};
}
sub mapping_session_date_fmt {
my $self = shift;
$self->{'_mapping_session_date_fmt'} = shift if (@_);
return $self->{'_mapping_session_date_fmt'};
}
sub stable_id_generator {
my $self = shift;
$self->{'_stable_id_generator'} = shift if (@_);
return $self->{'_stable_id_generator'};
}
1;
| danstaines/ensembl | modules/Bio/EnsEMBL/IdMapping/StableIdMapper.pm | Perl | apache-2.0 | 21,342 |
#
# 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::cisco::asa::snmp::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
%{$self->{modes}} = (
'cpu' => 'centreon::common::cisco::standard::snmp::mode::cpu',
'failover' => 'network::cisco::asa::snmp::mode::failover',
'interfaces' => 'snmp_standard::mode::interfaces',
'ipsec-tunnel' => 'centreon::common::cisco::standard::snmp::mode::ipsectunnel',
'list-interfaces' => 'snmp_standard::mode::listinterfaces',
'memory' => 'centreon::common::cisco::standard::snmp::mode::memory',
'sensors' => 'snmp_standard::mode::entity',
'sessions' => 'centreon::common::cisco::standard::snmp::mode::sessions',
);
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Cisco ASA in SNMP.
!!! Be careful: Cisco ASA had an internal SNMP buffer of 512B. Use --subsetleef=20 (or lower) option !!!
=cut
| Tpo76/centreon-plugins | network/cisco/asa/snmp/plugin.pm | Perl | apache-2.0 | 1,897 |
package WinWorkspaceBase;
# ************************************************************
# Description : A Windows base module for Workspace Creators
# Author : Chad Elliott
# Create Date : 2/26/2007
# $Id: WinWorkspaceBase.pm 2035 2011-10-06 15:05:21Z johnnyw $
# ************************************************************
# ************************************************************
# Pragmas
# ************************************************************
use strict;
use WinPropertyBase;
use vars qw(@ISA);
@ISA = qw(WinPropertyBase);
# ************************************************************
# Subroutine Section
# ************************************************************
sub crlf {
return $_[0]->windows_crlf();
}
sub convert_slashes {
#my $self = shift;
return 1;
}
sub case_insensitive {
#my $self = shift;
return 1;
}
1;
| batmancn/TinySDNController | ACE_wrappers/MPC/modules/WinWorkspaceBase.pm | Perl | apache-2.0 | 874 |
package Paws::Route53::ListTrafficPolicyInstancesResponse;
use Moose;
has HostedZoneIdMarker => (is => 'ro', isa => 'Str');
has IsTruncated => (is => 'ro', isa => 'Bool', required => 1);
has MaxItems => (is => 'ro', isa => 'Str', required => 1);
has TrafficPolicyInstanceNameMarker => (is => 'ro', isa => 'Str');
has TrafficPolicyInstances => (is => 'ro', isa => 'ArrayRef[Paws::Route53::TrafficPolicyInstance]', required => 1);
has TrafficPolicyInstanceTypeMarker => (is => 'ro', isa => 'Str');
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::Route53::ListTrafficPolicyInstancesResponse
=head1 ATTRIBUTES
=head2 HostedZoneIdMarker => Str
If C<IsTruncated> is C<true>, C<HostedZoneIdMarker> is the ID of the
hosted zone of the first traffic policy instance that Amazon Route 53
will return if you submit another C<ListTrafficPolicyInstances>
request.
=head2 B<REQUIRED> IsTruncated => Bool
A flag that indicates whether there are more traffic policy instances
to be listed. If the response was truncated, you can get more traffic
policy instances by calling C<ListTrafficPolicyInstances> again and
specifying the values of the C<HostedZoneIdMarker>,
C<TrafficPolicyInstanceNameMarker>, and
C<TrafficPolicyInstanceTypeMarker> in the corresponding request
parameters.
=head2 B<REQUIRED> MaxItems => Str
The value that you specified for the C<MaxItems> parameter in the call
to C<ListTrafficPolicyInstances> that produced the current response.
=head2 TrafficPolicyInstanceNameMarker => Str
If C<IsTruncated> is C<true>, C<TrafficPolicyInstanceNameMarker> is the
name of the first traffic policy instance that Amazon Route 53 will
return if you submit another C<ListTrafficPolicyInstances> request.
=head2 B<REQUIRED> TrafficPolicyInstances => ArrayRef[L<Paws::Route53::TrafficPolicyInstance>]
A list that contains one C<TrafficPolicyInstance> element for each
traffic policy instance that matches the elements in the request.
=head2 TrafficPolicyInstanceTypeMarker => Str
If C<IsTruncated> is C<true>, C<TrafficPolicyInstanceTypeMarker> is the
DNS type of the resource record sets that are associated with the first
traffic policy instance that Amazon Route 53 will return if you submit
another C<ListTrafficPolicyInstances> request.
Valid values are: C<"SOA">, C<"A">, C<"TXT">, C<"NS">, C<"CNAME">, C<"MX">, C<"NAPTR">, C<"PTR">, C<"SRV">, C<"SPF">, C<"AAAA">, C<"CAA">
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/Route53/ListTrafficPolicyInstancesResponse.pm | Perl | apache-2.0 | 2,480 |
=pod
=head1 NAME
verify - Utility to verify certificates
=head1 SYNOPSIS
B<openssl> B<verify>
[B<-help>]
[B<-CAfile file>]
[B<-CApath directory>]
[B<-no-CAfile>]
[B<-no-CApath>]
[B<-allow_proxy_certs>]
[B<-attime timestamp>]
[B<-check_ss_sig>]
[B<-CRLfile file>]
[B<-crl_download>]
[B<-crl_check>]
[B<-crl_check_all>]
[B<-engine id>]
[B<-explicit_policy>]
[B<-extended_crl>]
[B<-ignore_critical>]
[B<-inhibit_any>]
[B<-inhibit_map>]
[B<-no_check_time>]
[B<-partial_chain>]
[B<-policy arg>]
[B<-policy_check>]
[B<-policy_print>]
[B<-purpose purpose>]
[B<-suiteB_128>]
[B<-suiteB_128_only>]
[B<-suiteB_192>]
[B<-trusted_first>]
[B<-no_alt_chains>]
[B<-untrusted file>]
[B<-trusted file>]
[B<-use_deltas>]
[B<-verbose>]
[B<-auth_level level>]
[B<-verify_depth num>]
[B<-verify_email email>]
[B<-verify_hostname hostname>]
[B<-verify_ip ip>]
[B<-verify_name name>]
[B<-x509_strict>]
[B<-show_chain>]
[B<->]
[certificates]
=head1 DESCRIPTION
The B<verify> command verifies certificate chains.
=head1 OPTIONS
=over 4
=item B<-help>
Print out a usage message.
=item B<-CAfile file>
A B<file> of trusted certificates.
The file should contain one or more certificates in PEM format.
=item B<-CApath directory>
A directory of trusted certificates. The certificates should have names
of the form: hash.0 or have symbolic links to them of this
form ("hash" is the hashed certificate subject name: see the B<-hash> option
of the B<x509> utility). Under Unix the B<c_rehash> script will automatically
create symbolic links to a directory of certificates.
=item B<-no-CAfile>
Do not load the trusted CA certificates from the default file location
=item B<-no-CApath>
Do not load the trusted CA certificates from the default directory location
=item B<-allow_proxy_certs>
Allow the verification of proxy certificates
=item B<-attime timestamp>
Perform validation checks using time specified by B<timestamp> and not
current system time. B<timestamp> is the number of seconds since
01.01.1970 (UNIX time).
=item B<-check_ss_sig>
Verify the signature on the self-signed root CA. This is disabled by default
because it doesn't add any security.
=item B<-CRLfile file>
The B<file> should contain one or more CRLs in PEM format.
This option can be specified more than once to include CRLs from multiple
B<files>.
=item B<-crl_download>
Attempt to download CRL information for this certificate.
=item B<-crl_check>
Checks end entity certificate validity by attempting to look up a valid CRL.
If a valid CRL cannot be found an error occurs.
=item B<-crl_check_all>
Checks the validity of B<all> certificates in the chain by attempting
to look up valid CRLs.
=item B<-engine id>
Specifying an engine B<id> will cause L<verify(1)> to attempt to load the
specified engine.
The engine will then be set as the default for all its supported algorithms.
If you want to load certificates or CRLs that require engine support via any of
the B<-trusted>, B<-untrusted> or B<-CRLfile> options, the B<-engine> option
must be specified before those options.
=item B<-explicit_policy>
Set policy variable require-explicit-policy (see RFC5280).
=item B<-extended_crl>
Enable extended CRL features such as indirect CRLs and alternate CRL
signing keys.
=item B<-ignore_critical>
Normally if an unhandled critical extension is present which is not
supported by OpenSSL the certificate is rejected (as required by RFC5280).
If this option is set critical extensions are ignored.
=item B<-inhibit_any>
Set policy variable inhibit-any-policy (see RFC5280).
=item B<-inhibit_map>
Set policy variable inhibit-policy-mapping (see RFC5280).
=item B<-no_check_time>
This option suppresses checking the validity period of certificates and CRLs
against the current time. If option B<-attime timestamp> is used to specify
a verification time, the check is not suppressed.
=item B<-partial_chain>
Allow verification to succeed even if a I<complete> chain cannot be built to a
self-signed trust-anchor, provided it is possible to construct a chain to a
trusted certificate that might not be self-signed.
=item B<-policy arg>
Enable policy processing and add B<arg> to the user-initial-policy-set (see
RFC5280). The policy B<arg> can be an object name an OID in numeric form.
This argument can appear more than once.
=item B<-policy_check>
Enables certificate policy processing.
=item B<-policy_print>
Print out diagnostics related to policy processing.
=item B<-purpose purpose>
The intended use for the certificate. If this option is not specified,
B<verify> will not consider certificate purpose during chain verification.
Currently accepted uses are B<sslclient>, B<sslserver>, B<nssslserver>,
B<smimesign>, B<smimeencrypt>. See the B<VERIFY OPERATION> section for more
information.
=item B<-suiteB_128_only>, B<-suiteB_128>, B<-suiteB_192>
enable the Suite B mode operation at 128 bit Level of Security, 128 bit or
192 bit, or only 192 bit Level of Security respectively.
See RFC6460 for details. In particular the supported signature algorithms are
reduced to support only ECDSA and SHA256 or SHA384 and only the elliptic curves
P-256 and P-384.
=item B<-trusted_first>
When constructing the certificate chain, use the trusted certificates specified
via B<-CAfile>, B<-CApath> or B<-trusted> before any certificates specified via
B<-untrusted>.
This can be useful in environments with Bridge or Cross-Certified CAs.
As of OpenSSL 1.1.0 this option is on by default and cannot be disabled.
=item B<-no_alt_chains>
By default, unless B<-trusted_first> is specified, when building a certificate
chain, if the first certificate chain found is not trusted, then OpenSSL will
attempt to replace untrusted issuer certificates with certificates from the
trust store to see if an alternative chain can be found that is trusted.
As of OpenSSL 1.1.0, with B<-trusted_first> always on, this option has no
effect.
=item B<-untrusted file>
A B<file> of additional untrusted certificates (intermediate issuer CAs) used
to construct a certificate chain from the subject certificate to a trust-anchor.
The B<file> should contain one or more certificates in PEM format.
This option can be specified more than once to include untrusted certificates
from multiple B<files>.
=item B<-trusted file>
A B<file> of trusted certificates, which must be self-signed, unless the
B<-partial_chain> option is specified.
The B<file> contains one or more certificates in PEM format.
With this option, no additional (e.g., default) certificate lists are
consulted.
That is, the only trust-anchors are those listed in B<file>.
This option can be specified more than once to include trusted certificates
from multiple B<files>.
This option implies the B<-no-CAfile> and B<-no-CApath> options.
This option cannot be used in combination with either of the B<-CAfile> or
B<-CApath> options.
=item B<-use_deltas>
Enable support for delta CRLs.
=item B<-verbose>
Print extra information about the operations being performed.
=item B<-auth_level level>
Set the certificate chain authentication security level to B<level>.
The authentication security level determines the acceptable signature and
public key strength when verifying certificate chains.
For a certificate chain to validate, the public keys of all the certificates
must meet the specified security B<level>.
The signature algorithm security level is enforced for all the certificates in
the chain except for the chain's I<trust anchor>, which is either directly
trusted or validated by means other than its signature.
See L<SSL_CTX_set_security_level(3)> for the definitions of the available
levels.
The default security level is -1, or "not set".
At security level 0 or lower all algorithms are acceptable.
Security level 1 requires at least 80-bit-equivalent security and is broadly
interoperable, though it will, for example, reject MD5 signatures or RSA keys
shorter than 1024 bits.
=item B<-verify_depth num>
Limit the certificate chain to B<num> intermediate CA certificates.
A maximal depth chain can have up to B<num+2> certificates, since neither the
end-entity certificate nor the trust-anchor certificate count against the
B<-verify_depth> limit.
=item B<-verify_email email>
Verify if the B<email> matches the email address in Subject Alternative Name or
the email in the subject Distinguished Name.
=item B<-verify_hostname hostname>
Verify if the B<hostname> matches DNS name in Subject Alternative Name or
Common Name in the subject certificate.
=item B<-verify_ip ip>
Verify if the B<ip> matches the IP address in Subject Alternative Name of
the subject certificate.
=item B<-verify_name name>
Use default verification policies like trust model and required certificate
policies identified by B<name>.
The trust model determines which auxiliary trust or reject OIDs are applicable
to verifying the given certificate chain.
See the B<-addtrust> and B<-addreject> options of the L<x509(1)> command-line
utility.
Supported policy names include: B<default>, B<pkcs7>, B<smime_sign>,
B<ssl_client>, B<ssl_server>.
These mimics the combinations of purpose and trust settings used in SSL, CMS
and S/MIME.
As of OpenSSL 1.1.0, the trust model is inferred from the purpose when not
specified, so the B<-verify_name> options are functionally equivalent to the
corresponding B<-purpose> settings.
=item B<-x509_strict>
For strict X.509 compliance, disable non-compliant workarounds for broken
certificates.
=item B<-show_chain>
Display information about the certificate chain that has been built (if
successful). Certificates in the chain that came from the untrusted list will be
flagged as "untrusted".
=item B<->
Indicates the last option. All arguments following this are assumed to be
certificate files. This is useful if the first certificate filename begins
with a B<->.
=item B<certificates>
One or more certificates to verify. If no certificates are given, B<verify>
will attempt to read a certificate from standard input. Certificates must be
in PEM format.
=back
=head1 VERIFY OPERATION
The B<verify> program uses the same functions as the internal SSL and S/MIME
verification, therefore this description applies to these verify operations
too.
There is one crucial difference between the verify operations performed
by the B<verify> program: wherever possible an attempt is made to continue
after an error whereas normally the verify operation would halt on the
first error. This allows all the problems with a certificate chain to be
determined.
The verify operation consists of a number of separate steps.
Firstly a certificate chain is built up starting from the supplied certificate
and ending in the root CA.
It is an error if the whole chain cannot be built up.
The chain is built up by looking up the issuers certificate of the current
certificate.
If a certificate is found which is its own issuer it is assumed to be the root
CA.
The process of 'looking up the issuers certificate' itself involves a number of
steps.
After all certificates whose subject name matches the issuer name of the current
certificate are subject to further tests.
The relevant authority key identifier components of the current certificate (if
present) must match the subject key identifier (if present) and issuer and
serial number of the candidate issuer, in addition the keyUsage extension of
the candidate issuer (if present) must permit certificate signing.
The lookup first looks in the list of untrusted certificates and if no match
is found the remaining lookups are from the trusted certificates. The root CA
is always looked up in the trusted certificate list: if the certificate to
verify is a root certificate then an exact match must be found in the trusted
list.
The second operation is to check every untrusted certificate's extensions for
consistency with the supplied purpose. If the B<-purpose> option is not included
then no checks are done. The supplied or "leaf" certificate must have extensions
compatible with the supplied purpose and all other certificates must also be valid
CA certificates. The precise extensions required are described in more detail in
the B<CERTIFICATE EXTENSIONS> section of the B<x509> utility.
The third operation is to check the trust settings on the root CA. The root CA
should be trusted for the supplied purpose.
For compatibility with previous versions of OpenSSL, a certificate with no
trust settings is considered to be valid for all purposes.
The final operation is to check the validity of the certificate chain. The validity
period is checked against the current system time and the notBefore and notAfter
dates in the certificate. The certificate signatures are also checked at this
point.
If all operations complete successfully then certificate is considered valid. If
any operation fails then the certificate is not valid.
=head1 DIAGNOSTICS
When a verify operation fails the output messages can be somewhat cryptic. The
general form of the error message is:
server.pem: /C=AU/ST=Queensland/O=CryptSoft Pty Ltd/CN=Test CA (1024 bit)
error 24 at 1 depth lookup:invalid CA certificate
The first line contains the name of the certificate being verified followed by
the subject name of the certificate. The second line contains the error number
and the depth. The depth is number of the certificate being verified when a
problem was detected starting with zero for the certificate being verified itself
then 1 for the CA that signed the certificate and so on. Finally a text version
of the error number is presented.
A partial list of the error codes and messages is shown below, this also
includes the name of the error code as defined in the header file x509_vfy.h
Some of the error codes are defined but never returned: these are described
as "unused".
=over 4
=item B<X509_V_OK>
The operation was successful.
=item B<X509_V_ERR_UNSPECIFIED>
Unspecified error; should not happen.
=item B<X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT>
The issuer certificate of a looked up certificate could not be found. This
normally means the list of trusted certificates is not complete.
=item B<X509_V_ERR_UNABLE_TO_GET_CRL>
The CRL of a certificate could not be found.
=item B<X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE>
The certificate signature could not be decrypted. This means that the actual signature value
could not be determined rather than it not matching the expected value, this is only
meaningful for RSA keys.
=item B<X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE>
The CRL signature could not be decrypted: this means that the actual signature value
could not be determined rather than it not matching the expected value. Unused.
=item B<X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY>
The public key in the certificate SubjectPublicKeyInfo could not be read.
=item B<X509_V_ERR_CERT_SIGNATURE_FAILURE>
The signature of the certificate is invalid.
=item B<X509_V_ERR_CRL_SIGNATURE_FAILURE>
The signature of the certificate is invalid.
=item B<X509_V_ERR_CERT_NOT_YET_VALID>
The certificate is not yet valid: the notBefore date is after the current time.
=item B<X509_V_ERR_CERT_HAS_EXPIRED>
The certificate has expired: that is the notAfter date is before the current time.
=item B<X509_V_ERR_CRL_NOT_YET_VALID>
The CRL is not yet valid.
=item B<X509_V_ERR_CRL_HAS_EXPIRED>
The CRL has expired.
=item B<X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD>
The certificate notBefore field contains an invalid time.
=item B<X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD>
The certificate notAfter field contains an invalid time.
=item B<X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD>
The CRL lastUpdate field contains an invalid time.
=item B<X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD>
The CRL nextUpdate field contains an invalid time.
=item B<X509_V_ERR_OUT_OF_MEM>
An error occurred trying to allocate memory. This should never happen.
=item B<X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT>
The passed certificate is self-signed and the same certificate cannot be found in the list of
trusted certificates.
=item B<X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN>
The certificate chain could be built up using the untrusted certificates but the root could not
be found locally.
=item B<X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY>
The issuer certificate could not be found: this occurs if the issuer
certificate of an untrusted certificate cannot be found.
=item B<X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE>
No signatures could be verified because the chain contains only one certificate and it is not
self signed.
=item B<X509_V_ERR_CERT_CHAIN_TOO_LONG>
The certificate chain length is greater than the supplied maximum depth. Unused.
=item B<X509_V_ERR_CERT_REVOKED>
The certificate has been revoked.
=item B<X509_V_ERR_INVALID_CA>
A CA certificate is invalid. Either it is not a CA or its extensions are not consistent
with the supplied purpose.
=item B<X509_V_ERR_PATH_LENGTH_EXCEEDED>
The basicConstraints pathlength parameter has been exceeded.
=item B<X509_V_ERR_INVALID_PURPOSE>
The supplied certificate cannot be used for the specified purpose.
=item B<X509_V_ERR_CERT_UNTRUSTED>
the root CA is not marked as trusted for the specified purpose.
=item B<X509_V_ERR_CERT_REJECTED>
The root CA is marked to reject the specified purpose.
=item B<X509_V_ERR_SUBJECT_ISSUER_MISMATCH>
not used as of OpenSSL 1.1.0 as a result of the deprecation of the
B<-issuer_checks> option.
=item B<X509_V_ERR_AKID_SKID_MISMATCH>
Not used as of OpenSSL 1.1.0 as a result of the deprecation of the
B<-issuer_checks> option.
=item B<X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH>
Not used as of OpenSSL 1.1.0 as a result of the deprecation of the
B<-issuer_checks> option.
=item B<X509_V_ERR_KEYUSAGE_NO_CERTSIGN>
Not used as of OpenSSL 1.1.0 as a result of the deprecation of the
B<-issuer_checks> option.
=item B<X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER>
Unable to get CRL issuer certificate.
=item B<X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION>
Unhandled critical extension.
=item B<X509_V_ERR_KEYUSAGE_NO_CRL_SIGN>
Key usage does not include CRL signing.
=item B<X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION>
Unhandled critical CRL extension.
=item B<X509_V_ERR_INVALID_NON_CA>
Invalid non-CA certificate has CA markings.
=item B<X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED>
Proxy path length constraint exceeded.
=item B<X509_V_ERR_PROXY_SUBJECT_INVALID>
Proxy certificate subject is invalid. It MUST be the same as the issuer
with a single CN component added.
=item B<X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE>
Key usage does not include digital signature.
=item B<X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED>
Proxy certificates not allowed, please use B<-allow_proxy_certs>.
=item B<X509_V_ERR_INVALID_EXTENSION>
Invalid or inconsistent certificate extension.
=item B<X509_V_ERR_INVALID_POLICY_EXTENSION>
Invalid or inconsistent certificate policy extension.
=item B<X509_V_ERR_NO_EXPLICIT_POLICY>
No explicit policy.
=item B<X509_V_ERR_DIFFERENT_CRL_SCOPE>
Different CRL scope.
=item B<X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE>
Unsupported extension feature.
=item B<X509_V_ERR_UNNESTED_RESOURCE>
RFC 3779 resource not subset of parent's resources.
=item B<X509_V_ERR_PERMITTED_VIOLATION>
Permitted subtree violation.
=item B<X509_V_ERR_EXCLUDED_VIOLATION>
Excluded subtree violation.
=item B<X509_V_ERR_SUBTREE_MINMAX>
Name constraints minimum and maximum not supported.
=item B<X509_V_ERR_APPLICATION_VERIFICATION>
Application verification failure. Unused.
=item B<X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE>
Unsupported name constraint type.
=item B<X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX>
Unsupported or invalid name constraint syntax.
=item B<X509_V_ERR_UNSUPPORTED_NAME_SYNTAX>
Unsupported or invalid name syntax.
=item B<X509_V_ERR_CRL_PATH_VALIDATION_ERROR>
CRL path validation error.
=item B<X509_V_ERR_PATH_LOOP>
Path loop.
=item B<X509_V_ERR_SUITE_B_INVALID_VERSION>
Suite B: certificate version invalid.
=item B<X509_V_ERR_SUITE_B_INVALID_ALGORITHM>
Suite B: invalid public key algorithm.
=item B<X509_V_ERR_SUITE_B_INVALID_CURVE>
Suite B: invalid ECC curve.
=item B<X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM>
Suite B: invalid signature algorithm.
=item B<X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED>
Suite B: curve not allowed for this LOS.
=item B<X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256>
Suite B: cannot sign P-384 with P-256.
=item B<X509_V_ERR_HOSTNAME_MISMATCH>
Hostname mismatch.
=item B<X509_V_ERR_EMAIL_MISMATCH>
Email address mismatch.
=item B<X509_V_ERR_IP_ADDRESS_MISMATCH>
IP address mismatch.
=item B<X509_V_ERR_DANE_NO_MATCH>
DANE TLSA authentication is enabled, but no TLSA records matched the
certificate chain.
This error is only possible in L<s_client(1)>.
=back
=head1 BUGS
Although the issuer checks are a considerable improvement over the old technique they still
suffer from limitations in the underlying X509_LOOKUP API. One consequence of this is that
trusted certificates with matching subject name must either appear in a file (as specified by the
B<-CAfile> option) or a directory (as specified by B<-CApath>). If they occur in both then only
the certificates in the file will be recognised.
Previous versions of OpenSSL assume certificates with matching subject name are identical and
mishandled them.
Previous versions of this documentation swapped the meaning of the
B<X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT> and
B<X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY> error codes.
=head1 SEE ALSO
L<x509(1)>
=head1 HISTORY
The B<-show_chain> option was first added to OpenSSL 1.1.0.
The B<-issuer_checks> option is deprecated as of OpenSSL 1.1.0 and
is silently ignored.
=head1 COPYRIGHT
Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| openweave/openweave-core | third_party/openssl/openssl/doc/apps/verify.pod | Perl | apache-2.0 | 22,058 |
#!/usr/bin/perl -w
###############################################################################
# $Id: DataStructure.pm 1675483 2015-04-22 19:59:24Z arkurth $
###############################################################################
# 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::DataStructure - VCL data structure module
=head1 SYNOPSIS
my $data_structure;
eval {
$data_structure = new VCL::DataStructure({request_id => 66, reservation_id => 65});
};
if (my $e = Exception::Class::Base->caught()) {
die $e->message;
}
# Access data by calling method on the DataStructure object
my $user_id = $data_structure->get_user_id;
# Pass the DataStructure object to a module
my $xcat = new VCL::Module::Provisioning::xCAT({data_structure => $data_structure});
...
# Access data from xCAT.pm
# Note: the data() subroutine is implented by Provisioning.pm which xCAT.pm is
# a subclass of
# ->data-> could also be written as ->data()->
my $management_node_id = $self->data->get_management_node_id;
=head1 DESCRIPTION
This module retrieves and stores data from the VCL database. It provides
methods to access the data. The database schema and data structures used by
core VCL code should not be visible to most modules. This module encapsulates
the data and provides an interface to access it.
=cut
##############################################################################
package VCL::DataStructure;
# Specify the lib path using FindBin
use FindBin;
use lib "$FindBin::Bin/..";
# Configure inheritance
use base qw();
# 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 English '-no_match_vars';
use Object::InsideOut;
use List::Util qw(min max);
use YAML;
use Storable qw(dclone);
use VCL::utils;
##############################################################################
=head1 CLASS ATTRIBUTES
=cut
=head3 %SUBROUTINE_MAPPINGS
Data type : hash
Description : %SUBROUTINE_MAPPINGS hash maps subroutine names to hash keys.
It is used by AUTOMETHOD to return the corresponding hash data
when an undefined subroutine is called on a DataStructure object.
=cut
my %SUBROUTINE_MAPPINGS;
$SUBROUTINE_MAPPINGS{blockrequest_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{id}';
$SUBROUTINE_MAPPINGS{blockrequest_name} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{name}';
$SUBROUTINE_MAPPINGS{blockrequest_image_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{imageid}';
$SUBROUTINE_MAPPINGS{blockrequest_number_machines} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{numMachines}';
$SUBROUTINE_MAPPINGS{blockrequest_group_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{groupid}';
$SUBROUTINE_MAPPINGS{blockrequest_group_name} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{groupname}';
$SUBROUTINE_MAPPINGS{blockrequest_repeating} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{repeating}';
$SUBROUTINE_MAPPINGS{blockrequest_owner_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{ownerid}';
$SUBROUTINE_MAPPINGS{blockrequest_management_node_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{managementnodeid}';
$SUBROUTINE_MAPPINGS{blockrequest_expire} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{expireTime}';
$SUBROUTINE_MAPPINGS{blockrequest_processing} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{processing}';
$SUBROUTINE_MAPPINGS{blockrequest_mode} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{MODE}';
$SUBROUTINE_MAPPINGS{blockrequest_blocktimes_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{BLOCKTIMES_ID}';
$SUBROUTINE_MAPPINGS{blockrequest_owner_email} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{owner}{email}';
$SUBROUTINE_MAPPINGS{blockrequest_owner_affiliation_helpaddress} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{owner}{affiliation}{helpaddress}';
$SUBROUTINE_MAPPINGS{blockrequest_image_prettyname} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{image}{prettyname}';
$SUBROUTINE_MAPPINGS{blocktime_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{blockTimes}{BLOCKTIME_ID}{id}';
#$SUBROUTINE_MAPPINGS{blocktime_blockrequest_id} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{blockTimes}{BLOCKTIME_ID}{blockRequestid}';
$SUBROUTINE_MAPPINGS{blocktime_start} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{blockTimes}{BLOCKTIME_ID}{start}';
$SUBROUTINE_MAPPINGS{blocktime_end} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{blockTimes}{BLOCKTIME_ID}{end}';
$SUBROUTINE_MAPPINGS{blocktime_processed} = '$self->blockrequest_data->{BLOCKREQUEST_ID}{blockTimes}{BLOCKTIME_ID}{processed}';
$SUBROUTINE_MAPPINGS{request_check_time} = '$self->request_data->{CHECKTIME}';
$SUBROUTINE_MAPPINGS{request_modified_time} = '$self->request_data->{datemodified}';
$SUBROUTINE_MAPPINGS{request_requested_time} = '$self->request_data->{daterequested}';
$SUBROUTINE_MAPPINGS{request_end_time} = '$self->request_data->{end}';
$SUBROUTINE_MAPPINGS{request_forimaging} = '$self->request_data->{forimaging}';
$SUBROUTINE_MAPPINGS{request_id} = '$self->request_data->{id}';
$SUBROUTINE_MAPPINGS{request_laststate_id} = '$self->request_data->{laststateid}';
$SUBROUTINE_MAPPINGS{request_log_id} = '$self->request_data->{logid}';
$SUBROUTINE_MAPPINGS{request_notice_interval} = '$self->request_data->{NOTICEINTERVAL}';
$SUBROUTINE_MAPPINGS{request_is_cluster_parent} = '$self->request_data->{PARENTIMAGE}';
$SUBROUTINE_MAPPINGS{request_pid} = '$self->request_data->{PID}';
$SUBROUTINE_MAPPINGS{request_ppid} = '$self->request_data->{PPID}';
$SUBROUTINE_MAPPINGS{request_preload} = '$self->request_data->{preload}';
$SUBROUTINE_MAPPINGS{request_preload_only} = '$self->request_data->{PRELOADONLY}';
$SUBROUTINE_MAPPINGS{request_reservation_count} = '$self->request_data->{RESERVATIONCOUNT}';
$SUBROUTINE_MAPPINGS{request_start_time} = '$self->request_data->{start}';
$SUBROUTINE_MAPPINGS{request_duration_epoch} = '$self->request_data->{DURATION}';
$SUBROUTINE_MAPPINGS{request_checkuser} = '$self->request_data->{checkuser}';
#$SUBROUTINE_MAPPINGS{request_stateid} = '$self->request_data->{stateid}';
$SUBROUTINE_MAPPINGS{request_is_cluster_child} = '$self->request_data->{SUBIMAGE}';
$SUBROUTINE_MAPPINGS{request_test} = '$self->request_data->{test}';
$SUBROUTINE_MAPPINGS{request_updated} = '$self->request_data->{UPDATED}';
#$SUBROUTINE_MAPPINGS{request_userid} = '$self->request_data->{userid}';
$SUBROUTINE_MAPPINGS{request_state_name} = '$self->request_data->{state}{name}';
$SUBROUTINE_MAPPINGS{request_laststate_name} = '$self->request_data->{laststate}{name}';
$SUBROUTINE_MAPPINGS{log_userid} = '$self->request_data->{log}{userid}';
$SUBROUTINE_MAPPINGS{log_nowfuture} = '$self->request_data->{log}{nowfuture}';
$SUBROUTINE_MAPPINGS{log_start} = '$self->request_data->{log}{start}';
$SUBROUTINE_MAPPINGS{log_loaded} = '$self->request_data->{log}{loaded}';
$SUBROUTINE_MAPPINGS{log_initialend} = '$self->request_data->{log}{initialend}';
$SUBROUTINE_MAPPINGS{log_finalend} = '$self->request_data->{log}{finalend}';
$SUBROUTINE_MAPPINGS{log_wasavailable} = '$self->request_data->{log}{wasavailable}';
$SUBROUTINE_MAPPINGS{log_ending} = '$self->request_data->{log}{ending}';
$SUBROUTINE_MAPPINGS{log_requestid} = '$self->request_data->{log}{requestid}';
$SUBROUTINE_MAPPINGS{log_computerid} = '$self->request_data->{log}{computerid}';
$SUBROUTINE_MAPPINGS{log_remote_ip} = '$self->request_data->{log}{remoteIP}';
$SUBROUTINE_MAPPINGS{log_imageid} = '$self->request_data->{log}{imageid}';
$SUBROUTINE_MAPPINGS{log_size} = '$self->request_data->{log}{size}';
$SUBROUTINE_MAPPINGS{sublog_id} = '$self->request_data->{reservation}{RESERVATION_ID}{SUBLOG_ID}';
#$SUBROUTINE_MAPPINGS{request_reservationid} = '$self->request_data->{RESERVATIONID}';
$SUBROUTINE_MAPPINGS{reservation_id} = '$self->request_data->{RESERVATIONID}';
#$SUBROUTINE_MAPPINGS{reservation_computerid} = '$self->request_data->{reservation}{RESERVATION_ID}{computerid}';
#$SUBROUTINE_MAPPINGS{reservation_id} = '$self->request_data->{reservation}{RESERVATION_ID}{id}';
#$SUBROUTINE_MAPPINGS{reservation_imageid} = '$self->request_data->{reservation}{RESERVATION_ID}{imageid}';
#$SUBROUTINE_MAPPINGS{reservation_imagerevisionid} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevisionid}';
$SUBROUTINE_MAPPINGS{reservation_lastcheck_time} = '$self->request_data->{reservation}{RESERVATION_ID}{lastcheck}';
$SUBROUTINE_MAPPINGS{reservation_machine_ready} = '$self->request_data->{reservation}{RESERVATION_ID}{MACHINEREADY}';
#$SUBROUTINE_MAPPINGS{reservation_managementnodeid} = '$self->request_data->{reservation}{RESERVATION_ID}{managementnodeid}';
$SUBROUTINE_MAPPINGS{reservation_password} = '$self->request_data->{reservation}{RESERVATION_ID}{pw}';
#$SUBROUTINE_MAPPINGS{reservation_remote_ip} = '$self->request_data->{reservation}{RESERVATION_ID}{remoteIP}';
#$SUBROUTINE_MAPPINGS{reservation_requestid} = '$self->request_data->{reservation}{RESERVATION_ID}{requestid}';
$SUBROUTINE_MAPPINGS{reservation_ready} = '$self->request_data->{reservation}{RESERVATION_ID}{READY}';
$SUBROUTINE_MAPPINGS{reservation_users} = '$self->request_data->{reservation}{RESERVATION_ID}{users}';
$SUBROUTINE_MAPPINGS{computer_data} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}';
$SUBROUTINE_MAPPINGS{computer_current_image_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimageid}';
$SUBROUTINE_MAPPINGS{computer_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{deleted}';
$SUBROUTINE_MAPPINGS{computer_drive_type} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{drivetype}';
$SUBROUTINE_MAPPINGS{computer_dsa} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{dsa}';
$SUBROUTINE_MAPPINGS{computer_dsa_pub} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{dsapub}';
$SUBROUTINE_MAPPINGS{computer_eth0_mac_address} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{eth0macaddress}';
$SUBROUTINE_MAPPINGS{computer_eth1_mac_address} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{eth1macaddress}';
#$SUBROUTINE_MAPPINGS{computer_host} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{host}';
$SUBROUTINE_MAPPINGS{computer_hostname} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{hostname}';
$SUBROUTINE_MAPPINGS{computer_host_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{hostname}';
#$SUBROUTINE_MAPPINGS{computer_hostpub} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{hostpub}';
$SUBROUTINE_MAPPINGS{computer_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{id}';
$SUBROUTINE_MAPPINGS{computer_imagerevision_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{imagerevisionid}';
$SUBROUTINE_MAPPINGS{computer_lastcheck_time} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{lastcheck}';
$SUBROUTINE_MAPPINGS{computer_location} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{location}';
$SUBROUTINE_MAPPINGS{computer_networking_speed} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{network}';
$SUBROUTINE_MAPPINGS{computer_node_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{NODENAME}';
$SUBROUTINE_MAPPINGS{computer_notes} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{notes}';
$SUBROUTINE_MAPPINGS{computer_owner_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{ownerid}';
$SUBROUTINE_MAPPINGS{computer_platform_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{platformid}';
$SUBROUTINE_MAPPINGS{computer_nextimage_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimageid}';
$SUBROUTINE_MAPPINGS{computer_private_ip_address} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{privateIPaddress}';
$SUBROUTINE_MAPPINGS{computer_public_ip_address} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{IPaddress}';
$SUBROUTINE_MAPPINGS{computer_processor_count} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{procnumber}';
$SUBROUTINE_MAPPINGS{computer_processor_speed} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{procspeed}';
$SUBROUTINE_MAPPINGS{computer_ram} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{RAM}';
$SUBROUTINE_MAPPINGS{computer_rsa} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{rsa}';
$SUBROUTINE_MAPPINGS{computer_rsa_pub} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{rsapub}';
$SUBROUTINE_MAPPINGS{computer_schedule_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{scheduleid}';
$SUBROUTINE_MAPPINGS{computer_short_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{SHORTNAME}';
$SUBROUTINE_MAPPINGS{computer_state_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{stateid}';
$SUBROUTINE_MAPPINGS{computer_state_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{state}{name}';
$SUBROUTINE_MAPPINGS{computer_type} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{type}';
$SUBROUTINE_MAPPINGS{computer_provisioning_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioningid}';
$SUBROUTINE_MAPPINGS{computer_vmhost_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhostid}';
$SUBROUTINE_MAPPINGS{computer_provisioning_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioning}{name}';
$SUBROUTINE_MAPPINGS{computer_provisioning_pretty_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioning}{prettyname}';
$SUBROUTINE_MAPPINGS{computer_provisioning_module_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioning}{moduleid}';
$SUBROUTINE_MAPPINGS{computer_provisioning_module_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioning}{module}{name}';
$SUBROUTINE_MAPPINGS{computer_provisioning_module_pretty_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioning}{module}{prettyname}';
$SUBROUTINE_MAPPINGS{computer_provisioning_module_description} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioning}{module}{description}';
$SUBROUTINE_MAPPINGS{computer_provisioning_module_perl_package} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{provisioning}{module}{perlpackage}';
$SUBROUTINE_MAPPINGS{computer_predictive_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictiveid}';
$SUBROUTINE_MAPPINGS{computer_predictive_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictive}{module}{name}';
$SUBROUTINE_MAPPINGS{computer_predictive_pretty_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictive}{module}{prettyname}';
$SUBROUTINE_MAPPINGS{computer_predictive_module_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictive}{module}{id}';
$SUBROUTINE_MAPPINGS{computer_predictive_module_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictive}{module}{name}';
$SUBROUTINE_MAPPINGS{computer_predictive_module_pretty_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictive}{module}{prettyname}';
$SUBROUTINE_MAPPINGS{computer_predictive_module_description} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictive}{module}{description}';
$SUBROUTINE_MAPPINGS{computer_predictive_module_perl_package} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{predictive}{module}{perlpackage}';
$SUBROUTINE_MAPPINGS{nathost_info} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}';
$SUBROUTINE_MAPPINGS{nathost_hostname} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{HOSTNAME}';
$SUBROUTINE_MAPPINGS{nathost_date_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{datedeleted}';
$SUBROUTINE_MAPPINGS{nathost_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{deleted}';
$SUBROUTINE_MAPPINGS{nathost_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{id}';
$SUBROUTINE_MAPPINGS{nathost_public_ip_address} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{publicIPaddress}';
$SUBROUTINE_MAPPINGS{nathost_internal_ip_address} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{internalIPaddress}';
$SUBROUTINE_MAPPINGS{nathost_resource_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{resource}{id}';
$SUBROUTINE_MAPPINGS{nathost_resource_subid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{resource}{subid}';
$SUBROUTINE_MAPPINGS{nathost_resourcetype_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{resource}{resourcetype}{id}';
$SUBROUTINE_MAPPINGS{nathost_resource_type} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nathost}{resource}{resourcetype}{name}';
$SUBROUTINE_MAPPINGS{vmhost_computer_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{computerid}';
$SUBROUTINE_MAPPINGS{vmhost_hostname} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{computer}{hostname}';
$SUBROUTINE_MAPPINGS{vmhost_short_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{computer}{SHORTNAME}';
$SUBROUTINE_MAPPINGS{vmhost_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{id}';
$SUBROUTINE_MAPPINGS{vmhost_image_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{imageid}';
$SUBROUTINE_MAPPINGS{vmhost_image_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{image}{name}';
$SUBROUTINE_MAPPINGS{vmhost_ram} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{computer}{RAM}';
$SUBROUTINE_MAPPINGS{vmhost_state} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{computer}{state}{name}';
#$SUBROUTINE_MAPPINGS{vmhost_type} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{computer}{type}';
$SUBROUTINE_MAPPINGS{vmhost_kernal_nic} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmkernalnic}';
$SUBROUTINE_MAPPINGS{vmhost_vm_limit} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmlimit}';
$SUBROUTINE_MAPPINGS{vmhost_profile_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofileid}';
$SUBROUTINE_MAPPINGS{vmhost_profile_repository_path} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{repositorypath}';
$SUBROUTINE_MAPPINGS{vmhost_profile_repository_imagetype_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{repositoryimagetypeid}';
$SUBROUTINE_MAPPINGS{vmhost_profile_datastore_path} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{datastorepath}';
$SUBROUTINE_MAPPINGS{vmhost_profile_repository_imagetype_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{datastoreimagetypeid}';
#$SUBROUTINE_MAPPINGS{vmhost_profile_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{id}';
$SUBROUTINE_MAPPINGS{vmhost_profile_image_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{imageid}';
$SUBROUTINE_MAPPINGS{vmhost_profile_resource_path} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{resourcepath}';
$SUBROUTINE_MAPPINGS{vmhost_profile_folder_path} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{folderpath}';
$SUBROUTINE_MAPPINGS{vmhost_profile_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{profilename}';
$SUBROUTINE_MAPPINGS{vmhost_profile_virtualswitch0} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{virtualswitch0}';
$SUBROUTINE_MAPPINGS{vmhost_profile_virtualswitch1} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{virtualswitch1}';
$SUBROUTINE_MAPPINGS{vmhost_profile_virtualswitch2} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{virtualswitch2}';
$SUBROUTINE_MAPPINGS{vmhost_profile_virtualswitch3} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{virtualswitch3}';
$SUBROUTINE_MAPPINGS{vmhost_profile_vmdisk} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{vmdisk}';
$SUBROUTINE_MAPPINGS{vmhost_profile_vmpath} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{vmpath}';
$SUBROUTINE_MAPPINGS{vmhost_profile_username} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{username}';
$SUBROUTINE_MAPPINGS{vmhost_profile_password} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{password}';
$SUBROUTINE_MAPPINGS{vmhost_profile_eth0generated} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{eth0generated}';
$SUBROUTINE_MAPPINGS{vmhost_profile_eth1generated} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{vmprofile}{eth1generated}';
$SUBROUTINE_MAPPINGS{vmhost_repository_imagetype_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{repositoryimagetype}{name}';
$SUBROUTINE_MAPPINGS{vmhost_datastore_imagetype_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{vmhost}{datastoreimagetype}{name}';
$SUBROUTINE_MAPPINGS{computer_currentimage_data} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_data} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}';
$SUBROUTINE_MAPPINGS{computer_currentimage_architecture} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{architecture}';
$SUBROUTINE_MAPPINGS{computer_currentimage_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{deleted}';
$SUBROUTINE_MAPPINGS{computer_currentimage_forcheckout} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{forcheckout}';
$SUBROUTINE_MAPPINGS{computer_currentimage_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{id}';
$SUBROUTINE_MAPPINGS{computer_currentimage_imagemetaid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{imagemetaid}';
$SUBROUTINE_MAPPINGS{computer_currentimage_lastupdate} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{lastupdate}';
$SUBROUTINE_MAPPINGS{computer_currentimage_maxconcurrent} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{maxconcurrent}';
$SUBROUTINE_MAPPINGS{computer_currentimage_maxinitialtime} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{maxinitialtime}';
$SUBROUTINE_MAPPINGS{computer_currentimage_minnetwork} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{minnetwork}';
$SUBROUTINE_MAPPINGS{computer_currentimage_minprocnumber} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{minprocnumber}';
$SUBROUTINE_MAPPINGS{computer_currentimage_minprocspeed} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{minprocspeed}';
$SUBROUTINE_MAPPINGS{computer_currentimage_minram} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{minram}';
$SUBROUTINE_MAPPINGS{computer_currentimage_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{imagename}';
$SUBROUTINE_MAPPINGS{computer_currentimage_osid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{OSid}';
$SUBROUTINE_MAPPINGS{computer_currentimage_ownerid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{ownerid}';
$SUBROUTINE_MAPPINGS{computer_currentimage_platformid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{platformid}';
$SUBROUTINE_MAPPINGS{computer_currentimage_prettyname} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{prettyname}';
$SUBROUTINE_MAPPINGS{computer_currentimage_project} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{project}';
$SUBROUTINE_MAPPINGS{computer_currentimage_reloadtime} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{reloadtime}';
$SUBROUTINE_MAPPINGS{computer_currentimage_size} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{size}';
$SUBROUTINE_MAPPINGS{computer_currentimage_test} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{test}';
$SUBROUTINE_MAPPINGS{computer_currentimage_vcld_post_load} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimage}{vcld_post_load}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_comments} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{comments}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_datecreated} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{datecreated}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{deleted}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{id}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_imageid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{imageid}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_imagename} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{imagename}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_production} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{production}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_revision} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{revision}';
$SUBROUTINE_MAPPINGS{computer_currentimagerevision_userid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{currentimagerevision}{userid}';
$SUBROUTINE_MAPPINGS{computer_platform_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{platform}{name}';
$SUBROUTINE_MAPPINGS{computer_nextimage_architecture} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{architecture}';
$SUBROUTINE_MAPPINGS{computer_nextimage_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{deleted}';
$SUBROUTINE_MAPPINGS{computer_nextimage_forcheckout} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{forcheckout}';
$SUBROUTINE_MAPPINGS{computer_nextimage_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{id}';
$SUBROUTINE_MAPPINGS{computer_nextimage_imagemetaid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{imagemetaid}';
$SUBROUTINE_MAPPINGS{computer_nextimage_lastupdate} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{lastupdate}';
$SUBROUTINE_MAPPINGS{computer_nextimage_maxconcurrent} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{maxconcurrent}';
$SUBROUTINE_MAPPINGS{computer_nextimage_maxinitialtime} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{maxinitialtime}';
$SUBROUTINE_MAPPINGS{computer_nextimage_minnetwork} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{minnetwork}';
$SUBROUTINE_MAPPINGS{computer_nextimage_minprocnumber} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{minprocnumber}';
$SUBROUTINE_MAPPINGS{computer_nextimage_minprocspeed} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{minprocspeed}';
$SUBROUTINE_MAPPINGS{computer_nextimage_minram} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{minram}';
$SUBROUTINE_MAPPINGS{computer_nextimage_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{imagename}';
$SUBROUTINE_MAPPINGS{computer_nextimage_osid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{OSid}';
$SUBROUTINE_MAPPINGS{computer_nextimage_ownerid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{ownerid}';
$SUBROUTINE_MAPPINGS{computer_nextimage_platformid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{platformid}';
$SUBROUTINE_MAPPINGS{computer_nextimage_prettyname} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{prettyname}';
$SUBROUTINE_MAPPINGS{computer_nextimage_project} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{project}';
$SUBROUTINE_MAPPINGS{computer_nextimage_reloadtime} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{reloadtime}';
$SUBROUTINE_MAPPINGS{computer_nextimage_size} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{size}';
$SUBROUTINE_MAPPINGS{computer_nextimage_test} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimage}{test}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_comments} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{comments}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_datecreated} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{datecreated}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{deleted}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_id} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{id}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_imageid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{imageid}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_imagename} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{imagename}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_production} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{production}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_revision} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{revision}';
$SUBROUTINE_MAPPINGS{computer_nextimagerevision_userid} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{nextimagerevision}{userid}';
$SUBROUTINE_MAPPINGS{computer_schedule_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{schedule}{name}';
$SUBROUTINE_MAPPINGS{computer_state_name} = '$self->request_data->{reservation}{RESERVATION_ID}{computer}{state}{name}';
$SUBROUTINE_MAPPINGS{image_architecture} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{architecture}';
$SUBROUTINE_MAPPINGS{image_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{deleted}';
$SUBROUTINE_MAPPINGS{image_forcheckout} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{forcheckout}';
$SUBROUTINE_MAPPINGS{image_id} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{id}';
$SUBROUTINE_MAPPINGS{image_identity} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{IDENTITY}';
$SUBROUTINE_MAPPINGS{image_imagemetaid} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemetaid}';
$SUBROUTINE_MAPPINGS{image_lastupdate} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{lastupdate}';
$SUBROUTINE_MAPPINGS{image_maxconcurrent} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{maxconcurrent}';
$SUBROUTINE_MAPPINGS{image_maxinitialtime} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{maxinitialtime}';
$SUBROUTINE_MAPPINGS{image_minnetwork} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{minnetwork}';
$SUBROUTINE_MAPPINGS{image_minprocnumber} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{minprocnumber}';
$SUBROUTINE_MAPPINGS{image_minprocspeed} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{minprocspeed}';
#$SUBROUTINE_MAPPINGS{image_minram} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{minram}';
#$SUBROUTINE_MAPPINGS{image_name} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{name}';
#$SUBROUTINE_MAPPINGS{image_osid} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OSid}';
$SUBROUTINE_MAPPINGS{image_os_id} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OSid}';
$SUBROUTINE_MAPPINGS{image_ownerid} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{ownerid}';
$SUBROUTINE_MAPPINGS{image_platformid} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{platformid}';
$SUBROUTINE_MAPPINGS{image_prettyname} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{prettyname}';
$SUBROUTINE_MAPPINGS{image_project} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{project}';
$SUBROUTINE_MAPPINGS{image_reload_time} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{reloadtime}';
$SUBROUTINE_MAPPINGS{image_settestflag} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{SETTESTFLAG}';
$SUBROUTINE_MAPPINGS{image_size} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{size}';
$SUBROUTINE_MAPPINGS{image_test} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{test}';
$SUBROUTINE_MAPPINGS{image_updateimagename} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{UPDATEIMAGENAME}';
$SUBROUTINE_MAPPINGS{imagemeta_checkuser} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemeta}{checkuser}';
$SUBROUTINE_MAPPINGS{imagemeta_id} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemeta}{id}';
$SUBROUTINE_MAPPINGS{imagemeta_postoption} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemeta}{postoption}';
$SUBROUTINE_MAPPINGS{imagemeta_subimages} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemeta}{subimages}';
$SUBROUTINE_MAPPINGS{imagemeta_sysprep} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemeta}{sysprep}';
$SUBROUTINE_MAPPINGS{imagemeta_rootaccess} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemeta}{rootaccess}';
$SUBROUTINE_MAPPINGS{imagemeta_sethostname} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagemeta}{sethostname}';
$SUBROUTINE_MAPPINGS{image_os_name} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{name}';
$SUBROUTINE_MAPPINGS{image_os_prettyname} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{prettyname}';
$SUBROUTINE_MAPPINGS{image_os_type} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{type}';
$SUBROUTINE_MAPPINGS{image_os_install_type} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{installtype}';
$SUBROUTINE_MAPPINGS{image_os_minram} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{minram}';
$SUBROUTINE_MAPPINGS{image_os_source_path} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{sourcepath}';
$SUBROUTINE_MAPPINGS{image_os_moduleid} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{moduleid}';
$SUBROUTINE_MAPPINGS{image_os_module_name} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{module}{name}';
$SUBROUTINE_MAPPINGS{image_os_module_pretty_name} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{module}{prettyname}';
$SUBROUTINE_MAPPINGS{image_os_module_description} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{module}{description}';
$SUBROUTINE_MAPPINGS{image_os_module_perl_package} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{module}{perlpackage}';
$SUBROUTINE_MAPPINGS{image_os_type_id} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{OStype}{id}';
$SUBROUTINE_MAPPINGS{image_os_type_name} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{OS}{OStype}{name}';
$SUBROUTINE_MAPPINGS{image_platform_name} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{platform}{name}';
$SUBROUTINE_MAPPINGS{imagetype_name} = '$self->request_data->{reservation}{RESERVATION_ID}{image}{imagetype}{name}';
$SUBROUTINE_MAPPINGS{server_request_id} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{id}';
$SUBROUTINE_MAPPINGS{server_request_fixed_ip} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{fixedIP}';
$SUBROUTINE_MAPPINGS{server_request_router} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{router}';
$SUBROUTINE_MAPPINGS{server_request_netmask} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{netmask}';
$SUBROUTINE_MAPPINGS{server_request_dns_servers} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{DNSservers}';
$SUBROUTINE_MAPPINGS{server_request_fixed_mac} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{fixedMAC}';
$SUBROUTINE_MAPPINGS{server_request_admingroupid} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{admingroupid}';
$SUBROUTINE_MAPPINGS{server_request_logingroupid} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{logingroupid}';
$SUBROUTINE_MAPPINGS{server_request_monitored} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{monitored}';
$SUBROUTINE_MAPPINGS{server_allow_users} = '$self->request_data->{reservation}{RESERVATION_ID}{serverrequest}{ALLOW_USERS}';
$SUBROUTINE_MAPPINGS{imagerevision_comments} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{comments}';
$SUBROUTINE_MAPPINGS{imagerevision_date_created} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{datecreated}';
$SUBROUTINE_MAPPINGS{imagerevision_deleted} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{deleted}';
$SUBROUTINE_MAPPINGS{imagerevision_id} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{id}';
$SUBROUTINE_MAPPINGS{imagerevision_imageid} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{imageid}';
#$SUBROUTINE_MAPPINGS{imagerevision_imagename} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{imagename}';
$SUBROUTINE_MAPPINGS{image_name} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{imagename}';
$SUBROUTINE_MAPPINGS{imagerevision_production} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{production}';
$SUBROUTINE_MAPPINGS{imagerevision_revision} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{revision}';
$SUBROUTINE_MAPPINGS{imagerevision_userid} = '$self->request_data->{reservation}{RESERVATION_ID}{imagerevision}{userid}';
$SUBROUTINE_MAPPINGS{connect_methods} = '$self->request_data->{reservation}{RESERVATION_ID}{connect_methods}';
$SUBROUTINE_MAPPINGS{user_adminlevelid} = '$self->request_data->{user}{adminlevelid}';
$SUBROUTINE_MAPPINGS{user_affiliationid} = '$self->request_data->{user}{affiliationid}';
$SUBROUTINE_MAPPINGS{user_audiomode} = '$self->request_data->{user}{audiomode}';
$SUBROUTINE_MAPPINGS{user_bpp} = '$self->request_data->{user}{bpp}';
$SUBROUTINE_MAPPINGS{user_email} = '$self->request_data->{user}{email}';
$SUBROUTINE_MAPPINGS{user_emailnotices} = '$self->request_data->{user}{emailnotices}';
$SUBROUTINE_MAPPINGS{user_firstname} = '$self->request_data->{user}{firstname}';
$SUBROUTINE_MAPPINGS{user_height} = '$self->request_data->{user}{height}';
$SUBROUTINE_MAPPINGS{user_id} = '$self->request_data->{user}{id}';
$SUBROUTINE_MAPPINGS{user_im_id} = '$self->request_data->{user}{IMid}';
$SUBROUTINE_MAPPINGS{user_imtypeid} = '$self->request_data->{user}{IMtypeid}';
$SUBROUTINE_MAPPINGS{user_lastname} = '$self->request_data->{user}{lastname}';
$SUBROUTINE_MAPPINGS{user_lastupdated} = '$self->request_data->{user}{lastupdated}';
$SUBROUTINE_MAPPINGS{user_mapdrives} = '$self->request_data->{user}{mapdrives}';
$SUBROUTINE_MAPPINGS{user_mapprinters} = '$self->request_data->{user}{mapprinters}';
$SUBROUTINE_MAPPINGS{user_mapserial} = '$self->request_data->{user}{mapserial}';
$SUBROUTINE_MAPPINGS{user_preferred_name} = '$self->request_data->{user}{preferredname}';
$SUBROUTINE_MAPPINGS{user_showallgroups} = '$self->request_data->{user}{showallgroups}';
$SUBROUTINE_MAPPINGS{user_standalone} = '$self->request_data->{user}{STANDALONE}';
$SUBROUTINE_MAPPINGS{user_uid} = '$self->request_data->{user}{uid}';
#$SUBROUTINE_MAPPINGS{user_unityid} = '$self->request_data->{user}{unityid}';
$SUBROUTINE_MAPPINGS{user_login_id} = '$self->request_data->{user}{unityid}';
$SUBROUTINE_MAPPINGS{user_width} = '$self->request_data->{user}{width}';
$SUBROUTINE_MAPPINGS{user_adminlevel_name} = '$self->request_data->{user}{adminlevel}{name}';
$SUBROUTINE_MAPPINGS{user_affiliation_dataupdatetext} = '$self->request_data->{user}{affiliation}{dataUpdateText}';
$SUBROUTINE_MAPPINGS{user_affiliation_helpaddress} = '$self->request_data->{user}{affiliation}{helpaddress}';
$SUBROUTINE_MAPPINGS{user_affiliation_name} = '$self->request_data->{user}{affiliation}{name}';
$SUBROUTINE_MAPPINGS{user_affiliation_sitewwwaddress} = '$self->request_data->{user}{affiliation}{sitewwwaddress}';
$SUBROUTINE_MAPPINGS{user_imtype_name} = '$self->request_data->{user}{IMtype}{name}';
$SUBROUTINE_MAPPINGS{user_use_public_keys} = '$self->request_data->{user}{usepublickeys}';
$SUBROUTINE_MAPPINGS{user_ssh_public_keys} = '$self->request_data->{user}{sshpublickeys}';
$SUBROUTINE_MAPPINGS{management_node_id} = '$ENV{management_node_info}{id}';
$SUBROUTINE_MAPPINGS{management_node_ipaddress} = '$ENV{management_node_info}{IPaddress}';
$SUBROUTINE_MAPPINGS{management_node_hostname} = '$ENV{management_node_info}{hostname}';
$SUBROUTINE_MAPPINGS{management_node_ownerid} = '$ENV{management_node_info}{ownerid}';
$SUBROUTINE_MAPPINGS{management_node_stateid} = '$ENV{management_node_info}{stateid}';
$SUBROUTINE_MAPPINGS{management_node_lastcheckin} = '$ENV{management_node_info}{lastcheckin}';
$SUBROUTINE_MAPPINGS{management_node_checkininterval} = '$ENV{management_node_info}{checkininterval}';
$SUBROUTINE_MAPPINGS{management_node_install_path} = '$ENV{management_node_info}{installpath}';
$SUBROUTINE_MAPPINGS{management_node_image_lib_enable} = '$ENV{management_node_info}{imagelibenable}';
$SUBROUTINE_MAPPINGS{management_node_image_lib_group_id} = '$ENV{management_node_info}{imagelibgroupid}';
$SUBROUTINE_MAPPINGS{management_node_image_lib_user} = '$ENV{management_node_info}{imagelibuser}';
$SUBROUTINE_MAPPINGS{management_node_image_lib_key} = '$ENV{management_node_info}{imagelibkey}';
$SUBROUTINE_MAPPINGS{management_node_keys} = '$ENV{management_node_info}{keys}';
$SUBROUTINE_MAPPINGS{management_node_image_lib_partners} = '$ENV{management_node_info}{IMAGELIBPARTNERS}';
$SUBROUTINE_MAPPINGS{management_node_short_name} = '$ENV{management_node_info}{SHORTNAME}';
$SUBROUTINE_MAPPINGS{management_node_state_name} = '$ENV{management_node_info}{state}{name}';
$SUBROUTINE_MAPPINGS{management_node_os_name} = '$ENV{management_node_info}{OSNAME}';
$SUBROUTINE_MAPPINGS{management_node_predictive_module_id} = '$ENV{management_node_info}{predictivemoduleid}';
$SUBROUTINE_MAPPINGS{management_node_ssh_port} = '$ENV{management_node_info}{sshport}';
$SUBROUTINE_MAPPINGS{management_node_public_ip_configuration} = '$ENV{management_node_info}{PUBLIC_IP_CONFIGURATION}';
$SUBROUTINE_MAPPINGS{management_node_public_subnet_mask} = '$ENV{management_node_info}{PUBLIC_SUBNET_MASK}';
#$SUBROUTINE_MAPPINGS{management_node_public_default_gateway} = '$ENV{management_node_info}{PUBLIC_DEFAULT_GATEWAY}';
$SUBROUTINE_MAPPINGS{management_node_public_dns_server} = '$ENV{management_node_info}{PUBLIC_DNS_SERVER}';
$SUBROUTINE_MAPPINGS{management_node_sysadmin_email} = '$ENV{management_node_info}{SYSADMIN_EMAIL}';
$SUBROUTINE_MAPPINGS{management_node_shared_email_box} = '$ENV{management_node_info}{SHARED_EMAIL_BOX}';
$SUBROUTINE_MAPPINGS{management_node_not_standalone} = '$ENV{management_node_info}{NOT_STANDALONE}';
$SUBROUTINE_MAPPINGS{management_node_predictive_module_name} = '$ENV{management_node_info}{predictive_name}';
$SUBROUTINE_MAPPINGS{management_node_predictive_module_pretty_name} = '$ENV{management_node_info}{predictive_prettyname}';
$SUBROUTINE_MAPPINGS{management_node_predictive_module_description} = '$ENV{management_node_info}{predictive_description}';
$SUBROUTINE_MAPPINGS{management_node_predictive_module_perl_package} = '$ENV{management_node_info}{predictive_perlpackage}';
$SUBROUTINE_MAPPINGS{general_inuse_check} = '$ENV{management_node_info}{GENERAL_INUSE_CHECK}';
$SUBROUTINE_MAPPINGS{server_inuse_check} = '$ENV{management_node_info}{SERVER_INUSE_CHECK}';
$SUBROUTINE_MAPPINGS{cluster_inuse_check} = '$ENV{management_node_info}{cluster_INUSE_CHECK}';
$SUBROUTINE_MAPPINGS{subroutine_mappings} = '\%SUBROUTINE_MAPPINGS';
##############################################################################
=head1 OBJECT ATTRIBUTES
=cut
=head3 @request_id
Data type : array of scalars
Description :
=cut
my @request_id : Field : Arg('Name' => 'request_id', 'Default' => 0) : Type(scalar) : Get('Name' => 'request_id', 'Private' => 1);
=head3 @reservation_id
Data type : array of scalars
Description :
=cut
my @reservation_id : Field : Arg('Name' => 'reservation_id', 'Default' => 0) : Type(scalar) : Get('Name' => 'reservation_id', 'Private' => 1);
=head3 @blockrequest_id
Data type : array of scalars
Description :
=cut
my @blockrequest_id : Field : Arg('Name' => 'blockrequest_id') : Type(scalar) : Get('Name' => 'blockrequest_id', 'Private' => 1);
=head3 @blocktime_id
Data type : array of scalars
Description :
=cut
my @blocktime_id : Field : Arg('Name' => 'blocktime_id') : Type(scalar) : Get('Name' => 'blocktime_id', 'Private' => 1);
=head3 @request_data
Data type : array of hashes
Description :
=cut
my @request_data : Field : Deep : Arg('Name' => 'request_data', 'Default' => {}) : Get('Name' => 'request_data', 'Private' => 1) : Set('Name' => 'refresh_request_data', 'Private' => 1);
=head3 @blockrequest_data
Data type : array of hashes
Description :
=cut
my @blockrequest_data : Field : Arg('Name' => 'blockrequest_data', 'Default' => {}) : Get('Name' => 'blockrequest_data', 'Private' => 1);
=head3 @computer_identifier
Data type : array of scalars
Description :
=cut
my @computer_identifier : Field : Arg('Name' => 'computer_identifier') : Type(scalar) : Get('Name' => 'computer_identifier', 'Private' => 1);
=head3 @vmhost_identifier
Data type : array of scalars
Description :
=cut
my @vmhost_identifier : Field : Arg('Name' => 'vmhost_identifier') : Type(scalar) : Get('Name' => 'vmhost_identifier', 'Private' => 1);
=head3 @image_identifier
Data type : array of scalars
Description :
=cut
my @image_identifier : Field : Arg('Name' => 'image_identifier') : Type(scalar) : Get('Name' => 'image_identifier', 'Private' => 1);
=head3 @image_identifier
Data type : array of scalars
Description :
=cut
my @imagerevision_identifier : Field : Arg('Name' => 'imagerevision_identifier') : Type(scalar) : Get('Name' => 'imagerevision_identifier', 'Private' => 1);
=head3 @mn_os
Data type : array of scalars
Description :
=cut
my @mn_os : Field : Arg('Name' => 'mn_os') : Get('Name' => 'mn_os', 'Private' => 1) : Set('Name' => 'set_mn_os');
##############################################################################
=head1 PRIVATE OBJECT METHODS
=cut
=head2 initialize
Parameters : None
Returns : 1 if successful, 0 if failed
Description : This subroutine initializes the DataStructure object. It
retrieves the data for the specified request ID from the
database and adds the data to the object.
=cut
sub _initialize : Init {
my ($self, $args) = @_;
# Get the management node info and add it to %ENV
my $management_node_info = get_management_node_info();
if (!$management_node_info) {
notify($ERRORS{'WARNING'}, 0, "unable to obtain management node info for this node");
return;
}
# Replace the request data with a deep copy if itself
# This creates entirely separate copies in case multiple DataStructure objects are used
# If not deep copied, the separate objects will alter each other's data
$self->refresh_request_data(dclone($self->request_data)) if $self->request_data;
# Set the request and reservation IDs in the request data hash if they are undefined
$self->request_data->{id} = ($self->request_id || 0) if (!defined($self->request_data->{id}));
$self->request_data->{RESERVATIONID} = ($self->reservation_id || 0) if (!defined($self->request_data->{RESERVATIONID}));
if ($self->request_data->{RESERVATIONID} == 0) {
$self->request_data->{reservation}{0}{serverrequest}{id} = 0;
$self->request_data->{forimaging} = 0;
$self->request_data->{state}{name} = "available";
}
my $computer_identifier = $self->computer_identifier;
my $vmhost_identifier = $self->vmhost_identifier;
my $image_identifier = $self->image_identifier;
my $imagerevision_identifier = $self->imagerevision_identifier;
# Get the computer info if the computer_identifier argument was specified and add it to this object
if ($computer_identifier) {
notify($ERRORS{'DEBUG'}, 0, "computer identifier argument was specified, retrieving data for computer: $computer_identifier");
my $computer_info = get_computer_info($computer_identifier, 1);
if (!$computer_info) {
notify($ERRORS{'WARNING'}, 0, "DataStructure object could not be initialized, failed to retrieve data for computer: $computer_identifier");
# Throw an exception because simply returning undefined (return;) does not result in this DataStructure object being undefined
Exception::Class::Base->throw( error => "DataStructure object could not be initialized, failed to retrieve data for computer: $computer_identifier");
return;
}
$self->request_data->{reservation}{$self->reservation_id}{computer} = $computer_info;
}
# Get the VM host info if the $vmhost_identifier argument was specified and add it to this object
if ($vmhost_identifier) {
notify($ERRORS{'DEBUG'}, 0, "VM host identifier argument was specified, retrieving data for VM host: $vmhost_identifier");
my $vmhost_info = get_vmhost_info($vmhost_identifier, 1);
if (!$vmhost_info) {
notify($ERRORS{'WARNING'}, 0, "DataStructure object could not be initialized, failed to retrieve data for VM host: $vmhost_identifier");
# Throw an exception because simply returning undefined (return;) does not result in this DataStructure object being undefined
Exception::Class::Base->throw( error => "DataStructure object could not be initialized, failed to retrieve data for VM host: $vmhost_identifier");
return;
}
$self->request_data->{reservation}{$self->reservation_id}{computer}{vmhost} = $vmhost_info;
}
# If either the computer, image, or imagerevision identifier arguments are specified, retrieve appropriate image and imagerevision data
if (defined($imagerevision_identifier) || defined($image_identifier) || defined($computer_identifier)) {
my $imagerevision_info;
if (defined($imagerevision_identifier)) {
$imagerevision_identifier = 'noimage' if !$imagerevision_identifier;
notify($ERRORS{'DEBUG'}, 0, "imagerevision identifier argument was specified: $imagerevision_identifier, DataStructure object will contain image information for this imagerevision: $imagerevision_identifier");
$imagerevision_info = get_imagerevision_info($imagerevision_identifier);
}
elsif (defined($image_identifier)) {
$image_identifier = 'noimage' if !$image_identifier;
notify($ERRORS{'DEBUG'}, 0, "image identifier argument was specified: $image_identifier, DataStructure object will contain image information for the production imagerevision of this image");
$imagerevision_info = get_production_imagerevision_info($image_identifier);
}
elsif (defined($computer_identifier)) {
my $imagerevision_id = $self->get_computer_imagerevision_id();
if (defined($imagerevision_id)) {
notify($ERRORS{'DEBUG'}, 0, "computer identifier argument was specified ($computer_identifier) but image and imagerevision ID arguments were not, DataStructure object will contain image information for the computer's current imagerevision ID: $imagerevision_id");
if (!$imagerevision_id) {
notify($ERRORS{'DEBUG'}, 0, "computer identifier argument was specified ($computer_identifier) imagerevision_id is set to $imagerevision_id");
my $image_id = $self->get_computer_currentimage_id();
if (defined($image_id)) {
$imagerevision_info = get_production_imagerevision_info($image_id);
}
else {
Exception::Class::Base->throw( error => "DataStructure object could not be initialized, computer's current imagerevision ID could not be retrieved from the current DataStructure data:\n" . format_data($self->get_request_data));
return;
}
}
else {
$imagerevision_info = get_imagerevision_info($imagerevision_id);
}
}
else {
Exception::Class::Base->throw( error => "DataStructure object could not be initialized, computer's current imagerevision ID could not be retrieved from the current DataStructure data:\n" . format_data($self->get_request_data));
return;
}
}
if ($imagerevision_info) {
my $imagerevision_id = $imagerevision_info->{id};
notify($ERRORS{'DEBUG'}, 0, "retrieved data for imagerevision ID: $imagerevision_id");
$self->request_data->{reservation}{$self->reservation_id}{imagerevision} = $imagerevision_info;
}
else {
Exception::Class::Base->throw( error => "DataStructure object could not be initialized, failed to retrieve imagerevision data");
return;
}
my $image_id = $imagerevision_info->{imageid};
if (!defined($image_id)) {
Exception::Class::Base->throw( error => "DataStructure object could not be initialized, failed to retrieve image ID from the imagerevision data:\n" . format_data($imagerevision_info));
return;
}
my $image_info = get_image_info($image_id);
if ($image_info) {
notify($ERRORS{'DEBUG'}, 0, "retrieved data for image ID: $image_id");
$self->request_data->{reservation}{$self->reservation_id}{image} = $image_info;
}
else {
Exception::Class::Base->throw( error => "DataStructure object could not be initialized, failed to retrieve data for image ID: " . $self->image_id);
return;
}
}
return 1;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 automethod
Parameters : None
Returns : Data based on the method name, 0 if method was not handled
Description : This subroutine is automatically invoked when an class method is
called on a DataStructure object but the method isn't explicitly
defined. Function names are mapped to data stored in the request
data hash. This subroutine returns the requested data. An
optional argument can be specified with a value of 1 to suppress
warnings if data is not initialized for the value requested.
=cut
sub _automethod : Automethod {
my $self = shift;
my @args = @_;
my $method_name = $_;
# Make sure the function name begins with get_ or set_
my $mode;
my $data_identifier;
if ($method_name =~ /^(get|set)_(.*)/) {
# $mode stores either 'get' or 'set', data stores the requested data
$mode = $1;
$data_identifier = $2;
}
else {
notify($ERRORS{'WARNING'}, 0, "illegal subroutine name: $method_name");
return sub { };
}
# Determines whether or not warnings are shown if data is not initialized
my $show_warnings = 1;
# If set, make sure an argument was passed
my $set_data;
if ($mode =~ /set/ && defined $args[0]) {
$set_data = $args[0];
}
elsif ($mode =~ /set/) {
notify($ERRORS{'WARNING'}, 0, "data structure $method_name function was called without an argument");
return sub { };
}
elsif ($mode =~ /get/ && defined $args[0] && !$args[0]) {
$show_warnings = 0;
}
# Check if the sub name is defined in the subroutine mappings hash
# Return if it isn't
if (!defined $SUBROUTINE_MAPPINGS{$data_identifier}) {
notify($ERRORS{'WARNING'}, 0, "unsupported subroutine name: $method_name");
return sub { };
}
# Get the hash path out of the subroutine mappings hash
my $hash_path = $SUBROUTINE_MAPPINGS{$data_identifier};
# Replace RESERVATION_ID with the actual reservation ID if it exists in the hash path
my $reservation_id = $self->reservation_id;
$reservation_id = 'undefined' if !defined($reservation_id);
$hash_path =~ s/RESERVATION_ID/$reservation_id/;
# Replace BLOCKREQUEST_ID with the actual blockrequest ID if it exists in the hash path
my $blockrequest_id = $self->blockrequest_id;
$blockrequest_id = 'undefined' if !defined($blockrequest_id);
$hash_path =~ s/BLOCKREQUEST_ID/$blockrequest_id/;
# Replace BLOCKTIME_ID with the actual blocktime ID if it exists in the hash path
my $blocktime_id = $self->blocktime_id;
$blocktime_id = 'undefined' if !defined($blocktime_id);
$hash_path =~ s/BLOCKTIME_ID/$blocktime_id/;
if ($mode =~ /get/) {
# Get the data from the request_data hash
# eval is required in order to interpolate the hash path before retrieving the data
my $key_defined = eval "defined $hash_path";
my $return_value;
# If log or sublog data was requested and not yet populated, attempt to retrieve it
if (!$key_defined && $data_identifier =~ /^(log_|sublog_)/) {
notify($ERRORS{'DEBUG'}, 0, "attempting to retrieve log data, requested data has not been initialized ($data_identifier)");
if ($self->get_log_data()) {
# Log data was retrieved, check if requested data is now populated
if (eval "defined $hash_path") {
$return_value = eval $hash_path;
notify($ERRORS{'DEBUG'}, 0, "log data was retrieved and corresponding data has been initialized for $method_name: $return_value");
}
else {
notify($ERRORS{'WARNING'}, 0, "log data was retrieved but corresponding data has not been initialized for $method_name: $hash_path", $self->request_data) if $show_warnings;
return sub { };
}
}
else {
notify($ERRORS{'WARNING'}, 0, "log data could not be retrieved");
return sub { };
}
}
elsif ($data_identifier =~ /^(management_node)/) {
# Get the management node info
# If no argument was specified get_management_node_info will return data for this management node
my $management_node_info_retrieved = get_management_node_info($args[0]);
unless ($management_node_info_retrieved) {
notify($ERRORS{'WARNING'}, 0, "failed to retrieve data for management node: $args[0]");
return sub { };
}
# The normal reservation management node data is stored in $ENV{management_node_info}{<identifier>}
# We don't want to overwrite this, but want to temporarily store the data retrieved
# This allows the $hash_path mechanism to work without alterations
# Temporarily overwrite this data by using 'local', and set it to the data just retrieved
# Once the current scope is exited, $ENV{management_node_info} will return to its original value
local $ENV{management_node_info} = $management_node_info_retrieved;
# Attempt to retrieve the value from the temporary data: $ENV{management_node_info}{KEY}
$return_value = eval $hash_path;
}
elsif (!$key_defined) {
notify($ERRORS{'WARNING'}, 0, "corresponding data has not been initialized for $method_name: $hash_path", $self->request_data) if $show_warnings;
return sub { };
}
else {
# Just attempt to retrieve the value from the hash path
$return_value = eval $hash_path;
}
if (!defined $return_value) {
if ($show_warnings && $method_name !~ /^(get_management_node_keys)$/) {
notify($ERRORS{'WARNING'}, 0, "corresponding data is undefined for $method_name: $hash_path");
}
return sub { };
}
# Return the data
return sub {$return_value;};
} ## end if ($mode =~ /get/)
elsif ($mode =~ /set/) {
eval $hash_path . ' = $set_data';
# Make sure the value was set in the hash
my $check_value = eval $hash_path;
if ($check_value eq $set_data) {
#notify($ERRORS{'DEBUG'}, 0, "data structure updated, hash path: $hash_path, data identifier: $data_identifier");
return sub {1;};
}
else {
notify($ERRORS{'WARNING'}, 0, "data structure could not be updated, hash path: $hash_path, data identifier: $data_identifier, data:\n" . format_data($set_data));
return sub {0;};
}
} ## end elsif ($mode =~ /set/) [ if ($mode =~ /get/)
} ## end sub _automethod :
#/////////////////////////////////////////////////////////////////////////////
=head2 get_request_data (deprecated)
Parameters : None
Returns : scalar
Description : Returns the request data hash.
=cut
sub get_request_data {
my $self = shift;
return $self->request_data;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 refresh
Parameters : None
Returns :
Description :
=cut
sub refresh {
my $self = shift;
# Save the current state names
my $request_id = $self->get_request_id();
my $request_state_name = $self->get_request_state_name();
my $request_laststate_name = $self->get_request_laststate_name();
# Get the full set of database data for this request
if (my $request_info = get_request_info($request_id)) {
notify($ERRORS{'DEBUG'}, 0, "retrieved current request information from database for request $request_id");
# Set the state names in the newly retrieved hash to their original values
$request_info->{state}{name} = $request_state_name;
$request_info->{laststate}{name} = $request_laststate_name;
# Replace the request data for this DataStructure object
$self->refresh_request_data($request_info);
notify($ERRORS{'DEBUG'}, 0, "updated DataStructure object with current request information from database");
}
else {
notify($ERRORS{'WARNING'}, 0, "could not retrieve current request information from database");
return;
}
return 1;
} ## end sub refresh
#/////////////////////////////////////////////////////////////////////////////
=head2 get_blockrequest_data (deprecated)
Parameters : None
Returns : scalar
Description : Returns the block request data hash.
=cut
sub get_blockrequest_data {
my $self = shift;
# Check to make sure block request ID is defined
if (!$self->blockrequest_id) {
notify($ERRORS{'WARNING'}, 0, "failed to return block request data hash, block request ID is not defined");
return;
}
# Check to make sure block request ID is defined
if (!$self->blockrequest_data) {
notify($ERRORS{'WARNING'}, 0, "block request data hash is not defined");
return;
}
# Check to make sure block request data is defined for the ID
if (!$self->blockrequest_data->{$self->blockrequest_id}) {
notify($ERRORS{'WARNING'}, 0, "block request data hash is not defined for block request $self->blockrequest_id");
return;
}
# Data is there, return it
return $self->blockrequest_data->{$self->blockrequest_id};
} ## end sub get_blockrequest_data
#/////////////////////////////////////////////////////////////////////////////
=head2 get_reservation_count
Parameters : None
Returns : scalar
Description : Returns the number of reservations for the request
associated with this reservation's DataStructure object.
=cut
sub get_reservation_count {
my $self = shift;
my $reservation_count = scalar keys %{$self->request_data->{reservation}};
return $reservation_count;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_reservation_ids
Parameters : none
Returns : array
Description : Returns an array containing all reservation IDs for the current
request sorted from lowest to highest.
=cut
sub get_reservation_ids {
my $self = shift;
my @reservation_ids = sort {$a <=> $b} keys %{$self->request_data->{reservation}};
return @reservation_ids;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_child_reservation_ids
Parameters : none
Returns : array
Description : Returns an array containing all child reservation IDs for the
current request sorted from lowest to highest. The parent
reservation id is omitted.
=cut
sub get_child_reservation_ids {
my $self = shift;
my $parent_reservation_id = $self->get_parent_reservation_id();
my @reservation_ids = $self->get_reservation_ids();
my @child_reservation_ids = grep { $_ ne $parent_reservation_id } @reservation_ids;
return @child_reservation_ids;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_parent_reservation_id
Parameters : none
Returns : integer
Description : Returns the reservation ID for the parent reservation of a
cluster request.
=cut
sub get_parent_reservation_id {
my $self = shift;
# The parent reservation has the lowest ID
return min $self->get_reservation_ids();
}
#/////////////////////////////////////////////////////////////////////////////
=head2 is_parent_reservation
Parameters : None
Returns : scalar, either 1 or 0
Description : This subroutine returns 1 if this is the parent reservation for
the request or if the request has 1 reservation associated with
it. It returns 0 if there are multiple reservations associated
with the request and this reservation is a child.
=cut
sub is_parent_reservation {
my $self = shift;
my $reservation_id = $self->get_reservation_id();
my $parent_reservation_id = $self->get_parent_reservation_id();
if ($reservation_id == $parent_reservation_id) {
notify($ERRORS{'DEBUG'}, 0, "this is the parent reservation");
return 1;
}
else {
notify($ERRORS{'DEBUG'}, 0, "this is a child reservation, parent reservation ID for this request: $parent_reservation_id");
return 0;
}
} ## end sub is_parent_reservation
#/////////////////////////////////////////////////////////////////////////////
=head2 get_reservation_data
Parameters : reservation id
Returns : DataStructure object of specific reservation
Description :
=cut
sub get_reservation_data {
my $self = shift;
my $reservation_id = shift;
# Check to make sure reservation ID was passed
if (!$reservation_id) {
notify($ERRORS{'WARNING'}, 0, "reservation ID was not specified, useless use of this subroutine, returning self");
return $self;
}
# Make sure reservation ID is an integer
if ($reservation_id !~ /^\d+$/) {
notify($ERRORS{'CRITICAL'}, 0, "reservation ID must be an integer, invalid value was passed: $reservation_id");
return;
}
# Check if the reservation ID is the same as the one for this object
if ($reservation_id == $self->reservation_id) {
notify($ERRORS{'WARNING'}, 0, "reservation ID the same as this object's, useless use of this subroutine, returning self");
return $self;
}
# Make sure reservation ID exists for this request
my @reservation_ids = $self->get_reservation_ids();
if (!grep($reservation_id, @reservation_ids)) {
notify($ERRORS{'WARNING'}, 0, "reservation ID does not exist for this request: $reservation_id");
return;
}
# Get a new data structure object
my $sibling_data_structure;
eval {$sibling_data_structure = new VCL::DataStructure({request_data => $self->request_data, reservation_id => $reservation_id});};
if (my $e = Exception::Class::Base->caught()) {
notify($ERRORS{'CRITICAL'}, 0, "unable to create sibling DataStructure object" . $e->message);
return;
}
return $sibling_data_structure;
} ## end sub get_reservation_data
#/////////////////////////////////////////////////////////////////////////////
=head2 set_reservation_remote_ip
Parameters : $remote_ip
Returns : boolean
Description : Updates the reservation.remoteIP value in the database.
=cut
sub set_reservation_remote_ip {
my $self = shift;
my $reservation_id = $self->get_reservation_id();
my $remote_ip = shift;
# Check to make sure reservation ID was passed
if (!$remote_ip) {
notify($ERRORS{'WARNING'}, 0, "remote IP address argument was not specified");
return 0;
}
# Set the current value in the request data hash
$self->request_data->{reservation}{$reservation_id}{remoteIP} = $remote_ip;
my $update_statement = <<EOF;
UPDATE
reservation
SET
remoteIP = '$remote_ip'
WHERE
id = '$reservation_id'
EOF
# Call the database execute subroutine
if (database_execute($update_statement)) {
notify($ERRORS{'OK'}, 0, "remote IP updated to $remote_ip for reservation $reservation_id");
return 1;
}
else {
notify($ERRORS{'CRITICAL'}, 0, "failed to update remote IP to $remote_ip for reservation $reservation_id");
return 0;
}
} ## end sub set_reservation_remote_ip
#/////////////////////////////////////////////////////////////////////////////
=head2 get_reservation_remote_ip
Parameters : None
Returns : string
Description :
=cut
sub get_reservation_remote_ip {
my $self = shift;
my $reservation_id = $self->get_reservation_id();
# Create the select statement
my $select_statement = "
SELECT
remoteIP
FROM
reservation
WHERE
id = $reservation_id
";
# Call the database select subroutine
my @selected_rows = database_select($select_statement);
# Check to make sure 1 row was returned
if (scalar @selected_rows == 0) {
notify($ERRORS{'WARNING'}, 0, "failed to get reservation remote IP for reservation $reservation_id, zero rows were returned from database select");
return;
}
elsif (scalar @selected_rows > 1) {
notify($ERRORS{'WARNING'}, 0, "failed to get reservation remote IP for reservation $reservation_id, " . scalar @selected_rows . " rows were returned from database select");
return;
}
# Get the single returned row
# It contains a hash
my $remote_ip;
# Return 0 if the column isn't set
if (!defined $selected_rows[0]{remoteIP}) {
#notify($ERRORS{'OK'}, 0, "reservation remote IP is not defined");
return 0;
}
# Make sure we return 0 if remote IP is blank
elsif ($selected_rows[0]{remoteIP} eq '') {
#notify($ERRORS{'OK'}, 0, "reservation remote IP is not set");
return 0;
}
# Set the current value in the request data hash
$self->request_data->{reservation}{$reservation_id}{remoteIP} = $selected_rows[0]{remoteIP};
notify($ERRORS{'DEBUG'}, 0, "retrieved remote IP for reservation $reservation_id: $selected_rows[0]{remoteIP}");
return $selected_rows[0]{remoteIP};
} ## end sub get_reservation_remote_ip
#/////////////////////////////////////////////////////////////////////////////
=head2 get_state_name
Parameters : None
Returns : string
Description : Returns either the request state name or 'blockrequest'. Useful
for vcld when make_new_child needs to figure out which module
to call. Without this subroutine, it would need to include
if statement and then call get_request_state_name or hack the
name if it's processing a block request;
=cut
sub get_state_name {
my $self = shift;
if ($self->blockrequest_id) {
return 'blockrequest';
}
elsif ($self->request_data->{state}{name}) {
return $self->request_data->{state}{name};
}
else {
notify($ERRORS{'WARNING'}, 0, "blockrequest ID is not set and request state name is undefined");
return;
}
} ## end sub get_state_name
#/////////////////////////////////////////////////////////////////////////////
=head2 get_next_image_data_structure
Parameters : none
Returns : array
Description : called mainly from reclaim module. Refreshes predictive load
module information from database, loads module and calls next_image.
=cut
sub get_next_image_data_structure {
my $self = shift;
# Get the current image data in case something goes wrong
my $image_name = $self->get_image_name();
my $image_id = $self->get_image_id();
my $imagerevision_id = $self->get_imagerevision_id();
# Assemble an array with the current image information
# This will be returned if the predictive method fails
my @current_image;
if ($image_name && $image_id && $imagerevision_id) {
@current_image = ("reload", $image_name, $image_id, $imagerevision_id);
}
else {
notify($ERRORS{'WARNING'}, 0, "unable to obtain current image information");
@current_image = ();
}
#collect predictive reload information from database.
my $computer_predictive_module_id = $self->get_computer_predictive_module_id();
if (!$computer_predictive_module_id) {
notify($ERRORS{'CRITICAL'}, 0, "unable to obtain management node info for this node, returning current reservation image information");
return @current_image;
}
#update ENV in case other modules need to know
my $management_node_info = get_management_node_info();
$management_node_info->{predictivemoduleid} = $self->get_computer_predictive_module_id();
$management_node_info->{predictive_name} = $self->get_computer_predictive_module_name();
$management_node_info->{predictive_prettyname} = $self->get_computer_predictive_pretty_name();
$management_node_info->{predictive_description} = $self->get_computer_predictive_module_description();
$management_node_info->{predictive_perlpackage} = $self->get_computer_predictive_module_perl_package();
my $predictive_perl_package = $self->get_computer_predictive_module_perl_package();
my @nextimage;
if ($predictive_perl_package) {
notify($ERRORS{'OK'}, 0, "attempting to load predictive loading module: $predictive_perl_package");
eval "use $predictive_perl_package";
if ($EVAL_ERROR) {
notify($ERRORS{'WARNING'}, 0, "$predictive_perl_package module could not be loaded");
notify($ERRORS{'OK'}, 0, "returning current reservation image information");
return @current_image;
}
if (my $predictor = ($predictive_perl_package)->new({data_structure => $self})) {
@nextimage = $predictor->get_next_image();
notify($ERRORS{'OK'}, 0, ref($predictor) . " predictive loading object successfully created");
notify($ERRORS{'OK'}, 0, "predictive loading module retreived image information: @nextimage");
if (scalar(@nextimage) == 4) {
return @nextimage;
}
else {
notify($ERRORS{'WARNING'}, 0, "predictive loading module failed to retrieve image information, returning current reservation image information");
return @current_image;
}
}
else {
notify($ERRORS{'WARNING'}, 0, "predictive loading object could not be created, returning current reservation image information");
return @current_image;
}
} ## end if ($predictive_perl_package)
else {
notify($ERRORS{'OK'}, 0, "predictive loading module not loaded, Perl package is not defined, returning current reservation image information");
return @current_image;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 print_data
Parameters :
Returns :
Description :
=cut
sub print_data {
my $self = shift;
my $request_data = format_data($self->request_data, 'request');
my $management_node_info = format_data($ENV{management_node_info}, 'management_node');
notify($ERRORS{'OK'}, 0, "request data:\n$request_data\n\nmanagement node info:\n$management_node_info");
}
#/////////////////////////////////////////////////////////////////////////////
=head2 print_subroutines
Parameters :
Returns :
Description :
=cut
sub print_subroutines {
my $self = shift;
my $output;
foreach my $mapping_key (sort keys %SUBROUTINE_MAPPINGS) {
my $mapping_value = $SUBROUTINE_MAPPINGS{$mapping_key};
$mapping_value =~ s/^\$self->request_data->/\%request/;
$mapping_value =~ s/^\$ENV{management_node_info}/\%management_node/;
$output .= "get_$mapping_key() : $mapping_value\n";
}
notify($ERRORS{'OK'}, 0, "valid subroutines:\n$output");
} ## end sub print_subroutines
#/////////////////////////////////////////////////////////////////////////////
=head2 get_log_data
Parameters : none
Returns : hash reference
Description : Retrieves data from the log and sublog tables for the log ID
either specified via an argument or the log ID for the
reservation represented by the DataStructure object.
=cut
sub get_log_data {
my $self = shift;
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'WARNING'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
my $current_reservation_id = $self->get_reservation_id();
my $request_id = $self->get_request_id();
my @reservation_ids = $self->get_reservation_ids();
# Retrieve log info for all reservations
my $log_info = get_request_log_info($request_id) || return;
$self->request_data->{log} = $log_info;
# Get a mapping between computer to reservation IDs
# TODO: add sublog.reservationid column, this will no longer be necessary
my $computer_reservation_ids = {};
for my $reservation_id (@reservation_ids) {
my $reservation_data;
if ($reservation_id eq $current_reservation_id) {
$reservation_data = $self;
}
else {
$reservation_data = $self->get_reservation_data($reservation_id);
}
if (!$reservation_data) {
notify($ERRORS{'WARNING'}, 0, "DataStructure object could not be retrieved for reservation $reservation_id");
next;
}
my $reservation_computer_id = $reservation_data->get_computer_id();
if (!$reservation_computer_id) {
notify($ERRORS{'WARNING'}, 0, "computer ID could not be determined for reservation $reservation_id");
next;
}
$computer_reservation_ids->{$reservation_computer_id} = $reservation_id;
}
for my $sublog_id (keys %{$log_info->{sublog}}) {
my $sublog_computer_id = $log_info->{sublog}{$sublog_id}{computerid};
if (!$sublog_computer_id) {
notify($ERRORS{'WARNING'}, 0, "computer ID is not defined for sublog $sublog_id:\n" . format_data($log_info));
next;
}
my $reservation_id = $computer_reservation_ids->{$sublog_computer_id};
if (!$reservation_id) {
notify($ERRORS{'WARNING'}, 0, "computer ID is set to $sublog_computer_id for sublog ID $sublog_id, no reservation assigned to this request is assigned that computer ID");
next;
}
$self->request_data->{reservation}{$reservation_id}{SUBLOG_ID} = $sublog_id;
$self->request_data->{reservation}{$reservation_id}{sublog} = $log_info->{sublog}{$sublog_id};
}
notify($ERRORS{'DEBUG'}, 0, "updated DataStructure object with log and sublog data");
return $self->request_data->{log};
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_computer_private_ip_address
Parameters : $suppress_warning (optional)
Returns : string
Description : Retrieves the private IP address for a computer. If an address is
already stored in the DataStructure object, then that address is
returned. If no address is stored, null is returned and a warning
message is displayed in the log file. This can be suppressed via
the argument.
=cut
sub get_computer_private_ip_address {
my $self = shift;
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'WARNING'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
my $suppress_warning = shift;
my $computer_id = $self->get_computer_id();
my $computer_hostname = $self->get_computer_hostname();
if (!defined($computer_id) || !defined($computer_hostname)) {
notify($ERRORS{'WARNING'}, 0, "computer ID and hostname are not stored in this DataStructure object");
return;
}
# Check if the IP address is already stored
my $data_structure_private_ip_address = $self->request_data->{reservation}{$self->reservation_id}{computer}{privateIPaddress};
my $env_private_ip_address = $ENV{computer_private_ip_address}{$computer_id};
# Check if private IP adddress is stored in %ENV and differs from this object's data
if ($data_structure_private_ip_address) {
if ($env_private_ip_address) {
if ($env_private_ip_address =~ /null/i) {
notify($ERRORS{'DEBUG'}, 0, "private IP address for $computer_hostname ($computer_id) is stored in this object $data_structure_private_ip_address, \%ENV is set to null, deleting private IP address from this object");
delete $self->request_data->{reservation}{$self->reservation_id}{computer}{privateIPaddress};
return;
}
elsif ($data_structure_private_ip_address eq $env_private_ip_address) {
notify($ERRORS{'DEBUG'}, 0, "private IP address for $computer_hostname ($computer_id) stored in this object matches IP address stored in \%ENV: $data_structure_private_ip_address");
}
else {
notify($ERRORS{'DEBUG'}, 0, "private IP address for $computer_hostname ($computer_id) stored in this object $data_structure_private_ip_address does not match IP address stored in \%ENV, updating private IP address stored in this object: $env_private_ip_address");
$self->request_data->{reservation}{$self->reservation_id}{computer}{privateIPaddress} = $env_private_ip_address;
}
return $env_private_ip_address;
}
else {
notify($ERRORS{'DEBUG'}, 0, "returning private IP address of $computer_hostname ($computer_id) already stored in this DataStructure object: $data_structure_private_ip_address");
return $data_structure_private_ip_address;
}
}
else {
if ($env_private_ip_address && $env_private_ip_address !~ /null/i) {
notify($ERRORS{'DEBUG'}, 0, "private IP address for $computer_hostname ($computer_id) is not stored in this object but is stored in \%ENV, setting private IP address in this object: $env_private_ip_address");
$self->request_data->{reservation}{$self->reservation_id}{computer}{privateIPaddress} = $env_private_ip_address;
return $env_private_ip_address;
}
else {
if ($suppress_warning) {
notify($ERRORS{'DEBUG'}, 0, "private IP address of $computer_hostname ($computer_id) is not set in this object");
}
else {
notify($ERRORS{'WARNING'}, 0, "private IP address of $computer_hostname ($computer_id) is not set in this object")
}
return;
}
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 set_computer_private_ip_address
Parameters : $private_ip_address
Returns : boolean
Description : Sets the computer private IP address in the DataStructure. If the
IP address argument is different than the value currently stored
in the DataStructure object, the database is updated.
=cut
sub set_computer_private_ip_address {
my $self = shift;
# Check if subroutine was called as an object method
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
my $private_ip_address_argument = shift;
if (!$private_ip_address_argument) {
notify($ERRORS{'WARNING'}, 0, "computer private IP address argument was not supplied");
return;
}
elsif ($private_ip_address_argument !~ /null/i && !is_valid_ip_address($private_ip_address_argument)) {
notify($ERRORS{'WARNING'}, 0, "computer private IP address argument is not valid: '$private_ip_address_argument'");
return;
}
my $computer_id = $self->get_computer_id();
if (!defined($computer_id)) {
notify($ERRORS{'WARNING'}, 0, "computer ID is not stored in this DataStructure object");
return;
}
my $computer_hostname = $self->get_computer_hostname();
if (!$computer_hostname) {
notify($ERRORS{'WARNING'}, 0, "computer hostname is not stored in this DataStructure object");
return;
}
# Update this DataStructure object
if ($private_ip_address_argument =~ /null/i) {
delete $self->request_data->{reservation}{$self->reservation_id}{computer}{privateIPaddress};
}
else {
$self->request_data->{reservation}{$self->reservation_id}{computer}{privateIPaddress} = $private_ip_address_argument;
}
# Update the database
if ($computer_id && !update_computer_private_ip_address($computer_id, $private_ip_address_argument)) {
notify($ERRORS{'WARNING'}, 0, "failed to update private IP address of $computer_hostname to $private_ip_address_argument, unable to update the database");
return;
}
notify($ERRORS{'DEBUG'}, 0, "private IP address of $computer_hostname set to $private_ip_address_argument");
return 1;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_image_affiliation_name
Parameters : None.
Returns : If successful: string containing affiliation name
If failed: false
Description : This subroutine determines the affiliation name for the image
assigned to the reservation.
The image affiliation is based on the affiliation of the image
owner.
=cut
sub get_image_affiliation_name {
my $self = shift;
# Check if subroutine was called as an object method
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
# Get the image owner id in order to determine the image affiliation
my $image_owner_id = $self->get_image_ownerid();
notify($ERRORS{'DEBUG'}, 0, "image owner id: $image_owner_id");
unless ($image_owner_id) {
notify($ERRORS{'WARNING'}, 0, "unable to determine image owner id in order to determine image affiliation");
return;
}
# Get the data for the user who owns the image
my $image_owner_data = get_user_info($image_owner_id);
unless ($image_owner_data) {
notify($ERRORS{'WARNING'}, 0, "unable to retrieve image owner data in order to determine image affiliation");
return;
}
# Get the affiliation name from the user data hash
my $image_affiliation_name = $image_owner_data->{affiliation}{name};
unless ($image_affiliation_name) {
notify($ERRORS{'WARNING'}, 0, "unable to retrieve image owner affiliation name");
return;
}
return $image_affiliation_name;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_image_affiliation_id
Parameters : None.
Returns : If successful: string containing affiliation id
If failed: false
Description : This subroutine determines the affiliation id for the image
assigned to the reservation.
The image affiliation is based on the affiliation of the image
owner.
=cut
sub get_image_affiliation_id {
my $self = shift;
# Check if subroutine was called as an object method
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
# Get the image owner id in order to determine the image affiliation
my $image_owner_id = $self->get_image_ownerid();
notify($ERRORS{'DEBUG'}, 0, "image owner id: $image_owner_id");
if (!defined($image_owner_id)) {
notify($ERRORS{'WARNING'}, 0, "unable to determine image owner id in order to determine image affiliation");
return;
}
# Get the data for the user who owns the image
my $image_owner_data = get_user_info($image_owner_id);
unless ($image_owner_data) {
notify($ERRORS{'WARNING'}, 0, "unable to retrieve image owner data in order to determine image affiliation");
return;
}
# Get the affiliation id from the user data hash
my $image_affiliation_id = $image_owner_data->{affiliation}{id};
unless ($image_affiliation_id) {
notify($ERRORS{'WARNING'}, 0, "unable to retrieve image owner affiliation id");
return;
}
return $image_affiliation_id;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 is_blockrequest
Parameters : None.
Returns : If DataStructure contains blockrequest data: true
If DataStructure does not contain blockrequest data: false
Description : This subroutine determines whether or not the DataStructure
contains data for a blockrequest.
=cut
sub is_blockrequest {
my $self = shift;
# Check if subroutine was called as an object method
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
# Check if reservation_id has been set, return 1 or 0 based on that
if ($self->blockrequest_id) {
return 1;
}
else {
return 0;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 is_server_request
Parameters : None.
Returns :
Description : This subroutine determines whether or not the DataStructure
contains data for a server request.
=cut
sub is_server_request {
my $self = shift;
# Check if subroutine was called as an object method
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
return $self->get_server_request_id() ? 1 : 0;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_management_node_public_default_gateway
Parameters : None
Returns : If successful: string containing IP address
If failed: false
Description : Returns the management node's default gateway IP address. This
subroutine will return the address configured on the "GATEWAY="
line in the vcld.conf file if configured.
Otherwise it uses the "route -n" command and attempts to
locate a single line beginning with 0.0.0.0.
If it fails to determine the default gateway using the route
command, the dhcpd.conf file is checked for an "option routers"
line containing a valid public IP address.
=cut
sub get_management_node_public_default_gateway {
my $default_gateway;
# Attempt to retrieve the default gateway explicitly configured for this management node
my $management_node_info = get_management_node_info();
if ($management_node_info) {
$default_gateway = $management_node_info->{PUBLIC_DEFAULT_GATEWAY};
if ($default_gateway && is_valid_ip_address($default_gateway)) {
notify($ERRORS{'DEBUG'}, 0, "returning default gateway configured for management node: $default_gateway");
return $default_gateway;
}
}
# Attempt to retrieve the gateway from the route command
my ($route_exit_status, $route_output) = run_command('route -n', 1);
if ($route_output && (my @route_gateway_lines = grep(/^0.0.0.0/, @$route_output))) {
if (scalar @route_gateway_lines == 1) {
($default_gateway) = $route_gateway_lines[0] =~ /^[\d\.]+\s+([\d\.]+)/;
if (is_valid_ip_address($default_gateway)) {
notify($ERRORS{'DEBUG'}, 0, "returning default gateway from route command: $default_gateway");
return $default_gateway;
}
else {
notify($ERRORS{'WARNING'}, 0, "unable to determine default gateway valid IP address from route command output:\n" . join("\n", @route_gateway_lines));
}
}
else {
notify($ERRORS{'WARNING'}, 0, "multiple default gateway lines found in route command output:\n" . join("\n", @route_gateway_lines));
}
}
# Attempt to retrieve the gateway from the "option routers" line in dhcpd.conf
my @dhcpd_conf_lines = read_file_to_array('/etc/dhcpd.conf');
if (@dhcpd_conf_lines) {
my @option_routers_lines = grep(/\s*[^#]\s*option\s+routers/, @dhcpd_conf_lines);
notify($ERRORS{'DEBUG'}, 0, "dhcpd.conf option routers lines:\n" . join("\n", @option_routers_lines));
# Store public IP addresses found on "option routers" lines as hash keys to ignore duplicates
my %public_option_routers_addresses;
# Loop through any "option routers" lines found in dhcpd.conf
for my $option_routers_line (@option_routers_lines) {
# Extract the IP address from the "option routers" line
my ($option_routers_ip) = $option_routers_line =~ /option\s+routers\s+([\d\.]+)/;
# Check if IP address was found, is valid, and is public
if (!$option_routers_ip) {
notify($ERRORS{'DEBUG'}, 0, "option routers line does not contain an IP address: $option_routers_line");
next;
}
if (!is_valid_ip_address($option_routers_ip)) {
notify($ERRORS{'DEBUG'}, 0, "option routers line does not contain a valid IP address: $option_routers_line");
next;
}
if (!is_public_ip_address($option_routers_ip)) {
notify($ERRORS{'DEBUG'}, 0, "option routers line contains a non-public address: $option_routers_line");
next;
}
notify($ERRORS{'DEBUG'}, 0, "public option routers IP address found in dhcpd.conf: $option_routers_ip");
$public_option_routers_addresses{$option_routers_ip} = 1;
}
# Check if only 1 "option routers" line was found containing a valid public IP address
if (scalar keys(%public_option_routers_addresses) == 1) {
my $default_gateway = (keys(%public_option_routers_addresses))[0];
notify($ERRORS{'DEBUG'}, 0, "returning default gateway found in dhcpd.conf: $default_gateway");
return $default_gateway;
}
else {
notify($ERRORS{'DEBUG'}, 0, "multiple public option routers IP addresses found in dhcpd.conf: " . keys(%public_option_routers_addresses));
}
}
else {
notify($ERRORS{'WARNING'}, 0, "unable to retrieve dhcpd.conf contents");
}
return;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_management_node_public_dns_servers
Parameters : None
Returns : If successful: array containing IP addresses
If failed: false
Description : Returns an array containing the addresses of the public DNS
servers configured for the management node.
=cut
sub get_management_node_public_dns_servers {
# Attempt to retrieve the DNS server addresses configured for this management node
my $management_node_info = get_management_node_info();
if (!$management_node_info) {
notify($ERRORS{'WARNING'}, 0, "unable to determine public DNS servers, management node information could not be retrieved");
return;
}
my $dns_address_string = $management_node_info->{PUBLIC_DNS_SERVER};
if (!$dns_address_string) {
notify($ERRORS{'DEBUG'}, 0, "no public DNS server addresses are configured for the management node");
return ();
}
return split(/\s*[,;]\s*/, $dns_address_string);
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_management_node_identity_key_paths
Parameters : None
Returns : If successful: array containing paths to SSH identity keys
If failed: false
Description : Returns an array containing the paths to SSH identity keys
configured for the management node.
=cut
sub get_management_node_identity_key_paths {
my $management_node_info = get_management_node_info();
if (!$management_node_info) {
notify($ERRORS{'WARNING'}, 0, "unable to determine public management node identity key paths, management node information could not be retrieved");
return;
}
my $keys_string = $management_node_info->{keys};
if (!$keys_string) {
notify($ERRORS{'WARNING'}, 0, "no identity key paths are configured for the management node");
return ();
}
return split(/\s*[,;]\s*/, $keys_string);
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_computer_state_name
Parameters : computer name (optional
Returns : String containing state name for a particular computer
Description : Queries database for current computer state and returns the
state name. The database is queried rather than simply returning
the value in the data structure in case the computer state
changed by some other process after the reservation process
began. This is mainly done for safety in case the computer state
gets set to maintenance.
=cut
sub get_computer_state_name {
my $self;
my $argument = shift;
my $computer_name;
# Check if subroutine was called as an object method
if (ref($argument) && $argument->isa('VCL::DataStructure')) {
# Subroutine was called as an object method, check if an argument was specified
$self = $argument;
$argument = shift;
if ($argument) {
# Argument was specified, use this as the computer name
$computer_name = $argument;
}
else {
# Argument was not specified, get the computer short name for this reservation
$computer_name = $self->get_computer_short_name();
}
}
elsif (ref($argument)) {
notify($ERRORS{'WARNING'}, 0, "subroutine was called with an illegal argument type: " . ref($argument));
return;
}
else {
# Subroutine was not called as an object method
$computer_name = $argument;
}
# Make sure the computer name was determined either from an argument or the request data
if (!$computer_name) {
notify($ERRORS{'WARNING'}, 0, "unable to determine computer name from argument or request data");
return;
}
# Create the select statement
my $select_statement = "
SELECT DISTINCT
state.name AS name
FROM
state,
computer
WHERE
computer.stateid = state.id
AND (computer.hostname LIKE '$computer_name.%' OR computer.hostname = '$computer_name')
";
# Call the database select subroutine
# This will return an array of one or more rows based on the select statement
my @selected_rows = database_select($select_statement);
# Check to make sure 1 row was returned
if (scalar @selected_rows == 0) {
notify($ERRORS{'WARNING'}, 0, "zero rows were returned from database select");
return ();
}
elsif (scalar @selected_rows > 1) {
notify($ERRORS{'WARNING'}, 0, scalar @selected_rows . " rows were returned from database select");
return ();
}
# Make sure we return undef if the column wasn't found
if (defined $selected_rows[0]{name}) {
my $computer_state_name = $selected_rows[0]{name};
notify($ERRORS{'DEBUG'}, 0, "retrieved current state of computer $computer_name from the database: $computer_state_name");
$self->set_computer_state_name($computer_state_name);
return $computer_state_name;
}
else {
notify($ERRORS{'WARNING'}, 0, "unable to retrieve current state of computer $computer_name from the database");
return undef;
}
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_reservation_info_string
Parameters : None.
Returns : String
Description : Assembles a string containing reservation information for
debugging purposes.
=cut
sub get_reservation_info_string {
my $self = shift;
# Check if subroutine was called as an object method
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
my $string;
$string .= "management node: " . (defined($_ = $self->get_management_node_hostname(0)) ? $_ : '<undefined>') . "\n";
$string .= "reservation PID: $PID\n";
$string .= "parent vcld PID: " . (defined($_ = getppid()) ? $_ : '<undefined>') . "\n";
my $request_id = $self->get_request_id(0);
if ($request_id) {
$string .= "\n";
$string .= "request ID: $request_id\n";
$string .= "reservation ID: " . (defined($_ = $self->get_reservation_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "request state/laststate: " . (defined($_ = $self->get_request_state_name(0)) ? $_ : '<undefined>') . "/" . (defined($_ = $self->get_request_laststate_name(0)) ? $_ : '<undefined>') . "\n";
$string .= "request start time: " . (defined($_ = $self->get_request_start_time(0)) ? $_ : '<undefined>') . "\n";
$string .= "request end time: " . (defined($_ = $self->get_request_end_time(0)) ? $_ : '<undefined>') . "\n";
$string .= "for imaging: " . (defined($_ = $self->get_request_forimaging(0)) ? ($_ ? 'yes' : 'no') : '<undefined>') . "\n";
$string .= "log ID: " . (defined($_ = $self->get_request_log_id(0)) ? ($_ eq '0' ? 'none' : $_) : '<undefined>') . "\n";
my $reservation_count = $self->get_request_reservation_count(0);
if (defined($reservation_count) && $reservation_count > 1) {
$string .= "cluster reservation: yes\n";
$string .= "reservation count: $reservation_count\n";
$string .= "parent reservation: " . (defined($_ = $self->get_request_is_cluster_parent(0)) ? ($_ ? 'yes' : 'no') : '<undefined>') . "\n";
}
}
my $blockrequest_id = $self->get_blockrequest_id(0);
if ($blockrequest_id) {
$string .= "\n";
$string .= "blockrequest: " . (defined($_ = $self->get_blockrequest_name(0)) ? $_ : '<undefined>') . "\n";
$string .= "block request ID: $blockrequest_id\n";
$string .= "blockrequest image ID: " . (defined($_ = $self->get_blockrequest_image_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "number of machines: " . (defined($_ = $self->get_blockrequest_number_machines(0)) ? $_ : '<undefined>') . "\n";
$string .= "owner ID: " . (defined($_ = $self->get_blockrequest_owner_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "management node ID: " . (defined($_ = $self->get_blockrequest_management_node_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "processing flag: " . (defined($_ = $self->get_blockrequest_processing(0)) ? $_ : '<undefined>') . "\n";
$string .= "mode: " . (defined($_ = $self->get_blockrequest_mode(0)) ? $_ : '<undefined>') . "\n";
$string .= "blocktime ID: " . (defined($_ = $self->get_blocktime_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "blocktime start: " . (defined($_ = $self->get_blocktime_start(0)) ? $_ : '<undefined>') . "\n";
$string .= "blocktime end: " . (defined($_ = $self->get_blocktime_end(0)) ? $_ : '<undefined>') . "\n";
$string .= "blocktime processed flag: " . (defined($_ = $self->get_blocktime_processed(0)) ? $_ : '<undefined>') . "\n";
}
my $computer_id = $self->get_computer_id(0);
if (defined($computer_id)) {
$string .= "\n";
$string .= "computer: " . (defined($_ = $self->get_computer_hostname(0)) ? $_ : '<undefined>') . "\n";
$string .= "computer id: $computer_id\n";
$string .= "computer type: " . (defined($_ = $self->get_computer_type(0)) ? $_ : '<undefined>') . "\n";
$string .= "computer eth0 MAC address: " . (defined($_ = $self->get_computer_eth0_mac_address(0)) ? $_ : '<undefined>') . "\n";
$string .= "computer eth1 MAC address: " . (defined($_ = $self->get_computer_eth1_mac_address(0)) ? $_ : '<undefined>') . "\n";
$string .= "computer private IP address: " . (defined($_ = $self->get_computer_private_ip_address(0)) ? $_ : '<undefined>') . "\n";
$string .= "computer public IP address: " . (defined($_ = $self->get_computer_public_ip_address(0)) ? $_ : '<undefined>') . "\n";
$string .= "computer in block allocation: " . (defined($_ = is_inblockrequest($self->get_computer_id(0))) ? ($_ ? 'yes' : 'no') : '<undefined>') . "\n";
$string .= "provisioning module: " . (defined($_ = $self->get_computer_provisioning_module_perl_package(0)) ? $_ : '<undefined>') . "\n";
if ($self->get_computer_type(0) eq 'virtualmachine') {
$string .= "\n";
$string .= "vm host: " . (defined($_ = $self->get_vmhost_hostname(0)) ? $_ : '<undefined>') . "\n";
$string .= "vm host ID: " . (defined($_ = $self->get_vmhost_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "vm host computer ID: " . (defined($_ = $self->get_vmhost_computer_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "vm profile: " . (defined($_ = $self->get_vmhost_profile_name(0)) ? $_ : '<undefined>') . "\n";
$string .= "vm profile VM path: " . (defined($_ = $self->get_vmhost_profile_vmpath(0)) ? $_ : '<undefined>') . "\n";
$string .= "vm profile repository path: " . (defined($_ = $self->get_vmhost_profile_repository_path(0)) ? $_ : '<undefined>') . "\n";
$string .= "vm profile datastore path: " . (defined($_ = $self->get_vmhost_profile_datastore_path(0)) ? $_ : '<undefined>') . "\n";
$string .= "vm profile disk type: " . (defined($_ = $self->get_vmhost_profile_vmdisk(0)) ? $_ : '<undefined>') . "\n";
}
}
my $image_id = $self->get_image_id(0);
if (defined($image_id)) {
$string .= "\n";
$string .= "image: " . (defined($_ = $self->get_image_name(0)) ? $_ : '<undefined>') . "\n";
$string .= "image display name: " . (defined($_ = $self->get_image_prettyname(0)) ? $_ : '<undefined>') . "\n";
$string .= "image ID: $image_id\n";
$string .= "image revision ID: " . (defined($_ = $self->get_imagerevision_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "image size: " . (defined($_ = $self->get_image_size(0)) ? $_ : '<undefined>') . " MB\n";
$string .= "use Sysprep: " . (defined($_ = $self->get_imagemeta_sysprep(0)) ? ($_ ? 'yes' : 'no') : '<undefined>') . "\n";
$string .= "root access: " . (defined($_ = $self->get_imagemeta_rootaccess(0)) ? ($_ ? 'yes' : 'no') : '<undefined>') . "\n";
$string .= "image owner ID: " . (defined($_ = $self->get_image_ownerid(0)) ? $_ : '<undefined>') . "\n";
$string .= "image owner affiliation: " . (defined($_ = $self->get_image_affiliation_name(0)) ? $_ : '<undefined>') . "\n";
$string .= "image revision date created: " . (defined($_ = $self->get_imagerevision_date_created(0)) ? $_ : '<undefined>') . "\n";
$string .= "image revision production: " . (defined($_ = $self->get_imagerevision_production(0)) ? ($_ ? 'yes' : 'no') : '<undefined>') . "\n";
$string .= "OS module: " . (defined($_ = $self->get_image_os_module_perl_package(0)) ? $_ : '<undefined>') . "\n";
my $imagerevision_comments = $self->get_imagerevision_comments(0);
$string .= "image revision comments: $imagerevision_comments\n" if $imagerevision_comments;
}
my $user_id = $self->get_user_id(0);
if (defined($user_id)) {
$string .= "\n";
$string .= "user: " . (defined($_ = $self->get_user_login_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "user name: " . (defined($_ = $self->get_user_firstname(0)) ? $_ : '<undefined>') . " " . (defined($_ = $self->get_user_lastname(0)) ? $_ : '<undefined>') . "\n";
$string .= "user ID: " . (defined($_ = $self->get_user_id(0)) ? $_ : '<undefined>') . "\n";
$string .= "user affiliation: " . (defined($_ = $self->get_user_affiliation_name(0)) ? $_ : '<undefined>') . "\n";
}
return $string;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_reservation_user_login_ids
Parameters : none
Returns : array
Description : Returns an array containing the reservation user login IDs
(usernames).
=cut
sub get_reservation_user_login_ids {
my $self = shift;
my $reservation_user_info = $self->get_reservation_users();
if (!$reservation_user_info) {
notify($ERRORS{'WARNING'}, 0, "unable to retrieve reservation user login IDs, reservation user info is not populated in the request data");
return;
}
my @reservation_users = map { $reservation_user_info->{$_}{unityid} } keys %$reservation_user_info;
return @reservation_users;
}
#/////////////////////////////////////////////////////////////////////////////
=head2 get_image_minram
Parameters : none
Returns : integer
Description : Returns the larger of the image.minram and OS.minram values.
=cut
sub get_image_minram {
my $self = shift;
# Check if subroutine was called as an object method
unless (ref($self) && $self->isa('VCL::DataStructure')) {
notify($ERRORS{'CRITICAL'}, 0, "subroutine can only be called as a VCL::DataStructure module object method");
return;
}
my $reservation_id = $self->reservation_id;
my $image_minram = $self->request_data->{reservation}{$reservation_id}{image}{minram};
my $os_minram = $self->request_data->{reservation}{$reservation_id}{image}{OS}{minram};
my $minram = max ($image_minram, $os_minram);
#notify($ERRORS{'DEBUG'}, 0, "image minram: $image_minram, OS minram: $os_minram, result: $minram");
return $minram;
}
#/////////////////////////////////////////////////////////////////////////////
1;
__END__
=head1 SEE ALSO
L<http://cwiki.apache.org/VCL/>
=cut
| bq-xiao/apache-vcl | managementnode/lib/VCL/DataStructure.pm | Perl | apache-2.0 | 109,541 |
#
# 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::fritzbox::upnp::mode::system;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold_ng);
use POSIX;
my $unitdiv = { s => 1, w => 604800, d => 86400, h => 3600, m => 60 };
my $unitdiv_long = { s => 'seconds', w => 'weeks', d => 'days', h => 'hours', m => 'minutes' };
sub custom_uptime_perfdata {
my ($self, %options) = @_;
$self->{output}->perfdata_add(
nlabel => $self->{nlabel} . '.' . $unitdiv_long->{ $self->{instance_mode}->{option_results}->{unit} },
unit => $self->{instance_mode}->{option_results}->{unit},
value => floor($self->{result_values}->{uptime} / $unitdiv->{ $self->{instance_mode}->{option_results}->{unit} }),
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{thlabel}),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{thlabel}),
min => 0
);
}
sub custom_uptime_threshold {
my ($self, %options) = @_;
return $self->{perfdata}->threshold_check(
value => floor($self->{result_values}->{uptime} / $unitdiv->{ $self->{instance_mode}->{option_results}->{unit} }),
threshold => [
{ label => 'critical-' . $self->{thlabel}, exit_litteral => 'critical' },
{ label => 'warning-'. $self->{thlabel}, exit_litteral => 'warning' },
{ label => 'unknown-'. $self->{thlabel}, exit_litteral => 'unknown' }
]
);
}
sub custom_status_output {
my ($self, %options) = @_;
return sprintf(
'physical link status is %s and %s is %s',
$self->{result_values}->{link_status},
$self->{result_values}->{wan_access_type},
$self->{result_values}->{connection_status}
);
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'global', type => 0 }
];
$self->{maps_counters}->{global} = [
{
label => 'connection-status',
type => 2,
critical_default => '%{link_status} !~ /^up$/i and %{connection_status} !~ /^connected$/i',
set => {
key_values => [
{ name => 'connection_status' }, { name => 'link_status' }, { name => 'wan_access_type' }
],
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold_ng
}
},
{ label => 'uptime', nlabel => 'system.uptime', set => {
key_values => [ { name => 'uptime' }, { name => 'uptime_human' } ],
output_template => 'uptime: %s',
output_use => 'uptime_human',
closure_custom_perfdata => $self->can('custom_uptime_perfdata'),
closure_custom_threshold_check => $self->can('custom_uptime_threshold')
}
}
];
}
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 => {
'unit:s' => { name => 'unit', default => 's' }
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
if ($self->{option_results}->{unit} eq '' || !defined($unitdiv->{$self->{option_results}->{unit}})) {
$self->{option_results}->{unit} = 's';
}
}
sub manage_selection {
my ($self, %options) = @_;
$self->{global} = {};
my $infos = $options{custom}->request(url => 'WANCommonIFC1', ns => 'WANCommonInterfaceConfig', verb => 'GetCommonLinkProperties');
$self->{global}->{wan_access_type} = $infos->{'s:Body'}->{'u:GetCommonLinkPropertiesResponse'}->{NewWANAccessType};
$self->{global}->{link_status} = $infos->{'s:Body'}->{'u:GetCommonLinkPropertiesResponse'}->{NewPhysicalLinkStatus};
$infos = $options{custom}->request(url => 'WANIPConn1', ns => 'WANIPConnection', verb => 'GetStatusInfo');
$self->{global}->{connection_status} = $infos->{'s:Body'}->{'u:GetStatusInfoResponse'}->{NewConnectionStatus};
$self->{global}->{uptime} = $infos->{'s:Body'}->{'u:GetStatusInfoResponse'}->{NewUptime}; # seconds
$self->{global}->{uptime_human} = centreon::plugins::misc::change_seconds(value => $self->{global}->{uptime});
}
1;
__END__
=head1 MODE
Check system.
=over 8
=item B<--filter-counters>
Only display some counters (regexp can be used).
Example: --filter-counters='uptime'
=item B<--warning-status>
Set warning threshold for status.
Can use special variables like: %{connection_status}, %{link_status}
=item B<--critical-status>
Set critical threshold for status (Default: '%{link_status} !~ /^up$/i and %{connection_status} !~ /^connected$/i').
Can use special variables like: %{connection_status}, %{link_status}
=item B<--unit>
Select the unit for uptime threshold. May be 's' for seconds, 'm' for minutes,
'h' for hours, 'd' for days, 'w' for weeks. Default is days.
=item B<--warning-*> B<--critical-*>
Thresholds.
Can be: 'uptime'.
=back
=cut
| Tpo76/centreon-plugins | network/fritzbox/upnp/mode/system.pm | Perl | apache-2.0 | 6,047 |
package ACDwide::DB::Schema;
# Created by DBIx::Class::Schema::Loader
# DO NOT MODIFY THE FIRST PART OF THIS FILE
use strict;
use warnings;
use base 'DBIx::Class::Schema';
__PACKAGE__->load_namespaces;
# Created by DBIx::Class::Schema::Loader v0.07010 @ 2015-06-17 23:49:29
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:laF+JK0oAmjW3fu+8af2lQ
# You can replace this text with custom code or comments, and it will be preserved on regeneration
1;
| ivanoff/ACDwide | opt/ACDwide/DB/Schema.pm | Perl | apache-2.0 | 454 |
#!/usr/local/bin/perl
print "/* apps/progs.h */\n";
print "/* automatically generated by progs.pl for openssl.c */\n\n";
grep(s/^asn1pars$/asn1parse/,@ARGV);
foreach (@ARGV)
{ printf "extern int %s_main(int argc,char *argv[]);\n",$_; }
print <<'EOF';
#define FUNC_TYPE_GENERAL 1
#define FUNC_TYPE_MD 2
#define FUNC_TYPE_CIPHER 3
#define FUNC_TYPE_PKEY 4
#define FUNC_TYPE_MD_ALG 5
#define FUNC_TYPE_CIPHER_ALG 6
typedef struct {
int type;
const char *name;
int (*func)(int argc,char *argv[]);
} FUNCTION;
DECLARE_LHASH_OF(FUNCTION);
FUNCTION functions[] = {
EOF
foreach (@ARGV)
{
push(@files,$_);
$str="\t{FUNC_TYPE_GENERAL,\"$_\",${_}_main},\n";
if (($_ =~ /^s_/) || ($_ =~ /^ciphers$/))
{ print "#if !defined(OPENSSL_NO_SOCK) && !(defined(OPENSSL_NO_SSL2) && defined(OPENSSL_NO_SSL3))\n${str}#endif\n"; }
elsif ( ($_ =~ /^speed$/))
{ print "#ifndef OPENSSL_NO_SPEED\n${str}#endif\n"; }
elsif ( ($_ =~ /^engine$/))
{ print "#ifndef OPENSSL_NO_ENGINE\n${str}#endif\n"; }
elsif ( ($_ =~ /^rsa$/) || ($_ =~ /^genrsa$/) || ($_ =~ /^rsautl$/))
{ print "#ifndef OPENSSL_NO_RSA\n${str}#endif\n"; }
elsif ( ($_ =~ /^dsa$/) || ($_ =~ /^gendsa$/) || ($_ =~ /^dsaparam$/))
{ print "#ifndef OPENSSL_NO_DSA\n${str}#endif\n"; }
elsif ( ($_ =~ /^ec$/) || ($_ =~ /^ecparam$/))
{ print "#ifndef OPENSSL_NO_EC\n${str}#endif\n";}
elsif ( ($_ =~ /^dh$/) || ($_ =~ /^gendh$/) || ($_ =~ /^dhparam$/))
{ print "#ifndef OPENSSL_NO_DH\n${str}#endif\n"; }
elsif ( ($_ =~ /^pkcs12$/))
{ print "#if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_SHA1)\n${str}#endif\n"; }
elsif ( ($_ =~ /^cms$/))
{ print "#ifndef OPENSSL_NO_CMS\n${str}#endif\n"; }
elsif ( ($_ =~ /^ocsp$/))
{ print "#ifndef OPENSSL_NO_OCSP\n${str}#endif\n"; }
elsif ( ($_ =~ /^srp$/))
{ print "#ifndef OPENSSL_NO_SRP\n${str}#endif\n"; }
else
{ print $str; }
}
foreach ("md2","md4","md5","sha","sha1","mdc2","rmd160")
{
push(@files,$_);
printf "#ifndef OPENSSL_NO_".uc($_)."\n\t{FUNC_TYPE_MD,\"".$_."\",dgst_main},\n#endif\n";
}
foreach (
"aes-128-cbc", "aes-128-ecb",
"aes-192-cbc", "aes-192-ecb",
"aes-256-cbc", "aes-256-ecb",
"camellia-128-cbc", "camellia-128-ecb",
"camellia-192-cbc", "camellia-192-ecb",
"camellia-256-cbc", "camellia-256-ecb",
"base64", "zlib",
"des", "des3", "desx", "idea", "seed", "rc4", "rc4-40",
"rc2", "bf", "cast", "rc5",
"des-ecb", "des-ede", "des-ede3",
"des-cbc", "des-ede-cbc","des-ede3-cbc",
"des-cfb", "des-ede-cfb","des-ede3-cfb",
"des-ofb", "des-ede-ofb","des-ede3-ofb",
"idea-cbc","idea-ecb", "idea-cfb", "idea-ofb",
"seed-cbc","seed-ecb", "seed-cfb", "seed-ofb",
"rc2-cbc", "rc2-ecb", "rc2-cfb","rc2-ofb", "rc2-64-cbc", "rc2-40-cbc",
"bf-cbc", "bf-ecb", "bf-cfb", "bf-ofb",
"cast5-cbc","cast5-ecb", "cast5-cfb","cast5-ofb",
"cast-cbc", "rc5-cbc", "rc5-ecb", "rc5-cfb", "rc5-ofb")
{
push(@files,$_);
$t=sprintf("\t{FUNC_TYPE_CIPHER,\"%s\",enc_main},\n",$_);
if ($_ =~ /des/) { $t="#ifndef OPENSSL_NO_DES\n${t}#endif\n"; }
elsif ($_ =~ /aes/) { $t="#ifndef OPENSSL_NO_AES\n${t}#endif\n"; }
elsif ($_ =~ /camellia/) { $t="#ifndef OPENSSL_NO_CAMELLIA\n${t}#endif\n"; }
elsif ($_ =~ /idea/) { $t="#ifndef OPENSSL_NO_IDEA\n${t}#endif\n"; }
elsif ($_ =~ /seed/) { $t="#ifndef OPENSSL_NO_SEED\n${t}#endif\n"; }
elsif ($_ =~ /rc4/) { $t="#ifndef OPENSSL_NO_RC4\n${t}#endif\n"; }
elsif ($_ =~ /rc2/) { $t="#ifndef OPENSSL_NO_RC2\n${t}#endif\n"; }
elsif ($_ =~ /bf/) { $t="#ifndef OPENSSL_NO_BF\n${t}#endif\n"; }
elsif ($_ =~ /cast/) { $t="#ifndef OPENSSL_NO_CAST\n${t}#endif\n"; }
elsif ($_ =~ /rc5/) { $t="#ifndef OPENSSL_NO_RC5\n${t}#endif\n"; }
elsif ($_ =~ /zlib/) { $t="#ifdef ZLIB\n${t}#endif\n"; }
print $t;
}
print "\t{0,NULL,NULL}\n\t};\n";
| caidongyun/nginx-openresty-windows | nginx/objs/lib/openssl-1.0.1g/apps/progs.pl | Perl | bsd-2-clause | 3,857 |
package Tapper::CLI::Init;
BEGIN {
$Tapper::CLI::Init::AUTHORITY = 'cpan:TAPPER';
}
{
$Tapper::CLI::Init::VERSION = '4.1.3';
}
use 5.010;
use strict;
use warnings;
use Tapper::Cmd::Init;
sub init
{
my ($c) = @_;
$c->getopt( 'quiet|q', 'help|?', 'default|d' );
my $use_defaults = $c->options->{default};
if ( $c->options->{help} or not $use_defaults ) {
say STDERR "Usage: $0 init --default|d [ --quiet ]";
say STDERR "";
say STDERR " --default Use default values for all parameters (currently required)";
say STDERR " --quiet Stay silent.";
say STDERR " --help Print this help message and exit.";
exit -1;
}
my %options = ( $use_defaults ?
(
db => "SQLite",
)
: (
db => $c->options->{db},
),
);
my $cmd = Tapper::Cmd::Init->new;
$cmd->init(\%options);
return;
}
sub setup
{
my ($c) = @_;
$c->register('init', \&init, 'Initialize $HOME/.tapper/ for non-root use-cases.');
return;
}
1; # End of Tapper::CLI
__END__
=pod
=encoding utf-8
=head1 NAME
Tapper::CLI::Init
=head1 SYNOPSIS
This module is part of the Tapper::CLI framework. It is supposed to be
used together with App::Rad. All following functions expect their
arguments as $c->options->{$arg}.
use App::Rad;
use Tapper::CLI::Init;
Tapper::CLI::Init::setup($c);
App::Rad->run();
=head1 NAME
Tapper::CLI::Init - Tapper - set up a user-specific $HOME/.tapper/
=head1 FUNCTIONS
=head2 init
Initialize a $HOME/.tapper/ with tapper.cfg and initial SQLite database.
=head2 setup
Initialize the testplan functions for tapper CLI
=head1 AUTHOR
AMD OSRC Tapper Team <tapper@amd64.org>
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2012 by Advanced Micro Devices, Inc..
This is free software, licensed under:
The (two-clause) FreeBSD License
=cut
| gitpan/Tapper-CLI | lib/Tapper/CLI/Init.pm | Perl | bsd-2-clause | 2,150 |
package DbUser;
use strict;
use warnings;
use parent 'DBIx::Class';
__PACKAGE__->load_components("Core");
__PACKAGE__->table("dbuser");
__PACKAGE__->add_columns
(
"id", { data_type => "INT", default_value => undef, is_nullable => 0, size => 11, is_auto_increment => 1, },
"name", { data_type => "VARCHAR", default_value => undef, is_nullable => 0, size => 255, },
);
__PACKAGE__->set_primary_key("id");
1;
| csdb/Tapper-MCP | xt/DbUser.pm | Perl | bsd-2-clause | 465 |
package Loong::DB::Mango;
use Loong::Base 'Mango';
use Data::Dumper;
sub trim_db {
my ( $self, $db ) = @_;
$db =~ s/www.//g;
$db =~ s/.com//g;
$db =~ s/\./_/g;
return $db;
}
sub save_crawl_info {
my ( $self, $crawled, $seed, $name ) = @_;
my $set = '$set';
my $db = $self->trim_db($seed);
my $collection = $self->db('hupu')->collection($name);
my $opts = {
query => { url => $crawled->{url} },
update => { $set => $crawled },
};
return $collection->find_and_modify(
$opts => sub {
my ( $collection, $err, $doc ) = @_;
return defined $doc ? $doc : $collection->insert( $crawled => sub { } );
}
);
}
sub get_counter_collection_by {
my ( $self, $seed ) = @_;
my $db = $seed;
# 替换掉域名里面的点和 www com,防止生成不合法的 db
$db =~ s/www.//g;
$db =~ s/.com//g;
$db =~ s/\./_/g;
return $self->db($db)->collection('counter');
}
1;
| niumang/loong | lib/Loong/DB/Mango.pm | Perl | bsd-3-clause | 1,014 |
/* Part of XPCE --- The SWI-Prolog GUI toolkit
Author: Christian Schlichtherle
WWW: http://www.swi-prolog.org
Copyright (c) 1995, Christian Schlichtherle
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(rubik,[ordered/1,
ordered/7,
adjust/2,
draw/3,
draws/3,
opt_draws/2,
perm_turn_cube/2,
turn_cube/2,
perm_tilt_cube/2,
tilt_cube/2,
random_draws/1,
disordered/1,
portray/1]).
:-use_module(library(pce)).
:-use_module(maplist).
:- require([ append/3
, member/2
, random/3
]).
:- license(gplv2).
:- op(0, fx, l).
/** <module> Rubik's Cube
The algorithm of this program is based on Josef Trajber's book
'Der Wuerfel (Rubiks Cube); Loesungswege; math. Grundlagen; Varianten fuer
Supertueftler', Falken-Verlag, 1981.
There are two different data structures handled by this program:
1. The cube is represented as a prolog term
cube(+Field1, ...+Field54)
where FieldX is the X-th field on the cube. The ordinate X of a field
can easily be seen when you take a cube and fold it out into a
2-dimensional cross. The fields on this cross are numbered in
canonical order, i.e. from left to right, top down. Any full
instantiated term can be used as a value of a field since the terms
are only used to compare them to the terms of the centerstones. 2.
Draws to the cube are notated as a Prolog term like this:
S/N, where S is one of:
l: left side.
f: front side.
r: right side.
b: back side.
u: upside.
d: downside.
and N is the number of clockwise 90 degree turns applying to this side:
-1: one turn counterclockwise (i.e. three clockwise turns).
0: no op.
1: one turn.
2: two turns (either directions).
To know how a sidename is attached to a side of the cube you should know
that the heart of the cross is called the front side. All other sidenames
are then obvious.
## Internals
Important note: Rotating the cube clockwise around the front surface
(turn_cube/3 does this for you) is a permutation of the sides adjacent
to the front side. The permutation is (l u r d) (<-- This is the cyclic
notation of the permutation). Thus, if you have a list of draws applying
to a one times 90 degree clockwise turned cube and you want to know
which draws would do the same job on the unturned cube, take the side of
the cube to turn from each draw and apply the permutation backwards! The
number and direction of each turn stays the same! Thus, the draw list
[r/1,f/ -1,l/2] becomes [u/1,f/ -1,d/2] (f and b stay the same because
they are not permuted and are thus not mentioned in the cycle). In
general: If the cube was turned n times, you have to apply the
permutation n times backwards. Thus, if the cube was three times turned
clockwise, the draw r/ -1 becomes d/ -1. Note that this is the same as
if the cube has been turned counterclockwise one time (thus applying the
permutation one times forward).
*/
% This is for printing Rubik's Cube:
% I splitted the predicate up so SB-Prolog can work with it.
portray([]):-!.
portray([H|T]):-
portray(H),write(','),portray(T).
portray(S/N):-
portray(S),write('/'),portray(N).
portray(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9)
):-
!,
portray(cube_up(U1,U2,U3,
U4,U5,U6,
U7,U8,U9)),
portray(cube_mid(L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9)),
portray(cube_down(D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9)).
portray(
cube_up(U1,U2,U3,
U4,U5,U6,
U7,U8,U9)
):-
tab(6),portray(U1),write(' '),portray(U2),write(' '),portray(U3),nl,
tab(6),portray(U4),write(' '),portray(U5),write(' '),portray(U6),nl,
tab(6),portray(U7),write(' '),portray(U8),write(' '),portray(U9),nl.
portray(
cube_mid(L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9)
):-
tab(0),portray(L1),write(' '),portray(L2),write(' '),portray(L3),write(' '),
portray(F1),write(' '),portray(F2),write(' '),portray(F3),write(' '),
portray(R1),write(' '),portray(R2),write(' '),portray(R3),nl,
tab(0),portray(L4),write(' '),portray(L5),write(' '),portray(L6),write(' '),
portray(F4),write(' '),portray(F5),write(' '),portray(F6),write(' '),
portray(R4),write(' '),portray(R5),write(' '),portray(R6),nl,
tab(0),portray(L7),write(' '),portray(L8),write(' '),portray(L9),write(' '),
portray(F7),write(' '),portray(F8),write(' '),portray(F9),write(' '),
portray(R7),write(' '),portray(R8),write(' '),portray(R9),nl.
portray(
cube_down(D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9)
):-
tab(6),portray(D1),write(' '),portray(D2),write(' '),portray(D3),nl,
tab(6),portray(D4),write(' '),portray(D5),write(' '),portray(D6),nl,
tab(6),portray(D7),write(' '),portray(D8),write(' '),portray(D9),nl,
tab(6),portray(B1),write(' '),portray(B2),write(' '),portray(B3),nl,
tab(6),portray(B4),write(' '),portray(B5),write(' '),portray(B6),nl,
tab(6),portray(B7),write(' '),portray(B8),write(' '),portray(B9),nl.
portray(X):-atomic(X),!,write(X).
% This will assign the symbols to the cube's fields:
ordered(C):-
ordered('B','R','G','O','W','Y',C).
% This is the cube in ordered state:
ordered(U,L,F,R,D,B,
cube(U,U,U,
U,U,U,
U,U,U,
L,L,L,F,F,F,R,R,R,
L,L,L,F,F,F,R,R,R,
L,L,L,F,F,F,R,R,R,
D,D,D,
D,D,D,
D,D,D,
B,B,B,
B,B,B,
B,B,B)
).
% Adjust Rubik's Cube.
adjust(C1,L6):-
adjust1(C1,L1,C2),
adjust2(C2,L2,C3),
adjust3(C3,L3,_),
append(L2,L3,L4),
append(L1,L4,L5),
opt_draws(L5,L6).
%
% The adjustXXX/3 predicates have the general form
% adjustXXX(+CubeBefore,-DrawList,-CubeAfter)
% with:
% CubeBefore : The disordered cube before adjustment.
% DrawList : The list of draws to adjust the cube.
% CubeAfter : The cube after adjustment.
%
% Some of these predicates have only two arguments (CubeBefore and DrawList).
% In this case CubeAfter is always the fully ordered cube.
%
% Adjust the first layer. Assume nothing about the look of the cube.
adjust1(C1,L3,C3):-
adjust1sides(C1,L1,C2),
adjust1corners(C2,L2,C3),
append(L1,L2,L3).
%
% Adjust the side stones of the first layer
% (i.e. the front surface) of the cube.
% Assume nothing about the look of the cube.
%
adjust1sides(C,[],C):-
C = cube( _, _, _,
_, U, _,
_, U, _,
_, _, _, _, F, _, _, _, _,
_, L, L, F, F, F, R, R, _,
_, _, _, _, F, _, _, _, _,
_, D, _,
_, D, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _).
adjust1sides(C1,L3,C3):-
meta_match_pattern1sides(C1,L1,C2),
adjust1sides(C2,L2,C3),
append(L1,L2,L3).
% First try only constructive draws...
meta_match_pattern1sides(C1,L2,C3):-
turn_cube(C1,N,C2),
match_cst_pattern1sides(C2,L1),
n_maplist(N,perm_turn_cube,L2,L1),
draws(C1,L2,C3).
% then try only destructive draws.
meta_match_pattern1sides(C1,L2,C3):-
turn_cube(C1,N,C2),
match_dst_pattern1sides(C2,L1),
n_maplist(N,perm_turn_cube,L2,L1),
draws(C1,L2,C3).
% First try only constructive moves...
match_cst_pattern1sides(
cube( _, _, _,
F, _, _,
_, _, _,
_, L, _, _, _, _, _, _, _,
_, L, _, _, F, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[l/1]
).
match_cst_pattern1sides(
cube( _, _, _,
_, _, F,
_, _, _,
_, _, _, _, _, _, _, R, _,
_, _, _, _, F, _, _, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/ -1]
).
match_cst_pattern1sides(
cube( _, _, _,
F, _, _,
_, _, _,
_, R, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[f/2,l/1,f/2]
).
match_cst_pattern1sides(
cube( _, _, _,
_, _, F,
_, _, _,
_, _, _, _, _, _, _, L, _,
_, L, _, _, F, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[f/2,r/ -1,f/2]
).
match_cst_pattern1sides(C1,[b/Turns|DrawList]):-
draw(C1,b/Turns,C2),
match_pattern1sides_turned_backside(C2,DrawList).
% if no constructive move matches, then try destructive moves.
match_dst_pattern1sides(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, F, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/2]
).
match_dst_pattern1sides(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, F, X, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/2]
):-
X\==R.
match_dst_pattern1sides(
cube( _, _, _,
F, _, _,
_, _, _,
_, X, _, _, _, _, _, _, _,
_, L, _, _, F, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[l/ -1,b/1,l/1]
):-
X\==L.
match_dst_pattern1sides(
cube( _, _, _,
_, _, F,
_, _, _,
_, _, _, _, _, _, _, X, _,
_, _, _, _, F, _, _, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/1,b/1,r/ -1]
):-
X\==R.
% Draws with the backside rotated: All of these are constructive.
match_pattern1sides_turned_backside(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
_, D, _,
_, F, _,
_, _, _,
_, _, _),
[d/2]
).
match_pattern1sides_turned_backside(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, _, F,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
_, _, _,
_, _, _,
_, _, D,
_, _, _),
[r/1,d/ -1,r/ -1]
).
match_pattern1sides_turned_backside(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
F, _, _, _, F, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
_, _, _,
_, _, _,
D, _, _,
_, _, _),
[l/ -1,d/1,l/1]
).
%
% Adjust the corner stones of the first layer.
% Assume that the side stones of the first layer are already adjusted.
%
% The corner stones are correct in this case:
adjust1corners(C,[],C):-
C = cube( _, _, _,
_, U, _,
U, _, U,
_, _, L, _, _, _, R, _, _,
_, L, _, _, _, _, _, R, _,
_, _, L, _, _, _, R, _, _,
D, _, D,
_, D, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _).
adjust1corners(C1,L3,C3):-
meta_match_pattern1corners(C1,L1,C2),
adjust1corners(C2,L2,C3),
append(L1,L2,L3).
% First try only constructive draws...
meta_match_pattern1corners(C1,L4,C4):-
turn_cube(C1,N,C2),
draw(C2,b/Turns,C3),
match_cst_pattern1corners(C3,DrawList),
n_maplist(N,perm_turn_cube,L4,[b/Turns|DrawList]),
draws(C1,L4,C4).
% then try only destructive draws.
meta_match_pattern1corners(C1,L4,C4):-
turn_cube(C1,N,C2),
draw(C2,b/Turns,C3),
match_dst_pattern1corners(C3,DrawList),
n_maplist(N,perm_turn_cube,L4,[b/Turns|DrawList]),
draws(C1,L4,C4).
% These are constructive draws.
match_cst_pattern1corners(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, R, _,
_, _, _, _, _, _, _, _, F,
_, _, _,
_, _, _,
_, _, _,
_, _, R,
_, _, _,
_, _, _),
[r/ -1,b/ -1,r/1]
).
match_cst_pattern1corners(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, R, _,
_, _, _, _, _, _, _, _, R,
_, _, _,
_, _, _,
_, _, F,
_, _, _,
_, _, _,
_, _, _),
[d/1,b/1,d/ -1]
).
match_cst_pattern1corners(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, L, _, _, F, _, _, _, _,
_, _, _, _, _, _, _, _, F,
_, _, _,
_, _, _,
_, _, L,
_, _, _,
_, _, _,
_, _, _),
[l/1,b/ -1,l/ -1]
).
match_cst_pattern1corners(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, R, _,
F, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
R, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/ -1,b/1,r/1]
).
% These are destructive draws.
match_dst_pattern1corners(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, R,
_, _, F,
_, _, _,
_, _, _),
[r/ -1,b/2,r/1]
).
match_dst_pattern1corners(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, _, _,
_, _, _, _, _, F, _, _, _,
_, _, X,
_, D, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/ -1,b/ -1,r/1]
):-
X\==D.
match_dst_pattern1corners(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, F, _, _, _, _,
_, _, _, _, _, _, X, _, _,
_, _, Y,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/ -1,b/ -1,r/1]
):-
X==F;
Y==F.
%
% Adjust the second layer. Assume that the first layer is already adjusted.
%
adjust2(C1,L,C2):-
adjust2sides(C1,L,C2).
%
% Adjust the side stones of the second layer of the cube.
% This assumes that the first layer is already adjusted.
%
adjust2sides(C,[],C):-
C = cube( _, _, _,
U, U, U,
_, _, _,
_, L, _, _, _, _, _, R, _,
_, L, _, _, _, _, _, R, _,
_, L, _, _, _, _, _, R, _,
_, _, _,
D, D, D,
_, _, _,
_, _, _,
_, _, _,
_, _, _).
adjust2sides(C1,L3,C3):-
meta_match_pattern2sides(C1,L1,C2),
adjust2sides(C2,L2,C3),
append(L1,L2,L3).
meta_match_pattern2sides(C1,L2,C3):-
turn_cube(C1,N,C2),
match_cst_pattern2sides(C2,L1),
n_maplist(N,perm_turn_cube,L2,L1),
draws(C1,L2,C3).
meta_match_pattern2sides(C1,L2,C3):-
turn_cube(C1,N,C2),
match_dst_pattern2sides(C2,L1),
n_maplist(N,perm_turn_cube,L2,L1),
draws(C1,L2,C3).
% These are constructive draws.
match_cst_pattern2sides(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, L, _, _, _, _, _, R, _,
_, R, _, _, _, _, _, L, _,
_, _, _,
D, D, D,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/2,b/2,r/2,b/2,r/2]
).
match_cst_pattern2sides(C1,[b/Turns|DrawList]):-
draw(C1,b/Turns,C2),
match_pattern2sides_turned_backside(C2,DrawList).
% These are destructive draws.
match_dst_pattern2sides(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, R, _,
_, _, _, _, _, _, _, X, _,
_, _, _,
_, D, Y,
_, _, _,
_, _, _,
_, _, _,
_, _, _),
[r/ -1,b/ -1,r/1,b/1,d/1,b/1,d/ -1]
):-
X\==R;
Y\==D.
% These are constructive draws.
match_pattern2sides_turned_backside(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
D, _, _, _, _, _, _, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
_, _, _,
_, _, _,
R, _, _,
_, _, _),
[r/ -1,b/ -1,r/1,b/1,d/1,b/1,d/ -1]
).
match_pattern2sides_turned_backside(
cube( _, R, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
_, _, _,
_, _, _,
_, _, _,
_, D, _),
[d/1,b/ -1,d/ -1,b/ -1,r/ -1,b/1,r/1]
).
% Adjust the third layer. Assume that the second layer is already adjusted.
adjust3(C1,L5,C4):-
adjust3draw_corners(C1,L1,C2),
adjust3turn_corners(C2,L2,C3),
append(L1,L2,L3),
adjust3sides(C3,L4,C4),
append(L3,L4,L5).
%
% Draw the corner stones of the third layer of the cube to their places.
% This assumes that the second layer is already adjusted.
% This needs some explanation:
% 1. Find the two adjacent corner stones which have two colors in common
% (the one of the backside and one other).
% Such two stones must always exist!
% 2. Turn the backside of the cube so that these two stones are at the correct
% side.
% 3. Now there are four possible cases:
% - These stones and the other two stones are at their correct place,
% i.e. all corner stones are at their correct place.
% - These stones are at their right place,
% but the other two stones are exchanged.
% - These stones are exchanged,
% but the other two stones are at their correct place.
% - Both these stones and the other two stones are exchanged.
% In each case, use a specific list of draws which will draw the corner
% stones to their correct place.
%
adjust3draw_corners(Cube,ResList,ResCube):-
turn_cube(Cube,N,Cube1), % rotate the cube and focus on the left side.
draw(Cube1,b/Turns,Cube2), % rotate the backside of the cube.
Cube2
= cube(A1, _,C1,
_, U, _,
_, _, _,
A2, _, _, _, _, _, _, _,C2,
_, L, _, _, _, _, _, _, _,
B1, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
B2, _, _,
B3, _, _,
_, _, _,
A3, _,C3),
% check if the two left cornerstones are at their right place.
member(L,[A1,A2,A3]),
member(L,[B1,B2,B3]),
% filter the color that is not in common
findall(Color,(member(Color,[A1,A2,A3]),
member(Color,[U,D])),
[UpLeftColor]),
findall(Color,(member(Color,[C1,C2,C3]),
member(Color,[U,D])),
[UpRightColor]),
% determine the drawlist which corrects the corners
match_pattern3draw_corners(UpLeftColor,U,UpRightColor,DrawList),
n_maplist(N,perm_turn_cube,ResList,[b/Turns|DrawList]),
draws(Cube,ResList,ResCube).
% Select a drawlist to draw the corner stones of the cube to their right
% places.
match_pattern3draw_corners(
UpColor,
UpColor,
UpColor,
[]
):-!.
match_pattern3draw_corners(
_,
UpColor,
UpColor,
[d/ -1,r/1,d/1,b/1,d/ -1,b/ -1,r/ -1,b/1,d/1]
):-!.
match_pattern3draw_corners(
UpColor,
UpColor,
_,
[u/ -1,l/1,u/1,b/1,u/ -1,b/ -1,l/ -1,b/1,u/1]
):-!.
match_pattern3draw_corners(
_,
_,
_,
[r/1,b/1,d/1,b/ -1,d/ -1,r/ -1]
).
%
% Turn the corner stones of the third layer of the cube.
% This assumes that the second layer is already adjusted and all corner
% stones are already at the right place.
%
adjust3turn_corners(C,[],C):-
C = cube( U, _, U,
_, _, _,
_, _, _,
L, _, _, _, _, _, _, _, R,
_, _, _, _, _, _, _, _, _,
L, _, _, _, _, _, _, _, R,
_, _, _,
_, _, _,
D, _, D,
_, _, _,
_, _, _,
_, _, _).
adjust3turn_corners(Cube,ResList,ResCube):-
turn_cube(Cube,N,Cube1),
match_pattern3turn_corners(Cube1,List1),
n_maplist(N,perm_turn_cube,ResList,List1),
draws(Cube,ResList,ResCube).
match_pattern3turn_corners(
cube( L, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, U,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, D,
_, _, _,
_, _, _,
L, _, _,
D, _, R,
_, _, _,
U, _, R),
[d/1,b/1,l/1,b/ -1,l/ -1,b/1,l/1,b/ -1,l/ -1,d/ -1]
).
match_pattern3turn_corners(
cube( _, _, U,
_, _, _,
_, _, _,
U, _, _, _, _, _, _, _, R,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, D,
_, _, _,
_, _, _,
L, _, _,
D, _, R,
_, _, _,
L, _, _),
[l/ -1,b/ -1,l/1,b/ -1,l/ -1,b/2,l/1,b/2]
).
match_pattern3turn_corners(
cube( L, _, U,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, R,
_, _, _, _, _, _, _, _, _,
D, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, R,
L, _, D,
_, _, _,
U, _, _),
[b/2,l/ -1,b/2,l/1,b/1,l/ -1,b/1,l/1]
).
match_pattern3turn_corners(
cube( L, _, R,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, _,
L, _, _, _, _, _, _, _, R,
_, _, _,
_, _, _,
D, _, D,
_, _, _,
_, _, _,
U, _, U),
[d/ -1,b/ -1,d/1,b/ -1,d/ -1,b/2,d/1,l/ -1,b/2,l/1,b/1,l/ -1,b/1,l/1]
).
match_pattern3turn_corners(
cube( _, _, _,
_, _, _,
_, _, _,
U, _, _, _, _, _, _, _, U,
_, _, _, _, _, _, _, _, _,
L, _, _, _, _, _, _, _, R,
_, _, _,
_, _, _,
D, _, D,
_, _, _,
_, _, _,
L, _, R),
[l/ -1,b/ -1,l/1,b/ -1,l/ -1,b/2,l/1,d/ -1,b/2,d/1,b/1,d/ -1,b/1,d/1]
).
match_pattern3turn_corners(
cube( U, _, _,
_, _, _,
_, _, _,
L, _, _, _, _, _, _, _, U,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, R,
_, _, _,
_, _, _,
L, _, D,
D, _, _,
_, _, _,
_, _, R),
[l/ -1,b/ -1,l/1,b/ -1,l/ -1,b/2,l/1,r/ -1,b/2,r/1,b/1,r/ -1,b/1,r/1]
).
match_pattern3turn_corners(
cube( L, _, R,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
L, _, R,
D, _, D,
_, _, _,
U, _, U),
[l/ -1,b/ -1,l/1,b/ -1,l/ -1,b/1,l/1,b/ -1,l/ -1,b/2,l/1]
).
%
% Adjust the side stones of the third layer of the cube.
% This assumes that the corner stones of the third layer are already
% adjusted.
%
% In this case the side stones are already adjusted.
adjust3sides(C,[],C):-
C = cube( _, U, _,
_, U, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
L, L, _, _, _, _, _, R, R,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
_, D, _,
_, _, _,
_, _, _,
_, _, _).
adjust3sides(Cube,ResList,ResCube):-
meta_match_pattern3sides(Cube,List1,Cube1),
adjust3sides(Cube1,List2,ResCube),
append(List1,List2,ResList).
meta_match_pattern3sides(Cube,ResList,ResCube):-
turn_cube(Cube,N,Cube1),
match_pattern3sides(Cube1,List1),
n_maplist(N,perm_turn_cube,ResList,List1),
draws(Cube,ResList,ResCube).
match_pattern3sides(
cube( _, _, _,
_, U, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
A1, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
A2, B, _,
_, _, _),
[l/2,f/ -1,d/2,l/1,r/ -1,b/2,l/ -1,r/1,f/1,l/2]
):-
turn_side([A1,A2],[U,B]).
match_pattern3sides(
cube( _, _, _,
_, U, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_,A1, _,
_,A2, _,
_, B, _,
_, _, _),
[r/2,f/ -1,u/2,r/1,l/ -1,b/2,r/ -1,l/1,f/1,r/2]
):-
turn_side([A1,A2],[U,B]).
match_pattern3sides(
cube( _, _, _,
_, U, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _,A1,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
_, B,A2,
_, _, _),
[r/2,f/ -1,r/1,l/ -1,b/2,r/ -1,l/1,u/2,f/1,r/2]
):-
turn_side([A1,A2],[U,B]).
match_pattern3sides(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, L, _, _, _, _, _, _, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, D, _,
_, _, _,
_, D, _,
L, _, _,
_, _, _),
[l/ -1,b/2,l/2,b/1,l/ -1,b/ -1,l/ -1,b/2,r/1,d/1,l/1,d/ -1,r/ -1]
).
match_pattern3sides(
cube( _, _, _,
_, _, _,
_, _, _,
_, _, _, _, _, _, _, _, _,
_, L, _, _, _, _, _, R, _,
_, _, _, _, _, _, _, _, _,
_, _, _,
_, _, _,
_, _, _,
_, _, _,
L, _, R,
_, _, _),
[r/1,d/1,l/ -1,b/2,l/2,b/1,l/ -1,b/ -1,l/ -1,
b/2,r/1,d/1,l/1,d/ -1,r/ -1,d/ -1,r/ -1]
).
% These predicates optimise a draw list.
opt_draws([],[]).
opt_draws([_/0|List],ResList):-
!,
opt_draws(List,ResList).
opt_draws([M1/C1|List1],ResList):-
opt_draws(List1,[M2/C2|List3]),
!,
C3 is C1+C2,
opt_two_draws(M1/C1,M2/C2,C3,List2),
append(List2,List3,ResList).
opt_draws(List,List).
opt_two_draws(M /_ ,M /_ ,-2,[M / 2] ):-!.
opt_two_draws(M /_ ,M /_ , 0,[] ):-!.
opt_two_draws(M /_ ,M /_ , 3,[M / -1] ):-!.
opt_two_draws(M /_ ,M /_ , 4,[] ):-!.
opt_two_draws(M /_ ,M /_ , C,[M / C] ):-!.
opt_two_draws(M1/C1,M2/C2, _,[M1/C1,M2/C2]).
disordered(Cube):-
ordered(Ordered),
random_draws(Draws),
draws(Ordered,Draws,Cube).
% random_draws(-DrawList).
random_draws(DrawList):-
random(0, 6, Draws),
random_draws(Draws,DrawList).
random_draws(0,[]):-!.
random_draws(Draws,[Draw|DrawList]):-
random_draw(Draw),
NewDraws is Draws - 1,
random_draws(NewDraws,DrawList).
% random_draw(-Draw).
random_draw(M/N):-
random(0, 6, X),
int2draw(X,M),
random(0,3,Y),
(Y =:= 0 -> N is -1; N is Y).
int2draw(0,u).
int2draw(1,l).
int2draw(2,f).
int2draw(3,r).
int2draw(4,d).
int2draw(5,b).
%
% Do a list of draws.
% Note: It is possible to specify an empty list of draws with this predicate,
% whereas you cannot specify 'no draw' with the draw/3 predicate.
%
draws(C,[],C).
draws(C1,[M|T],C3):-
draw(C1,M,C2),
draws(C2,T,C3).
% These are the legal draws.
% For speed reasons, all single clockwise draws are given *explicitly* here
% instead of computing them from applying one single draw to a several times
% turned and tilted cube.
% Note: Order is important here. Zero clockwise turns must be the last
% solution found!
draw(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
l/1,
cube(B1,U2,U3,
B4,U5,U6,
B7,U8,U9,
L7,L4,L1,U1,F2,F3,R1,R2,R3,
L8,L5,L2,U4,F5,F6,R4,R5,R6,
L9,L6,L3,U7,F8,F9,R7,R8,R9,
F1,D2,D3,
F4,D5,D6,
F7,D8,D9,
D1,B2,B3,
D4,B5,B6,
D7,B8,B9)
).
draw(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
f/1,
cube(U1,U2,U3,
U4,U5,U6,
L9,L6,L3,
L1,L2,D1,F7,F4,F1,U7,R2,R3,
L4,L5,D2,F8,F5,F2,U8,R5,R6,
L7,L8,D3,F9,F6,F3,U9,R8,R9,
R7,R4,R1,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9)
).
draw(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
r/1,
cube(U1,U2,F3,
U4,U5,F6,
U7,U8,F9,
L1,L2,L3,F1,F2,D3,R7,R4,R1,
L4,L5,L6,F4,F5,D6,R8,R5,R2,
L7,L8,L9,F7,F8,D9,R9,R6,R3,
D1,D2,B3,
D4,D5,B6,
D7,D8,B9,
B1,B2,U3,
B4,B5,U6,
B7,B8,U9)
).
draw(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
b/1,
cube(R3,R6,R9,
U4,U5,U6,
U7,U8,U9,
U3,L2,L3,F1,F2,F3,R1,R2,D9,
U2,L5,L6,F4,F5,F6,R4,R5,D8,
U1,L8,L9,F7,F8,F9,R7,R8,D7,
D1,D2,D3,
D4,D5,D6,
L1,L4,L7,
B7,B4,B1,
B8,B5,B2,
B9,B6,B3)
).
draw(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
u/1,
cube(U7,U4,U1,
U8,U5,U2,
U9,U6,U3,
F1,F2,F3,R1,R2,R3,B9,B8,B7,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
L3,L2,L1)
).
draw(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
d/1,
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
B3,B2,B1,L7,L8,L9,F7,F8,F9,
D7,D4,D1,
D8,D5,D2,
D9,D6,D3,
R9,R8,R7,
B4,B5,B6,
B7,B8,B9)
).
draw(C1,M/2,C3):-
draw(C1,M/1,C2),
draw(C2,M/1,C3).
draw(C1,M/ -1,C2):-
draw(C2,M/1,C1).
draw(C,_/0,C).
%
% These predicates are used to correct a list of draws applied to a turned
% cube (see intro).
%
% This is the draw permutation for clockwise cube rotations around the
% front/back axis.
perm_turn_cube(d/N,l/N).
perm_turn_cube(l/N,u/N).
perm_turn_cube(u/N,r/N).
perm_turn_cube(r/N,d/N).
perm_turn_cube(f/N,f/N).
perm_turn_cube(b/N,b/N).
% This is the draw permutation for cube tilts from the front to the upside.
perm_tilt_cube(u/N,b/N).
perm_tilt_cube(f/N,u/N).
perm_tilt_cube(d/N,f/N).
perm_tilt_cube(b/N,d/N).
perm_tilt_cube(l/N,l/N).
perm_tilt_cube(r/N,r/N).
% This predicate will rotate the cube clockwise around its front and
% back sides as the rotation axis.
% The notation is turn_cube(?C1,+N,?C2),
% where C1 is the original cube and C2 is the turned cube.
% N indicates how many times C2 was turned 90 degree clockwise.
% Note: Order is important here. Zero turns must be the last solution found!
turn_cube(C1,1,C2):-
turn_cube(C1,C2).
turn_cube(C1,2,C3):-
turn_cube(C1,C2),
turn_cube(C2,C3).
turn_cube(C1,3,C2):-
turn_cube(C2,C1).
turn_cube(C1,0,C1).
% turn_cube(?C1, ?C2) turns the cube C1 to be cube C2
% where the front and back side make up the rotation axis.
turn_cube(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
cube(L7,L4,L1,
L8,L5,L2,
L9,L6,L3,
D7,D4,D1,F7,F4,F1,U7,U4,U1,
D8,D5,D2,F8,F5,F2,U8,U5,U2,
D9,D6,D3,F9,F6,F3,U9,U6,U3,
R7,R4,R1,
R8,R5,R2,
R9,R6,R3,
B3,B6,B9,
B2,B5,B8,
B1,B4,B7)
).
% tilt_cube(?UnTiltCube,?TiltCube) turns the front side to the upside of the
% cube.
tilt_cube(
cube(U1,U2,U3,
U4,U5,U6,
U7,U8,U9,
L1,L2,L3,F1,F2,F3,R1,R2,R3,
L4,L5,L6,F4,F5,F6,R4,R5,R6,
L7,L8,L9,F7,F8,F9,R7,R8,R9,
D1,D2,D3,
D4,D5,D6,
D7,D8,D9,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9),
cube(F1,F2,F3,
F4,F5,F6,
F7,F8,F9,
L3,L6,L9,D1,D2,D3,R7,R4,R1,
L2,L5,L8,D4,D5,D6,R8,R5,R2,
L1,L4,L7,D7,D8,D9,R9,R6,R3,
B1,B2,B3,
B4,B5,B6,
B7,B8,B9,
U1,U2,U3,
U4,U5,U6,
U7,U8,U9)
).
% Specify what a turned corner stone may look like
turn_corner([M1,M2,M3],[M1,M2,M3]).
turn_corner([M3,M1,M2],[M1,M2,M3]).
turn_corner([M2,M3,M1],[M1,M2,M3]).
% Specify what a turned side stone may look like:
turn_side([M1,M2],[M1,M2]).
turn_side([M2,M1],[M1,M2]).
end_of_file.
| TeamSPoon/logicmoo_workspace | docker/rootfs/usr/local/lib/swipl/xpce/prolog/contrib/rubik/rubik.pl | Perl | mit | 35,632 |
% -----------------------------------------------------------------------------
%
% S I S version 0.1
%
% (Straightforward Implementation of Scheme)
%
% This program is a compiler for the Scheme language which generates
% native code (for MC68000). Quintus prolog has been used to develop the
% program.
%
% Sample use (on a SUN):
%
% $ prolog
% | ?- restore('sc.bin'). (load the compiler's image)
% | ?- ex.
% Input file name (.scm) : test
% Input file is "test.scm"
% Output file is "test.s"
% | ?- halt.
% $ asm test
% $ test
%
% -----------------------------------------------------------------------------
%
% Revision history:
%
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
%
% Version 0.0 (Dec 15, 1987).
%
% - 'rest' arguments are not implemented (e.g. (lambda (a b . c) c)) and
% a maximum of 126 arguments can be passed to a procedure.
% - backquote notation is not supported
% - floating point numbers and bignums are not implemented
% - first class continuations are not implemented (all is ready for them
% though; the stack could be copied by call-with-current-continuation
% and restored by a call to the continuation)
% - there is no garbage-collector and heap-overflow is not checked
% - list constants will cause the assembly to abort (this is a restriction
% caused by the SUN's assembler not the Scheme compiler) however, you
% can use 'cons' to build a list at execution time
% - symbols are not interned (i.e. symbol constants with the same name at
% two different places are not eq?)
% - only a small number of procedures are implemented, and they do not
% check the type or number of their arguments. The following procedures
% are implemented:
%
% not, eq?, pair? cons, car, cdr, set-car!, set-cdr!, null?,
% =, <, >, +, -, *, /, -1+, force, write, newline
%
% new procedures can be added by putting their names in the
% 'initial_global_env' list (in the compiler) and by adding their
% definition in the 'header.s' file.
%
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
%
% Version 0.1 (Jan 26, 1988).
%
% - 'rest' arguments are now permitted.
% - backquote notation is implemented.
% - list constants now work correctly.
% - symbols are now interned.
% - primitive procedures now check the type and number of their arguments.
% - it is now possible to open-code certain procedure calls; this is
% done by typing 'integrate(all).' before compiling (note: open-coded
% procedures do no error checking).
% - source-code can be printed for procedures written with 'write' by
% typing 'debug(on).'.
% - some new procedures have been added:
%
% append, length, list, vector, list->vector, memq, assq, symbol?,
% vector?, string?, procedure?, number?, char?
%
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
%
% Version 0.2 (Feb 3, 1988).
%
% - procedure calls can be traced by typing 'trace(on).'.
%
% -----------------------------------------------------------------------------
% -----------------------------------------------------------------------------
% Toplevel of compiler.
ex :-
query_io_files(I,O),
parse(I,Program),
compile(Program,Code),
write_code(Code,O).
query_io_files(I,O) :-
write_term('Input file name (.scm) : '),
read_line(X),
append(X,".scm",Y),
name(I,Y),
append(X,".s",Z),
name(O,Z),
write_term('Input file is "'), write_term(I), write_term('"'), newline,
write_term('Output file is "'), write_term(O), write_term('"'), newline.
% -----------------------------------------------------------------------------
% Basic file I/O and utilities.
open_input(Filename) :- see(Filename).
read_char(Ch) :- get0(C), read_char2(C,Ch).
read_char2(-1,eof) :- !.
read_char2(C,C).
close_input :- seen.
read_line(L) :- read_char(C), read_line(C,L).
read_line(C,[]) :- eoln(C), !.
read_line(C1,[C1|L]) :- read_char(C2), read_line(C2,L).
open_output(Filename) :- tell(Filename).
write_char(Ch) :- put(Ch).
write_term(X) :- write(X).
newline :- nl.
close_output :- told.
eoln(10).
append([],L,L).
append([E|X],Y,[E|Z]) :- append(X,Y,Z).
reverse(L1,L2) :- reverse_aux(L1,[],L2).
reverse_aux([],L,L).
reverse_aux([X|Y],L1,L2) :- reverse_aux(Y,[X|L1],L2).
symbol([]) :- !, fail.
symbol(X) :- atom(X).
% -----------------------------------------------------------------------------
% Compiler option management.
option_on(X) :- retract(options(Y)), !, union(X,Y,Z), asserta(options(Z)).
option_off(X) :- retract(options(Y)), !, difference(Y,X,Z), asserta(options(Z)).
option(X) :- options(O), memb(X,O).
:- dynamic options/1.
options([]).
integrate(all) :- !, option_on([int(car),int(cdr),int('+'),int('-'),int('*'),
int('/'),int('-1+')]).
integrate(none) :- !, option_off([int(car),int(cdr),int('+'),int('-'),int('*'),
int('/'),int('-1+')]).
integrate(X) :- option_on([int(X)]).
debug(on) :- option_on([debug]).
debug(off) :- option_off([debug]).
trace(on) :- option_on([trace]).
trace(off) :- option_off([trace]).
% -----------------------------------------------------------------------------
% Parser.
parse(I,Program) :-
write_term('1) Reading input...'), newline,
open_input(I), get_source(Source), !, close_input,
write_term(' ...done'), newline,
write_term('2) Parsing...'), newline,
white(Source,Start), sexprs(Program,Start,[]), !,
write_term(' ...done'), newline.
get_source(S) :- read_char(C), get_source(C,S).
get_source(eof,[]) :- !.
get_source(C,[C|S]) :- get_source(S).
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
% Use DCG for parser.
blank --> [C], {C =< 32}, white.
blank --> ";", comment, white.
white --> blank.
white --> [].
comment --> [C], {eoln(C)}, !.
comment --> [C], comment.
sexprs([H|T]) --> sexpr(H), !, sexprs(T).
sexprs([]) --> [].
sexpr(L) --> "(", !, white, sexpr_list(L), white.
sexpr(vec(V)) --> "#(", !, sexpr_vector(V), white.
sexpr(boo(t)) --> "#t", !, white.
sexpr(boo(f)) --> "#f", !, white.
sexpr(chr(N)) --> "#\", [C], !, {N is C}, white. % "
sexpr(str(S)) --> """", !, sexpr_string(S), white.
sexpr([quote,E]) --> "'", !, white, sexpr(E).
sexpr([quasiquote,E]) --> "`", !, white, sexpr(E).
sexpr(['unquote-splicing',E]) --> ",@", !, white, sexpr(E).
sexpr([unquote,E]) --> ",", !, white, sexpr(E).
sexpr(E) --> sym_or_num(E), white.
sexpr_list([]) --> ")", !.
sexpr_list(_) --> ".", [C], {\+ sym_char(C)}, !, fail.
sexpr_list([Car|Cdr]) --> sexpr(Car), !, sexpr_rest(Cdr).
sexpr_rest([]) --> ")", !.
sexpr_rest(E) --> ".", [C], {\+ sym_char(C)}, !, sexpr(E,C), !, ")".
sexpr_rest([Car|Cdr]) --> sexpr(Car), !, sexpr_rest(Cdr).
sexpr_vector([]) --> ")", !.
sexpr_vector([First|Rest]) --> sexpr(First), !, sexpr_vector(Rest).
sexpr_string([]) --> """", !.
sexpr_string([C|S]) --> chr(C), sexpr_string(S).
chr(92) --> "\\", !.
chr(34) --> "\""", !. % "
chr(N) --> [C], {C >= 32, N is C}.
sym_or_num(E) --> [C], {sym_char(C)}, sym_string(S), {string_to_atom([C|S],E)}.
sym_string([H|T]) --> [H], {sym_char(H)}, sym_string(T).
sym_string([]) --> [].
number(N) --> unsigned_number(N).
number(N) --> "-", unsigned_number(M), {N is -M}.
number(N) --> "+", unsigned_number(N).
unsigned_number(N) --> digit(X), unsigned_number(X,N).
unsigned_number(N,M) --> digit(X), {Y is N*10+X}, unsigned_number(Y,M).
unsigned_number(N,N) --> [].
digit(N) --> [C], {C >= 48, C =<57, N is C-48}.
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
sexpr(E,C,X,Z) :- white([C|X],Y), sexpr(E,Y,Z).
sym_char(C) :- C > 32, \+ memb(C,";()#""',`").
string_to_atom(S,N) :- number(N,S,[]), !.
string_to_atom(S,I) :- lowcase(S,L), name(I,L).
lowcase([],[]).
lowcase([C1|T1],[C2|T2]) :- lowercase(C1,C2), lowcase(T1,T2).
lowercase(C1,C2) :- C1 >= 65, C1 =< 90, !, C2 is C1+32.
lowercase(C,C).
% -----------------------------------------------------------------------------
% Compilation.
compile(Program,Code) :-
write_term('3) Compilation...'), newline,
compile_list(Program,Expr), !,
write_term(' ...done'), newline,
write_term('4) Virtual machine code generation...'), newline,
gen_program(Expr,Code), !,
write_term(' ...done'), newline.
compile_list([],cst(U)) :- !, undefined(U).
compile_list([Expr],C) :- !, compile_expr(Expr,C).
compile_list([Expr|Tail],app([pro(['#'],none,[],[],Rest,[]),C])) :-
compile_expr(Expr,C),
compile_list(Tail,Rest).
compile_expr([define|Def],set(Var,C)) :- !,
definition(Def,[Var,Expr]),
write_term(' compiling '), write_term(Var), newline,
compile_expression(Expr,C).
compile_expr(Expr,C) :-
write_term(' compiling <expression>'), newline,
compile_expression(Expr,C).
compile_expression(E,C) :-
expand(E,X), % expand macros and convert to prolog structures
alpha(X,Y), % rename variables and convert assignments
closurize(Y,C). % find out which lambda-expression are actually going to
% be 'true' closures (i.e. they have closed variables)
% To add new predefined procedures, add their names to this list:
initial_global_env([
'#trace', '#make-promise', '#memv', '#cons', '#list', '#append', '#list->vector',
not, 'eq?', 'pair?', cons, append, length, car, cdr, 'set-car!', 'set-cdr!',
'null?', '=', '<', '>', '+', '-', '*', '/', '-1+', force, write, newline,
list, vector, 'list->vector', memq, assq, 'symbol?', 'vector?', 'string?',
'procedure?', 'number?', 'char?'
]).
% -----------------------------------------------------------------------------
% Code output to file.
write_code(Code,O) :-
write_term('5) Writing M68000 machine code...'), newline,
open_output(O),
emit_objects(Code,[],_), !,
close_output,
write_term(' ...done'), newline.
% Emit a sequence of Scheme objects (i.e. symbols, lists, vectors, strings
% and procedure definitions) to the output file. The complication is
% that writing an object might require writing others (e.g. for vectors
% the elements have to be written also (recursively)) and that a given
% symbol should only be output once.
emit_objects([],Syms,Syms).
emit_objects([Object|Tail],Syms1,Syms3) :-
emit_object(Object,Vals1,Syms1,Syms2),
append(Vals1,Tail,Vals2),
emit_objects(Vals2,Syms2,Syms3).
emit_object(obj(Label,S),Vals,Syms1,Syms2) :- symbol(S), !,
name(S,L),
conv_obj(str(L),String,[],Vals,Syms1,Syms2),
write_term(symbol_object(Label,String)), newline.
emit_object(obj(Label,[Car|Cdr]),Vals2,Syms1,Syms3) :-
conv_obj(Car,Car_val,[],Vals1,Syms1,Syms2),
conv_obj(Cdr,Cdr_val,Vals1,Vals2,Syms2,Syms3),
write_term(pair_object(Label,Car_val,Cdr_val)), newline.
emit_object(obj(Label,vec(L)),Vals,Syms1,Syms2) :-
length(L,Length),
write_term(vector_object(Label,Length)), newline,
emit_object_list(L,[],Vals,Syms1,Syms2).
emit_object(obj(Label,str(L)),[],Syms,Syms) :-
length(L,Length),
write_term(string_object), write_char(40),
write_term(Label), comma, emit_string(L), write_char(41), newline.
emit_object(obj(Label,pro(L,Source)),Vals,Syms1,Syms2) :-
write_term(procedure_object_begin(Label)), newline,
emit_instructions(L,[],Const1),
write_term(procedure_object_constants), newline,
genlabel(Source_label),
include_source(Source,Include),
append(Const1,[const(Source_label,Include)],Const2),
emit_constants(Const2,[],Vals,Syms1,Syms2),
write_term(procedure_object_end), newline.
emit_string(S) :- write_char(96), write_char(34),
emit_string2(S),
write_char(34), write_char(39).
emit_string2([]).
emit_string2([C|L]) :- (C<32;C=34;C=92;C>=127), !, write_char(92),
N1 is 48+(C // 64), write_char(N1),
N2 is 48+((C // 8) mod 8), write_char(N2),
N3 is 48+(C mod 8), write_char(N3),
emit_string2(L).
emit_string2([C|L]) :- write_char(C), emit_string2(L).
include_source(Source,Source) :- option(debug), !.
include_source(Source,[]).
emit_instructions([],Const,Const).
emit_instructions([Instr|Tail],Const1,Const3) :-
emit(Instr,Const1,Const2),
emit_instructions(Tail,Const2,Const3).
emit_constants([],Vals,Vals,Syms,Syms).
emit_constants([const(Label,Object)|Tail],Vals1,Vals3,Syms1,Syms3) :-
emit(label(Label)),
conv_obj(Object,Value,Vals1,Vals2,Syms1,Syms2),
opcode('.long'), label(Value), newline,
emit_constants(Tail,Vals2,Vals3,Syms2,Syms3).
emit_object_list([],Vals,Vals,Syms,Syms).
emit_object_list([Object|Tail],Vals1,Vals3,Syms1,Syms3) :-
conv_obj(Object,Value,Vals1,Vals2,Syms1,Syms2),
opcode('.long'), label(Value), newline,
emit_object_list(Tail,Vals2,Vals3,Syms2,Syms3).
conv_obj(Object,Value,Vals,Vals,Syms,Syms) :- non_gc(Object,Value), !.
conv_obj(Object,Value,Vals,Vals,Syms,Syms) :- memb(sym(Object,Value),Syms), !.
conv_obj(Object,Value,Vals,[obj(Value,Object)|Vals],Syms1,Syms2) :-
genlabel(Value),
intern_symbol(Object,Value,Syms1,Syms2).
intern_symbol(Object,Value,Syms,[sym(Object,Value)|Syms]) :- symbol(Object), !.
intern_symbol(Object,Value,Syms,Syms).
% -----------------------------------------------------------------------------
% Virtual machine implementation for MC68000.
% Each virtual instruction generated is expanded into MC68000 code. The
% virtual instructions are:
% label(Label) - declare a label
% dealloc(Depth) - deallocate words from the stack
% return(Depth) - deallocate and return to caller
% enter(Type,Nb_args,Kind) - enter a procedure of Nb_args parameters (Type
% is the type of procedure (either 'closure' or
% 'plain') and Kind specifies if the last
% parameter is a rest parameter)
% jump_glo(Disp,Nb_args) - jump to a global procedure
% jump(Src,Nb_args) - jump to a procedure (general form)
% sub_procedure(Label) - declare a sub-procedure label
% push_continuation(Label) - push a sub-procedure label (ie. a return addr.)
% branch_if_false(Src,Label) - branch to label if 'Src' is false
% branch_always(Label) - branch to label
% move(Src,Dest) - move 'Src' to 'Dest'
% set_glo(Disp,Src) - set a global variable
% set_clo(Depth,Disp,Src) - set a closed variable
% set_loc(Disp,Src) - set a local variable
% box_clo(Depth,Disp,Dest) - put a closed variable in a cell
% box_loc(Disp,Dest) - put a local variable in a cell
% get_clo(Depth,Disp,Dest) - fetch the value of a mutable closed variable
% get_loc(Disp,Dest) - fetch the value of a mutable local variable
% ref_glo(Disp,Dest) - fetch the value of a global variable
% ref_clo(Depth,Disp,Dest) - fetch the value of a closed variable
% ref_loc(Disp,Dest) - fetch the value of a local variable
% cst(Val,Dest) - move a constant value to 'Dest'
% make_closure(Body,Nb_closed,Dest) - make a closure with a given 'Body'
% close_loc(Disp) - add a local variable to a closure
% close_clo(Disp) - add a closed variable to a closure
% open_code(Proc,Nb_args) - open code the procedure 'Proc' taking
% 'Nb_args' arguments
integrable(car,1).
emit(open_code(car,1)) :-
opcode(movl), dregister(1), comma, aregister(0), newline,
opcode(movl), indirect(0,0), comma, dregister(1), newline.
integrable(cdr,1).
emit(open_code(cdr,1)) :-
opcode(movl), dregister(1), comma, aregister(0), newline,
opcode(movl), autodecr(0), comma, dregister(1), newline.
integrable('+',2).
emit(open_code('+',2)) :-
opcode(addl), dregister(2), comma, dregister(1), newline.
integrable('-',1).
emit(open_code('-',1)) :-
opcode(negl), dregister(1), newline.
integrable('-',2).
emit(open_code('-',2)) :-
opcode(subl), dregister(2), comma, dregister(1), newline.
integrable('*',2).
emit(open_code('*',2)) :-
opcode(asrl), immediate(3), comma, dregister(1), newline,
opcode(muls), dregister(2), comma, dregister(1), newline.
integrable('/',2).
emit(open_code('/',2)) :-
opcode(divs), dregister(2), comma, dregister(1), newline,
opcode(extl), dregister(1), newline,
opcode(asll), immediate(3), comma, dregister(1), newline.
integrable('-1+',1).
emit(open_code('-1+',1)) :-
opcode(subql), immediate(8), comma, dregister(1), newline.
emit(cst(Object,Dest),Const,Const) :- non_gc(Object,Value), !,
emit_non_gc(Value,Dest).
emit(cst(Object,Dest),Const,[const(Label,Object)|Const]) :- !,
genlabel(Label),
opcode(movl), label(Label), comma, destination(Dest), newline.
emit(make_closure(Proc,Nb_closed,Dest),Const,[const(Label,Proc)|Const]) :-
genlabel(Label),
Tag is Nb_closed+1-8192,
opcode(movw), immediate(Tag), comma, autoincr(5), newline,
opcode(movl), aregister(5), comma, destination(Dest), newline,
opcode(movw), immediate(20153), comma, autoincr(5), newline,
opcode(movl), label(Label), comma, autoincr(5), newline.
emit(Instr,Const,Const) :- emit(Instr).
emit(ref_loc(Disp,Dest)) :-
Byte_disp is Disp*4,
opcode(movl), indirect(7,Byte_disp), comma, destination(Dest), newline.
emit(ref_clo(Depth,Disp,Dest)) :-
Byte_depth is Depth*4-4,
Byte_disp is Disp*4+6,
opcode(movl), indirect(7,Byte_depth), comma, aregister(0), newline,
opcode(movl), indirect(0,Byte_disp), comma, destination(Dest), newline.
emit(ref_glo(Disp,Dest)) :-
Byte_disp is Disp*6+6,
opcode(movl), indirect(6,Byte_disp), comma, destination(Dest), newline.
emit(get_loc(Disp,Dest)) :-
emit(ref_loc(Disp,-1)),
opcode(movl), indirect(0,0), comma, destination(Dest), newline.
emit(get_clo(Depth,Disp,Dest)) :-
emit(ref_clo(Depth,Disp,-1)),
opcode(movl), indirect(0,0), comma, destination(Dest), newline.
emit(box_loc(Disp,Dest)) :-
emit(ref_loc(Disp,0)),
opcode(movl), dregister(0), comma, autodecr(4), newline,
opcode(movl), aregister(4), comma, destination(Dest), newline,
opcode(movl), dregister(0), comma, autodecr(4), newline.
emit(box_clo(Depth,Disp,Dest)) :-
emit(ref_clo(Depth,Disp,0)),
opcode(movl), dregister(0), comma, autodecr(4), newline,
opcode(movl), aregister(4), comma, destination(Dest), newline,
opcode(movl), dregister(0), comma, autodecr(4), newline.
emit(set_loc(Disp,Src)) :-
emit(ref_loc(Disp,-1)),
opcode(movl), source(Src), comma, indirect(0,0), newline.
emit(set_clo(Depth,Disp,Src)) :-
emit(ref_clo(Depth,Disp,-1)),
opcode(movl), source(Src), comma, indirect(0,0), newline.
emit(set_glo(Disp,Src)) :-
Byte_disp1 is Disp*6+4,
Byte_disp2 is Disp*6+6,
opcode(movw), immediate(20115), comma, indirect(6,Byte_disp1), newline,
opcode(movl), source(Src), comma, indirect(6,Byte_disp2), newline.
emit(move(X,X)) :- !.
emit(move(Src,Dest)) :-
opcode(movl), destination(Src), comma, destination(Dest), newline.
emit(branch_always(Label)) :-
opcode(bra), label(Label), newline.
emit(branch_if_false(Src,Label)) :-
opcode(addql), immediate(3), comma, source(Src), newline,
opcode(bcs), label(Label), newline.
emit(push_continuation(Label)) :- !,
opcode(pea), label(Label), newline.
emit(close_loc(Disp)) :-
Byte_disp is Disp*4,
opcode(movl), indirect(7,Byte_disp), comma, autoincr(5), newline.
emit(close_clo(Depth,Disp)) :-
Byte_depth is Depth*4-4,
Byte_disp is Disp*4+6,
opcode(movl), indirect(7,Byte_depth), comma, aregister(0), newline,
opcode(movl), indirect(0,Byte_disp), comma, autoincr(5), newline.
emit(sub_procedure(Label)) :-
write_term(sub_procedure(Label)), newline.
emit(jump(Src,Nb_args)) :-
nb_arg_code(Nb_args,Code),
genlabel(Error),
opcode(btst), source(Src), comma, dregister(7), newline,
opcode(beqs), label(Error), newline,
opcode(movl), source(Src), comma, aregister(0), newline,
opcode(tstw), indirect(0,-2), newline,
opcode(bpls), label(Error), newline,
opcode(moveq), immediate(Code), comma, dregister(0), newline,
opcode(jmp), indirect(0,0), newline,
emit(label(Error)),
opcode(jmp), indirect(6,-510), newline.
emit(jump_glo(Disp,Nb_args)) :-
nb_arg_code(Nb_args,Code),
Byte_disp is Disp*6+4,
opcode(moveq), immediate(Code), comma, dregister(0), newline,
opcode(jmp), indirect(6,Byte_disp), newline.
emit(return(Depth)) :-
emit(dealloc(Depth),Const,Const),
opcode(rts), newline.
emit(dealloc(0)) :- !.
emit(dealloc(Depth)) :- Depth =< 2, !,
Byte_depth is Depth*4,
opcode(addql), immediate(Byte_depth), comma, aregister(7), newline.
emit(dealloc(Depth)) :-
Byte_depth is Depth*4,
opcode(addw), immediate(Byte_depth), comma, aregister(7), newline.
emit(label(Label)) :-
label(Label), write_char(58), newline.
emit(enter(Type,Nb_args,rest)) :-
genlabel(Label),
rest_enter(Type,Handler),
opcode(movw), immediate(Nb_args), comma, aregister(0), newline,
opcode(lea), label(Label), comma, aregister(1), newline,
opcode(jmp), indirect(6,Handler), newline,
emit(sub_procedure(Label)).
emit(enter(plain,Nb_args,none)) :-
genlabel(Error),
genlabel(Continue),
emit_arg_check(Nb_args,Error),
opcode(cmpl), indirect(6,0), comma, aregister(7), newline,
opcode(bhis), label(Continue), newline,
emit(label(Error)),
opcode(jmp), indirect(6,-522), newline,
emit(label(Continue)),
emit_push_args(Nb_args).
emit(enter(closure,Nb_args,none)) :-
genlabel(Error),
genlabel(Continue),
emit_arg_check(Nb_args,Error),
opcode(cmpl), indirect(6,0), comma, aregister(7), newline,
opcode(bhis), label(Continue), newline,
emit(label(Error)),
opcode(jmp), indirect(6,-516), newline,
emit(label(Continue)),
opcode(subql), immediate(6), comma, indirect(7,0), newline,
emit_push_args(Nb_args).
rest_enter(plain,-534).
rest_enter(closure,-528).
emit_arg_check(1,Label) :- !,
opcode(bpls), label(Label), newline.
emit_arg_check(2,Label) :- !,
opcode(bnes), label(Label), newline.
emit_arg_check(N,Label) :- N < 8, !,
M is N+1,
opcode(subqw), immediate(M), comma, dregister(0), newline,
opcode(bnes), label(Label), newline.
emit_arg_check(N,Label) :-
M is N+1,
opcode(subw), immediate(M), comma, dregister(0), newline,
opcode(bnes), label(Label), newline.
emit_push_args(0) :- !.
emit_push_args(1) :- !,
opcode(movl), dregister(1), comma, destination(push), newline.
emit_push_args(2) :- !,
opcode(movl), dregister(2), comma, destination(push), newline,
opcode(movl), dregister(1), comma, destination(push), newline.
emit_push_args(3) :- !,
opcode(moveml), immediate(28672), comma, destination(push), newline.
emit_push_args(4) :- !,
opcode(moveml), immediate(30720), comma, destination(push), newline.
emit_push_args(N) :- !,
emit_push_arg(N),
emit_push_args(4).
emit_push_arg(4) :- !.
emit_push_arg(N) :-
Dist is -4*N, M is N-1,
opcode(movl), indirect(6,Dist), comma, destination(push), newline,
emit_push_arg(M).
nb_arg_code(1,-1) :- !.
nb_arg_code(2,0) :- !.
nb_arg_code(N,M) :- M is N+1.
non_gc(Val,Value) :- integer(Val), Value is Val*8.
non_gc([],-1).
non_gc(boo(f),-3).
non_gc(boo(t),-5).
non_gc(Val,-7) :- undefined(Val).
non_gc(chr(N),Value) :- Value is N*2-131071.
data_reg(N) :- integer(N), 1 =< N, N =< 4.
emit_non_gc(Value,Dest) :- -128=<Value, Value<128, \+ data_reg(Dest), !,
opcode(moveq), immediate(Value), comma, dregister(0), newline,
emit(move(0,Dest)).
emit_non_gc(Value,Dest) :- -128=<Value, Value<128, Dest>=0, !,
opcode(moveq), immediate(Value), comma, destination(Dest), newline.
emit_non_gc(Value,Dest) :-
opcode(movl), immediate(Value), comma, destination(Dest), newline.
label(Label) :-
write_term(Label).
opcode(Op) :- write_char(9), write_term(Op), write_char(9).
comma :- write_char(44).
immediate(N) :- write_char(35), write_term(N).
aregister(N) :- write_char(97), write_term(N).
dregister(N) :- write_char(100), write_term(N).
indirect(Areg,0) :- !,
aregister(Areg),
write_char(64).
indirect(Areg,Disp) :-
aregister(Areg),
write_char(64),
write_char(40),
write_term(Disp),
write_char(41).
autoincr(N) :- indirect(N,0), write_char(43).
autodecr(N) :- indirect(N,0), write_char(45).
destination(push) :- !, autodecr(7).
destination(pop) :- !, autoincr(7).
destination(top) :- !, indirect(7,0).
destination(N) :- N < 0, !, M is -1-N, aregister(M).
destination(N) :- N > 4, !, Byte_disp is -4*N, indirect(6,Byte_disp).
destination(N) :- dregister(N).
source(push) :- !, destination(top).
source(pop) :- !, destination(top).
source(X) :- destination(X).
% -----------------------------------------------------------------------------
% Symbol generation routines.
genvar(V) :- gensym('#',V).
genlabel(V) :- gensym(l,V).
gensym(Name,S) :-
gennum(N),
name(Name,S1),
name(N,S2),
append(S1,S2,S3),
name(S,S3), !.
gennum(N) :-
last_num(LN),
N is LN+1,
retract(last_num(LN)), !,
asserta(last_num(N)).
:- dynamic last_num/1.
last_num(0).
% -----------------------------------------------------------------------------
% Mutable variable analysis.
% Compute the set of all variables which are assigned in a given expression.
mut_vars(Expr,L) :- mut_vars(Expr,[],L).
mut_vars(cst(C),Env,[]).
mut_vars(ref(V),Env,[]).
mut_vars(set(V,E),Env,S) :- free_var(V,Env,X), mut_vars(E,Y), union(X,Y,S).
mut_vars(tst(X,Y,Z),Env,S) :- mut_list([X,Y,Z],Env,S).
mut_vars(pro(P,K,B,_),Env,S) :- append(P,Env,X), mut_vars(B,X,S).
mut_vars(app(L),Env,S) :- mut_list(L,Env,S).
mut_list([],Env,[]).
mut_list([E|Tail],Env,S) :-
mut_vars(E,Env,X),
mut_list(Tail,Env,Y),
union(X,Y,S).
mut_bindings([],_,[]).
mut_bindings([V|Tail],Vals,S) :-
memb(val(V,Val),Vals),
mut_vars(Val,X),
mut_bindings(Tail,Vals,Y),
union(X,Y,S).
% -----------------------------------------------------------------------------
% Free variable analysis.
% Compute the set of all free variables in a given expression.
free_vars(Expr,L) :- free_vars(Expr,[],L).
free_vars(cst(C),Env,[]).
free_vars(ref(V),Env,S) :- free_var(V,Env,S).
free_vars(get(V),Env,S) :- free_var(V,Env,S).
free_vars(box(V),Env,S) :- free_var(V,Env,S).
free_vars(set(V,E),Env,S) :- free_var(V,Env,X), free_vars(E,Y), union(X,Y,S).
free_vars(tst(X,Y,Z),Env,S) :- free_list([X,Y,Z],Env,S).
free_vars(pro(P,K,B,_),Env,S) :- append(P,Env,X), free_vars(B,X,S).
free_vars(app(L),Env,S) :- free_list(L,Env,S).
free_list([],Env,[]).
free_list([E|Tail],Env,S) :-
free_vars(E,Env,X),
free_list(Tail,Env,Y),
union(X,Y,S).
free_var(V,Env,[]) :- memb(V,Env), !.
free_var(V,Env,[V]).
% -----------------------------------------------------------------------------
% Normalization of expressions.
% The input is an S-expression that follows Scheme's syntax for expressions.
% The resulting expression will only contain the following structures:
%
% cst(C) a constant of value 'C'
% ref(V) a reference to variable 'V'
% set(V,X) an assignment of expression 'X' to variable 'V'
% tst(X,Y,Z) a conditionnal expression (X=test,Y=consequent,Z=alternative)
% app(L) an application (first expr in 'L'=procedure, rest=arguments)
% pro(P,K,B,S) a procedure (lambda-expression) having 'P' as formal
% parameters (i.e. the list of all parameters in order),
% the expression 'B' as body and 'S' as source-code ('K' is
% 'rest' if there is a rest parameter and 'none' otherwise)
%
% Most of the conversion is done through macro expansion and is fairly
% straightforward. The hardest expressions to convert are mutually or
% self-recursive expressions (such as 'letrec's, 'define's, etc...).
% They are converted first by doing a topological sort on the sub-expressions
% according to the variable dependencies between them. The equivalent of a
% cascade of 'let's is generated for the expressions which are not really
% recursive. When they really are recursive (i.e. a cycle has been discovered
% while doing the topological sort), a method involving a kind of 'Y' operator
% is used. I will not describe it in detail but here is an example that gives
% a flavor of what is done:
%
% (letrec ((fact (lambda (x) (if (< x 2) 1 (* x (fact (- x 1))))))) (fact 5))
%
% is converted into the equivalent of:
%
% (let ((fact (lambda (fact)
% (lambda (x)
% (let ((fact (fact fact)))
% (if (< x 2) 1 (* x (fact (- x 1)))))))))
% (let ((fact (fact fact)))
% (fact 5)))
%
% There is an added complication when the recursive expressions are bound
% to mutable variables. In this case, an allocate/assign/use form must
% be generated. For example,
%
% (letrec ((loop (lambda () (loop)))) (set! loop read))
%
% is transformed into the equivalent of:
%
% (let ((loop 'undefined))
% (set! loop (lambda () (loop)))
% (set! loop read))
expand([H|T],X) :- !, expnd([H|T],X).
expand(V,ref(V)) :- symbol(V), !.
expand(C,cst(C)).
expnd([quote,X],cst(X)) :- !.
expnd(['set!',V,E],set(V,X)) :- !, expand(E,X).
expnd([if,X,Y],Z) :- undefined(U), !, expand([if,X,Y,U],Z).
expnd([if,X,Y,Z],tst(A,B,C)) :- !, expand(X,A), expand(Y,B), expand(Z,C).
expnd([lambda,Parms|X],pro(P,K,B,[lambda,Parms|X])) :- !,
parameters(Parms,P,K), body(X,B).
expnd([letrec,Bindings|Exprs],Y) :- !, body(Exprs,X), letrec(Bindings,X,Y).
expnd([begin|Tail],Y) :- !, expnd_list(Tail,X), begin(X,Y).
expnd(X,Z) :- macro(X,Y), !, expand(Y,Z).
expnd(X,Z) :- expnd_list(X,Y), add_trace(X,Y,Z).
add_trace(X,Y,app([pro(Temps,none,Z,[])|Y])) :- option(trace), !,
make_temps(Y,Temps),
ref_list(Temps,Refs),
begin([app([ref('#trace'),app([ref('#list')|Refs])]),app(Refs)],Z).
add_trace(X,Y,app(Y)).
make_temps([],[]).
make_temps([E|Tail1],[V|Tail2]) :- genvar(V), make_temps(Tail1,Tail2).
parameters(Param_pattern,Params,Kind) :- params(Param_pattern,Kind,[],Params).
params([],none,P,P) :- !.
params([V|Tail],R,P1,P3) :- !, param_add(V,P1,P2), params(Tail,R,P2,P3).
params(V,rest,P1,P2) :- param_add(V,P1,P2).
param_add(V,_,_) :- \+ symbol(V), !,
error("Variable name must be a symbol").
param_add(V,P,_) :- memb(V,P), !,
error("Duplicate variable name in binding list").
param_add(V,P1,P2) :- append(P1,[V],P2).
expnd_list([],[]).
expnd_list([X|Tail1],[Y|Tail2]) :- expand(X,Y), expnd_list(Tail1,Tail2).
begin([E],E).
begin([E|Tail],app([pro([V],none,X,[]),E])) :- begin(Tail,X), genvar(V).
body(Exprs,Z) :-
local_defs(Exprs,Defs,Body),
expnd_list(Body,X),
begin(X,Y),
letrec(Defs,Y,Z).
local_defs([[define|Def1]|Tail1],[Def2|Tail2],B) :- !,
definition(Def1,Def2),
local_defs(Tail1,Tail2,B).
local_defs(B,[],B).
definition([[Variable|Formals]|Body],[Variable,[lambda,Formals|Body]]) :- !.
definition([Variable,Expression],[Variable,Expression]) :- !.
definition([Variable],[Variable,U]) :- undefined(U).
letrec(Bindings,Body,X) :-
split(Bindings,Vars,Vals),
dependency_graph(Vals,Vars,Dep),
topological_sort(Dep,Binding_order),
bind_in_order(Binding_order,Body,Vals,X).
split([],[],[]).
split([[Var,Val]|Tail1],Vars2,[val(Var,X)|Tail2]) :-
expand(Val,X),
split(Tail1,Vars1,Tail2),
union([Var],Vars1,Vars2).
dependency_graph([],_,[]).
dependency_graph([val(Var,Val)|Tail1],Vars,[node(Var,Dep,_)|Tail2]) :-
free_vars(Val,L),
intersection(Vars,L,Dep),
dependency_graph(Tail1,Vars,Tail2).
bind_in_order([],Body,Vals,Body).
bind_in_order([Bindings|Tail],Body,Vals,X) :-
bind_in_order(Tail,Body,Vals,New_body),
bind_level(Bindings,New_body,Vals,X).
bind_level(V,Body,Vals,app([pro([V],none,Body,[]),Val])) :- symbol(V), !,
memb(val(V,Val),Vals).
bind_level(L,Body,Vals,X) :- lambdas(L,Vals), !,
mut_bindings(L,Vals,Mut1),
mut_vars(Body,Mut2),
union(Mut1,Mut2,Mut3),
intersection(Mut3,L,Mut),
difference(L,Mut,Non_mut),
bind_cyclic(Mut,Non_mut,Body,Vals,X).
bind_level(_,_,_,_) :-
error("untransformable cyclical definition").
lambdas([],_).
lambdas([V|Tail],Vals) :- memb(val(V,pro(_,_,_,_)),Vals), lambdas(Tail,Vals).
bind_cyclic([],Non_mut,Body,Vals,X) :- !,
bind_non_mut(Non_mut,Body,Vals,X).
bind_cyclic(Mut,Non_mut,Body,Vals,app([pro(Mut,none,Z,[])|Undefs])) :- !,
bind_mut(Mut,Vals,Undefs,Assignments),
append(Assignments,[Body],X),
begin(X,Y),
bind_non_mut(Non_mut,Y,Vals,Z).
bind_mut([],_,[],[]).
bind_mut([V|Tail1],Vals,[U|Tail2],[set(V,Val)|Tail3]) :-
undefined(U),
memb(val(V,Val),Vals),
bind_mut(Tail1,Vals,Tail2,Tail3).
bind_non_mut([],Body,_,Body) :- !.
bind_non_mut(L,Body,Vals,
app([pro(L,none,app([pro(L,none,Body,[])|V1]),[])|V2])) :-
fix_procs1(L,L,V1),
fix_procs2(L,L,Vals,V1,V2).
fix_procs1(L,[],[]).
fix_procs1(L,[V|Tail1],[app(X)|Tail2]) :-
ref_list([V|L],X),
fix_procs1(L,Tail1,Tail2).
fix_procs2(L,[],_,_,[]).
fix_procs2(L,[V|T1],Vals,V1,
[pro(L,none,pro(X,Y,app([pro(L,none,Z,[])|V1]),S),[])|T2]) :-
memb(val(V,pro(X,Y,Z,S)),Vals),
fix_procs2(L,T1,Vals,V1,T2).
ref_list([],[]).
ref_list([V|Tail1],[ref(V)|Tail2]) :- ref_list(Tail1,Tail2).
undefined(spc(undef)).
% -----------------------------------------------------------------------------
% Macro definitions.
% (quasiquote A) -->
macro([quasiquote,X],Y) :- template(X,1,Y).
template(X,0,X) :- !.
template([unquote,X],1,X) :- !.
template(['unquote-splicing'],1,_) :- !,
error("Misplaced 'unquote-splicing' special form").
template([quasiquote,X],N,Y) :- !, M is N+1, list_template([quasiquote,X],M,Y).
template([unquote,X],N,Y) :- !, M is N-1, list_template([unquote,X],M,Y).
template([Car|Cdr],N,Y) :- list_template([Car|Cdr],N,Y).
template(vec(L),N,Y) :- vector_template(L,N,X), vectorize_form(X,Y).
template(X,N,[quote,X]).
list_template([['unquote-splicing',X]],1,X) :- !.
list_template([['unquote-splicing',X]|Cdr],1,Y) :- !,
template(Cdr,1,A),
append_forms(X,A,Y).
list_template([Car|Cdr],N,Y) :-
template(Car,N,A),
template(Cdr,N,B),
cons_forms(A,B,Y).
vector_template([['unquote-splicing',X]],1,X) :- !.
vector_template([['unquote-splicing',X]|Cdr],1,Y) :- !,
vector_template(Cdr,1,A),
append_forms(X,A,Y).
vector_template([],N,[]) :- !.
vector_template([Car|Cdr],N,Y) :-
template(Car,N,A),
vector_template(Cdr,N,B),
cons_forms(A,B,Y).
append_forms([quote,X],[quote,Y],[quote,Z]) :- !, append(X,Y,Z).
append_forms(X,Y,['#append',X,Y]).
cons_forms([quote,X],[quote,Y],[quote,[X|Y]]) :- !.
cons_forms(X,Y,['#cons',X,Y]).
vectorize_form([quote,X],[quote,vec(X)]) :- !.
vectorize_form(X,['#list->vector',X]).
% (unquote A) --> error
macro([unquote,X],_) :-
error("Misplaced 'unquote' special form").
% (unquote-splicing A) --> error
macro(['unquote-splicing',X],_) :-
error("Misplaced 'unquote-splicing' special form").
% (let ((a A)...) B C...) --> ((lambda (a...) B C...) A...)
% and
% (let name ((a A)...) B C...) -->
% ((letrec ((name (lambda (a...) B C...))) name) A...)
macro([let,Name,Bindings|Body],
[[letrec,[[Name,[lambda,Vars|Body]]],Name]|Exprs]) :- symbol(Name), !,
let_bindings(Bindings,Vars,Exprs).
macro([let,Bindings|Body],[[lambda,Vars|Body]|Exprs]) :-
let_bindings(Bindings,Vars,Exprs).
let_bindings([],[],[]).
let_bindings([[V,E]|X],[V|Y],[E|Z]) :- let_bindings(X,Y,Z).
% (let* () A B...) --> (let () A B...)
% and
% (let* ((a A)) B C...) --> (let ((a A)) B C...)
% and
% (let* ((a A) (b B) (c C)...) D E...) -->
% (let ((a A)) (let* ((b B) (c C)...) D E...)
macro(['let*',[]|Body],[let,[]|Body]) :- !.
macro(['let*',[[V,E]]|Body],[let,[[V,E]]|Body]) :- !.
macro(['let*',[[V,E]|Tail]|Body],[let,[[V,E]],['let*',Tail|Body]]).
% (and A) --> A
% and
% (and A B C...) --> (let ((@ A)) (if @ (and B C...) @))
macro([and,E],E) :- !.
macro([and,E|Tail],[let,[[V,E]],[if,V,[and|Tail],V]]) :- genvar(V).
% (or A) --> A
% and
% (or A B C...) --> (let ((@ A)) (if @ @ (or B C...)))
macro([or,E],E) :- !.
macro([or,E|Tail],[let,[[V,E]],[if,V,V,[or|Tail]]]) :- genvar(V).
% (cond) --> ?
% and
% (cond (else A B...)) --> (begin A B...)
% and
% (cond (A) (B C...)...) --> (or A (cond (B C...)...))
% and
% (cond (A B C...) (D E...)...) --> (if A (begin B C...) (cond (D E...)...))
% and
% (cond (A => B) (C D...)...) --> (let ((@ A)) (if @ (B @)
% (cond (C D...)...)))
macro([cond],U) :- !, undefined(U).
macro([cond,[else|Tail]],[begin|Tail]) :- !.
macro([cond,[E]|Tail],[or,E,[cond|Tail]]) :- !.
macro([cond,[E,'=>',P]|Tail],[let,[[V,E]],[if,V,[P,V],[cond|Tail]]]) :- !,
genvar(V).
macro([cond,[E|Tail1]|Tail2],[if,E,[begin|Tail1],[cond|Tail2]]).
% (case A ((x...) B C...)...) -->
% (let ((@ A)) (cond ((memv @ '(x...)) B C...)...))
macro([case,Key|Clauses],[let,[[V,Key]],[cond|X]]) :-
genvar(V),
cases(V,Clauses,X).
cases(V,[],[]) :- !.
cases(V,[[else|Tail]],[[else|Tail]]) :- !.
cases(V,[[Set|Tail1]|Tail2],[[['#memv',V,[quote,Set]]|Tail1]|X]) :-
cases(V,Tail2,X).
% (define ...) --> error
macro([define|_],_) :- error("Misplaced 'define' special form").
% (delay A) --> (make-promise (lambda () A))
macro([delay,E],['#make-promise',[lambda,[],E]]).
% (do ((a A B)...) (C D...) E F...) -->
% (let @ ((a A)...) (if C (begin ? D...) (let () E F... (@ a/B...))))
macro([do,Bindings,[Test|Result]|Body],
[let,Loop,Inits,[if,Test,[begin,U|Result],[let,[]|New_body]]]) :-
genvar(Loop),
undefined(U),
do_bindings(Bindings,Inits,Steps),
append(Body,[[Loop|Steps]],New_body).
do_bindings([],[],[]).
do_bindings([[V,I]|X],[[V,I]|Y],[V|Z]) :- do_bindings(X,Y,Z).
do_bindings([[V,I,S]|X],[[V,I]|Y],[S|Z]) :- do_bindings(X,Y,Z).
% -----------------------------------------------------------------------------
% Alpha conversion (renaming of variables) and assignment conversion.
% This phase renames all of the variables local to the expression (to eliminate
% aliasing problems) and adds 'boxes' (cells) to handle assignment to local
% variables. For each mutable variable (i.e. a local variable that is assigned
% somewhere in the expression), create a box containing the value of the
% variable. References to mutable variables is done by dereferencing the box
% it is associated to. For example, the normal form of this expression:
%
% (lambda (x y) (set! x (- x y)) x)
%
% is transformed into the equivalent of:
%
% (lambda (x y) (let ((x (box x))) (set-box! x (- (get x) y)) (get x)))
alpha(Expr,C) :- alpha(Expr,C,[]).
alpha(cst(C),cst(C),Env).
alpha(ref(V),get(T),Env) :- memb(var(V,T,mut),Env), !.
alpha(ref(V),ref(T),Env) :- memb(var(V,T,non_mut),Env), !.
alpha(ref(V),ref(V),Env).
alpha(set(V,E),set(T,C),Env) :- memb(var(V,T,mut),Env), !, alpha(E,C,Env).
alpha(set(V,E),set(V,C),Env) :- alpha(E,C,Env).
alpha(tst(X,Y,Z),tst(A,B,C),Env) :- alpha_list([X,Y,Z],[A,B,C],Env).
alpha(app(L),app(C),Env) :- alpha_list(L,C,Env).
alpha(pro(Params1,Kind,Body1,S),pro(Params2,Kind,Body3,S),Env) :-
mut_vars(Body1,Mutable),
rename(Mutable,Params1,Params2,Bindings,Box1,Box2),
append(Bindings,Env,New_env),
alpha(Body1,Body2,New_env),
alpha_pro(Box1,Box2,Body2,Body3).
alpha_pro([],_,Body,Body) :- !.
alpha_pro(Box1,Box2,Body,app([pro(Box2,none,Body,[])|X])) :- boxes(Box1,X).
boxes([],[]).
boxes([V|Tail1],[box(V)|Tail2]) :- boxes(Tail1,Tail2).
rename(Mut,[],[],[],[],[]).
rename(Mut,[V|T1],[X|T2],[var(V,Y,mut)|T3],[X|T4],[Y|T5]) :- memb(V,Mut), !,
genvar(X), genvar(Y), rename(Mut,T1,T2,T3,T4,T5).
rename(Mut,[V|T1],[X|T2],[var(V,X,non_mut)|T3],T4,T5) :-
genvar(X), rename(Mut,T1,T2,T3,T4,T5).
alpha_list([],[],Env).
alpha_list([E|T1],[C|T2],Env) :- alpha(E,C,Env), alpha_list(T1,T2,Env).
% -----------------------------------------------------------------------------
% Closure analysis.
% For every procedure definition (i.e. lambda-expression) in the given
% expression, compute the set of closed variables of the procedure
% and the set of parameters which are referenced in the procedure
% and augment the procedure definition by these sets. A closed variable
% is a variable that is declared_as in a lambda-expression and used
% in a sub-lambda-expression. For example, the expression:
%
% (lambda (x y z) (map (lambda (n) (+ y n)) x))
%
% would be augmented to this:
%
% (lambda (x y z) [] [x y] (map (lambda (n) [y] [n] (+ y n)) x))
%
% because,
% 'y' is a closed variable,
% 'map' and '+' are global variables,
% 'x', 'z' and 'n' are non-closed local variables.
closurize(Expr,C) :- closurize(Expr,C,[]).
closurize(cst(C),cst(C),Env).
closurize(ref(V),ref(V),Env).
closurize(get(V),get(V),Env).
closurize(box(V),box(V),Env).
closurize(set(V,E),set(V,C),Env) :-
closurize(E,C,Env).
closurize(tst(X,Y,Z),tst(A,B,C),Env) :-
closurize_list([X,Y,Z],[A,B,C],Env).
closurize(app(L),app(C),Env) :-
closurize_list(L,C,Env).
closurize(pro(Params,Kind,Body1,S),pro(Params,Kind,Closed,Used,Body2,S),Env) :-
free_vars(Body1,Free),
intersection(Free,Env,Closed),
make_set(Params,Vars),
intersection(Free,Vars,Used),
union(Vars,Env,New_env),
closurize(Body1,Body2,New_env).
closurize_list([],[],Env).
closurize_list([E|Tail1],[C|Tail2],Env) :-
closurize(E,C,Env),
closurize_list(Tail1,Tail2,Env).
% -----------------------------------------------------------------------------
% Code generation for the virtual machine.
gen_program(Expr,[obj(entry,pro(Main_code,[]))]) :-
initial_global_env(G1),
gen(Expr,t,env([],[],G1),env([],[],G2),Main_code,[]).
gen_procedure(Params,Kind,Closed,Body,Source,pro(Code1,Source),G1,G2) :-
gen_proc_entry(Params,Kind,Closed,Locals,Code1,Code2),
gen(Body,t,env(Locals,Closed,G1),env(Locals,Closed,G2),Code2,[]).
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
% Use DCG for code generation.
gen_proc_entry(Params1,Kind,[],Params2) --> !,
{length(Params1,Nb_args), reverse(Params1,Params2)},
[enter(plain,Nb_args,Kind)].
gen_proc_entry(Params1,Kind,Closed,[temp|Params2]) -->
{length(Params1,Nb_args), reverse(Params1,Params2)},
[enter(closure,Nb_args,Kind)].
% gen(Expr,Dest,Env1,Env2)
%
% Generate intermediate code for expression Expr given the run-time environment
% Env1. Env2 is the environment after having executed Expr. Dest specifies
% where to put the result: 'd' means discard the result, 't' means the
% expression is in tail position, 'push' means push the result on the run-time
% stack otherwise Dest is a virtual register number.
gen(cst(C),d,E1,E1) --> !, [].
gen(cst(C),t,E1,E2) --> !, gen(cst(C),1,E1,E2), gen_return(E2).
gen(cst(C),D,E1,E2) --> !, {fix(D,E1,E2)}, [cst(C,D)].
gen(ref(V),d,E1,E1) --> !, [].
gen(ref(V),t,E1,E2) --> !, gen(ref(V),1,E1,E2), gen_return(E2).
gen(ref(V),D,E1,E2) --> {loc(V,E1,X), fix(D,E1,E2)}, !, [ref_loc(X,D)].
gen(ref(V),D,E1,E2) --> {clo(V,E1,X,Y), fix(D,E1,E2)}, !, [ref_clo(X,Y,D)].
gen(ref(V),D,E1,E3) --> {glo(V,E1,E2,X), fix(D,E2,E3)}, !, [ref_glo(X,D)].
gen(get(V),d,E1,E1) --> !, [].
gen(get(V),t,E1,E2) --> !, gen(get(V),1,E1,E2), gen_return(E2).
gen(get(V),D,E1,E2) --> {loc(V,E1,X), fix(D,E1,E2)}, !, [get_loc(X,D)].
gen(get(V),D,E1,E2) --> {clo(V,E1,X,Y), fix(D,E1,E2)}, !, [get_clo(X,Y,D)].
gen(box(V),d,E1,E1) --> !, [].
gen(box(V),t,E1,E2) --> !, gen(box(V),1,E1,E2), gen_return(E2).
gen(box(V),D,E1,E2) --> {loc(V,E1,X), fix(D,E1,E2)}, !, [box_loc(X,D)].
gen(box(V),D,E1,E2) --> {clo(V,E1,X,Y), fix(D,E1,E2)}, !, [box_clo(X,Y,D)].
gen(set(V,E),d,E1,E2) --> !, gen(set(V,E),1,E1,E2).
gen(set(V,E),t,E1,E2) --> !, gen(set(V,E),1,E1,E2), gen_return(E2).
gen(set(V,E),D,E1,E3) --> !, gen(E,D,E1,E2), gen_set(V,D,E2,E3).
gen_set(V,S,E1,E1) --> {loc(V,E1,X)}, !, [set_loc(X,S)].
gen_set(V,S,E1,E1) --> {clo(V,E1,X,Y)}, !, [set_clo(X,Y,S)].
gen_set(V,S,E1,E2) --> {glo(V,E1,E2,X)}, !, [set_glo(X,S)].
gen(tst(X,Y,Z),t,E1,E5) --> !,
{genlabel(Label1)},
gen(X,1,E1,E2),
[branch_if_false(1,Label1)],
gen(Y,t,E2,E3),
[label(Label1)],
{join_env(E2,E3,E4)},
gen(Z,t,E4,E5).
gen(tst(X,Y,Z),D,E1,E5) -->
{genlabel(Label1), genlabel(Label2)},
gen(X,1,E1,E2),
[branch_if_false(1,Label1)],
gen(Y,D,E2,E3),
[branch_always(Label2)],
[label(Label1)],
{join_env(E2,E3,E4)},
gen(Z,D,E4,E5),
[label(Label2)].
gen(app([pro(P,none,C,U,B,_)|A]),D,E1,E2) --> !, gen_app_pro(P,C,U,B,A,D,E1,E2).
gen(app(L),d,E1,E2) --> !, gen(app(L),1,E1,E2).
gen(app([ref(V)|Args]),t,E1,E2) -->
{length(Args,Nb_args), option(int(V)), integrable(V,Nb_args)}, !,
gen_app_args(Args,1,E1,E2),
[open_code(V,Nb_args)],
gen_return(E2).
gen(app([ref(V)|Args]),t,E1,E3) --> {glo(V,E1,E2,X)}, !,
gen_app_args(Args,1,E2,E3),
{length(Args,Nb_args), depth(E3,Depth)},
[dealloc(Depth)],
[jump_glo(X,Nb_args)].
gen(app([Proc|Args]),t,E1,E2) --> !,
gen_app_args([Proc|Args],0,E1,E2),
{depth(E2,Depth), length(Args,Nb_args)},
[dealloc(Depth)],
[jump(0,Nb_args)].
gen(app([ref(V)|Args]),D,E1,E4) -->
{length(Args,Nb_args), option(int(V)), integrable(V,Nb_args)}, !,
gen_app_args(Args,1,E1,E2),
[open_code(V,Nb_args)],
[move(1,D)],
{join_env(E1,E2,E3), fix(D,E3,E4)}.
gen(app([ref(V)|Args]),D,E1,E5) --> {glo(V,E1,E2,X)}, !,
gen_app_args(Args,1,E2,E3),
{genlabel(Label), length(Args,Nb_args)},
[push_continuation(Label)],
[jump_glo(X,Nb_args)],
[sub_procedure(Label)],
[move(1,D)],
{join_env(E1,E3,E4), fix(D,E4,E5)}.
gen(app([Proc|Args]),D,E1,E4) --> !,
gen_app_args([Proc|Args],0,E1,E2),
{genlabel(Label), length(Args,Nb_args)},
[push_continuation(Label)],
[jump(0,Nb_args)],
[sub_procedure(Label)],
[move(1,D)],
{join_env(E1,E2,E3), fix(D,E3,E4)}.
gen_app_args(L,N,E1,E3) -->
{split_args(L,N,Non_trivial,Trivial)},
gen_non_trivial_args(Non_trivial,E1,E2),
gen_trivial_args(Trivial,E2,E3).
gen_non_trivial_args([],E1,E1) --> !, [].
gen_non_trivial_args([arg(Dest,Arg)],E1,E2) --> !,
gen(Arg,1,E1,E2),
[move(1,Dest)].
gen_non_trivial_args([arg(Dest,Arg)|Tail],E1,E4) --> !,
gen(Arg,push,E1,E2),
gen_non_trivial_args(Tail,E2,E3),
[move(pop,Dest)],
{fix(pop,E3,E4)}.
gen_trivial_args([],E1,E1) --> [].
gen_trivial_args([arg(Dest,Arg)|Tail],E1,E3) -->
gen(Arg,Dest,E1,E2),
gen_trivial_args(Tail,E2,E3).
gen_app_pro(P,C,U,B,A,D,E1,E5) -->
gen_alloc_args(P,U,A,N,E1,E2),
gen_body(B,D,N,E2,E3),
{join_env(E1,E3,E4), fix(D,E4,E5)}.
gen_alloc_args([],U,[],0,E1,E1) --> !, [].
gen_alloc_args([V|Tail1],U,[A|Tail2],N,E1,E4) --> {memb(V,U)}, !,
gen(A,push,E1,E2),
{rename_temp(V,E2,E3)},
gen_alloc_args(Tail1,U,Tail2,M,E3,E4),
{N is M+1}.
gen_alloc_args([V|Tail1],U,[A|Tail2],N,E1,E3) --> !,
gen(A,d,E1,E2),
gen_alloc_args(Tail1,U,Tail2,N,E2,E3).
gen_body(B,D,0,E1,E2) --> !, gen(B,D,E1,E2).
gen_body(B,t,N,E1,E2) --> !, gen(B,t,E1,E2).
gen_body(B,push,N,E1,E2) --> !,
gen(B,1,E1,E2),
[dealloc(N)],
[move(1,push)].
gen_body(B,D,N,E1,E2) --> !,
gen(B,D,E1,E2),
[dealloc(N)].
gen(pro(Params,Kind,Closed,Used,Body,Source),d,E1,E1) --> !, [].
gen(pro(Params,Kind,Closed,Used,Body,Source),t,E1,E2) --> !,
gen(pro(Params,Kind,Closed,Used,Body,Source),1,E1,E2),
gen_return(E2).
gen(pro(Params,Kind,[],Used,Body,Source),D,env(L,C,G1),E) --> !,
{gen_procedure(Params,Kind,[],Body,Source,Proc,G1,G2),
fix(D,env(L,C,G2),E)},
[cst(Proc,D)].
gen(pro(Params,Kind,Closed,Used,Body,Source),D,env(L,C,G1),E) --> !,
{gen_procedure(Params,Kind,Closed,Body,Source,Proc,G1,G2),
fix(D,env(L,C,G2),E), length(Closed,Nb_closed)},
[make_closure(Proc,Nb_closed,D)],
gen_close_var(Closed,E).
gen_close_var([],Env) --> [].
gen_close_var([V|Tail],Env) --> {loc(V,Env,X)}, !,
[close_loc(X)],
gen_close_var(Tail,Env).
gen_close_var([V|Tail],Env) --> {clo(V,Env,X,Y)}, !,
[close_clo(X,Y)],
gen_close_var(Tail,Env).
gen_return(Env) -->
{depth(Env,Depth)},
[return(Depth)].
% . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
% Utilities for code generation.
join_env(env(L1,C,G1),env(L2,C,G2),env(L1,C,G2)).
depth(env(L,C,G),Depth) :- length(L,Depth).
loc(V,env(L,C,G),Y) :- length(L,Depth), position(V,L,X), Y is Depth-X-1.
clo(V,env(L,C,G),Depth,X) :- length(L,Depth), position(V,C,X).
glo(V,env(L,C,G),env(L,C,G),X) :-
\+ memb(V,L),
\+ memb(V,C),
position(V,G,X), !.
glo(V,env(L,C,G1),env(L,C,G2),X) :-
\+ memb(V,L),
\+ memb(V,C),
append(G1,[V],G2),
position(V,G2,X).
position(X,L,P) :- position(X,L,P,0).
position(X,[X|Tail],N,N) :- !.
position(X,[_|Tail],P,N) :- M is N+1, position(X,Tail,P,M).
fix(push,env(L1,C,G),env(L2,C,G)) :- !, append(L1,[temp],L2).
fix(pop,env(L1,C,G),env(L2,C,G)) :- !, append(L2,[_],L1).
fix(Dest,Env,Env).
rename_temp(V,env(L1,C,G),env(L3,C,G)) :-
append(L2,[temp],L1),
append(L2,[V],L3).
split_args([],N,[],[]).
split_args([Arg|Tail1],N,Tail2,[arg(N,Arg)|Tail3]) :- trivial(Arg), !,
M is N+1,
split_args(Tail1,M,Tail2,Tail3).
split_args([Arg|Tail1],N,Tail2,Tail3) :-
M is N+1,
split_args(Tail1,M,Tail4,Tail3),
append(Tail4,[arg(N,Arg)],Tail2).
trivial(cst(_)).
trivial(ref(_)).
trivial(get(_)).
trivial(box(_)).
% -----------------------------------------------------------------------------
% Set manipulation.
memb(X,[X|T]) :- !.
memb(X,[Y|T]) :- memb(X,T).
remove(E,[],[]) :- !.
remove(E,[E|T],T) :- !.
remove(E,[X|T],[X|S]) :- remove(E,T,S).
make_set([],[]).
make_set([X|Y],Z) :- make_set(Y,S), union([X],S,Z).
union([],S,S) :- !.
union(S,[],S) :- !.
union([E|T1],[E|T2],[E|T3]) :- !, union(T1,T2,T3).
union([E1|T1],[E2|T2],[E1|T3]) :- E1 @< E2, !, union(T1,[E2|T2],T3).
union([E1|T1],[E2|T2],[E2|T3]) :- E1 @> E2, !, union([E1|T1],T2,T3).
intersection([],S,[]) :- !.
intersection(S,[],[]) :- !.
intersection([E|T1],[E|T2],[E|T3]) :- !, intersection(T1,T2,T3).
intersection([E1|T1],[E2|T2],T3) :- E1 @< E2, !, intersection(T1,[E2|T2],T3).
intersection([E1|T1],[E2|T2],T3) :- E1 @> E2, !, intersection([E1|T1],T2,T3).
difference([],S,[]) :- !.
difference(S,[],S) :- !.
difference([E|T1],[E|T2],T3) :- !, difference(T1,T2,T3).
difference([E1|T1],[E2|T2],[E1|T3]) :- E1 @< E2, !, difference(T1,[E2|T2],T3).
difference([E1|T1],[E2|T2],T3) :- E1 @> E2, !, difference([E1|T1],T2,T3).
% -----------------------------------------------------------------------------
% Graph manipulation.
% A graph is a set of nodes of the form: node(Name,Set_of_neighbors,Info)
% Transitive closure of a graph.
transitive_closure(G1,G2) :-
add_neighbors(G1,X),
transitive_closure(G1,X,G2), !.
transitive_closure(X,X,X).
transitive_closure(_,G1,G2) :- transitive_closure(G1,G2).
add_neighbors(G1,G2) :- add_neighbors(G1,G1,G2).
add_neighbors(G,[],[]).
add_neighbors(G,[node(X,N1,Info)|Tail1],[node(X,N2,Info)|Tail2]) :-
union_of_neighbors(G,N1,N1,N2),
add_neighbors(G,Tail1,Tail2).
union_of_neighbors(G,[],N,N).
union_of_neighbors(G,[X|Tail],N1,N3) :-
memb(node(X,N,_),G),
union(N,N1,N2),
union_of_neighbors(G,Tail,N2,N3).
% Topological sorting (modified to handle cycles).
topological_sort(G1,L) :- transitive_closure(G1,G2), topo_sort(G2,L).
topo_sort([],[]).
topo_sort(G1,[X|Tail]) :- memb(node(X,[],_),G1), !,
remove_node(X,G1,G2),
topo_sort(G2,Tail).
topo_sort(G1,[N|Tail]) :-
topo_sort_find_cycle(G1,G1,N),
remove_nodes(N,G1,G2),
topo_sort(G2,Tail).
topo_sort_find_cycle(G,[node(X,N,_)|_],N) :- memb(X,N), cyclic(G,N,N), !.
topo_sort_find_cycle(G,[_|Tail],N) :- topo_sort_find_cycle(G,Tail,N).
cyclic(G,N,[]).
cyclic(G,N,[X|Tail]) :- memb(node(X,N,_),G), cyclic(G,N,Tail).
remove_nodes([],G,G).
remove_nodes([X|Tail],G1,G3) :- remove_node(X,G1,G2), remove_nodes(Tail,G2,G3).
remove_node(X,[],[]) :- !.
remove_node(X,[node(X,_,_)|Tail1],Tail2) :- !, remove_node(X,Tail1,Tail2).
remove_node(X,[node(Y,N1,Info)|Tail1],[node(Y,N2,Info)|Tail2]) :-
remove(X,N1,N2),
remove_node(X,Tail1,Tail2).
end_of_file.
SIS Compiler documentation
(Straightforward Implementation of Scheme)
(for SUN version 0.1, jan 26 1988)
By Marc Feeley
---------------------------------------------------------------------------
1. Using the compiler
The compiler comes with the following files:
doc this file
sc the compiler itself written in Quintus Prolog
header.s an assembly file containing the run-time system
asm command file to assemble the code generated by the compiler
queens.scm a couple of test files in scheme
fib.scm
tak.scm
sort.scm
To use the compiler, write the scheme program you want to compile into a
file; the file must have the extension '.scm' (for the sake of brevity
let's call it 'source.scm'). Then start your Prolog and load 'sc'. Type
the query 'ex.' to start the compiler. It will then ask for the name of
the file to compile; type the file's name without the extension (ie.
source). A trace of the compilation phases should appear. The file
'source.s' will be generated which contains an MC68000 assembly language
program. Exit Prolog and type 'asm source' this will assemble the
compiler's output and generate the file 'source', the executable image of
the program. To execute, type 'source'.
It is possible to ask for the open-coding of certain procedure calls
(presently only car, cdr, +, -, *, /, -1+). This can be done by
typing 'integrate(all).' before typing 'ex.'. This speeds up execution
by a small amount. However, open-coded procedures do not check the
type of their arguments or result, so be careful. To remove open-coding
type 'integrate(none).'. By typing the query 'debug(on).', the compiler
will generate code that will enable 'write' to print the source of the
procedures instead of just '#<procedure>'. Type 'debug(off).' to
generate the usual code.
Although the compiler adheres fairly closely to R3RS there are certain
restrictions. The most important of which are the lack of a GC and
the small number of primitive procedures implemented. However, all
special forms are implemented. You should read the comments in 'sc' for
more information. Here is a list of the primitives which are implemented:
not, eq?, pair?, cons, append, length, car, cdr, set-car!, set-cdr!,
null?, =, <, >, +, -, *, /, -1+, force, write, newline, list, vector,
list->vector, memq, assq, symbol?, vector?, string?, procedure?, number?,
char?
In Quintus Prolog you can pre-compile 'sc' to save time on the following
uses of the compiler. Simply type:
compile(sc).
when you are in Quintus (this gives some warning messages) and then type:
save('sc.bin').
On subsequent uses of the compiler, startup Quintus and then type the query:
restore('sc.bin').
The compiler itself is written in a fairly portable fashion. The main
system dependent code is for I/O. Interface procedures have been written
for I/O so only these have to be modified. The compiler uses 'retract'
and 'assert' statements (to generate symbols and so forth), which means
that some of the clauses have been declared_as 'dynamic'. On other Prologs
the 'dynamic' declarations might have to be removed.
2. How does it work?
Compilation is a 3 step process:
1 - Parse input (ie. generate parse tree for program)
2 - Compile program (ie. generate intermediate code)
3 - Generate assembly code (ie. transform interm. code to M68000 code)
2.1 Parsing
The first step consists in reading all the characters of the source file
into a list. This is not very efficient but it simplifies parsing.
The list is parsed using a DCG grammar description of Scheme. A parse
tree of the program is generated by the parser. A simple list
representation similar to Scheme's own representation for S-expressions
is used. For example, the expression
(DEFINE (weird x) (list x "ABC" 123 #t #(1 2 3)))
is represented by the Prolog structure:
[define,[weird,x],[list,x,str([65,66,67]),123,boo(t),vec([1,2,3])]]
Note: uppercase characters are automatically transformed to lowercase.
2.2 Compiling to intermediate code
This step takes the parse tree of the program and generates the
corresponding intermediate code (ie. pseudocode). Before the intermediate
code can actually be generated, the expressions must first be put into
a normal form. This simplifies case analysis in the code generator.
The normalization of the expressions is done in 3 steps.
1 - Macro expansion (to take care of derived special forms)
2 - Alphatization (ie. renaming of the variables) and
assignment conversion
3 - closure analysis
Most of macro expansion is straightforward. It's simplicity stems from
Prolog's ease of doing pattern matching and case analysis. The hardest
case to handle is mutually or self-recursive expressions (such as
'letrec's, 'define's, etc.). I will explain this case using an example.
Suppose the expression to compile is:
(letrec ((a (lambda (x) (b (+ x (c 1))))) ; def1
(b (lambda (x) (if (d x 0) (a x) (c x)))) ; def2
(c (lambda (x) (- x))) ; def3
(d (lambda (x y) (< x y)))) ; def4
(a (c -30))) ; body
The compiler will start by constructing the variable dependency graph
for the (local) variables in this expression. Thus for the example:
a <-----> b ( x --> y means x depends on y )
\ / |
\ / |
V V V
c d
It then does a topological sort on the graph to find out in which order
the variables should be bound. The topological sort also discovers
the cycles in the dependencies; these must be handled in a special manner.
Cyclical dependencies conversion involves a kind of 'Y' operator. For
the example we would obtain:
(let ((c (lambda (x) (- x))))
(let ((d (lambda (x y) (< x y))))
(let ((a (lambda (a b)
(lambda (x)
(let ((a (a a b))
(b (b a b)))
(b (+ x (c 1)))))))
(b (lambda (a b)
(lambda (x)
(let ((a (a a b))
(b (b a b)))
(if (d x 0) (a x) (c x)))))))
(let ((a (a a b))
(b (b a b)))
(a (c -30))))))
Think about it, it works... A more 'natural' conversion would be to
generate an allocate/assign/use form (as explained in the R3RS) but
our solution is entirely functional and through data-flow analysis the
compiler could recover the original expression's semantics (presently
the compiler is not that intelligent but it might come in the future).
After this phase, only the basic special form of expressions are left
in the program, ie.
- constant reference eg. 123
- variable reference eg. x
- assignement eg. (set! x 456)
- conditional expression eg. (if a b c)
- application eg. (list a b c)
- lambda-expression eg. (lambda (b) b)
Alphatization consists of renaming the local variables to prevent
aliasing problems. In this step, assignments are also converted into a
'functional' equivalent by introducing cells which hold the values
of mutable variables. This simplifies the handling of closures and
continuations since after this conversion, the value of any (non-global)
variable always stays the same after it has been bound. Only
data structures are mutable.
The last normalization step is closure analysis. It consists in anotating
each lambda-expression with the set of its closed variables (ie. the
free, non-global variables which are referenced in its body). Space for
these variables will be allocated in the closures generated for this
lambda-expression.
Once the program is normalized, it is passed to a DCG grammar in order to
generate the intermediate code. Code generation is case driven and
is basically a post-order traversal of the normalized parse tree.
However, several special cases are recognized for which efficient code
can be generated. This includes code for:
- the application of a procedure bound to a global variable
- the body of lambda-expressions with no closed variables
- the application of a lambda-expression (ie. a 'let')
- a 'let' variable which is not used in the body
- ordering of arguments to evaluate trivial arguments last
(ie. arguments which need only a small number of resources)
2.3 Assembly code generation
This step scans the intermediate code instruction stream and generates
the appropriate MC68000 code for them. The intermediate code is machine
independent where as the assembly code generated is MC68000 and 'run-time
structure' dependent. In theory, only this part has to be modified to
generate code for another machine.
In addition, this step is responsible for the 'dumping' of Scheme objects
to the code file. These are most often the constants contained in the
source program. For example, if the following expression were compiled:
(member 'b '(a b c))
the symbols a, b and c and the list (a b c) would be 'dumped' to the code
file (and the symbol b would be dumped only once).
3. Benchmarks
We have run the compiler on a few benchmark programs. No special declarations
were used and the programs were run on a SUN3. Here are the results in secs:
Our comp. MIT Scheme (compiled)
tak 1.3
sort 1.7
queens (without the trace) 1.7
fib (10 times (fib 20)) 4.1
4. Run-time structure
A quick look at the benchmarks shows that the code generated is fairly
efficient. The system's efficiency is mainly due to a cleverly designed
run-time architecture. It has been designed in a way that makes frequent
operations perform quickly. Some of the most frequent operations in Scheme
are:
- checking type of an object
- calling a procedure (very frequently the procedure comes from a
global variable and has no closed variables)
In our system, objects are represented by tagged 32 bit pointers. The
tag resides in the 3 least significant bits of the pointer. The coding
is as follows:
least 3 bits = 000 object is a 29 bit integer (ie. a fixnum)
least 3 bits = 100 object is a pair whose address is given by the
pointer. the address is where the car is and
the cdr is just BEFORE this address.
least 2 bits = 10 object is a memory allocated object (other than
a pair) whose address is given by the pointer.
the word that precedes this address gives the
type of the object.
least bit = 1 object is either a special value ( (), #f, #t ),
a character or a 31 bit floating point number
the value 111..111 represents () and 111..101
represents #f.
With this coding integers can be added or substracted directly without
first having to extract the type (multiplication and division require
an additional 3 bit shift).
Pairs can also be manipulated easily. Indirect addressing can be used to
access the car of the pair and predecrement addressing to access the cdr.
Procedures (which are memory allocated objects) can be called simply by
jumping to the pointer. This is possible because all procedures
(including true closures) start with machine code. True closures (ie.
procedures with closed variables) are represented like this:
<- 16bits ->
+----------+----------+----------+----------+----------+----
---> |JSR opcode| | | | | ...
+----------+----------+----------+----------+----------+----
\_________ _________/ \_________ _________/
| |
Pointer to closure's First closed ...
body variable's value
Thus the caller does not have to distinguish simple procedures from true
closures. Environment related processing is done automatically (and if
needed) by the callee. This implies that there is no overhead when
calling procedures with no closed variables (the most frequent case).
Testing for 'falsity' is also efficient. Remember, in Scheme both () and
#f represent false. In some implementations they are the same object
(which means you can't distinguish () from #f). In our system we wanted
them to be different. The representation is such that () and #f are the
2 highest object values whose least significant bit is 1. By adding 3
and checking the carry flag one can determine if the object was () or #f
(ie. the carry is on) or if it was something else (ie. the carry flag is
off).
In order to have efficient type checks we have 3 dedicated data registers
that always contain the following masks:
d5 = 00000001000000010000000100000001 for checking fixnums
d6 = 00010000000100000001000000010000 for checking pairs
d7 = 01000100010001000100010001000100 for checking mem. alloc. obj.
To test if a given data register contains a given type a single 'btst'
(bit test) instruction is required. For example, branching to a label
if d1 contains a pair can be performed with the following code:
btst d1,d6 (use last 5 bits of d1 to index d6)
bne label (branch if bit tested was 1)
A very common type check is making sure that only procedure objects are
called. With our representation this involves 7 MC68000 inctructions.
It would be prohibitive to perform this check every time a procedure
is called. In our system, a special trick is used for the frequent
case of calling procedures bound to global variables. Global variables
are allocated in a table (one of the address register points to this
table). Each global variable occupies 6 bytes; 4 bytes for the variable's
value and 2 bytes (just before the value) that encode the type of the
value. These 2 bytes contain the opcode 'jmp' (long jump) if the value
is a procedure and a 'trap' opcode if it isn't a procedure of if the type
is not yet known. When a procedure bound to a global variable needs to
be called a jump to the variable's opcode is done. Most of the time
the value of the variable will be a procedure and it will be jumped to.
If this is not the case the trap handler is called; it will determine
if the value at the return address is a procedure or not. If it is,
the opcode will be changed to 'jmp' and a jump to the procedure will
be performed. If it is not, an error handler is called. The price
one pays for this scheme is that assignments to global variables must
also change the variable's opcode back to a 'trap' opcode. Since
assignments are infrequent in Scheme programs this is not a high price
to pay.
The procedure calling convention used in our system are as follows:
- the first 4 arguments are passed in registers (d1, d2, d3 and d4)
and the rest in fixed memory locations.
- the register d0 is loaded with an argument count code just
before jumping to the procedure.
The procedure called must check that it has been called with the correct
number of arguments. To make this check efficient we have a special coding
for the argument count:
number of arguments: 0 1 2 3 4 5 ...
argument count code: 1 -1 0 4 5 6 ...
When the argument count code is loaded into d0 the flags are automatically
set in accordance to the code loaded. For 1 argument the N (negative) flag is
set, for 2 arguments the Z (zero) flag is set. Thus a single branch-on-
condition instruction is required for the check when 1 or 2 arguments are
expected (these are frequent cases).
5. Future plans
In its present state, the compiler is mainly useful for learning about
Scheme or Lisp compilation techniques. Real applications can not be
developed due to the lack of a GC, debugger, support routines, etc.
In addition, since the compiler is written in Prolog the system is far
from being interactive.
In the future (and if time permits), we plan on doing some of the following:
- rewritting the compiler in Scheme and cleaning up the code
- adding a GC and a full bag of primitive procedures
- turning the system into an interactive one (with read-eval-print loop)
- adding some 'intelligence' to the compiler.
All comments regarding the SIS compiler are welcome (especially bug reports
and suggestions).
6. Acknowledgements
The compiler is the outgrowth of a course project for the 'Logic Programming'
course taught by Tim Hickey at Brandeis University. We would like to thank
Tim for his wonderful course and for suggesting this project.
HEADER============
| -----------------------------------------------------------------------------
|
| This is the 'header.s' file which is appended to the front of the
| assembly program output by the compiler. It contains run-time routines
| for the scheme system and M4 macro definitions which are needed to
| expand the macros in the compiler's output.
| -----------------------------------------------------------------------------
|
| Representation of objects:
|
| An object is represented using a 32 bit value. When more than 32 bits
| are needed to represent an object, the 32 bits are actually a pointer
| to the object in memory.
|
| 28 28
| Fixnums (integers in the range -2 .. 2 -1):
|
| XXXXXXXXXXXXXXXXXXXXXXXXXXXXX000
| \------ integer value ------/
|
| Floating point numbers and other constants:
|
| XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX1
| \-- encoding of f.p. number --/
| or constant
|
| Pair (i.e. cons cell):
| 16 bits
| +-------+ |
| | | \ |
| |- - - -| > cdr | high mem.
| | | / |
| +-------+ |
| XXXXXXXXXXXXXXXXXXXXXXXXXXXXX100 --> | | \ V
| |- - - -| > car
| | | /
| +-------+
|
| Hunk (i.e. object in mem. other than pair, e.g. vectors, strings, proc.):
|
| 16 bits
| +-------+ |
| |field1 | |
| |- - - -| | high mem.
| XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX10 --> |field2 | |
| +-------+\ |
| | | | V
| dword 1 |- - - -| |
| | | |
| +-------+ |
| . | . | |
| . | . | length (# of double words)
| . | . | |
| +-------+ |
| | | |
| dword N |- - - -| |
| | | |
| +-------+/
|
| meaning of field1 and field2:
|
| field1 field2 type of object
|
| 0TTTTTTTXXXXXXXX XXXXXXXXXXXXXXXX TT..TT = type, GC information is
| in a table indexed by TT..TT,
| XX.XX = auxiliary information
| 1000000000000000 forwarded hunk (dword 1 = forw addr.)
| 10DDDDDDDDDDDDDD first word of proc. sub-procedure (DD..DD distance in # of
| quad-bytes from parent procedure)
| 110NNNNNNNNNNNNN first word of proc. prim proc. (dword M..dword N =
| GC information)
| 111NNNNNNNNNNNNN JSR opcode closure (dword 1 = pointer to body,
| dword 2 ..dword N = closed values)
|------------------------------------------------------------------------------
|
| Scheme constants:
|
Cst_nil = 0xFFFFFFFF | -1
Cst_false = 0xFFFFFFFD | -3
Cst_true = 0xFFFFFFFB | -5
Cst_undefined = 0xFFFFFFF9 | -7
Forwarded_pair = 0xFFFFFFF7 | -9, if car of pair is this value, pair has
| already been forwarded to new space
|------------------------------------------------------------------------------
|
| Constants:
|
Fix_type_set = 0x01010101 | value ends with 000
FP_type_set = 0xAAAAAAAA | value ends with 1
Pair_type_set = 0x10101010 | value ends with 100
Hunk_type_set = 0x44444444 | value ends with 10
Forwarded_hunk = 0x8000 | if field1 of hunk is this value, the hunk
| has already been copied to new space
Vector_type = 0x40 | type field for vectors
Symbol_type = 0x41 | type field for symbols
String_type = 0x60 | type field for strings
Sub_proc_type = 0x8000 | type field for sub-procedures
Primitive_type = 0xC000 | type field for primitives
Closure_type = 0xE000 | type field for closures
|------------------------------------------------------------------------------
|
| Macro definitions:
|
define(concatenate,`$1$2$3$4$5$6$7$8$9')
define(the_number,`0')
define(new_number,`define(`the_number',incr(the_number))the_number')
define(new_symbol,`define(`the_symbol',concatenate($1,new_number))the_symbol')
define(change_area,
`define(`current_area',$1)
$1')
define(begin_main,
` .lcomm _reg_at_entry,4*16
change_area(.text)
.globl _entry
_entry:
moveml d0-d7/a0-a7,_reg_at_entry
movl sp,d0
andl #0xfffffffc,d0
movl d0,sp')
define(end_main,
` moveml _reg_at_entry,d0-d7/a0-a7
rts')
define(save_regs,
` moveml d0-d7/a0-a6,sp@-')
define(restore_regs,
` moveml sp@+,d0-d7/a0-a6')
define(print_str,
` .data2
new_symbol(Str): .asciz $1
current_area
save_regs
pea the_symbol
jbsr _printf
addqw #0x4,sp
restore_regs')
define(print_int,
` .data2
new_symbol(Str): .asciz $1
current_area
save_regs
movl $2,sp@-
pea the_symbol
jbsr _printf
addqw #0x8,sp
restore_regs')
define(print_chr,
` .data2
new_symbol(Str): .asciz $1
current_area
save_regs
movb $2,d0
extbl d0
movl d0,sp@-
pea the_symbol
jbsr _printf
addqw #0x8,sp
restore_regs')
define(define_primitive,
`define(`the_procedure_name',$1)define(`the_procedure',scm_$1)
.align 4
.word (end_of_procedure_scm_$1-scm_$1)/4+Primitive_type
scm_$1:')
define(end_primitive,
` .align 4
concatenate(start_of_constants_,the_procedure):
.long new_symbol(Sym)
.long (concatenate(end_of_procedure_,the_procedure)-concatenate(start_of_constants_,the_procedure))/4-1
concatenate(end_of_procedure_,the_procedure):
symbol_object(the_symbol,new_symbol(Str))
string_object(the_symbol,"the_procedure_name")')
define(procedure_object_begin,
`define(`the_procedure',$1)
.align 4
.word (end_of_procedure_$1-$1)/4+Primitive_type
$1:')
define(procedure_object_constants,
` .align 4
concatenate(start_of_constants_,the_procedure):')
define(procedure_object_end,
` .long (concatenate(end_of_procedure_,the_procedure)-concatenate(start_of_constants_,the_procedure))/4-1
concatenate(end_of_procedure_,the_procedure):')
define(sub_procedure,
` .align 4
.word ($1-the_procedure)/4+Sub_proc_type
$1:')
define(pair_object,
` .data
.long $3
$1: .long $2
current_area')
define(vector_object,
` .align 4
.word Vector_type*256
$1: .word $2')
define(symbol_object,
` .align 4
.word Symbol_type*256
$1: .word 1
.long $2')
define(string_object,
` .align 4
.word String_type*256
$1: .word end_of_$1-$1-2
.ascii `$2'
end_of_$1:')
| -----------------------------------------------------------------------------
|
| Interface for SUN:
|
change_area(.text)
.globl _main
_main:
link a6,#0
jbsr _entry
unlk a6
rts
begin_main
lea data_adr,a0 | make sure pairs are on octuple address
.data
.skip 4 | 'magical' offset to bring 'data' section to an
data_adr: | octuple address (may be different on other systems)
current_area
movl a0,d0
andl #7,d0
beq pairs_are_ok
print_str("Can not execute; pairs are not at an address multiple of 8\012")
print_str("Change magical offset in header file\012")
bra exit
pairs_are_ok:
movl #Hunk_type_set,d7 | mask to test tags of hunks
movl #Pair_type_set,d6 | mask to test tags of pairs
movl #Fix_type_set,d5 | mask to test tags of fixnums
lea globals,a6 | setup pointer to global area
lea heap_bottom,a5 | setup pointer to allocate hunks
movl a5,d0
andl #0xFFFFFFF8,d0 | make sure address ends with 000
movl d0,a5
lea heap_top,a4 | setup pointer to allocate pairs
movl a4,d0
andl #0xFFFFFFF8,d0 | make sure address ends with 000
movl d0,a4
lea handler,a3 | error handler
.lcomm stack_bottom,41000
.lcomm stack_top,0
lea stack_bottom,a0 | set stack limit
movl a0,a6@
lea stack_top,a7 | set stack pointer
jmp eval_print | eval program and print result
exit:
end_main
|------------------------------------------------------------------------------
|
| low-level run-time routines:
rest_enter_2:
subql #6,a7@ | fix environment pointer for closures
rest_enter_1:
cmpl a6@,a7 | check for stack overflow
bhis rest_enter_ok
bra error_1
rest_enter_ok:
movl a6,a2 | transfer arguments from registers to
movl d1,a2@- | argument vector
movl d2,a2@-
movl d3,a2@-
movl d4,a2@-
tstw d0 | get number of actual parameters in d0
bgts not_special_code
addqw #3,d0
not_special_code:
movw d0,d1 | save number of actual parameters
subw a0,d0 | are there enough actual parameters?
bpls enough_args
print_str("error: too few arguments to an n-ary procedure\012")
jmp dump
enough_args:
subqw #1,d1 | compute location of last argument in
extl d1 | argument vector
asll #2,d1
movl a6,a2
subl d1,a2
moveq #Cst_nil,d1 | start with the empty list
subqw #1,d0 | just enough actual parameters?
bmis push_rest_arg
construct_list_loop:
movl a2@+,a4@-
movl a4,a0
movl d1,a4@-
movl a0,d1
dbra d0,construct_list_loop
push_rest_arg:
movl d1,a7@-
bras rest_enter_push
rest_enter_loop:
movl a2@+,a7@-
rest_enter_push:
cmpl a2,a6
bnes rest_enter_loop
jmp a1@ | return to procedure
handler:
movl a7@+,a0 | get pointer to value of global variable
movw d0,a7@-
movl a0@,d0
btst d0,d7 | is it a procedure?
beqs error_3
movl d0,a1
tstw a1@(-2)
bpls error_3
movw #20217,a0@(-2) | change trap to a long 'jmp'
movw a7@+,d0 | jump to it...
jmp a1@
error_1:
cmpl a6@,a7
bhis wrong_nb_args
stack_overflow:
print_str("error: stack overflow\012")
jmp dump
wrong_nb_args:
print_str("error: wrong number of arguments to a user procedure\012")
jmp dump
error_2:
subql #6,a7@
cmpl a6@,a7
bhis wrong_nb_args
bras stack_overflow
error_3:
print_str("error: application of a non-procedure object\012")
jmp dump
error_4:
print_str("error: wrong number of arguments to a primitive procedure\012")
jmp dump
| -----------------------------------------------------------------------------
|
| Heap:
change_area(.bss)
.skip 8
heap_bottom:
.skip 8*400000 | reserve space for heap
heap_top:
| -----------------------------------------------------------------------------
|
| Globals:
change_area(.data1)
.word 20217
.long rest_enter_1 | entering a procedure with a 'rest' parameter
.word 20217
.long rest_enter_2 | entering a closure with a 'rest' parameter
.word 20217
.long error_1 | wrong number of arg or stack overflow
.word 20217
.long error_2 | wrong number of arg or stack overflow (for a
| closure)
.word 20217
.long error_3 | calling a non-procedure
.skip 126*4 | space for 126 arguments
globals:
.long 0
.word 20217
.long scm_trace
.word 20217
.long scm_make_promise
.word 20217
.long scm_memv
.word 20217
.long scm_cons
.word 20217
.long scm_list
.word 20217
.long scm_append
.word 20217
.long scm_list_vector
.word 20217
.long scm_not
.word 20217
.long scm_eq
.word 20217
.long scm_pair
.word 20217
.long scm_cons
.word 20217
.long scm_append
.word 20217
.long scm_length
.word 20217
.long scm_car
.word 20217
.long scm_cdr
.word 20217
.long scm_set_car
.word 20217
.long scm_set_cdr
.word 20217
.long scm_null
.word 20217
.long scm_num_eq
.word 20217
.long scm_num_lt
.word 20217
.long scm_num_gt
.word 20217
.long scm_plus
.word 20217
.long scm_minus
.word 20217
.long scm_times
.word 20217
.long scm_quotient
.word 20217
.long scm_minus_1
.word 20217
.long scm_force
.word 20217
.long scm_write
.word 20217
.long scm_newline
.word 20217
.long scm_list
.word 20217
.long scm_vect
.word 20217
.long scm_list_vector
.word 20217
.long scm_memv
.word 20217
.long scm_assq
.word 20217
.long scm_symbol
.word 20217
.long scm_vector
.word 20217
.long scm_string
.word 20217
.long scm_procedure
.word 20217
.long scm_number
.word 20217
.long scm_char
| space for 128 other global variables (initially undefined)
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
.word 20115,-1,-7,20115,-1,-7,20115,-1,-7,20115,-1,-7
| -----------------------------------------------------------------------------
|
| Primitive procedures:
define_primitive(trace)
print_str("\012Trace: calling ")
tstw d0
jmp scm_write
end_primitive
define_primitive(append)
bnes scm_append2
movl d2,a1
btst d1,d6 | is arg1 a pair?
beqs scm_append1
movl d1,a0
movl a0@,a4@-
movl a4,a1
movl d2,a4@-
scm_append_loop:
movl a0@-,d1
btst d1,d6 | is the tail a pair?
beqs scm_append1
movl d1,a0
movl a0@,a4@-
movl a4,a4@(4)
movl d2,a4@-
bras scm_append_loop
scm_append1:
cmpl #Cst_nil,d1
bnes scm_append3
movl a1,d1
rts
scm_append2:
jmp error_4 | for now signal an error (should be n-ary)
scm_append3:
print_str("error: improper list passed to 'append'\012")
jmp dump
end_primitive
define_primitive(length)
bpls scm_length2
moveq #0,d2
scm_length_loop:
btst d1,d6 | is arg1 a pair?
beqs scm_length1
movl d1,a0
movl a0@-,d1
addql #8,d2
bras scm_length_loop
scm_length1:
cmpl #Cst_nil,d1
bnes scm_length3
movl d2,d1
rts
scm_length2:
jmp error_4
scm_length3:
print_str("error: improper list passed to 'length'\012")
jmp dump
end_primitive
define_primitive(not)
bpls scm_not2
addql #3,d1
bcss scm_not1
moveq #Cst_false,d1
rts
scm_not1:
moveq #Cst_true,d1
rts
scm_not2:
jmp error_4
end_primitive
define_primitive(list_vector)
bpls scm_list_vector3
movl d1,sp@-
pea scm_list_vector1
moveq #-1,d0
jmp scm_length
sub_procedure(scm_list_vector1)
movl d1,d2
asrl #3,d2
movw #Vector_type*256,a5@+
movl a5,d1
movw d2,a5@+
movl sp@+,d2
scm_list_vector_loop:
btst d2,d6
beqs scm_list_vector2
movl d2,a0
movl a0@,a5@+
movl a0@-,d2
bras scm_list_vector_loop
scm_list_vector2:
rts
scm_list_vector3:
jmp error_4
end_primitive
define_primitive(eq)
bnes scm_eq2
cmpl d2,d1
beqs scm_eq1
moveq #Cst_false,d1
rts
scm_eq1:
moveq #Cst_true,d1
rts
scm_eq2:
jmp error_4
end_primitive
define_primitive(pair)
bpls scm_pair2
btst d1,d6
bnes scm_pair1
moveq #Cst_false,d1
rts
scm_pair1:
moveq #Cst_true,d1
rts
scm_pair2:
jmp error_4
end_primitive
define_primitive(cons)
bnes scm_cons1
movl d1,a4@-
movl a4,d1
movl d2,a4@-
rts
scm_cons1:
jmp error_4
end_primitive
define_primitive(car)
bpls scm_car2
btst d1,d6
beqs scm_car1
movl d1,a0
movl a0@,d1
rts
scm_car1:
print_str("error: non pair argument to 'car': ")
moveq #-1,d0
jbsr scm_write
print_str("\012")
jmp dump
scm_car2:
jmp error_4
end_primitive
define_primitive(cdr)
bpls scm_cdr2
btst d1,d6
beqs scm_cdr1
movl d1,a0
movl a0@-,d1
rts
scm_cdr1:
print_str("error: non pair argument to 'cdr': ")
moveq #-1,d0
jbsr scm_write
print_str("\012")
jmp dump
scm_cdr2:
jmp error_4
end_primitive
define_primitive(set_car)
bnes scm_set_car2
btst d1,d6
beqs scm_set_car1
movl d1,a0
movl d2,a0@
rts
scm_set_car1:
print_str("error: non pair argument to 'set-car': ")
moveq #-1,d0
jbsr scm_write
print_str("\012")
jmp dump
scm_set_car2:
jmp error_4
end_primitive
define_primitive(set_cdr)
bnes scm_set_cdr2
btst d1,d6
beqs scm_set_cdr1
movl d1,a0
movl d2,a0@-
rts
scm_set_cdr1:
print_str("error: non pair argument to 'set-cdr': ")
moveq #-1,d0
jbsr scm_write
print_str("\012")
jmp dump
scm_set_cdr2:
jmp error_4
end_primitive
define_primitive(null)
bpls scm_null2
addql #1,d1
beqs scm_null1
moveq #Cst_false,d1
rts
scm_null1:
moveq #Cst_true,d1
rts
scm_null2:
jmp error_4
end_primitive
define_primitive(num_eq)
bnes scm_num_eq3
btst d1,d5 | is arg1 a fixnum?
beqs scm_num_eq2
btst d2,d5 | is arg2 a fixnum?
beqs scm_num_eq2
cmpl d2,d1
beqs scm_num_eq1
moveq #Cst_false,d1
rts
scm_num_eq1:
moveq #Cst_true,d1
rts
scm_num_eq2:
print_str("error: non fixnum argument(s) to '='\012")
jmp dump
scm_num_eq3:
jmp error_4
end_primitive
define_primitive(num_lt)
bnes scm_num_lt3
btst d1,d5 | is arg1 a fixnum?
beqs scm_num_lt2
btst d2,d5 | is arg2 a fixnum?
beqs scm_num_lt2
cmpl d2,d1
blts scm_num_lt1
moveq #Cst_false,d1
rts
scm_num_lt1:
moveq #Cst_true,d1
rts
scm_num_lt2:
print_str("error: non fixnum argument(s) to '<'\012")
jmp dump
scm_num_lt3:
jmp error_4
end_primitive
define_primitive(num_gt)
bnes scm_num_gt3
btst d1,d5 | is arg1 a fixnum?
beqs scm_num_gt2
btst d2,d5 | is arg2 a fixnum?
beqs scm_num_gt2
cmpl d2,d1
bgts scm_num_gt1
moveq #Cst_false,d1
rts
scm_num_gt1:
moveq #Cst_true,d1
rts
scm_num_gt2:
print_str("error: non fixnum argument(s) to '>'\012")
jmp dump
scm_num_gt3:
jmp error_4
end_primitive
define_primitive(plus)
bnes scm_plus2
btst d1,d5 | is arg1 a fixnum?
beqs scm_plus5
btst d2,d5 | is arg2 a fixnum?
beqs scm_plus5
addl d2,d1
bvss scm_plus1
rts
scm_plus1:
print_str("error: overflow on '+'\012") | for now signal an error, eventually
jmp dump | should convert result to bignum
scm_plus2:
bpls scm_plus3
btst d1,d5 | is arg1 a fixnum?
beqs scm_plus5
rts
scm_plus3:
subql #1,d0
bnes scm_plus4
moveq #0,d0
rts
scm_plus4:
addql #1,d0
jmp error_4 | for now signal an error (should be n-ary)
scm_plus5:
print_str("error: non fixnum argument(s) to '+'\012")
jmp dump
end_primitive
define_primitive(minus)
bnes scm_minus2
btst d1,d5 | is arg1 a fixnum?
beqs scm_minus4
btst d2,d5 | is arg2 a fixnum?
beqs scm_minus4
subl d2,d1
bvss scm_minus1
rts
scm_minus1:
print_str("error: overflow on '-'\012") | for now signal an error, eventually
jmp dump | should convert result to bignum
scm_minus2:
bpls scm_minus3
btst d1,d5 | is arg1 a fixnum?
beqs scm_minus4
negl d1
bvss scm_minus1
rts
scm_minus3:
jmp error_4 | for now signal an error (should be n-ary)
scm_minus4:
print_str("error: non fixnum argument(s) to '-'\012")
jmp dump
end_primitive
define_primitive(times)
bnes scm_times2
btst d1,d5 | is arg1 a fixnum?
beqs scm_times5
btst d2,d5 | is arg2 a fixnum?
beqs scm_times5
asrl #3,d1
muls d2,d1
bvss scm_times1
rts
scm_times1:
print_str("error: overflow on '*'\012") | for now signal an error, eventually
jmp dump | should convert result to bignum
scm_times2:
bpls scm_times3
btst d1,d5 | is arg1 a fixnum?
beqs scm_times5
rts
scm_times3:
subql #1,d0
bnes scm_times4
moveq #8,d0
rts
scm_times4:
addql #1,d0
jmp error_4 | for now signal an error (should be n-ary)
scm_times5:
print_str("error: non fixnum argument(s) to '*'\012")
jmp dump
end_primitive
define_primitive(quotient)
bnes scm_quotient1
btst d1,d5 | is arg1 a fixnum?
beqs scm_quotient2
btst d2,d5 | is arg2 a fixnum?
beqs scm_quotient2
divs d2,d1
extl d1
asll #3,d1
rts
scm_quotient1:
jmp error_4 | for now signal an error (should be n-ary)
scm_quotient2:
print_str("error: non fixnum argument(s) to '/'\012")
jmp dump
end_primitive
define_primitive(minus_1)
bpls scm_minus_11
btst d1,d5 | is arg1 a fixnum?
beqs scm_minus_12
subql #8,d1
rts
scm_minus_11:
jmp error_4
scm_minus_12:
print_str("error: non fixnum argument to '-1+'\012")
jmp dump
end_primitive
define_primitive(force)
bpls scm_force2
btst d1,d7
beqs scm_force1
movl d1,a0
tstw a0@(-2)
bpls scm_force1
moveq #1,d0
jmp a0@
scm_force1:
jmp a6@(-510)
scm_force2:
jmp error_4
end_primitive
define_primitive(write)
bpls scm_write1
btst d1,d5 | is it a fixnum?
beqs not_fixnum
movl d1,d2
asrl #3,d2
print_int("%d",d2)
moveq #Cst_undefined,d1
rts
scm_write1:
jmp error_4
not_fixnum:
btst #0,d1
beqs not_char2
swap d1
cmpw #-2,d1
bnes not_char1
swap d1
asrw #1,d1
print_chr("#\134%c",d1)
moveq #Cst_undefined,d1
rts
not_char1:
swap d1
not_char2:
btst d1,d6 | is it a pair?
beq not_pair
print_str("\050")
next_pair:
movl d1,a0
movl a0@,d1
movl a0@-,a7@-
moveq #-1,d0
jbsr scm_write
movl a7@+,d1
cmpl #Cst_nil,d1
bnes not_end
print_str("\051")
moveq #Cst_undefined,d1
rts
not_end:
btst d1,d6 | is it a pair?
bnes pair_again
print_str(" . ")
moveq #-1,d0
jbsr scm_write
print_str("\051")
moveq #Cst_undefined,d1
rts
pair_again:
print_str(" ")
bra next_pair
not_pair:
cmpl #Cst_nil,d1
bnes not_nil
print_str("\050\051")
moveq #Cst_undefined,d1
rts
not_nil:
cmpl #Cst_false,d1
bnes not_false
print_str("#f")
moveq #Cst_undefined,d1
rts
not_false:
cmpl #Cst_true,d1
bnes not_true
print_str("#t")
moveq #Cst_undefined,d1
rts
not_true:
cmpl #Cst_undefined,d1
bnes not_undef
print_str("#<undefined>")
moveq #Cst_undefined,d1
rts
not_undef:
btst d1,d7
beq unknown
movl d1,a0
movw a0@(-2),d0
bpl other_hunks
cmpw #Closure_type,d0
bhi write_closure
cmpw #Primitive_type,d0
bhi write_primitive
print_str("#<return address into ")
subw #Sub_proc_type,d0
extl d0
asll #2,d0
subl d0,a0
movl a0,d1
moveq #-1,d0
jbsr scm_write
print_str(">")
moveq #Cst_undefined,d1
rts
write_primitive:
print_str("#<procedure")
subw #Primitive_type,d0
extl d0
asll #2,d0
addl d0,a0
subql #6,a0
movl a0@,d1
cmpl #Cst_nil,d1
beqs write_primitive1
print_str(" ")
moveq #-1,d0
jbsr scm_write
write_primitive1:
print_str(">")
moveq #Cst_undefined,d1
rts
write_closure:
addql #2,a0
movl a0@,d1
moveq #-1,d0
jbsr scm_write
moveq #Cst_undefined,d1
rts
other_hunks:
asrw #8,d0
cmpb #Vector_type,d0
bne other_1
print_str("#\050")
subql #2,a0
movl a0@+,d0
andl #0xFFFFFF,d0
beqs vector_end
write_vector_loop:
movl a0@+,d1
movl d0,a7@-
movl a0,a7@-
moveq #-1,d0
jbsr scm_write
movl a7@+,a0
movl a7@+,d0
subql #1,d0
beqs vector_end
print_str(" ")
bra write_vector_loop
vector_end:
print_str("\051")
moveq #Cst_undefined,d1
rts
other_1:
cmpb #String_type,d0
bne other_2
print_str("\042")
subql #2,a0
movl a0@+,d0
andl #0xFFFFFF,d0
beqs string_end
write_string_loop:
movb a0@+,d1
cmpb #34,d1
beqs write_escape
cmpb #92,d1
bnes write_string_char
write_escape:
print_chr("%c",#92)
write_string_char:
print_chr("%c",d1)
subql #1,d0
bnes write_string_loop
string_end:
print_str("\042")
moveq #Cst_undefined,d1
rts
other_2:
cmpb #Symbol_type,d0
bne other_3
movl a0@(2),a0
subql #2,a0
movl a0@+,d0
andl #0xFFFFFF,d0
beqs symbol_end
write_symbol_loop:
movb a0@+,d1
print_chr("%c",d1)
subql #1,d0
bnes write_symbol_loop
symbol_end:
moveq #Cst_undefined,d1
rts
other_3:
unknown:
print_str("#<unknown>")
moveq #Cst_undefined,d1
rts
end_primitive
define_primitive(newline)
subqw #1,d0
bne scm_newline1
print_str("\012")
moveq #Cst_undefined,d1
rts
scm_newline1:
addqw #1,d0
jmp error_4
end_primitive
define_primitive(assq)
bnes scm_assq4
scm_assq1:
btst d2,d6
beqs scm_assq2
movl d2,a0
movl a0@,d3
movl a0@-,d2
btst d3,d6
beqs scm_assq3
movl d3,a1
cmpl a1@,d1 | use eq? for now (should use eqv?)
bnes scm_assq1
movl d3,d1
rts
scm_assq2:
moveq #Cst_false,d1
rts
scm_assq3:
print_str("error: illformed a-list to 'assq'\012")
jmp dump
scm_assq4:
jmp error_4
end_primitive
define_primitive(symbol)
bpls scm_symbol2
btst d1,d7
beqs scm_symbol1
movl d1,a0
cmpb #Symbol_type,a0@(-2)
bnes scm_symbol1
moveq #Cst_true,d1
rts
scm_symbol1:
moveq #Cst_false,d1
rts
scm_symbol2:
jmp error_4
end_primitive
define_primitive(vector)
bpls scm_vector2
btst d1,d7
beqs scm_vector1
movl d1,a0
cmpb #Vector_type,a0@(-2)
bnes scm_vector1
moveq #Cst_true,d1
rts
scm_vector1:
moveq #Cst_false,d1
rts
scm_vector2:
jmp error_4
end_primitive
define_primitive(string)
bpls scm_string2
btst d1,d7
beqs scm_string1
movl d1,a0
cmpb #String_type,a0@(-2)
bnes scm_string1
moveq #Cst_true,d1
rts
scm_string1:
moveq #Cst_false,d1
rts
scm_string2:
jmp error_4
end_primitive
define_primitive(procedure)
bpls scm_procedure2
btst d1,d7
beqs scm_procedure1
movl d1,a0
tstw a0@(-2)
bpls scm_procedure1
moveq #Cst_true,d1
rts
scm_procedure1:
moveq #Cst_false,d1
rts
scm_procedure2:
jmp error_4
end_primitive
define_primitive(number)
bpls scm_number2
btst d1,d5
beqs scm_number1
moveq #Cst_true,d1
rts
scm_number1:
moveq #Cst_false,d1
rts
scm_number2:
jmp error_4
end_primitive
define_primitive(char)
bpls scm_char2
btst #0,d1
beqs scm_char1
swap d1
cmpw #-2,d1
bnes scm_char1
moveq #Cst_true,d1
rts
scm_char1:
moveq #Cst_false,d1
rts
scm_char2:
jmp error_4
end_primitive
| -----------------------------------------------------------------------------
|
| Run-time procedures (written in Scheme):
procedure_object_begin(eval_print)
pea eval_print1
moveq #1,d0
jmp entry | enter program
sub_procedure(eval_print1)
print_str("Result: ")
pea eval_print2
moveq #-1,d0
jmp scm_write
sub_procedure(eval_print2)
print_str("\012")
jmp exit
procedure_object_constants
.long Cst_nil
procedure_object_end
procedure_object_begin(dump)
print_str("\012Stack dump:\012")
dump1:
cmpl #stack_top,a7
bccs dump2
print_str("> ")
movl sp@+,d1
moveq #-1,d0
jbsr scm_write
print_str("\012")
bras dump1
dump2:
jmp exit
procedure_object_constants
procedure_object_end
define_primitive(make_promise)
| (define (make-promise thunk)
| (let ((computed #f))
| (lambda ()
| (if computed thunk
| (begin
| (set! thunk (thunk))
| (set! computed #t)
| thunk)))))
bpls scm_make_promise2
cmpl a6@,a7
bhis scm_make_promise3
scm_make_promise2:
jmp a6@(-522)
scm_make_promise3:
movl d1,a7@-
movl a7@,d0
movl d0,a4@-
movl a4,a7@-
movl d0,a4@-
moveq #Cst_false,d0
movl d0,a7@-
movl a7@,d0
movl d0,a4@-
movl a4,a7@-
movl d0,a4@-
movw #-8189,a5@+
movl a5,d1
movw #20153,a5@+
lea scm_make_promise4,a0
movl a0,a5@+
movl a7@(8),a5@+
movl a7@,a5@+
addw #16,a7
rts
sub_procedure(scm_make_promise4)
subql #1,d0
bnes scm_make_promise5
cmpl a6@,a7
bhis scm_make_promise6
scm_make_promise5:
jmp a6@(-516)
scm_make_promise6:
subql #6,a7@
movl a7@,a0
movl a0@(10),a0
movl a0@,d1
addql #3,d1
bcs scm_make_promise7
movl a7@,a0
movl a0@(6),a0
movl a0@,d1
addql #4,a7
rts
scm_make_promise7:
movl a7@,a0
movl a0@(6),a0
movl a0@,d0
pea scm_make_promise9
btst d0,d7
beqs scm_make_promise8
movl d0,a0
tstw a0@(-2)
bpls scm_make_promise8
moveq #1,d0
jmp a0@
scm_make_promise8:
jmp a6@(-510)
sub_procedure(scm_make_promise9)
movl a7@,a0
movl a0@(6),a0
movl d1,a0@
moveq #Cst_true,d1
movl a7@,a0
movl a0@(10),a0
movl d1,a0@
movl a7@,a0
movl a0@(6),a0
movl a0@,d1
addql #4,a7
rts
end_primitive
define_primitive(memv)
| (define (memv obj list)
| (if (pair? list)
| (if (eqv? (car list) obj)
| list
| (memv obj (cdr list)))
| #f))
bnes scm_memv1
cmpl a6@,a7
bhis scm_memv3
scm_memv1:
jmp a6@(-522)
scm_memv2:
movl a0@-,d2
scm_memv3:
btst d2,d6
beqs scm_memv4
movl d2,a0
cmpl a0@,d1 | use eq? for now (should use eqv?)
bnes scm_memv2
movl d2,d1
rts
scm_memv4:
moveq #Cst_false,d1
rts
end_primitive
define_primitive(list)
| (define (list . l) l)
movw #1,a0
lea scm_list1,a1
jmp a6@(-534)
sub_procedure(scm_list1)
movl a7@,d1
addql #4,a7
rts
end_primitive
define_primitive(vect)
| (define (vector . l) (list->vector l))
movw #1,a0
lea scm_vect1,a1
jmp a6@(-534)
sub_procedure(scm_vect1)
movl a7@+,d1
moveq #-1,d0
jmp scm_list_vector
end_primitive
| -----------------------------------------------------------------------------
|
| The program:
===========================================
cat header.s $1.s > asm.tmp1
sed -e s/#/@sharp@/ asm.tmp1 | m4 | sed -e s/@sharp@/#/ > asm.tmp2
as -o asm.o asm.tmp2
cc asm.o -o $1
rm asm.o
| TeamSPoon/MUD_ScriptEngines | prolog/wam_cl/reference/moo_ext_scheme_sis.pl | Perl | mit | 98,207 |
package Google::Ads::AdWords::v201409::MediaService::ResponseHeader;
use strict;
use warnings;
{ # BLOCK to scope variables
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409' }
__PACKAGE__->__set_name('ResponseHeader');
__PACKAGE__->__set_nillable();
__PACKAGE__->__set_minOccurs();
__PACKAGE__->__set_maxOccurs();
__PACKAGE__->__set_ref();
use base qw(
SOAP::WSDL::XSD::Typelib::Element
Google::Ads::AdWords::v201409::SoapResponseHeader
);
}
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201409::MediaService::ResponseHeader
=head1 DESCRIPTION
Perl data type class for the XML Schema defined element
ResponseHeader from the namespace https://adwords.google.com/api/adwords/cm/v201409.
=head1 METHODS
=head2 new
my $element = Google::Ads::AdWords::v201409::MediaService::ResponseHeader->new($data);
Constructor. The following data structure may be passed to new():
$a_reference_to, # see Google::Ads::AdWords::v201409::SoapResponseHeader
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| gitpan/GOOGLE-ADWORDS-PERL-CLIENT | lib/Google/Ads/AdWords/v201409/MediaService/ResponseHeader.pm | Perl | apache-2.0 | 1,032 |
package #
Date::Manip::Offset::off414;
# Copyright (c) 2008-2014 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
# This file was automatically generated. Any changes to this file will
# be lost the next time 'tzdata' is run.
# Generated on: Fri Nov 21 11:03:46 EST 2014
# Data version: tzdata2014j
# Code version: tzcode2014j
# This module contains data from the zoneinfo time zone database. The original
# data was obtained from the URL:
# ftp://ftp.iana.orgtz
use strict;
use warnings;
require 5.010000;
our ($VERSION);
$VERSION='6.48';
END { undef $VERSION; }
our ($Offset,%Offset);
END {
undef $Offset;
undef %Offset;
}
$Offset = '-09:30:00';
%Offset = (
0 => [
'pacific/marquesas',
],
1 => [
'pacific/rarotonga',
'pacific/honolulu',
],
);
1;
| nriley/Pester | Source/Manip/Offset/off414.pm | Perl | bsd-2-clause | 927 |
package #
Date::Manip::TZ::amphoe00;
# 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 10:41:41 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.org/tz
use strict;
use warnings;
require 5.010000;
our (%Dates,%LastRule);
END {
undef %Dates;
undef %LastRule;
}
our ($VERSION);
$VERSION='6.48';
END { undef $VERSION; }
%Dates = (
1 =>
[
[ [1,1,2,0,0,0],[1,1,1,16,31,42],'-07:28:18',[-7,-28,-18],
'LMT',0,[1883,11,18,18,59,59],[1883,11,18,11,31,41],
'0001010200:00:00','0001010116:31:42','1883111818:59:59','1883111811:31:41' ],
],
1883 =>
[
[ [1883,11,18,19,0,0],[1883,11,18,12,0,0],'-07:00:00',[-7,0,0],
'MST',0,[1918,3,31,8,59,59],[1918,3,31,1,59,59],
'1883111819:00:00','1883111812:00:00','1918033108:59:59','1918033101:59:59' ],
],
1918 =>
[
[ [1918,3,31,9,0,0],[1918,3,31,3,0,0],'-06:00:00',[-6,0,0],
'MDT',1,[1918,10,27,7,59,59],[1918,10,27,1,59,59],
'1918033109:00:00','1918033103:00:00','1918102707:59:59','1918102701:59:59' ],
[ [1918,10,27,8,0,0],[1918,10,27,1,0,0],'-07:00:00',[-7,0,0],
'MST',0,[1919,3,30,8,59,59],[1919,3,30,1,59,59],
'1918102708:00:00','1918102701:00:00','1919033008:59:59','1919033001:59:59' ],
],
1919 =>
[
[ [1919,3,30,9,0,0],[1919,3,30,3,0,0],'-06:00:00',[-6,0,0],
'MDT',1,[1919,10,26,7,59,59],[1919,10,26,1,59,59],
'1919033009:00:00','1919033003:00:00','1919102607:59:59','1919102601:59:59' ],
[ [1919,10,26,8,0,0],[1919,10,26,1,0,0],'-07:00:00',[-7,0,0],
'MST',0,[1942,2,9,8,59,59],[1942,2,9,1,59,59],
'1919102608:00:00','1919102601:00:00','1942020908:59:59','1942020901:59:59' ],
],
1942 =>
[
[ [1942,2,9,9,0,0],[1942,2,9,3,0,0],'-06:00:00',[-6,0,0],
'MWT',1,[1944,1,1,6,0,59],[1944,1,1,0,0,59],
'1942020909:00:00','1942020903:00:00','1944010106:00:59','1944010100:00:59' ],
],
1944 =>
[
[ [1944,1,1,6,1,0],[1943,12,31,23,1,0],'-07:00:00',[-7,0,0],
'MST',0,[1944,4,1,7,0,59],[1944,4,1,0,0,59],
'1944010106:01:00','1943123123:01:00','1944040107:00:59','1944040100:00:59' ],
[ [1944,4,1,7,1,0],[1944,4,1,1,1,0],'-06:00:00',[-6,0,0],
'MWT',1,[1944,10,1,6,0,59],[1944,10,1,0,0,59],
'1944040107:01:00','1944040101:01:00','1944100106:00:59','1944100100:00:59' ],
[ [1944,10,1,6,1,0],[1944,9,30,23,1,0],'-07:00:00',[-7,0,0],
'MST',0,[1967,4,30,8,59,59],[1967,4,30,1,59,59],
'1944100106:01:00','1944093023:01:00','1967043008:59:59','1967043001:59:59' ],
],
1967 =>
[
[ [1967,4,30,9,0,0],[1967,4,30,3,0,0],'-06:00:00',[-6,0,0],
'MDT',1,[1967,10,29,7,59,59],[1967,10,29,1,59,59],
'1967043009:00:00','1967043003:00:00','1967102907:59:59','1967102901:59:59' ],
[ [1967,10,29,8,0,0],[1967,10,29,1,0,0],'-07:00:00',[-7,0,0],
'MST',0,[9999,12,31,0,0,0],[9999,12,30,17,0,0],
'1967102908:00:00','1967102901:00:00','9999123100:00:00','9999123017:00:00' ],
],
);
%LastRule = (
);
1;
| nriley/Pester | Source/Manip/TZ/amphoe00.pm | Perl | bsd-2-clause | 3,580 |
#!/usr/bin/env swipl
%
% Dec 13, 2034
% Douglas Miles
% cls ; kill -9 %1 ; swipl -g "ensure_loaded(pack(logicmoo_base/t/sanity_base/clause_fwd_01c.pfc'))."
:- include(test_header).
% :- set_prolog_flag(lm_pfc_lean,true).
% :- use_module(library(pfc)).
:- kb_local(aa/2).
( aa(N):- _B ) ==> early_aa_H(N).
( aa(N):- B ) ==> early_aa_HB(N,B).
%TODO error ( H :- B ) ==> early_HB(H,B).
( aa(N) ) ==> early_aa(N).
( ~H :- B ) ==> early_not_HB(H,B).
( ~bb(H) :- B ) ==> early_not_bb_HB(H,B).
( ~bb(H) :- _B ) ==> early_not_bb_H(H).
%TODO performance ( P ) ==> early_p(P).
%TODO performance ( ~P ) ==> early_not_p(P).
aa(1):- writeln(1+1).
aa(2).
aa(3):- true.
aa(N):- member(N,[4,5]).
% FWI, not assertable: gg(8):- _G.
gg(9):- call(_G).
gg(G):- G.
gg(G):- call(G).
~bb(1):- writeln(1+1).
~bb(2).
~bb(3):- true.
~bb(N):- member(N,[4,5]).
% FWI, not assertable: ~ng(8):- _G.
~ng(9):- call(_G).
~ng(G):- G.
~ng(G):- call(G).
( aa(N):- _B ) ==> late_aa_H(N).
( aa(N):- B ) ==> late_aa_HB(N,B).
%TODO error ( H :- B ) ==> late_HB(H,B).
( aa(N) ) ==> late_aa(N).
( ~H :- B ) ==> late_not_HB(H,B).
( ~bb(H) :- B ) ==> late_not_bb_HB(H,B).
( ~bb(H) :- _B ) ==> late_not_bb_H(H).
%TODO performance ( P ) ==> late_p(P).
%TODO performance ( ~P ) ==> late_not_p(P).
:- mpred_test(early_aa(1)).
:- mpred_test(early_aa(2)).
:- mpred_test(early_aa(3)).
:- mpred_test(early_aa(4)).
:- mpred_test(early_aa(5)).
:- mpred_test(late_aa(1)).
:- mpred_test(late_aa(2)).
:- mpred_test(late_aa(3)).
:- mpred_test(late_aa(4)).
:- mpred_test(late_aa(5)).
:- mpred_test(late_aa_HB(A, member(A, [4, 5]))).
:- mpred_test(late_aa_HB(3, true)).
:- mpred_test(late_aa_HB(2, true)).
:- mpred_test(late_aa_HB(1, writeln(1+1))).
% :- mpred_test(late_aa_HB(A, inherit_above(user, aa(A)))).
:- mpred_test(early_aa_HB(A, member(A, [4, 5]))).
:- warn_fail_TODO(early_aa_HB(2, true)).
:- warn_fail_TODO(early_aa_HB(3, true)).
:- mpred_test(early_aa_HB(1, writeln(1+1))).
% :- mpred_test(early_aa_HB(A, inherit_above(user, aa(A)))).
:- warn_fail_TODO(late_aa_H(1)).
:- warn_fail_TODO(late_aa_H(2)).
:- warn_fail_TODO(late_aa_H(3)).
:- warn_fail_TODO(late_aa_H(_)).
:- mpred_test(clause_asserted(late_aa_H(_))).
:- warn_fail_TODO(\+ clause_asserted(late_aa_H(4))).
:- warn_fail_TODO(\+ clause_asserted(late_aa_H(5))).
:- warn_fail_TODO(early_aa_H(1)).
:- warn_fail_TODO(early_aa_H(2)).
:- warn_fail_TODO(early_aa_H(3)).
:- warn_fail_TODO(early_aa_H(_)).
:- mpred_test(clause_asserted(early_aa_H(_))).
:- warn_fail_TODO(\+ clause_asserted(early_aa_H(4))).
:- warn_fail_TODO(\+ clause_asserted(early_aa_H(5))).
:- listing([early_aa/1,late_aa/1]).
:- listing([early_aa_HB/2,late_aa_HB/2]).
:- listing([early_aa_H/1,late_aa_H/1]).
:- listing([early_not_bb_H/1,late_not_bb_H/1]).
:- listing([early_not_HB/2,late_not_HB/2]).
:- listing([early_not_bb_HB/2,late_not_bb_HB/2]).
| TeamSPoon/logicmoo_workspace | packs_sys/pfc/t/sanity_base/clause_fwd_02.pfc.pl | Perl | mit | 2,867 |
package CPANPLUS::Internals::Source::SQLite::Tie;
use deprecate;
use strict;
use warnings;
use CPANPLUS::Error;
use CPANPLUS::Module;
use CPANPLUS::Module::Fake;
use CPANPLUS::Module::Author::Fake;
use CPANPLUS::Internals::Constants;
use Params::Check qw[check];
use Module::Load::Conditional qw[can_load];
use Locale::Maketext::Simple Class => 'CPANPLUS', Style => 'gettext';
use vars qw[@ISA $VERSION];
$VERSION = "0.9135";
require Tie::Hash;
push @ISA, 'Tie::StdHash';
sub TIEHASH {
my $class = shift;
my %hash = @_;
my $tmpl = {
dbh => { required => 1 },
table => { required => 1 },
key => { required => 1 },
cb => { required => 1 },
offset => { default => 0 },
};
my $args = check( $tmpl, \%hash ) or return;
my $obj = bless { %$args, store => {} } , $class;
return $obj;
}
sub FETCH {
my $self = shift;
my $key = shift or return;
my $dbh = $self->{dbh};
my $cb = $self->{cb};
my $table = $self->{table};
### did we look this one up before?
if( my $obj = $self->{store}->{$key} ) {
return $obj;
}
my $res = $dbh->query(
"SELECT * from $table where $self->{key} = ?", $key
) or do {
error( $dbh->error );
return;
};
my $href = $res->hash;
### get rid of the primary key
delete $href->{'id'};
### no results?
return unless keys %$href;
### expand author if needed
### XXX no longer generic :(
if( $table eq 'module' ) {
$href->{author} = $cb->author_tree( $href->{author } ) or return;
}
my $class = {
module => 'CPANPLUS::Module',
author => 'CPANPLUS::Module::Author',
}->{ $table };
my $obj = $self->{store}->{$key} = $class->new( %$href, _id => $cb->_id );
return $obj;
}
sub STORE {
my $self = shift;
my $key = shift;
my $val = shift;
$self->{store}->{$key} = $val;
}
1;
sub FIRSTKEY {
my $self = shift;
my $dbh = $self->{'dbh'};
my $res = $dbh->query(
"select $self->{key} from $self->{table} order by $self->{key} limit 1"
);
$self->{offset} = 0;
my $key = $res->flat->[0];
return $key;
}
sub NEXTKEY {
my $self = shift;
my $dbh = $self->{'dbh'};
my $res = $dbh->query(
"select $self->{key} from $self->{table} ".
"order by $self->{key} limit 1 offset $self->{offset}"
);
$self->{offset} +=1;
my $key = $res->flat->[0];
my $val = $self->FETCH( $key );
### use each() semantics
return wantarray ? ( $key, $val ) : $key;
}
sub EXISTS { !!$_[0]->FETCH( $_[1] ) }
sub SCALAR {
my $self = shift;
my $dbh = $self->{'dbh'};
my $res = $dbh->query( "select count(*) from $self->{table}" );
return $res->flat;
}
### intentionally left blank
sub DELETE { }
sub CLEAR { }
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/CPANPLUS/Internals/Source/SQLite/Tie.pm | Perl | mit | 3,045 |
use strict;
use warnings FATAL => 'all';
local $| = 1; # unbuffered mode
my $r = shift;
print "Content-Type: text/html\n\n";
print "yet another boring test string";
# This line passes a bucket brigade with a single bucket FLUSH
# it was causing problems in the mod_deflate filter which was trying to
# deflate empty output buffer, (the previous print has already flushed
# all the output) (the fix in mod_deflate.c was to check whether the
# buffer is full)
print "";
| gitpan/mod_perl | ModPerl-Registry/t/cgi-bin/flush.pl | Perl | apache-2.0 | 473 |
######################################################################
# Copyright (c) 2012, Yahoo! Inc. All rights reserved.
#
# This program is free software. You may copy or redistribute it under
# the same terms as Perl itself. Please see the LICENSE.Artistic file
# included with this project for the terms of the Artistic License
# under which this project is licensed.
######################################################################
package Gearbox::StatusManager;
# implementation entirely in swig generated Gearbox.pmx
use Gearbox;
1;
| getgearbox/gearbox | gearbox/swig/perl/lib/Gearbox/StatusManager.pm | Perl | bsd-3-clause | 553 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/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';
0715 0716
072A
072F
END
| efortuna/AndroidSDKClone | ndk_experimental/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Jg/DalathRi.pl | Perl | apache-2.0 | 447 |
# display args for pam_securetty.so.pl
# display_args(&service, &module, &args)
sub display_module_args
{
local $file = "/etc/securetty";
print &ui_table_row($text{'securetty_ttys'},
&ui_textarea("ttys", &read_file_contents($file), 5, 40), 3);
}
# parse_module_args(&service, &module, &args)
sub parse_module_args
{
local $file = "/etc/securetty";
&lock_file($file);
&open_tempfile(FILE, ">$file");
$in{'ttys'} =~ s/\r//g;
$in{'ttys'} =~ s/\s*$/\n/;
&print_tempfile(FILE, $in{'ttys'});
&close_tempfile(FILE);
&unlock_file($file);
}
| HasClass0/webmin | pam/pam_securetty.so.pl | Perl | bsd-3-clause | 535 |
###########################################################################
#
# This file is auto-generated by the Perl DateTime Suite locale
# generator (0.05). This code generator comes with the
# DateTime::Locale distribution in the tools/ directory, and is called
# generate-from-cldr.
#
# This file as generated from the CLDR XML locale data. See the
# LICENSE.cldr file included in this distribution for license details.
#
# This file was generated from the source file es_DO.xml
# The source file version number was 1.54, generated on
# 2009/05/05 23:06:35.
#
# Do not edit this file directly.
#
###########################################################################
package DateTime::Locale::es_DO;
use strict;
use warnings;
use utf8;
use base 'DateTime::Locale::es';
sub cldr_version { return "1\.7\.1" }
{
my $first_day_of_week = "1";
sub first_day_of_week { return $first_day_of_week }
}
{
my $glibc_date_format = "\%d\/\%m\/\%y";
sub glibc_date_format { return $glibc_date_format }
}
{
my $glibc_date_1_format = "\%a\ \%b\ \%e\ \%H\:\%M\:\%S\ \%Z\ \%Y";
sub glibc_date_1_format { return $glibc_date_1_format }
}
{
my $glibc_datetime_format = "\%a\ \%d\ \%b\ \%Y\ \%T\ \%Z";
sub glibc_datetime_format { return $glibc_datetime_format }
}
{
my $glibc_time_format = "\%T";
sub glibc_time_format { return $glibc_time_format }
}
1;
__END__
=pod
=encoding utf8
=head1 NAME
DateTime::Locale::es_DO
=head1 SYNOPSIS
use DateTime;
my $dt = DateTime->now( locale => 'es_DO' );
print $dt->month_name();
=head1 DESCRIPTION
This is the DateTime locale package for Spanish Dominican Republic.
=head1 DATA
This locale inherits from the L<DateTime::Locale::es> locale.
It contains the following data.
=head2 Days
=head3 Wide (format)
lunes
martes
miércoles
jueves
viernes
sábado
domingo
=head3 Abbreviated (format)
lun
mar
mié
jue
vie
sáb
dom
=head3 Narrow (format)
L
M
M
J
V
S
D
=head3 Wide (stand-alone)
lunes
martes
miércoles
jueves
viernes
sábado
domingo
=head3 Abbreviated (stand-alone)
lun
mar
mié
jue
vie
sáb
dom
=head3 Narrow (stand-alone)
L
M
M
J
V
S
D
=head2 Months
=head3 Wide (format)
enero
febrero
marzo
abril
mayo
junio
julio
agosto
septiembre
octubre
noviembre
diciembre
=head3 Abbreviated (format)
ene
feb
mar
abr
may
jun
jul
ago
sep
oct
nov
dic
=head3 Narrow (format)
E
F
M
A
M
J
J
A
S
O
N
D
=head3 Wide (stand-alone)
enero
febrero
marzo
abril
mayo
junio
julio
agosto
septiembre
octubre
noviembre
diciembre
=head3 Abbreviated (stand-alone)
ene
feb
mar
abr
may
jun
jul
ago
sep
oct
nov
dic
=head3 Narrow (stand-alone)
E
F
M
A
M
J
J
A
S
O
N
D
=head2 Quarters
=head3 Wide (format)
1er trimestre
2º trimestre
3er trimestre
4º trimestre
=head3 Abbreviated (format)
T1
T2
T3
T4
=head3 Narrow (format)
1
2
3
4
=head3 Wide (stand-alone)
1er trimestre
2º trimestre
3er trimestre
4º trimestre
=head3 Abbreviated (stand-alone)
T1
T2
T3
T4
=head3 Narrow (stand-alone)
1
2
3
4
=head2 Eras
=head3 Wide
antes de Cristo
anno Dómini
=head3 Abbreviated
a.C.
d.C.
=head3 Narrow
a.C.
d.C.
=head2 Date Formats
=head3 Full
2008-02-05T18:30:30 = martes 5 de febrero de 2008
1995-12-22T09:05:02 = viernes 22 de diciembre de 1995
-0010-09-15T04:44:23 = sábado 15 de septiembre de -10
=head3 Long
2008-02-05T18:30:30 = 5 de febrero de 2008
1995-12-22T09:05:02 = 22 de diciembre de 1995
-0010-09-15T04:44:23 = 15 de septiembre de -10
=head3 Medium
2008-02-05T18:30:30 = 05/02/2008
1995-12-22T09:05:02 = 22/12/1995
-0010-09-15T04:44:23 = 15/09/-010
=head3 Short
2008-02-05T18:30:30 = 05/02/08
1995-12-22T09:05:02 = 22/12/95
-0010-09-15T04:44:23 = 15/09/-10
=head3 Default
2008-02-05T18:30:30 = 05/02/2008
1995-12-22T09:05:02 = 22/12/1995
-0010-09-15T04:44:23 = 15/09/-010
=head2 Time Formats
=head3 Full
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Long
2008-02-05T18:30:30 = 18:30:30 UTC
1995-12-22T09:05:02 = 09:05:02 UTC
-0010-09-15T04:44:23 = 04:44:23 UTC
=head3 Medium
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head3 Short
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 09:05
-0010-09-15T04:44:23 = 04:44
=head3 Default
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head2 Datetime Formats
=head3 Full
2008-02-05T18:30:30 = martes 5 de febrero de 2008 18:30:30 UTC
1995-12-22T09:05:02 = viernes 22 de diciembre de 1995 09:05:02 UTC
-0010-09-15T04:44:23 = sábado 15 de septiembre de -10 04:44:23 UTC
=head3 Long
2008-02-05T18:30:30 = 5 de febrero de 2008 18:30:30 UTC
1995-12-22T09:05:02 = 22 de diciembre de 1995 09:05:02 UTC
-0010-09-15T04:44:23 = 15 de septiembre de -10 04:44:23 UTC
=head3 Medium
2008-02-05T18:30:30 = 05/02/2008 18:30:30
1995-12-22T09:05:02 = 22/12/1995 09:05:02
-0010-09-15T04:44:23 = 15/09/-010 04:44:23
=head3 Short
2008-02-05T18:30:30 = 05/02/08 18:30
1995-12-22T09:05:02 = 22/12/95 09:05
-0010-09-15T04:44:23 = 15/09/-10 04:44
=head3 Default
2008-02-05T18:30:30 = 05/02/2008 18:30:30
1995-12-22T09:05:02 = 22/12/1995 09:05:02
-0010-09-15T04:44:23 = 15/09/-010 04:44:23
=head2 Available Formats
=head3 d (d)
2008-02-05T18:30:30 = 5
1995-12-22T09:05:02 = 22
-0010-09-15T04:44:23 = 15
=head3 EEEd (EEE d)
2008-02-05T18:30:30 = mar 5
1995-12-22T09:05:02 = vie 22
-0010-09-15T04:44:23 = sáb 15
=head3 HHmm (HH:mm)
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 09:05
-0010-09-15T04:44:23 = 04:44
=head3 hhmm (hh:mm a)
2008-02-05T18:30:30 = 06:30 p.m.
1995-12-22T09:05:02 = 09:05 a.m.
-0010-09-15T04:44:23 = 04:44 a.m.
=head3 HHmmss (HH:mm:ss)
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 09:05:02
-0010-09-15T04:44:23 = 04:44:23
=head3 hhmmss (hh:mm:ss a)
2008-02-05T18:30:30 = 06:30:30 p.m.
1995-12-22T09:05:02 = 09:05:02 a.m.
-0010-09-15T04:44:23 = 04:44:23 a.m.
=head3 Hm (H:mm)
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 9:05
-0010-09-15T04:44:23 = 4:44
=head3 hm (h:mm a)
2008-02-05T18:30:30 = 6:30 p.m.
1995-12-22T09:05:02 = 9:05 a.m.
-0010-09-15T04:44:23 = 4:44 a.m.
=head3 Hms (H:mm:ss)
2008-02-05T18:30:30 = 18:30:30
1995-12-22T09:05:02 = 9:05:02
-0010-09-15T04:44:23 = 4:44:23
=head3 hms (h:mm:ss a)
2008-02-05T18:30:30 = 6:30:30 p.m.
1995-12-22T09:05:02 = 9:05:02 a.m.
-0010-09-15T04:44:23 = 4:44:23 a.m.
=head3 M (L)
2008-02-05T18:30:30 = 2
1995-12-22T09:05:02 = 12
-0010-09-15T04:44:23 = 9
=head3 Md (d/M)
2008-02-05T18:30:30 = 5/2
1995-12-22T09:05:02 = 22/12
-0010-09-15T04:44:23 = 15/9
=head3 MEd (E, d-M)
2008-02-05T18:30:30 = mar, 5-2
1995-12-22T09:05:02 = vie, 22-12
-0010-09-15T04:44:23 = sáb, 15-9
=head3 MMd (d/MM)
2008-02-05T18:30:30 = 5/02
1995-12-22T09:05:02 = 22/12
-0010-09-15T04:44:23 = 15/09
=head3 MMdd (MM/dd)
2008-02-05T18:30:30 = 02/05
1995-12-22T09:05:02 = 12/22
-0010-09-15T04:44:23 = 09/15
=head3 MMM (LLL)
2008-02-05T18:30:30 = feb
1995-12-22T09:05:02 = dic
-0010-09-15T04:44:23 = sep
=head3 MMMd (d MMM)
2008-02-05T18:30:30 = 5 feb
1995-12-22T09:05:02 = 22 dic
-0010-09-15T04:44:23 = 15 sep
=head3 MMMdd (dd-MMM)
2008-02-05T18:30:30 = 05-feb
1995-12-22T09:05:02 = 22-dic
-0010-09-15T04:44:23 = 15-sep
=head3 MMMEd (E d MMM)
2008-02-05T18:30:30 = mar 5 feb
1995-12-22T09:05:02 = vie 22 dic
-0010-09-15T04:44:23 = sáb 15 sep
=head3 MMMMd (d 'de' MMMM)
2008-02-05T18:30:30 = 5 de febrero
1995-12-22T09:05:02 = 22 de diciembre
-0010-09-15T04:44:23 = 15 de septiembre
=head3 MMMMEd (E d MMMM)
2008-02-05T18:30:30 = mar 5 febrero
1995-12-22T09:05:02 = vie 22 diciembre
-0010-09-15T04:44:23 = sáb 15 septiembre
=head3 mmss (mm:ss)
2008-02-05T18:30:30 = 30:30
1995-12-22T09:05:02 = 05:02
-0010-09-15T04:44:23 = 44:23
=head3 ms (mm:ss)
2008-02-05T18:30:30 = 30:30
1995-12-22T09:05:02 = 05:02
-0010-09-15T04:44:23 = 44:23
=head3 y (y)
2008-02-05T18:30:30 = 2008
1995-12-22T09:05:02 = 1995
-0010-09-15T04:44:23 = -10
=head3 yM (M/yyyy)
2008-02-05T18:30:30 = 2/2008
1995-12-22T09:05:02 = 12/1995
-0010-09-15T04:44:23 = 9/-010
=head3 yMEd (EEE d/M/yyyy)
2008-02-05T18:30:30 = mar 5/2/2008
1995-12-22T09:05:02 = vie 22/12/1995
-0010-09-15T04:44:23 = sáb 15/9/-010
=head3 yMMM (MMM y)
2008-02-05T18:30:30 = feb 2008
1995-12-22T09:05:02 = dic 1995
-0010-09-15T04:44:23 = sep -10
=head3 yMMMEd (EEE, d MMM y)
2008-02-05T18:30:30 = mar, 5 feb 2008
1995-12-22T09:05:02 = vie, 22 dic 1995
-0010-09-15T04:44:23 = sáb, 15 sep -10
=head3 yMMMM (MMMM 'de' y)
2008-02-05T18:30:30 = febrero de 2008
1995-12-22T09:05:02 = diciembre de 1995
-0010-09-15T04:44:23 = septiembre de -10
=head3 yQ (Q yyyy)
2008-02-05T18:30:30 = 1 2008
1995-12-22T09:05:02 = 4 1995
-0010-09-15T04:44:23 = 3 -010
=head3 yQQQ (QQQ yyyy)
2008-02-05T18:30:30 = T1 2008
1995-12-22T09:05:02 = T4 1995
-0010-09-15T04:44:23 = T3 -010
=head3 yyMM (MM/yy)
2008-02-05T18:30:30 = 02/08
1995-12-22T09:05:02 = 12/95
-0010-09-15T04:44:23 = 09/-10
=head3 yyMMM (MMM-yy)
2008-02-05T18:30:30 = feb-08
1995-12-22T09:05:02 = dic-95
-0010-09-15T04:44:23 = sep--10
=head3 yyQ (Q yy)
2008-02-05T18:30:30 = 1 08
1995-12-22T09:05:02 = 4 95
-0010-09-15T04:44:23 = 3 -10
=head3 yyQQQQ (QQQQ 'de' yy)
2008-02-05T18:30:30 = 1er trimestre de 08
1995-12-22T09:05:02 = 4º trimestre de 95
-0010-09-15T04:44:23 = 3er trimestre de -10
=head3 yyyyMM (MM/yyyy)
2008-02-05T18:30:30 = 02/2008
1995-12-22T09:05:02 = 12/1995
-0010-09-15T04:44:23 = 09/-010
=head2 Miscellaneous
=head3 Prefers 24 hour time?
Yes
=head3 Local first day of the week
lunes
=head1 SUPPORT
See L<DateTime::Locale>.
=head1 AUTHOR
Dave Rolsky <autarch@urth.org>
=head1 COPYRIGHT
Copyright (c) 2008 David Rolsky. All rights reserved. This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.
This module was generated from data provided by the CLDR project, see
the LICENSE.cldr in this distribution for details on the CLDR data's
license.
=cut
| liuyangning/WX_web | xampp/perl/vendor/lib/DateTime/Locale/es_DO.pm | Perl | mit | 10,673 |
#!/usr/bin/env perl
#
# $Header$
#
# copyright (c) 2007-2010
# Author: Jeffrey I Cohen
#
#
use Pod::Usage;
use Getopt::Long;
use Data::Dumper;
use strict;
use warnings;
=head1 NAME
B<dld.pl> - [D]ead[L]ock [D]etector
=head1 SYNOPSIS
B<dld> [options]
Options:
-help brief help message
-man full documentation
-connect psql connect parameters
=head1 OPTIONS
=over 8
=item B<-help>
Print a brief help message and exits.
=item B<-man>
Prints the manual page and exits.
=item B<-connect>
psql connect string, e.g:
-connect '-p 11000 template1'
=back
=head1 DESCRIPTION
dld.pl finds (but does not fix) deadlocks
perl dld.pl -connect '-p 11000 template1'
Substitute the correct "connect string" for your postgres database.
=head1 AUTHORS
Jeffrey I Cohen
Copyright (c) 2007-2010 GreenPlum. All rights reserved.
Address bug reports and comments to: jcohen@greenplum.com
=cut
my $glob_id = "";
my $glob_tab;
my $glob_connect;
my $glob_verbose = 1;
BEGIN {
my $man = 0;
my $help = 0;
my $table;
my $conn;
GetOptions(
'help|?' => \$help, man => \$man,
"table=s" => \$table,
"connect=s" => \$conn
)
or pod2usage(2);
pod2usage(-msg => $glob_id, -exitstatus => 1) if $help;
pod2usage(-msg => $glob_id, -exitstatus => 0, -verbose => 2) if $man;
$glob_tab = $table;
$glob_connect = $conn;
$glob_connect = '-p 11000 template1'
unless (defined($glob_connect));
$glob_verbose = 1;
# print "loading...\n" ;
}
# convert a postgresql psql formatted table into an array of hashes
sub tablelizer
{
my $ini = shift;
# first, split into separate lines, the find all the column headings
my @lines = split(/\n/, $ini);
return undef
unless (scalar(@lines));
my $line1 = shift @lines;
# look for <space>|<space>
my @colheads = split(/\s+\|\s+/, $line1);
# fixup first, last column head (remove leading,trailing spaces)
$colheads[0] =~ s/^\s+//;
$colheads[0] =~ s/\s+$//;
$colheads[-1] =~ s/^\s+//;
$colheads[-1] =~ s/\s+$//;
return undef
unless (scalar(@lines));
shift @lines; # skip dashed separator
my @rows;
for my $lin (@lines)
{
my @cols = split(/\|/, $lin, scalar(@colheads));
last
unless (scalar(@cols) == scalar(@colheads));
my $rowh = {};
for my $colhd (@colheads)
{
my $rawcol = shift @cols;
$rawcol =~ s/^\s+//;
$rawcol =~ s/\s+$//;
$rowh->{$colhd} = $rawcol;
}
push @rows, $rowh;
}
return \@rows;
}
sub walk_graph
{
my ($wfg, $key, $visited) = @_;
if ($glob_verbose && defined($key))
{
print "key: $key\n";
print "visit: ", join("-> ", @{$visited}), "\n";
}
return 0
unless (defined($wfg) && (ref($wfg) eq 'HASH'));
my @wfg_keys = keys(%{$wfg});
unless (defined($visited))
{
for my $k1 (@wfg_keys)
{
my $stat = walk_graph($wfg, $k1, [$k1]);
return 0
unless ($stat);
}
return 1;
}
my $k1 = $key;
return 1
unless (exists($wfg->{$k1}));
{
for my $holder (@{$wfg->{$k1}->{primary}})
{
for my $itm (@{$visited})
{
if ($itm eq $holder)
{
print "cycle detected!\n";
my $first = $visited->[0];
print join(" -> ", @{$visited}, $first), "\n";
return 0;
}
}
my $v2;
$v2 = [];
push @{$v2}, @{$visited}, $holder;
return 0
unless (walk_graph($wfg, $holder, $v2));
}
}
return 1;
}
if (1)
{
my $psql_str = "psql ";
$psql_str .= $glob_connect
if (defined($glob_connect));
# need to deal with mirrors, etc
# $psql_str .= " -c \'select * from gp_configuration where definedprimary is true or content > 0\'";
$psql_str .= " -c \'select * from gp_segment_configuration where role=" .
# use "dollar-quoting" to avoid dealing with nested single-quotes:
# $q$p$q$ is equivalent to 'p'
'$q$p$q$' . " \'";
# print $psql_str, "\n";
my $tabdef = `$psql_str`;
print $tabdef
if ($glob_verbose);
my $mpp_config_table = tablelizer($tabdef);
# some locks are on txns, not relations, so no relnames
my $sel_str = "\'select cl.relname as relname, lk.* from pg_locks as lk left outer join pg_class as cl on cl.relfilenode = lk.relation\'";
my @combo_tab;
my @rel_list;
my @txn_list;
for my $rowh (@{$mpp_config_table})
{
# print Data::Dumper->Dump([$vv]), "\n";
my $psql_seg = "PGOPTIONS=\'-c gp_session_role=utility\' psql -h $rowh->{hostname} -p $rowh->{port} template1 -c $sel_str";
print $psql_seg,"\n"
if ($glob_verbose);
my $lk1 = `$psql_seg`;
print $lk1
if ($glob_verbose);
my $tabh = tablelizer($lk1);
# print Data::Dumper->Dump([$tabh]), "\n";
for my $rr (@{$tabh})
{
$rr->{segid} = $rowh->{content};
# look for waiters - "granted = [f]alse"
if ($rr->{granted} =~ m/\s*f\s*/ )
{
if ($rr->{locktype} =~ m/transactionid/)
{
push @txn_list, $rr->{transactionid};
}
else
{
push @rel_list, $rr->{relation};
}
}
}
push @combo_tab, @{$tabh};
}
# find all txns with same tables as waiters
my @wait_tab;
my $rel_str = join(", ", @rel_list);
my $txn_str = join(", ", @txn_list);
# print "rel_str: $rel_str\ntxn_str: $txn_str\n";
$sel_str = "\'select cl.relname as relname, lk.* from pg_locks as lk left outer join pg_class as cl on cl.relfilenode = lk.relation ";
if (scalar(@rel_list) || scalar(@txn_list))
{
$sel_str .= " \'";
for my $rowh (@{$mpp_config_table})
{
# print Data::Dumper->Dump([$vv]), "\n";
my $psql_seg = "PGOPTIONS=\'-c gp_session_role=utility\' psql -h $rowh->{hostname} -p $rowh->{port} template1 -c $sel_str";
my $lk1 = `$psql_seg`;
print $lk1
if ($glob_verbose);
my $tabh = tablelizer($lk1);
# print Data::Dumper->Dump([$tabh]), "\n";
for my $rr (@{$tabh})
{
$rr->{segid} = $rowh->{content};
# map {$_->{segid} = $mpp_config_table->{content} }, @{$tabh};
}
push @wait_tab, @{$tabh};
}
}
print "wait_tab:", Data::Dumper->Dump(\@wait_tab), "\n"
if ($glob_verbose);
# print Data::Dumper->Dump(\@combo_tab), "\n";
my %holders;
my %waiters;
# find lock holders and lock waiters per relation
for my $wrow (@wait_tab)
{
my $reltn = $wrow->{relation};
next
unless (defined($reltn));
if ($wrow->{granted} eq 't')
{
unless (exists($holders{$reltn}))
{
$holders{$reltn} = [];
}
push @{$holders{$reltn}}, $wrow;
}
else
{
unless (exists($waiters{$reltn}))
{
$waiters{$reltn} = [];
}
push @{$waiters{$reltn}}, $wrow;
}
}
my %wfg; # WAIT FOR GRAPH by segment, pid
while ( my ($kk, $vv) = each(%waiters))
{
for my $waititm (@{$vv})
{
my $big_id = $waititm->{segid} . "/" . $waititm->{pid};
unless (exists($wfg{$big_id}))
{
$wfg{$big_id} = {primary => []};
}
unless (exists($holders{$kk}))
{
print "no lock holder for relation $kk!!\n";
next;
}
for my $holditm (@{$holders{$kk}})
{
my $h_id = $holditm->{segid} . "/" . $holditm->{pid};
# don't wait on yourself
next
if ($h_id eq $big_id);
push @{$wfg{$big_id}->{primary}}, $h_id;
}
}
}
if ($glob_verbose)
{
print "waiters:\n",Data::Dumper->Dump([%waiters]), "\n";
print "holders:\n",Data::Dumper->Dump([%holders]), "\n";
print "wfg:\n",Data::Dumper->Dump([%wfg]), "\n";
}
walk_graph(\%wfg);
}
exit();
| PGer/incubator-hawq | src/test/regress/dld.pl | Perl | apache-2.0 | 8,763 |
package Digest;
use strict;
use vars qw($VERSION %MMAP $AUTOLOAD);
$VERSION = "1.15";
%MMAP = (
"SHA-1" => ["Digest::SHA1", ["Digest::SHA", 1], ["Digest::SHA2", 1]],
"SHA-224" => [["Digest::SHA", 224]],
"SHA-256" => [["Digest::SHA", 256], ["Digest::SHA2", 256]],
"SHA-384" => [["Digest::SHA", 384], ["Digest::SHA2", 384]],
"SHA-512" => [["Digest::SHA", 512], ["Digest::SHA2", 512]],
"HMAC-MD5" => "Digest::HMAC_MD5",
"HMAC-SHA-1" => "Digest::HMAC_SHA1",
"CRC-16" => [["Digest::CRC", type => "crc16"]],
"CRC-32" => [["Digest::CRC", type => "crc32"]],
"CRC-CCITT" => [["Digest::CRC", type => "crcccitt"]],
);
sub new
{
shift; # class ignored
my $algorithm = shift;
my $impl = $MMAP{$algorithm} || do {
$algorithm =~ s/\W+//;
"Digest::$algorithm";
};
$impl = [$impl] unless ref($impl);
my $err;
for (@$impl) {
my $class = $_;
my @args;
($class, @args) = @$class if ref($class);
no strict 'refs';
unless (exists ${"$class\::"}{"VERSION"}) {
eval "require $class";
if ($@) {
$err ||= $@;
next;
}
}
return $class->new(@args, @_);
}
die $err;
}
sub AUTOLOAD
{
my $class = shift;
my $algorithm = substr($AUTOLOAD, rindex($AUTOLOAD, '::')+2);
$class->new($algorithm, @_);
}
1;
__END__
=head1 NAME
Digest - Modules that calculate message digests
=head1 SYNOPSIS
$md5 = Digest->new("MD5");
$sha1 = Digest->new("SHA-1");
$sha256 = Digest->new("SHA-256");
$sha384 = Digest->new("SHA-384");
$sha512 = Digest->new("SHA-512");
$hmac = Digest->HMAC_MD5($key);
=head1 DESCRIPTION
The C<Digest::> modules calculate digests, also called "fingerprints"
or "hashes", of some data, called a message. The digest is (usually)
some small/fixed size string. The actual size of the digest depend of
the algorithm used. The message is simply a sequence of arbitrary
bytes or bits.
An important property of the digest algorithms is that the digest is
I<likely> to change if the message change in some way. Another
property is that digest functions are one-way functions, that is it
should be I<hard> to find a message that correspond to some given
digest. Algorithms differ in how "likely" and how "hard", as well as
how efficient they are to compute.
Note that the properties of the algorithms change over time, as the
algorithms are analyzed and machines grow faster. If your application
for instance depends on it being "impossible" to generate the same
digest for a different message it is wise to make it easy to plug in
stronger algorithms as the one used grow weaker. Using the interface
documented here should make it easy to change algorithms later.
All C<Digest::> modules provide the same programming interface. A
functional interface for simple use, as well as an object oriented
interface that can handle messages of arbitrary length and which can
read files directly.
The digest can be delivered in three formats:
=over 8
=item I<binary>
This is the most compact form, but it is not well suited for printing
or embedding in places that can't handle arbitrary data.
=item I<hex>
A twice as long string of lowercase hexadecimal digits.
=item I<base64>
A string of portable printable characters. This is the base64 encoded
representation of the digest with any trailing padding removed. The
string will be about 30% longer than the binary version.
L<MIME::Base64> tells you more about this encoding.
=back
The functional interface is simply importable functions with the same
name as the algorithm. The functions take the message as argument and
return the digest. Example:
use Digest::MD5 qw(md5);
$digest = md5($message);
There are also versions of the functions with "_hex" or "_base64"
appended to the name, which returns the digest in the indicated form.
=head1 OO INTERFACE
The following methods are available for all C<Digest::> modules:
=over 4
=item $ctx = Digest->XXX($arg,...)
=item $ctx = Digest->new(XXX => $arg,...)
=item $ctx = Digest::XXX->new($arg,...)
The constructor returns some object that encapsulate the state of the
message-digest algorithm. You can add data to the object and finally
ask for the digest. The "XXX" should of course be replaced by the proper
name of the digest algorithm you want to use.
The two first forms are simply syntactic sugar which automatically
load the right module on first use. The second form allow you to use
algorithm names which contains letters which are not legal perl
identifiers, e.g. "SHA-1". If no implementation for the given algorithm
can be found, then an exception is raised.
If new() is called as an instance method (i.e. $ctx->new) it will just
reset the state the object to the state of a newly created object. No
new object is created in this case, and the return value is the
reference to the object (i.e. $ctx).
=item $other_ctx = $ctx->clone
The clone method creates a copy of the digest state object and returns
a reference to the copy.
=item $ctx->reset
This is just an alias for $ctx->new.
=item $ctx->add( $data )
=item $ctx->add( $chunk1, $chunk2, ... )
The string value of the $data provided as argument is appended to the
message we calculate the digest for. The return value is the $ctx
object itself.
If more arguments are provided then they are all appended to the
message, thus all these lines will have the same effect on the state
of the $ctx object:
$ctx->add("a"); $ctx->add("b"); $ctx->add("c");
$ctx->add("a")->add("b")->add("c");
$ctx->add("a", "b", "c");
$ctx->add("abc");
Most algorithms are only defined for strings of bytes and this method
might therefore croak if the provided arguments contain chars with
ordinal number above 255.
=item $ctx->addfile( $io_handle )
The $io_handle is read until EOF and the content is appended to the
message we calculate the digest for. The return value is the $ctx
object itself.
The addfile() method will croak() if it fails reading data for some
reason. If it croaks it is unpredictable what the state of the $ctx
object will be in. The addfile() method might have been able to read
the file partially before it failed. It is probably wise to discard
or reset the $ctx object if this occurs.
In most cases you want to make sure that the $io_handle is in
"binmode" before you pass it as argument to the addfile() method.
=item $ctx->add_bits( $data, $nbits )
=item $ctx->add_bits( $bitstring )
The add_bits() method is an alternative to add() that allow partial
bytes to be appended to the message. Most users should just ignore
this method as partial bytes is very unlikely to be of any practical
use.
The two argument form of add_bits() will add the first $nbits bits
from $data. For the last potentially partial byte only the high order
C<< $nbits % 8 >> bits are used. If $nbits is greater than C<<
length($data) * 8 >>, then this method would do the same as C<<
$ctx->add($data) >>.
The one argument form of add_bits() takes a $bitstring of "1" and "0"
chars as argument. It's a shorthand for C<< $ctx->add_bits(pack("B*",
$bitstring), length($bitstring)) >>.
The return value is the $ctx object itself.
This example shows two calls that should have the same effect:
$ctx->add_bits("111100001010");
$ctx->add_bits("\xF0\xA0", 12);
Most digest algorithms are byte based and for these it is not possible
to add bits that are not a multiple of 8, and the add_bits() method
will croak if you try.
=item $ctx->digest
Return the binary digest for the message.
Note that the C<digest> operation is effectively a destructive,
read-once operation. Once it has been performed, the $ctx object is
automatically C<reset> and can be used to calculate another digest
value. Call $ctx->clone->digest if you want to calculate the digest
without resetting the digest state.
=item $ctx->hexdigest
Same as $ctx->digest, but will return the digest in hexadecimal form.
=item $ctx->b64digest
Same as $ctx->digest, but will return the digest as a base64 encoded
string.
=back
=head1 Digest speed
This table should give some indication on the relative speed of
different algorithms. It is sorted by throughput based on a benchmark
done with of some implementations of this API:
Algorithm Size Implementation MB/s
MD4 128 Digest::MD4 v1.3 165.0
MD5 128 Digest::MD5 v2.33 98.8
SHA-256 256 Digest::SHA2 v1.1.0 66.7
SHA-1 160 Digest::SHA v4.3.1 58.9
SHA-1 160 Digest::SHA1 v2.10 48.8
SHA-256 256 Digest::SHA v4.3.1 41.3
Haval-256 256 Digest::Haval256 v1.0.4 39.8
SHA-384 384 Digest::SHA2 v1.1.0 19.6
SHA-512 512 Digest::SHA2 v1.1.0 19.3
SHA-384 384 Digest::SHA v4.3.1 19.2
SHA-512 512 Digest::SHA v4.3.1 19.2
Whirlpool 512 Digest::Whirlpool v1.0.2 13.0
MD2 128 Digest::MD2 v2.03 9.5
Adler-32 32 Digest::Adler32 v0.03 1.3
CRC-16 16 Digest::CRC v0.05 1.1
CRC-32 32 Digest::CRC v0.05 1.1
MD5 128 Digest::Perl::MD5 v1.5 1.0
CRC-CCITT 16 Digest::CRC v0.05 0.8
These numbers was achieved Apr 2004 with ActivePerl-5.8.3 running
under Linux on a P4 2.8 GHz CPU. The last 5 entries differ by being
pure perl implementations of the algorithms, which explains why they
are so slow.
=head1 SEE ALSO
L<Digest::Adler32>, L<Digest::CRC>, L<Digest::Haval256>,
L<Digest::HMAC>, L<Digest::MD2>, L<Digest::MD4>, L<Digest::MD5>,
L<Digest::SHA>, L<Digest::SHA1>, L<Digest::SHA2>, L<Digest::Whirlpool>
New digest implementations should consider subclassing from L<Digest::base>.
L<MIME::Base64>
http://en.wikipedia.org/wiki/Cryptographic_hash_function
=head1 AUTHOR
Gisle Aas <gisle@aas.no>
The C<Digest::> interface is based on the interface originally
developed by Neil Winton for his C<MD5> module.
This library is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
Copyright 1998-2006 Gisle Aas.
Copyright 1995,1996 Neil Winton.
=cut
| leighpauls/k2cro4 | third_party/cygwin/lib/perl5/5.10/Digest.pm | Perl | bsd-3-clause | 10,316 |
#
# Copyright (C) 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
# Copyright (C) 2006 Anders Carlsson <andersca@mac.com>
# Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org>
# Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org>
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
# Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
# Copyright (C) Research In Motion Limited 2010. All rights reserved.
# Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this library; see the file COPYING.LIB. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
package CodeGeneratorJS;
my $module = "";
my $outputDir = "";
my $writeDependencies = 0;
my @headerContentHeader = ();
my @headerContent = ();
my %headerIncludes = ();
my %headerTrailingIncludes = ();
my @implContentHeader = ();
my @implContent = ();
my %implIncludes = ();
my @depsContent = ();
my $numCachedAttributes = 0;
my $currentCachedAttribute = 0;
# Default .h template
my $headerTemplate = << "EOF";
/*
This file is part of the WebKit open source project.
This file has been generated by generate-bindings.pl. DO NOT MODIFY!
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
EOF
# Default constructor
sub new
{
my $object = shift;
my $reference = { };
$codeGenerator = shift;
$outputDir = shift;
shift; # $outputHeadersDir
shift; # $useLayerOnTop
shift; # $preprocessor
$writeDependencies = shift;
bless($reference, $object);
return $reference;
}
sub finish
{
my $object = shift;
# Commit changes!
$object->WriteData();
}
sub leftShift($$) {
my ($value, $distance) = @_;
return (($value << $distance) & 0xFFFFFFFF);
}
# Params: 'domClass' struct
sub GenerateInterface
{
my $object = shift;
my $dataNode = shift;
my $defines = shift;
$codeGenerator->LinkOverloadedFunctions($dataNode);
# Start actual generation
if ($dataNode->extendedAttributes->{"Callback"}) {
$object->GenerateCallbackHeader($dataNode);
$object->GenerateCallbackImplementation($dataNode);
} else {
$object->GenerateHeader($dataNode);
$object->GenerateImplementation($dataNode);
}
my $name = $dataNode->name;
# Open files for writing
my $headerFileName = "$outputDir/JS$name.h";
my $implFileName = "$outputDir/JS$name.cpp";
my $depsFileName = "$outputDir/JS$name.dep";
# Remove old dependency file.
unlink($depsFileName);
open($IMPL, ">$implFileName") || die "Couldn't open file $implFileName";
open($HEADER, ">$headerFileName") || die "Couldn't open file $headerFileName";
if (@depsContent) {
open($DEPS, ">$depsFileName") || die "Couldn't open file $depsFileName";
}
}
sub GenerateAttributeEventListenerCall
{
my $className = shift;
my $implSetterFunctionName = shift;
my $windowEventListener = shift;
my $wrapperObject = $windowEventListener ? "globalObject" : "thisObject";
my @GenerateEventListenerImpl = ();
if ($className eq "JSSVGElementInstance") {
# SVGElementInstances have to create JSEventListeners with the wrapper equal to the correspondingElement
$wrapperObject = "asObject(correspondingElementWrapper)";
push(@GenerateEventListenerImpl, <<END);
JSValue correspondingElementWrapper = toJS(exec, castedThis->globalObject(), imp->correspondingElement());
if (correspondingElementWrapper.isObject())
END
# Add leading whitespace to format the imp->set... line correctly
push(@GenerateEventListenerImpl, " ");
}
push(@GenerateEventListenerImpl, " imp->set$implSetterFunctionName(createJSAttributeEventListener(exec, value, $wrapperObject));\n");
return @GenerateEventListenerImpl;
}
sub GenerateEventListenerCall
{
my $className = shift;
my $functionName = shift;
my $passRefPtrHandling = ($functionName eq "add") ? "" : ".get()";
$implIncludes{"JSEventListener.h"} = 1;
my @GenerateEventListenerImpl = ();
my $wrapperObject = "castedThis";
if ($className eq "JSSVGElementInstance") {
# SVGElementInstances have to create JSEventListeners with the wrapper equal to the correspondingElement
$wrapperObject = "asObject(correspondingElementWrapper)";
push(@GenerateEventListenerImpl, <<END);
JSValue correspondingElementWrapper = toJS(exec, castedThis->globalObject(), imp->correspondingElement());
if (!correspondingElementWrapper.isObject())
return JSValue::encode(jsUndefined());
END
}
push(@GenerateEventListenerImpl, <<END);
JSValue listener = exec->argument(1);
if (!listener.isObject())
return JSValue::encode(jsUndefined());
imp->${functionName}EventListener(ustringToAtomicString(exec->argument(0).toString(exec)), JSEventListener::create(asObject(listener), $wrapperObject, false, currentWorld(exec))$passRefPtrHandling, exec->argument(2).toBoolean(exec));
return JSValue::encode(jsUndefined());
END
return @GenerateEventListenerImpl;
}
# Params: 'idlDocument' struct
sub GenerateModule
{
my $object = shift;
my $dataNode = shift;
$module = $dataNode->module;
}
sub GetParentClassName
{
my $dataNode = shift;
return $dataNode->extendedAttributes->{"LegacyParent"} if $dataNode->extendedAttributes->{"LegacyParent"};
return "JSDOMWrapper" if (@{$dataNode->parents} eq 0);
return "JS" . $codeGenerator->StripModule($dataNode->parents(0));
}
sub GetVisibleClassName
{
my $className = shift;
return "DOMException" if $className eq "DOMCoreException";
return "FormData" if $className eq "DOMFormData";
return "MimeType" if $className eq "DOMMimeType";
return "MimeTypeArray" if $className eq "DOMMimeTypeArray";
return "Plugin" if $className eq "DOMPlugin";
return "PluginArray" if $className eq "DOMPluginArray";
return $className;
}
sub GetCallbackClassName
{
my $className = shift;
return "JSCustomVoidCallback" if $className eq "VoidCallback";
return "JS$className";
}
sub IndexGetterReturnsStrings
{
my $type = shift;
return 1 if $type eq "CSSStyleDeclaration" or $type eq "MediaList" or $type eq "DOMStringList" or $type eq "DOMTokenList" or $type eq "DOMSettableTokenList";
return 0;
}
sub AddIncludesForType
{
my $type = $codeGenerator->StripModule(shift);
my $isCallback = @_ ? shift : 0;
# When we're finished with the one-file-per-class
# reorganization, we won't need these special cases.
if ($codeGenerator->IsPrimitiveType($type) or $codeGenerator->AvoidInclusionOfType($type)
or $type eq "DOMString" or $type eq "DOMObject" or $type eq "Array") {
} elsif ($type =~ /SVGPathSeg/) {
$joinedName = $type;
$joinedName =~ s/Abs|Rel//;
$implIncludes{"${joinedName}.h"} = 1;
} elsif ($type eq "XPathNSResolver") {
$implIncludes{"JSXPathNSResolver.h"} = 1;
$implIncludes{"JSCustomXPathNSResolver.h"} = 1;
} elsif ($isCallback) {
$implIncludes{"JS${type}.h"} = 1;
} else {
# default, include the same named file
$implIncludes{"${type}.h"} = 1;
}
# additional includes (things needed to compile the bindings but not the header)
if ($type eq "CanvasRenderingContext2D") {
$implIncludes{"CanvasGradient.h"} = 1;
$implIncludes{"CanvasPattern.h"} = 1;
$implIncludes{"CanvasStyle.h"} = 1;
}
if ($type eq "CanvasGradient" or $type eq "XPathNSResolver" or $type eq "MessagePort") {
$implIncludes{"PlatformString.h"} = 1;
}
if ($type eq "Document") {
$implIncludes{"NodeFilter.h"} = 1;
}
if ($type eq "MediaQueryListListener") {
$implIncludes{"MediaQueryListListener.h"} = 1;
}
}
# FIXME: This method will go away once all SVG animated properties are converted to the new scheme.
sub AddIncludesForSVGAnimatedType
{
my $type = shift;
$type =~ s/SVGAnimated//;
if ($type eq "Point" or $type eq "Rect") {
$implIncludes{"Float$type.h"} = 1;
} elsif ($type eq "String") {
$implIncludes{"PlatformString.h"} = 1;
}
}
sub IsScriptProfileType
{
my $type = shift;
return 1 if ($type eq "ScriptProfileNode");
return 0;
}
sub AddTypedefForScriptProfileType
{
my $type = shift;
(my $jscType = $type) =~ s/Script//;
push(@headerContent, "typedef JSC::$jscType $type;\n\n");
}
sub AddClassForwardIfNeeded
{
my $implClassName = shift;
# SVGAnimatedLength/Number/etc. are typedefs to SVGAnimatedTemplate, so don't use class forwards for them!
unless ($codeGenerator->IsSVGAnimatedType($implClassName) or IsScriptProfileType($implClassName)) {
push(@headerContent, "class $implClassName;\n\n");
# ScriptProfile and ScriptProfileNode are typedefs to JSC::Profile and JSC::ProfileNode.
} elsif (IsScriptProfileType($implClassName)) {
AddTypedefForScriptProfileType($implClassName);
}
}
sub HashValueForClassAndName
{
my $class = shift;
my $name = shift;
# SVG Filter enums live in WebCore namespace (platform/graphics/)
if ($class =~ /^SVGFE*/ or $class =~ /^SVGComponentTransferFunctionElement$/) {
return "WebCore::$name";
}
return "${class}::$name";
}
sub hashTableAccessor
{
my $noStaticTables = shift;
my $className = shift;
if ($noStaticTables) {
return "get${className}Table(exec)";
} else {
return "&${className}Table";
}
}
sub prototypeHashTableAccessor
{
my $noStaticTables = shift;
my $className = shift;
if ($noStaticTables) {
return "get${className}PrototypeTable(exec)";
} else {
return "&${className}PrototypeTable";
}
}
sub GenerateConditionalStringFromAttributeValue
{
my $conditional = shift;
if ($conditional =~ /&/) {
return "ENABLE(" . join(") && ENABLE(", split(/&/, $conditional)) . ")";
} elsif ($conditional =~ /\|/) {
return "ENABLE(" . join(") || ENABLE(", split(/\|/, $conditional)) . ")";
} else {
return "ENABLE(" . $conditional . ")";
}
}
sub GenerateConditionalString
{
my $node = shift;
my $conditional = $node->extendedAttributes->{"Conditional"};
if ($conditional) {
return GenerateConditionalStringFromAttributeValue($conditional);
} else {
return "";
}
}
sub GenerateGetOwnPropertySlotBody
{
my ($dataNode, $interfaceName, $className, $implClassName, $hasAttributes, $inlined) = @_;
my $namespaceMaybe = ($inlined ? "JSC::" : "");
my @getOwnPropertySlotImpl = ();
if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
push(@getOwnPropertySlotImpl, " ${namespaceMaybe}JSValue proto = prototype();\n");
push(@getOwnPropertySlotImpl, " if (proto.isObject() && static_cast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n");
push(@getOwnPropertySlotImpl, " return false;\n\n");
}
my $manualLookupGetterGeneration = sub {
my $requiresManualLookup = $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasNameGetter"};
if ($requiresManualLookup) {
push(@getOwnPropertySlotImpl, " const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n");
push(@getOwnPropertySlotImpl, " if (entry) {\n");
push(@getOwnPropertySlotImpl, " slot.setCustom(this, entry->propertyGetter());\n");
push(@getOwnPropertySlotImpl, " return true;\n");
push(@getOwnPropertySlotImpl, " }\n");
}
};
if (!$dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
&$manualLookupGetterGeneration();
}
if ($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@getOwnPropertySlotImpl, " bool ok;\n");
push(@getOwnPropertySlotImpl, " unsigned index = propertyName.toUInt32(ok);\n");
# If the item function returns a string then we let the ConvertNullStringTo handle the cases
# where the index is out of range.
if (IndexGetterReturnsStrings($implClassName)) {
push(@getOwnPropertySlotImpl, " if (ok) {\n");
} else {
push(@getOwnPropertySlotImpl, " if (ok && index < static_cast<$implClassName*>(impl())->length()) {\n");
}
if ($dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@getOwnPropertySlotImpl, " slot.setValue(getByIndex(exec, index));\n");
} else {
push(@getOwnPropertySlotImpl, " slot.setCustomIndex(this, index, indexGetter);\n");
}
push(@getOwnPropertySlotImpl, " return true;\n");
push(@getOwnPropertySlotImpl, " }\n");
}
if ($dataNode->extendedAttributes->{"HasNameGetter"} || $dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
push(@getOwnPropertySlotImpl, " if (canGetItemsForName(exec, static_cast<$implClassName*>(impl()), propertyName)) {\n");
push(@getOwnPropertySlotImpl, " slot.setCustom(this, nameGetter);\n");
push(@getOwnPropertySlotImpl, " return true;\n");
push(@getOwnPropertySlotImpl, " }\n");
if ($inlined) {
$headerIncludes{"wtf/text/AtomicString.h"} = 1;
} else {
$implIncludes{"wtf/text/AtomicString.h"} = 1;
}
}
if ($dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
&$manualLookupGetterGeneration();
}
if ($dataNode->extendedAttributes->{"DelegatingGetOwnPropertySlot"}) {
push(@getOwnPropertySlotImpl, " if (getOwnPropertySlotDelegate(exec, propertyName, slot))\n");
push(@getOwnPropertySlotImpl, " return true;\n");
}
if ($hasAttributes) {
if ($inlined) {
die "Cannot inline if NoStaticTables is set." if ($dataNode->extendedAttributes->{"NoStaticTables"});
push(@getOwnPropertySlotImpl, " return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, s_info.staticPropHashTable, this, propertyName, slot);\n");
} else {
push(@getOwnPropertySlotImpl, " return ${namespaceMaybe}getStaticValueSlot<$className, Base>(exec, " . hashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n");
}
} else {
push(@getOwnPropertySlotImpl, " return Base::getOwnPropertySlot(exec, propertyName, slot);\n");
}
return @getOwnPropertySlotImpl;
}
sub GenerateGetOwnPropertyDescriptorBody
{
my ($dataNode, $interfaceName, $className, $implClassName, $hasAttributes, $inlined) = @_;
my $namespaceMaybe = ($inlined ? "JSC::" : "");
my @getOwnPropertyDescriptorImpl = ();
if ($dataNode->extendedAttributes->{"CheckDomainSecurity"}) {
if ($interfaceName eq "DOMWindow") {
push(@implContent, " if (!static_cast<$className*>(thisObject)->allowsAccessFrom(exec))\n");
} else {
push(@implContent, " if (!allowsAccessFromFrame(exec, static_cast<$className*>(thisObject)->impl()->frame()))\n");
}
push(@implContent, " return false;\n");
}
if ($interfaceName eq "NamedNodeMap" or $interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
push(@getOwnPropertyDescriptorImpl, " ${namespaceMaybe}JSValue proto = prototype();\n");
push(@getOwnPropertyDescriptorImpl, " if (proto.isObject() && static_cast<${namespaceMaybe}JSObject*>(asObject(proto))->hasProperty(exec, propertyName))\n");
push(@getOwnPropertyDescriptorImpl, " return false;\n\n");
}
my $manualLookupGetterGeneration = sub {
my $requiresManualLookup = $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasNameGetter"};
if ($requiresManualLookup) {
push(@getOwnPropertyDescriptorImpl, " const ${namespaceMaybe}HashEntry* entry = ${className}Table.entry(exec, propertyName);\n");
push(@getOwnPropertyDescriptorImpl, " if (entry) {\n");
push(@getOwnPropertyDescriptorImpl, " PropertySlot slot;\n");
push(@getOwnPropertyDescriptorImpl, " slot.setCustom(this, entry->propertyGetter());\n");
push(@getOwnPropertyDescriptorImpl, " descriptor.setDescriptor(slot.getValue(exec, propertyName), entry->attributes());\n");
push(@getOwnPropertyDescriptorImpl, " return true;\n");
push(@getOwnPropertyDescriptorImpl, " }\n");
}
};
if (!$dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
&$manualLookupGetterGeneration();
}
if ($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@getOwnPropertyDescriptorImpl, " bool ok;\n");
push(@getOwnPropertyDescriptorImpl, " unsigned index = propertyName.toUInt32(ok);\n");
push(@getOwnPropertyDescriptorImpl, " if (ok && index < static_cast<$implClassName*>(impl())->length()) {\n");
if ($dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
# Assume that if there's a setter, the index will be writable
if ($dataNode->extendedAttributes->{"HasIndexSetter"} || $dataNode->extendedAttributes->{"HasCustomIndexSetter"}) {
push(@getOwnPropertyDescriptorImpl, " descriptor.setDescriptor(getByIndex(exec, index), ${namespaceMaybe}DontDelete);\n");
} else {
push(@getOwnPropertyDescriptorImpl, " descriptor.setDescriptor(getByIndex(exec, index), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
}
} else {
push(@getOwnPropertyDescriptorImpl, " ${namespaceMaybe}PropertySlot slot;\n");
push(@getOwnPropertyDescriptorImpl, " slot.setCustomIndex(this, index, indexGetter);\n");
# Assume that if there's a setter, the index will be writable
if ($dataNode->extendedAttributes->{"HasIndexSetter"} || $dataNode->extendedAttributes->{"HasCustomIndexSetter"}) {
push(@getOwnPropertyDescriptorImpl, " descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete);\n");
} else {
push(@getOwnPropertyDescriptorImpl, " descriptor.setDescriptor(slot.getValue(exec, propertyName), ${namespaceMaybe}DontDelete | ${namespaceMaybe}ReadOnly);\n");
}
}
push(@getOwnPropertyDescriptorImpl, " return true;\n");
push(@getOwnPropertyDescriptorImpl, " }\n");
}
if ($dataNode->extendedAttributes->{"HasNameGetter"} || $dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
push(@getOwnPropertyDescriptorImpl, " if (canGetItemsForName(exec, static_cast<$implClassName*>(impl()), propertyName)) {\n");
push(@getOwnPropertyDescriptorImpl, " ${namespaceMaybe}PropertySlot slot;\n");
push(@getOwnPropertyDescriptorImpl, " slot.setCustom(this, nameGetter);\n");
push(@getOwnPropertyDescriptorImpl, " descriptor.setDescriptor(slot.getValue(exec, propertyName), ReadOnly | DontDelete | DontEnum);\n");
push(@getOwnPropertyDescriptorImpl, " return true;\n");
push(@getOwnPropertyDescriptorImpl, " }\n");
if ($inlined) {
$headerIncludes{"wtf/text/AtomicString.h"} = 1;
} else {
$implIncludes{"wtf/text/AtomicString.h"} = 1;
}
}
if ($dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
&$manualLookupGetterGeneration();
}
if ($dataNode->extendedAttributes->{"DelegatingGetOwnPropertySlot"}) {
push(@getOwnPropertyDescriptorImpl, " if (getOwnPropertyDescriptorDelegate(exec, propertyName, descriptor))\n");
push(@getOwnPropertyDescriptorImpl, " return true;\n");
}
if ($hasAttributes) {
if ($inlined) {
die "Cannot inline if NoStaticTables is set." if ($dataNode->extendedAttributes->{"NoStaticTables"});
push(@getOwnPropertyDescriptorImpl, " return ${namespaceMaybe}getStaticValueDescriptor<$className, Base>(exec, s_info.staticPropHashTable, this, propertyName, descriptor);\n");
} else {
push(@getOwnPropertyDescriptorImpl, " return ${namespaceMaybe}getStaticValueDescriptor<$className, Base>(exec, " . hashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, descriptor);\n");
}
} else {
push(@getOwnPropertyDescriptorImpl, " return Base::getOwnPropertyDescriptor(exec, propertyName, descriptor);\n");
}
return @getOwnPropertyDescriptorImpl;
}
sub GenerateHeaderContentHeader
{
my $dataNode = shift;
my $className = "JS" . $dataNode->name;
my @headerContentHeader = split("\r", $headerTemplate);
# - Add header protection
push(@headerContentHeader, "\n#ifndef $className" . "_h");
push(@headerContentHeader, "\n#define $className" . "_h\n\n");
my $conditionalString = GenerateConditionalString($dataNode);
push(@headerContentHeader, "#if ${conditionalString}\n\n") if $conditionalString;
return @headerContentHeader;
}
sub GenerateImplementationContentHeader
{
my $dataNode = shift;
my $className = "JS" . $dataNode->name;
my @implContentHeader = split("\r", $headerTemplate);
push(@implContentHeader, "\n#include \"config.h\"\n");
my $conditionalString = GenerateConditionalString($dataNode);
push(@implContentHeader, "\n#if ${conditionalString}\n\n") if $conditionalString;
push(@implContentHeader, "#include \"$className.h\"\n\n");
return @implContentHeader;
}
my %usesToJSNewlyCreated = (
"CDATASection" => 1,
"Element" => 1,
"Node" => 1,
"Text" => 1,
"Touch" => 1,
"TouchList" => 1
);
sub GenerateHeader
{
my $object = shift;
my $dataNode = shift;
my $interfaceName = $dataNode->name;
my $className = "JS$interfaceName";
my $implClassName = $interfaceName;
my @ancestorInterfaceNames = ();
my %structureFlags = ();
# We only support multiple parents with SVG (for now).
if (@{$dataNode->parents} > 1) {
die "A class can't have more than one parent" unless $interfaceName =~ /SVG/;
$codeGenerator->AddMethodsConstantsAndAttributesFromParentClasses($dataNode, \@ancestorInterfaceNames);
}
my $hasLegacyParent = $dataNode->extendedAttributes->{"LegacyParent"};
my $hasRealParent = @{$dataNode->parents} > 0;
my $hasParent = $hasLegacyParent || $hasRealParent;
my $parentClassName = GetParentClassName($dataNode);
my $eventTarget = $dataNode->extendedAttributes->{"EventTarget"};
my $needsMarkChildren = $dataNode->extendedAttributes->{"CustomMarkFunction"} || $dataNode->extendedAttributes->{"EventTarget"};
# - Add default header template and header protection
push(@headerContentHeader, GenerateHeaderContentHeader($dataNode));
if ($hasParent) {
$headerIncludes{"$parentClassName.h"} = 1;
} else {
$headerIncludes{"JSDOMBinding.h"} = 1;
$headerIncludes{"<runtime/JSGlobalObject.h>"} = 1;
$headerIncludes{"<runtime/ObjectPrototype.h>"} = 1;
}
if ($dataNode->extendedAttributes->{"CustomCall"}) {
$headerIncludes{"<runtime/CallData.h>"} = 1;
}
if ($dataNode->extendedAttributes->{"InlineGetOwnPropertySlot"}) {
$headerIncludes{"<runtime/Lookup.h>"} = 1;
$headerIncludes{"<wtf/AlwaysInline.h>"} = 1;
}
if ($hasParent && $dataNode->extendedAttributes->{"GenerateNativeConverter"}) {
$headerIncludes{"$implClassName.h"} = 1;
}
$headerIncludes{"<runtime/JSObjectWithGlobalObject.h>"} = 1;
$headerIncludes{"SVGElement.h"} = 1 if $className =~ /^JSSVG/;
my $implType = $implClassName;
my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($implType);
$implType = $svgNativeType if $svgNativeType;
my $svgPropertyOrListPropertyType;
$svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType;
$svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType;
my $numConstants = @{$dataNode->constants};
my $numAttributes = @{$dataNode->attributes};
my $numFunctions = @{$dataNode->functions};
push(@headerContent, "\nnamespace WebCore {\n\n");
if ($codeGenerator->IsSVGAnimatedType($implClassName)) {
$headerIncludes{"$implClassName.h"} = 1;
} else {
# Implementation class forward declaration
AddClassForwardIfNeeded($implClassName) unless $svgPropertyOrListPropertyType;
}
AddClassForwardIfNeeded("JSDOMWindowShell") if $interfaceName eq "DOMWindow";
# Class declaration
push(@headerContent, "class $className : public $parentClassName {\n");
push(@headerContent, " typedef $parentClassName Base;\n");
push(@headerContent, "public:\n");
# Constructor
if ($interfaceName eq "DOMWindow") {
push(@headerContent, " $className(JSC::JSGlobalData&, JSC::Structure*, PassRefPtr<$implType>, JSDOMWindowShell*);\n");
} elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
push(@headerContent, " $className(JSC::JSGlobalData&, JSC::Structure*, PassRefPtr<$implType>);\n");
} else {
push(@headerContent, " $className(JSC::Structure*, JSDOMGlobalObject*, PassRefPtr<$implType>);\n");
}
# Prototype
push(@headerContent, " static JSC::JSObject* createPrototype(JSC::ExecState*, JSC::JSGlobalObject*);\n") unless ($dataNode->extendedAttributes->{"ExtendsDOMGlobalObject"});
$headerTrailingIncludes{"${className}Custom.h"} = 1 if $dataNode->extendedAttributes->{"CustomHeader"};
$implIncludes{"${className}Custom.h"} = 1 if !$dataNode->extendedAttributes->{"CustomHeader"} && ($dataNode->extendedAttributes->{"CustomPutFunction"} || $dataNode->extendedAttributes->{"DelegatingPutFunction"});
my $hasGetter = $numAttributes > 0
|| !($dataNode->extendedAttributes->{"OmitConstructor"}
|| $dataNode->extendedAttributes->{"CustomConstructor"})
|| $dataNode->extendedAttributes->{"HasIndexGetter"}
|| $dataNode->extendedAttributes->{"HasCustomIndexGetter"}
|| $dataNode->extendedAttributes->{"HasNumericIndexGetter"}
|| $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}
|| $dataNode->extendedAttributes->{"DelegatingGetOwnPropertySlot"}
|| $dataNode->extendedAttributes->{"HasNameGetter"}
|| $dataNode->extendedAttributes->{"HasOverridingNameGetter"};
# Getters
if ($hasGetter) {
push(@headerContent, " virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertySlot&);\n");
push(@headerContent, " virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertyDescriptor&);\n");
push(@headerContent, " virtual bool getOwnPropertySlot(JSC::ExecState*, unsigned propertyName, JSC::PropertySlot&);\n") if ($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) && !$dataNode->extendedAttributes->{"HasOverridingNameGetter"};
push(@headerContent, " bool getOwnPropertySlotDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n") if $dataNode->extendedAttributes->{"DelegatingGetOwnPropertySlot"};
push(@headerContent, " bool getOwnPropertyDescriptorDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);\n") if $dataNode->extendedAttributes->{"DelegatingGetOwnPropertySlot"};
$structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;
}
# Check if we have any writable properties
my $hasReadWriteProperties = 0;
foreach (@{$dataNode->attributes}) {
if ($_->type !~ /^readonly\ attribute$/) {
$hasReadWriteProperties = 1;
}
}
my $hasSetter = $hasReadWriteProperties
|| $dataNode->extendedAttributes->{"CustomPutFunction"}
|| $dataNode->extendedAttributes->{"DelegatingPutFunction"}
|| $dataNode->extendedAttributes->{"HasCustomIndexSetter"};
# Getters
if ($hasSetter) {
push(@headerContent, " virtual void put(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
push(@headerContent, " virtual void put(JSC::ExecState*, unsigned propertyName, JSC::JSValue);\n") if $dataNode->extendedAttributes->{"HasCustomIndexSetter"};
push(@headerContent, " bool putDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::JSValue, JSC::PutPropertySlot&);\n") if $dataNode->extendedAttributes->{"DelegatingPutFunction"};
}
# Class info
push(@headerContent, " static const JSC::ClassInfo s_info;\n\n");
# Structure ID
if ($interfaceName eq "DOMWindow") {
$structureFlags{"JSC::ImplementsHasInstance"} = 1;
$structureFlags{"JSC::NeedsThisConversion"} = 1;
}
push(@headerContent,
" static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)\n" .
" {\n" .
" return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);\n" .
" }\n\n");
# visit function
if ($needsMarkChildren) {
push(@headerContent, " virtual void visitChildren(JSC::SlotVisitor&);\n\n");
$structureFlags{"JSC::OverridesVisitChildren"} = 1;
}
# Custom pushEventHandlerScope function
push(@headerContent, " virtual JSC::ScopeChainNode* pushEventHandlerScope(JSC::ExecState*, JSC::ScopeChainNode*) const;\n\n") if $dataNode->extendedAttributes->{"CustomPushEventHandlerScope"};
# Custom call functions
push(@headerContent, " virtual JSC::CallType getCallData(JSC::CallData&);\n\n") if $dataNode->extendedAttributes->{"CustomCall"};
# Custom deleteProperty function
push(@headerContent, " virtual bool deleteProperty(JSC::ExecState*, const JSC::Identifier&);\n") if $dataNode->extendedAttributes->{"CustomDeleteProperty"};
# Custom getPropertyNames function exists on DOMWindow
if ($interfaceName eq "DOMWindow") {
push(@headerContent, " virtual void getPropertyNames(JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode mode = JSC::ExcludeDontEnumProperties);\n");
$structureFlags{"JSC::OverridesGetPropertyNames"} = 1;
}
# Custom defineProperty function exists on DOMWindow
push(@headerContent, " virtual bool defineOwnProperty(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::PropertyDescriptor&, bool shouldThrow);\n") if $interfaceName eq "DOMWindow";
# Custom getOwnPropertyNames function
if ($dataNode->extendedAttributes->{"CustomGetPropertyNames"} || $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@headerContent, " virtual void getOwnPropertyNames(JSC::ExecState*, JSC::PropertyNameArray&, JSC::EnumerationMode mode = JSC::ExcludeDontEnumProperties);\n");
$structureFlags{"JSC::OverridesGetPropertyNames"} = 1;
}
# Custom defineGetter function
push(@headerContent, " virtual void defineGetter(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSObject* getterFunction, unsigned attributes);\n") if $dataNode->extendedAttributes->{"CustomDefineGetter"};
# Custom defineSetter function
push(@headerContent, " virtual void defineSetter(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSObject* setterFunction, unsigned attributes);\n") if $dataNode->extendedAttributes->{"CustomDefineSetter"};
# Custom lookupGetter function
push(@headerContent, " virtual JSC::JSValue lookupGetter(JSC::ExecState*, const JSC::Identifier& propertyName);\n") if $dataNode->extendedAttributes->{"CustomLookupGetter"};
# Custom lookupSetter function
push(@headerContent, " virtual JSC::JSValue lookupSetter(JSC::ExecState*, const JSC::Identifier& propertyName);\n") if $dataNode->extendedAttributes->{"CustomLookupSetter"};
# Override toBoolean to return false for objects that want to 'MasqueradesAsUndefined'.
if ($dataNode->extendedAttributes->{"MasqueradesAsUndefined"}) {
push(@headerContent, " virtual bool toBoolean(JSC::ExecState*) const { return false; };\n");
$structureFlags{"JSC::MasqueradesAsUndefined"} = 1;
}
# Constructor object getter
push(@headerContent, " static JSC::JSValue getConstructor(JSC::ExecState*, JSC::JSGlobalObject*);\n") if (!($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"}));
my $numCustomFunctions = 0;
my $numCustomAttributes = 0;
# Attribute and function enums
if ($numAttributes > 0) {
foreach (@{$dataNode->attributes}) {
my $attribute = $_;
$numCustomAttributes++ if $attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCCustom"};
$numCustomAttributes++ if $attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCCustomGetter"};
$numCustomAttributes++ if $attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCCustomSetter"};
if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
push(@headerContent, " static const unsigned " . $attribute->signature->name . "Slot = $numCachedAttributes + Base::AnonymousSlotCount;\n");
$numCachedAttributes++;
}
}
}
if ($numCachedAttributes > 0) {
push(@headerContent, " using $parentClassName" . "::putAnonymousValue;\n");
push(@headerContent, " using $parentClassName" . "::getAnonymousValue;\n");
}
if ($numCustomAttributes > 0) {
push(@headerContent, "\n // Custom attributes\n");
foreach my $attribute (@{$dataNode->attributes}) {
if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCCustom"}) {
push(@headerContent, " JSC::JSValue " . $codeGenerator->WK_lcfirst($attribute->signature->name) . "(JSC::ExecState*) const;\n");
if ($attribute->type !~ /^readonly/) {
push(@headerContent, " void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState*, JSC::JSValue);\n");
}
} elsif ($attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCCustomGetter"}) {
push(@headerContent, " JSC::JSValue " . $codeGenerator->WK_lcfirst($attribute->signature->name) . "(JSC::ExecState*) const;\n");
} elsif ($attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCCustomSetter"}) {
if ($attribute->type !~ /^readonly/) {
push(@headerContent, " void set" . $codeGenerator->WK_ucfirst($attribute->signature->name) . "(JSC::ExecState*, JSC::JSValue);\n");
}
}
}
}
foreach my $function (@{$dataNode->functions}) {
$numCustomFunctions++ if $function->signature->extendedAttributes->{"Custom"} || $function->signature->extendedAttributes->{"JSCCustom"};
}
if ($numCustomFunctions > 0) {
push(@headerContent, "\n // Custom functions\n");
foreach my $function (@{$dataNode->functions}) {
if ($function->signature->extendedAttributes->{"Custom"} || $function->signature->extendedAttributes->{"JSCCustom"}) {
my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementationFunction"} || $codeGenerator->WK_lcfirst($function->signature->name);
push(@headerContent, " JSC::JSValue " . $functionImplementationName . "(JSC::ExecState*);\n");
}
}
}
if (!$hasParent) {
push(@headerContent, " $implType* impl() const { return m_impl.get(); }\n\n");
push(@headerContent, "private:\n");
push(@headerContent, " RefPtr<$implType> m_impl;\n");
} elsif ($dataNode->extendedAttributes->{"GenerateNativeConverter"}) {
push(@headerContent, " $implClassName* impl() const\n");
push(@headerContent, " {\n");
push(@headerContent, " return static_cast<$implClassName*>(Base::impl());\n");
push(@headerContent, " }\n");
}
# anonymous slots
if ($numCachedAttributes) {
push(@headerContent, "public:\n");
push(@headerContent, " static const unsigned AnonymousSlotCount = $numCachedAttributes + Base::AnonymousSlotCount;\n");
}
# structure flags
push(@headerContent, "protected:\n");
push(@headerContent, " static const unsigned StructureFlags = ");
foreach my $structureFlag (keys %structureFlags) {
push(@headerContent, $structureFlag . " | ");
}
push(@headerContent, "Base::StructureFlags;\n");
# Index getter
if ($dataNode->extendedAttributes->{"HasIndexGetter"}) {
push(@headerContent, " static JSC::JSValue indexGetter(JSC::ExecState*, JSC::JSValue, unsigned);\n");
}
if ($dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@headerContent, " JSC::JSValue getByIndex(JSC::ExecState*, unsigned index);\n");
}
# Index setter
if ($dataNode->extendedAttributes->{"HasCustomIndexSetter"}) {
push(@headerContent, " void indexSetter(JSC::ExecState*, unsigned index, JSC::JSValue);\n");
}
# Name getter
if ($dataNode->extendedAttributes->{"HasNameGetter"} || $dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
push(@headerContent, "private:\n");
push(@headerContent, " static bool canGetItemsForName(JSC::ExecState*, $implClassName*, const JSC::Identifier&);\n");
push(@headerContent, " static JSC::JSValue nameGetter(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
}
push(@headerContent, "};\n\n");
if ($dataNode->extendedAttributes->{"InlineGetOwnPropertySlot"} && !$dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) {
push(@headerContent, "ALWAYS_INLINE bool ${className}::getOwnPropertySlot(JSC::ExecState* exec, const JSC::Identifier& propertyName, JSC::PropertySlot& slot)\n");
push(@headerContent, "{\n");
push(@headerContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 1));
push(@headerContent, "}\n\n");
push(@headerContent, "ALWAYS_INLINE bool ${className}::getOwnPropertyDescriptor(JSC::ExecState* exec, const JSC::Identifier& propertyName, JSC::PropertyDescriptor& descriptor)\n");
push(@headerContent, "{\n");
push(@headerContent, GenerateGetOwnPropertyDescriptorBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 1));
push(@headerContent, "}\n\n");
}
if ($dataNode->extendedAttributes->{"GenerateIsReachable"} ||
$dataNode->extendedAttributes->{"CustomIsReachable"} ||
$dataNode->extendedAttributes->{"CustomFinalize"} ||
$dataNode->extendedAttributes->{"ActiveDOMObject"}) {
push(@headerContent, "class JS${implType}Owner : public JSC::WeakHandleOwner {\n");
push(@headerContent, " virtual bool isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown>, void* context, JSC::SlotVisitor&);\n");
push(@headerContent, " virtual void finalize(JSC::Handle<JSC::Unknown>, void* context);\n");
push(@headerContent, "};\n");
push(@headerContent, "\n");
push(@headerContent, "inline JSC::WeakHandleOwner* wrapperOwner(DOMWrapperWorld*, $implType*)\n");
push(@headerContent, "{\n");
push(@headerContent, " DEFINE_STATIC_LOCAL(JS${implType}Owner, js${implType}Owner, ());\n");
push(@headerContent, " return &js${implType}Owner;\n");
push(@headerContent, "}\n");
push(@headerContent, "\n");
push(@headerContent, "inline void* wrapperContext(DOMWrapperWorld* world, $implType*)\n");
push(@headerContent, "{\n");
push(@headerContent, " return world;\n");
push(@headerContent, "}\n");
push(@headerContent, "\n");
}
if (!$hasParent || $dataNode->extendedAttributes->{"GenerateToJS"} || $dataNode->extendedAttributes->{"CustomToJS"}) {
push(@headerContent, "JSC::JSValue toJS(JSC::ExecState*, JSDOMGlobalObject*, $implType*);\n");
}
if (!$hasParent || $dataNode->extendedAttributes->{"GenerateNativeConverter"}) {
if ($interfaceName eq "NodeFilter") {
push(@headerContent, "PassRefPtr<NodeFilter> toNodeFilter(JSC::JSGlobalData&, JSC::JSValue);\n");
} else {
push(@headerContent, "$implType* to${interfaceName}(JSC::JSValue);\n");
}
}
if ($usesToJSNewlyCreated{$interfaceName}) {
push(@headerContent, "JSC::JSValue toJSNewlyCreated(JSC::ExecState*, JSDOMGlobalObject*, $interfaceName*);\n");
}
push(@headerContent, "\n");
# Add prototype declaration.
%structureFlags = ();
push(@headerContent, "class ${className}Prototype : public JSC::JSObjectWithGlobalObject {\n");
push(@headerContent, " typedef JSC::JSObjectWithGlobalObject Base;\n");
push(@headerContent, "public:\n");
if ($interfaceName eq "DOMWindow") {
push(@headerContent, " void* operator new(size_t);\n");
} elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
push(@headerContent, " void* operator new(size_t, JSC::JSGlobalData*);\n");
} else {
push(@headerContent, " static JSC::JSObject* self(JSC::ExecState*, JSC::JSGlobalObject*);\n");
}
push(@headerContent, " static const JSC::ClassInfo s_info;\n");
if ($numFunctions > 0 || $numConstants > 0 || $dataNode->extendedAttributes->{"DelegatingPrototypeGetOwnPropertySlot"}) {
push(@headerContent, " virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n");
push(@headerContent, " virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);\n");
push(@headerContent, " bool getOwnPropertySlotDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n") if $dataNode->extendedAttributes->{"DelegatingPrototypeGetOwnPropertySlot"};
push(@headerContent, " bool getOwnPropertyDescriptorDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);\n") if $dataNode->extendedAttributes->{"DelegatingPrototypeGetOwnPropertySlot"};
$structureFlags{"JSC::OverridesGetOwnPropertySlot"} = 1;
}
if ($dataNode->extendedAttributes->{"CustomMarkFunction"} or $needsMarkChildren) {
$structureFlags{"JSC::OverridesVisitChildren"} = 1;
}
push(@headerContent,
" static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)\n" .
" {\n" .
" return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);\n" .
" }\n");
if ($dataNode->extendedAttributes->{"DelegatingPrototypePutFunction"}) {
push(@headerContent, " virtual void put(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSValue, JSC::PutPropertySlot&);\n");
push(@headerContent, " bool putDelegate(JSC::ExecState*, const JSC::Identifier&, JSC::JSValue, JSC::PutPropertySlot&);\n");
}
# Custom defineGetter function
push(@headerContent, " virtual void defineGetter(JSC::ExecState*, const JSC::Identifier& propertyName, JSC::JSObject* getterFunction, unsigned attributes);\n") if $dataNode->extendedAttributes->{"CustomPrototypeDefineGetter"};
push(@headerContent, " ${className}Prototype(JSC::JSGlobalData& globalData, JSC::JSGlobalObject* globalObject, JSC::Structure* structure) : JSC::JSObjectWithGlobalObject(globalData, globalObject, structure) { }\n");
# structure flags
push(@headerContent, "protected:\n");
push(@headerContent, " static const unsigned StructureFlags = ");
foreach my $structureFlag (keys %structureFlags) {
push(@headerContent, $structureFlag . " | ");
}
push(@headerContent, "Base::StructureFlags;\n");
push(@headerContent, "};\n\n");
# Conditionally emit the constructor object's declaration
if ($dataNode->extendedAttributes->{"CustomConstructFunction"}) {
GenerateConstructorDeclaration(\@headerContent, $className, $dataNode);
}
if ($numFunctions > 0) {
push(@headerContent,"// Functions\n\n");
foreach my $function (@{$dataNode->functions}) {
next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
my $functionName = $codeGenerator->WK_lcfirst($className) . "PrototypeFunction" . $codeGenerator->WK_ucfirst($function->signature->name);
push(@headerContent, "JSC::EncodedJSValue JSC_HOST_CALL ${functionName}(JSC::ExecState*);\n");
}
}
if ($numAttributes > 0 || !($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"})) {
push(@headerContent,"// Attributes\n\n");
foreach my $attribute (@{$dataNode->attributes}) {
my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
unless ($attribute->type =~ /readonly/) {
my $setter = "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
push(@headerContent, "void ${setter}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue);\n");
}
}
if (!($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"})) {
my $getter = "js" . $interfaceName . "Constructor";
push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
}
if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
my $constructorFunctionName = "setJS" . $interfaceName . "Constructor";
push(@headerContent, "void ${constructorFunctionName}(JSC::ExecState*, JSC::JSObject*, JSC::JSValue);\n");
}
}
if ($numConstants > 0) {
push(@headerContent,"// Constants\n\n");
foreach my $constant (@{$dataNode->constants}) {
my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
push(@headerContent, "JSC::JSValue ${getter}(JSC::ExecState*, JSC::JSValue, const JSC::Identifier&);\n");
}
}
my $conditionalString = GenerateConditionalString($dataNode);
push(@headerContent, "\n} // namespace WebCore\n\n");
push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditionalString;
push(@headerContent, "#endif\n");
# - Generate dependencies.
if ($writeDependencies && @ancestorInterfaceNames) {
push(@depsContent, "$className.h : ", join(" ", map { "$_.idl" } @ancestorInterfaceNames), "\n");
push(@depsContent, map { "$_.idl :\n" } @ancestorInterfaceNames);
}
}
sub GenerateAttributesHashTable($$)
{
my ($object, $dataNode) = @_;
# FIXME: These should be functions on $dataNode.
my $interfaceName = $dataNode->name;
my $className = "JS$interfaceName";
# - Add all attributes in a hashtable definition
my $numAttributes = @{$dataNode->attributes};
$numAttributes++ if (!($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"}));
return 0 if !$numAttributes;
my $hashSize = $numAttributes;
my $hashName = $className . "Table";
my @hashKeys = ();
my @hashSpecials = ();
my @hashValue1 = ();
my @hashValue2 = ();
my %conditionals = ();
my @entries = ();
foreach my $attribute (@{$dataNode->attributes}) {
my $name = $attribute->signature->name;
push(@hashKeys, $name);
my @specials = ();
push(@specials, "DontDelete") unless $attribute->signature->extendedAttributes->{"Deletable"};
push(@specials, "DontEnum") if $attribute->signature->extendedAttributes->{"DontEnum"};
push(@specials, "ReadOnly") if $attribute->type =~ /readonly/;
my $special = (@specials > 0) ? join(" | ", @specials) : "0";
push(@hashSpecials, $special);
my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
push(@hashValue1, $getter);
if ($attribute->type =~ /readonly/) {
push(@hashValue2, "0");
} else {
my $setter = "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
push(@hashValue2, $setter);
}
my $conditional = $attribute->signature->extendedAttributes->{"Conditional"};
if ($conditional) {
$conditionals{$name} = $conditional;
}
}
if (!($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"})) {
push(@hashKeys, "constructor");
my $getter = "js" . $interfaceName . "Constructor";
push(@hashValue1, $getter);
if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
my $setter = "setJS" . $interfaceName . "Constructor";
push(@hashValue2, $setter);
push(@hashSpecials, "DontEnum | DontDelete");
} else {
push(@hashValue2, "0");
push(@hashSpecials, "DontEnum | ReadOnly");
}
}
$object->GenerateHashTable($hashName, $hashSize,
\@hashKeys, \@hashSpecials,
\@hashValue1, \@hashValue2,
\%conditionals);
return $numAttributes;
}
sub GenerateParametersCheckExpression
{
my $numParameters = shift;
my $function = shift;
my @andExpression = ();
push(@andExpression, "exec->argumentCount() == $numParameters");
my $parameterIndex = 0;
foreach $parameter (@{$function->parameters}) {
last if $parameterIndex >= $numParameters;
my $value = "exec->argument($parameterIndex)";
my $type = $codeGenerator->StripModule($parameter->type);
# Only DOMString or wrapper types are checked.
# For DOMString, Null, Undefined and any Object are accepted too, as
# these are acceptable values for a DOMString argument (any Object can
# be converted to a string via .toString).
if ($codeGenerator->IsStringType($type)) {
push(@andExpression, "(${value}.isNull() || ${value}.isUndefined() || ${value}.isString() || ${value}.isObject())");
} elsif ($parameter->extendedAttributes->{"Callback"}) {
# For Callbacks only checks if the value is null or object.
push(@andExpression, "(${value}.isNull() || ${value}.isObject())");
} elsif (!IsNativeType($type)) {
push(@andExpression, "(${value}.isNull() || (${value}.isObject() && asObject(${value})->inherits(&JS${type}::s_info)))");
}
$parameterIndex++;
}
my $res = join(" && ", @andExpression);
$res = "($res)" if @andExpression > 1;
return $res;
}
sub GenerateFunctionParametersCheck
{
my $function = shift;
my @orExpression = ();
my $numParameters = 0;
foreach $parameter (@{$function->parameters}) {
if ($parameter->extendedAttributes->{"Optional"}) {
push(@orExpression, GenerateParametersCheckExpression($numParameters, $function));
}
$numParameters++;
}
push(@orExpression, GenerateParametersCheckExpression($numParameters, $function));
return join(" || ", @orExpression);
}
sub GenerateOverloadedPrototypeFunction
{
my $function = shift;
my $dataNode = shift;
my $implClassName = shift;
# Generate code for choosing the correct overload to call. Overloads are
# chosen based on the total number of arguments passed and the type of
# values passed in non-primitive argument slots. When more than a single
# overload is applicable, precedence is given according to the order of
# declaration in the IDL.
my $functionName = "js${implClassName}PrototypeFunction" . $codeGenerator->WK_ucfirst($function->signature->name);
push(@implContent, "EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)\n");
push(@implContent, <<END);
{
END
foreach my $overload (@{$function->{overloads}}) {
my $parametersCheck = GenerateFunctionParametersCheck($overload);
push(@implContent, " if ($parametersCheck)\n");
push(@implContent, " return ${functionName}$overload->{overloadIndex}(exec);\n");
}
push(@implContent, <<END);
return throwVMTypeError(exec);
}
END
}
sub GenerateImplementation
{
my ($object, $dataNode) = @_;
my $interfaceName = $dataNode->name;
my $className = "JS$interfaceName";
my $implClassName = $interfaceName;
my $hasLegacyParent = $dataNode->extendedAttributes->{"LegacyParent"};
my $hasRealParent = @{$dataNode->parents} > 0;
my $hasParent = $hasLegacyParent || $hasRealParent;
my $parentClassName = GetParentClassName($dataNode);
my $visibleClassName = GetVisibleClassName($interfaceName);
my $eventTarget = $dataNode->extendedAttributes->{"EventTarget"};
my $needsMarkChildren = $dataNode->extendedAttributes->{"CustomMarkFunction"} || $dataNode->extendedAttributes->{"EventTarget"};
# - Add default header template
push(@implContentHeader, GenerateImplementationContentHeader($dataNode));
AddIncludesForSVGAnimatedType($interfaceName) if $className =~ /^JSSVGAnimated/;
$implIncludes{"<wtf/GetPtr.h>"} = 1;
$implIncludes{"<runtime/PropertyNameArray.h>"} = 1 if $dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"};
AddIncludesForType($interfaceName);
@implContent = ();
push(@implContent, "\nusing namespace JSC;\n\n");
push(@implContent, "namespace WebCore {\n\n");
push(@implContent, "ASSERT_CLASS_FITS_IN_CELL($className);\n\n");
my $numAttributes = GenerateAttributesHashTable($object, $dataNode);
my $numConstants = @{$dataNode->constants};
my $numFunctions = @{$dataNode->functions};
# - Add all constants
if (!($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"})) {
$hashSize = $numConstants;
$hashName = $className . "ConstructorTable";
@hashKeys = ();
@hashValue1 = ();
@hashValue2 = ();
@hashSpecials = ();
# FIXME: we should not need a function for every constant.
foreach my $constant (@{$dataNode->constants}) {
push(@hashKeys, $constant->name);
my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
push(@hashValue1, $getter);
push(@hashValue2, "0");
push(@hashSpecials, "DontDelete | ReadOnly");
}
$object->GenerateHashTable($hashName, $hashSize,
\@hashKeys, \@hashSpecials,
\@hashValue1, \@hashValue2);
push(@implContent, $codeGenerator->GenerateCompileTimeCheckForEnumsIfNeeded($dataNode));
my $protoClassName = "${className}Prototype";
GenerateConstructorDeclaration(\@implContent, $className, $dataNode) unless $dataNode->extendedAttributes->{"CustomConstructFunction"};
GenerateConstructorDefinition(\@implContent, $className, $protoClassName, $interfaceName, $visibleClassName, $dataNode);
}
# - Add functions and constants to a hashtable definition
$hashSize = $numFunctions + $numConstants;
$hashName = $className . "PrototypeTable";
@hashKeys = ();
@hashValue1 = ();
@hashValue2 = ();
@hashSpecials = ();
# FIXME: we should not need a function for every constant.
foreach my $constant (@{$dataNode->constants}) {
push(@hashKeys, $constant->name);
my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
push(@hashValue1, $getter);
push(@hashValue2, "0");
push(@hashSpecials, "DontDelete | ReadOnly");
}
foreach my $function (@{$dataNode->functions}) {
next if $function->{overloadIndex} && $function->{overloadIndex} > 1;
my $name = $function->signature->name;
push(@hashKeys, $name);
my $value = $codeGenerator->WK_lcfirst($className) . "PrototypeFunction" . $codeGenerator->WK_ucfirst($name);
push(@hashValue1, $value);
my $numParameters = @{$function->parameters};
push(@hashValue2, $numParameters);
my @specials = ();
push(@specials, "DontDelete") unless $function->signature->extendedAttributes->{"Deletable"};
push(@specials, "DontEnum") if $function->signature->extendedAttributes->{"DontEnum"};
push(@specials, "Function");
my $special = (@specials > 0) ? join(" | ", @specials) : "0";
push(@hashSpecials, $special);
}
$object->GenerateHashTable($hashName, $hashSize,
\@hashKeys, \@hashSpecials,
\@hashValue1, \@hashValue2);
if ($dataNode->extendedAttributes->{"NoStaticTables"}) {
push(@implContent, "static const HashTable* get${className}PrototypeTable(ExecState* exec)\n");
push(@implContent, "{\n");
push(@implContent, " return getHashTableForGlobalData(exec->globalData(), &${className}PrototypeTable);\n");
push(@implContent, "}\n\n");
push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleClassName}Prototype\", &JSC::JSObjectWithGlobalObject::s_info, 0, get${className}PrototypeTable };\n\n");
} else {
push(@implContent, "const ClassInfo ${className}Prototype::s_info = { \"${visibleClassName}Prototype\", &JSC::JSObjectWithGlobalObject::s_info, &${className}PrototypeTable, 0 };\n\n");
}
if ($interfaceName eq "DOMWindow") {
push(@implContent, "void* ${className}Prototype::operator new(size_t size)\n");
push(@implContent, "{\n");
push(@implContent, " return JSDOMWindow::commonJSGlobalData()->heap.allocate(size);\n");
push(@implContent, "}\n\n");
} elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
push(@implContent, "void* ${className}Prototype::operator new(size_t size, JSGlobalData* globalData)\n");
push(@implContent, "{\n");
push(@implContent, " return globalData->heap.allocate(size);\n");
push(@implContent, "}\n\n");
} else {
push(@implContent, "JSObject* ${className}Prototype::self(ExecState* exec, JSGlobalObject* globalObject)\n");
push(@implContent, "{\n");
push(@implContent, " return getDOMPrototype<${className}>(exec, globalObject);\n");
push(@implContent, "}\n\n");
}
if ($numConstants > 0 || $numFunctions > 0 || $dataNode->extendedAttributes->{"DelegatingPrototypeGetOwnPropertySlot"}) {
push(@implContent, "bool ${className}Prototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n");
push(@implContent, "{\n");
if ($dataNode->extendedAttributes->{"DelegatingPrototypeGetOwnPropertySlot"}) {
push(@implContent, " if (getOwnPropertySlotDelegate(exec, propertyName, slot))\n");
push(@implContent, " return true;\n");
}
if ($numConstants eq 0 && $numFunctions eq 0) {
push(@implContent, " return Base::getOwnPropertySlot(exec, propertyName, slot);\n");
} elsif ($numConstants eq 0) {
push(@implContent, " return getStaticFunctionSlot<JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n");
} elsif ($numFunctions eq 0) {
push(@implContent, " return getStaticValueSlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n");
} else {
push(@implContent, " return getStaticPropertySlot<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, slot);\n");
}
push(@implContent, "}\n\n");
push(@implContent, "bool ${className}Prototype::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)\n");
push(@implContent, "{\n");
if ($dataNode->extendedAttributes->{"DelegatingPrototypeGetOwnPropertySlot"}) {
push(@implContent, " if (getOwnPropertyDescriptorDelegate(exec, propertyName, descriptor))\n");
push(@implContent, " return true;\n");
}
if ($numConstants eq 0 && $numFunctions eq 0) {
push(@implContent, " return Base::getOwnPropertyDescriptor(exec, propertyName, descriptor);\n");
} elsif ($numConstants eq 0) {
push(@implContent, " return getStaticFunctionDescriptor<JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, descriptor);\n");
} elsif ($numFunctions eq 0) {
push(@implContent, " return getStaticValueDescriptor<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, descriptor);\n");
} else {
push(@implContent, " return getStaticPropertyDescriptor<${className}Prototype, JSObject>(exec, " . prototypeHashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, propertyName, descriptor);\n");
}
push(@implContent, "}\n\n");
}
if ($dataNode->extendedAttributes->{"DelegatingPrototypePutFunction"}) {
push(@implContent, "void ${className}Prototype::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)\n");
push(@implContent, "{\n");
push(@implContent, " if (putDelegate(exec, propertyName, value, slot))\n");
push(@implContent, " return;\n");
push(@implContent, " Base::put(exec, propertyName, value, slot);\n");
push(@implContent, "}\n\n");
}
# - Initialize static ClassInfo object
if ($numAttributes > 0 && $dataNode->extendedAttributes->{"NoStaticTables"}) {
push(@implContent, "static const HashTable* get${className}Table(ExecState* exec)\n");
push(@implContent, "{\n");
push(@implContent, " return getHashTableForGlobalData(exec->globalData(), &${className}Table);\n");
push(@implContent, "}\n\n");
}
push(@implContent, "const ClassInfo $className" . "::s_info = { \"${visibleClassName}\", &" . $parentClassName . "::s_info, ");
if ($numAttributes > 0 && !$dataNode->extendedAttributes->{"NoStaticTables"}) {
push(@implContent, "&${className}Table");
} else {
push(@implContent, "0");
}
if ($numAttributes > 0 && $dataNode->extendedAttributes->{"NoStaticTables"}) {
push(@implContent, ", get${className}Table ");
} else {
push(@implContent, ", 0 ");
}
push(@implContent, "};\n\n");
my $implType = $implClassName;
my ($svgPropertyType, $svgListPropertyType, $svgNativeType) = GetSVGPropertyTypes($implType);
$implType = $svgNativeType if $svgNativeType;
my $svgPropertyOrListPropertyType;
$svgPropertyOrListPropertyType = $svgPropertyType if $svgPropertyType;
$svgPropertyOrListPropertyType = $svgListPropertyType if $svgListPropertyType;
# Constructor
if ($interfaceName eq "DOMWindow") {
AddIncludesForType("JSDOMWindowShell");
push(@implContent, "${className}::$className(JSGlobalData& globalData, Structure* structure, PassRefPtr<$implType> impl, JSDOMWindowShell* shell)\n");
push(@implContent, " : $parentClassName(globalData, structure, impl, shell)\n");
} elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
AddIncludesForType($interfaceName);
push(@implContent, "${className}::$className(JSGlobalData& globalData, Structure* structure, PassRefPtr<$implType> impl)\n");
push(@implContent, " : $parentClassName(globalData, structure, impl)\n");
} else {
push(@implContent, "${className}::$className(Structure* structure, JSDOMGlobalObject* globalObject, PassRefPtr<$implType> impl)\n");
if ($hasParent) {
push(@implContent, " : $parentClassName(structure, globalObject, impl)\n");
} else {
push(@implContent, " : $parentClassName(structure, globalObject)\n");
push(@implContent, " , m_impl(impl)\n");
}
}
push(@implContent, "{\n");
push(@implContent, " ASSERT(inherits(&s_info));\n");
if ($numCachedAttributes > 0) {
push(@implContent, " for (unsigned i = Base::AnonymousSlotCount; i < AnonymousSlotCount; i++)\n");
push(@implContent, " putAnonymousValue(globalObject->globalData(), i, JSValue());\n");
}
push(@implContent, "}\n\n");
if ($needsMarkChildren && !$dataNode->extendedAttributes->{"CustomMarkFunction"}) {
push(@implContent, "void ${className}::visitChildren(SlotVisitor& visitor)\n");
push(@implContent, "{\n");
push(@implContent, " Base::visitChildren(visitor);\n");
push(@implContent, " impl()->visitJSEventListeners(visitor);\n");
push(@implContent, "}\n\n");
}
if (!$dataNode->extendedAttributes->{"ExtendsDOMGlobalObject"}) {
push(@implContent, "JSObject* ${className}::createPrototype(ExecState* exec, JSGlobalObject* globalObject)\n");
push(@implContent, "{\n");
if ($hasParent && $parentClassName ne "JSC::DOMNodeFilter") {
push(@implContent, " return new (exec) ${className}Prototype(exec->globalData(), globalObject, ${className}Prototype::createStructure(exec->globalData(), ${parentClassName}Prototype::self(exec, globalObject)));\n");
} else {
push(@implContent, " return new (exec) ${className}Prototype(exec->globalData(), globalObject, ${className}Prototype::createStructure(globalObject->globalData(), globalObject->objectPrototype()));\n");
}
push(@implContent, "}\n\n");
}
my $hasGetter = $numAttributes > 0
|| !($dataNode->extendedAttributes->{"OmitConstructor"}
|| $dataNode->extendedAttributes->{"CustomConstructor"})
|| $dataNode->extendedAttributes->{"HasIndexGetter"}
|| $dataNode->extendedAttributes->{"HasCustomIndexGetter"}
|| $dataNode->extendedAttributes->{"HasNumericIndexGetter"}
|| $dataNode->extendedAttributes->{"DelegatingGetOwnPropertySlot"}
|| $dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}
|| $dataNode->extendedAttributes->{"HasNameGetter"}
|| $dataNode->extendedAttributes->{"HasOverridingNameGetter"};
# Attributes
if ($hasGetter) {
if (!$dataNode->extendedAttributes->{"InlineGetOwnPropertySlot"} && !$dataNode->extendedAttributes->{"CustomGetOwnPropertySlot"}) {
push(@implContent, "bool ${className}::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n");
push(@implContent, "{\n");
push(@implContent, GenerateGetOwnPropertySlotBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 0));
push(@implContent, "}\n\n");
push(@implContent, "bool ${className}::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)\n");
push(@implContent, "{\n");
push(@implContent, GenerateGetOwnPropertyDescriptorBody($dataNode, $interfaceName, $className, $implClassName, $numAttributes > 0, 0));
push(@implContent, "}\n\n");
}
if (($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"})
&& !$dataNode->extendedAttributes->{"HasOverridingNameGetter"}) {
push(@implContent, "bool ${className}::getOwnPropertySlot(ExecState* exec, unsigned propertyName, PropertySlot& slot)\n");
push(@implContent, "{\n");
push(@implContent, " if (propertyName < static_cast<$implClassName*>(impl())->length()) {\n");
if ($dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@implContent, " slot.setValue(getByIndex(exec, propertyName));\n");
} else {
push(@implContent, " slot.setCustomIndex(this, propertyName, indexGetter);\n");
}
push(@implContent, " return true;\n");
push(@implContent, " }\n");
push(@implContent, " return getOwnPropertySlot(exec, Identifier::from(exec, propertyName), slot);\n");
push(@implContent, "}\n\n");
}
if ($numAttributes > 0) {
foreach my $attribute (@{$dataNode->attributes}) {
my $name = $attribute->signature->name;
my $type = $codeGenerator->StripModule($attribute->signature->type);
my $getFunctionName = "js" . $interfaceName . $codeGenerator->WK_ucfirst($attribute->signature->name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
my $implGetterFunctionName = $codeGenerator->WK_lcfirst($name);
my $attributeConditionalString = GenerateConditionalString($attribute->signature);
push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString;
push(@implContent, "JSValue ${getFunctionName}(ExecState* exec, JSValue slotBase, const Identifier&)\n");
push(@implContent, "{\n");
push(@implContent, " ${className}* castedThis = static_cast<$className*>(asObject(slotBase));\n");
if ($dataNode->extendedAttributes->{"CheckDomainSecurity"} &&
!$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurity"} &&
!$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurityOnGet"}) {
push(@implContent, " if (!castedThis->allowsAccessFrom(exec))\n");
push(@implContent, " return jsUndefined();\n");
}
if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCCustom"} || $attribute->signature->extendedAttributes->{"CustomGetter"} || $attribute->signature->extendedAttributes->{"JSCCustomGetter"}) {
push(@implContent, " return castedThis->$implGetterFunctionName(exec);\n");
} elsif ($attribute->signature->extendedAttributes->{"CheckNodeSecurity"}) {
$implIncludes{"JSDOMBinding.h"} = 1;
push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(castedThis->impl());\n");
push(@implContent, " return checkNodeSecurity(exec, imp->$implGetterFunctionName()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, "imp->$implGetterFunctionName()", "castedThis") . " : jsUndefined();\n");
} elsif ($attribute->signature->extendedAttributes->{"CheckFrameSecurity"}) {
$implIncludes{"Document.h"} = 1;
$implIncludes{"JSDOMBinding.h"} = 1;
push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(castedThis->impl());\n");
push(@implContent, " return checkNodeSecurity(exec, imp->contentDocument()) ? " . NativeToJSValue($attribute->signature, 0, $implClassName, "imp->$implGetterFunctionName()", "castedThis") . " : jsUndefined();\n");
} elsif ($type eq "EventListener") {
$implIncludes{"EventListener.h"} = 1;
push(@implContent, " UNUSED_PARAM(exec);\n");
push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(castedThis->impl());\n");
push(@implContent, " if (EventListener* listener = imp->$implGetterFunctionName()) {\n");
push(@implContent, " if (const JSEventListener* jsListener = JSEventListener::cast(listener)) {\n");
if ($implClassName eq "Document" || $implClassName eq "WorkerContext" || $implClassName eq "SharedWorkerContext" || $implClassName eq "DedicatedWorkerContext") {
push(@implContent, " if (JSObject* jsFunction = jsListener->jsFunction(imp))\n");
} else {
push(@implContent, " if (JSObject* jsFunction = jsListener->jsFunction(imp->scriptExecutionContext()))\n");
}
push(@implContent, " return jsFunction;\n");
push(@implContent, " }\n");
push(@implContent, " }\n");
push(@implContent, " return jsNull();\n");
} elsif ($attribute->signature->type =~ /Constructor$/) {
my $constructorType = $codeGenerator->StripModule($attribute->signature->type);
$constructorType =~ s/Constructor$//;
# Constructor attribute is only used by DOMWindow.idl, so it's correct to pass castedThis as the global object
# Once JSDOMWrappers have a back-pointer to the globalObject we can pass castedThis->globalObject()
push(@implContent, " return JS" . $constructorType . "::getConstructor(exec, castedThis);\n");
} elsif (!@{$attribute->getterExceptions}) {
push(@implContent, " UNUSED_PARAM(exec);\n");
my $cacheIndex = 0;
if ($attribute->signature->extendedAttributes->{"CachedAttribute"}) {
$cacheIndex = $currentCachedAttribute;
$currentCachedAttribute++;
push(@implContent, " if (JSValue cachedValue = castedThis->getAnonymousValue(" . $className . "::" . $attribute->signature->name . "Slot))\n");
push(@implContent, " return cachedValue;\n");
}
if ($svgListPropertyType) {
push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "castedThis->impl()->$implGetterFunctionName()", "castedThis") . ";\n");
} elsif ($svgPropertyOrListPropertyType) {
push(@implContent, " $svgPropertyOrListPropertyType& imp = castedThis->impl()->propertyReference();\n");
if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber
push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "imp", "castedThis") . ";\n");
} else {
push(@implContent, " JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "imp.$implGetterFunctionName()", "castedThis") . ";\n");
}
} else {
my $getterExpression = "imp->" . $codeGenerator->GetterExpressionPrefix(\%implIncludes, $interfaceName, $attribute) . ")";
my $jsType = NativeToJSValue($attribute->signature, 0, $implClassName, $getterExpression, "castedThis");
push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(castedThis->impl());\n");
if ($codeGenerator->IsSVGAnimatedType($type)) {
push(@implContent, " RefPtr<$type> obj = $jsType;\n");
push(@implContent, " JSValue result = toJS(exec, castedThis->globalObject(), obj.get());\n");
} else {
push(@implContent, " JSValue result = $jsType;\n");
}
}
push(@implContent, " castedThis->putAnonymousValue(exec->globalData(), " . $className . "::" . $attribute->signature->name . "Slot, result);\n") if ($attribute->signature->extendedAttributes->{"CachedAttribute"});
push(@implContent, " return result;\n");
} else {
push(@implContent, " ExceptionCode ec = 0;\n");
if ($svgPropertyOrListPropertyType) {
push(@implContent, " $svgPropertyOrListPropertyType imp(*castedThis->impl());\n");
push(@implContent, " JSC::JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "imp.$implGetterFunctionName(ec)", "castedThis") . ";\n");
} else {
push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(castedThis->impl());\n");
push(@implContent, " JSC::JSValue result = " . NativeToJSValue($attribute->signature, 0, $implClassName, "imp->$implGetterFunctionName(ec)", "castedThis") . ";\n");
}
push(@implContent, " setDOMException(exec, ec);\n");
push(@implContent, " return result;\n");
}
push(@implContent, "}\n\n");
push(@implContent, "#endif\n") if $attributeConditionalString;
push(@implContent, "\n");
}
if (!($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"})) {
my $constructorFunctionName = "js" . $interfaceName . "Constructor";
push(@implContent, "JSValue ${constructorFunctionName}(ExecState* exec, JSValue slotBase, const Identifier&)\n");
push(@implContent, "{\n");
push(@implContent, " ${className}* domObject = static_cast<$className*>(asObject(slotBase));\n");
if ($dataNode->extendedAttributes->{"CheckDomainSecurity"}) {
push(@implContent, " if (!domObject->allowsAccessFrom(exec))\n");
push(@implContent, " return jsUndefined();\n");
}
push(@implContent, " return ${className}::getConstructor(exec, domObject->globalObject());\n");
push(@implContent, "}\n\n");
}
}
# Check if we have any writable attributes
my $hasReadWriteProperties = 0;
foreach my $attribute (@{$dataNode->attributes}) {
$hasReadWriteProperties = 1 if $attribute->type !~ /^readonly/;
}
my $hasSetter = $hasReadWriteProperties
|| $dataNode->extendedAttributes->{"DelegatingPutFunction"}
|| $dataNode->extendedAttributes->{"HasCustomIndexSetter"};
if ($hasSetter) {
if (!$dataNode->extendedAttributes->{"CustomPutFunction"}) {
push(@implContent, "void ${className}::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)\n");
push(@implContent, "{\n");
if ($dataNode->extendedAttributes->{"HasCustomIndexSetter"}) {
push(@implContent, " bool ok;\n");
push(@implContent, " unsigned index = propertyName.toUInt32(ok);\n");
push(@implContent, " if (ok) {\n");
push(@implContent, " indexSetter(exec, index, value);\n");
push(@implContent, " return;\n");
push(@implContent, " }\n");
}
if ($dataNode->extendedAttributes->{"DelegatingPutFunction"}) {
push(@implContent, " if (putDelegate(exec, propertyName, value, slot))\n");
push(@implContent, " return;\n");
}
if ($hasReadWriteProperties) {
push(@implContent, " lookupPut<$className, Base>(exec, propertyName, value, " . hashTableAccessor($dataNode->extendedAttributes->{"NoStaticTables"}, $className) . ", this, slot);\n");
} else {
push(@implContent, " Base::put(exec, propertyName, value, slot);\n");
}
push(@implContent, "}\n\n");
}
if ($dataNode->extendedAttributes->{"HasCustomIndexSetter"}) {
push(@implContent, "void ${className}::put(ExecState* exec, unsigned propertyName, JSValue value)\n");
push(@implContent, "{\n");
push(@implContent, " indexSetter(exec, propertyName, value);\n");
push(@implContent, " return;\n");
push(@implContent, "}\n\n");
}
if ($hasReadWriteProperties) {
foreach my $attribute (@{$dataNode->attributes}) {
if ($attribute->type !~ /^readonly/) {
my $name = $attribute->signature->name;
my $type = $codeGenerator->StripModule($attribute->signature->type);
my $putFunctionName = "setJS" . $interfaceName . $codeGenerator->WK_ucfirst($name) . ($attribute->signature->type =~ /Constructor$/ ? "Constructor" : "");
my $implSetterFunctionName = $codeGenerator->WK_ucfirst($name);
my $attributeConditionalString = GenerateConditionalString($attribute->signature);
push(@implContent, "#if ${attributeConditionalString}\n") if $attributeConditionalString;
push(@implContent, "void ${putFunctionName}(ExecState* exec, JSObject* thisObject, JSValue value)\n");
push(@implContent, "{\n");
if ($dataNode->extendedAttributes->{"CheckDomainSecurity"} && !$attribute->signature->extendedAttributes->{"DoNotCheckDomainSecurity"}) {
if ($interfaceName eq "DOMWindow") {
push(@implContent, " if (!static_cast<$className*>(thisObject)->allowsAccessFrom(exec))\n");
} else {
push(@implContent, " if (!allowsAccessFromFrame(exec, static_cast<$className*>(thisObject)->impl()->frame()))\n");
}
push(@implContent, " return;\n");
}
if ($attribute->signature->extendedAttributes->{"Custom"} || $attribute->signature->extendedAttributes->{"JSCCustom"} || $attribute->signature->extendedAttributes->{"CustomSetter"} || $attribute->signature->extendedAttributes->{"JSCCustomSetter"}) {
push(@implContent, " static_cast<$className*>(thisObject)->set$implSetterFunctionName(exec, value);\n");
} elsif ($type eq "EventListener") {
$implIncludes{"JSEventListener.h"} = 1;
push(@implContent, " UNUSED_PARAM(exec);\n");
push(@implContent, " ${className}* castedThis = static_cast<${className}*>(thisObject);\n");
my $windowEventListener = $attribute->signature->extendedAttributes->{"WindowEventListener"};
if ($windowEventListener) {
push(@implContent, " JSDOMGlobalObject* globalObject = castedThis->globalObject();\n");
}
push(@implContent, " $implClassName* imp = static_cast<$implClassName*>(castedThis->impl());\n");
if ((($interfaceName eq "DOMWindow") or ($interfaceName eq "WorkerContext")) and $name eq "onerror") {
$implIncludes{"JSErrorHandler.h"} = 1;
push(@implContent, " imp->set$implSetterFunctionName(createJSErrorHandler(exec, value, thisObject));\n");
} else {
push(@implContent, GenerateAttributeEventListenerCall($className, $implSetterFunctionName, $windowEventListener));
}
} elsif ($attribute->signature->type =~ /Constructor$/) {
my $constructorType = $attribute->signature->type;
$constructorType =~ s/Constructor$//;
if ($constructorType ne "DOMObject") {
$implIncludes{"JS" . $constructorType . ".h"} = 1;
}
push(@implContent, " // Shadowing a built-in constructor\n");
if ($interfaceName eq "DOMWindow" && $className eq "JSblah") {
push(@implContent, " static_cast<$className*>(thisObject)->putDirect(exec->globalData(), exec->propertyNames().constructor, value);\n");
} else {
push(@implContent, " static_cast<$className*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, \"$name\"), value);\n");
}
} elsif ($attribute->signature->extendedAttributes->{"Replaceable"}) {
push(@implContent, " // Shadowing a built-in object\n");
push(@implContent, " static_cast<$className*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, \"$name\"), value);\n");
} else {
push(@implContent, " $className* castedThis = static_cast<$className*>(thisObject);\n");
push(@implContent, " $implType* imp = static_cast<$implType*>(castedThis->impl());\n");
push(@implContent, " ExceptionCode ec = 0;\n") if @{$attribute->setterExceptions};
# If the "StrictTypeChecking" extended attribute is present, and the attribute's type is an
# interface type, then if the incoming value does not implement that interface, a TypeError
# is thrown rather than silently passing NULL to the C++ code.
# Per the Web IDL and ECMAScript specifications, incoming values can always be converted to
# both strings and numbers, so do not throw TypeError if the attribute is of these types.
if ($attribute->signature->extendedAttributes->{"StrictTypeChecking"}) {
$implIncludes{"<runtime/Error.h>"} = 1;
my $argType = $attribute->signature->type;
if (!IsNativeType($argType)) {
push(@implContent, " if (!value.isUndefinedOrNull() && !value.inherits(&JS${argType}::s_info)) {\n");
push(@implContent, " throwVMTypeError(exec);\n");
push(@implContent, " return;\n");
push(@implContent, " };\n");
}
}
my $nativeValue = JSValueToNative($attribute->signature, "value");
if ($svgPropertyOrListPropertyType) {
if ($svgPropertyType) {
push(@implContent, " if (imp->role() == AnimValRole) {\n");
push(@implContent, " setDOMException(exec, NO_MODIFICATION_ALLOWED_ERR);\n");
push(@implContent, " return;\n");
push(@implContent, " }\n");
}
push(@implContent, " $svgPropertyOrListPropertyType& podImp = imp->propertyReference();\n");
if ($svgPropertyOrListPropertyType eq "float") { # Special case for JSSVGNumber
push(@implContent, " podImp = $nativeValue;\n");
} else {
push(@implContent, " podImp.set$implSetterFunctionName($nativeValue");
push(@implContent, ", ec") if @{$attribute->setterExceptions};
push(@implContent, ");\n");
push(@implContent, " setDOMException(exec, ec);\n") if @{$attribute->setterExceptions};
}
if ($svgPropertyType) {
if (@{$attribute->setterExceptions}) {
push(@implContent, " if (!ec)\n");
push(@implContent, " imp->commitChange();\n");
} else {
push(@implContent, " imp->commitChange();\n");
}
}
} else {
my $setterExpressionPrefix = $codeGenerator->SetterExpressionPrefix(\%implIncludes, $interfaceName, $attribute);
push(@implContent, " imp->$setterExpressionPrefix$nativeValue");
push(@implContent, ", ec") if @{$attribute->setterExceptions};
push(@implContent, ");\n");
push(@implContent, " setDOMException(exec, ec);\n") if @{$attribute->setterExceptions};
}
}
push(@implContent, "}\n\n");
push(@implContent, "#endif\n") if $attributeConditionalString;
push(@implContent, "\n");
}
}
}
if ($dataNode->extendedAttributes->{"ReplaceableConstructor"}) {
my $constructorFunctionName = "setJS" . $interfaceName . "Constructor";
push(@implContent, "void ${constructorFunctionName}(ExecState* exec, JSObject* thisObject, JSValue value)\n");
push(@implContent, "{\n");
if ($dataNode->extendedAttributes->{"CheckDomainSecurity"}) {
if ($interfaceName eq "DOMWindow") {
push(@implContent, " if (!static_cast<$className*>(thisObject)->allowsAccessFrom(exec))\n");
} else {
push(@implContent, " if (!allowsAccessFromFrame(exec, static_cast<$className*>(thisObject)->impl()->frame()))\n");
}
push(@implContent, " return;\n");
}
push(@implContent, " // Shadowing a built-in constructor\n");
if ($interfaceName eq "DOMWindow") {
push(@implContent, " static_cast<$className*>(thisObject)->putDirect(exec->globalData(), exec->propertyNames().constructor, value);\n");
} else {
push(@implContent, " static_cast<$className*>(thisObject)->putDirect(exec->globalData(), Identifier(exec, \"$name\"), value);\n");
}
push(@implContent, "}\n\n");
}
}
}
if (($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) && !$dataNode->extendedAttributes->{"CustomGetPropertyNames"}) {
push(@implContent, "void ${className}::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)\n");
push(@implContent, "{\n");
if ($dataNode->extendedAttributes->{"HasIndexGetter"} || $dataNode->extendedAttributes->{"HasCustomIndexGetter"} || $dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@implContent, " for (unsigned i = 0; i < static_cast<${implClassName}*>(impl())->length(); ++i)\n");
push(@implContent, " propertyNames.add(Identifier::from(exec, i));\n");
}
push(@implContent, " Base::getOwnPropertyNames(exec, propertyNames, mode);\n");
push(@implContent, "}\n\n");
}
if (!($dataNode->extendedAttributes->{"OmitConstructor"} || $dataNode->extendedAttributes->{"CustomConstructor"})) {
push(@implContent, "JSValue ${className}::getConstructor(ExecState* exec, JSGlobalObject* globalObject)\n{\n");
push(@implContent, " return getDOMConstructor<${className}Constructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject));\n");
push(@implContent, "}\n\n");
}
# Functions
if ($numFunctions > 0) {
foreach my $function (@{$dataNode->functions}) {
AddIncludesForType($function->signature->type);
my $functionName = $codeGenerator->WK_lcfirst($className) . "PrototypeFunction" . $codeGenerator->WK_ucfirst($function->signature->name);
if ($function->{overloads} && @{$function->{overloads}} > 1) {
# Append a number to an overloaded method's name to make it unique:
$functionName = $functionName . $function->{overloadIndex};
# Make this function static to avoid compiler warnings, since we
# don't generate a prototype for it in the header.
push(@implContent, "static ");
}
my $functionImplementationName = $function->signature->extendedAttributes->{"ImplementationFunction"} || $codeGenerator->WK_lcfirst($function->signature->name);
push(@implContent, "EncodedJSValue JSC_HOST_CALL ${functionName}(ExecState* exec)\n");
push(@implContent, "{\n");
$implIncludes{"<runtime/Error.h>"} = 1;
if ($interfaceName eq "DOMWindow") {
push(@implContent, " $className* castedThis = toJSDOMWindow(exec->hostThisValue().toThisObject(exec));\n");
push(@implContent, " if (!castedThis)\n");
push(@implContent, " return throwVMTypeError(exec);\n");
} elsif ($dataNode->extendedAttributes->{"IsWorkerContext"}) {
push(@implContent, " $className* castedThis = to${className}(exec->hostThisValue().toThisObject(exec));\n");
push(@implContent, " if (!castedThis)\n");
push(@implContent, " return throwVMTypeError(exec);\n");
} else {
push(@implContent, " JSValue thisValue = exec->hostThisValue();\n");
push(@implContent, " if (!thisValue.inherits(&${className}::s_info))\n");
push(@implContent, " return throwVMTypeError(exec);\n");
push(@implContent, " $className* castedThis = static_cast<$className*>(asObject(thisValue));\n");
}
if ($dataNode->extendedAttributes->{"CheckDomainSecurity"} &&
!$function->signature->extendedAttributes->{"DoNotCheckDomainSecurity"}) {
push(@implContent, " if (!castedThis->allowsAccessFrom(exec))\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
}
if ($function->signature->extendedAttributes->{"Custom"} || $function->signature->extendedAttributes->{"JSCCustom"}) {
push(@implContent, " return JSValue::encode(castedThis->" . $functionImplementationName . "(exec));\n");
} else {
push(@implContent, " $implType* imp = static_cast<$implType*>(castedThis->impl());\n");
if ($svgPropertyType) {
push(@implContent, " if (imp->role() == AnimValRole) {\n");
push(@implContent, " setDOMException(exec, NO_MODIFICATION_ALLOWED_ERR);\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
push(@implContent, " }\n");
push(@implContent, " $svgPropertyType& podImp = imp->propertyReference();\n");
}
my $numParameters = @{$function->parameters};
my $requiresAllArguments = $function->signature->extendedAttributes->{"RequiresAllArguments"};
if ($requiresAllArguments) {
my $numMandatoryParams = @{$function->parameters};
foreach my $param (reverse(@{$function->parameters})) {
if ($param->extendedAttributes->{"Optional"}) {
$numMandatoryParams--;
} else {
last;
}
}
push(@implContent, " if (exec->argumentCount() < $numMandatoryParams)\n");
if ($requiresAllArguments eq "Raise") {
push(@implContent, " return throwVMError(exec, createSyntaxError(exec, \"Not enough arguments\"));\n");
} else {
push(@implContent, " return JSValue::encode(jsUndefined());\n");
}
}
if (@{$function->raisesExceptions}) {
push(@implContent, " ExceptionCode ec = 0;\n");
}
if ($function->signature->extendedAttributes->{"SVGCheckSecurityDocument"}) {
push(@implContent, " if (!checkNodeSecurity(exec, imp->getSVGDocument(" . (@{$function->raisesExceptions} ? "ec" : "") .")))\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
$implIncludes{"JSDOMBinding.h"} = 1;
}
if ($function->signature->name eq "addEventListener") {
push(@implContent, GenerateEventListenerCall($className, "add"));
} elsif ($function->signature->name eq "removeEventListener") {
push(@implContent, GenerateEventListenerCall($className, "remove"));
} else {
my $argsIndex = 0;
my $paramIndex = 0;
my $functionString = (($svgPropertyOrListPropertyType and !$svgListPropertyType) ? "podImp." : "imp->") . $functionImplementationName . "(";
my $hasOptionalArguments = 0;
if ($function->signature->extendedAttributes->{"CustomArgumentHandling"}) {
push(@implContent, " RefPtr<ScriptArguments> scriptArguments(createScriptArguments(exec, $numParameters));\n");
push(@implContent, " size_t maxStackSize = imp->shouldCaptureFullStackTrace() ? ScriptCallStack::maxCallStackSizeToCapture : 1;\n");
push(@implContent, " RefPtr<ScriptCallStack> callStack(createScriptCallStack(exec, maxStackSize));\n");
$implIncludes{"ScriptArguments.h"} = 1;
$implIncludes{"ScriptCallStack.h"} = 1;
$implIncludes{"ScriptCallStackFactory.h"} = 1;
}
my $callWith = $function->signature->extendedAttributes->{"CallWith"};
if ($callWith) {
my $callWithArg = "COMPILE_ASSERT(false)";
if ($callWith eq "DynamicFrame") {
push(@implContent, " Frame* dynamicFrame = toDynamicFrame(exec);\n");
push(@implContent, " if (!dynamicFrame)\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
$callWithArg = "dynamicFrame";
} elsif ($callWith eq "ScriptState") {
$callWithArg = "exec";
} elsif ($callWith eq "ScriptExecutionContext") {
push(@implContent, " ScriptExecutionContext* scriptContext = static_cast<JSDOMGlobalObject*>(exec->lexicalGlobalObject())->scriptExecutionContext();\n");
push(@implContent, " if (!scriptContext)\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
$callWithArg = "scriptContext";
}
$functionString .= ", " if $paramIndex;
$functionString .= $callWithArg;
$paramIndex++;
}
$implIncludes{"ExceptionCode.h"} = 1;
$implIncludes{"JSDOMBinding.h"} = 1;
foreach my $parameter (@{$function->parameters}) {
# Optional callbacks should be treated differently, because they always have a default value (0),
# and we can reduce the number of overloaded functions that take a different number of parameters.
if ($parameter->extendedAttributes->{"Optional"} && !$parameter->extendedAttributes->{"Callback"}) {
# Generate early call if there are enough parameters.
if (!$hasOptionalArguments) {
push(@implContent, "\n int argsCount = exec->argumentCount();\n");
$hasOptionalArguments = 1;
}
push(@implContent, " if (argsCount <= $argsIndex) {\n");
GenerateImplementationFunctionCall($function, $functionString, $paramIndex, " " x 2, $svgPropertyType, $implClassName);
push(@implContent, " }\n\n");
}
my $name = $parameter->name;
my $argType = $codeGenerator->StripModule($parameter->type);
if ($argType eq "XPathNSResolver") {
push(@implContent, " RefPtr<XPathNSResolver> customResolver;\n");
push(@implContent, " XPathNSResolver* resolver = toXPathNSResolver(exec->argument($argsIndex));\n");
push(@implContent, " if (!resolver) {\n");
push(@implContent, " customResolver = JSCustomXPathNSResolver::create(exec, exec->argument($argsIndex));\n");
push(@implContent, " if (exec->hadException())\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
push(@implContent, " resolver = customResolver.get();\n");
push(@implContent, " }\n");
} elsif ($parameter->extendedAttributes->{"Callback"}) {
my $callbackClassName = GetCallbackClassName($argType);
$implIncludes{"$callbackClassName.h"} = 1;
if ($parameter->extendedAttributes->{"Optional"}) {
push(@implContent, " RefPtr<$argType> $name;\n");
push(@implContent, " if (exec->argumentCount() > $argsIndex && !exec->argument($argsIndex).isNull() && !exec->argument($argsIndex).isUndefined()) {\n");
push(@implContent, " if (!exec->argument($argsIndex).isObject()) {\n");
push(@implContent, " setDOMException(exec, TYPE_MISMATCH_ERR);\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
push(@implContent, " }\n");
push(@implContent, " $name = ${callbackClassName}::create(asObject(exec->argument($argsIndex)), castedThis->globalObject());\n");
push(@implContent, " }\n");
} else {
push(@implContent, " if (exec->argumentCount() <= $argsIndex || !exec->argument($argsIndex).isObject()) {\n");
push(@implContent, " setDOMException(exec, TYPE_MISMATCH_ERR);\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
push(@implContent, " }\n");
push(@implContent, " RefPtr<$argType> $name = ${callbackClassName}::create(asObject(exec->argument($argsIndex)), castedThis->globalObject());\n");
}
} else {
# If the "StrictTypeChecking" extended attribute is present, and the argument's type is an
# interface type, then if the incoming value does not implement that interface, a TypeError
# is thrown rather than silently passing NULL to the C++ code.
# Per the Web IDL and ECMAScript semantics, incoming values can always be converted to both
# strings and numbers, so do not throw TypeError if the argument is of these types.
if ($function->signature->extendedAttributes->{"StrictTypeChecking"}) {
$implIncludes{"<runtime/Error.h>"} = 1;
my $argValue = "exec->argument($argsIndex)";
if (!IsNativeType($argType)) {
push(@implContent, " if (exec->argumentCount() > $argsIndex && !${argValue}.isUndefinedOrNull() && !${argValue}.inherits(&JS${argType}::s_info))\n");
push(@implContent, " return throwVMTypeError(exec);\n");
}
}
push(@implContent, " " . GetNativeTypeFromSignature($parameter) . " $name(" . JSValueToNative($parameter, "exec->argument($argsIndex)") . ");\n");
# If a parameter is "an index" and it's negative it should throw an INDEX_SIZE_ERR exception.
# But this needs to be done in the bindings, because the type is unsigned and the fact that it
# was negative will be lost by the time we're inside the DOM.
if ($parameter->extendedAttributes->{"IsIndex"}) {
push(@implContent, " if ($name < 0) {\n");
push(@implContent, " setDOMException(exec, INDEX_SIZE_ERR);\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
push(@implContent, " }\n");
}
# Check if the type conversion succeeded.
push(@implContent, " if (exec->hadException())\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
if ($codeGenerator->IsSVGTypeNeedingTearOff($argType) and not $implClassName =~ /List$/) {
push(@implContent, " if (!$name) {\n");
push(@implContent, " setDOMException(exec, TYPE_MISMATCH_ERR);\n");
push(@implContent, " return JSValue::encode(jsUndefined());\n");
push(@implContent, " }\n");
}
}
$functionString .= ", " if $paramIndex;
if ($argType eq "NodeFilter") {
$functionString .= "$name.get()";
} elsif ($codeGenerator->IsSVGTypeNeedingTearOff($argType) and not $implClassName =~ /List$/) {
$functionString .= "$name->propertyReference()";
} else {
$functionString .= $name;
}
$argsIndex++;
$paramIndex++;
}
if ($function->signature->extendedAttributes->{"NeedsUserGestureCheck"}) {
$functionString .= ", " if $paramIndex;
$functionString .= "processingUserGesture()";
$paramIndex++;
}
push(@implContent, "\n");
GenerateImplementationFunctionCall($function, $functionString, $paramIndex, " ", $svgPropertyType, $implClassName);
}
}
push(@implContent, "}\n\n");
if ($function->{overloads} && @{$function->{overloads}} > 1 && $function->{overloadIndex} == @{$function->{overloads}}) {
# Generate a function dispatching call to the rest of the overloads.
GenerateOverloadedPrototypeFunction($function, $dataNode, $implClassName);
}
}
}
if ($numConstants > 0) {
push(@implContent, "// Constant getters\n\n");
foreach my $constant (@{$dataNode->constants}) {
my $getter = "js" . $interfaceName . $codeGenerator->WK_ucfirst($constant->name);
# FIXME: this casts into int to match our previous behavior which turned 0xFFFFFFFF in -1 for NodeFilter.SHOW_ALL
push(@implContent, "JSValue ${getter}(ExecState* exec, JSValue, const Identifier&)\n");
push(@implContent, "{\n");
if ($constant->type eq "DOMString") {
push(@implContent, " return jsStringOrNull(exec, String(" . $constant->value . "));\n");
} else {
push(@implContent, " UNUSED_PARAM(exec);\n");
push(@implContent, " return jsNumber(static_cast<int>(" . $constant->value . "));\n");
}
push(@implContent, "}\n\n");
}
}
if ($dataNode->extendedAttributes->{"HasIndexGetter"}) {
push(@implContent, "\nJSValue ${className}::indexGetter(ExecState* exec, JSValue slotBase, unsigned index)\n");
push(@implContent, "{\n");
push(@implContent, " ${className}* thisObj = static_cast<$className*>(asObject(slotBase));\n");
if (IndexGetterReturnsStrings($implClassName)) {
$implIncludes{"KURL.h"} = 1;
push(@implContent, " return jsStringOrNull(exec, thisObj->impl()->item(index));\n");
} else {
push(@implContent, " return toJS(exec, thisObj->globalObject(), static_cast<$implClassName*>(thisObj->impl())->item(index));\n");
}
push(@implContent, "}\n\n");
if ($interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
$implIncludes{"JSNode.h"} = 1;
$implIncludes{"Node.h"} = 1;
}
}
if ($dataNode->extendedAttributes->{"HasNumericIndexGetter"}) {
push(@implContent, "\nJSValue ${className}::getByIndex(ExecState*, unsigned index)\n");
push(@implContent, "{\n");
push(@implContent, " return jsNumber(static_cast<$implClassName*>(impl())->item(index));\n");
push(@implContent, "}\n\n");
if ($interfaceName eq "HTMLCollection" or $interfaceName eq "HTMLAllCollection") {
$implIncludes{"JSNode.h"} = 1;
$implIncludes{"Node.h"} = 1;
}
}
if ($dataNode->extendedAttributes->{"GenerateIsReachable"} || $dataNode->extendedAttributes->{"ActiveDOMObject"}) {
push(@implContent, "static inline bool isObservable(JS${implType}* js${implType})\n");
push(@implContent, "{\n");
push(@implContent, " if (js${implType}->hasCustomProperties())\n");
push(@implContent, " return true;\n");
if ($eventTarget) {
push(@implContent, " if (js${implType}->impl()->hasEventListeners())\n");
push(@implContent, " return true;\n");
}
push(@implContent, " return false;\n");
push(@implContent, "}\n\n");
push(@implContent, "bool JS${implType}Owner::isReachableFromOpaqueRoots(JSC::Handle<JSC::Unknown> handle, void*, SlotVisitor& visitor)\n");
push(@implContent, "{\n");
push(@implContent, " JS${implType}* js${implType} = static_cast<JS${implType}*>(handle.get().asCell());\n");
# All ActiveDOMObjects implement hasPendingActivity(), but not all of them
# increment their C++ reference counts when hasPendingActivity() becomes
# true. As a result, ActiveDOMObjects can be prematurely destroyed before
# their pending activities complete. To wallpaper over this bug, JavaScript
# wrappers unconditionally keep ActiveDOMObjects with pending activity alive.
# FIXME: Fix this lifetime issue in the DOM, and move this hasPendingActivity
# check below the isObservable check.
if ($dataNode->extendedAttributes->{"ActiveDOMObject"}) {
push(@implContent, " if (js${implType}->impl()->hasPendingActivity())\n");
push(@implContent, " return true;\n");
}
push(@implContent, " if (!isObservable(js${implType}))\n");
push(@implContent, " return false;\n");
if ($dataNode->extendedAttributes->{"GenerateIsReachable"}) {
my $rootString;
if ($dataNode->extendedAttributes->{"GenerateIsReachable"} eq "Impl") {
$rootString = " ${implType}* root = js${implType}->impl();\n";
} elsif ($dataNode->extendedAttributes->{"GenerateIsReachable"} eq "ImplContext") {
$rootString = " WebGLRenderingContext* root = js${implType}->impl()->context();\n";
} elsif ($dataNode->extendedAttributes->{"GenerateIsReachable"} eq "ImplFrame") {
$rootString = " Frame* root = js${implType}->impl()->frame();\n";
$rootString .= " if (!root)\n";
$rootString .= " return false;\n";
} elsif ($dataNode->extendedAttributes->{"GenerateIsReachable"} eq "ImplDocument") {
$rootString = " Document* root = js${implType}->impl()->document();\n";
$rootString .= " if (!root)\n";
$rootString .= " return false;\n";
} elsif ($dataNode->extendedAttributes->{"GenerateIsReachable"} eq "ImplElementRoot") {
$rootString = " Element* element = js${implType}->impl()->element();\n";
$rootString .= " if (!element)\n";
$rootString .= " return false;\n";
$rootString .= " void* root = WebCore::root(element);\n";
} elsif ($interfaceName eq "CanvasRenderingContext") {
$rootString = " void* root = WebCore::root(js${implType}->impl()->canvas());\n";
} elsif ($interfaceName eq "HTMLCollection") {
$rootString = " void* root = WebCore::root(js${implType}->impl()->base());\n";
} else {
$rootString = " void* root = WebCore::root(js${implType}->impl());\n";
}
push(@implContent, $rootString);
push(@implContent, " return visitor.containsOpaqueRoot(root);\n");
} else {
push(@implContent, " UNUSED_PARAM(visitor);\n");
push(@implContent, " return false;\n");
}
push(@implContent, "}\n\n");
}
if (!$dataNode->extendedAttributes->{"CustomFinalize"} &&
($dataNode->extendedAttributes->{"GenerateIsReachable"} ||
$dataNode->extendedAttributes->{"CustomIsReachable"} ||
$dataNode->extendedAttributes->{"ActiveDOMObject"})) {
push(@implContent, "void JS${implType}Owner::finalize(JSC::Handle<JSC::Unknown> handle, void* context)\n");
push(@implContent, "{\n");
push(@implContent, " JS${implType}* js${implType} = static_cast<JS${implType}*>(handle.get().asCell());\n");
push(@implContent, " DOMWrapperWorld* world = static_cast<DOMWrapperWorld*>(context);\n");
push(@implContent, " uncacheWrapper(world, js${implType}->impl(), js${implType});\n");
push(@implContent, "}\n\n");
}
if ((!$hasParent or $dataNode->extendedAttributes->{"GenerateToJS"}) and !$dataNode->extendedAttributes->{"CustomToJS"}) {
push(@implContent, "JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, $implType* impl)\n");
push(@implContent, "{\n");
if ($svgPropertyType) {
push(@implContent, " return wrap<$className, $implType>(exec, globalObject, impl);\n");
} else {
push(@implContent, " return wrap<$className>(exec, globalObject, impl);\n");
}
push(@implContent, "}\n\n");
}
if ((!$hasParent or $dataNode->extendedAttributes->{"GenerateNativeConverter"}) and !$dataNode->extendedAttributes->{"CustomNativeConverter"}) {
push(@implContent, "$implType* to${interfaceName}(JSC::JSValue value)\n");
push(@implContent, "{\n");
push(@implContent, " return value.inherits(&${className}::s_info) ? static_cast<$className*>(asObject(value))->impl() : 0");
push(@implContent, ";\n}\n");
}
push(@implContent, "\n}\n");
my $conditionalString = GenerateConditionalString($dataNode);
push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString;
}
sub GenerateCallbackHeader
{
my $object = shift;
my $dataNode = shift;
my $interfaceName = $dataNode->name;
my $className = "JS$interfaceName";
# - Add default header template and header protection
push(@headerContentHeader, GenerateHeaderContentHeader($dataNode));
$headerIncludes{"ActiveDOMCallback.h"} = 1;
$headerIncludes{"$interfaceName.h"} = 1;
$headerIncludes{"JSCallbackData.h"} = 1;
$headerIncludes{"<wtf/Forward.h>"} = 1;
push(@headerContent, "\nnamespace WebCore {\n\n");
push(@headerContent, "class $className : public $interfaceName, public ActiveDOMCallback {\n");
push(@headerContent, "public:\n");
# The static create() method.
push(@headerContent, " static PassRefPtr<$className> create(JSC::JSObject* callback, JSDOMGlobalObject* globalObject)\n");
push(@headerContent, " {\n");
push(@headerContent, " return adoptRef(new $className(callback, globalObject));\n");
push(@headerContent, " }\n\n");
# Destructor
push(@headerContent, " virtual ~$className();\n");
# Functions
my $numFunctions = @{$dataNode->functions};
if ($numFunctions > 0) {
push(@headerContent, "\n // Functions\n");
foreach my $function (@{$dataNode->functions}) {
my @params = @{$function->parameters};
if (!$function->signature->extendedAttributes->{"Custom"} &&
!(GetNativeType($function->signature->type) eq "bool")) {
push(@headerContent, " COMPILE_ASSERT(false)");
}
push(@headerContent, " virtual " . GetNativeType($function->signature->type) . " " . $function->signature->name . "(");
my @args = ();
foreach my $param (@params) {
push(@args, GetNativeType($param->type) . " " . $param->name);
}
push(@headerContent, join(", ", @args));
push(@headerContent, ");\n");
}
}
push(@headerContent, "\nprivate:\n");
# Constructor
push(@headerContent, " $className(JSC::JSObject* callback, JSDOMGlobalObject*);\n\n");
# Private members
push(@headerContent, " JSCallbackData* m_data;\n");
push(@headerContent, "};\n\n");
push(@headerContent, "} // namespace WebCore\n\n");
my $conditionalString = GenerateConditionalString($dataNode);
push(@headerContent, "#endif // ${conditionalString}\n\n") if $conditionalString;
push(@headerContent, "#endif\n");
}
sub GenerateCallbackImplementation
{
my ($object, $dataNode) = @_;
my $interfaceName = $dataNode->name;
my $className = "JS$interfaceName";
# - Add default header template
push(@implContentHeader, GenerateImplementationContentHeader($dataNode));
$implIncludes{"ScriptExecutionContext.h"} = 1;
$implIncludes{"<runtime/JSLock.h>"} = 1;
$implIncludes{"<wtf/MainThread.h>"} = 1;
@implContent = ();
push(@implContent, "\nusing namespace JSC;\n\n");
push(@implContent, "namespace WebCore {\n\n");
# Constructor
push(@implContent, "${className}::${className}(JSObject* callback, JSDOMGlobalObject* globalObject)\n");
push(@implContent, " : ActiveDOMCallback(globalObject->scriptExecutionContext())\n");
push(@implContent, " , m_data(new JSCallbackData(callback, globalObject))\n");
push(@implContent, "{\n");
push(@implContent, "}\n\n");
# Destructor
push(@implContent, "${className}::~${className}()\n");
push(@implContent, "{\n");
push(@implContent, " ScriptExecutionContext* context = scriptExecutionContext();\n");
push(@implContent, " // When the context is destroyed, all tasks with a reference to a callback\n");
push(@implContent, " // should be deleted. So if the context is 0, we are on the context thread.\n");
push(@implContent, " if (!context || context->isContextThread())\n");
push(@implContent, " delete m_data;\n");
push(@implContent, " else\n");
push(@implContent, " context->postTask(DeleteCallbackDataTask::create(m_data));\n");
push(@implContent, "#ifndef NDEBUG\n");
push(@implContent, " m_data = 0;\n");
push(@implContent, "#endif\n");
push(@implContent, "}\n");
# Functions
my $numFunctions = @{$dataNode->functions};
if ($numFunctions > 0) {
push(@implContent, "\n// Functions\n");
foreach my $function (@{$dataNode->functions}) {
my @params = @{$function->parameters};
if ($function->signature->extendedAttributes->{"Custom"} ||
!(GetNativeType($function->signature->type) eq "bool")) {
next;
}
AddIncludesForType($function->signature->type);
push(@implContent, "\n" . GetNativeType($function->signature->type) . " ${className}::" . $function->signature->name . "(");
my @args = ();
foreach my $param (@params) {
AddIncludesForType($param->type, 1);
push(@args, GetNativeType($param->type) . " " . $param->name);
}
push(@implContent, join(", ", @args));
push(@implContent, ")\n");
push(@implContent, "{\n");
push(@implContent, " if (!canInvokeCallback())\n");
push(@implContent, " return true;\n\n");
push(@implContent, " RefPtr<$className> protect(this);\n\n");
push(@implContent, " JSLock lock(SilenceAssertionsOnly);\n\n");
push(@implContent, " ExecState* exec = m_data->globalObject()->globalExec();\n");
push(@implContent, " MarkedArgumentBuffer args;\n");
foreach my $param (@params) {
my $paramName = $param->name;
if ($param->type eq "DOMString") {
push(@implContent, " args.append(jsString(exec, ${paramName}));\n");
} else {
push(@implContent, " args.append(toJS(exec, m_data->globalObject(), ${paramName}));\n");
}
}
push(@implContent, "\n bool raisedException = false;\n");
push(@implContent, " m_data->invokeCallback(args, &raisedException);\n");
push(@implContent, " return !raisedException;\n");
push(@implContent, "}\n");
}
}
push(@implContent, "\n}\n");
my $conditionalString = GenerateConditionalString($dataNode);
push(@implContent, "\n#endif // ${conditionalString}\n") if $conditionalString;
}
sub GenerateImplementationFunctionCall()
{
my $function = shift;
my $functionString = shift;
my $paramIndex = shift;
my $indent = shift;
my $svgPropertyType = shift;
my $implClassName = shift;
if ($function->signature->extendedAttributes->{"CustomArgumentHandling"}) {
$functionString .= ", " if $paramIndex;
$paramIndex += 2;
$functionString .= "scriptArguments, callStack";
}
if (@{$function->raisesExceptions}) {
$functionString .= ", " if $paramIndex;
$functionString .= "ec";
}
$functionString .= ")";
if ($function->signature->type eq "void") {
push(@implContent, $indent . "$functionString;\n");
push(@implContent, $indent . "setDOMException(exec, ec);\n") if @{$function->raisesExceptions};
if ($svgPropertyType) {
if (@{$function->raisesExceptions}) {
push(@implContent, $indent . "if (!ec)\n");
push(@implContent, $indent . " imp->commitChange();\n");
} else {
push(@implContent, $indent . "imp->commitChange();\n");
}
}
push(@implContent, $indent . "return JSValue::encode(jsUndefined());\n");
} else {
push(@implContent, "\n" . $indent . "JSC::JSValue result = " . NativeToJSValue($function->signature, 1, $implClassName, $functionString, "castedThis") . ";\n");
push(@implContent, $indent . "setDOMException(exec, ec);\n") if @{$function->raisesExceptions};
$callWith = $function->signature->extendedAttributes->{"CallWith"};
if ($callWith and $callWith eq "ScriptState") {
push(@implContent, $indent . "if (exec->hadException())\n");
push(@implContent, $indent . " return JSValue::encode(jsUndefined());\n");
}
push(@implContent, $indent . "return JSValue::encode(result);\n");
}
}
sub GetNativeTypeFromSignature
{
my $signature = shift;
my $type = $codeGenerator->StripModule($signature->type);
if ($type eq "unsigned long" and $signature->extendedAttributes->{"IsIndex"}) {
# Special-case index arguments because we need to check that they aren't < 0.
return "int";
}
return GetNativeType($type);
}
my %nativeType = (
"CompareHow" => "Range::CompareHow",
"DOMString" => "const String&",
"DOMObject" => "ScriptValue",
"NodeFilter" => "RefPtr<NodeFilter>",
"SerializedScriptValue" => "RefPtr<SerializedScriptValue>",
"IDBKey" => "RefPtr<IDBKey>",
"boolean" => "bool",
"double" => "double",
"float" => "float",
"short" => "short",
"long" => "int",
"unsigned long" => "unsigned",
"unsigned short" => "unsigned short",
"long long" => "long long",
"unsigned long long" => "unsigned long long",
"MediaQueryListListener" => "RefPtr<MediaQueryListListener>"
);
sub GetNativeType
{
my $type = shift;
my $svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($type);
return "${svgNativeType}*" if $svgNativeType;
return $nativeType{$type} if exists $nativeType{$type};
# For all other types, the native type is a pointer with same type name as the IDL type.
return "${type}*";
}
sub GetSVGPropertyTypes
{
my $implType = shift;
my $svgPropertyType;
my $svgListPropertyType;
my $svgNativeType;
return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $implType =~ /SVG/;
$svgNativeType = $codeGenerator->GetSVGTypeNeedingTearOff($implType);
return ($svgPropertyType, $svgListPropertyType, $svgNativeType) if not $svgNativeType;
# Append space to avoid compilation errors when using PassRefPtr<$svgNativeType>
$svgNativeType = "$svgNativeType ";
my $svgWrappedNativeType = $codeGenerator->GetSVGWrappedTypeNeedingTearOff($implType);
if ($svgNativeType =~ /SVGPropertyTearOff/) {
$svgPropertyType = $svgWrappedNativeType;
$headerIncludes{"$svgWrappedNativeType.h"} = 1;
$headerIncludes{"SVGAnimatedPropertyTearOff.h"} = 1;
} elsif ($svgNativeType =~ /SVGListPropertyTearOff/ or $svgNativeType =~ /SVGStaticListPropertyTearOff/) {
$svgListPropertyType = $svgWrappedNativeType;
$headerIncludes{"$svgWrappedNativeType.h"} = 1;
$headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
} elsif ($svgNativeType =~ /SVGTransformListPropertyTearOff/) {
$svgListPropertyType = $svgWrappedNativeType;
$headerIncludes{"$svgWrappedNativeType.h"} = 1;
$headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
$headerIncludes{"SVGTransformListPropertyTearOff.h"} = 1;
} elsif ($svgNativeType =~ /SVGPathSegListPropertyTearOff/) {
$svgListPropertyType = $svgWrappedNativeType;
$headerIncludes{"$svgWrappedNativeType.h"} = 1;
$headerIncludes{"SVGAnimatedListPropertyTearOff.h"} = 1;
$headerIncludes{"SVGPathSegListPropertyTearOff.h"} = 1;
}
return ($svgPropertyType, $svgListPropertyType, $svgNativeType);
}
sub IsNativeType
{
my $type = shift;
return exists $nativeType{$type};
}
sub JSValueToNative
{
my $signature = shift;
my $value = shift;
my $type = $codeGenerator->StripModule($signature->type);
return "$value.toBoolean(exec)" if $type eq "boolean";
return "$value.toNumber(exec)" if $type eq "double";
return "$value.toFloat(exec)" if $type eq "float";
return "$value.toInt32(exec)" if $type eq "long" or $type eq "short";
return "$value.toUInt32(exec)" if $type eq "unsigned long" or $type eq "unsigned short";
return "static_cast<$type>($value.toInteger(exec))" if $type eq "long long" or $type eq "unsigned long long";
return "valueToDate(exec, $value)" if $type eq "Date";
return "static_cast<Range::CompareHow>($value.toInt32(exec))" if $type eq "CompareHow";
if ($type eq "DOMString") {
return "valueToStringWithNullCheck(exec, $value)" if $signature->extendedAttributes->{"ConvertNullToNullString"} || $signature->extendedAttributes->{"Reflect"};
return "valueToStringWithUndefinedOrNullCheck(exec, $value)" if $signature->extendedAttributes->{"ConvertUndefinedOrNullToNullString"};
return "ustringToString($value.toString(exec))";
}
if ($type eq "DOMObject") {
return "exec->globalData(), $value";
}
if ($type eq "NodeFilter") {
$implIncludes{"JS$type.h"} = 1;
return "to$type(exec->globalData(), $value)";
}
if ($type eq "MediaQueryListListener") {
$implIncludes{"MediaQueryListListener.h"} = 1;
return "MediaQueryListListener::create(ScriptValue(exec->globalData(), " . $value ."))";
}
if ($type eq "SerializedScriptValue" or $type eq "any") {
$implIncludes{"SerializedScriptValue.h"} = 1;
return "SerializedScriptValue::create(exec, $value)";
}
if ($type eq "IDBKey") {
$implIncludes{"IDBBindingUtilities.h"} = 1;
$implIncludes{"IDBKey.h"} = 1;
return "createIDBKeyFromValue(exec, $value)";
}
$implIncludes{"HTMLOptionElement.h"} = 1 if $type eq "HTMLOptionElement";
$implIncludes{"JSCustomVoidCallback.h"} = 1 if $type eq "VoidCallback";
$implIncludes{"Event.h"} = 1 if $type eq "Event";
# Default, assume autogenerated type conversion routines
$implIncludes{"JS$type.h"} = 1;
return "to$type($value)";
}
sub NativeToJSValue
{
my $signature = shift;
my $inFunctionCall = shift;
my $implClassName = shift;
my $value = shift;
my $thisValue = shift;
my $type = $codeGenerator->StripModule($signature->type);
return "jsBoolean($value)" if $type eq "boolean";
# Need to check Date type before IsPrimitiveType().
if ($type eq "Date") {
return "jsDateOrNull(exec, $value)";
}
if ($signature->extendedAttributes->{"Reflect"} and ($type eq "unsigned long" or $type eq "unsigned short")) {
$value =~ s/getUnsignedIntegralAttribute/getIntegralAttribute/g;
return "jsNumber(std::max(0, " . $value . "))";
}
if ($codeGenerator->IsPrimitiveType($type) or $type eq "DOMTimeStamp") {
return "jsNumber($value)";
}
if ($codeGenerator->IsStringType($type)) {
$implIncludes{"KURL.h"} = 1;
my $conv = $signature->extendedAttributes->{"ConvertNullStringTo"};
if (defined $conv) {
return "jsStringOrNull(exec, $value)" if $conv eq "Null";
return "jsStringOrUndefined(exec, $value)" if $conv eq "Undefined";
return "jsStringOrFalse(exec, $value)" if $conv eq "False";
die "Unknown value for ConvertNullStringTo extended attribute";
}
$conv = $signature->extendedAttributes->{"ConvertScriptString"};
return "jsOwnedStringOrNull(exec, $value)" if $conv;
$implIncludes{"<runtime/JSString.h>"} = 1;
return "jsString(exec, $value)";
}
my $globalObject = "$thisValue->globalObject()";
if ($type eq "CSSStyleDeclaration") {
$implIncludes{"CSSMutableStyleDeclaration.h"} = 1;
}
if ($type eq "NodeList") {
$implIncludes{"NameNodeList.h"} = 1;
}
if ($type eq "DOMObject") {
if ($implClassName eq "Document") {
$implIncludes{"JSCanvasRenderingContext2D.h"} = 1;
} else {
return "$value.jsValue();";
}
} elsif ($type =~ /SVGPathSeg/) {
$implIncludes{"JS$type.h"} = 1;
$joinedName = $type;
$joinedName =~ s/Abs|Rel//;
$implIncludes{"$joinedName.h"} = 1;
} elsif ($type eq "SerializedScriptValue" or $type eq "any") {
$implIncludes{"SerializedScriptValue.h"} = 1;
return "$value ? $value->deserialize(exec, castedThis->globalObject()) : jsNull()";
} else {
# Default, include header with same name.
$implIncludes{"JS$type.h"} = 1;
$implIncludes{"$type.h"} = 1 if not $codeGenerator->AvoidInclusionOfType($type);
}
return $value if $codeGenerator->IsSVGAnimatedType($type);
if ($signature->extendedAttributes->{"ReturnsNew"}) {
return "toJSNewlyCreated(exec, $globalObject, WTF::getPtr($value))";
}
if ($codeGenerator->IsSVGAnimatedType($implClassName)) {
# Convert from abstract SVGProperty to real type, so the right toJS() method can be invoked.
$value = "static_cast<" . GetNativeType($type) . ">($value)";
} elsif ($codeGenerator->IsSVGTypeNeedingTearOff($type) and not $implClassName =~ /List$/) {
my $tearOffType = $codeGenerator->GetSVGTypeNeedingTearOff($type);
if ($codeGenerator->IsSVGTypeWithWritablePropertiesNeedingTearOff($type) and $inFunctionCall eq 0 and not defined $signature->extendedAttributes->{"Immutable"}) {
my $getter = $value;
$getter =~ s/imp\.//;
$getter =~ s/imp->//;
$getter =~ s/\(\)//;
my $updateMethod = "&${implClassName}::update" . $codeGenerator->WK_ucfirst($getter);
my $selfIsTearOffType = $codeGenerator->IsSVGTypeNeedingTearOff($implClassName);
if ($selfIsTearOffType) {
$implIncludes{"SVGStaticPropertyWithParentTearOff.h"} = 1;
$tearOffType =~ s/SVGPropertyTearOff</SVGStaticPropertyWithParentTearOff<$implClassName, /;
if ($value =~ /matrix/ and $implClassName eq "SVGTransform") {
# SVGTransform offers a matrix() method for internal usage that returns an AffineTransform
# and a svgMatrix() method returning a SVGMatrix, used for the bindings.
$value =~ s/matrix/svgMatrix/;
}
$value = "${tearOffType}::create(castedThis->impl(), $value, $updateMethod)";
} else {
$implIncludes{"SVGStaticPropertyTearOff.h"} = 1;
$tearOffType =~ s/SVGPropertyTearOff</SVGStaticPropertyTearOff<$implClassName, /;
$value = "${tearOffType}::create(imp, $value, $updateMethod)";
}
} elsif ($tearOffType =~ /SVGStaticListPropertyTearOff/) {
my $extraImp = "GetOwnerElementForType<$implClassName, IsDerivedFromSVGElement<$implClassName>::value>::ownerElement(imp), ";
$value = "${tearOffType}::create($extraImp$value)";
} elsif (not $tearOffType =~ /SVG(Point|PathSeg)List/) {
$value = "${tearOffType}::create($value)";
}
}
return "toJS(exec, $globalObject, WTF::getPtr($value))";
}
sub ceilingToPowerOf2
{
my ($size) = @_;
my $powerOf2 = 1;
while ($size > $powerOf2) {
$powerOf2 <<= 1;
}
return $powerOf2;
}
# Internal Helper
sub GenerateHashTable
{
my $object = shift;
my $name = shift;
my $size = shift;
my $keys = shift;
my $specials = shift;
my $value1 = shift;
my $value2 = shift;
my $conditionals = shift;
# Generate size data for compact' size hash table
my @table = ();
my @links = ();
my $compactSize = ceilingToPowerOf2($size * 2);
my $maxDepth = 0;
my $collisions = 0;
my $numEntries = $compactSize;
my $i = 0;
foreach (@{$keys}) {
my $depth = 0;
my $h = $object->GenerateHashValue($_) % $numEntries;
while (defined($table[$h])) {
if (defined($links[$h])) {
$h = $links[$h];
$depth++;
} else {
$collisions++;
$links[$h] = $compactSize;
$h = $compactSize;
$compactSize++;
}
}
$table[$h] = $i;
$i++;
$maxDepth = $depth if ($depth > $maxDepth);
}
# Start outputing the hashtables
my $nameEntries = "${name}Values";
$nameEntries =~ s/:/_/g;
if (($name =~ /Prototype/) or ($name =~ /Constructor/)) {
my $type = $name;
my $implClass;
if ($name =~ /Prototype/) {
$type =~ s/Prototype.*//;
$implClass = $type; $implClass =~ s/Wrapper$//;
push(@implContent, "/* Hash table for prototype */\n");
} else {
$type =~ s/Constructor.*//;
$implClass = $type; $implClass =~ s/Constructor$//;
push(@implContent, "/* Hash table for constructor */\n");
}
} else {
push(@implContent, "/* Hash table */\n");
}
# Dump the hash table
my $count = scalar @{$keys} + 1;
push(@implContent, "#if ENABLE(JIT)\n");
push(@implContent, "#define THUNK_GENERATOR(generator) , generator\n");
push(@implContent, "#else\n");
push(@implContent, "#define THUNK_GENERATOR(generator)\n");
push(@implContent, "#endif\n");
push(@implContent, "\nstatic const HashTableValue $nameEntries\[$count\] =\n\{\n");
$i = 0;
foreach my $key (@{$keys}) {
my $conditional;
my $targetType;
if ($conditionals) {
$conditional = $conditionals->{$key};
}
if ($conditional) {
my $conditionalString = GenerateConditionalStringFromAttributeValue($conditional);
push(@implContent, "#if ${conditionalString}\n");
}
if ("@$specials[$i]" =~ m/Function/) {
$targetType = "static_cast<NativeFunction>";
} else {
$targetType = "static_cast<PropertySlot::GetValueFunc>";
}
push(@implContent, " { \"$key\", @$specials[$i], (intptr_t)" . $targetType . "(@$value1[$i]), (intptr_t)@$value2[$i] THUNK_GENERATOR(0) },\n");
if ($conditional) {
push(@implContent, "#endif\n");
}
++$i;
}
push(@implContent, " { 0, 0, 0, 0 THUNK_GENERATOR(0) }\n");
push(@implContent, "};\n\n");
push(@implContent, "#undef THUNK_GENERATOR\n");
my $compactSizeMask = $numEntries - 1;
push(@implContent, "static JSC_CONST_HASHTABLE HashTable $name = { $compactSize, $compactSizeMask, $nameEntries, 0 };\n");
}
# Internal helper
sub GenerateHashValue
{
my $object = shift;
@chars = split(/ */, $_[0]);
# This hash is designed to work on 16-bit chunks at a time. But since the normal case
# (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
# were 16-bit chunks, which should give matching results
my $EXP2_32 = 4294967296;
my $hash = 0x9e3779b9;
my $l = scalar @chars; #I wish this was in Ruby --- Maks
my $rem = $l & 1;
$l = $l >> 1;
my $s = 0;
# Main loop
for (; $l > 0; $l--) {
$hash += ord($chars[$s]);
my $tmp = leftShift(ord($chars[$s+1]), 11) ^ $hash;
$hash = (leftShift($hash, 16)% $EXP2_32) ^ $tmp;
$s += 2;
$hash += $hash >> 11;
$hash %= $EXP2_32;
}
# Handle end case
if ($rem != 0) {
$hash += ord($chars[$s]);
$hash ^= (leftShift($hash, 11)% $EXP2_32);
$hash += $hash >> 17;
}
# Force "avalanching" of final 127 bits
$hash ^= leftShift($hash, 3);
$hash += ($hash >> 5);
$hash = ($hash% $EXP2_32);
$hash ^= (leftShift($hash, 2)% $EXP2_32);
$hash += ($hash >> 15);
$hash = $hash% $EXP2_32;
$hash ^= (leftShift($hash, 10)% $EXP2_32);
# this avoids ever returning a hash code of 0, since that is used to
# signal "hash not computed yet", using a value that is likely to be
# effectively the same as 0 when the low bits are masked
$hash = 0x80000000 if ($hash == 0);
return $hash;
}
# Internal helper
sub WriteData
{
if (defined($IMPL)) {
# Write content to file.
print $IMPL @implContentHeader;
my @includes = ();
foreach my $include (keys %implIncludes) {
my $checkType = $include;
$checkType =~ s/\.h//;
next if $codeGenerator->IsSVGAnimatedType($checkType);
$include = "\"$include\"" unless $include =~ /^["<]/; # "
push @includes, $include;
}
foreach my $include (sort @includes) {
print $IMPL "#include $include\n";
}
print $IMPL @implContent;
close($IMPL);
undef($IMPL);
@implContentHeader = ();
@implContent = ();
%implIncludes = ();
}
if (defined($HEADER)) {
# Write content to file.
print $HEADER @headerContentHeader;
my @includes = ();
foreach my $include (keys %headerIncludes) {
$include = "\"$include\"" unless $include =~ /^["<]/; # "
push @includes, $include;
}
foreach my $include (sort @includes) {
print $HEADER "#include $include\n";
}
print $HEADER @headerContent;
@includes = ();
foreach my $include (keys %headerTrailingIncludes) {
$include = "\"$include\"" unless $include =~ /^["<]/; # "
push @includes, $include;
}
foreach my $include (sort @includes) {
print $HEADER "#include $include\n";
}
close($HEADER);
undef($HEADER);
@headerContentHeader = ();
@headerContent = ();
%headerIncludes = ();
%headerTrailingIncludes = ();
}
if (defined($DEPS)) {
# Write dependency file.
print $DEPS @depsContent;
close($DEPS);
undef($DEPS);
@depsContent = ();
}
}
sub GenerateConstructorDeclaration
{
my $outputArray = shift;
my $className = shift;
my $dataNode = shift;
my $constructorClassName = "${className}Constructor";
my $canConstruct = $dataNode->extendedAttributes->{"CanBeConstructed"};
my $callWith = $dataNode->extendedAttributes->{"CallWith"};
push(@$outputArray, "class ${constructorClassName} : public DOMConstructorObject {\n");
push(@$outputArray, "public:\n");
push(@$outputArray, " ${constructorClassName}(JSC::ExecState*, JSC::Structure*, JSDOMGlobalObject*);\n\n");
push(@$outputArray, " virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&);\n");
push(@$outputArray, " virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&);\n");
push(@$outputArray, " static const JSC::ClassInfo s_info;\n");
push(@$outputArray, " static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)\n");
push(@$outputArray, " {\n");
push(@$outputArray, " return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);\n");
push(@$outputArray, " }\n");
push(@$outputArray, "protected:\n");
push(@$outputArray, " static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags;\n");
if ($canConstruct) {
push(@$outputArray, " static JSC::EncodedJSValue JSC_HOST_CALL construct${className}(JSC::ExecState*);\n");
push(@$outputArray, " virtual JSC::ConstructType getConstructData(JSC::ConstructData&);\n");
}
push(@$outputArray, "};\n\n");
}
sub GenerateConstructorDefinition
{
my $outputArray = shift;
my $className = shift;
my $protoClassName = shift;
my $interfaceName = shift;
my $visibleClassName = shift;
my $dataNode = shift;
my $constructorClassName = "${className}Constructor";
my $canConstruct = $dataNode->extendedAttributes->{"CanBeConstructed"};
my $customConstructFunction = $dataNode->extendedAttributes->{"CustomConstructFunction"};
my $callWith = $dataNode->extendedAttributes->{"CallWith"};
my $numberOfconstructParameters = $dataNode->extendedAttributes->{"ConstructorParameters"};
push(@$outputArray, "const ClassInfo ${constructorClassName}::s_info = { \"${visibleClassName}Constructor\", &DOMConstructorObject::s_info, &${constructorClassName}Table, 0 };\n\n");
push(@$outputArray, "${constructorClassName}::${constructorClassName}(ExecState* exec, Structure* structure, JSDOMGlobalObject* globalObject)\n");
push(@$outputArray, " : DOMConstructorObject(structure, globalObject)\n");
push(@$outputArray, "{\n");
push(@$outputArray, " ASSERT(inherits(&s_info));\n");
if ($interfaceName eq "DOMWindow") {
push(@$outputArray, " putDirect(exec->globalData(), exec->propertyNames().prototype, globalObject->prototype(), DontDelete | ReadOnly);\n");
} else {
push(@$outputArray, " putDirect(exec->globalData(), exec->propertyNames().prototype, ${protoClassName}::self(exec, globalObject), DontDelete | ReadOnly);\n");
}
push(@$outputArray, " putDirect(exec->globalData(), exec->propertyNames().length, jsNumber(${numberOfconstructParameters}), ReadOnly | DontDelete | DontEnum);\n") if $numberOfconstructParameters;
push(@$outputArray, "}\n\n");
push(@$outputArray, "bool ${constructorClassName}::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)\n");
push(@$outputArray, "{\n");
push(@$outputArray, " return getStaticValueSlot<${constructorClassName}, JSDOMWrapper>(exec, &${constructorClassName}Table, this, propertyName, slot);\n");
push(@$outputArray, "}\n\n");
push(@$outputArray, "bool ${constructorClassName}::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)\n");
push(@$outputArray, "{\n");
push(@$outputArray, " return getStaticValueDescriptor<${constructorClassName}, JSDOMWrapper>(exec, &${constructorClassName}Table, this, propertyName, descriptor);\n");
push(@$outputArray, "}\n\n");
if ($canConstruct) {
if (!$customConstructFunction) {
push(@$outputArray, "EncodedJSValue JSC_HOST_CALL ${constructorClassName}::construct${className}(ExecState* exec)\n");
push(@$outputArray, "{\n");
my $constructorArg = "";
if ($callWith and $callWith eq "ScriptExecutionContext") {
$constructorArg = "context";
push(@$outputArray, " ScriptExecutionContext* context = static_cast<${constructorClassName}*>(exec->callee())->scriptExecutionContext();\n");
push(@$outputArray, " if (!context)\n");
push(@$outputArray, " return throwVMError(exec, createReferenceError(exec, \"Reference error\"));\n");
}
push(@$outputArray, " return JSValue::encode(asObject(toJS(exec, static_cast<${constructorClassName}*>(exec->callee())->globalObject(), ${interfaceName}::create(${constructorArg}))));\n");
push(@$outputArray, "}\n\n");
}
push(@$outputArray, "ConstructType ${constructorClassName}::getConstructData(ConstructData& constructData)\n");
push(@$outputArray, "{\n");
push(@$outputArray, " constructData.native.function = construct${className};\n");
push(@$outputArray, " return ConstructTypeHost;\n");
push(@$outputArray, "}\n\n");
}
}
1;
| 13W/phantomjs | src/qt/src/3rdparty/webkit/Source/WebCore/bindings/scripts/CodeGeneratorJS.pm | Perl | bsd-3-clause | 153,633 |
package OAuth::Lite2::Client::WebServer;
use strict;
use warnings;
use base 'Class::ErrorHandler';
use bytes ();
use URI;
use Carp ();
use Try::Tiny qw/try catch/;
use LWP::UserAgent;
use MIME::Base64 qw(encode_base64);
use HTTP::Request;
use HTTP::Headers;
use Params::Validate qw(HASHREF);
use OAuth::Lite2;
use OAuth::Lite2::Util qw(build_content);
use OAuth::Lite2::Client::TokenResponseParser;
use OAuth::Lite2::Client::StateResponseParser;
=head1 NAME
OAuth::Lite2::Client::WebServer - OAuth 2.0 Web Server Profile Client
=head1 SYNOPSIS
my $client = OAuth::Lite2::Client::WebServer->new(
id => q{my_client_id},
secret => q{my_client_secret},
authorize_uri => q{http://example.org/authorize},
access_token_uri => q{http://example.org/token},
);
# redirect user to authorize page.
sub start_authorize {
my $your_app = shift;
my $redirect_url = $client->uri_to_redirect(
redirect_uri => q{http://yourapp/callback},
scope => q{photo},
state => q{optional_state},
);
$your_app->res->redirect( $redirect_url );
}
# this method corresponds to the url 'http://yourapp/callback'
sub callback {
my $your_app = shift;
my $code = $your_app->request->param("code");
my $access_token = $client->get_access_token(
code => $code,
redirect_uri => q{http://yourapp/callback},
) or return $your_app->error( $client->errstr );
$your_app->store->save( access_token => $access_token->access_token );
$your_app->store->save( expires_at => time() + $access_token->expires_in );
$your_app->store->save( refresh_token => $access_token->refresh_token );
}
sub refresh_access_token {
my $your_app = shift;
my $access_token = $client->refresh_access_token(
refresh_token => $refresh_token,
) or return $your_app->error( $client->errstr );
$your_app->store->save( access_token => $access_token->access_token );
$your_app->store->save( expires_at => time() + $access_token->expires_in );
$your_app->store->save( refresh_token => $access_token->refresh_token );
}
sub access_to_protected_resource {
my $your_app = shift;
my $access_token = $your_app->store->get("access_token");
my $expires_at = $your_app->store->get("expires_at");
my $refresh_token = $your_app->store->get("refresh_token");
unless ($access_token) {
$your_app->start_authorize();
return;
}
if ($expires_at < time()) {
$your_app->refresh_access_token();
return;
}
my $req = HTTP::Request->new( GET => q{http://example.org/photo} );
$req->header( Authorization => sprintf(q{OAuth %s}, $access_token) );
my $agent = LWP::UserAgent->new;
my $res = $agent->request($req);
...
}
=head1 DESCRIPTION
Client library for OAuth 2.0 Web Server Profile.
=head1 METHODS
=head2 new( %params )
=over 4
=item id
Client ID
=item secret
Client secret
=item authorize_uri
authorization page uri on auth-server.
=item access_token_uri
token endpoint uri on auth-server.
=item refresh_token_uri
refresh-token endpoint uri on auth-server.
if you omit this, access_token_uri is used instead.
=item agent
user agent. if you omit this, LWP::UserAgent's object is set by default.
You can use your custom agent or preset-agents.
See also
L<OAuth::Lite2::Agent::Dump>
L<OAuth::Lite2::Agent::Strict>
L<OAuth::Lite2::Agent::PSGIMock>
=back
=cut
sub new {
my $class = shift;
my %args = Params::Validate::validate(@_, {
id => 1,
secret => 1,
# format => { optional => 1 },
authorize_uri => { optional => 1 },
access_token_uri => { optional => 1 },
refresh_token_uri => { optional => 1 },
agent => { optional => 1 },
});
my $self = bless {
id => undef,
secret => undef,
authorize_uri => undef,
access_token_uri => undef,
refresh_token_uri => undef,
last_request => undef,
last_response => undef,
%args,
}, $class;
unless ($self->{agent}) {
$self->{agent} = LWP::UserAgent->new;
$self->{agent}->agent(
join "/", __PACKAGE__, $OAuth::Lite2::VERSION);
}
$self->{format} ||= 'json';
$self->{response_parser} = OAuth::Lite2::Client::TokenResponseParser->new;
$self->{state_response_parser} = OAuth::Lite2::Client::StateResponseParser->new;
return $self;
}
=head2 uri_to_redirect( %params )
=cut
sub uri_to_redirect {
my $self = shift;
my %args = Params::Validate::validate(@_, {
redirect_uri => 1,
state => { optional => 1 },
scope => { optional => 1 },
immediate => { optional => 1 },
uri => { optional => 1 },
extra => { optional => 1, type => HASHREF },
});
my %params = (
response_type => 'code',
client_id => $self->{id},
redirect_uri => $args{redirect_uri},
);
$params{state} = $args{state} if $args{state};
$params{scope} = $args{scope} if $args{scope};
$params{immediate} = $args{immediate} if $args{immediate};
if ($args{extra}) {
for my $key ( keys %{$args{extra}} ) {
$params{$key} = $args{extra}{$key};
}
}
my $uri = $args{uri}
|| $self->{authorize_uri}
|| Carp::croak "uri not found";
$uri = URI->new($uri);
$uri->query_form(%params);
return $uri->as_string;
}
=head2 get_access_token( %params )
execute verification,
and returns L<OAuth::Lite2::Client::Token> object.
=over 4
=item code
Authorization-code that is issued beforehand by server
=item redirect_uri
The URL that has used for user authorization's callback
=back
=cut
sub get_access_token {
my $self = shift;
my %args = Params::Validate::validate(@_, {
code => 1,
redirect_uri => 1,
server_state => { optional => 1 },
uri => { optional => 1 },
use_basic_schema => { optional => 1 },
# secret_type => { optional => 1 },
# format => { optional => 1 },
});
unless (exists $args{uri}) {
$args{uri} = $self->{access_token_uri}
|| Carp::croak "uri not found";
}
# $args{format} ||= $self->{format};
my %params = (
grant_type => 'authorization_code',
code => $args{code},
redirect_uri => $args{redirect_uri},
# format => $args{format},
);
$params{server_state} = $args{server_state} if $args{server_state};
unless ($args{use_basic_schema}){
$params{client_id} = $self->{id};
$params{client_secret} = $self->{secret};
}
# $params{secret_type} = $args{secret_type}
# if $args{secret_type};
my $content = build_content(\%params);
my $headers = HTTP::Headers->new;
$headers->header("Content-Type" => q{application/x-www-form-urlencoded});
$headers->header("Content-Length" => bytes::length($content));
$headers->authorization_basic($self->{id}, $self->{secret})
if($args{use_basic_schema});
my $req = HTTP::Request->new( POST => $args{uri}, $headers, $content );
my $res = $self->{agent}->request($req);
$self->{last_request} = $req;
$self->{last_response} = $res;
my ($token, $errmsg);
try {
$token = $self->{response_parser}->parse($res);
} catch {
$errmsg = "$_";
};
return $token || $self->error($errmsg);
}
=head2 refresh_access_token( %params )
Refresh access token by refresh_token,
returns L<OAuth::Lite2::Client::Token> object.
=over 4
=item refresh_token
=back
=cut
sub refresh_access_token {
my $self = shift;
my %args = Params::Validate::validate(@_, {
refresh_token => 1,
# secret_type => { optional => 1 },
# format => { optional => 1 },
uri => { optional => 1 },
use_basic_schema => { optional => 1 },
});
unless (exists $args{uri}) {
$args{uri} = $self->{access_token_uri}
|| Carp::croak "uri not found";
}
# $args{format} ||= $self->{format};
my %params = (
grant_type => 'refresh_token',
refresh_token => $args{refresh_token},
# format => $args{format},
);
unless ($args{use_basic_schema}){
$params{client_id} = $self->{id};
$params{client_secret} = $self->{secret};
}
# $params{secret_type} = $args{secret_type}
# if $args{secret_type};
my $content = build_content(\%params);
my $headers = HTTP::Headers->new;
$headers->header("Content-Type" => q{application/x-www-form-urlencoded});
$headers->header("Content-Length" => bytes::length($content));
$headers->authorization_basic($self->{id}, $self->{secret})
if($args{use_basic_schema});
my $req = HTTP::Request->new( POST => $args{uri}, $headers, $content );
my $res = $self->{agent}->request($req);
$self->{last_request} = $req;
$self->{last_response} = $res;
my ($token, $errmsg);
try {
$token = $self->{response_parser}->parse($res);
} catch {
$errmsg = "$_";
};
return $token || $self->error($errmsg);
}
=head2 get_server_state
Obtain L<OAuth::Lite2::Client::ServerState> object.
=cut
sub get_server_state {
my $self = shift;
my %args = Params::Validate::validate(@_, {
uri => { optional => 1 },
});
unless (exists $args{uri}) {
$args{uri} = $self->{access_token_uri}
|| Carp::croak "uri not found";
}
my %params = (
grant_type => 'server_state',
client_id => $self->{id},
);
my $content = build_content(\%params);
my $headers = HTTP::Headers->new;
$headers->header("Content-Type" => q{application/x-www-form-urlencoded});
$headers->header("Content-Length" => bytes::length($content));
my $req = HTTP::Request->new( POST => $args{uri}, $headers, $content );
my $res = $self->{agent}->request($req);
$self->{last_request} = $req;
$self->{last_response} = $res;
my ($state, $errmsg);
try {
$state = $self->{state_response_parser}->parse($res);
} catch {
$errmsg = "$_";
};
return $state || $self->error($errmsg);
}
=head2 last_request
Returns a HTTP::Request object that is used
when you obtain or refresh access token last time internally.
=head2 last_request
Returns a HTTP::Response object that is used
when you obtain or refresh access token last time internally.
=cut
sub last_request { $_[0]->{last_request} }
sub last_response { $_[0]->{last_response} }
=head1 AUTHOR
Ryo Ito, E<lt>ritou.06@gmail.comE<gt>
Lyo Kato, E<lt>lyo.kato@gmail.comE<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2010 by Lyo Kato
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.8 or,
at your option, any later version of Perl 5 you may have available.
=cut
1;
| movabletype/mt-plugin-google-openid-connect | plugins/GoogleOpenIDConnect/extlib/OAuth/Lite2/Client/WebServer.pm | Perl | mit | 11,446 |
use 5.022;
{
package Table;
use Moose;
use namespace::autoclean;
has '_drinks' => (
is => 'rw',
isa => 'ArrayRef',
default => sub { []; },
);
has 'strategy' => (
is => 'rw',
isa => 'BillingStrategy',
);
sub add {
my $self = shift;
my ($p,$q) = (shift, shift);
my @drinks = @{$self->_drinks};
push @drinks, $self->strategy->get_actual_price($p * $q);
$self->_drinks(\@drinks);
}
sub report {
my $self = shift;
my $sum = 0;
my @drinks = @{$self->_drinks};
for my $i (@drinks) {
$sum += $i;
}
say "Total due: " . sprintf("%.2f", $sum);
$self->_drinks([]);
}
sub set_strategy {
my $self = shift;
my $strategy = shift;
$self->strategy($strategy);
}
__PACKAGE__->meta->make_immutable;
}
{
package BillingStrategy;
use Moose::Role;
requires qw(get_actual_price);
}
{
package NormalStrategy;
use Moose;
with 'BillingStrategy';
sub get_actual_price {
my $self = shift;
my $raw = shift;
return($raw);
}
}
{
package HappyHourStrategy;
use Moose;
with 'BillingStrategy';
sub get_actual_price {
my $self = shift;
my $raw = shift;
return($raw * 0.50);
}
}
my $a = Table->new(strategy => NormalStrategy->new);
$a->add(5.60, 1);
$a->set_strategy(HappyHourStrategy->new);
$a->add(2.99, 2);
my $b = Table->new(strategy => HappyHourStrategy->new);
$b->add(6.40, 2);
$b->add(5.60, 1);
$b->report;
$a->report;
$b->add(5.60, 2);
$b->add(2.99, 1);
$b->report; | jmcveigh/perl-design-patterns | BehavioralPatterns/StrategyPattern.pl | Perl | mit | 1,769 |
##############################################################################
# $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/distributions/Perl-Critic/lib/Perl/Critic/Policy/ValuesAndExpressions/ProhibitSpecialLiteralHeredocTerminator.pm $
# $Date: 2012-07-02 22:16:39 -0700 (Mon, 02 Jul 2012) $
# $Author: thaljef $
# $Revision: 4126 $
##############################################################################
package Perl::Critic::Policy::ValuesAndExpressions::ProhibitSpecialLiteralHeredocTerminator;
use 5.006001;
use strict;
use warnings;
use Readonly;
use Perl::Critic::Utils qw{ :severities };
use base 'Perl::Critic::Policy';
our $VERSION = '1.118';
#-----------------------------------------------------------------------------
Readonly::Hash my %SPECIAL_LITERAL => map { '__' . $_ . '__' => 1 }
qw( FILE LINE PACKAGE END DATA );
Readonly::Scalar my $DESC =>
q{Heredoc terminator must not be a special literal};
#-----------------------------------------------------------------------------
sub supported_parameters { return () }
sub default_severity { return $SEVERITY_MEDIUM }
sub default_themes { return qw(core maintenance) }
sub applies_to { return 'PPI::Token::HereDoc' }
#-----------------------------------------------------------------------------
sub violates {
my ( $self, $elem, undef ) = @_;
# remove << and (optional) quotes from around terminator
( my $heredoc_terminator = $elem ) =~
s{ \A << \s* (["']?) (.*) \1 \z }{$2}xms;
if ( $SPECIAL_LITERAL{ $heredoc_terminator } ) {
my $expl = qq{Used "$heredoc_terminator" as heredoc terminator};
return $self->violation( $DESC, $expl, $elem );
}
return; #ok!
}
1;
__END__
#-----------------------------------------------------------------------------
=pod
=head1 NAME
Perl::Critic::Policy::ValuesAndExpressions::ProhibitSpecialLiteralHeredocTerminator - Don't write C< print <<'__END__' >.
=head1 AFFILIATION
This Policy is part of the core L<Perl::Critic|Perl::Critic>
distribution.
=head1 DESCRIPTION
Using one of Perl's special literals as a HEREDOC terminator could be
confusing to tools that try to parse perl.
print <<'__END__'; #not ok
Hello world
__END__
print <<'__END_OF_WORLD__'; #ok
Goodbye world!
__END_OF_WORLD__
The special literals that this policy prohibits are:
=over
=item __END__
=item __DATA__
=item __PACKAGE__
=item __FILE__
=item __LINE__
=back
=head1 CONFIGURATION
This Policy is not configurable except for the standard options.
=head1 SEE ALSO
L<Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator|Perl::Critic::Policy::ValuesAndExpressions::RequireUpperCaseHeredocTerminator>
L<Perl::Critic::Policy::ValuesAndExpressions::RequireQuotedHeredocTerminator|Perl::Critic::Policy::ValuesAndExpressions::RequireQuotedHeredocTerminator>
=head1 AUTHOR
Kyle Hasselbacher <kyle@cpan.org>
=head1 COPYRIGHT
Copyright (c) 2009-2011 Kyle Hasselbacher.
This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. The full text of this license
can be found in the LICENSE file included with this module.
=cut
# Local Variables:
# mode: cperl
# cperl-indent-level: 4
# fill-column: 78
# indent-tabs-mode: nil
# c-indentation-style: bsd
# End:
# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :
| amidoimidazol/bio_info | Beginning Perl for Bioinformatics/lib/Perl/Critic/Policy/ValuesAndExpressions/ProhibitSpecialLiteralHeredocTerminator.pm | Perl | mit | 3,536 |
use strict;
use warnings;
require 'Configuration/Config.pl';
use vars qw($loginConfig $gameConfig $redeemConfig $dbConfig);
use Module::Find;
use Utils::Tools;
use Utils::Logger;
use Utils::Crypt;
use Drivers::Mysql;
use Drivers::Sock;
use Misc::Crumbs;
use Server::Centre::PluginBase;
usesub Server::Systems;
usesub Server::Plugins;
# Dont uncomment until further notice
#use ServerGames::Manager;
#use Server::Games::Gaming;
#use server::Games::Tables;
use Server::ClubPenguin;
use Server::CPUser;
my $objLoginServer = ClubPenguin->new($loginConfig, $dbConfig);
my $objGameServer = ClubPenguin->new($gameConfig, $dbConfig);
my $objRedeemServer = ClubPenguin->new($redeemConfig, $dbConfig);
$objLoginServer->initializeSource();
$objGameServer->initializeSource();
$objRedeemServer->initializeSource();
while (1) {
$objLoginServer->{modules}->{base}->serverLoop();
$objGameServer->{modules}->{base}->serverLoop();
$objRedeemServer->{modules}->{base}->serverLoop();
} | lake-icp/Luna | Run.pm | Perl | mit | 1,000 |
# This file is auto-generated by the Perl DateTime Suite time zone
# code generator (0.07) This code generator comes with the
# DateTime::TimeZone module distribution in the tools/ directory
#
# Generated from /tmp/BU3Xn7v6Kb/asia. Olson data version 2015g
#
# Do not edit this file directly.
#
package DateTime::TimeZone::Asia::Dubai;
$DateTime::TimeZone::Asia::Dubai::VERSION = '1.94';
use strict;
use Class::Singleton 1.03;
use DateTime::TimeZone;
use DateTime::TimeZone::OlsonDB;
@DateTime::TimeZone::Asia::Dubai::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' );
my $spans =
[
[
DateTime::TimeZone::NEG_INFINITY, # utc_start
60557746728, # utc_end 1919-12-31 20:18:48 (Wed)
DateTime::TimeZone::NEG_INFINITY, # local_start
60557760000, # local_end 1920-01-01 00:00:00 (Thu)
13272,
0,
'LMT',
],
[
60557746728, # utc_start 1919-12-31 20:18:48 (Wed)
DateTime::TimeZone::INFINITY, # utc_end
60557761128, # local_start 1920-01-01 00:18:48 (Thu)
DateTime::TimeZone::INFINITY, # local_end
14400,
0,
'GST',
],
];
sub olson_version {'2015g'}
sub has_dst_changes {0}
sub _max_year {2025}
sub _new_instance {
return shift->_init( @_, spans => $spans );
}
1;
| rosiro/wasarabi | local/lib/perl5/DateTime/TimeZone/Asia/Dubai.pm | Perl | mit | 1,210 |
#########################################################
package AnyData::Format::Ini;
#########################################################
# copyright (c) 2000, Jeff Zucker <jeff@vpservices.com>
# all rights reserved
#########################################################
=head1 NAME
AnyData::Format::Ini - tiedhash & DBI/SQL access to ini files
=head1 SYNOPSIS
use AnyData;
my $table = adHash( 'Ini', $filename,'r',$flags );
while (my $row = each %$table) {
print $row->{name},"\n" if $row->{country} =~ /us|mx|ca/;
}
# ... other tied hash operations
OR
use DBI
my $dbh = DBI->connect('dbi:AnyData:');
$dbh->func('table1','Init', $filename,$flags,'ad_catalog');
my $hits = $dbh->selectall_arrayref( qq{
SELECT name FROM table1 WHERE country = 'us'
});
# ... other DBI/SQL operations
=head1 DESCRIPTION
This is a parser for simple name=value style Ini files. Soon it will also handle files with sections.
Please refer to the documentation for AnyData.pm and DBD::AnyData.pm
for further details.
=head1 AUTHOR & COPYRIGHT
copyright 2000, Jeff Zucker <jeff@vpservices.com>
all rights reserved
=cut
use AnyData::Format::CSV;
use strict;
use vars qw/@ISA $VERSION/;
@ISA = qw(AnyData::Format::CSV);
$VERSION = '0.05';
sub new {
my $class = shift;
my $flags = shift || {};
$flags->{field_sep} ||= '=';
my $self = AnyData::Format::CSV::->new( $flags );
return bless $self, $class;
}
sub write_fields {
my($self,$key,$value) = @_;
return undef unless $key;
$value ||= '';
return "$key = $value" . $self->{record_sep};
}
sub read_fields {
my $self = shift;
my $str = shift || return undef;
$str =~ s/^\s+//;
$str =~ s/\s+$//;
return undef unless $str;
my @fields = $str =~ /^([^=]*?)\s*=\s*(.*)/;
die "Couldn't parse line '$str'\n" unless defined $fields[0];
return( @fields );
}
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/AnyData/Format/Ini.pm | Perl | mit | 1,897 |
/* <module>
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Both A Bottom Up and Top Down Chart Parser
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% from the book "Natural Language Processing in Prolog" %
% published by Addison Wesley %
% Copyright (c) 1989, Gerald Gazdar & Christopher Mellish. %
% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
% Logicmoo Project PrologMUD: A MUD server written in Prolog
% Maintainer: Douglas Miles
% Dec 13, 2035
%
*/
:-module(parser_chart89, [chart89/0,test_chart89_regressions/0]).
% :- ensure_loaded(logicmoo(mpred/logicmoo_i_header)).
% :- baseKB:ensure_loaded(library(bugger)).
% :- register_module_type(utility).
:- style_check(+discontiguous).
:- baseKB:call(op(0,xfx,'/')).
:- baseKB:call(op(0,fx,'-')).
:- baseKB:call(op(200,fy,'-')).
:- baseKB:call(op(500,yfx,'-')).
:- baseKB:call(op(600,xfy,':')).
:- baseKB:call(op(400,yfx,'/')).
:- asserta((t_l:enable_src_loop_checking)).
:-multifile(baseKB:type_action_info/3).
:-multifile(baseKB:agent_call_command/2).
:-multifile(baseKB:mud_test/2).
% ===========================================================
% CHART89 command
% ===========================================================
baseKB:type_action_info(tHumanControlled,chart89(ftListFn(ftTerm)),"Development test CHART-89 Text for a human. Usage: CHART89 Cant i see the blue backpack?").
baseKB:agent_call_command(_Gent,chart89([])):- chart89.
baseKB:agent_call_command(_Gent,chart89(StringM)):-nonvar(StringM), chart89(StringM).
% its i do that much with my numbers.. i avoid calling is/2 until its needed (i can build up
% ===========================================================
% CHART89 REPL
% ===========================================================
:-thread_local t_l:chart89_interactive/0.
chart89 :- locally(tracing80,
locally(t_l:chart89_interactive,
with_no_assertions(t_l:useOnlyExternalDBs,
with_no_assertions(lmconf:use_cyc_database,
(told, repeat, prompt_read('CHART89> ',U),
into_lexical_segs(U,WL),((WL==[bye];WL==[end,'_',of,'_',file];(mmake,once(chart89(WL)),fail)))))))).
:- thread_local(t_l:into_form_code/0).
:- asserta(t_l:into_form_code).
% :- ensure_loaded(logicmoo(parsing/chart89/dcgtrans)). % generator
:- include(chart89/buchart2). % toplevel
%:-export(test_chart89_regressions/0).
test_chart89_regressions:- time((test1,test2)).
:- retract(t_l:into_form_code).
:- retractall(t_l:enable_src_loop_checking).
baseKB:mud_test(chart89_regressions,test_chart89_regressions).
% :- context_module(CM),module_predicates_are_exported(CM).
% :- context_module(CM),quiet_all_module_predicates_are_transparent(CM).
% :- context_module(CM),module_property(CM, exports(List)),moo_hide_show_childs(List).
% :- ensure_loaded(logicmoo('vworld/moo_footer.pl')).
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/prolog/logicmoo_nlu/parser_chart89.pl | Perl | mit | 2,992 |
% This was an assignment that i did for the PL class (2013) for a friend.
% It is a graph-search-related, optimization problem - i don't remember what it actually does (!)
% but it was well optimized - basically, i do a tree-pruning on the search space
% based on some restrictions that applied to the specific problem.
% Run: provata("provata1.txt",L).
provata(File,MinCost):- read_tasos(File,Stanes,Provata,Source,Dest), lleutheia(Stanes,Lstanes), eutheia(Provata,Lprovata),
start(Lstanes,[Lprovata],Source,Dest,Stanes,Lmiki), min_list(Lmiki,Min_mikos), MinCost is (Provata*2)+(Min_mikos*3).
% ftiaxnei to tree_search ksekinontas apo kathe Stani.
start([Riza|Rest],LEE,S,D,Stanes,[Mikos|T]):- search_tree([Riza],LEE,[[]],S,D,Stanes,Mikos), start(Rest,LEE,S,D,Stanes,T).
start([],_,_,_,_,[]).
% ftaixnei to tree siga siga kanei load unload se kathe diadromi, kanei pruning, kai sto telos bgazei
% to mikos tou mikroterou monopatiou pou eftase proto se [] lista LEE,
% dld o Tasos afise ola ta probata kai teliose tin douleia tou!
search_tree(Level,LEE,LPlati,S,D,Stanes,Mikos):- work_level(Level,LEE,LNEE,LPlati,NLPlati,S,D), check_empty(LNEE,Check),
(Check =:= 1 -> bres_miki(LNEE,K), nth1(Thesi,K,0), nth1(Thesi,Level,Kombos), length(Kombos,Mikos) ;
adeiasma(LNEE,EE,NLPlati,NP,Level,NLevel), expand_tree(NLevel,L,EE,E,NP,P,Stanes), search_tree(L,E,P,S,D,Stanes,Mikos)).
% kanoume kata platos 'work' sto dentro.
work_level([HKombos|TKombos],[HE|TE],[HNEE|TNEE],[HPlati|TPlati],[HNPlati|TNPlati],S,D):-
work(HKombos,HE,HNEE,HPlati,HNPlati,S,D), work_level(TKombos,TE,TNEE,TPlati,TNPlati,S,D).
work_level([],[],[],[],[],_,_).
% i work douleuei apokleistika me kathe enan kombo ksexorista kai tou kanei unload+load!!!
% work([1,3],[1,2,3,4],NEE,[1,2],NPlati,[1,1,2,3],[2,3,1,2]).
% NEE = [1, 3, 4],
% NPlati = [1, 4].
work(Kombos,E,NEE,Plati,NPlati,S,D):- last(Kombos,Stani), unload(Plati,D,Stani,Poia), reverse(Poia,P),
append(NNPlati,P,Plati), deli(E,Poia,NEE), ksana(Kombos,Bool), load(NNPlati,S,Stani,NPlati,1,Bool).
% Bool = 1 an to last tis L ksanaemfanizetai, eidallos Bool = 0.
ksana(L,Bool):- last(L,Last), check_ksana(L,Last,Bool).
% elegxei an iparcei to teleuteo xtoixeio mias listas kapou allou mesa tis, dld:
% check_ksana([1,1,3],3,L) -> L = 0.
% check_ksana([3,1,3],3,L) -> L = 1.
check_ksana([_],_,0):-!.
check_ksana([H|T],Last,Bool):- (H =\= Last -> check_ksana(T,Last,Bool) ; Bool = 1).
% diegrapse ola ta stoixeia tis listas [H|T] apo tin lista E.
deli(E,[H|T],NEE):- delete(E,H,L), deli(L,T,NEE).
deli(E,[],E).
% ftiaxnei tin nea plati tou Tasou me probata pou exoun os Source([H|T]) tin Stani.(panta:Thesi=1)
% AN I TELEUTEA PARAMETROS EINAI 0 SIMAINEI OTI PROTI FORA SINANTAO TIN STANI AUTI OPOTE KANO LOAD
% ALLIOS MENEI I PLATI TOU TASOU OS EXEI (1).
% p.x.: load([],[1,1,2,3],1,NPL,1,0) -> NPL = [1, 2].
load(Plati,[H|T],Stani,NPlati,Thesi,0):- NThesi is Thesi+1, (H =:= Stani -> append(Plati,[Thesi],NNPlati),
load(NNPlati,T,Stani,NPlati,NThesi,0) ; load(Plati,T,Stani,NPlati,NThesi,0)).
load(P,[],_,P,_,0).
load(P,_,_,P,_,1).
% unload([1,2,3,4],[2,3,1,2],1,P) -> P = [] kai: unload([1,2,3],[2,3,1,2],1,P) -> P = [3].
% unload([1,2],[2,3,1,2],3,P) -> P = [2].
unload(Plati,D,Stani,Poia):- last(Plati,Provato), nth1(Provato,D,DStani), append(L,[Provato],Plati),
(Stani =:= DStani -> Poia = [Provato|T], unload(L,D,Stani,T) ; unload([],D,Stani,Poia)).
unload([],_,_,[]).
% elegxei an iparxei keni lista mesa stis listes:
check_empty([H|T],Check):- (H = [] -> Check = 1 ; check_empty(T,Check)).
check_empty([],0).
% pairnei tin lista me ta probata pou exoun minei apo ta arxika - se na bathos dentrou - mazi
% me tin lista apo Plates tou Tasou kai ta antoistoixa tree_nodes (os listes)
% kai paragei ta nea pou tha sinexisoun!
% adeiasma([[1,2,3,4],[1,2,3],[2,3,4]],LL,[[],[1,2],[2,3]],NP,[[1,2],[1,3],[1,4]],NT).
% LL = [[1, 2, 3], [2, 3, 4]],
% NP = [[1, 2], [2, 3]],
% NT = [[1, 3], [1, 4]]
adeiasma(L,LL,LPlati,NLPlati,Oldtree,Newtree):- min_lista(L,Thesi), del(L,Thesi,LL), del(LPlati,Thesi,NLPlati),
del(Oldtree,Thesi,Newtree).
% ftiaxnei lista me ta stoixeia pou einai stis theseis [H|T].
del(L,[H|T],LL):- nth1(H,L,A), LL=[A|Tail], del(L,T,Tail).
del(_,[],[]).
% epistrefei ton pinaka me tis theseis ton elaxiston se mikos liston tis listas apo listes L!
% min_lista([[1,2],[3,4],[1,2,3,4],[2,3]],L) -> L = [1, 2, 4].
min_lista(L,Thesi):- bres_miki(L,LL), min_list(LL,Min), length(LL,MM), bres_min_theseis(LL,Min,Thesi,MM,1).
% briskei tis theseis ton elaxiston [H|T] dld ton timon = Min.
% bres_min_theseis([1,2,1,4,6,5,1,3,4],1:to elaxisto pou emfanizetai stin lista,T,9:mikos_listas,1:panta) => T = [1, 3, 7].
bres_min_theseis([H|T],Min,Thesi,Mikos,Th):- Mikos>=Th, NTh is Th+1, (H =:= Min -> Thesi = [Th|Tail], bres_min_theseis(T,Min,Tail,Mikos,NTh)
; bres_min_theseis(T,Min,Thesi,Mikos,NTh)).
bres_min_theseis([],_,[],Mikos,Th):- Mikos < Th.
% briskei ta miki ton liston : bres_miki([[],[1,2,3],[2],[4,4,4,4,4]],K).
% K = [0, 3, 1, 5].
bres_miki([H|T],[A|B]):- length(H,A), bres_miki(T,B).
bres_miki([],[]).
% ftiaxnei tous kombous tou tree enos epomenou "bathmou" maz ime tis listes liston tis platis tou Tasou
% kai ton probaton pou exoun meinei(E).
% expand_tree([[1,2],[1,3]],L,[[1,2,3,4],[1,3,4]],K,[[],[1]],P,3).
% L = [[1, 2, 3], [1, 2, 1], [1, 3, 2], [1, 3, 1]],
% K = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 3, 4], [1, 3, 4]],
% P = [[], [], [1], [1]] ;
expand_tree([HNLevel|TNLevel],L,[HEE|TEE],E,[HNP|TNP],P,Stanes):- filla(HNLevel,K,Stanes), length(K,Len),
make(Len,HEE,NEE), make(Len,HNP,NNP), expand_tree(TNLevel,LL,TEE,LEE,TNP,LP,Stanes), append(K,LL,L),
append(NEE,LEE,E), append(NNP,LP,P).
expand_tree([],[],[],[],[],[],_).
make(Len,K,[K|T]):- Len > 0, L is Len-1, make(L,K,T).
make(0,_,[]).
% ftiaxnei tous kombous tou tree enos epomenou "bathmou"
% p.x. tree([[1]],L,3) -> L = [[1, 3], [1, 2]] ;
% tree([H|T],LL,N):- filla(H,HH,N), tree(T,LLL,N), append(HH,LLL,LL).
% tree([],[],_).
% ftiaxnei ta filla enos kombou L enos dentrou me N-1 filla ana kombo, dld
% o kombos [1,2,3,2] me N=4 exei gia paidia: [1,2,3,2,1],[1,2,3,2,3],[1,2,3,2,4]
filla(L,LL,N):- N>0, last(L,A), NN is N-1,(A =\= N -> LL=[H|T], append(L,[N],H), filla(L,T,NN) ; filla(L,LL,NN)).
filla(_,[],0).
% ftiaxnei anapoda mia lista, dld [5,4,3,2,1] gia N=5.
create(N,[N|T]):- N>0, NN is N-1, create(NN,T).
create(0,[]).
% kanei oti kai i create alla me listes liston!
llcreate(N,[[N]|T]):- N>0, NN is N-1, llcreate(NN,T).
llcreate(0,[]).
% kanei oti kai i eutheia(N,L) alla me listes liston!
lleutheia(N,L):- llcreate(N,LL), reverse(LL,L).
% ftiaxnei kanonika mia lista, dld [1,2,3] gia N=3.
eutheia(N,L):- create(N,LL), reverse(LL,L).
read_tasos(File,Stanes,Provata,S,D):-
open(File,read,Stream), read_line(Stream,[Stanes,Provata]),
read_more(Provata,S,D,Stream),
close(Stream).
read_more(Provata,[H1|T1],[H2|T2],Stream):- Provata > 0, read_line(Stream,[H1,H2]), NProvata is Provata-1, read_more(NProvata,T1,T2,Stream).
read_more(0,[],[],_).
/* An auxiliary predicate that reads a line and returns the list of integers that the line contains */
read_line(Stream, List):- read_line_to_codes(Stream, Line), atom_codes(A, Line), atomic_list_concat(As,' ', A), maplist(atom_number, As, List). | bblodfon/Prolog | prolog_files/provata.pl | Perl | mit | 7,273 |
package Handlers;
use lib '/';
use Plex::Compiler;
use Plex::Lexer;
local $/ = undef;
my $lex = Plex::Lexer->new();
sub html_handler {
my (undef, $file) = @_;
open(HTML, $file);
my $retr = <HTML>;
close (HTML);
return $retr;
}
sub plex_handler {
my (undef, $file, $c, $r) = @_;
my %ARGS;
$ARGS{'REMOTE_ADDR'} = $c->peerhost if defined $c;
$ARGS{'QUERY_STRING'} = $r->url->equery if defined $r;
$lex->read_file( $file );
$lex->lex();
my $comp = Plex::Compiler->new(%{$lex->{tokens}}, %ARGS);
$comp->compile();
$comp->execute();
return $comp->{out};
}
sub image_handler {
my (undef, $file) = @_;
open(IMAGE, $file);
my $retr = <IMAGE>;
close (IMAGE);
return $retr;
}
sub js_handler {
my (undef, $file) = @_;
open(JS, $file);
my $retr = <JS>;
close (JS);
return $retr;
}
sub flash_handler {
my (undef, $file) = @_;
open(FLASH, $file);
my $retr = <FLASH>;
close (FLASH);
return $retr;
}
1;
| zulla/plex | src/Handlers.pm | Perl | mit | 1,015 |
#!/gsc/bin/perl
#takes two files:
#arg0 = copy number file - standard 5-column CBS output (chr, start, stop, num.probes, seg.mean)
#arg1 = bed file containing "blocked" gene names and positions (chr, start, stop, geneName)
# where blocked means one line per gene - start of gene to end of gene
#outputs original CN calls with comma-separated gene names appended
#
#assumes that bedtools is installed
use warnings;
use strict;
use IO::File;
`intersectBed -a $ARGV[0] -b $ARGV[1] -wao >$ARGV[0].geneint`;
my %cnHash;
my $inFh = IO::File->new( "$ARGV[0].geneint" ) || die "can't open file\n";
while( my $line = $inFh->getline )
{
chomp($line);
my @F = split("\t",$line);
my @gene = split(/:/,$F[8]);
$cnHash{join("\t",@F[0..4])}{$gene[0]} = 1;
}
close($inFh);
foreach my $k (keys(%cnHash)){
my @genes;
foreach my $g (keys(%{$cnHash{$k}})){
push(@genes,$g)
}
print $k . "\t" . join(",",@genes) . "\n";
}
| chrisamiller/bioinfoSnippets | annotateCnWithGenes.pl | Perl | mit | 955 |
#
# Copyright 2019 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package database::informix::sql::mode::tablelocks;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use centreon::plugins::misc;
use centreon::plugins::statefile;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments =>
{
"warning-deadlks:s" => { name => 'warning_deadlks', },
"critical-deadlks:s" => { name => 'critical_deadlks', },
"warning-lockwts:s" => { name => 'warning_lockwts', },
"critical-lockwts:s" => { name => 'critical_lockwts', },
"warning-lockreqs:s" => { name => 'warning_lockreqs', },
"critical-lockreqs:s" => { name => 'critical_lockreqs', },
"warning-lktouts:s" => { name => 'warning_lktouts', },
"critical-lktouts:s" => { name => 'critical_lktouts', },
"name:s" => { name => 'name', },
"regexp" => { name => 'use_regexp' },
"filter-tables:s" => { name => 'filter_tables' },
"only-databases" => { name => 'only_databases' },
});
$self->{statefile_cache} = centreon::plugins::statefile->new(%options);
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (($self->{perfdata}->threshold_validate(label => 'warning-deadlks', value => $self->{option_results}->{warning_deadlks})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning-deadlks threshold '" . $self->{option_results}->{warning_deadlks} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical-deadlks', value => $self->{option_results}->{critical_deadlks})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical-deadlks threshold '" . $self->{option_results}->{critical_deadlks} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'warning-lockwts', value => $self->{option_results}->{warning_lockwts})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning-lockwts threshold '" . $self->{option_results}->{warning_lockwts} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical-lockwts', value => $self->{option_results}->{critical_lockwts})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical-lockwts threshold '" . $self->{option_results}->{critical_lockwts} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'warning-lockreqs', value => $self->{option_results}->{warning_lockreqs})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning-lockreqs threshold '" . $self->{option_results}->{warning_lockreqs} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical-lockreqs', value => $self->{option_results}->{critical_lockreqs})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical-lockreqs threshold '" . $self->{option_results}->{critical_lockreqs} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'warning-lktouts', value => $self->{option_results}->{warning_block})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong warning-lktouts threshold '" . $self->{option_results}->{warning_block} . "'.");
$self->{output}->option_exit();
}
if (($self->{perfdata}->threshold_validate(label => 'critical-lktouts', value => $self->{option_results}->{critical_lktouts})) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong critical-lktouts threshold '" . $self->{option_results}->{critical_lktouts} . "'.");
$self->{output}->option_exit();
}
$self->{statefile_cache}->check_options(%options);
}
sub run {
my ($self, %options) = @_;
# $options{sql} = sqlmode object
$self->{sql} = $options{sql};
$self->{sql}->connect();
my $query = q{
SELECT dbsname, tabname, deadlks, lockwts, lockreqs, lktouts FROM sysptprof
ORDER BY dbsname, tabname
};
$self->{sql}->query(query => $query);
$self->{output}->output_add(severity => 'OK',
short_msg => 'All database/table locks are ok');
my $new_datas = {};
$self->{statefile_cache}->read(statefile => 'informix_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save());
my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp');
$new_datas->{last_timestamp} = time();
my $count = 0;
my $db_found = {};
while ((my $row = $self->{sql}->fetchrow_hashref())) {
my $dbname = centreon::plugins::misc::trim($row->{dbsname});
my $tabname = centreon::plugins::misc::trim($row->{tabname});
my $longname = $dbname . '.' . $tabname;
next if (defined($self->{option_results}->{name}) && !defined($self->{option_results}->{use_regexp}) && $dbname ne $self->{option_results}->{name});
next if (defined($self->{option_results}->{name}) && defined($self->{option_results}->{use_regexp}) && $dbname !~ /$self->{option_results}->{name}/);
next if (defined($self->{option_results}->{filter_tables}) && $longname !~ /$self->{option_results}->{filter_tables}/);
$count++;
my $old_datas = {};
my $get_old_value = 0;
$db_found->{$dbname} = {deadlks => 0, lockwts => 0, lockreqs => 0, lktouts => 0, process => 0} if (!defined($db_found->{$dbname}));
foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
$new_datas->{$dbname . '_' . $_} = 0 if (!defined($new_datas->{$dbname . '_' . $_}));
$new_datas->{$dbname . '_' . $_} += $row->{$_};
$new_datas->{$longname . '_' . $_} = $row->{$_};
$old_datas->{$longname . '_' . $_} = $self->{statefile_cache}->get(name => $longname . '_' . $_);
# Restart or onstat -z - we set to 0
$old_datas->{$longname . '_' . $_} = 0 if (defined($old_datas->{$longname . '_' . $_}) && $old_datas->{$longname . '_' . $_} > $new_datas->{$longname . '_' . $_});
# If we have a buffer or not
if (defined($old_datas->{$longname . '_' . $_})) {
$get_old_value = 1;
$db_found->{$dbname}->{$_} += $old_datas->{$longname . '_' . $_};
}
}
# Buffer needed
next if ($get_old_value == 0 || !defined($old_timestamp));
$db_found->{$dbname}->{process} = 1;
next if ($self->{option_results}->{only_databases});
my $diff = {};
foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
$diff->{$_} = $new_datas->{$longname . '_' . $_} - $old_datas->{$longname . '_' . $_};
}
my $exit1 = $self->{perfdata}->threshold_check(value => $diff->{deadlks}, threshold => [ { label => 'critical-deadlks', 'exit_litteral' => 'critical' }, { label => 'warning-deadlks', exit_litteral => 'warning' } ]);
my $exit2 = $self->{perfdata}->threshold_check(value => $diff->{lockwts}, threshold => [ { label => 'critical-lockwts', 'exit_litteral' => 'critical' }, { label => 'warning-lockwts', exit_litteral => 'warning' } ]);
my $exit3 = $self->{perfdata}->threshold_check(value => $diff->{lockreqs}, threshold => [ { label => 'critical-lockreqs', 'exit_litteral' => 'critical' }, { label => 'warning-lockreqs', exit_litteral => 'warning' } ]);
my $exit4 = $self->{perfdata}->threshold_check(value => $diff->{lktouts}, threshold => [ { label => 'critical-lktouts', 'exit_litteral' => 'critical' }, { label => 'warning-lktouts', exit_litteral => 'warning' } ]);
my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3, $exit4 ]);
$self->{output}->output_add(long_msg => sprintf("Table '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, Lock Timeouts %d",
$longname, $diff->{deadlks}, $diff->{lockwts}, $diff->{lockreqs}, $diff->{lktouts}));
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Table '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, Lock Timeouts %d",
$longname, $diff->{deadlks}, $diff->{lockwts}, $diff->{lockreqs}, $diff->{lktouts}));
}
foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
$self->{output}->perfdata_add(label => 'tbl_' . $_ . '_' . $longname,
value => $diff->{$_},
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $_),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $_),
min => 0);
}
}
foreach my $dbname (keys %{$db_found}) {
next if ($db_found->{$dbname}->{process} == 0);
my $exit1 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_deadlks'} - $db_found->{$dbname}->{deadlks}, threshold => [ { label => 'critical-deadlks', 'exit_litteral' => 'critical' }, { label => 'warning-deadlks', exit_litteral => 'warning' } ]);
my $exit2 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_lockwts'} - $db_found->{$dbname}->{lockwts}, threshold => [ { label => 'critical-lockwts', 'exit_litteral' => 'critical' }, { label => 'warning-lockwts', exit_litteral => 'warning' } ]);
my $exit3 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_lockreqs'} - $db_found->{$dbname}->{lockreqs}, threshold => [ { label => 'critical-lockreqs', 'exit_litteral' => 'critical' }, { label => 'warning-lockreqs', exit_litteral => 'warning' } ]);
my $exit4 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_lktouts'} - $db_found->{$dbname}->{lktouts}, threshold => [ { label => 'critical-lktouts', 'exit_litteral' => 'critical' }, { label => 'warning-lktouts', exit_litteral => 'warning' } ]);
my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3, $exit4 ]);
$self->{output}->output_add(long_msg => sprintf("Database '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, lock timeouts %d",
$dbname,
$new_datas->{$dbname . '_deadlks'} - $db_found->{$dbname}->{deadlks},
$new_datas->{$dbname . '_lockwts'} - $db_found->{$dbname}->{lockwts},
$new_datas->{$dbname . '_lockreqs'} - $db_found->{$dbname}->{lockreqs},
$new_datas->{$dbname . '_lktouts'} - $db_found->{$dbname}->{lktouts}));
if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Database '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, lock timeouts %d",
$dbname,
$new_datas->{$dbname . '_deadlks'} - $db_found->{$dbname}->{deadlks},
$new_datas->{$dbname . '_lockwts'} - $db_found->{$dbname}->{lockwts},
$new_datas->{$dbname . '_lockreqs'} - $db_found->{$dbname}->{lockreqs},
$new_datas->{$dbname . '_lktouts'} - $db_found->{$dbname}->{lktouts}));
}
foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
$self->{output}->perfdata_add(label => 'db_' . $_ . '_' . $dbname,
value => $new_datas->{$dbname . '_' . $_} - $db_found->{$dbname}->{$_},
warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $_),
critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $_),
min => 0);
}
}
if ($count == 0) {
$self->{output}->output_add(severity => 'UNKNOWN',
short_msg => "Cannot find a table (maybe filters).");
}
$self->{statefile_cache}->write(data => $new_datas);
if (!defined($old_timestamp)) {
$self->{output}->output_add(severity => 'OK',
short_msg => "Buffer creation...");
}
$self->{output}->display();
$self->{output}->exit();
}
1;
__END__
=head1 MODE
Check table locks:
- deadlks: deadlocks.
- lockwts: lock waits.
- lockreqs: lock requests.
- lktouts: lock timeouts.
=over 8
=item B<--warning-deadlks>
Threshold warning 'deadlks' in absolute.
=item B<--critical-deadlks>
Threshold critical 'deadlks' in absolute.
=item B<--warning-lockwts>
Threshold warning 'lockwts' in absolute.
=item B<--critical-lockwts>
Threshold critical 'lockwts' in absolute.
=item B<--warning-lockreqs>
Threshold warning 'lockreqs' in absolute.
=item B<--critical-lockreqs>
Threshold critical 'lockreqs' in absolute.
=item B<--warning-lktouts>
Threshold warning 'lktouts' in absolute.
=item B<--critical-lktouts>
Threshold critical 'lktouts' in absolute.
=item B<--name>
Set the database (empty means 'check all databases').
=item B<--regexp>
Allows to use regexp to filter database (with option --name).
=item B<--filter-tables>
Filter tables (format of a table name: 'sysmater.dual').
=item B<--only-databases>
only check locks globally on database (no output for tables).
=back
=cut
| Sims24/centreon-plugins | database/informix/sql/mode/tablelocks.pm | Perl | apache-2.0 | 15,568 |
# German adjectives related to quantities
# @(#) $Id: aj_color.pl 36 2008-09-08 06:05:06Z gfis $
# 2006-06-23, Georg Fischer
# caution, must be stored in UTF-8 encoding: äöüÄÖÜß, output in UTF-8
#
# Copyright 2006 Dr. Georg Fischer <punctum at punctum dot kom>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
use strict;
# binmode(STDOUT, ":utf8");
while (<DATA>) {
next if m/^\#/;
next if m/^\s*$/;
my ($aj,$rgb) = split;
print "$aj\t=AjColr.$rgb\n";
}
__DATA__
rot FF0000
blau 0000FF
grün 008000
gelb FFFF00
schwarz 000000
weiß FFFFFF
grau C0C0C0
violett EE82EE
lila FF00FF
rosa FA8072
# salmon FA8072
blond F5DEB3
# wheat F5DEB3
brünett 800000
# maroon 800000
beige F5F5DC
orange FFA500
braun A52A2A
# seldom:
magenta FF00FF
türkis 40E0D0
ocker F0E68C
# khaki F0E68C
sienna A0522D
oliv 808000
pink FFC0CB
purpur 800080
aquamarin 7FFFD4
| gfis/gramword | dict/Aj/aj_color.pl | Perl | apache-2.0 | 1,621 |
package Paws::Rekognition::Face;
use Moose;
has BoundingBox => (is => 'ro', isa => 'Paws::Rekognition::BoundingBox');
has Confidence => (is => 'ro', isa => 'Num');
has ExternalImageId => (is => 'ro', isa => 'Str');
has FaceId => (is => 'ro', isa => 'Str');
has ImageId => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::Rekognition::Face
=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::Rekognition::Face object:
$service_obj->Method(Att1 => { BoundingBox => $value, ..., ImageId => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::Rekognition::Face object:
$result = $service_obj->Method(...);
$result->Att1->BoundingBox
=head1 DESCRIPTION
Describes the face properties such as the bounding box, face ID, image
ID of the input image, and external image ID that you assigned.
=head1 ATTRIBUTES
=head2 BoundingBox => L<Paws::Rekognition::BoundingBox>
Bounding box of the face.
=head2 Confidence => Num
Confidence level that the bounding box contains a face (and not a
different object such as a tree).
=head2 ExternalImageId => Str
Identifier that you assign to all the faces in the input image.
=head2 FaceId => Str
Unique identifier that Amazon Rekognition assigns to the face.
=head2 ImageId => Str
Unique identifier that Amazon Rekognition assigns to the input image.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::Rekognition>
=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/Rekognition/Face.pm | Perl | apache-2.0 | 2,014 |
#
# Copyright 2009-2013 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package MongoDB::BulkWrite;
# ABSTRACT: MongoDB bulk write interface
use version;
our $VERSION = 'v0.707.2.0';
use MongoDB::Error;
use MongoDB::OID;
use MongoDB::WriteResult;
use MongoDB::BulkWriteView;
use Try::Tiny;
use Safe::Isa;
use Syntax::Keyword::Junction qw/any/;
use Moose;
use namespace::clean -except => 'meta';
#pod =attr collection (required)
#pod
#pod The L<MongoDB::Collection> where the operations are to be performed.
#pod
#pod =cut
has 'collection' => (
is => 'ro',
isa => 'MongoDB::Collection',
required => 1,
);
#pod =attr ordered (required)
#pod
#pod A boolean for whether or not operations should be ordered (true) or
#pod unordered (false).
#pod
#pod =cut
has 'ordered' => (
is => 'ro',
isa => 'Bool',
required => 1,
);
has '_executed' => (
is => 'rw',
isa => 'Bool',
init_arg => undef,
default => 0,
);
has '_queue' => (
is => 'rw',
isa => 'ArrayRef[ArrayRef]',
init_arg => undef,
default => sub { [] },
traits => ['Array'],
handles => {
_enqueue_write => 'push',
_all_writes => 'elements',
_count_writes => 'count',
_clear_writes => 'clear',
}
);
has '_database' => (
is => 'ro',
isa => 'MongoDB::Database',
lazy_build => 1,
);
sub _build__database {
my ($self) = @_;
return $self->collection->_database;
}
has '_client' => (
is => 'ro',
isa => 'MongoDB::MongoClient',
lazy_build => 1,
);
sub _build__client {
my ($self) = @_;
return $self->_database->_client;
}
has '_use_write_cmd' => (
is => 'ro',
isa => 'Bool',
lazy_build => 1,
);
sub _build__use_write_cmd {
my ($self) = @_;
return $self->_client->get_master->_use_write_cmd;
}
with 'MongoDB::Role::_WriteQueue';
#pod =method find
#pod
#pod $view = $bulk->find( $query_document );
#pod
#pod The C<find> method returns a L<MongoDB::BulkWriteView> object that allows
#pod write operations like C<update> or C<remove>, constrained by a query document.
#pod
#pod A query document is required. Use an empty hashref for no criteria:
#pod
#pod $bulk->find( {} )->remove; # remove all documents!
#pod
#pod An exception will be thrown on error.
#pod
#pod =cut
sub find {
my ( $self, $doc ) = @_;
confess "find requires a criteria document. Use an empty hashref for no criteria."
unless defined $doc;
unless ( @_ == 2 && ref $doc eq any(qw/HASH ARRAY Tie::IxHash/) ) {
confess "argument to find must be a single hashref, arrayref or Tie::IxHash";
}
if ( ref $doc eq 'ARRAY' ) {
confess "array reference to find must have key/value pairs"
if @$doc % 2;
$doc = {@$doc};
}
return MongoDB::BulkWriteView->new(
query => $doc,
write_queue => $self,
);
}
#pod =method insert
#pod
#pod $bulk->insert( $doc );
#pod
#pod Queues a document for insertion when L</execute> is called. The document may
#pod be a hash reference, an array reference (with balance key/value pairs) or a
#pod L<Tie::IxHash> object. If the document does not have an C<_id> field, one will
#pod be added.
#pod
#pod The method has an empty return on success; an exception will be thrown on error.
#pod
#pod =cut
sub insert {
my ( $self, $doc ) = @_;
unless ( @_ == 2 && ref $doc eq any(qw/HASH ARRAY Tie::IxHash/) ) {
confess "argument to insert must be a single hashref, arrayref or Tie::IxHash";
}
if ( ref $doc eq 'ARRAY' ) {
confess "array reference to insert must have key/value pairs"
if @$doc % 2;
$doc = {@$doc};
}
elsif ( ref $doc eq 'HASH' ) {
$doc = {%$doc}; # shallow copy
}
else {
$doc = Tie::IxHash->new( map {; $_ => $doc->FETCH($_) } $doc->Keys );
$doc->STORE( '_id', MongoDB::OID->new ) unless $doc->EXISTS('_id');
}
if ( ref $doc eq 'HASH' ) {
$doc->{_id} = MongoDB::OID->new unless exists $doc->{_id};
}
$self->_enqueue_write( [ insert => $doc ] );
return;
}
#pod =method execute
#pod
#pod my $result = $bulk->execute;
#pod
#pod Executes the queued operations. The order and semantics depend on
#pod whether the bulk object is ordered or unordered:
#pod
#pod =for :list
#pod * ordered — operations are executed in order, but operations of the same type
#pod (e.g. multiple inserts) may be grouped together and sent to the server. If
#pod the server returns an error, the bulk operation will stop and an error will
#pod be thrown.
#pod * unordered — operations are grouped by type and sent to the server in an
#pod unpredictable order. After all operations are sent, if any errors occurred,
#pod an error will be thrown.
#pod
#pod When grouping operations of a type, operations will be sent to the server in
#pod batches not exceeding 16MiB or 1000 items (for a version 2.6 or later server)
#pod or individually (for legacy servers without write command support).
#pod
#pod This method returns a L<MongoDB::WriteResult> object if the bulk operation
#pod executes successfully.
#pod
#pod Typical errors might include:
#pod
#pod =for :list
#pod * C<MongoDB::WriteError> — one or more write operations failed
#pod * C<MongoDB::WriteConcernError> - all writes were accepted by a primary, but
#pod the write concern failed
#pod * C<MongoDB::DatabaseError> — a command to the database failed entirely
#pod
#pod See L<MongoDB::Error> for more on error handling.
#pod
#pod B<NOTE>: it is an error to call C<execute> without any operations or
#pod to call C<execute> more than once on the same bulk object.
#pod
#pod =cut
my %OP_MAP = (
insert => [ insert => 'documents' ],
update => [ update => 'updates' ],
delete => [ delete => 'deletes' ],
);
sub execute {
my ( $self, $write_concern ) = @_;
if ( $self->_executed ) {
MongoDB::Error->throw("bulk op execute called more than once");
}
else {
$self->_executed(1);
}
$write_concern ||= $self->_client->_write_concern;
my $ordered = $self->ordered;
my $use_write_cmd = $self->_use_write_cmd;
# If using legacy write ops, then there will never be a valid nModified
# result so we set that to undef in the constructor; otherwise, we set it
# to 0 so that results accumulate normally. If a mongos on a mixed cluster
# later fails to set it, results merging will handle it that case.
my $result = MongoDB::WriteResult->new( nModified => $use_write_cmd ? 0 : undef, );
unless ( $self->_count_writes ) {
MongoDB::Error->throw("no bulk ops to execute");
}
for my $batch ( $ordered ? $self->_batch_ordered : $self->_batch_unordered ) {
if ($use_write_cmd) {
$self->_execute_write_command_batch( $batch, $result, $ordered, $write_concern );
}
else {
$self->_execute_legacy_batch( $batch, $result, $ordered, $write_concern );
}
}
# only reach here with an error for unordered bulk ops
$self->_assert_no_write_error($result);
# write concern errors are thrown only for the entire batch
$self->_assert_no_write_concern_error($result);
return $result;
}
# _execute_write_command_batch may split batches if they are too large and
# execute them separately
sub _execute_write_command_batch {
my ( $self, $batch, $result, $ordered, $write_concern ) = @_;
my ( $type, $docs ) = @$batch;
my ( $cmd, $op_key ) = @{ $OP_MAP{$type} };
my $boolean_ordered = $ordered ? boolean::true : boolean::false;
my $coll_name = $self->collection->name;
my @left_to_send = ($docs);
while (@left_to_send) {
my $chunk = shift @left_to_send;
my $cmd_doc = [
$cmd => $coll_name,
$op_key => $chunk,
ordered => $boolean_ordered,
( $write_concern ? ( writeConcern => $write_concern ) : () )
];
my $cmd_result = try {
$self->_database->_try_run_command($cmd_doc);
}
catch {
if ( $_->$_isa("MongoDB::_CommandSizeError") ) {
if ( @$chunk == 1 ) {
MongoDB::DocumentSizeError->throw(
message => "document too large",
document => $chunk->[0],
);
}
else {
unshift @left_to_send, $self->_split_chunk( $chunk, $_->size );
}
}
else {
die $_;
}
return;
};
next unless $cmd_result;
my $r = MongoDB::WriteResult->_parse(
op => $type,
op_count => scalar @$chunk,
result => $cmd_result,
);
# append corresponding ops to errors
if ( $r->count_writeErrors ) {
for my $error ( @{ $r->writeErrors } ) {
$error->{op} = $chunk->[ $error->{index} ];
# convert boolean::true|false back to 1 or 0
for my $k (qw/upsert multi/) {
$error->{op}{$k} = 0+ $error->{op}{$k} if exists $error->{op}{$k};
}
}
}
$result->_merge_result($r);
$self->_assert_no_write_error($result) if $ordered;
}
return;
}
sub _split_chunk {
my ( $self, $chunk, $size ) = @_;
my $max_wire_size = $self->_client->_max_bson_wire_size;
my $avg_cmd_size = $size / @$chunk;
my $new_cmds_per_chunk = int( $max_wire_size / $avg_cmd_size );
my @split_chunks;
while (@$chunk) {
push @split_chunks, [ splice( @$chunk, 0, $new_cmds_per_chunk ) ];
}
return @split_chunks;
}
sub _batch_ordered {
my ($self) = @_;
my @batches;
my $last_type = '';
my $count = 0;
my $max_batch_count = $self->_client->_max_write_batch_size;
for my $op ( $self->_all_writes ) {
my ( $type, $doc ) = @$op;
if ( $type ne $last_type || $count == $max_batch_count ) {
push @batches, [ $type => [$doc] ];
$last_type = $type;
$count = 1;
}
else {
push @{ $batches[-1][-1] }, $doc;
$count++;
}
}
return @batches;
}
sub _batch_unordered {
my ($self) = @_;
my %batches = map { ; $_ => [ [] ] } keys %OP_MAP;
my $max_batch_count = $self->_client->_max_write_batch_size;
for my $op ( $self->_all_writes ) {
my ( $type, $doc ) = @$op;
if ( @{ $batches{$type}[-1] } == $max_batch_count ) {
push @{ $batches{$type} }, [$doc];
}
else {
push @{ $batches{$type}[-1] }, $doc;
}
}
# insert/update/delete are guaranteed to be in random order on Perl 5.18+
my @batches;
for my $type ( grep { scalar @{ $batches{$_}[-1] } } keys %batches ) {
push @batches, map { [ $type => $_ ] } @{ $batches{$type} };
}
return @batches;
}
sub _assert_no_write_error {
my ( $self, $result ) = @_;
if ( my $write_errors = $result->count_writeErrors ) {
MongoDB::WriteError->throw(
message => "writeErrors: $write_errors",
result => $result,
);
}
return;
}
sub _assert_no_write_concern_error {
my ( $self, $result ) = @_;
if ( my $write_concern_errors = $result->count_writeConcernErrors ) {
MongoDB::WriteConcernError->throw(
message => "writeConcernErrors: $write_concern_errors",
result => $result,
);
}
return;
}
# XXX the _execute_legacy_(insert|update|delete) commands duplicate code in
# Collection.pm, but that code is wrapped up in a way that doesn't easily allow
# grabbing result details. We can't parse a response directly because the
# network receive code is tightly coupled to a cursor. These functions work
# around these limitations for the time being
sub _execute_legacy_batch {
my ( $self, $batch, $result, $ordered, $write_concern ) = @_;
my ( $type, $docs ) = @$batch;
my $coll = $self->collection;
my $client = $self->_client;
my $ns = $coll->full_name;
my $method = "_gen_legacy_$type";
# check write_concern with 'eq' for string "0" because write concern can be
# 'majority' or a tag-set and it would be an error to check that with '=='
my $w_0 = defined $write_concern->{w} && $write_concern->{w} eq "0";
for my $doc (@$docs) {
# legacy server doesn't check keys on insert; we fake an error if it happens
if ( $type eq 'insert' && ( my $r = $self->_check_no_dollar_keys($doc) ) ) {
if ($w_0) {
last if $ordered;
}
else {
$result->_merge_result($r);
$self->_assert_no_write_error($result) if $ordered;
}
next;
}
my $op_string = $self->$method( $ns, $doc );
# this isn't quite right; a command should allow a max-sized object plus
# some overhead, but this is consistent with how Collection.pm does it
if ( length($op_string) > $client->max_bson_size ) {
if ($w_0) {
last if $ordered;
}
else {
$result->_merge_result( $self->_fake_doc_size_error($doc) );
$self->_assert_no_write_error($result) if $ordered;
}
next;
}
my $gle_result;
# Even for {w:0}, if the batch is ordered we have to check each result
# and break on the first error, but we don't throw the error to the user.
if ( $ordered || !$w_0 ) {
my $op_result = $coll->_make_safe_cursor( $op_string, $write_concern )->next;
$gle_result = $self->_get_writeresult_from_gle( $type, $op_result, $doc );
last if $w_0 && $gle_result->count_writeErrors;
}
else {
# Fire and forget and mock up an empty result to get the right op count
$client->send($op_string);
$gle_result = MongoDB::WriteResult->_parse(
op => $type,
op_count => 1,
result => { n => 0 },
);
}
$result->_merge_result($gle_result);
$self->_assert_no_write_error($result) if $ordered;
}
return;
}
sub _get_writeresult_from_gle {
my ( $self, $type, $gle, $doc ) = @_;
my ( @writeErrors, $writeConcernError, @upserted );
# Still checking for $err here because it's not yet handled during
# reply unpacking
if ( exists $gle->{'$err'} ) {
MongoDB::DatabaseError->throw(
message => $gle->{'$err'},
result => MongoDB::CommandResult->new( result => $gle ),
);
}
# 'ok' false means GLE itself failed
if ( !$gle->{ok} ) {
MongoDB::DatabaseError->throw(
message => $gle->{errmsg},
result => MongoDB::CommandResult->new( result => $gle ),
);
}
# usually we shouldn't check wnote or jnote, but the Bulk API QA test says we should
# detect no journal or replication not enabled, so we check for special strings.
# These strings were checked back to MongoDB 1.8.5.
if ( exists $gle->{jnote} && $gle->{jnote} =~ /^journaling not enabled/ ) {
MongoDB::DatabaseError->throw(
message => $gle->{jnote},
result => MongoDB::CommandResult->new( result => $gle ),
);
}
if ( exists $gle->{wnote} && $gle->{wnote} =~ /^no replication has been enabled/ ) {
MongoDB::DatabaseError->throw(
message => $gle->{wnote},
result => MongoDB::CommandResult->new( result => $gle ),
);
}
my $affected = 0;
my $errmsg =
defined $gle->{err} ? $gle->{err}
: defined $gle->{errmsg} ? $gle->{errmsg}
: undef;
my $wtimeout = $gle->{wtimeout};
if ($wtimeout) {
my $code = $gle->{code} || WRITE_CONCERN_ERROR;
$writeConcernError = {
errmsg => $errmsg,
errInfo => { wtimeout => $wtimeout },
code => $code
};
}
if ( defined $errmsg && !$wtimeout ) {
my $code = $gle->{code} || UNKNOWN_ERROR;
# index is always 0 because ops are executed individually; later
# merging of results will fix up the index values as usual
my $error_doc = {
errmsg => $errmsg,
code => $code,
index => 0,
op => $doc,
};
# convert boolean::true|false back to 1 or 0
for my $k (qw/upsert multi/) {
$error_doc->{op}{$k} = 0+ $error_doc->{op}{$k} if exists $error_doc->{op}{$k};
}
$error_doc->{errInfo} = $gle->{errInfo} if exists $gle->{errInfo};
push @writeErrors, $error_doc;
}
else {
# GLE: n only returned for update/remove, so we infer it for insert
$affected =
$type eq 'insert' ? 1
: defined $gle->{n} ? $gle->{n}
: 0;
# For upserts, index is always 0 because ops are executed individually;
# later merging of results will fix up the index values as usual. For
# 2.4 and earlier, 'upserted' has _id only if the _id is an OID. Otherwise,
# we have to pick it out of the update document or query document when we
# see updateExisting is false but the number of docs affected is 1
if ( exists $gle->{upserted} ) {
push @upserted, { index => 0, _id => $gle->{upserted} };
}
elsif (exists $gle->{updatedExisting}
&& !$gle->{updatedExisting}
&& $gle->{n} == 1 )
{
my $id = exists $doc->{u}{_id} ? $doc->{u}{_id} : $doc->{q}{_id};
push @upserted, { index => 0, _id => $id };
}
}
my $result = MongoDB::WriteResult->_parse(
op => $type,
op_count => 1,
result => {
n => $affected,
writeErrors => \@writeErrors,
writeConcernError => $writeConcernError,
( @upserted ? ( upserted => \@upserted ) : () ),
},
);
return $result;
}
sub _gen_legacy_insert {
my ( $self, $ns, $doc ) = @_;
# $doc is a document to insert
# for bulk, we don't accumulate IDs
my ( $insert, undef ) = MongoDB::write_insert( $ns, [$doc], 0 );
return $insert;
}
sub _gen_legacy_update {
my ( $self, $ns, $doc ) = @_;
# $doc is { q: $query, u: $update, multi: $multi, upsert: $upsert }
my $flags = 0;
$flags |= 1 << 0 if $doc->{upsert};
$flags |= 1 << 1 if $doc->{multi};
return MongoDB::write_update( $ns, $doc->{q}, $doc->{u}, $flags );
}
sub _gen_legacy_delete {
my ( $self, $ns, $doc ) = @_;
# $doc is { q: $query, limit: $limit }
return MongoDB::write_remove( $ns, $doc->{q}, $doc->{limit} ? 1 : 0 );
}
sub _check_no_dollar_keys {
my ( $self, $doc ) = @_;
my @keys = ref $doc eq 'Tie::IxHash' ? $doc->Keys : keys %$doc;
if ( my @bad = grep { substr( $_, 0, 1 ) eq '$' } @keys ) {
my $errdoc = {
index => 0,
errmsg => "Document can't have '\$' prefixed field names: @bad",
code => UNKNOWN_ERROR
};
return MongoDB::WriteResult->new(
op_count => 1,
nModified => undef,
writeErrors => [$errdoc]
);
}
return;
}
sub _fake_doc_size_error {
my ( $self, $doc ) = @_;
my $errdoc = {
index => 0,
errmsg => "Document too large",
code => UNKNOWN_ERROR
};
return MongoDB::WriteResult->new(
op_count => 1,
writeErrors => [$errdoc]
);
}
__PACKAGE__->meta->make_immutable;
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
MongoDB::BulkWrite - MongoDB bulk write interface
=head1 VERSION
version v0.707.2.0
=head1 SYNOPSIS
use Safe::Isa;
use Try::Tiny;
my $bulk = $collection->initialize_ordered_bulk_op;
$bulk->insert( $doc );
$bulk->find( $query )->upsert->replace_one( $doc )
$bulk->find( $query )->update( $modification )
my $result = try {
$bulk->execute;
}
catch {
if ( $_->$isa("MongoDB::WriteConcernError") ) {
warn "Write concern failed";
}
else {
die $_;
}
};
=head1 DESCRIPTION
This class constructs a list of write operations to perform in bulk for a
single collection. On a MongoDB 2.6 or later server with write command support
this allow grouping similar operations together for transit to the database,
minimizing network round-trips.
To begin a bulk operation, use one these methods from L<MongoDB::Collection>:
=over 4
=item *
L<initialize_ordered_bulk_op|MongoDB::Collection/initialize_ordered_bulk_op>
=item *
L<initialize_unordered_bulk_op|MongoDB::Collection/initialize_unordered_bulk_op>
=back
=head2 Ordered Operations
With an ordered operations list, MongoDB executes the write operations in the
list serially. If an error occurs during the processing of one of the write
operations, MongoDB will return without processing any remaining write
operations in the list.
=head2 Unordered Operations
With an unordered operations list, MongoDB can execute in parallel, as well as
in a nondeterministic order, the write operations in the list. If an error
occurs during the processing of one of the write operations, MongoDB will
continue to process remaining write operations in the list.
=head1 ATTRIBUTES
=head2 collection (required)
The L<MongoDB::Collection> where the operations are to be performed.
=head2 ordered (required)
A boolean for whether or not operations should be ordered (true) or
unordered (false).
=head1 METHODS
=head2 find
$view = $bulk->find( $query_document );
The C<find> method returns a L<MongoDB::BulkWriteView> object that allows
write operations like C<update> or C<remove>, constrained by a query document.
A query document is required. Use an empty hashref for no criteria:
$bulk->find( {} )->remove; # remove all documents!
An exception will be thrown on error.
=head2 insert
$bulk->insert( $doc );
Queues a document for insertion when L</execute> is called. The document may
be a hash reference, an array reference (with balance key/value pairs) or a
L<Tie::IxHash> object. If the document does not have an C<_id> field, one will
be added.
The method has an empty return on success; an exception will be thrown on error.
=head2 execute
my $result = $bulk->execute;
Executes the queued operations. The order and semantics depend on
whether the bulk object is ordered or unordered:
=over 4
=item *
ordered — operations are executed in order, but operations of the same type (e.g. multiple inserts) may be grouped together and sent to the server. If the server returns an error, the bulk operation will stop and an error will be thrown.
=item *
unordered — operations are grouped by type and sent to the server in an unpredictable order. After all operations are sent, if any errors occurred, an error will be thrown.
=back
When grouping operations of a type, operations will be sent to the server in
batches not exceeding 16MiB or 1000 items (for a version 2.6 or later server)
or individually (for legacy servers without write command support).
This method returns a L<MongoDB::WriteResult> object if the bulk operation
executes successfully.
Typical errors might include:
=over 4
=item *
C<MongoDB::WriteError> — one or more write operations failed
=item *
C<MongoDB::WriteConcernError> - all writes were accepted by a primary, but the write concern failed
=item *
C<MongoDB::DatabaseError> — a command to the database failed entirely
=back
See L<MongoDB::Error> for more on error handling.
B<NOTE>: it is an error to call C<execute> without any operations or
to call C<execute> more than once on the same bulk object.
=head1 AUTHORS
=over 4
=item *
David Golden <david.golden@mongodb.org>
=item *
Mike Friedman <friedo@mongodb.com>
=item *
Kristina Chodorow <kristina@mongodb.org>
=item *
Florian Ragwitz <rafl@debian.org>
=back
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2014 by MongoDB, Inc..
This is free software, licensed under:
The Apache License, Version 2.0, January 2004
=cut
| gitpan/MongoDB | lib/MongoDB/BulkWrite.pm | Perl | apache-2.0 | 25,098 |
package VMOMI::PropertyChange;
use parent 'VMOMI::DynamicData';
use strict;
use warnings;
our @class_ancestors = (
'DynamicData',
);
our @class_members = (
['name', undef, 0, ],
['op', 'PropertyChangeOp', 0, ],
['val', 'anyType', 0, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/PropertyChange.pm | Perl | apache-2.0 | 478 |
package ExecuteAndTrace;
use strict;
################################################################################
#
# P E R L M O D U L E
#
################################################################################
#
# DATE OF ORIGIN : Mar 19, 2015
#
#----------------------------------- PURPOSE ------------------------------------
#** @file ExecuteAndTrace.pm
#
# This module will emulate the real ExecuteAndTrace.pm for testing puprposes.
#
#*
#----------------------------------- SYNOPSIS -----------------------------------
# CAUTIONS:
#
# ASSUMPTIONS/PRECONDITIONS:
#
# POSTCONDITIONS:
#
# PARAMETER DESCRIPTION:
# Input:
#
#
# Return value:
# none
#
#
#--------------------------- GLOBAL DATA DESCRIPTION ----------------------------
#---------------------------- PROJECT SPECIFIC DATA -----------------------------
#
#---------------------------- DESCRIPTION OF LOGIC ------------------------------
#
#
################################################################################
use vars qw(@ISA @EXPORT $VERSION);
use Exporter;
use Carp;
use Data::Dumper;
$VERSION = 0.1.0;
@ISA = ('Exporter');
# List the functions and var's that must be available.
# If you want to create a global var, create it as 'our'
@EXPORT = qw(
&DieIfExecuteFails
&Log
);
# ==============================================================================
# V A R I A B L E S
# ==============================================================================
# ==============================================================================
# F U N C T I O N S
# ==============================================================================
# -----------------------------------------------------------------
#** @function [public|protected|private] [return-type] function-name (parameters)
# @brief A brief description of the function
#
# A detailed description of the function
# @params value [required|optional] [details]
# @retval value [details]
# ....
#*
# ---------------
sub DieIfExecuteFails {
my $szCmd = shift;
}
sub Log {
my $szMessage = shift;
}
# This ends the perl module/package definition.
1; | henk52/virman | bin/unit_tests/ExecuteAndTrace.pm | Perl | apache-2.0 | 2,349 |
:- module(persvalue, [
persistent_file/2,
load_file/2,
save_file/2,
group_to_string/2,
show_values/1,
save_group/1,
retract_group/1,
set_value/3,
current_value/3,
main/0],
[functions]).
:- use_module(library(file_utils)).
:- use_module(library(aggregates)).
:- use_module(library(lists)).
:- use_module(library('make/make_rt')).
:- use_module(library(distutils)).
:- use_module(library(system)).
:- use_module(library(dynamic)).
:- use_module(library(strings)).
:- use_module(library('persvalue/persvalue_base')).
:- data persistent_file/2.
:- data current_value/3.
get_value(Group, Name, Value) :-
persistent_file(Group, FileName),
( file_exists(FileName) ->
file_to_string(FileName, Strings)
;
Strings=""
),
get_value_from_string(Strings, Name, Value).
load_file(Group, FileName) :-
retract_group(Group),
assertz_fact(persistent_file(Group, FileName)),
(
get_value(Group,NameS,ValueS),
atom_codes(Name, NameS),
atom_codes(Value, ValueS),
assertz_fact(current_value(Group,Name,Value)),
fail
;
true
).
retract_group(Group) :-
retractall(persistent_file(Group,_)),
retractall(current_value(Group,_,_)).
save_file(Group, FileName) :-
string_to_file(~list_concat([
"# -*- mode: Makefile; -*-\n",
"# Warning: This file has been created automatically\n\n",
~group_to_string(Group)]), FileName).
group_to_string(Group, String) :-
findall(Line, (current_value(Group,Name,Value),
atom_codes(Name, NameS),
atom_codes(Value, ValueS),
list_concat([NameS, "=", ValueS,"\n"], Line)), L),
list_concat(L, String).
save_group(Group) :-
persistent_file(Group, FileName),
save_file(Group, FileName).
show_values(Group) :-
write_string(~group_to_string(Group)).
set_value(Group, Name, Value) :-
retractall(current_value(Group, Name, _)),
assertz_fact(current_value(Group, Name, Value)).
main :-
load_file(test,'test.txt'),
show_values(test),
assertz_fact(current_value(test,'Eureka','Aristoteles')),
save_file(test,'test.txt').
| leuschel/ecce | www/CiaoDE/ciao/contrib/persvalue/persvalue.pl | Perl | apache-2.0 | 2,006 |
:- class(class5method).
method1.
method2.
method3.
method4.
method5.
| leuschel/ecce | www/CiaoDE/ciao/library/class/benchmarks/new/on_method/class5method.pl | Perl | apache-2.0 | 71 |
package Tapper::TestSuite::Netperf;
# ABSTRACT: Tapper - Network performance measurements
use Moose;
with 'MooseX::Log::Log4perl';
1; # End of Tapper::TestSuite::Netperf
__END__
=head1 SYNOPSIS
You most likely want to run the frontend cmdline tool like this
# host 1
$ tapper-testsuite-netperf-server
# host 2
$ tapper-testsuite-netperf-client
=head1 DESCRIPTION
This distribution provides Tapper with Network performance measurements.
=cut
| tapper/Tapper-TestSuite-Netperf | lib/Tapper/TestSuite/Netperf.pm | Perl | bsd-2-clause | 460 |
package CoGeX::Result::Organism;
use strict;
use warnings;
use base 'DBIx::Class::Core';
use JSON qw(encode_json);
=head1 NAME
CoGeX::Organism
=head1 SYNOPSIS
This object uses the DBIx::Class to define an interface to the C<organism> table in the CoGe database.
The C<organism> table contains the name, description, and normalized name for an organism.
=head1 DESCRIPTION
Has columns:
C<organism_id> (Primary Key)
Type: INT, Default: undef, Nullable: no, Size: 11
Primary identification key for table.
C<name>
Type: VARCHAR, Default: "", Nullable: no, Size: 200
Organism name.
C<description>
Type: VARCHAR, Default: undef, Nullable: yes, Size: 255
Organism description.
C<normalized_name>
Type:VARCHAR, Default: "", Nullable: no, Size: 200
File-system 'safe' (only alphanumeric characters and underscores) version of 'name' field above.
Relates to CCoGeX::Result::Genome> via C<organism_id>, in a one-to-many relationship.
=head1 USAGE
use CoGeX;
=head1 METHODS
=cut
__PACKAGE__->table("organism");
__PACKAGE__->add_columns(
"organism_id",
{ data_type => "INT", default_value => undef, is_nullable => 0, size => 11 },
"name",
{ data_type => "VARCHAR", default_value => "", is_nullable => 0, size => 200 },
"description",
{
data_type => "VARCHAR",
default_value => undef,
is_nullable => 1,
size => 255,
},
"restricted", { data_type => "int", default_value => "0", is_nullable => 0, size => 1 }
);
__PACKAGE__->set_primary_key("organism_id");
__PACKAGE__->has_many("genomes" => "CoGeX::Result::Genome", 'organism_id');
################################################ subroutine header begin ##
=head2 to_*
Usage :
Purpose :
Returns :
Argument :
Throws :
Comments :
See Also :
=cut
################################################## subroutine header end ##
sub to_hash {
my $self = shift;
return {
id => $self->id,
name => $self->name,
description => $self->description,
restricted => $self->restricted
}
}
sub to_json {
return encode_json( shift->to_hash );
}
################################################ subroutine header begin ##
=head2 genomes
Usage : $org->genomes
Purpose : alias for $org->dataset_groups (defined through database relationship)
Returns : dataset_group objects
Argument :
Throws :
Comments :
:
See Also :
=cut
################################################## subroutine header end ##
sub dataset_groups
{
print STDERR "Organism::dataset_groups is deprecated, use genomes\n";
return shift->genomes;
}
################################################ subroutine header begin ##
=head2 public genomes
Usage :
Purpose :
Returns :
Argument :
Throws :
Comments :
:
See Also :
=cut
################################################## subroutine header end ##
sub public_genomes
{
return shift->genomes({restricted=>0});
}
################################################ subroutine header begin ##
=head2 current_genome
Usage :
Purpose :
Returns :
Argument :
Throws :
Comments :
:
See Also :
=cut
################################################## subroutine header end ##
sub current_genome
{
my $self = shift;
my %opts = @_;
my $gstid = $opts{type} || $opts{genomic_sequence_type} || $opts{sequence_type} || $opts{gstid};
$gstid = 1 unless $gstid;
$gstid = ref($gstid) =~/Type/ ? $gstid->id : $gstid;
my ($dsg) = $self->genomes({genomic_sequence_type_id=>$gstid},
{'order_by' => 'me.version desc',
join=>[{'dataset_connectors'=>'dataset'}, 'organism'],
prefetch=>[{'dataset_connectors'=>'dataset'}, 'organism']
},
);
return $dsg;
}
################################################ subroutine header begin ##
=head2 current_datasets
Usage :
Purpose :
Returns :
Argument :
Throws :
Comments :
:
See Also :
=cut
################################################## subroutine header end ##
sub current_datasets
{
my $self = shift;
my %opts = @_;
my $dgs = $self->current_genome(%opts);
return $dgs->datasets();
}
################################################ subroutine header begin ##
=head2 current_datasets_old
Usage :
Purpose :
Returns :
Argument :
Throws :
Comments :
:
See Also :
=cut
################################################## subroutine header end ##
#sub current_datasets_old
# {
# my $self = shift;
# my %opts = @_;
# my $type = $opts{type} || $opts{genomic_sequence_type} || $opts{sequence_type} || $opts{gstid};
# $type =1 unless $type;
# my %data;
# my $typeid;
# $typeid = ref($type) =~/Type/ ? $type->id : $type;
# my $version;
# my $contig_set =0;
# ds_loop: foreach my $ds ($self->datasets({},{distict=>'version',order_by=>'version desc'}))
# {
# next unless $ds->sequence_type && $ds->sequence_type->id eq $typeid;
# $version = $ds->version unless $version;
# $version = $ds->version if $ds->version > $version;
## next unless $version == $ds->version;
# my @chrs = $ds->get_chromosomes;
# $contig_set = 1 if scalar @chrs > 50; #more than 50 chromosome? probably a contig dataset
# foreach my $chr (@chrs)
# {
# #this is a hack but the general problem is that some organisms have different chromosomes at different versions, however, partially complete genomes will have many contigs and different versions will have different contigs. So, to get around this, there is a check to see if the chromosome name has contig in it, if so, then only the most current version is used. Otherwise, all versions are game.
# next unless $chr;
# if ($chr =~ /contig/i || $chr=~/scaffold/i || $contig_set)
# {
# $contig_set = 1;
# next ds_loop if $ds->version ne $version;
# }
# $data{$chr} = $ds unless $data{$chr};# || $contig_set;
# $data{$chr} = $ds if $ds->version > $data{$chr}->version;
# }
# }
# %data = map {$_->id,$_} values %data;
# return wantarray ? values %data : [values %data];
# }
################################################ subroutine header begin ##
=head2 genomic_sequence_types
Usage :
Purpose :
Returns :
Argument :
Throws :
Comments :
See Also :
=cut
################################################## subroutine header end ##
sub genomic_sequence_types
{
my $self = shift;
my %data;
foreach my $ds ($self->datasets)
{
my $type = $ds->sequence_type;
$data{$type->id} = $type;
}
return wantarray ? values %data : [values %data];
}
################################################ subroutine header begin ##
=head2 types
Usage :
Purpose : See genomic_sequence_types()
Returns :
Argument :
Throws :
Comments : Alias for genomic_sequence_types() method.
See Also : genomic_sequence_types()
=cut
################################################## subroutine header end ##
sub types
{
return shift->genomic_sequence_types(@_);
}
################################################ subroutine header begin ##
=head2 datasets
Usage :
Purpose :
Returns :
Argument :
Throws :
Comments :
See Also :
=cut
################################################## subroutine header end ##
sub datasets
{
my $self = shift;
my %opts = @_;
my %ds;
map {$ds{$_->id}=$_} map{$_->datasets} $self->genomes;
return wantarray ? values %ds : [values %ds];
}
################################################ subroutine header begin ##
=head2 info
Usage : $self->info
Purpose : returns a string of information about the organism.
Returns : returns a string
Argument : none
Throws :
Comments : To be used to quickly generate a string about the organism
See Also :
=cut
################################################## subroutine header end ##
sub info {
my $self = shift;
my %opts = @_;
my $info;
$info .= $self->name;
return $info;
}
1;
=head1 AUTHORS
Eric Lyons
Brent Pedersen
=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
| LyonsLab/coge | modules/Database/lib/CoGeX/Result/Organism.pm | Perl | bsd-2-clause | 8,333 |
#!/usr/bin/perl
use Frontier::Client;
use Data::Dumper;
$coder = Frontier::RPC2->new;
my $HOST = 'server';
my $user = 'user';
my $pass = 'password';
my $client = new Frontier::Client(url => "http://$HOST/rpc/api");
my $session = $client->call('auth.login',$user, $pass);
my $packages = $client->call('system.listLatestUpgradablePackages', $session, '<system_id>');
#print Dumper $systems;
foreach my $package (@$packages)
{
print $package->{'name'}."\n";
}
$client->call('auth.logout', $session);
| at-boy/spwlk_cli | testing/latest_upgradable_packages.pl | Perl | bsd-3-clause | 507 |
package App::Netdisco::Worker::Plugin::Hook::Exec;
use Dancer ':syntax';
use App::Netdisco::Worker::Plugin;
use aliased 'App::Netdisco::Worker::Status';
use MIME::Base64 'decode_base64';
use Command::Runner;
use Template;
register_worker({ phase => 'main' }, sub {
my ($job, $workerconf) = @_;
my $extra = from_json( decode_base64( $job->extra || '' ) );
my $event_data = $extra->{'event_data'};
my $action_conf = $extra->{'action_conf'};
return Status->error('missing cmd parameter to exec Hook')
if !defined $action_conf->{'cmd'};
my $tt = Template->new({ ENCODING => 'utf8' });
my ($orig_cmd, $cmd) = ($action_conf->{'cmd'}, undef);
$action_conf->{'cmd_is_template'} ||= 1
if !exists $action_conf->{'cmd_is_template'};
if ($action_conf->{'cmd_is_template'}) {
if (ref $orig_cmd) {
foreach my $part (@$orig_cmd) {
my $tmp_part = undef;
$tt->process(\$part, $event_data, \$tmp_part);
push @$cmd, $tmp_part;
}
}
else {
$tt->process(\$orig_cmd, $event_data, \$cmd);
}
}
$cmd ||= $orig_cmd;
my $result = Command::Runner->new(
command => $cmd,
timeout => ($action_conf->{'timeout'} || 60),
env => {
%ENV,
ND_EVENT => $action_conf->{'event'},
ND_DEVICE_IP => $event_data->{'ip'},
},
)->run();
$result->{cmd} = $cmd;
$job->subaction(to_json($result));
if ($action_conf->{'ignore_failure'} or not $result->{'result'}) {
return Status->done(sprintf 'Exec Hook: exit status %s', $result->{'result'});
}
else {
return Status->error(sprintf 'Exec Hook: exit status %s', $result->{'result'});
}
});
true;
| netdisco/netdisco | lib/App/Netdisco/Worker/Plugin/Hook/Exec.pm | Perl | bsd-3-clause | 1,689 |
#
# This file is part of MooseX-Attribute-Deflator
#
# This software is Copyright (c) 2012 by Moritz Onken.
#
# This is free software, licensed under:
#
# The (three-clause) BSD License
#
package MooseX::Attribute::LazyInflator::Meta::Role::Method::Accessor;
{
$MooseX::Attribute::LazyInflator::Meta::Role::Method::Accessor::VERSION = '2.2.2';
}
# ABSTRACT: Lazy inflate attributes
use base 'Moose::Meta::Method::Accessor';
use strict;
use warnings;
sub _inline_check_lazy {
my ( $self, $instance ) = @_;
my $slot_exists = $self->_inline_has($instance);
my $code = "if($slot_exists && !\$attr->is_inflated($instance)) {\n ";
$code .= "my \$inflated = \$attr->inflate($instance, " . $self->_inline_get($instance) . ");\n";
$code .= $self->_inline_check_coercion("\$inflated") . "\n";
$code .= $self->_inline_check_constraint("\$inflated") . "\n";
$code .= $self->_inline_store( $instance, "\$inflated" ) . "\n";
$code .= "}\n\n";
$code .= $self->next::method($instance);
return $code;
}
1;
=pod
=head1 NAME
MooseX::Attribute::LazyInflator::Meta::Role::Method::Accessor - Lazy inflate attributes
=head1 VERSION
version 2.2.2
=head1 INHERITANCE
This class is a base class of L<Moose::Meta::Method::Accessor>.
This is subject to change. As the name suggests, it should be role.
=head1 METHODS
=over 8
=item override B<_inline_check_lazy>
The attribute's value is being inflated and set if it has a value and hasn't been inflated yet.
=back
=head1 AUTHOR
Moritz Onken
=head1 COPYRIGHT AND LICENSE
This software is Copyright (c) 2012 by Moritz Onken.
This is free software, licensed under:
The (three-clause) BSD License
=cut
__END__
| gitpan/MooseX-Attribute-Deflator | lib/MooseX/Attribute/LazyInflator/Meta/Role/Method/Accessor.pm | Perl | bsd-3-clause | 1,703 |
#!/usr/bin/perl -w
use strict;
my $nodes_per_host = 4;
my $num_threads = $ARGV[0] || 32;
my $sleep_time = 100000;
my $interval = 24000000;
my $num_messages = 10;
my $logging = 0;
my $downgrade_to_none = 0;
my $current_time = (time()+10);
print "Running nodes_per $nodes_per_host num_threads $num_threads current_time $current_time downgrade_to_none $downgrade_to_none";
system(qq{echo "Running nodes_per $nodes_per_host num_threads $num_threads current_time $current_time downgrade_to_none $downgrade_to_none" >> runs.txt});
system(qq{python generatep.py $nodes_per_host $num_threads $num_messages $current_time $logging $downgrade_to_none > /homes/ckillian/groupstream/run_${nodes_per_host}_${num_threads}.sh});
system(qq{chmod 777 /homes/ckillian/groupstream/run_${nodes_per_host}_${num_threads}.sh});
# cd /homes/ckillian/groupstream/
exec("python /homes/ckillian/src/pssh-1.4.3/bin/pssh -v -P -t 700 -h /homes/ckillian/groupstream/hosts.pssh /homes/ckillian/groupstream/run_${nodes_per_host}_${num_threads}.sh $sleep_time $interval");
#pkill groupstream
| jojochuang/eventwave | application/appgroupstream/run.pl | Perl | bsd-3-clause | 1,063 |
package Excel::Writer::XLSX::Examples;
###############################################################################
#
# Examples - Excel::Writer::XLSX examples.
#
# A documentation only module showing the examples that are
# included in the Excel::Writer::XLSX distribution. This
# file was generated automatically via the gen_examples_pod.pl
# program that is also included in the examples directory.
#
# Copyright 2000-2012, John McNamara, jmcnamara@cpan.org
#
# Documentation after __END__
#
use strict;
use warnings;
our $VERSION = '0.75';
1;
__END__
=pod
=encoding ISO8859-1
=head1 NAME
Examples - Excel::Writer::XLSX example programs.
=head1 DESCRIPTION
This is a documentation only module showing the examples that are
included in the L<Excel::Writer::XLSX> distribution.
This file was auto-generated via the gen_examples_pod.pl
program that is also included in the examples directory.
=head1 Example programs
The following is a list of the 82 example programs that are included in the Excel::Writer::XLSX distribution.
=over
=item * L<Example: a_simple.pl> A simple demo of some of the features.
=item * L<Example: bug_report.pl> A template for submitting bug reports.
=item * L<Example: demo.pl> A demo of some of the available features.
=item * L<Example: formats.pl> All the available formatting on several worksheets.
=item * L<Example: regions.pl> A simple example of multiple worksheets.
=item * L<Example: stats.pl> Basic formulas and functions.
=item * L<Example: autofilter.pl> Examples of worksheet autofilters.
=item * L<Example: array_formula.pl> Examples of how to write array formulas.
=item * L<Example: cgi.pl> A simple CGI program.
=item * L<Example: chart_area.pl> A demo of area style charts.
=item * L<Example: chart_bar.pl> A demo of bar (vertical histogram) style charts.
=item * L<Example: chart_column.pl> A demo of column (histogram) style charts.
=item * L<Example: chart_line.pl> A demo of line style charts.
=item * L<Example: chart_pie.pl> A demo of pie style charts.
=item * L<Example: chart_radar.pl> A demo of radar style charts.
=item * L<Example: chart_scatter.pl> A demo of scatter style charts.
=item * L<Example: chart_secondary_axis.pl> A demo of a line chart with a secondary axis.
=item * L<Example: chart_stock.pl> A demo of stock style charts.
=item * L<Example: chart_data_table.pl> A demo of a chart with a data table on the axis.
=item * L<Example: chart_data_tools.pl> A demo of charts with data highlighting options.
=item * L<Example: colors.pl> A demo of the colour palette and named colours.
=item * L<Example: comments1.pl> Add comments to worksheet cells.
=item * L<Example: comments2.pl> Add comments with advanced options.
=item * L<Example: conditional_format.pl> Add conditional formats to a range of cells.
=item * L<Example: data_validate.pl> An example of data validation and dropdown lists.
=item * L<Example: date_time.pl> Write dates and times with write_date_time().
=item * L<Example: defined_name.pl> Example of how to create defined names.
=item * L<Example: diag_border.pl> A simple example of diagonal cell borders.
=item * L<Example: filehandle.pl> Examples of working with filehandles.
=item * L<Example: headers.pl> Examples of worksheet headers and footers.
=item * L<Example: hide_row_col.pl> Example of hiding rows and columns.
=item * L<Example: hide_sheet.pl> Simple example of hiding a worksheet.
=item * L<Example: hyperlink1.pl> Shows how to create web hyperlinks.
=item * L<Example: hyperlink2.pl> Examples of internal and external hyperlinks.
=item * L<Example: indent.pl> An example of cell indentation.
=item * L<Example: macros.pl> An example of adding macros from an existing file.
=item * L<Example: merge1.pl> A simple example of cell merging.
=item * L<Example: merge2.pl> A simple example of cell merging with formatting.
=item * L<Example: merge3.pl> Add hyperlinks to merged cells.
=item * L<Example: merge4.pl> An advanced example of merging with formatting.
=item * L<Example: merge5.pl> An advanced example of merging with formatting.
=item * L<Example: merge6.pl> An example of merging with Unicode strings.
=item * L<Example: mod_perl1.pl> A simple mod_perl 1 program.
=item * L<Example: mod_perl2.pl> A simple mod_perl 2 program.
=item * L<Example: outline.pl> An example of outlines and grouping.
=item * L<Example: outline_collapsed.pl> An example of collapsed outlines.
=item * L<Example: panes.pl> An example of how to create panes.
=item * L<Example: properties.pl> Add document properties to a workbook.
=item * L<Example: protection.pl> Example of cell locking and formula hiding.
=item * L<Example: rich_strings.pl> Example of strings with multiple formats.
=item * L<Example: right_to_left.pl> Change default sheet direction to right to left.
=item * L<Example: sales.pl> An example of a simple sales spreadsheet.
=item * L<Example: shape1.pl> Insert shapes in worksheet.
=item * L<Example: shape2.pl> Insert shapes in worksheet. With properties.
=item * L<Example: shape3.pl> Insert shapes in worksheet. Scaled.
=item * L<Example: shape4.pl> Insert shapes in worksheet. With modification.
=item * L<Example: shape5.pl> Insert shapes in worksheet. With connections.
=item * L<Example: shape6.pl> Insert shapes in worksheet. With connections.
=item * L<Example: shape7.pl> Insert shapes in worksheet. One to many connections.
=item * L<Example: shape8.pl> Insert shapes in worksheet. One to many connections.
=item * L<Example: shape_all.pl> Demo of all the available shape and connector types.
=item * L<Example: sparklines1.pl> Simple sparklines demo.
=item * L<Example: sparklines2.pl> Sparklines demo showing formatting options.
=item * L<Example: stats_ext.pl> Same as stats.pl with external references.
=item * L<Example: stocks.pl> Demonstrates conditional formatting.
=item * L<Example: tab_colors.pl> Example of how to set worksheet tab colours.
=item * L<Example: tables.pl> Add Excel tables to a worksheet.
=item * L<Example: write_handler1.pl> Example of extending the write() method. Step 1.
=item * L<Example: write_handler2.pl> Example of extending the write() method. Step 2.
=item * L<Example: write_handler3.pl> Example of extending the write() method. Step 3.
=item * L<Example: write_handler4.pl> Example of extending the write() method. Step 4.
=item * L<Example: write_to_scalar.pl> Example of writing an Excel file to a Perl scalar.
=item * L<Example: unicode_2022_jp.pl> Japanese: ISO-2022-JP.
=item * L<Example: unicode_8859_11.pl> Thai: ISO-8859_11.
=item * L<Example: unicode_8859_7.pl> Greek: ISO-8859_7.
=item * L<Example: unicode_big5.pl> Chinese: BIG5.
=item * L<Example: unicode_cp1251.pl> Russian: CP1251.
=item * L<Example: unicode_cp1256.pl> Arabic: CP1256.
=item * L<Example: unicode_cyrillic.pl> Russian: Cyrillic.
=item * L<Example: unicode_koi8r.pl> Russian: KOI8-R.
=item * L<Example: unicode_polish_utf8.pl> Polish : UTF8.
=item * L<Example: unicode_shift_jis.pl> Japanese: Shift JIS.
=back
=head2 Example: a_simple.pl
A simple example of how to use the Excel::Writer::XLSX module to
write text and numbers to an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/a_simple.jpg" width="640" height="420" alt="Output from a_simple.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# write text and numbers to an Excel xlsx file.
#
# reverse ('(c)'), March 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
# Create a new workbook called simple.xls and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'a_simple.xlsx' );
my $worksheet = $workbook->add_worksheet();
# The general syntax is write($row, $column, $token). Note that row and
# column are zero indexed
#
# Write some text
$worksheet->write( 0, 0, "Hi Excel!" );
# Write some numbers
$worksheet->write( 2, 0, 3 ); # Writes 3
$worksheet->write( 3, 0, 3.00000 ); # Writes 3
$worksheet->write( 4, 0, 3.00001 ); # Writes 3.00001
$worksheet->write( 5, 0, 3.14159 ); # TeX revision no.?
# Write some formulas
$worksheet->write( 7, 0, '=A3 + A6' );
$worksheet->write( 8, 0, '=IF(A5>3,"Yes", "No")' );
# Write a hyperlink
my $hyperlink_format = $workbook->add_format(
color => 'blue',
underline => 1,
);
$worksheet->write( 10, 0, 'http://www.perl.com/', $hyperlink_format );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/a_simple.pl>
=head2 Example: bug_report.pl
A template for submitting a bug report.
Run this program and read the output from the command line.
#!/usr/bin/perl -w
###############################################################################
#
# A template for submitting a bug report.
#
# Run this program and read the output from the command line.
#
# reverse ('(c)'), March 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
print << 'HINTS_1';
REPORTING A BUG OR ASKING A QUESTION
Feel free to report bugs or ask questions. However, to save time
consider the following steps first:
Read the documentation:
The Excel::Writer::XLSX documentation has been refined in
response to user questions. Therefore, if you have a question it is
possible that someone else has asked it before you and that it is
already addressed in the documentation. Since there is a lot of
documentation to get through you should at least read the table of
contents and search for keywords that you are interested in.
Look at the example programs:
There are over 80 example programs shipped with the standard
Excel::Writer::XLSX distribution. Many of these were created
in response to user questions. Try to identify an example program
that corresponds to your query and adapt it to your needs.
HINTS_1
print "Press enter ..."; <STDIN>;
print << 'HINTS_2';
If you submit a bug report here are some pointers.
1. Put "Excel::Writer::XLSX:" at the beginning of the subject line.
This helps to filter genuine messages from spam.
2. Describe the problems as clearly and as concisely as possible.
3. Send a sample program. It is often easier to describe a problem in
code than in written prose.
4. The sample program should be as small as possible to demonstrate the
problem. Don't copy and past large sections of your program. The
program should also be self contained and working.
A sample bug report is generated below. If you use this format then it
will help to analyse your question and respond to it more quickly.
Please don't send patches without contacting the author first.
HINTS_2
print "Press enter ..."; <STDIN>;
print << 'EMAIL';
=======================================================================
To: John McNamara <jmcnamara@cpan.org>
Subject: Excel::Writer::XLSX: Problem with something.
Hi John,
I am using Excel::Writer::XLSX and I have encountered a problem. I
want it to do SOMETHING but the module appears to do SOMETHING_ELSE.
Here is some code that demonstrates the problem.
#!/usr/bin/perl -w
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new("reload.xls");
my $worksheet = $workbook->addworksheet();
$worksheet->write(0, 0, "Hi Excel!");
__END__
My automatically generated system details are as follows:
EMAIL
print "\n Perl version : $]";
print "\n OS name : $^O";
print "\n Module versions: (not all are required)\n";
my @modules = qw(
Excel::Writer::XLSX
Spreadsheet::WriteExcel
Archive::Zip
XML::Writer
IO::File
File::Temp
);
for my $module (@modules) {
my $version;
eval "require $module";
if (not $@) {
$version = $module->VERSION;
$version = '(unknown)' if not defined $version;
}
else {
$version = '(not installed)';
}
printf "%21s%-24s\t%s\n", "", $module, $version;
}
print << "BYE";
Yours etc.,
A. Person
--
BYE
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/bug_report.pl>
=head2 Example: demo.pl
A simple demo of some of the features of Excel::Writer::XLSX.
This program is used to create the project screenshot for Freshmeat:
L<http://freshmeat.net/projects/writeexcel/>
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/demo.jpg" width="640" height="420" alt="Output from demo.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
#######################################################################
#
# A simple demo of some of the features of Excel::Writer::XLSX.
#
# This program is used to create the project screenshot for Freshmeat:
# L<http://freshmeat.net/projects/writeexcel/>
#
# reverse ('(c)'), October 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'demo.xlsx' );
my $worksheet = $workbook->add_worksheet( 'Demo' );
my $worksheet2 = $workbook->add_worksheet( 'Another sheet' );
my $worksheet3 = $workbook->add_worksheet( 'And another' );
my $bold = $workbook->add_format( bold => 1 );
#######################################################################
#
# Write a general heading
#
$worksheet->set_column( 'A:A', 36, $bold );
$worksheet->set_column( 'B:B', 20 );
$worksheet->set_row( 0, 40 );
my $heading = $workbook->add_format(
bold => 1,
color => 'blue',
size => 16,
merge => 1,
align => 'vcenter',
);
my $hyperlink_format = $workbook->add_format(
color => 'blue',
underline => 1,
);
my @headings = ( 'Features of Excel::Writer::XLSX', '' );
$worksheet->write_row( 'A1', \@headings, $heading );
#######################################################################
#
# Some text examples
#
my $text_format = $workbook->add_format(
bold => 1,
italic => 1,
color => 'red',
size => 18,
font => 'Lucida Calligraphy'
);
$worksheet->write( 'A2', "Text" );
$worksheet->write( 'B2', "Hello Excel" );
$worksheet->write( 'A3', "Formatted text" );
$worksheet->write( 'B3', "Hello Excel", $text_format );
$worksheet->write( 'A4', "Unicode text" );
$worksheet->write( 'B4', "\x{0410} \x{0411} \x{0412} \x{0413} \x{0414}" );
#######################################################################
#
# Some numeric examples
#
my $num1_format = $workbook->add_format( num_format => '$#,##0.00' );
my $num2_format = $workbook->add_format( num_format => ' d mmmm yyy' );
$worksheet->write( 'A5', "Numbers" );
$worksheet->write( 'B5', 1234.56 );
$worksheet->write( 'A6', "Formatted numbers" );
$worksheet->write( 'B6', 1234.56, $num1_format );
$worksheet->write( 'A7', "Formatted numbers" );
$worksheet->write( 'B7', 37257, $num2_format );
#######################################################################
#
# Formulae
#
$worksheet->set_selection( 'B8' );
$worksheet->write( 'A8', 'Formulas and functions, "=SIN(PI()/4)"' );
$worksheet->write( 'B8', '=SIN(PI()/4)' );
#######################################################################
#
# Hyperlinks
#
$worksheet->write( 'A9', "Hyperlinks" );
$worksheet->write( 'B9', 'http://www.perl.com/', $hyperlink_format );
#######################################################################
#
# Images
#
$worksheet->write( 'A10', "Images" );
$worksheet->insert_image( 'B10', 'republic.png', 16, 8 );
#######################################################################
#
# Misc
#
$worksheet->write( 'A18', "Page/printer setup" );
$worksheet->write( 'A19', "Multiple worksheets" );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/demo.pl>
=head2 Example: formats.pl
Examples of formatting using the Excel::Writer::XLSX module.
This program demonstrates almost all possible formatting options. It is worth
running this program and viewing the output Excel file if you are interested
in the various formatting possibilities.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/formats.jpg" width="640" height="420" alt="Output from formats.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Examples of formatting using the Excel::Writer::XLSX module.
#
# This program demonstrates almost all possible formatting options. It is worth
# running this program and viewing the output Excel file if you are interested
# in the various formatting possibilities.
#
# reverse ('(c)'), September 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'formats.xlsx' );
# Some common formats
my $center = $workbook->add_format( align => 'center' );
my $heading = $workbook->add_format( align => 'center', bold => 1 );
# The named colors
my %colors = (
0x08, 'black',
0x0C, 'blue',
0x10, 'brown',
0x0F, 'cyan',
0x17, 'gray',
0x11, 'green',
0x0B, 'lime',
0x0E, 'magenta',
0x12, 'navy',
0x35, 'orange',
0x21, 'pink',
0x14, 'purple',
0x0A, 'red',
0x16, 'silver',
0x09, 'white',
0x0D, 'yellow',
);
# Call these subroutines to demonstrate different formatting options
intro();
fonts();
named_colors();
standard_colors();
numeric_formats();
borders();
patterns();
alignment();
misc();
# Note: this is required
$workbook->close();
######################################################################
#
# Intro.
#
sub intro {
my $worksheet = $workbook->add_worksheet( 'Introduction' );
$worksheet->set_column( 0, 0, 60 );
my $format = $workbook->add_format();
$format->set_bold();
$format->set_size( 14 );
$format->set_color( 'blue' );
$format->set_align( 'center' );
my $format2 = $workbook->add_format();
$format2->set_bold();
$format2->set_color( 'blue' );
my $format3 = $workbook->add_format(
color => 'blue',
underline => 1,
);
$worksheet->write( 2, 0, 'This workbook demonstrates some of', $format );
$worksheet->write( 3, 0, 'the formatting options provided by', $format );
$worksheet->write( 4, 0, 'the Excel::Writer::XLSX module.', $format );
$worksheet->write( 'A7', 'Sections:', $format2 );
$worksheet->write( 'A8', "internal:Fonts!A1", 'Fonts', $format3 );
$worksheet->write( 'A9', "internal:'Named colors'!A1",
'Named colors', $format3 );
$worksheet->write(
'A10',
"internal:'Standard colors'!A1",
'Standard colors', $format3
);
$worksheet->write(
'A11',
"internal:'Numeric formats'!A1",
'Numeric formats', $format3
);
$worksheet->write( 'A12', "internal:Borders!A1", 'Borders', $format3 );
$worksheet->write( 'A13', "internal:Patterns!A1", 'Patterns', $format3 );
$worksheet->write( 'A14', "internal:Alignment!A1", 'Alignment', $format3 );
$worksheet->write( 'A15', "internal:Miscellaneous!A1", 'Miscellaneous',
$format3 );
}
######################################################################
#
# Demonstrate the named colors.
#
sub named_colors {
my $worksheet = $workbook->add_worksheet( 'Named colors' );
$worksheet->set_column( 0, 3, 15 );
$worksheet->write( 0, 0, "Index", $heading );
$worksheet->write( 0, 1, "Index", $heading );
$worksheet->write( 0, 2, "Name", $heading );
$worksheet->write( 0, 3, "Color", $heading );
my $i = 1;
while ( my ( $index, $color ) = each %colors ) {
my $format = $workbook->add_format(
bg_color => $color,
pattern => 1,
border => 1
);
$worksheet->write( $i + 1, 0, $index, $center );
$worksheet->write( $i + 1, 1, sprintf( "0x%02X", $index ), $center );
$worksheet->write( $i + 1, 2, $color, $center );
$worksheet->write( $i + 1, 3, '', $format );
$i++;
}
}
######################################################################
#
# Demonstrate the standard Excel colors in the range 8..63.
#
sub standard_colors {
my $worksheet = $workbook->add_worksheet( 'Standard colors' );
$worksheet->set_column( 0, 3, 15 );
$worksheet->write( 0, 0, "Index", $heading );
$worksheet->write( 0, 1, "Index", $heading );
$worksheet->write( 0, 2, "Color", $heading );
$worksheet->write( 0, 3, "Name", $heading );
for my $i ( 8 .. 63 ) {
my $format = $workbook->add_format(
bg_color => $i,
pattern => 1,
border => 1
);
$worksheet->write( ( $i - 7 ), 0, $i, $center );
$worksheet->write( ( $i - 7 ), 1, sprintf( "0x%02X", $i ), $center );
$worksheet->write( ( $i - 7 ), 2, '', $format );
# Add the color names
if ( exists $colors{$i} ) {
$worksheet->write( ( $i - 7 ), 3, $colors{$i}, $center );
}
}
}
######################################################################
#
# Demonstrate the standard numeric formats.
#
sub numeric_formats {
my $worksheet = $workbook->add_worksheet( 'Numeric formats' );
$worksheet->set_column( 0, 4, 15 );
$worksheet->set_column( 5, 5, 45 );
$worksheet->write( 0, 0, "Index", $heading );
$worksheet->write( 0, 1, "Index", $heading );
$worksheet->write( 0, 2, "Unformatted", $heading );
$worksheet->write( 0, 3, "Formatted", $heading );
$worksheet->write( 0, 4, "Negative", $heading );
$worksheet->write( 0, 5, "Format", $heading );
#<<<
my @formats;
push @formats, [ 0x00, 1234.567, 0, 'General' ];
push @formats, [ 0x01, 1234.567, 0, '0' ];
push @formats, [ 0x02, 1234.567, 0, '0.00' ];
push @formats, [ 0x03, 1234.567, 0, '#,##0' ];
push @formats, [ 0x04, 1234.567, 0, '#,##0.00' ];
push @formats, [ 0x05, 1234.567, -1234.567, '($#,##0_);($#,##0)' ];
push @formats, [ 0x06, 1234.567, -1234.567, '($#,##0_);[Red]($#,##0)' ];
push @formats, [ 0x07, 1234.567, -1234.567, '($#,##0.00_);($#,##0.00)' ];
push @formats, [ 0x08, 1234.567, -1234.567, '($#,##0.00_);[Red]($#,##0.00)' ];
push @formats, [ 0x09, 0.567, 0, '0%' ];
push @formats, [ 0x0a, 0.567, 0, '0.00%' ];
push @formats, [ 0x0b, 1234.567, 0, '0.00E+00' ];
push @formats, [ 0x0c, 0.75, 0, '# ?/?' ];
push @formats, [ 0x0d, 0.3125, 0, '# ??/??' ];
push @formats, [ 0x0e, 36892.521, 0, 'm/d/yy' ];
push @formats, [ 0x0f, 36892.521, 0, 'd-mmm-yy' ];
push @formats, [ 0x10, 36892.521, 0, 'd-mmm' ];
push @formats, [ 0x11, 36892.521, 0, 'mmm-yy' ];
push @formats, [ 0x12, 36892.521, 0, 'h:mm AM/PM' ];
push @formats, [ 0x13, 36892.521, 0, 'h:mm:ss AM/PM' ];
push @formats, [ 0x14, 36892.521, 0, 'h:mm' ];
push @formats, [ 0x15, 36892.521, 0, 'h:mm:ss' ];
push @formats, [ 0x16, 36892.521, 0, 'm/d/yy h:mm' ];
push @formats, [ 0x25, 1234.567, -1234.567, '(#,##0_);(#,##0)' ];
push @formats, [ 0x26, 1234.567, -1234.567, '(#,##0_);[Red](#,##0)' ];
push @formats, [ 0x27, 1234.567, -1234.567, '(#,##0.00_);(#,##0.00)' ];
push @formats, [ 0x28, 1234.567, -1234.567, '(#,##0.00_);[Red](#,##0.00)' ];
push @formats, [ 0x29, 1234.567, -1234.567, '_(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)' ];
push @formats, [ 0x2a, 1234.567, -1234.567, '_($* #,##0_);_($* (#,##0);_($* "-"_);_(@_)' ];
push @formats, [ 0x2b, 1234.567, -1234.567, '_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)' ];
push @formats, [ 0x2c, 1234.567, -1234.567, '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)' ];
push @formats, [ 0x2d, 36892.521, 0, 'mm:ss' ];
push @formats, [ 0x2e, 3.0153, 0, '[h]:mm:ss' ];
push @formats, [ 0x2f, 36892.521, 0, 'mm:ss.0' ];
push @formats, [ 0x30, 1234.567, 0, '##0.0E+0' ];
push @formats, [ 0x31, 1234.567, 0, '@' ];
#>>>
my $i;
foreach my $format ( @formats ) {
my $style = $workbook->add_format();
$style->set_num_format( $format->[0] );
$i++;
$worksheet->write( $i, 0, $format->[0], $center );
$worksheet->write( $i, 1, sprintf( "0x%02X", $format->[0] ), $center );
$worksheet->write( $i, 2, $format->[1], $center );
$worksheet->write( $i, 3, $format->[1], $style );
if ( $format->[2] ) {
$worksheet->write( $i, 4, $format->[2], $style );
}
$worksheet->write_string( $i, 5, $format->[3] );
}
}
######################################################################
#
# Demonstrate the font options.
#
sub fonts {
my $worksheet = $workbook->add_worksheet( 'Fonts' );
$worksheet->set_column( 0, 0, 30 );
$worksheet->set_column( 1, 1, 10 );
$worksheet->write( 0, 0, "Font name", $heading );
$worksheet->write( 0, 1, "Font size", $heading );
my @fonts;
push @fonts, [ 10, 'Arial' ];
push @fonts, [ 12, 'Arial' ];
push @fonts, [ 14, 'Arial' ];
push @fonts, [ 12, 'Arial Black' ];
push @fonts, [ 12, 'Arial Narrow' ];
push @fonts, [ 12, 'Century Schoolbook' ];
push @fonts, [ 12, 'Courier' ];
push @fonts, [ 12, 'Courier New' ];
push @fonts, [ 12, 'Garamond' ];
push @fonts, [ 12, 'Impact' ];
push @fonts, [ 12, 'Lucida Handwriting' ];
push @fonts, [ 12, 'Times New Roman' ];
push @fonts, [ 12, 'Symbol' ];
push @fonts, [ 12, 'Wingdings' ];
push @fonts, [ 12, 'A font that doesn\'t exist' ];
my $i;
foreach my $font ( @fonts ) {
my $format = $workbook->add_format();
$format->set_size( $font->[0] );
$format->set_font( $font->[1] );
$i++;
$worksheet->write( $i, 0, $font->[1], $format );
$worksheet->write( $i, 1, $font->[0], $format );
}
}
######################################################################
#
# Demonstrate the standard Excel border styles.
#
sub borders {
my $worksheet = $workbook->add_worksheet( 'Borders' );
$worksheet->set_column( 0, 4, 10 );
$worksheet->set_column( 5, 5, 40 );
$worksheet->write( 0, 0, "Index", $heading );
$worksheet->write( 0, 1, "Index", $heading );
$worksheet->write( 0, 3, "Style", $heading );
$worksheet->write( 0, 5, "The style is highlighted in red for ", $heading );
$worksheet->write( 1, 5, "emphasis, the default color is black.",
$heading );
for my $i ( 0 .. 13 ) {
my $format = $workbook->add_format();
$format->set_border( $i );
$format->set_border_color( 'red' );
$format->set_align( 'center' );
$worksheet->write( ( 2 * ( $i + 1 ) ), 0, $i, $center );
$worksheet->write( ( 2 * ( $i + 1 ) ),
1, sprintf( "0x%02X", $i ), $center );
$worksheet->write( ( 2 * ( $i + 1 ) ), 3, "Border", $format );
}
$worksheet->write( 30, 0, "Diag type", $heading );
$worksheet->write( 30, 1, "Index", $heading );
$worksheet->write( 30, 3, "Style", $heading );
$worksheet->write( 30, 5, "Diagonal Boder styles", $heading );
for my $i ( 1 .. 3 ) {
my $format = $workbook->add_format();
$format->set_diag_type( $i );
$format->set_diag_border( 1 );
$format->set_diag_color( 'red' );
$format->set_align( 'center' );
$worksheet->write( ( 2 * ( $i + 15 ) ), 0, $i, $center );
$worksheet->write( ( 2 * ( $i + 15 ) ),
1, sprintf( "0x%02X", $i ), $center );
$worksheet->write( ( 2 * ( $i + 15 ) ), 3, "Border", $format );
}
}
######################################################################
#
# Demonstrate the standard Excel cell patterns.
#
sub patterns {
my $worksheet = $workbook->add_worksheet( 'Patterns' );
$worksheet->set_column( 0, 4, 10 );
$worksheet->set_column( 5, 5, 50 );
$worksheet->write( 0, 0, "Index", $heading );
$worksheet->write( 0, 1, "Index", $heading );
$worksheet->write( 0, 3, "Pattern", $heading );
$worksheet->write( 0, 5, "The background colour has been set to silver.",
$heading );
$worksheet->write( 1, 5, "The foreground colour has been set to green.",
$heading );
for my $i ( 0 .. 18 ) {
my $format = $workbook->add_format();
$format->set_pattern( $i );
$format->set_bg_color( 'silver' );
$format->set_fg_color( 'green' );
$format->set_align( 'center' );
$worksheet->write( ( 2 * ( $i + 1 ) ), 0, $i, $center );
$worksheet->write( ( 2 * ( $i + 1 ) ),
1, sprintf( "0x%02X", $i ), $center );
$worksheet->write( ( 2 * ( $i + 1 ) ), 3, "Pattern", $format );
if ( $i == 1 ) {
$worksheet->write( ( 2 * ( $i + 1 ) ),
5, "This is solid colour, the most useful pattern.", $heading );
}
}
}
######################################################################
#
# Demonstrate the standard Excel cell alignments.
#
sub alignment {
my $worksheet = $workbook->add_worksheet( 'Alignment' );
$worksheet->set_column( 0, 7, 12 );
$worksheet->set_row( 0, 40 );
$worksheet->set_selection( 7, 0 );
my $format01 = $workbook->add_format();
my $format02 = $workbook->add_format();
my $format03 = $workbook->add_format();
my $format04 = $workbook->add_format();
my $format05 = $workbook->add_format();
my $format06 = $workbook->add_format();
my $format07 = $workbook->add_format();
my $format08 = $workbook->add_format();
my $format09 = $workbook->add_format();
my $format10 = $workbook->add_format();
my $format11 = $workbook->add_format();
my $format12 = $workbook->add_format();
my $format13 = $workbook->add_format();
my $format14 = $workbook->add_format();
my $format15 = $workbook->add_format();
my $format16 = $workbook->add_format();
my $format17 = $workbook->add_format();
$format02->set_align( 'top' );
$format03->set_align( 'bottom' );
$format04->set_align( 'vcenter' );
$format05->set_align( 'vjustify' );
$format06->set_text_wrap();
$format07->set_align( 'left' );
$format08->set_align( 'right' );
$format09->set_align( 'center' );
$format10->set_align( 'fill' );
$format11->set_align( 'justify' );
$format12->set_merge();
$format13->set_rotation( 45 );
$format14->set_rotation( -45 );
$format15->set_rotation( 270 );
$format16->set_shrink();
$format17->set_indent( 1 );
$worksheet->write( 0, 0, 'Vertical', $heading );
$worksheet->write( 0, 1, 'top', $format02 );
$worksheet->write( 0, 2, 'bottom', $format03 );
$worksheet->write( 0, 3, 'vcenter', $format04 );
$worksheet->write( 0, 4, 'vjustify', $format05 );
$worksheet->write( 0, 5, "text\nwrap", $format06 );
$worksheet->write( 2, 0, 'Horizontal', $heading );
$worksheet->write( 2, 1, 'left', $format07 );
$worksheet->write( 2, 2, 'right', $format08 );
$worksheet->write( 2, 3, 'center', $format09 );
$worksheet->write( 2, 4, 'fill', $format10 );
$worksheet->write( 2, 5, 'justify', $format11 );
$worksheet->write( 3, 1, 'merge', $format12 );
$worksheet->write( 3, 2, '', $format12 );
$worksheet->write( 3, 3, 'Shrink ' x 3, $format16 );
$worksheet->write( 3, 4, 'Indent', $format17 );
$worksheet->write( 5, 0, 'Rotation', $heading );
$worksheet->write( 5, 1, 'Rotate 45', $format13 );
$worksheet->write( 6, 1, 'Rotate -45', $format14 );
$worksheet->write( 7, 1, 'Rotate 270', $format15 );
}
######################################################################
#
# Demonstrate other miscellaneous features.
#
sub misc {
my $worksheet = $workbook->add_worksheet( 'Miscellaneous' );
$worksheet->set_column( 2, 2, 25 );
my $format01 = $workbook->add_format();
my $format02 = $workbook->add_format();
my $format03 = $workbook->add_format();
my $format04 = $workbook->add_format();
my $format05 = $workbook->add_format();
my $format06 = $workbook->add_format();
my $format07 = $workbook->add_format();
$format01->set_underline( 0x01 );
$format02->set_underline( 0x02 );
$format03->set_underline( 0x21 );
$format04->set_underline( 0x22 );
$format05->set_font_strikeout();
$format06->set_font_outline();
$format07->set_font_shadow();
$worksheet->write( 1, 2, 'Underline 0x01', $format01 );
$worksheet->write( 3, 2, 'Underline 0x02', $format02 );
$worksheet->write( 5, 2, 'Underline 0x21', $format03 );
$worksheet->write( 7, 2, 'Underline 0x22', $format04 );
$worksheet->write( 9, 2, 'Strikeout', $format05 );
$worksheet->write( 11, 2, 'Outline (Macintosh only)', $format06 );
$worksheet->write( 13, 2, 'Shadow (Macintosh only)', $format07 );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/formats.pl>
=head2 Example: regions.pl
An example of how to use the Excel::Writer::XLSX module to write a basic
Excel workbook with multiple worksheets.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/regions.jpg" width="640" height="420" alt="Output from regions.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# An example of how to use the Excel::Writer::XLSX module to write a basic
# Excel workbook with multiple worksheets.
#
# reverse ('(c)'), March 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
# Create a new Excel workbook
my $workbook = Excel::Writer::XLSX->new( 'regions.xlsx' );
# Add some worksheets
my $north = $workbook->add_worksheet( "North" );
my $south = $workbook->add_worksheet( "South" );
my $east = $workbook->add_worksheet( "East" );
my $west = $workbook->add_worksheet( "West" );
# Add a Format
my $format = $workbook->add_format();
$format->set_bold();
$format->set_color( 'blue' );
# Add a caption to each worksheet
foreach my $worksheet ( $workbook->sheets() ) {
$worksheet->write( 0, 0, "Sales", $format );
}
# Write some data
$north->write( 0, 1, 200000 );
$south->write( 0, 1, 100000 );
$east->write( 0, 1, 150000 );
$west->write( 0, 1, 100000 );
# Set the active worksheet
$south->activate();
# Set the width of the first column
$south->set_column( 0, 0, 20 );
# Set the active cell
$south->set_selection( 0, 1 );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/regions.pl>
=head2 Example: stats.pl
A simple example of how to use functions with the Excel::Writer::XLSX
module.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/stats.jpg" width="640" height="420" alt="Output from stats.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# A simple example of how to use functions with the Excel::Writer::XLSX
# module.
#
# reverse ('(c)'), March 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'stats.xlsx' );
my $worksheet = $workbook->add_worksheet( 'Test data' );
# Set the column width for columns 1
$worksheet->set_column( 0, 0, 20 );
# Create a format for the headings
my $format = $workbook->add_format();
$format->set_bold();
# Write the sample data
$worksheet->write( 0, 0, 'Sample', $format );
$worksheet->write( 0, 1, 1 );
$worksheet->write( 0, 2, 2 );
$worksheet->write( 0, 3, 3 );
$worksheet->write( 0, 4, 4 );
$worksheet->write( 0, 5, 5 );
$worksheet->write( 0, 6, 6 );
$worksheet->write( 0, 7, 7 );
$worksheet->write( 0, 8, 8 );
$worksheet->write( 1, 0, 'Length', $format );
$worksheet->write( 1, 1, 25.4 );
$worksheet->write( 1, 2, 25.4 );
$worksheet->write( 1, 3, 24.8 );
$worksheet->write( 1, 4, 25.0 );
$worksheet->write( 1, 5, 25.3 );
$worksheet->write( 1, 6, 24.9 );
$worksheet->write( 1, 7, 25.2 );
$worksheet->write( 1, 8, 24.8 );
# Write some statistical functions
$worksheet->write( 4, 0, 'Count', $format );
$worksheet->write( 4, 1, '=COUNT(B1:I1)' );
$worksheet->write( 5, 0, 'Sum', $format );
$worksheet->write( 5, 1, '=SUM(B2:I2)' );
$worksheet->write( 6, 0, 'Average', $format );
$worksheet->write( 6, 1, '=AVERAGE(B2:I2)' );
$worksheet->write( 7, 0, 'Min', $format );
$worksheet->write( 7, 1, '=MIN(B2:I2)' );
$worksheet->write( 8, 0, 'Max', $format );
$worksheet->write( 8, 1, '=MAX(B2:I2)' );
$worksheet->write( 9, 0, 'Standard Deviation', $format );
$worksheet->write( 9, 1, '=STDEV(B2:I2)' );
$worksheet->write( 10, 0, 'Kurtosis', $format );
$worksheet->write( 10, 1, '=KURT(B2:I2)' );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/stats.pl>
=head2 Example: autofilter.pl
An example of how to create autofilters with Excel::Writer::XLSX.
An autofilter is a way of adding drop down lists to the headers of a 2D range
of worksheet data. This allows users to filter the data based on
simple criteria so that some data is shown and some is hidden.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/autofilter.jpg" width="640" height="420" alt="Output from autofilter.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# An example of how to create autofilters with Excel::Writer::XLSX.
#
# An autofilter is a way of adding drop down lists to the headers of a 2D range
# of worksheet data. This allows users to filter the data based on
# simple criteria so that some data is shown and some is hidden.
#
# reverse ('(c)'), September 2007, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'autofilter.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $worksheet3 = $workbook->add_worksheet();
my $worksheet4 = $workbook->add_worksheet();
my $worksheet5 = $workbook->add_worksheet();
my $worksheet6 = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Extract the data embedded at the end of this file.
my @headings = split ' ', <DATA>;
my @data;
push @data, [split] while <DATA>;
# Set up several sheets with the same data.
for my $worksheet ( $workbook->sheets() ) {
$worksheet->set_column( 'A:D', 12 );
$worksheet->set_row( 0, 20, $bold );
$worksheet->write( 'A1', \@headings );
}
###############################################################################
#
# Example 1. Autofilter without conditions.
#
$worksheet1->autofilter( 'A1:D51' );
$worksheet1->write( 'A2', [ [@data] ] );
###############################################################################
#
#
# Example 2. Autofilter with a filter condition in the first column.
#
# The range in this example is the same as above but in row-column notation.
$worksheet2->autofilter( 0, 0, 50, 3 );
# The placeholder "Region" in the filter is ignored and can be any string
# that adds clarity to the expression.
#
$worksheet2->filter_column( 0, 'Region eq East' );
#
# Hide the rows that don't match the filter criteria.
#
my $row = 1;
for my $row_data ( @data ) {
my $region = $row_data->[0];
if ( $region eq 'East' ) {
# Row is visible.
}
else {
# Hide row.
$worksheet2->set_row( $row, undef, undef, 1 );
}
$worksheet2->write( $row++, 0, $row_data );
}
###############################################################################
#
#
# Example 3. Autofilter with a dual filter condition in one of the columns.
#
$worksheet3->autofilter( 'A1:D51' );
$worksheet3->filter_column( 'A', 'x eq East or x eq South' );
#
# Hide the rows that don't match the filter criteria.
#
$row = 1;
for my $row_data ( @data ) {
my $region = $row_data->[0];
if ( $region eq 'East' or $region eq 'South' ) {
# Row is visible.
}
else {
# Hide row.
$worksheet3->set_row( $row, undef, undef, 1 );
}
$worksheet3->write( $row++, 0, $row_data );
}
###############################################################################
#
#
# Example 4. Autofilter with filter conditions in two columns.
#
$worksheet4->autofilter( 'A1:D51' );
$worksheet4->filter_column( 'A', 'x eq East' );
$worksheet4->filter_column( 'C', 'x > 3000 and x < 8000' );
#
# Hide the rows that don't match the filter criteria.
#
$row = 1;
for my $row_data ( @data ) {
my $region = $row_data->[0];
my $volume = $row_data->[2];
if ( $region eq 'East'
and $volume > 3000
and $volume < 8000 )
{
# Row is visible.
}
else {
# Hide row.
$worksheet4->set_row( $row, undef, undef, 1 );
}
$worksheet4->write( $row++, 0, $row_data );
}
###############################################################################
#
#
# Example 5. Autofilter with filter for blanks.
#
# Create a blank cell in our test data.
$data[5]->[0] = '';
$worksheet5->autofilter( 'A1:D51' );
$worksheet5->filter_column( 'A', 'x == Blanks' );
#
# Hide the rows that don't match the filter criteria.
#
$row = 1;
for my $row_data ( @data ) {
my $region = $row_data->[0];
if ( $region eq '' ) {
# Row is visible.
}
else {
# Hide row.
$worksheet5->set_row( $row, undef, undef, 1 );
}
$worksheet5->write( $row++, 0, $row_data );
}
###############################################################################
#
#
# Example 6. Autofilter with filter for non-blanks.
#
$worksheet6->autofilter( 'A1:D51' );
$worksheet6->filter_column( 'A', 'x == NonBlanks' );
#
# Hide the rows that don't match the filter criteria.
#
$row = 1;
for my $row_data ( @data ) {
my $region = $row_data->[0];
if ( $region ne '' ) {
# Row is visible.
}
else {
# Hide row.
$worksheet6->set_row( $row, undef, undef, 1 );
}
$worksheet6->write( $row++, 0, $row_data );
}
__DATA__
Region Item Volume Month
East Apple 9000 July
East Apple 5000 July
South Orange 9000 September
North Apple 2000 November
West Apple 9000 November
South Pear 7000 October
North Pear 9000 August
West Orange 1000 December
West Grape 1000 November
South Pear 10000 April
West Grape 6000 January
South Orange 3000 May
North Apple 3000 December
South Apple 7000 February
West Grape 1000 December
East Grape 8000 February
South Grape 10000 June
West Pear 7000 December
South Apple 2000 October
East Grape 7000 December
North Grape 6000 April
East Pear 8000 February
North Apple 7000 August
North Orange 7000 July
North Apple 6000 June
South Grape 8000 September
West Apple 3000 October
South Orange 10000 November
West Grape 4000 July
North Orange 5000 August
East Orange 1000 November
East Orange 4000 October
North Grape 5000 August
East Apple 1000 December
South Apple 10000 March
East Grape 7000 October
West Grape 1000 September
East Grape 10000 October
South Orange 8000 March
North Apple 4000 July
South Orange 5000 July
West Apple 4000 June
East Apple 5000 April
North Pear 3000 August
East Grape 9000 November
North Orange 8000 October
East Apple 10000 June
South Pear 1000 December
North Grape 10000 July
East Grape 6000 February
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/autofilter.pl>
=head2 Example: array_formula.pl
Example of how to use the Excel::Writer::XLSX module to write simple
array formulas.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/array_formula.jpg" width="640" height="420" alt="Output from array_formula.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# Example of how to use the Excel::Writer::XLSX module to write simple
# array formulas.
#
# reverse ('(c)'), August 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'array_formula.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Write some test data.
$worksheet->write( 'B1', [ [ 500, 10 ], [ 300, 15 ] ] );
$worksheet->write( 'B5', [ [ 1, 2, 3 ], [ 20234, 21003, 10000 ] ] );
# Write an array formula that returns a single value
$worksheet->write( 'A1', '{=SUM(B1:C1*B2:C2)}' );
# Same as above but more verbose.
$worksheet->write_array_formula( 'A2:A2', '{=SUM(B1:C1*B2:C2)}' );
# Write an array formula that returns a range of values
$worksheet->write_array_formula( 'A5:A7', '{=TREND(C5:C7,B5:B7)}' );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/array_formula.pl>
=head2 Example: cgi.pl
Example of how to use the Excel::Writer::XLSX module to send an Excel
file to a browser in a CGI program.
On Windows the hash-bang line should be something like:
#!C:\Perl\bin\perl.exe
The "Content-Disposition" line will cause a prompt to be generated to save
the file. If you want to stream the file to the browser instead, comment out
that line as shown below.
#!/usr/bin/perl
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX module to send an Excel
# file to a browser in a CGI program.
#
# On Windows the hash-bang line should be something like:
#
# #!C:\Perl\bin\perl.exe
#
# The "Content-Disposition" line will cause a prompt to be generated to save
# the file. If you want to stream the file to the browser instead, comment out
# that line as shown below.
#
# reverse ('(c)'), March 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Set the filename and send the content type
my $filename = "cgitest.xlsx";
print "Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n";
# The Content-Disposition will generate a prompt to save the file. If you want
# to stream the file to the browser, comment out the following line.
print "Content-Disposition: attachment; filename=$filename\n";
print "\n";
# Redirect the output to STDOUT. Binmode the filehandle in case it is needed.
binmode STDOUT;
my $workbook = Excel::Writer::XLSX->new( \*STDOUT );
my $worksheet = $workbook->add_worksheet();
# Set the column width for column 1
$worksheet->set_column( 0, 0, 20 );
# Create a format
my $format = $workbook->add_format();
$format->set_bold();
$format->set_size( 15 );
$format->set_color( 'blue' );
# Write to the workbook
$worksheet->write( 0, 0, "Hi Excel!", $format );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/cgi.pl>
=head2 Example: chart_area.pl
A demo of an Area chart in Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_area.jpg" width="640" height="420" alt="Output from chart_area.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of an Area chart in Excel::Writer::XLSX.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_area.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 40, 40, 50, 30, 25, 50 ],
[ 30, 25, 30, 10, 5, 10 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart1 = $workbook->add_chart( type => 'area', embedded => 1 );
# Configure the first series.
$chart1->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series. Note alternative use of array ref to define
# ranges: [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
$chart1->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart1->set_title ( name => 'Results of sample analysis' );
$chart1->set_x_axis( name => 'Test number' );
$chart1->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart1->set_style( 11 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart1, 25, 10 );
#
# Create a stacked chart sub-type
#
my $chart2 = $workbook->add_chart(
type => 'area',
embedded => 1,
subtype => 'stacked'
);
# Configure the first series.
$chart2->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart2->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart2->set_title ( name => 'Stacked Chart' );
$chart2->set_x_axis( name => 'Test number' );
$chart2->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart2->set_style( 12 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D18', $chart2, 25, 11 );
#
# Create a percent stacked chart sub-type
#
my $chart3 = $workbook->add_chart(
type => 'area',
embedded => 1,
subtype => 'percent_stacked'
);
# Configure the first series.
$chart3->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart3->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart3->set_title ( name => 'Percent Stacked Chart' );
$chart3->set_x_axis( name => 'Test number' );
$chart3->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart3->set_style( 13 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D34', $chart3, 25, 11 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_area.pl>
=head2 Example: chart_bar.pl
A demo of an Bar chart in Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_bar.jpg" width="640" height="420" alt="Output from chart_bar.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of an Bar chart in Excel::Writer::XLSX.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_bar.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 10, 40, 50, 20, 10, 50 ],
[ 30, 60, 70, 50, 40, 30 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart1 = $workbook->add_chart( type => 'bar', embedded => 1 );
# Configure the first series.
$chart1->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series. Note alternative use of array ref to define
# ranges: [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
$chart1->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart1->set_title ( name => 'Results of sample analysis' );
$chart1->set_x_axis( name => 'Test number' );
$chart1->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart1->set_style( 11 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart1, 25, 10 );
#
# Create a stacked chart sub-type
#
my $chart2 = $workbook->add_chart(
type => 'bar',
embedded => 1,
subtype => 'stacked'
);
# Configure the first series.
$chart2->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart2->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart2->set_title ( name => 'Stacked Chart' );
$chart2->set_x_axis( name => 'Test number' );
$chart2->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart2->set_style( 12 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D18', $chart2, 25, 11 );
#
# Create a percent stacked chart sub-type
#
my $chart3 = $workbook->add_chart(
type => 'bar',
embedded => 1,
subtype => 'percent_stacked'
);
# Configure the first series.
$chart3->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart3->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart3->set_title ( name => 'Percent Stacked Chart' );
$chart3->set_x_axis( name => 'Test number' );
$chart3->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart3->set_style( 13 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D34', $chart3, 25, 11 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_bar.pl>
=head2 Example: chart_column.pl
A demo of an Column chart in Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_column.jpg" width="640" height="420" alt="Output from chart_column.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of an Column chart in Excel::Writer::XLSX.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_column.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 10, 40, 50, 20, 10, 50 ],
[ 30, 60, 70, 50, 40, 30 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart1 = $workbook->add_chart( type => 'column', embedded => 1 );
# Configure the first series.
$chart1->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series. Note alternative use of array ref to define
# ranges: [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
$chart1->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart1->set_title ( name => 'Results of sample analysis' );
$chart1->set_x_axis( name => 'Test number' );
$chart1->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart1->set_style( 11 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart1, 25, 10 );
#
# Create a stacked chart sub-type
#
my $chart2 = $workbook->add_chart(
type => 'column',
embedded => 1,
subtype => 'stacked'
);
# Configure the first series.
$chart2->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart2->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart2->set_title ( name => 'Stacked Chart' );
$chart2->set_x_axis( name => 'Test number' );
$chart2->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart2->set_style( 12 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D18', $chart2, 25, 11 );
#
# Create a percent stacked chart sub-type
#
my $chart3 = $workbook->add_chart(
type => 'column',
embedded => 1,
subtype => 'percent_stacked'
);
# Configure the first series.
$chart3->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart3->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart3->set_title ( name => 'Percent Stacked Chart' );
$chart3->set_x_axis( name => 'Test number' );
$chart3->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart3->set_style( 13 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D34', $chart3, 25, 11 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_column.pl>
=head2 Example: chart_line.pl
A demo of a Line chart in Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_line.jpg" width="640" height="420" alt="Output from chart_line.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of a Line chart in Excel::Writer::XLSX.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_line.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 10, 40, 50, 20, 10, 50 ],
[ 30, 60, 70, 50, 40, 30 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart = $workbook->add_chart( type => 'line', embedded => 1 );
# Configure the first series.
$chart->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series. Note alternative use of array ref to define
# ranges: [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
$chart->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart->set_title ( name => 'Results of sample analysis' );
$chart->set_x_axis( name => 'Test number' );
$chart->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Colors with white outline and shadow.
$chart->set_style( 10 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart, 25, 10 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_line.pl>
=head2 Example: chart_pie.pl
A demo of a Pie chart in Excel::Writer::XLSX.
The demo also shows how to set segment colours. It is possible to
define chart colors for most types of Excel::Writer::XLSX charts
via the add_series() method. However, Pie charts are a special case
since each segment is represented as a point so it is necessary to
assign formatting to each point in the series.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_pie.jpg" width="640" height="420" alt="Output from chart_pie.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of a Pie chart in Excel::Writer::XLSX.
#
# The demo also shows how to set segment colours. It is possible to
# define chart colors for most types of Excel::Writer::XLSX charts
# via the add_series() method. However, Pie charts are a special case
# since each segment is represented as a point so it is necessary to
# assign formatting to each point in the series.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_pie.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Category', 'Values' ];
my $data = [
[ 'Apple', 'Cherry', 'Pecan' ],
[ 60, 30, 10 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart1 = $workbook->add_chart( type => 'pie', embedded => 1 );
# Configure the series. Note the use of the array ref to define ranges:
# [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
# See below for an alternative syntax.
$chart1->add_series(
name => 'Pie sales data',
categories => [ 'Sheet1', 1, 3, 0, 0 ],
values => [ 'Sheet1', 1, 3, 1, 1 ],
);
# Add a title.
$chart1->set_title( name => 'Popular Pie Types' );
# Set an Excel chart style. Colors with white outline and shadow.
$chart1->set_style( 10 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'C2', $chart1, 25, 10 );
#
# Create a Pie chart with user defined segment colors.
#
# Create an example Pie chart like above.
my $chart2 = $workbook->add_chart( type => 'pie', embedded => 1 );
# Configure the series and add user defined segment colours.
$chart2->add_series(
name => 'Pie sales data',
categories => '=Sheet1!$A$2:$A$4',
values => '=Sheet1!$B$2:$B$4',
points => [
{ fill => { color => '#5ABA10' } },
{ fill => { color => '#FE110E' } },
{ fill => { color => '#CA5C05' } },
],
);
# Add a title.
$chart2->set_title( name => 'Pie Chart with user defined colors' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'C18', $chart2, 25, 10 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_pie.pl>
=head2 Example: chart_radar.pl
A demo of an Radar chart in Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_radar.jpg" width="640" height="420" alt="Output from chart_radar.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of an Radar chart in Excel::Writer::XLSX.
#
# reverse ('(c)'), October 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_radar.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 30, 60, 70, 50, 40, 30 ],
[ 25, 40, 50, 30, 50, 40 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart1 = $workbook->add_chart( type => 'radar', embedded => 1 );
# Configure the first series.
$chart1->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series. Note alternative use of array ref to define
# ranges: [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
$chart1->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart1->set_title ( name => 'Results of sample analysis' );
$chart1->set_x_axis( name => 'Test number' );
$chart1->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart1->set_style( 11 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart1, 25, 10 );
#
# Create a with_markers chart sub-type
#
my $chart2 = $workbook->add_chart(
type => 'radar',
embedded => 1,
subtype => 'with_markers'
);
# Configure the first series.
$chart2->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart2->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart2->set_title ( name => 'Stacked Chart' );
$chart2->set_x_axis( name => 'Test number' );
$chart2->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart2->set_style( 12 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D18', $chart2, 25, 11 );
#
# Create a filled chart sub-type
#
my $chart3 = $workbook->add_chart(
type => 'radar',
embedded => 1,
subtype => 'filled'
);
# Configure the first series.
$chart3->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart3->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart3->set_title ( name => 'Percent Stacked Chart' );
$chart3->set_x_axis( name => 'Test number' );
$chart3->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart3->set_style( 13 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D34', $chart3, 25, 11 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_radar.pl>
=head2 Example: chart_scatter.pl
A demo of a Scatter chart in Excel::Writer::XLSX. Other subtypes are
also supported such as markers_only (the default), straight_with_markers,
straight, smooth_with_markers and smooth. See the main documentation for
more details.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_scatter.jpg" width="640" height="420" alt="Output from chart_scatter.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of a Scatter chart in Excel::Writer::XLSX. Other subtypes are
# also supported such as markers_only (the default), straight_with_markers,
# straight, smooth_with_markers and smooth. See the main documentation for
# more details.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_scatter.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 10, 40, 50, 20, 10, 50 ],
[ 30, 60, 70, 50, 40, 30 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart1 = $workbook->add_chart( type => 'scatter', embedded => 1 );
# Configure the first series.
$chart1->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series. Note alternative use of array ref to define
# ranges: [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
$chart1->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart1->set_title ( name => 'Results of sample analysis' );
$chart1->set_x_axis( name => 'Test number' );
$chart1->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart1->set_style( 11 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart1, 25, 10 );
#
# Create a scatter chart sub-type with straight lines and markers.
#
my $chart2 = $workbook->add_chart(
type => 'scatter',
embedded => 1,
subtype => 'straight_with_markers'
);
# Configure the first series.
$chart2->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart2->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart2->set_title ( name => 'Straight line with markers' );
$chart2->set_x_axis( name => 'Test number' );
$chart2->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart2->set_style( 12 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D18', $chart2, 25, 11 );
#
# Create a scatter chart sub-type with straight lines and no markers.
#
my $chart3 = $workbook->add_chart(
type => 'scatter',
embedded => 1,
subtype => 'straight'
);
# Configure the first series.
$chart3->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart3->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart3->set_title ( name => 'Straight line' );
$chart3->set_x_axis( name => 'Test number' );
$chart3->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart3->set_style( 13 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D34', $chart3, 25, 11 );
#
# Create a scatter chart sub-type with smooth lines and markers.
#
my $chart4 = $workbook->add_chart(
type => 'scatter',
embedded => 1,
subtype => 'smooth_with_markers'
);
# Configure the first series.
$chart4->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart4->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart4->set_title ( name => 'Smooth line with markers' );
$chart4->set_x_axis( name => 'Test number' );
$chart4->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart4->set_style( 14 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D51', $chart4, 25, 11 );
#
# Create a scatter chart sub-type with smooth lines and no markers.
#
my $chart5 = $workbook->add_chart(
type => 'scatter',
embedded => 1,
subtype => 'smooth'
);
# Configure the first series.
$chart5->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart5->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart5->set_title ( name => 'Smooth line' );
$chart5->set_x_axis( name => 'Test number' );
$chart5->set_y_axis( name => 'Sample length (mm)' );
# Set an Excel chart style. Blue colors with white outline and shadow.
$chart5->set_style( 15 );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D66', $chart5, 25, 11 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_scatter.pl>
=head2 Example: chart_secondary_axis.pl
A demo of a Line chart with a secondary axis in Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_secondary_axis.jpg" width="640" height="420" alt="Output from chart_secondary_axis.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of a Line chart with a secondary axis in Excel::Writer::XLSX.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_secondary_axis.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Aliens', 'Humans', ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 10, 40, 50, 20, 10, 50 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a new chart object. In this case an embedded chart.
my $chart = $workbook->add_chart( type => 'line', embedded => 1 );
# Configure a series with a secondary axis
$chart->add_series(
name => '=Sheet1!$A$1',
values => '=Sheet1!$A$2:$A$7',
y2_axis => 1,
);
$chart->add_series(
name => '=Sheet1!$B$1',
values => '=Sheet1!$B$2:$B$7',
);
$chart->set_legend( position => 'right' );
# Add a chart title and some axis labels.
$chart->set_title( name => 'Survey results' );
$chart->set_x_axis( name => 'Days', );
$chart->set_y_axis( name => 'Population', major_gridlines => { visible => 0 } );
$chart->set_y2_axis( name => 'Laser wounds' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart, 25, 10 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_secondary_axis.pl>
=head2 Example: chart_stock.pl
A demo of a Stock chart in Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_stock.jpg" width="640" height="420" alt="Output from chart_stock.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of a Stock chart in Excel::Writer::XLSX.
#
# reverse ('(c)'), March 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_stock.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
my $date_format = $workbook->add_format( num_format => 'dd/mm/yyyy' );
my $chart = $workbook->add_chart( type => 'stock', embedded => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Date', 'High', 'Low', 'Close' ];
my $data = [
[ '2007-01-01T', '2007-01-02T', '2007-01-03T', '2007-01-04T', '2007-01-05T' ],
[ 27.2, 25.03, 19.05, 20.34, 18.5 ],
[ 23.49, 19.55, 15.12, 17.84, 16.34 ],
[ 25.45, 23.05, 17.32, 20.45, 17.34 ],
];
$worksheet->write( 'A1', $headings, $bold );
for my $row ( 0 .. 4 ) {
$worksheet->write_date_time( $row+1, 0, $data->[0]->[$row], $date_format );
$worksheet->write( $row+1, 1, $data->[1]->[$row] );
$worksheet->write( $row+1, 2, $data->[2]->[$row] );
$worksheet->write( $row+1, 3, $data->[3]->[$row] );
}
$worksheet->set_column( 'A:D', 11 );
# Add a series for each of the High-Low-Close columns.
$chart->add_series(
categories => '=Sheet1!$A$2:$A$6',
values => '=Sheet1!$B$2:$B$6',
);
$chart->add_series(
categories => '=Sheet1!$A$2:$A$6',
values => '=Sheet1!$C$2:$C$6',
);
$chart->add_series(
categories => '=Sheet1!$A$2:$A$6',
values => '=Sheet1!$D$2:$D$6',
);
# Add a chart title and some axis labels.
$chart->set_title ( name => 'High-Low-Close', );
$chart->set_x_axis( name => 'Date', );
$chart->set_y_axis( name => 'Share price', );
$worksheet->insert_chart( 'E9', $chart );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_stock.pl>
=head2 Example: chart_data_table.pl
A demo of an Column chart with a data table on the X-axis using
Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_data_table.jpg" width="640" height="420" alt="Output from chart_data_table.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of an Column chart with a data table on the X-axis using
# Excel::Writer::XLSX.
#
# reverse ('(c)'), December 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_data_table.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Batch 1', 'Batch 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 10, 40, 50, 20, 10, 50 ],
[ 30, 60, 70, 50, 40, 30 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
# Create a column chart with a data table.
my $chart1 = $workbook->add_chart( type => 'column', embedded => 1 );
# Configure the first series.
$chart1->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series. Note alternative use of array ref to define
# ranges: [ $sheetname, $row_start, $row_end, $col_start, $col_end ].
$chart1->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart1->set_title( name => 'Chart with Data Table' );
$chart1->set_x_axis( name => 'Test number' );
$chart1->set_y_axis( name => 'Sample length (mm)' );
# Set a default data table on the X-Axis.
$chart1->set_table();
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart1, 25, 10 );
#
# Create a second chart.
#
my $chart2 = $workbook->add_chart( type => 'column', embedded => 1 );
# Configure the first series.
$chart2->add_series(
name => '=Sheet1!$B$1',
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure second series.
$chart2->add_series(
name => '=Sheet1!$C$1',
categories => [ 'Sheet1', 1, 6, 0, 0 ],
values => [ 'Sheet1', 1, 6, 2, 2 ],
);
# Add a chart title and some axis labels.
$chart2->set_title( name => 'Data Table with legend keys' );
$chart2->set_x_axis( name => 'Test number' );
$chart2->set_y_axis( name => 'Sample length (mm)' );
# Set a data table on the X-Axis with the legend keys showm.
$chart2->set_table( show_keys => 1 );
# Hide the chart legend since the keys are show on the data table.
$chart2->set_legend( position => 'none' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D18', $chart2, 25, 11 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_data_table.pl>
=head2 Example: chart_data_tools.pl
A demo of an various Excel chart data tools that are available via
an Excel::Writer::XLSX chart.
These include, Trendlines, Data Labels, Error Bars, Drop Lines,
High-Low Lines and Up-Down Bars.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/chart_data_tools.jpg" width="640" height="420" alt="Output from chart_data_tools.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A demo of an various Excel chart data tools that are available via
# an Excel::Writer::XLSX chart.
#
# These include, Trendlines, Data Labels, Error Bars, Drop Lines,
# High-Low Lines and Up-Down Bars.
#
# reverse ('(c)'), December 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'chart_data_tools.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Add the worksheet data that the charts will refer to.
my $headings = [ 'Number', 'Data 1', 'Data 2' ];
my $data = [
[ 2, 3, 4, 5, 6, 7 ],
[ 10, 40, 50, 20, 10, 50 ],
[ 30, 60, 70, 50, 40, 30 ],
];
$worksheet->write( 'A1', $headings, $bold );
$worksheet->write( 'A2', $data );
#######################################################################
#
# Trendline example.
#
# Create a Line chart.
my $chart1 = $workbook->add_chart( type => 'line', embedded => 1 );
# Configure the first series with a polynomial trendline.
$chart1->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
trendline => {
type => 'polynomial',
order => 3,
},
);
# Configure the second series with a moving average trendline.
$chart1->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$C$2:$C$7',
trendline => { type => 'linear' },
);
# Add a chart title. and some axis labels.
$chart1->set_title( name => 'Chart with Trendlines' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D2', $chart1, 25, 10 );
#######################################################################
#
# Data Labels and Markers example.
#
# Create a Line chart.
my $chart2 = $workbook->add_chart( type => 'line', embedded => 1 );
# Configure the first series.
$chart2->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
data_labels => { value => 1 },
marker => { type => 'automatic' },
);
# Configure the second series.
$chart2->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$C$2:$C$7',
);
# Add a chart title. and some axis labels.
$chart2->set_title( name => 'Chart with Data Labels and Markers' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D18', $chart2, 25, 10 );
#######################################################################
#
# Error Bars example.
#
# Create a Line chart.
my $chart3 = $workbook->add_chart( type => 'line', embedded => 1 );
# Configure the first series.
$chart3->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
y_error_bars => { type => 'standard_error' },
);
# Configure the second series.
$chart3->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$C$2:$C$7',
);
# Add a chart title. and some axis labels.
$chart3->set_title( name => 'Chart with Error Bars' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D34', $chart3, 25, 10 );
#######################################################################
#
# Up-Down Bars example.
#
# Create a Line chart.
my $chart4 = $workbook->add_chart( type => 'line', embedded => 1 );
# Add the Up-Down Bars.
$chart4->set_up_down_bars();
# Configure the first series.
$chart4->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure the second series.
$chart4->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$C$2:$C$7',
);
# Add a chart title. and some axis labels.
$chart4->set_title( name => 'Chart with Up-Down Bars' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D50', $chart4, 25, 10 );
#######################################################################
#
# High-Low Lines example.
#
# Create a Line chart.
my $chart5 = $workbook->add_chart( type => 'line', embedded => 1 );
# Add the High-Low lines.
$chart5->set_high_low_lines();
# Configure the first series.
$chart5->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure the second series.
$chart5->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$C$2:$C$7',
);
# Add a chart title. and some axis labels.
$chart5->set_title( name => 'Chart with High-Low Lines' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D66', $chart5, 25, 10 );
#######################################################################
#
# Drop Lines example.
#
# Create a Line chart.
my $chart6 = $workbook->add_chart( type => 'line', embedded => 1 );
# Add Drop Lines.
$chart6->set_drop_lines();
# Configure the first series.
$chart6->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$B$2:$B$7',
);
# Configure the second series.
$chart6->add_series(
categories => '=Sheet1!$A$2:$A$7',
values => '=Sheet1!$C$2:$C$7',
);
# Add a chart title. and some axis labels.
$chart6->set_title( name => 'Chart with Drop Lines' );
# Insert the chart into the worksheet (with an offset).
$worksheet->insert_chart( 'D82', $chart6, 25, 10 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/chart_data_tools.pl>
=head2 Example: colors.pl
Demonstrates Excel::Writer::XLSX's named colours and the Excel colour
palette.
The set_custom_color() Worksheet method can be used to override one of the
built-in palette values with a more suitable colour. See the main docs.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/colors.jpg" width="640" height="420" alt="Output from colors.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
################################################################################
#
# Demonstrates Excel::Writer::XLSX's named colours and the Excel colour
# palette.
#
# The set_custom_color() Worksheet method can be used to override one of the
# built-in palette values with a more suitable colour. See the main docs.
#
# reverse ('(c)'), March 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'colors.xlsx' );
# Some common formats
my $center = $workbook->add_format( align => 'center' );
my $heading = $workbook->add_format( align => 'center', bold => 1 );
######################################################################
#
# Demonstrate the named colors.
#
my %colors = (
0x08, 'black',
0x0C, 'blue',
0x10, 'brown',
0x0F, 'cyan',
0x17, 'gray',
0x11, 'green',
0x0B, 'lime',
0x0E, 'magenta',
0x12, 'navy',
0x35, 'orange',
0x21, 'pink',
0x14, 'purple',
0x0A, 'red',
0x16, 'silver',
0x09, 'white',
0x0D, 'yellow',
);
my $worksheet1 = $workbook->add_worksheet( 'Named colors' );
$worksheet1->set_column( 0, 3, 15 );
$worksheet1->write( 0, 0, "Index", $heading );
$worksheet1->write( 0, 1, "Index", $heading );
$worksheet1->write( 0, 2, "Name", $heading );
$worksheet1->write( 0, 3, "Color", $heading );
my $i = 1;
while ( my ( $index, $color ) = each %colors ) {
my $format = $workbook->add_format(
fg_color => $color,
pattern => 1,
border => 1
);
$worksheet1->write( $i + 1, 0, $index, $center );
$worksheet1->write( $i + 1, 1, sprintf( "0x%02X", $index ), $center );
$worksheet1->write( $i + 1, 2, $color, $center );
$worksheet1->write( $i + 1, 3, '', $format );
$i++;
}
######################################################################
#
# Demonstrate the standard Excel colors in the range 8..63.
#
my $worksheet2 = $workbook->add_worksheet( 'Standard colors' );
$worksheet2->set_column( 0, 3, 15 );
$worksheet2->write( 0, 0, "Index", $heading );
$worksheet2->write( 0, 1, "Index", $heading );
$worksheet2->write( 0, 2, "Color", $heading );
$worksheet2->write( 0, 3, "Name", $heading );
for my $i ( 8 .. 63 ) {
my $format = $workbook->add_format(
fg_color => $i,
pattern => 1,
border => 1
);
$worksheet2->write( ( $i - 7 ), 0, $i, $center );
$worksheet2->write( ( $i - 7 ), 1, sprintf( "0x%02X", $i ), $center );
$worksheet2->write( ( $i - 7 ), 2, '', $format );
# Add the color names
if ( exists $colors{$i} ) {
$worksheet2->write( ( $i - 7 ), 3, $colors{$i}, $center );
}
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/colors.pl>
=head2 Example: comments1.pl
This example demonstrates writing cell comments.
A cell comment is indicated in Excel by a small red triangle in the upper
right-hand corner of the cell.
For more advanced comment options see comments2.pl.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/comments1.jpg" width="640" height="420" alt="Output from comments1.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# This example demonstrates writing cell comments.
#
# A cell comment is indicated in Excel by a small red triangle in the upper
# right-hand corner of the cell.
#
# For more advanced comment options see comments2.pl.
#
# reverse ('(c)'), November 2005, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'comments1.xlsx' );
my $worksheet = $workbook->add_worksheet();
$worksheet->write( 'A1', 'Hello' );
$worksheet->write_comment( 'A1', 'This is a comment' );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/comments1.pl>
=head2 Example: comments2.pl
This example demonstrates writing cell comments.
A cell comment is indicated in Excel by a small red triangle in the upper
right-hand corner of the cell.
Each of the worksheets demonstrates different features of cell comments.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/comments2.jpg" width="640" height="420" alt="Output from comments2.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# This example demonstrates writing cell comments.
#
# A cell comment is indicated in Excel by a small red triangle in the upper
# right-hand corner of the cell.
#
# Each of the worksheets demonstrates different features of cell comments.
#
# reverse ('(c)'), November 2005, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'comments2.xlsx' );
my $text_wrap = $workbook->add_format( text_wrap => 1, valign => 'top' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $worksheet3 = $workbook->add_worksheet();
my $worksheet4 = $workbook->add_worksheet();
my $worksheet5 = $workbook->add_worksheet();
my $worksheet6 = $workbook->add_worksheet();
my $worksheet7 = $workbook->add_worksheet();
my $worksheet8 = $workbook->add_worksheet();
# Variables that we will use in each example.
my $cell_text = '';
my $comment = '';
###############################################################################
#
# Example 1. Demonstrates a simple cell comments without formatting.
# comments.
#
# Set up some formatting.
$worksheet1->set_column( 'C:C', 25 );
$worksheet1->set_row( 2, 50 );
$worksheet1->set_row( 5, 50 );
# Simple ascii string.
$cell_text = 'Hold the mouse over this cell to see the comment.';
$comment = 'This is a comment.';
$worksheet1->write( 'C3', $cell_text, $text_wrap );
$worksheet1->write_comment( 'C3', $comment );
$cell_text = 'This is a UTF-8 string.';
$comment = chr 0x263a;
$worksheet1->write( 'C6', $cell_text, $text_wrap );
$worksheet1->write_comment( 'C6', $comment );
###############################################################################
#
# Example 2. Demonstrates visible and hidden comments.
#
# Set up some formatting.
$worksheet2->set_column( 'C:C', 25 );
$worksheet2->set_row( 2, 50 );
$worksheet2->set_row( 5, 50 );
$cell_text = 'This cell comment is visible.';
$comment = 'Hello.';
$worksheet2->write( 'C3', $cell_text, $text_wrap );
$worksheet2->write_comment( 'C3', $comment, visible => 1 );
$cell_text = "This cell comment isn't visible (the default).";
$comment = 'Hello.';
$worksheet2->write( 'C6', $cell_text, $text_wrap );
$worksheet2->write_comment( 'C6', $comment );
###############################################################################
#
# Example 3. Demonstrates visible and hidden comments set at the worksheet
# level.
#
# Set up some formatting.
$worksheet3->set_column( 'C:C', 25 );
$worksheet3->set_row( 2, 50 );
$worksheet3->set_row( 5, 50 );
$worksheet3->set_row( 8, 50 );
# Make all comments on the worksheet visible.
$worksheet3->show_comments();
$cell_text = 'This cell comment is visible, explicitly.';
$comment = 'Hello.';
$worksheet3->write( 'C3', $cell_text, $text_wrap );
$worksheet3->write_comment( 'C3', $comment, visible => 1 );
$cell_text =
'This cell comment is also visible because ' . 'we used show_comments().';
$comment = 'Hello.';
$worksheet3->write( 'C6', $cell_text, $text_wrap );
$worksheet3->write_comment( 'C6', $comment );
$cell_text = 'However, we can still override it locally.';
$comment = 'Hello.';
$worksheet3->write( 'C9', $cell_text, $text_wrap );
$worksheet3->write_comment( 'C9', $comment, visible => 0 );
###############################################################################
#
# Example 4. Demonstrates changes to the comment box dimensions.
#
# Set up some formatting.
$worksheet4->set_column( 'C:C', 25 );
$worksheet4->set_row( 2, 50 );
$worksheet4->set_row( 5, 50 );
$worksheet4->set_row( 8, 50 );
$worksheet4->set_row( 15, 50 );
$worksheet4->show_comments();
$cell_text = 'This cell comment is default size.';
$comment = 'Hello.';
$worksheet4->write( 'C3', $cell_text, $text_wrap );
$worksheet4->write_comment( 'C3', $comment );
$cell_text = 'This cell comment is twice as wide.';
$comment = 'Hello.';
$worksheet4->write( 'C6', $cell_text, $text_wrap );
$worksheet4->write_comment( 'C6', $comment, x_scale => 2 );
$cell_text = 'This cell comment is twice as high.';
$comment = 'Hello.';
$worksheet4->write( 'C9', $cell_text, $text_wrap );
$worksheet4->write_comment( 'C9', $comment, y_scale => 2 );
$cell_text = 'This cell comment is scaled in both directions.';
$comment = 'Hello.';
$worksheet4->write( 'C16', $cell_text, $text_wrap );
$worksheet4->write_comment( 'C16', $comment, x_scale => 1.2, y_scale => 0.8 );
$cell_text = 'This cell comment has width and height specified in pixels.';
$comment = 'Hello.';
$worksheet4->write( 'C19', $cell_text, $text_wrap );
$worksheet4->write_comment( 'C19', $comment, width => 200, height => 20 );
###############################################################################
#
# Example 5. Demonstrates changes to the cell comment position.
#
$worksheet5->set_column( 'C:C', 25 );
$worksheet5->set_row( 2, 50 );
$worksheet5->set_row( 5, 50 );
$worksheet5->set_row( 8, 50 );
$worksheet5->set_row( 11, 50 );
$worksheet5->show_comments();
$cell_text = 'This cell comment is in the default position.';
$comment = 'Hello.';
$worksheet5->write( 'C3', $cell_text, $text_wrap );
$worksheet5->write_comment( 'C3', $comment );
$cell_text = 'This cell comment has been moved to another cell.';
$comment = 'Hello.';
$worksheet5->write( 'C6', $cell_text, $text_wrap );
$worksheet5->write_comment( 'C6', $comment, start_cell => 'E4' );
$cell_text = 'This cell comment has been moved to another cell.';
$comment = 'Hello.';
$worksheet5->write( 'C9', $cell_text, $text_wrap );
$worksheet5->write_comment( 'C9', $comment, start_row => 8, start_col => 4 );
$cell_text = 'This cell comment has been shifted within its default cell.';
$comment = 'Hello.';
$worksheet5->write( 'C12', $cell_text, $text_wrap );
$worksheet5->write_comment( 'C12', $comment, x_offset => 30, y_offset => 12 );
###############################################################################
#
# Example 6. Demonstrates changes to the comment background colour.
#
$worksheet6->set_column( 'C:C', 25 );
$worksheet6->set_row( 2, 50 );
$worksheet6->set_row( 5, 50 );
$worksheet6->set_row( 8, 50 );
$worksheet6->show_comments();
$cell_text = 'This cell comment has a different colour.';
$comment = 'Hello.';
$worksheet6->write( 'C3', $cell_text, $text_wrap );
$worksheet6->write_comment( 'C3', $comment, color => 'green' );
$cell_text = 'This cell comment has the default colour.';
$comment = 'Hello.';
$worksheet6->write( 'C6', $cell_text, $text_wrap );
$worksheet6->write_comment( 'C6', $comment );
$cell_text = 'This cell comment has a different colour.';
$comment = 'Hello.';
$worksheet6->write( 'C9', $cell_text, $text_wrap );
$worksheet6->write_comment( 'C9', $comment, color => 0x35 );
###############################################################################
#
# Example 7. Demonstrates how to set the cell comment author.
#
$worksheet7->set_column( 'C:C', 30 );
$worksheet7->set_row( 2, 50 );
$worksheet7->set_row( 5, 50 );
$worksheet7->set_row( 8, 50 );
my $author = '';
my $cell = 'C3';
$cell_text = "Move the mouse over this cell and you will see 'Cell commented "
. "by $author' (blank) in the status bar at the bottom";
$comment = 'Hello.';
$worksheet7->write( $cell, $cell_text, $text_wrap );
$worksheet7->write_comment( $cell, $comment );
$author = 'Perl';
$cell = 'C6';
$cell_text = "Move the mouse over this cell and you will see 'Cell commented "
. "by $author' in the status bar at the bottom";
$comment = 'Hello.';
$worksheet7->write( $cell, $cell_text, $text_wrap );
$worksheet7->write_comment( $cell, $comment, author => $author );
$author = chr 0x20AC;
$cell = 'C9';
$cell_text = "Move the mouse over this cell and you will see 'Cell commented "
. "by $author' in the status bar at the bottom";
$comment = 'Hello.';
$worksheet7->write( $cell, $cell_text, $text_wrap );
$worksheet7->write_comment( $cell, $comment, author => $author );
###############################################################################
#
# Example 8. Demonstrates the need to explicitly set the row height.
#
# Set up some formatting.
$worksheet8->set_column( 'C:C', 25 );
$worksheet8->set_row( 2, 80 );
$worksheet8->show_comments();
$cell_text =
'The height of this row has been adjusted explicitly using '
. 'set_row(). The size of the comment box is adjusted '
. 'accordingly by Excel::Writer::XLSX.';
$comment = 'Hello.';
$worksheet8->write( 'C3', $cell_text, $text_wrap );
$worksheet8->write_comment( 'C3', $comment );
$cell_text =
'The height of this row has been adjusted by Excel due to the '
. 'text wrap property being set. Unfortunately this means that '
. 'the height of the row is unknown to Excel::Writer::XLSX at '
. "run time and thus the comment box is stretched as well.\n\n"
. 'Use set_row() to specify the row height explicitly to avoid '
. 'this problem.';
$comment = 'Hello.';
$worksheet8->write( 'C6', $cell_text, $text_wrap );
$worksheet8->write_comment( 'C6', $comment );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/comments2.pl>
=head2 Example: conditional_format.pl
Example of how to add conditional formatting to an Excel::Writer::XLSX file.
Conditional formatting allows you to apply a format to a cell or a range of
cells based on certain criteria.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/conditional_format.jpg" width="640" height="420" alt="Output from conditional_format.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to add conditional formatting to an Excel::Writer::XLSX file.
#
# Conditional formatting allows you to apply a format to a cell or a range of
# cells based on certain criteria.
#
# reverse ('(c)'), October 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'conditional_format.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $worksheet3 = $workbook->add_worksheet();
my $worksheet4 = $workbook->add_worksheet();
my $worksheet5 = $workbook->add_worksheet();
my $worksheet6 = $workbook->add_worksheet();
my $worksheet7 = $workbook->add_worksheet();
my $worksheet8 = $workbook->add_worksheet();
# Light red fill with dark red text.
my $format1 = $workbook->add_format(
bg_color => '#FFC7CE',
color => '#9C0006',
);
# Green fill with dark green text.
my $format2 = $workbook->add_format(
bg_color => '#C6EFCE',
color => '#006100',
);
# Some sample data to run the conditional formatting against.
my $data = [
[ 34, 72, 38, 30, 75, 48, 75, 66, 84, 86 ],
[ 6, 24, 1, 84, 54, 62, 60, 3, 26, 59 ],
[ 28, 79, 97, 13, 85, 93, 93, 22, 5, 14 ],
[ 27, 71, 40, 17, 18, 79, 90, 93, 29, 47 ],
[ 88, 25, 33, 23, 67, 1, 59, 79, 47, 36 ],
[ 24, 100, 20, 88, 29, 33, 38, 54, 54, 88 ],
[ 6, 57, 88, 28, 10, 26, 37, 7, 41, 48 ],
[ 52, 78, 1, 96, 26, 45, 47, 33, 96, 36 ],
[ 60, 54, 81, 66, 81, 90, 80, 93, 12, 55 ],
[ 70, 5, 46, 14, 71, 19, 66, 36, 41, 21 ],
];
###############################################################################
#
# Example 1.
#
my $caption = 'Cells with values >= 50 are in light red. '
. 'Values < 50 are in light green.';
# Write the data.
$worksheet1->write( 'A1', $caption );
$worksheet1->write_col( 'B3', $data );
# Write a conditional format over a range.
$worksheet1->conditional_formatting( 'B3:K12',
{
type => 'cell',
criteria => '>=',
value => 50,
format => $format1,
}
);
# Write another conditional format over the same range.
$worksheet1->conditional_formatting( 'B3:K12',
{
type => 'cell',
criteria => '<',
value => 50,
format => $format2,
}
);
###############################################################################
#
# Example 2.
#
$caption = 'Values between 30 and 70 are in light red. '
. 'Values outside that range are in light green.';
$worksheet2->write( 'A1', $caption );
$worksheet2->write_col( 'B3', $data );
$worksheet2->conditional_formatting( 'B3:K12',
{
type => 'cell',
criteria => 'between',
minimum => 30,
maximum => 70,
format => $format1,
}
);
$worksheet2->conditional_formatting( 'B3:K12',
{
type => 'cell',
criteria => 'not between',
minimum => 30,
maximum => 70,
format => $format2,
}
);
###############################################################################
#
# Example 3.
#
$caption = 'Duplicate values are in light red. '
. 'Unique values are in light green.';
$worksheet3->write( 'A1', $caption );
$worksheet3->write_col( 'B3', $data );
$worksheet3->conditional_formatting( 'B3:K12',
{
type => 'duplicate',
format => $format1,
}
);
$worksheet3->conditional_formatting( 'B3:K12',
{
type => 'unique',
format => $format2,
}
);
###############################################################################
#
# Example 4.
#
$caption = 'Above average values are in light red. '
. 'Below average values are in light green.';
$worksheet4->write( 'A1', $caption );
$worksheet4->write_col( 'B3', $data );
$worksheet4->conditional_formatting( 'B3:K12',
{
type => 'average',
criteria => 'above',
format => $format1,
}
);
$worksheet4->conditional_formatting( 'B3:K12',
{
type => 'average',
criteria => 'below',
format => $format2,
}
);
###############################################################################
#
# Example 5.
#
$caption = 'Top 10 values are in light red. '
. 'Bottom 10 values are in light green.';
$worksheet5->write( 'A1', $caption );
$worksheet5->write_col( 'B3', $data );
$worksheet5->conditional_formatting( 'B3:K12',
{
type => 'top',
value => '10',
format => $format1,
}
);
$worksheet5->conditional_formatting( 'B3:K12',
{
type => 'bottom',
value => '10',
format => $format2,
}
);
###############################################################################
#
# Example 6.
#
$caption = 'Cells with values >= 50 are in light red. '
. 'Values < 50 are in light green. Non-contiguous ranges.';
# Write the data.
$worksheet6->write( 'A1', $caption );
$worksheet6->write_col( 'B3', $data );
# Write a conditional format over a range.
$worksheet6->conditional_formatting( 'B3:K6,B9:K12',
{
type => 'cell',
criteria => '>=',
value => 50,
format => $format1,
}
);
# Write another conditional format over the same range.
$worksheet6->conditional_formatting( 'B3:K6,B9:K12',
{
type => 'cell',
criteria => '<',
value => 50,
format => $format2,
}
);
###############################################################################
#
# Example 7.
#
$caption = 'Examples of color scales and data bars. Default colors.';
$data = [ 1 .. 12 ];
$worksheet7->write( 'A1', $caption );
$worksheet7->write ( 'B2', "2 Color Scale" );
$worksheet7->write_col( 'B3', $data );
$worksheet7->write ( 'D2', "3 Color Scale" );
$worksheet7->write_col( 'D3', $data );
$worksheet7->write ( 'F2', "Data Bars" );
$worksheet7->write_col( 'F3', $data );
$worksheet7->conditional_formatting( 'B3:B14',
{
type => '2_color_scale',
}
);
$worksheet7->conditional_formatting( 'D3:D14',
{
type => '3_color_scale',
}
);
$worksheet7->conditional_formatting( 'F3:F14',
{
type => 'data_bar',
}
);
###############################################################################
#
# Example 8.
#
$caption = 'Examples of color scales and data bars. Modified colors.';
$data = [ 1 .. 12 ];
$worksheet8->write( 'A1', $caption );
$worksheet8->write ( 'B2', "2 Color Scale" );
$worksheet8->write_col( 'B3', $data );
$worksheet8->write ( 'D2', "3 Color Scale" );
$worksheet8->write_col( 'D3', $data );
$worksheet8->write ( 'F2', "Data Bars" );
$worksheet8->write_col( 'F3', $data );
$worksheet8->conditional_formatting( 'B3:B14',
{
type => '2_color_scale',
min_color => "#FF0000",
max_color => "#00FF00",
}
);
$worksheet8->conditional_formatting( 'D3:D14',
{
type => '3_color_scale',
min_color => "#C5D9F1",
mid_color => "#8DB4E3",
max_color => "#538ED5",
}
);
$worksheet8->conditional_formatting( 'F3:F14',
{
type => 'data_bar',
bar_color => '#63C384'
}
);
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/conditional_format.pl>
=head2 Example: data_validate.pl
Example of how to add data validation and dropdown lists to an
Excel::Writer::XLSX file.
Data validation is a feature of Excel which allows you to restrict the data
that a user enters in a cell and to display help and warning messages. It
also allows you to restrict input to values in a drop down list.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/data_validate.jpg" width="640" height="420" alt="Output from data_validate.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to add data validation and dropdown lists to an
# Excel::Writer::XLSX file.
#
# Data validation is a feature of Excel which allows you to restrict the data
# that a user enters in a cell and to display help and warning messages. It
# also allows you to restrict input to values in a drop down list.
#
# reverse ('(c)'), August 2008, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'data_validate.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Add a format for the header cells.
my $header_format = $workbook->add_format(
border => 1,
bg_color => 43,
bold => 1,
text_wrap => 1,
valign => 'vcenter',
indent => 1,
);
# Set up layout of the worksheet.
$worksheet->set_column( 'A:A', 68 );
$worksheet->set_column( 'B:B', 15 );
$worksheet->set_column( 'D:D', 15 );
$worksheet->set_row( 0, 36 );
$worksheet->set_selection( 'B3' );
# Write the header cells and some data that will be used in the examples.
my $row = 0;
my $txt;
my $heading1 = 'Some examples of data validation in Excel::Writer::XLSX';
my $heading2 = 'Enter values in this column';
my $heading3 = 'Sample Data';
$worksheet->write( 'A1', $heading1, $header_format );
$worksheet->write( 'B1', $heading2, $header_format );
$worksheet->write( 'D1', $heading3, $header_format );
$worksheet->write( 'D3', [ 'Integers', 1, 10 ] );
$worksheet->write( 'D4', [ 'List data', 'open', 'high', 'close' ] );
$worksheet->write( 'D5', [ 'Formula', '=AND(F5=50,G5=60)', 50, 60 ] );
#
# Example 1. Limiting input to an integer in a fixed range.
#
$txt = 'Enter an integer between 1 and 10';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'integer',
criteria => 'between',
minimum => 1,
maximum => 10,
}
);
#
# Example 2. Limiting input to an integer outside a fixed range.
#
$txt = 'Enter an integer that is not between 1 and 10 (using cell references)';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'integer',
criteria => 'not between',
minimum => '=E3',
maximum => '=F3',
}
);
#
# Example 3. Limiting input to an integer greater than a fixed value.
#
$txt = 'Enter an integer greater than 0';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'integer',
criteria => '>',
value => 0,
}
);
#
# Example 4. Limiting input to an integer less than a fixed value.
#
$txt = 'Enter an integer less than 10';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'integer',
criteria => '<',
value => 10,
}
);
#
# Example 5. Limiting input to a decimal in a fixed range.
#
$txt = 'Enter a decimal between 0.1 and 0.5';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'decimal',
criteria => 'between',
minimum => 0.1,
maximum => 0.5,
}
);
#
# Example 6. Limiting input to a value in a dropdown list.
#
$txt = 'Select a value from a drop down list';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'list',
source => [ 'open', 'high', 'close' ],
}
);
#
# Example 6. Limiting input to a value in a dropdown list.
#
$txt = 'Select a value from a drop down list (using a cell range)';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'list',
source => '=$E$4:$G$4',
}
);
#
# Example 7. Limiting input to a date in a fixed range.
#
$txt = 'Enter a date between 1/1/2008 and 12/12/2008';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'date',
criteria => 'between',
minimum => '2008-01-01T',
maximum => '2008-12-12T',
}
);
#
# Example 8. Limiting input to a time in a fixed range.
#
$txt = 'Enter a time between 6:00 and 12:00';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'time',
criteria => 'between',
minimum => 'T06:00',
maximum => 'T12:00',
}
);
#
# Example 9. Limiting input to a string greater than a fixed length.
#
$txt = 'Enter a string longer than 3 characters';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'length',
criteria => '>',
value => 3,
}
);
#
# Example 10. Limiting input based on a formula.
#
$txt = 'Enter a value if the following is true "=AND(F5=50,G5=60)"';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'custom',
value => '=AND(F5=50,G5=60)',
}
);
#
# Example 11. Displaying and modify data validation messages.
#
$txt = 'Displays a message when you select the cell';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'integer',
criteria => 'between',
minimum => 1,
maximum => 100,
input_title => 'Enter an integer:',
input_message => 'between 1 and 100',
}
);
#
# Example 12. Displaying and modify data validation messages.
#
$txt = 'Display a custom error message when integer isn\'t between 1 and 100';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'integer',
criteria => 'between',
minimum => 1,
maximum => 100,
input_title => 'Enter an integer:',
input_message => 'between 1 and 100',
error_title => 'Input value is not valid!',
error_message => 'It should be an integer between 1 and 100',
}
);
#
# Example 13. Displaying and modify data validation messages.
#
$txt =
'Display a custom information message when integer isn\'t between 1 and 100';
$row += 2;
$worksheet->write( $row, 0, $txt );
$worksheet->data_validation(
$row, 1,
{
validate => 'integer',
criteria => 'between',
minimum => 1,
maximum => 100,
input_title => 'Enter an integer:',
input_message => 'between 1 and 100',
error_title => 'Input value is not valid!',
error_message => 'It should be an integer between 1 and 100',
error_type => 'information',
}
);
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/data_validate.pl>
=head2 Example: date_time.pl
Excel::Writer::XLSX example of writing dates and times using the
write_date_time() Worksheet method.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/date_time.jpg" width="640" height="420" alt="Output from date_time.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Excel::Writer::XLSX example of writing dates and times using the
# write_date_time() Worksheet method.
#
# reverse ('(c)'), August 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'date_time.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
# Expand the first columns so that the date is visible.
$worksheet->set_column( "A:B", 30 );
# Write the column headers
$worksheet->write( 'A1', 'Formatted date', $bold );
$worksheet->write( 'B1', 'Format', $bold );
# Examples date and time formats. In the output file compare how changing
# the format codes change the appearance of the date.
#
my @date_formats = (
'dd/mm/yy',
'mm/dd/yy',
'',
'd mm yy',
'dd mm yy',
'',
'dd m yy',
'dd mm yy',
'dd mmm yy',
'dd mmmm yy',
'',
'dd mm y',
'dd mm yyy',
'dd mm yyyy',
'',
'd mmmm yyyy',
'',
'dd/mm/yy',
'dd/mm/yy hh:mm',
'dd/mm/yy hh:mm:ss',
'dd/mm/yy hh:mm:ss.000',
'',
'hh:mm',
'hh:mm:ss',
'hh:mm:ss.000',
);
# Write the same date and time using each of the above formats. The empty
# string formats create a blank line to make the example clearer.
#
my $row = 0;
for my $date_format ( @date_formats ) {
$row++;
next if $date_format eq '';
# Create a format for the date or time.
my $format = $workbook->add_format(
num_format => $date_format,
align => 'left'
);
# Write the same date using different formats.
$worksheet->write_date_time( $row, 0, '2004-08-01T12:30:45.123', $format );
$worksheet->write( $row, 1, $date_format );
}
# The following is an example of an invalid date. It is written as a string
# instead of a number. This is also Excel's default behaviour.
#
$row += 2;
$worksheet->write_date_time( $row, 0, '2004-13-01T12:30:45.123' );
$worksheet->write( $row, 1, 'Invalid date. Written as string.', $bold );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/date_time.pl>
=head2 Example: defined_name.pl
Example of how to create defined names in an Excel::Writer::XLSX file.
This method is used to define a user friendly name to represent a value,
a single cell or a range of cells in a workbook.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/defined_name.jpg" width="640" height="420" alt="Output from defined_name.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# Example of how to create defined names in an Excel::Writer::XLSX file.
#
# This method is used to define a user friendly name to represent a value,
# a single cell or a range of cells in a workbook.
#
# reverse ('(c)'), September 2008, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'defined_name.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
# Define some global/workbook names.
$workbook->define_name( 'Exchange_rate', '=0.96' );
$workbook->define_name( 'Sales', '=Sheet1!$G$1:$H$10' );
# Define a local/worksheet name.
$workbook->define_name( 'Sheet2!Sales', '=Sheet2!$G$1:$G$10' );
# Write some text in the file and one of the defined names in a formula.
for my $worksheet ( $workbook->sheets() ) {
$worksheet->set_column( 'A:A', 45 );
$worksheet->write( 'A1', 'This worksheet contains some defined names.' );
$worksheet->write( 'A2', 'See Formulas -> Name Manager above.' );
$worksheet->write( 'A3', 'Example formula in cell B3 ->' );
$worksheet->write( 'B3', '=Exchange_rate' );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/defined_name.pl>
=head2 Example: diag_border.pl
A simple formatting example that demonstrates how to add a diagonal cell
border with Excel::Writer::XLSX
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/diag_border.jpg" width="640" height="420" alt="Output from diag_border.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
##############################################################################
#
# A simple formatting example that demonstrates how to add a diagonal cell
# border with Excel::Writer::XLSX
#
# reverse ('(c)'), May 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'diag_border.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $format1 = $workbook->add_format( diag_type => '1' );
my $format2 = $workbook->add_format( diag_type => '2' );
my $format3 = $workbook->add_format( diag_type => '3' );
my $format4 = $workbook->add_format(
diag_type => '3',
diag_border => '7',
diag_color => 'red',
);
$worksheet->write( 'B3', 'Text', $format1 );
$worksheet->write( 'B6', 'Text', $format2 );
$worksheet->write( 'B9', 'Text', $format3 );
$worksheet->write( 'B12', 'Text', $format4 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/diag_border.pl>
=head2 Example: filehandle.pl
Example of using Excel::Writer::XLSX to write Excel files to different
filehandles.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/filehandle.jpg" width="640" height="420" alt="Output from filehandle.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of using Excel::Writer::XLSX to write Excel files to different
# filehandles.
#
# reverse ('(c)'), April 2003, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
use IO::Scalar;
###############################################################################
#
# Example 1. This demonstrates the standard way of creating an Excel file by
# specifying a file name.
#
my $workbook1 = Excel::Writer::XLSX->new( 'fh_01.xlsx' );
my $worksheet1 = $workbook1->add_worksheet();
$worksheet1->write( 0, 0, 'Hi Excel 1' );
###############################################################################
#
# Example 2. Write an Excel file to an existing filehandle.
#
open TEST, '>', 'fh_02.xlsx' or die "Couldn't open file: $!";
binmode TEST; # Always do this regardless of whether the platform requires it.
my $workbook2 = Excel::Writer::XLSX->new( \*TEST );
my $worksheet2 = $workbook2->add_worksheet();
$worksheet2->write( 0, 0, 'Hi Excel 2' );
###############################################################################
#
# Example 3. Write an Excel file to an existing OO style filehandle.
#
my $fh = FileHandle->new( '> fh_03.xlsx' ) or die "Couldn't open file: $!";
binmode( $fh );
my $workbook3 = Excel::Writer::XLSX->new( $fh );
my $worksheet3 = $workbook3->add_worksheet();
$worksheet3->write( 0, 0, 'Hi Excel 3' );
###############################################################################
#
# Example 4. Write an Excel file to a string via IO::Scalar. Please refer to
# the IO::Scalar documentation for further details.
#
my $xlsx_str;
tie *XLSX, 'IO::Scalar', \$xlsx_str;
my $workbook4 = Excel::Writer::XLSX->new( \*XLSX );
my $worksheet4 = $workbook4->add_worksheet();
$worksheet4->write( 0, 0, 'Hi Excel 4' );
$workbook4->close(); # This is required before we use the scalar
# The Excel file is now in $xlsx_str. As a demonstration, print it to a file.
open TMP, '>', 'fh_04.xlsx' or die "Couldn't open file: $!";
binmode TMP;
print TMP $xlsx_str;
close TMP;
###############################################################################
#
# Example 5. Write an Excel file to a string via IO::Scalar's newer interface.
# Please refer to the IO::Scalar documentation for further details.
#
my $xlsx_str2;
my $fh5 = IO::Scalar->new( \$xlsx_str2 );
my $workbook5 = Excel::Writer::XLSX->new( $fh5 );
my $worksheet5 = $workbook5->add_worksheet();
$worksheet5->write( 0, 0, 'Hi Excel 5' );
$workbook5->close(); # This is required before we use the scalar
# The Excel file is now in $xlsx_str. As a demonstration, print it to a file.
open TMP, '>', 'fh_05.xlsx' or die "Couldn't open file: $!";
binmode TMP;
print TMP $xlsx_str2;
close TMP;
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/filehandle.pl>
=head2 Example: headers.pl
This program shows several examples of how to set up headers and
footers with Excel::Writer::XLSX.
The control characters used in the header/footer strings are:
Control Category Description
======= ======== ===========
&L Justification Left
&C Center
&R Right
&P Information Page number
&N Total number of pages
&D Date
&T Time
&F File name
&A Worksheet name
&fontsize Font Font size
&"font,style" Font name and style
&U Single underline
&E Double underline
&S Strikethrough
&X Superscript
&Y Subscript
&& Miscellaneous Literal ampersand &
See the main Excel::Writer::XLSX documentation for more information.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/headers.jpg" width="640" height="420" alt="Output from headers.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
######################################################################
#
# This program shows several examples of how to set up headers and
# footers with Excel::Writer::XLSX.
#
# The control characters used in the header/footer strings are:
#
# Control Category Description
# ======= ======== ===========
# &L Justification Left
# &C Center
# &R Right
#
# &P Information Page number
# &N Total number of pages
# &D Date
# &T Time
# &F File name
# &A Worksheet name
#
# &fontsize Font Font size
# &"font,style" Font name and style
# &U Single underline
# &E Double underline
# &S Strikethrough
# &X Superscript
# &Y Subscript
#
# && Miscellaneous Literal ampersand &
#
# See the main Excel::Writer::XLSX documentation for more information.
#
# reverse ('(c)'), March 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'headers.xlsx' );
my $preview = 'Select Print Preview to see the header and footer';
######################################################################
#
# A simple example to start
#
my $worksheet1 = $workbook->add_worksheet( 'Simple' );
my $header1 = '&CHere is some centred text.';
my $footer1 = '&LHere is some left aligned text.';
$worksheet1->set_header( $header1 );
$worksheet1->set_footer( $footer1 );
$worksheet1->set_column( 'A:A', 50 );
$worksheet1->write( 'A1', $preview );
######################################################################
#
# This is an example of some of the header/footer variables.
#
my $worksheet2 = $workbook->add_worksheet( 'Variables' );
my $header2 = '&LPage &P of &N' . '&CFilename: &F' . '&RSheetname: &A';
my $footer2 = '&LCurrent date: &D' . '&RCurrent time: &T';
$worksheet2->set_header( $header2 );
$worksheet2->set_footer( $footer2 );
$worksheet2->set_column( 'A:A', 50 );
$worksheet2->write( 'A1', $preview );
$worksheet2->write( 'A21', 'Next sheet' );
$worksheet2->set_h_pagebreaks( 20 );
######################################################################
#
# This example shows how to use more than one font
#
my $worksheet3 = $workbook->add_worksheet( 'Mixed fonts' );
my $header3 = q(&C&"Courier New,Bold"Hello &"Arial,Italic"World);
my $footer3 = q(&C&"Symbol"e&"Arial" = mc&X2);
$worksheet3->set_header( $header3 );
$worksheet3->set_footer( $footer3 );
$worksheet3->set_column( 'A:A', 50 );
$worksheet3->write( 'A1', $preview );
######################################################################
#
# Example of line wrapping
#
my $worksheet4 = $workbook->add_worksheet( 'Word wrap' );
my $header4 = "&CHeading 1\nHeading 2";
$worksheet4->set_header( $header4 );
$worksheet4->set_column( 'A:A', 50 );
$worksheet4->write( 'A1', $preview );
######################################################################
#
# Example of inserting a literal ampersand &
#
my $worksheet5 = $workbook->add_worksheet( 'Ampersand' );
my $header5 = '&CCuriouser && Curiouser - Attorneys at Law';
$worksheet5->set_header( $header5 );
$worksheet5->set_column( 'A:A', 50 );
$worksheet5->write( 'A1', $preview );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/headers.pl>
=head2 Example: hide_row_col.pl
Example of how to hide rows and columns in Excel::Writer::XLSX. In order to
hide rows without setting each one, (of approximately 1 million rows),
Excel uses an optimisation to hide all rows that don't have data.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/hide_row_col.jpg" width="640" height="420" alt="Output from hide_row_col.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to hide rows and columns in Excel::Writer::XLSX. In order to
# hide rows without setting each one, (of approximately 1 million rows),
# Excel uses an optimisation to hide all rows that don't have data.
#
# reverse ('(c)'), December 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'hide_row_col.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Write some data.
$worksheet->write( 'D1', 'Some hidden columns.' );
$worksheet->write( 'A8', 'Some hidden rows.' );
# Hide all rows without data.
$worksheet->set_default_row( undef, 1 );
# Set emptys row that we do want to display. All other will be hidden.
for my $row (1 .. 6) {
$worksheet->set_row( $row, 15 );
}
# Hide a range of columns.
$worksheet->set_column( 'G:XFD', undef, undef, 1);
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/hide_row_col.pl>
=head2 Example: hide_sheet.pl
Example of how to hide a worksheet with Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/hide_sheet.jpg" width="640" height="420" alt="Output from hide_sheet.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# Example of how to hide a worksheet with Excel::Writer::XLSX.
#
# reverse ('(c)'), April 2005, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'hide_sheet.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $worksheet3 = $workbook->add_worksheet();
$worksheet1->set_column( 'A:A', 30 );
$worksheet2->set_column( 'A:A', 30 );
$worksheet3->set_column( 'A:A', 30 );
# Sheet2 won't be visible until it is unhidden in Excel.
$worksheet2->hide();
$worksheet1->write( 0, 0, 'Sheet2 is hidden' );
$worksheet2->write( 0, 0, "Now it's my turn to find you." );
$worksheet3->write( 0, 0, 'Sheet2 is hidden' );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/hide_sheet.pl>
=head2 Example: hyperlink1.pl
Example of how to use the Excel::Writer::XLSX module to write hyperlinks
See also hyperlink2.pl for worksheet URL examples.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/hyperlink1.jpg" width="640" height="420" alt="Output from hyperlink1.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX module to write hyperlinks
#
# See also hyperlink2.pl for worksheet URL examples.
#
# reverse ('(c)'), May 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'hyperlink.xlsx' );
my $worksheet = $workbook->add_worksheet( 'Hyperlinks' );
# Format the first column
$worksheet->set_column( 'A:A', 30 );
$worksheet->set_selection( 'B1' );
# Add the standard url link format.
my $url_format = $workbook->add_format(
color => 'blue',
underline => 1,
);
# Add a sample format.
my $red_format = $workbook->add_format(
color => 'red',
bold => 1,
underline => 1,
size => 12,
);
# Add an alternate description string to the URL.
my $str = 'Perl home.';
# Add a "tool tip" to the URL.
my $tip = 'Get the latest Perl news here.';
# Write some hyperlinks
$worksheet->write( 'A1', 'http://www.perl.com/', $url_format );
$worksheet->write( 'A3', 'http://www.perl.com/', $url_format, $str );
$worksheet->write( 'A5', 'http://www.perl.com/', $url_format, $str, $tip );
$worksheet->write( 'A7', 'http://www.perl.com/', $red_format );
$worksheet->write( 'A9', 'mailto:jmcnamara@cpan.org', $url_format, 'Mail me' );
# Write a URL that isn't a hyperlink
$worksheet->write_string( 'A11', 'http://www.perl.com/' );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/hyperlink1.pl>
=head2 Example: hyperlink2.pl
Example of how to use the Excel::Writer::XLSX module to write internal and
external hyperlinks.
If you wish to run this program and follow the hyperlinks you should create
the following directory structure:
C:\ -- Temp --+-- Europe
|
\-- Asia
See also hyperlink1.pl for web URL examples.
#!/usr/bin/perl
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX module to write internal and
# external hyperlinks.
#
# If you wish to run this program and follow the hyperlinks you should create
# the following directory structure:
#
# C:\ -- Temp --+-- Europe
# |
# \-- Asia
#
#
# See also hyperlink1.pl for web URL examples.
#
# reverse ('(c)'), February 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create three workbooks:
# C:\Temp\Europe\Ireland.xlsx
# C:\Temp\Europe\Italy.xlsx
# C:\Temp\Asia\China.xlsx
#
my $ireland = Excel::Writer::XLSX->new( 'C:\Temp\Europe\Ireland.xlsx' );
my $ire_links = $ireland->add_worksheet( 'Links' );
my $ire_sales = $ireland->add_worksheet( 'Sales' );
my $ire_data = $ireland->add_worksheet( 'Product Data' );
my $ire_url_format = $ireland->add_format(
color => 'blue',
underline => 1,
);
my $italy = Excel::Writer::XLSX->new( 'C:\Temp\Europe\Italy.xlsx' );
my $ita_links = $italy->add_worksheet( 'Links' );
my $ita_sales = $italy->add_worksheet( 'Sales' );
my $ita_data = $italy->add_worksheet( 'Product Data' );
my $ita_url_format = $italy->add_format(
color => 'blue',
underline => 1,
);
my $china = Excel::Writer::XLSX->new( 'C:\Temp\Asia\China.xlsx' );
my $cha_links = $china->add_worksheet( 'Links' );
my $cha_sales = $china->add_worksheet( 'Sales' );
my $cha_data = $china->add_worksheet( 'Product Data' );
my $cha_url_format = $china->add_format(
color => 'blue',
underline => 1,
);
# Add an alternative format
my $format = $ireland->add_format( color => 'green', bold => 1 );
$ire_links->set_column( 'A:B', 25 );
###############################################################################
#
# Examples of internal links
#
$ire_links->write( 'A1', 'Internal links', $format );
# Internal link
$ire_links->write_url( 'A2', 'internal:Sales!A2', $ire_url_format );
# Internal link to a range
$ire_links->write_url( 'A3', 'internal:Sales!A3:D3', $ire_url_format );
# Internal link with an alternative string
$ire_links->write_url( 'A4', 'internal:Sales!A4', $ire_url_format, 'Link' );
# Internal link with an alternative format
$ire_links->write_url( 'A5', 'internal:Sales!A5', $format );
# Internal link with an alternative string and format
$ire_links->write_url( 'A6', 'internal:Sales!A6', $ire_url_format, 'Link' );
# Internal link (spaces in worksheet name)
$ire_links->write_url( 'A7', q{internal:'Product Data'!A7}, $ire_url_format );
###############################################################################
#
# Examples of external links
#
$ire_links->write( 'B1', 'External links', $format );
# External link to a local file
$ire_links->write_url( 'B2', 'external:Italy.xlsx', $ire_url_format );
# External link to a local file with worksheet
$ire_links->write_url( 'B3', 'external:Italy.xlsx#Sales!B3', $ire_url_format );
# External link to a local file with worksheet and alternative string
$ire_links->write_url( 'B4', 'external:Italy.xlsx#Sales!B4', $ire_url_format, 'Link' );
# External link to a local file with worksheet and format
$ire_links->write_url( 'B5', 'external:Italy.xlsx#Sales!B5', $format );
# External link to a remote file, absolute path
$ire_links->write_url( 'B6', 'external:C:/Temp/Asia/China.xlsx', $ire_url_format );
# External link to a remote file, relative path
$ire_links->write_url( 'B7', 'external:../Asia/China.xlsx', $ire_url_format );
# External link to a remote file with worksheet
$ire_links->write_url( 'B8', 'external:C:/Temp/Asia/China.xlsx#Sales!B8', $ire_url_format );
# External link to a remote file with worksheet (with spaces in the name)
$ire_links->write_url( 'B9', q{external:C:/Temp/Asia/China.xlsx#'Product Data'!B9}, $ire_url_format );
###############################################################################
#
# Some utility links to return to the main sheet
#
$ire_sales->write_url( 'A2', 'internal:Links!A2', $ire_url_format, 'Back' );
$ire_sales->write_url( 'A3', 'internal:Links!A3', $ire_url_format, 'Back' );
$ire_sales->write_url( 'A4', 'internal:Links!A4', $ire_url_format, 'Back' );
$ire_sales->write_url( 'A5', 'internal:Links!A5', $ire_url_format, 'Back' );
$ire_sales->write_url( 'A6', 'internal:Links!A6', $ire_url_format, 'Back' );
$ire_data->write_url ( 'A7', 'internal:Links!A7', $ire_url_format, 'Back' );
$ita_links->write_url( 'A1', 'external:Ireland.xlsx#Links!B2', $ita_url_format, 'Back' );
$ita_sales->write_url( 'B3', 'external:Ireland.xlsx#Links!B3', $ita_url_format, 'Back' );
$ita_sales->write_url( 'B4', 'external:Ireland.xlsx#Links!B4', $ita_url_format, 'Back' );
$ita_sales->write_url( 'B5', 'external:Ireland.xlsx#Links!B5', $ita_url_format, 'Back' );
$cha_links->write_url( 'A1', 'external:C:/Temp/Europe/Ireland.xlsx#Links!B6', $cha_url_format, 'Back' );
$cha_sales->write_url( 'B8', 'external:C:/Temp/Europe/Ireland.xlsx#Links!B8', $cha_url_format, 'Back' );
$cha_data->write_url ( 'B9', 'external:C:/Temp/Europe/Ireland.xlsx#Links!B9', $cha_url_format, 'Back' );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/hyperlink2.pl>
=head2 Example: indent.pl
A simple formatting example using Excel::Writer::XLSX.
This program demonstrates the indentation cell format.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/indent.jpg" width="640" height="420" alt="Output from indent.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
##############################################################################
#
# A simple formatting example using Excel::Writer::XLSX.
#
# This program demonstrates the indentation cell format.
#
# reverse ('(c)'), May 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'indent.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $indent1 = $workbook->add_format( indent => 1 );
my $indent2 = $workbook->add_format( indent => 2 );
$worksheet->set_column( 'A:A', 40 );
$worksheet->write( 'A1', "This text is indented 1 level", $indent1 );
$worksheet->write( 'A2', "This text is indented 2 levels", $indent2 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/indent.pl>
=head2 Example: macros.pl
An example of adding macros to an Excel::Writer::XLSX file using
a VBA project file extracted from an existing Excel xlsm file.
The C<extract_vba> utility supplied with Excel::Writer::XLSX can be
used to extract the vbaProject.bin file.
An embedded macro is connected to a form button on the worksheet.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/macros.jpg" width="640" height="420" alt="Output from macros.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# An example of adding macros to an Excel::Writer::XLSX file using
# a VBA project file extracted from an existing Excel xlsm file.
#
# The C<extract_vba> utility supplied with Excel::Writer::XLSX can be
# used to extract the vbaProject.bin file.
#
# An embedded macro is connected to a form button on the worksheet.
#
# reverse('(c)'), November 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Note the file extension should be .xlsm.
my $workbook = Excel::Writer::XLSX->new( 'macros.xlsm' );
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 30 );
# Add the VBA project binary.
$workbook->add_vba_project( './vbaProject.bin' );
# Show text for the end user.
$worksheet->write( 'A3', 'Press the button to say hello.' );
# Add a button tied to a macro in the VBA project.
$worksheet->insert_button(
'B3',
{
macro => 'say_hello',
caption => 'Press Me',
width => 80,
height => 30
}
);
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/macros.pl>
=head2 Example: merge1.pl
Simple example of merging cells using the Excel::Writer::XLSX module.
This example merges three cells using the "Centre Across Selection"
alignment which was the Excel 5 method of achieving a merge. For a more
modern approach use the merge_range() worksheet method instead.
See the merge3.pl - merge6.pl programs.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/merge1.jpg" width="640" height="420" alt="Output from merge1.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Simple example of merging cells using the Excel::Writer::XLSX module.
#
# This example merges three cells using the "Centre Across Selection"
# alignment which was the Excel 5 method of achieving a merge. For a more
# modern approach use the merge_range() worksheet method instead.
# See the merge3.pl - merge6.pl programs.
#
# reverse ('(c)'), August 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'merge1.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Increase the cell size of the merged cells to highlight the formatting.
$worksheet->set_column( 'B:D', 20 );
$worksheet->set_row( 2, 30 );
# Create a merge format
my $format = $workbook->add_format( center_across => 1 );
# Only one cell should contain text, the others should be blank.
$worksheet->write( 2, 1, "Center across selection", $format );
$worksheet->write_blank( 2, 2, $format );
$worksheet->write_blank( 2, 3, $format );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/merge1.pl>
=head2 Example: merge2.pl
Simple example of merging cells using the Excel::Writer::XLSX module
This example merges three cells using the "Centre Across Selection"
alignment which was the Excel 5 method of achieving a merge. For a more
modern approach use the merge_range() worksheet method instead.
See the merge3.pl - merge6.pl programs.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/merge2.jpg" width="640" height="420" alt="Output from merge2.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Simple example of merging cells using the Excel::Writer::XLSX module
#
# This example merges three cells using the "Centre Across Selection"
# alignment which was the Excel 5 method of achieving a merge. For a more
# modern approach use the merge_range() worksheet method instead.
# See the merge3.pl - merge6.pl programs.
#
# reverse ('(c)'), August 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'merge2.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Increase the cell size of the merged cells to highlight the formatting.
$worksheet->set_column( 1, 2, 30 );
$worksheet->set_row( 2, 40 );
# Create a merged format
my $format = $workbook->add_format(
center_across => 1,
bold => 1,
size => 15,
pattern => 1,
border => 6,
color => 'white',
fg_color => 'green',
border_color => 'yellow',
align => 'vcenter',
);
# Only one cell should contain text, the others should be blank.
$worksheet->write( 2, 1, "Center across selection", $format );
$worksheet->write_blank( 2, 2, $format );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/merge2.pl>
=head2 Example: merge3.pl
Example of how to use Excel::Writer::XLSX to write a hyperlink in a
merged cell.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/merge3.jpg" width="640" height="420" alt="Output from merge3.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to use Excel::Writer::XLSX to write a hyperlink in a
# merged cell.
#
# reverse ('(c)'), September 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'merge3.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Increase the cell size of the merged cells to highlight the formatting.
$worksheet->set_row( $_, 30 ) for ( 3, 6, 7 );
$worksheet->set_column( 'B:D', 20 );
###############################################################################
#
# Example: Merge cells containing a hyperlink using merge_range().
#
my $format = $workbook->add_format(
border => 1,
underline => 1,
color => 'blue',
align => 'center',
valign => 'vcenter',
);
# Merge 3 cells
$worksheet->merge_range( 'B4:D4', 'http://www.perl.com', $format );
# Merge 3 cells over two rows
$worksheet->merge_range( 'B7:D8', 'http://www.perl.com', $format );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/merge3.pl>
=head2 Example: merge4.pl
Example of how to use the Excel::Writer::XLSX merge_range() workbook
method with complex formatting.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/merge4.jpg" width="640" height="420" alt="Output from merge4.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX merge_range() workbook
# method with complex formatting.
#
# reverse ('(c)'), September 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'merge4.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Increase the cell size of the merged cells to highlight the formatting.
$worksheet->set_row( $_, 30 ) for ( 1 .. 11 );
$worksheet->set_column( 'B:D', 20 );
###############################################################################
#
# Example 1: Text centered vertically and horizontally
#
my $format1 = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
valign => 'vcenter',
align => 'center',
);
$worksheet->merge_range( 'B2:D3', 'Vertical and horizontal', $format1 );
###############################################################################
#
# Example 2: Text aligned to the top and left
#
my $format2 = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
valign => 'top',
align => 'left',
);
$worksheet->merge_range( 'B5:D6', 'Aligned to the top and left', $format2 );
###############################################################################
#
# Example 3: Text aligned to the bottom and right
#
my $format3 = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
valign => 'bottom',
align => 'right',
);
$worksheet->merge_range( 'B8:D9', 'Aligned to the bottom and right', $format3 );
###############################################################################
#
# Example 4: Text justified (i.e. wrapped) in the cell
#
my $format4 = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
valign => 'top',
align => 'justify',
);
$worksheet->merge_range( 'B11:D12', 'Justified: ' . 'so on and ' x 18,
$format4 );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/merge4.pl>
=head2 Example: merge5.pl
Example of how to use the Excel::Writer::XLSX merge_cells() workbook
method with complex formatting and rotation.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/merge5.jpg" width="640" height="420" alt="Output from merge5.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX merge_cells() workbook
# method with complex formatting and rotation.
#
#
# reverse ('(c)'), September 2002, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'merge5.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Increase the cell size of the merged cells to highlight the formatting.
$worksheet->set_row( $_, 36 ) for ( 3 .. 8 );
$worksheet->set_column( $_, $_, 15 ) for ( 1, 3, 5 );
###############################################################################
#
# Rotation 1, letters run from top to bottom
#
my $format1 = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
valign => 'vcentre',
align => 'centre',
rotation => 270,
);
$worksheet->merge_range( 'B4:B9', 'Rotation 270', $format1 );
###############################################################################
#
# Rotation 2, 90° anticlockwise
#
my $format2 = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
valign => 'vcentre',
align => 'centre',
rotation => 90,
);
$worksheet->merge_range( 'D4:D9', 'Rotation 90°', $format2 );
###############################################################################
#
# Rotation 3, 90° clockwise
#
my $format3 = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
valign => 'vcentre',
align => 'centre',
rotation => -90,
);
$worksheet->merge_range( 'F4:F9', 'Rotation -90°', $format3 );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/merge5.pl>
=head2 Example: merge6.pl
Example of how to use the Excel::Writer::XLSX merge_cells() workbook
method with Unicode strings.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/merge6.jpg" width="640" height="420" alt="Output from merge6.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX merge_cells() workbook
# method with Unicode strings.
#
#
# reverse ('(c)'), December 2005, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'merge6.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Increase the cell size of the merged cells to highlight the formatting.
$worksheet->set_row( $_, 36 ) for 2 .. 9;
$worksheet->set_column( 'B:D', 25 );
# Format for the merged cells.
my $format = $workbook->add_format(
border => 6,
bold => 1,
color => 'red',
size => 20,
valign => 'vcentre',
align => 'left',
indent => 1,
);
###############################################################################
#
# Write an Ascii string.
#
$worksheet->merge_range( 'B3:D4', 'ASCII: A simple string', $format );
###############################################################################
#
# Write a UTF-8 Unicode string.
#
my $smiley = chr 0x263a;
$worksheet->merge_range( 'B6:D7', "UTF-8: A Unicode smiley $smiley", $format );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/merge6.pl>
=head2 Example: mod_perl1.pl
Example of how to use the Excel::Writer::XLSX module to send an Excel
file to a browser using mod_perl 1 and Apache
This module ties *XLSX directly to Apache, and with the correct
content-disposition/types it will prompt the user to save
the file, or open it at this location.
This script is a modification of the Excel::Writer::XLSX cgi.pl example.
Change the name of this file to Cgi.pm.
Change the package location to wherever you locate this package.
In the example below it is located in the Excel::Writer::XLSX directory.
Your httpd.conf entry for this module, should you choose to use it
as a stand alone app, should look similar to the following:
<Location /spreadsheet-test>
SetHandler perl-script
PerlHandler Excel::Writer::XLSX::Cgi
PerlSendHeader On
</Location>
The PerlHandler name above and the package name below *have* to match.
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX module to send an Excel
# file to a browser using mod_perl 1 and Apache
#
# This module ties *XLSX directly to Apache, and with the correct
# content-disposition/types it will prompt the user to save
# the file, or open it at this location.
#
# This script is a modification of the Excel::Writer::XLSX cgi.pl example.
#
# Change the name of this file to Cgi.pm.
# Change the package location to wherever you locate this package.
# In the example below it is located in the Excel::Writer::XLSX directory.
#
# Your httpd.conf entry for this module, should you choose to use it
# as a stand alone app, should look similar to the following:
#
# <Location /spreadsheet-test>
# SetHandler perl-script
# PerlHandler Excel::Writer::XLSX::Cgi
# PerlSendHeader On
# </Location>
#
# The PerlHandler name above and the package name below *have* to match.
# Apr 2001, Thomas Sullivan, webmaster@860.org
# Feb 2001, John McNamara, jmcnamara@cpan.org
package Excel::Writer::XLSX::Cgi;
##########################################
# Pragma Definitions
##########################################
use strict;
##########################################
# Required Modules
##########################################
use Apache::Constants qw(:common);
use Apache::Request;
use Apache::URI; # This may not be needed
use Excel::Writer::XLSX;
##########################################
# Main App Body
##########################################
sub handler {
# New apache object
# Should you decide to use it.
my $r = Apache::Request->new( shift );
# Set the filename and send the content type
# This will appear when they save the spreadsheet
my $filename = "cgitest.xlsx";
####################################################
## Send the content type headers
####################################################
print "Content-disposition: attachment;filename=$filename\n";
print "Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n\n";
####################################################
# Tie a filehandle to Apache's STDOUT.
# Create a new workbook and add a worksheet.
####################################################
tie *XLSX => 'Apache';
binmode( *XLSX );
my $workbook = Excel::Writer::XLSX->new( \*XLSX );
my $worksheet = $workbook->add_worksheet();
# Set the column width for column 1
$worksheet->set_column( 0, 0, 20 );
# Create a format
my $format = $workbook->add_format();
$format->set_bold();
$format->set_size( 15 );
$format->set_color( 'blue' );
# Write to the workbook
$worksheet->write( 0, 0, "Hi Excel!", $format );
# You must close the workbook for Content-disposition
$workbook->close();
}
1;
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/mod_perl1.pl>
=head2 Example: mod_perl2.pl
Example of how to use the Excel::Writer::XLSX module to send an Excel
file to a browser using mod_perl 2 and Apache.
This module ties *XLSX directly to Apache, and with the correct
content-disposition/types it will prompt the user to save
the file, or open it at this location.
This script is a modification of the Excel::Writer::XLSX cgi.pl example.
Change the name of this file to MP2Test.pm.
Change the package location to wherever you locate this package.
In the example below it is located in the Excel::Writer::XLSX directory.
Your httpd.conf entry for this module, should you choose to use it
as a stand alone app, should look similar to the following:
PerlModule Apache2::RequestRec
PerlModule APR::Table
PerlModule Apache2::RequestIO
<Location /spreadsheet-test>
SetHandler perl-script
PerlResponseHandler Excel::Writer::XLSX::MP2Test
</Location>
The PerlResponseHandler must match the package name below.
###############################################################################
#
# Example of how to use the Excel::Writer::XLSX module to send an Excel
# file to a browser using mod_perl 2 and Apache.
#
# This module ties *XLSX directly to Apache, and with the correct
# content-disposition/types it will prompt the user to save
# the file, or open it at this location.
#
# This script is a modification of the Excel::Writer::XLSX cgi.pl example.
#
# Change the name of this file to MP2Test.pm.
# Change the package location to wherever you locate this package.
# In the example below it is located in the Excel::Writer::XLSX directory.
#
# Your httpd.conf entry for this module, should you choose to use it
# as a stand alone app, should look similar to the following:
#
# PerlModule Apache2::RequestRec
# PerlModule APR::Table
# PerlModule Apache2::RequestIO
#
# <Location /spreadsheet-test>
# SetHandler perl-script
# PerlResponseHandler Excel::Writer::XLSX::MP2Test
# </Location>
#
# The PerlResponseHandler must match the package name below.
# Jun 2004, Matisse Enzer, matisse@matisse.net (mod_perl 2 version)
# Apr 2001, Thomas Sullivan, webmaster@860.org
# Feb 2001, John McNamara, jmcnamara@cpan.org
package Excel::Writer::XLSX::MP2Test;
##########################################
# Pragma Definitions
##########################################
use strict;
##########################################
# Required Modules
##########################################
use Apache2::Const -compile => qw( :common );
use Excel::Writer::XLSX;
##########################################
# Main App Body
##########################################
sub handler {
my ( $r ) = @_; # Apache request object is passed to handler in mod_perl 2
# Set the filename and send the content type
# This will appear when they save the spreadsheet
my $filename = "mod_perl2_test.xlsx";
####################################################
## Send the content type headers the mod_perl 2 way
####################################################
$r->headers_out->{'Content-Disposition'} = "attachment;filename=$filename";
$r->content_type( 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' );
####################################################
# Tie a filehandle to Apache's STDOUT.
# Create a new workbook and add a worksheet.
####################################################
tie *XLSX => $r; # The mod_perl 2 way. Tie to the Apache::RequestRec object
binmode( *XLSX );
my $workbook = Excel::Writer::XLSX->new( \*XLSX );
my $worksheet = $workbook->add_worksheet();
# Set the column width for column 1
$worksheet->set_column( 0, 0, 20 );
# Create a format
my $format = $workbook->add_format();
$format->set_bold();
$format->set_size( 15 );
$format->set_color( 'blue' );
# Write to the workbook
$worksheet->write( 0, 0, 'Hi Excel! from ' . $r->hostname, $format );
# You must close the workbook for Content-disposition
$workbook->close();
return Apache2::Const::OK;
}
1;
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/mod_perl2.pl>
=head2 Example: outline.pl
Example of how use Excel::Writer::XLSX to generate Excel outlines and
grouping.
Excel allows you to group rows or columns so that they can be hidden or
displayed with a single mouse click. This feature is referred to as outlines.
Outlines can reduce complex data down to a few salient sub-totals or
summaries.
This feature is best viewed in Excel but the following is an ASCII
representation of what a worksheet with three outlines might look like.
Rows 3-4 and rows 7-8 are grouped at level 2. Rows 2-9 are grouped at
level 1. The lines at the left hand side are called outline level bars.
------------------------------------------
1 2 3 | | A | B | C | D | ...
------------------------------------------
_ | 1 | A | | | | ...
| _ | 2 | B | | | | ...
| | | 3 | (C) | | | | ...
| | | 4 | (D) | | | | ...
| - | 5 | E | | | | ...
| _ | 6 | F | | | | ...
| | | 7 | (G) | | | | ...
| | | 8 | (H) | | | | ...
| - | 9 | I | | | | ...
- | . | ... | ... | ... | ... | ...
Clicking the minus sign on each of the level 2 outlines will collapse and
hide the data as shown in the next figure. The minus sign changes to a plus
sign to indicate that the data in the outline is hidden.
------------------------------------------
1 2 3 | | A | B | C | D | ...
------------------------------------------
_ | 1 | A | | | | ...
| | 2 | B | | | | ...
| + | 5 | E | | | | ...
| | 6 | F | | | | ...
| + | 9 | I | | | | ...
- | . | ... | ... | ... | ... | ...
Clicking on the minus sign on the level 1 outline will collapse the remaining
rows as follows:
------------------------------------------
1 2 3 | | A | B | C | D | ...
------------------------------------------
| 1 | A | | | | ...
+ | . | ... | ... | ... | ... | ...
See the main Excel::Writer::XLSX documentation for more information.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/outline.jpg" width="640" height="420" alt="Output from outline.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how use Excel::Writer::XLSX to generate Excel outlines and
# grouping.
#
#
# Excel allows you to group rows or columns so that they can be hidden or
# displayed with a single mouse click. This feature is referred to as outlines.
#
# Outlines can reduce complex data down to a few salient sub-totals or
# summaries.
#
# This feature is best viewed in Excel but the following is an ASCII
# representation of what a worksheet with three outlines might look like.
# Rows 3-4 and rows 7-8 are grouped at level 2. Rows 2-9 are grouped at
# level 1. The lines at the left hand side are called outline level bars.
#
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# _ | 1 | A | | | | ...
# | _ | 2 | B | | | | ...
# | | | 3 | (C) | | | | ...
# | | | 4 | (D) | | | | ...
# | - | 5 | E | | | | ...
# | _ | 6 | F | | | | ...
# | | | 7 | (G) | | | | ...
# | | | 8 | (H) | | | | ...
# | - | 9 | I | | | | ...
# - | . | ... | ... | ... | ... | ...
#
#
# Clicking the minus sign on each of the level 2 outlines will collapse and
# hide the data as shown in the next figure. The minus sign changes to a plus
# sign to indicate that the data in the outline is hidden.
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# _ | 1 | A | | | | ...
# | | 2 | B | | | | ...
# | + | 5 | E | | | | ...
# | | 6 | F | | | | ...
# | + | 9 | I | | | | ...
# - | . | ... | ... | ... | ... | ...
#
#
# Clicking on the minus sign on the level 1 outline will collapse the remaining
# rows as follows:
#
# ------------------------------------------
# 1 2 3 | | A | B | C | D | ...
# ------------------------------------------
# | 1 | A | | | | ...
# + | . | ... | ... | ... | ... | ...
#
# See the main Excel::Writer::XLSX documentation for more information.
#
# reverse ('(c)'), April 2003, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add some worksheets
my $workbook = Excel::Writer::XLSX->new( 'outline.xlsx' );
my $worksheet1 = $workbook->add_worksheet( 'Outlined Rows' );
my $worksheet2 = $workbook->add_worksheet( 'Collapsed Rows' );
my $worksheet3 = $workbook->add_worksheet( 'Outline Columns' );
my $worksheet4 = $workbook->add_worksheet( 'Outline levels' );
# Add a general format
my $bold = $workbook->add_format( bold => 1 );
###############################################################################
#
# Example 1: Create a worksheet with outlined rows. It also includes SUBTOTAL()
# functions so that it looks like the type of automatic outlines that are
# generated when you use the Excel Data->SubTotals menu item.
#
# For outlines the important parameters are $hidden and $level. Rows with the
# same $level are grouped together. The group will be collapsed if $hidden is
# non-zero. $height and $XF are assigned default values if they are undef.
#
# The syntax is: set_row($row, $height, $XF, $hidden, $level, $collapsed)
#
$worksheet1->set_row( 1, undef, undef, 0, 2 );
$worksheet1->set_row( 2, undef, undef, 0, 2 );
$worksheet1->set_row( 3, undef, undef, 0, 2 );
$worksheet1->set_row( 4, undef, undef, 0, 2 );
$worksheet1->set_row( 5, undef, undef, 0, 1 );
$worksheet1->set_row( 6, undef, undef, 0, 2 );
$worksheet1->set_row( 7, undef, undef, 0, 2 );
$worksheet1->set_row( 8, undef, undef, 0, 2 );
$worksheet1->set_row( 9, undef, undef, 0, 2 );
$worksheet1->set_row( 10, undef, undef, 0, 1 );
# Add a column format for clarity
$worksheet1->set_column( 'A:A', 20 );
# Add the data, labels and formulas
$worksheet1->write( 'A1', 'Region', $bold );
$worksheet1->write( 'A2', 'North' );
$worksheet1->write( 'A3', 'North' );
$worksheet1->write( 'A4', 'North' );
$worksheet1->write( 'A5', 'North' );
$worksheet1->write( 'A6', 'North Total', $bold );
$worksheet1->write( 'B1', 'Sales', $bold );
$worksheet1->write( 'B2', 1000 );
$worksheet1->write( 'B3', 1200 );
$worksheet1->write( 'B4', 900 );
$worksheet1->write( 'B5', 1200 );
$worksheet1->write( 'B6', '=SUBTOTAL(9,B2:B5)', $bold );
$worksheet1->write( 'A7', 'South' );
$worksheet1->write( 'A8', 'South' );
$worksheet1->write( 'A9', 'South' );
$worksheet1->write( 'A10', 'South' );
$worksheet1->write( 'A11', 'South Total', $bold );
$worksheet1->write( 'B7', 400 );
$worksheet1->write( 'B8', 600 );
$worksheet1->write( 'B9', 500 );
$worksheet1->write( 'B10', 600 );
$worksheet1->write( 'B11', '=SUBTOTAL(9,B7:B10)', $bold );
$worksheet1->write( 'A12', 'Grand Total', $bold );
$worksheet1->write( 'B12', '=SUBTOTAL(9,B2:B10)', $bold );
###############################################################################
#
# Example 2: Create a worksheet with outlined rows. This is the same as the
# previous example except that the rows are collapsed.
# Note: We need to indicate the row that contains the collapsed symbol '+'
# with the optional parameter, $collapsed.
# The group will be collapsed if $hidden is non-zero.
# The syntax is: set_row($row, $height, $XF, $hidden, $level, $collapsed)
#
$worksheet2->set_row( 1, undef, undef, 1, 2 );
$worksheet2->set_row( 2, undef, undef, 1, 2 );
$worksheet2->set_row( 3, undef, undef, 1, 2 );
$worksheet2->set_row( 4, undef, undef, 1, 2 );
$worksheet2->set_row( 5, undef, undef, 1, 1 );
$worksheet2->set_row( 6, undef, undef, 1, 2 );
$worksheet2->set_row( 7, undef, undef, 1, 2 );
$worksheet2->set_row( 8, undef, undef, 1, 2 );
$worksheet2->set_row( 9, undef, undef, 1, 2 );
$worksheet2->set_row( 10, undef, undef, 1, 1 );
$worksheet2->set_row( 11, undef, undef, 0, 0, 1 );
# Add a column format for clarity
$worksheet2->set_column( 'A:A', 20 );
# Add the data, labels and formulas
$worksheet2->write( 'A1', 'Region', $bold );
$worksheet2->write( 'A2', 'North' );
$worksheet2->write( 'A3', 'North' );
$worksheet2->write( 'A4', 'North' );
$worksheet2->write( 'A5', 'North' );
$worksheet2->write( 'A6', 'North Total', $bold );
$worksheet2->write( 'B1', 'Sales', $bold );
$worksheet2->write( 'B2', 1000 );
$worksheet2->write( 'B3', 1200 );
$worksheet2->write( 'B4', 900 );
$worksheet2->write( 'B5', 1200 );
$worksheet2->write( 'B6', '=SUBTOTAL(9,B2:B5)', $bold );
$worksheet2->write( 'A7', 'South' );
$worksheet2->write( 'A8', 'South' );
$worksheet2->write( 'A9', 'South' );
$worksheet2->write( 'A10', 'South' );
$worksheet2->write( 'A11', 'South Total', $bold );
$worksheet2->write( 'B7', 400 );
$worksheet2->write( 'B8', 600 );
$worksheet2->write( 'B9', 500 );
$worksheet2->write( 'B10', 600 );
$worksheet2->write( 'B11', '=SUBTOTAL(9,B7:B10)', $bold );
$worksheet2->write( 'A12', 'Grand Total', $bold );
$worksheet2->write( 'B12', '=SUBTOTAL(9,B2:B10)', $bold );
###############################################################################
#
# Example 3: Create a worksheet with outlined columns.
#
my $data = [
[ 'Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ' Total' ],
[ 'North', 50, 20, 15, 25, 65, 80, '=SUM(B2:G2)' ],
[ 'South', 10, 20, 30, 50, 50, 50, '=SUM(B3:G3)' ],
[ 'East', 45, 75, 50, 15, 75, 100, '=SUM(B4:G4)' ],
[ 'West', 15, 15, 55, 35, 20, 50, '=SUM(B5:G5)' ],
];
# Add bold format to the first row
$worksheet3->set_row( 0, undef, $bold );
# Syntax: set_column($col1, $col2, $width, $XF, $hidden, $level, $collapsed)
$worksheet3->set_column( 'A:A', 10, $bold );
$worksheet3->set_column( 'B:G', 5, undef, 0, 1 );
$worksheet3->set_column( 'H:H', 10 );
# Write the data and a formula
$worksheet3->write_col( 'A1', $data );
$worksheet3->write( 'H6', '=SUM(H2:H5)', $bold );
###############################################################################
#
# Example 4: Show all possible outline levels.
#
my $levels = [
"Level 1", "Level 2", "Level 3", "Level 4", "Level 5", "Level 6",
"Level 7", "Level 6", "Level 5", "Level 4", "Level 3", "Level 2",
"Level 1"
];
$worksheet4->write_col( 'A1', $levels );
$worksheet4->set_row( 0, undef, undef, undef, 1 );
$worksheet4->set_row( 1, undef, undef, undef, 2 );
$worksheet4->set_row( 2, undef, undef, undef, 3 );
$worksheet4->set_row( 3, undef, undef, undef, 4 );
$worksheet4->set_row( 4, undef, undef, undef, 5 );
$worksheet4->set_row( 5, undef, undef, undef, 6 );
$worksheet4->set_row( 6, undef, undef, undef, 7 );
$worksheet4->set_row( 7, undef, undef, undef, 6 );
$worksheet4->set_row( 8, undef, undef, undef, 5 );
$worksheet4->set_row( 9, undef, undef, undef, 4 );
$worksheet4->set_row( 10, undef, undef, undef, 3 );
$worksheet4->set_row( 11, undef, undef, undef, 2 );
$worksheet4->set_row( 12, undef, undef, undef, 1 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/outline.pl>
=head2 Example: outline_collapsed.pl
Example of how to use Excel::Writer::XLSX to generate Excel outlines and
grouping.
These examples focus mainly on collapsed outlines. See also the
outlines.pl example program for more general examples.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/outline_collapsed.jpg" width="640" height="420" alt="Output from outline_collapsed.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to use Excel::Writer::XLSX to generate Excel outlines and
# grouping.
#
# These examples focus mainly on collapsed outlines. See also the
# outlines.pl example program for more general examples.
#
# reverse ('(c)'), March 2008, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Create a new workbook and add some worksheets
my $workbook = Excel::Writer::XLSX->new( 'outline_collapsed.xlsx' );
my $worksheet1 = $workbook->add_worksheet( 'Outlined Rows' );
my $worksheet2 = $workbook->add_worksheet( 'Collapsed Rows 1' );
my $worksheet3 = $workbook->add_worksheet( 'Collapsed Rows 2' );
my $worksheet4 = $workbook->add_worksheet( 'Collapsed Rows 3' );
my $worksheet5 = $workbook->add_worksheet( 'Outline Columns' );
my $worksheet6 = $workbook->add_worksheet( 'Collapsed Columns' );
# Add a general format
my $bold = $workbook->add_format( bold => 1 );
#
# This function will generate the same data and sub-totals on each worksheet.
#
sub create_sub_totals {
my $worksheet = $_[0];
# Add a column format for clarity
$worksheet->set_column( 'A:A', 20 );
# Add the data, labels and formulas
$worksheet->write( 'A1', 'Region', $bold );
$worksheet->write( 'A2', 'North' );
$worksheet->write( 'A3', 'North' );
$worksheet->write( 'A4', 'North' );
$worksheet->write( 'A5', 'North' );
$worksheet->write( 'A6', 'North Total', $bold );
$worksheet->write( 'B1', 'Sales', $bold );
$worksheet->write( 'B2', 1000 );
$worksheet->write( 'B3', 1200 );
$worksheet->write( 'B4', 900 );
$worksheet->write( 'B5', 1200 );
$worksheet->write( 'B6', '=SUBTOTAL(9,B2:B5)', $bold );
$worksheet->write( 'A7', 'South' );
$worksheet->write( 'A8', 'South' );
$worksheet->write( 'A9', 'South' );
$worksheet->write( 'A10', 'South' );
$worksheet->write( 'A11', 'South Total', $bold );
$worksheet->write( 'B7', 400 );
$worksheet->write( 'B8', 600 );
$worksheet->write( 'B9', 500 );
$worksheet->write( 'B10', 600 );
$worksheet->write( 'B11', '=SUBTOTAL(9,B7:B10)', $bold );
$worksheet->write( 'A12', 'Grand Total', $bold );
$worksheet->write( 'B12', '=SUBTOTAL(9,B2:B10)', $bold );
}
###############################################################################
#
# Example 1: Create a worksheet with outlined rows. It also includes SUBTOTAL()
# functions so that it looks like the type of automatic outlines that are
# generated when you use the Excel Data->SubTotals menu item.
#
# The syntax is: set_row($row, $height, $XF, $hidden, $level, $collapsed)
$worksheet1->set_row( 1, undef, undef, 0, 2 );
$worksheet1->set_row( 2, undef, undef, 0, 2 );
$worksheet1->set_row( 3, undef, undef, 0, 2 );
$worksheet1->set_row( 4, undef, undef, 0, 2 );
$worksheet1->set_row( 5, undef, undef, 0, 1 );
$worksheet1->set_row( 6, undef, undef, 0, 2 );
$worksheet1->set_row( 7, undef, undef, 0, 2 );
$worksheet1->set_row( 8, undef, undef, 0, 2 );
$worksheet1->set_row( 9, undef, undef, 0, 2 );
$worksheet1->set_row( 10, undef, undef, 0, 1 );
# Write the sub-total data that is common to the row examples.
create_sub_totals( $worksheet1 );
###############################################################################
#
# Example 2: Create a worksheet with collapsed outlined rows.
# This is the same as the example 1 except that the all rows are collapsed.
# Note: We need to indicate the row that contains the collapsed symbol '+' with
# the optional parameter, $collapsed.
$worksheet2->set_row( 1, undef, undef, 1, 2 );
$worksheet2->set_row( 2, undef, undef, 1, 2 );
$worksheet2->set_row( 3, undef, undef, 1, 2 );
$worksheet2->set_row( 4, undef, undef, 1, 2 );
$worksheet2->set_row( 5, undef, undef, 1, 1 );
$worksheet2->set_row( 6, undef, undef, 1, 2 );
$worksheet2->set_row( 7, undef, undef, 1, 2 );
$worksheet2->set_row( 8, undef, undef, 1, 2 );
$worksheet2->set_row( 9, undef, undef, 1, 2 );
$worksheet2->set_row( 10, undef, undef, 1, 1 );
$worksheet2->set_row( 11, undef, undef, 0, 0, 1 );
# Write the sub-total data that is common to the row examples.
create_sub_totals( $worksheet2 );
###############################################################################
#
# Example 3: Create a worksheet with collapsed outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
$worksheet3->set_row( 1, undef, undef, 1, 2 );
$worksheet3->set_row( 2, undef, undef, 1, 2 );
$worksheet3->set_row( 3, undef, undef, 1, 2 );
$worksheet3->set_row( 4, undef, undef, 1, 2 );
$worksheet3->set_row( 5, undef, undef, 0, 1, 1 );
$worksheet3->set_row( 6, undef, undef, 1, 2 );
$worksheet3->set_row( 7, undef, undef, 1, 2 );
$worksheet3->set_row( 8, undef, undef, 1, 2 );
$worksheet3->set_row( 9, undef, undef, 1, 2 );
$worksheet3->set_row( 10, undef, undef, 0, 1, 1 );
# Write the sub-total data that is common to the row examples.
create_sub_totals( $worksheet3 );
###############################################################################
#
# Example 4: Create a worksheet with outlined rows.
# Same as the example 1 except that the two sub-totals are collapsed.
$worksheet4->set_row( 1, undef, undef, 1, 2 );
$worksheet4->set_row( 2, undef, undef, 1, 2 );
$worksheet4->set_row( 3, undef, undef, 1, 2 );
$worksheet4->set_row( 4, undef, undef, 1, 2 );
$worksheet4->set_row( 5, undef, undef, 1, 1, 1 );
$worksheet4->set_row( 6, undef, undef, 1, 2 );
$worksheet4->set_row( 7, undef, undef, 1, 2 );
$worksheet4->set_row( 8, undef, undef, 1, 2 );
$worksheet4->set_row( 9, undef, undef, 1, 2 );
$worksheet4->set_row( 10, undef, undef, 1, 1, 1 );
$worksheet4->set_row( 11, undef, undef, 0, 0, 1 );
# Write the sub-total data that is common to the row examples.
create_sub_totals( $worksheet4 );
###############################################################################
#
# Example 5: Create a worksheet with outlined columns.
#
my $data = [
[ 'Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Total' ],
[ 'North', 50, 20, 15, 25, 65, 80,, '=SUM(B2:G2)' ],
[ 'South', 10, 20, 30, 50, 50, 50,, '=SUM(B3:G3)' ],
[ 'East', 45, 75, 50, 15, 75, 100,, '=SUM(B4:G4)' ],
[ 'West', 15, 15, 55, 35, 20, 50,, '=SUM(B5:G6)' ],
];
# Add bold format to the first row
$worksheet5->set_row( 0, undef, $bold );
# Syntax: set_column($col1, $col2, $width, $XF, $hidden, $level, $collapsed)
$worksheet5->set_column( 'A:A', 10, $bold );
$worksheet5->set_column( 'B:G', 5, undef, 0, 1 );
$worksheet5->set_column( 'H:H', 10 );
# Write the data and a formula
$worksheet5->write_col( 'A1', $data );
$worksheet5->write( 'H6', '=SUM(H2:H5)', $bold );
###############################################################################
#
# Example 6: Create a worksheet with collapsed outlined columns.
# This is the same as the previous example except collapsed columns.
# Add bold format to the first row
$worksheet6->set_row( 0, undef, $bold );
# Syntax: set_column($col1, $col2, $width, $XF, $hidden, $level, $collapsed)
$worksheet6->set_column( 'A:A', 10, $bold );
$worksheet6->set_column( 'B:G', 5, undef, 1, 1 );
$worksheet6->set_column( 'H:H', 10, undef, 0, 0, 1 );
# Write the data and a formula
$worksheet6->write_col( 'A1', $data );
$worksheet6->write( 'H6', '=SUM(H2:H5)', $bold );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/outline_collapsed.pl>
=head2 Example: panes.pl
Example of using the Excel::Writer::XLSX module to create worksheet panes.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/panes.jpg" width="640" height="420" alt="Output from panes.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# Example of using the Excel::Writer::XLSX module to create worksheet panes.
#
# reverse ('(c)'), May 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'panes.xlsx' );
my $worksheet1 = $workbook->add_worksheet( 'Panes 1' );
my $worksheet2 = $workbook->add_worksheet( 'Panes 2' );
my $worksheet3 = $workbook->add_worksheet( 'Panes 3' );
my $worksheet4 = $workbook->add_worksheet( 'Panes 4' );
# Freeze panes
$worksheet1->freeze_panes( 1, 0 ); # 1 row
$worksheet2->freeze_panes( 0, 1 ); # 1 column
$worksheet3->freeze_panes( 1, 1 ); # 1 row and column
# Split panes.
# The divisions must be specified in terms of row and column dimensions.
# The default row height is 15 and the default column width is 8.43
#
$worksheet4->split_panes( 15, 8.43 ); # 1 row and column
#######################################################################
#
# Set up some formatting and text to highlight the panes
#
my $header = $workbook->add_format(
align => 'center',
valign => 'vcenter',
fg_color => 0x2A,
);
my $center = $workbook->add_format( align => 'center' );
#######################################################################
#
# Sheet 1
#
$worksheet1->set_column( 'A:I', 16 );
$worksheet1->set_row( 0, 20 );
$worksheet1->set_selection( 'C3' );
for my $i ( 0 .. 8 ) {
$worksheet1->write( 0, $i, 'Scroll down', $header );
}
for my $i ( 1 .. 100 ) {
for my $j ( 0 .. 8 ) {
$worksheet1->write( $i, $j, $i + 1, $center );
}
}
#######################################################################
#
# Sheet 2
#
$worksheet2->set_column( 'A:A', 16 );
$worksheet2->set_selection( 'C3' );
for my $i ( 0 .. 49 ) {
$worksheet2->set_row( $i, 15 );
$worksheet2->write( $i, 0, 'Scroll right', $header );
}
for my $i ( 0 .. 49 ) {
for my $j ( 1 .. 25 ) {
$worksheet2->write( $i, $j, $j, $center );
}
}
#######################################################################
#
# Sheet 3
#
$worksheet3->set_column( 'A:Z', 16 );
$worksheet3->set_selection( 'C3' );
$worksheet3->write( 0, 0, '', $header );
for my $i ( 1 .. 25 ) {
$worksheet3->write( 0, $i, 'Scroll down', $header );
}
for my $i ( 1 .. 49 ) {
$worksheet3->write( $i, 0, 'Scroll right', $header );
}
for my $i ( 1 .. 49 ) {
for my $j ( 1 .. 25 ) {
$worksheet3->write( $i, $j, $j, $center );
}
}
#######################################################################
#
# Sheet 4
#
$worksheet4->set_selection( 'C3' );
for my $i ( 1 .. 25 ) {
$worksheet4->write( 0, $i, 'Scroll', $center );
}
for my $i ( 1 .. 49 ) {
$worksheet4->write( $i, 0, 'Scroll', $center );
}
for my $i ( 1 .. 49 ) {
for my $j ( 1 .. 25 ) {
$worksheet4->write( $i, $j, $j, $center );
}
}
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/panes.pl>
=head2 Example: properties.pl
An example of adding document properties to a Excel::Writer::XLSX file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/properties.jpg" width="640" height="420" alt="Output from properties.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# An example of adding document properties to a Excel::Writer::XLSX file.
#
# reverse ('(c)'), August 2008, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'properties.xlsx' );
my $worksheet = $workbook->add_worksheet();
$workbook->set_properties(
title => 'This is an example spreadsheet',
subject => 'With document properties',
author => 'John McNamara',
manager => 'Dr. Heinz Doofenshmirtz',
company => 'of Wolves',
category => 'Example spreadsheets',
keywords => 'Sample, Example, Properties',
comments => 'Created with Perl and Excel::Writer::XLSX',
status => 'Quo',
);
$worksheet->set_column( 'A:A', 70 );
$worksheet->write( 'A1', qq{Select 'Office Button -> Prepare -> Properties' to see the file properties.} );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/properties.pl>
=head2 Example: protection.pl
Example of cell locking and formula hiding in an Excel worksheet via
the Excel::Writer::XLSX module.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/protection.jpg" width="640" height="420" alt="Output from protection.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
########################################################################
#
# Example of cell locking and formula hiding in an Excel worksheet via
# the Excel::Writer::XLSX module.
#
# reverse ('(c)'), August 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'protection.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Create some format objects
my $unlocked = $workbook->add_format( locked => 0 );
my $hidden = $workbook->add_format( hidden => 1 );
# Format the columns
$worksheet->set_column( 'A:A', 45 );
$worksheet->set_selection( 'B3' );
# Protect the worksheet
$worksheet->protect();
# Examples of cell locking and hiding.
$worksheet->write( 'A1', 'Cell B1 is locked. It cannot be edited.' );
$worksheet->write_formula( 'B1', '=1+2', undef, 3 ); # Locked by default.
$worksheet->write( 'A2', 'Cell B2 is unlocked. It can be edited.' );
$worksheet->write_formula( 'B2', '=1+2', $unlocked, 3 );
$worksheet->write( 'A3', "Cell B3 is hidden. The formula isn't visible." );
$worksheet->write_formula( 'B3', '=1+2', $hidden, 3 );
$worksheet->write( 'A5', 'Use Menu->Tools->Protection->Unprotect Sheet' );
$worksheet->write( 'A6', 'to remove the worksheet protection.' );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/protection.pl>
=head2 Example: rich_strings.pl
An Excel::Writer::XLSX example showing how to use "rich strings", i.e.,
strings with multiple formatting.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/rich_strings.jpg" width="640" height="420" alt="Output from rich_strings.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# An Excel::Writer::XLSX example showing how to use "rich strings", i.e.,
# strings with multiple formatting.
#
# reverse ('(c)'), February 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'rich_strings.xlsx' );
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 30 );
# Set some formats to use.
my $bold = $workbook->add_format( bold => 1 );
my $italic = $workbook->add_format( italic => 1 );
my $red = $workbook->add_format( color => 'red' );
my $blue = $workbook->add_format( color => 'blue' );
my $center = $workbook->add_format( align => 'center' );
my $super = $workbook->add_format( font_script => 1 );
# Write some strings with multiple formats.
$worksheet->write_rich_string( 'A1',
'This is ', $bold, 'bold', ' and this is ', $italic, 'italic' );
$worksheet->write_rich_string( 'A3',
'This is ', $red, 'red', ' and this is ', $blue, 'blue' );
$worksheet->write_rich_string( 'A5',
'Some ', $bold, 'bold text', ' centered', $center );
$worksheet->write_rich_string( 'A7',
$italic, 'j = k', $super, '(n-1)', $center );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/rich_strings.pl>
=head2 Example: right_to_left.pl
Example of how to change the default worksheet direction from
left-to-right to right-to-left as required by some eastern verions
of Excel.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/right_to_left.jpg" width="640" height="420" alt="Output from right_to_left.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# Example of how to change the default worksheet direction from
# left-to-right to right-to-left as required by some eastern verions
# of Excel.
#
# reverse ('(c)'), January 2006, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'right_to_left.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
$worksheet2->right_to_left();
$worksheet1->write( 0, 0, 'Hello' ); # A1, B1, C1, ...
$worksheet2->write( 0, 0, 'Hello' ); # ..., C1, B1, A1
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/right_to_left.pl>
=head2 Example: sales.pl
Example of a sales worksheet to demonstrate several different features.
Also uses functions from the L<Excel::Writer::XLSX::Utility> module.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/sales.jpg" width="640" height="420" alt="Output from sales.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Example of a sales worksheet to demonstrate several different features.
# Also uses functions from the L<Excel::Writer::XLSX::Utility> module.
#
# reverse ('(c)'), October 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
use Excel::Writer::XLSX::Utility;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'sales.xlsx' );
my $worksheet = $workbook->add_worksheet( 'May Sales' );
# Set up some formats
my %heading = (
bold => 1,
pattern => 1,
fg_color => 19,
border => 1,
align => 'center',
);
my %total = (
bold => 1,
top => 1,
num_format => '$#,##0.00'
);
my $heading = $workbook->add_format( %heading );
my $total_format = $workbook->add_format( %total );
my $price_format = $workbook->add_format( num_format => '$#,##0.00' );
my $date_format = $workbook->add_format( num_format => 'mmm d yyy' );
# Write the main headings
$worksheet->freeze_panes( 1 ); # Freeze the first row
$worksheet->write( 'A1', 'Item', $heading );
$worksheet->write( 'B1', 'Quantity', $heading );
$worksheet->write( 'C1', 'Price', $heading );
$worksheet->write( 'D1', 'Total', $heading );
$worksheet->write( 'E1', 'Date', $heading );
# Set the column widths
$worksheet->set_column( 'A:A', 25 );
$worksheet->set_column( 'B:B', 10 );
$worksheet->set_column( 'C:E', 16 );
# Extract the sales data from the __DATA__ section at the end of the file.
# In reality this information would probably come from a database
my @sales;
foreach my $line ( <DATA> ) {
chomp $line;
next if $line eq '';
# Simple-minded processing of CSV data. Refer to the Text::CSV_XS
# and Text::xSV modules for a more complete CSV handling.
my @items = split /,/, $line;
push @sales, \@items;
}
# Write out the items from each row
my $row = 1;
foreach my $sale ( @sales ) {
$worksheet->write( $row, 0, @$sale[0] );
$worksheet->write( $row, 1, @$sale[1] );
$worksheet->write( $row, 2, @$sale[2], $price_format );
# Create a formula like '=B2*C2'
my $formula =
'=' . xl_rowcol_to_cell( $row, 1 ) . "*" . xl_rowcol_to_cell( $row, 2 );
$worksheet->write( $row, 3, $formula, $price_format );
# Parse the date
my $date = xl_decode_date_US( @$sale[3] );
$worksheet->write( $row, 4, $date, $date_format );
$row++;
}
# Create a formula to sum the totals, like '=SUM(D2:D6)'
my $total = '=SUM(D2:' . xl_rowcol_to_cell( $row - 1, 3 ) . ")";
$worksheet->write( $row, 3, $total, $total_format );
__DATA__
586 card,20,125.50,5/12/01
Flat Screen Monitor,1,1300.00,5/12/01
64 MB dimms,45,49.99,5/13/01
15 GB HD,12,300.00,5/13/01
Speakers (pair),5,15.50,5/14/01
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/sales.pl>
=head2 Example: shape1.pl
A simple example of how to use the Excel::Writer::XLSX module to
add shapes to an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape1.jpg" width="640" height="420" alt="Output from shape1.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# add shapes to an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape1.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Add a circle, with centered text.
my $ellipse = $workbook->add_shape(
type => 'ellipse',
text => "Hello\nWorld",
width => 60,
height => 60
);
$worksheet->insert_shape( 'A1', $ellipse, 50, 50 );
# Add a plus sign.
my $plus = $workbook->add_shape( type => 'plus', width => 20, height => 20 );
$worksheet->insert_shape( 'D8', $plus );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape1.pl>
=head2 Example: shape2.pl
A simple example of how to use the Excel::Writer::XLSX module to
modify shape properties in an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape2.jpg" width="640" height="420" alt="Output from shape2.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# modify shape properties in an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape2.xlsx' );
my $worksheet = $workbook->add_worksheet();
$worksheet->hide_gridlines( 2 );
my $plain = $workbook->add_shape(
type => 'smileyFace',
text => "Plain",
width => 100,
height => 100,
);
my $bbformat = $workbook->add_format(
color => 'red',
font => 'Lucida Calligraphy',
);
$bbformat->set_bold();
$bbformat->set_underline();
$bbformat->set_italic();
my $decor = $workbook->add_shape(
type => 'smileyFace',
text => "Decorated",
rotation => 45,
width => 200,
height => 100,
format => $bbformat,
line_type => 'sysDot',
line_weight => 3,
fill => 'FFFF00',
line => '3366FF',
);
$worksheet->insert_shape( 'A1', $plain, 50, 50 );
$worksheet->insert_shape( 'A1', $decor, 250, 50 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape2.pl>
=head2 Example: shape3.pl
A simple example of how to use the Excel::Writer::XLSX module to
scale shapes in an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape3.jpg" width="640" height="420" alt="Output from shape3.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# scale shapes in an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape3.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $normal = $workbook->add_shape(
name => 'chip',
type => 'diamond',
text => "Normal",
width => 100,
height => 100,
);
$worksheet->insert_shape( 'A1', $normal, 50, 50 );
$normal->set_text( 'Scaled 3w x 2h' );
$normal->set_name( 'Hope' );
$worksheet->insert_shape( 'A1', $normal, 250, 50, 3, 2 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape3.pl>
=head2 Example: shape4.pl
A simple example of how to use the Excel::Writer::XLSX module to
demonstrate stenciling in an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape4.jpg" width="640" height="420" alt="Output from shape4.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# demonstrate stenciling in an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape4.xlsx' );
my $worksheet = $workbook->add_worksheet();
$worksheet->hide_gridlines( 2 );
my $type = 'rect';
my $shape = $workbook->add_shape(
type => $type,
width => 90,
height => 90,
);
for my $n ( 1 .. 10 ) {
# Change the last 5 rectangles to stars. Previously inserted shapes stay
# as rectangles.
$type = 'star5' if $n == 6;
$shape->set_type( $type );
$shape->set_text( "$type $n" );
$worksheet->insert_shape( 'A1', $shape, $n * 100, 50 );
}
my $stencil = $workbook->add_shape(
stencil => 1, # The default.
width => 90,
height => 90,
text => 'started as a box',
);
$worksheet->insert_shape( 'A1', $stencil, 100, 150 );
$stencil->set_stencil( 0 );
$worksheet->insert_shape( 'A1', $stencil, 200, 150 );
$worksheet->insert_shape( 'A1', $stencil, 300, 150 );
# Ooops! Changed my mind. Change the rectangle to an ellipse (circle),
# for the last two shapes.
$stencil->set_type( 'ellipse' );
$stencil->set_text( 'Now its a circle' );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape4.pl>
=head2 Example: shape5.pl
A simple example of how to use the Excel::Writer::XLSX module to
add shapes (objects and top/bottom connectors) to an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape5.jpg" width="640" height="420" alt="Output from shape5.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# add shapes (objects and top/bottom connectors) to an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape5.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $s1 = $workbook->add_shape( type => 'ellipse', width => 60, height => 60 );
$worksheet->insert_shape( 'A1', $s1, 50, 50 );
my $s2 = $workbook->add_shape( type => 'plus', width => 20, height => 20 );
$worksheet->insert_shape( 'A1', $s2, 250, 200 );
# Create a connector to link the two shapes.
my $cxn_shape = $workbook->add_shape( type => 'bentConnector3' );
# Link the start of the connector to the right side.
$cxn_shape->set_start( $s1->get_id() );
$cxn_shape->set_start_index( 4 ); # 4th connection pt, clockwise from top(0).
$cxn_shape->set_start_side( 'b' ); # r)ight or b)ottom.
# Link the end of the connector to the left side.
$cxn_shape->set_end( $s2->get_id() );
$cxn_shape->set_end_index( 0 ); # clockwise from top(0).
$cxn_shape->set_end_side( 't' ); # t)top.
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape5.pl>
=head2 Example: shape6.pl
A simple example of how to use the Excel::Writer::XLSX module to
add shapes (objects and right/left connectors) to an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape6.jpg" width="640" height="420" alt="Output from shape6.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# add shapes (objects and right/left connectors) to an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape6.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $s1 = $workbook->add_shape( type => 'chevron', width => 60, height => 60 );
$worksheet->insert_shape( 'A1', $s1, 50, 50 );
my $s2 = $workbook->add_shape( type => 'pentagon', width => 20, height => 20 );
$worksheet->insert_shape( 'A1', $s2, 250, 200 );
# Create a connector to link the two shapes.
my $cxn_shape = $workbook->add_shape( type => 'curvedConnector3' );
# Link the start of the connector to the right side.
$cxn_shape->set_start( $s1->get_id() );
$cxn_shape->set_start_index( 2 ); # 2nd connection pt, clockwise from top(0).
$cxn_shape->set_start_side( 'r' ); # r)ight or b)ottom.
# Link the end of the connector to the left side.
$cxn_shape->set_end( $s2->get_id() );
$cxn_shape->set_end_index( 4 ); # 4th connection pt, clockwise from top(0).
$cxn_shape->set_end_side( 'l' ); # l)eft or t)op.
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape6.pl>
=head2 Example: shape7.pl
A simple example of how to use the Excel::Writer::XLSX module to
add shapes and one-to-many connectors to an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape7.jpg" width="640" height="420" alt="Output from shape7.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# add shapes and one-to-many connectors to an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape7.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Add a circle, with centered text. c is for circle, not center.
my $cw = 60;
my $ch = 60;
my $cx = 210;
my $cy = 190;
my $ellipse = $workbook->add_shape(
type => 'ellipse',
id => 2,
text => "Hello\nWorld",
width => $cw,
height => $ch
);
$worksheet->insert_shape( 'A1', $ellipse, $cx, $cy );
# Add a plus sign at 4 different positions around the circle.
my $pw = 20;
my $ph = 20;
my $px = 120;
my $py = 250;
my $plus =
$workbook->add_shape( type => 'plus', id => 3, width => $pw, height => $ph );
my $p1 = $worksheet->insert_shape( 'A1', $plus, 350, 350 );
my $p2 = $worksheet->insert_shape( 'A1', $plus, 150, 350 );
my $p3 = $worksheet->insert_shape( 'A1', $plus, 350, 150 );
$plus->set_adjustments( 35 ); # change shape of plus symbol.
my $p4 = $worksheet->insert_shape( 'A1', $plus, 150, 150 );
my $cxn_shape = $workbook->add_shape( type => 'bentConnector3', fill => 0 );
$cxn_shape->set_start( $ellipse->get_id() );
$cxn_shape->set_start_index( 4 ); # 4nd connection pt, clockwise from top(0).
$cxn_shape->set_start_side( 'b' ); # r)ight or b)ottom.
$cxn_shape->set_end( $p1->get_id() );
$cxn_shape->set_end_index( 0 );
$cxn_shape->set_end_side( 't' );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
$cxn_shape->set_end( $p2->get_id() );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
$cxn_shape->set_end( $p3->get_id() );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
$cxn_shape->set_end( $p4->get_id() );
$cxn_shape->set_adjustments( -50, 45, 120 );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape7.pl>
=head2 Example: shape8.pl
A simple example of how to use the Excel::Writer::XLSX module to
add shapes and one-to-many connectors to an Excel xlsx file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape8.jpg" width="640" height="420" alt="Output from shape8.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# add shapes and one-to-many connectors to an Excel xlsx file.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape8.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Add a circle, with centered text. c is for circle, not center.
my $cw = 60;
my $ch = 60;
my $cx = 210;
my $cy = 190;
my $ellipse = $workbook->add_shape(
type => 'ellipse',
id => 2,
text => "Hello\nWorld",
width => $cw,
height => $ch
);
$worksheet->insert_shape( 'A1', $ellipse, $cx, $cy );
# Add a plus sign at 4 different positions around the circle.
my $pw = 20;
my $ph = 20;
my $px = 120;
my $py = 250;
my $plus =
$workbook->add_shape( type => 'plus', id => 3, width => $pw, height => $ph );
my $p1 = $worksheet->insert_shape( 'A1', $plus, 350, 150 ); # 2:00
my $p2 = $worksheet->insert_shape( 'A1', $plus, 350, 350 ); # 4:00
my $p3 = $worksheet->insert_shape( 'A1', $plus, 150, 350 ); # 8:00
my $p4 = $worksheet->insert_shape( 'A1', $plus, 150, 150 ); # 10:00
my $cxn_shape = $workbook->add_shape( type => 'bentConnector3', fill => 0 );
$cxn_shape->set_start( $ellipse->get_id() );
$cxn_shape->set_start_index( 2 ); # 2nd connection pt, clockwise from top(0).
$cxn_shape->set_start_side( 'r' ); # r)ight or b)ottom.
$cxn_shape->set_end( $p1->get_id() );
$cxn_shape->set_end_index( 3 ); # 3rd connection point on plus, right side
$cxn_shape->set_end_side( 'l' );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
$cxn_shape->set_end( $p2->get_id() );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
$cxn_shape->set_end( $p3->get_id() );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
$cxn_shape->set_end( $p4->get_id() );
$cxn_shape->set_adjustments( -50, 45, 120 );
$worksheet->insert_shape( 'A1', $cxn_shape, 0, 0 );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape8.pl>
=head2 Example: shape_all.pl
A simple example of how to use the Excel::Writer::XLSX module to
add all shapes (as currently implemented) to an Excel xlsx file.
The list at the end consists of all the shape types defined as
ST_ShapeType in ECMA-376, Office Open XML File Formats Part 4.
The grouping by worksheet name is for illustration only. It isn't
part of the ECMA-376 standard.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/shape_all.jpg" width="640" height="420" alt="Output from shape_all.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# A simple example of how to use the Excel::Writer::XLSX module to
# add all shapes (as currently implemented) to an Excel xlsx file.
#
# The list at the end consists of all the shape types defined as
# ST_ShapeType in ECMA-376, Office Open XML File Formats Part 4.
#
# The grouping by worksheet name is for illustration only. It isn't
# part of the ECMA-376 standard.
#
# reverse ('(c)'), May 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'shape_all.xlsx' );
my ( $worksheet, $last_sheet, $shape, $r ) = ( 0, '', '', undef, 0 );
while ( <DATA> ) {
chomp;
next unless m/^\w/; # Skip blank lines and comments.
my ( $sheet, $name ) = split( /\t/, $_ );
if ( $last_sheet ne $sheet ) {
$worksheet = $workbook->add_worksheet( $sheet );
$r = 2;
}
$last_sheet = $sheet;
$shape = $workbook->add_shape(
type => $name,
text => $name,
width => 90,
height => 90
);
# Connectors can not have labels, so write the connector name in the cell
# to the left.
$worksheet->write( $r, 0, $name ) if $sheet eq 'Connector';
$worksheet->insert_shape( $r, 2, $shape, 0, 0 );
$r += 5;
}
__END__
Action actionButtonBackPrevious
Action actionButtonBeginning
Action actionButtonBlank
Action actionButtonDocument
Action actionButtonEnd
Action actionButtonForwardNext
Action actionButtonHelp
Action actionButtonHome
Action actionButtonInformation
Action actionButtonMovie
Action actionButtonReturn
Action actionButtonSound
Arrow bentArrow
Arrow bentUpArrow
Arrow circularArrow
Arrow curvedDownArrow
Arrow curvedLeftArrow
Arrow curvedRightArrow
Arrow curvedUpArrow
Arrow downArrow
Arrow leftArrow
Arrow leftCircularArrow
Arrow leftRightArrow
Arrow leftRightCircularArrow
Arrow leftRightUpArrow
Arrow leftUpArrow
Arrow notchedRightArrow
Arrow quadArrow
Arrow rightArrow
Arrow stripedRightArrow
Arrow swooshArrow
Arrow upArrow
Arrow upDownArrow
Arrow uturnArrow
Basic blockArc
Basic can
Basic chevron
Basic cube
Basic decagon
Basic diamond
Basic dodecagon
Basic donut
Basic ellipse
Basic funnel
Basic gear6
Basic gear9
Basic heart
Basic heptagon
Basic hexagon
Basic homePlate
Basic lightningBolt
Basic line
Basic lineInv
Basic moon
Basic nonIsoscelesTrapezoid
Basic noSmoking
Basic octagon
Basic parallelogram
Basic pentagon
Basic pie
Basic pieWedge
Basic plaque
Basic rect
Basic round1Rect
Basic round2DiagRect
Basic round2SameRect
Basic roundRect
Basic rtTriangle
Basic smileyFace
Basic snip1Rect
Basic snip2DiagRect
Basic snip2SameRect
Basic snipRoundRect
Basic star10
Basic star12
Basic star16
Basic star24
Basic star32
Basic star4
Basic star5
Basic star6
Basic star7
Basic star8
Basic sun
Basic teardrop
Basic trapezoid
Basic triangle
Callout accentBorderCallout1
Callout accentBorderCallout2
Callout accentBorderCallout3
Callout accentCallout1
Callout accentCallout2
Callout accentCallout3
Callout borderCallout1
Callout borderCallout2
Callout borderCallout3
Callout callout1
Callout callout2
Callout callout3
Callout cloudCallout
Callout downArrowCallout
Callout leftArrowCallout
Callout leftRightArrowCallout
Callout quadArrowCallout
Callout rightArrowCallout
Callout upArrowCallout
Callout upDownArrowCallout
Callout wedgeEllipseCallout
Callout wedgeRectCallout
Callout wedgeRoundRectCallout
Chart chartPlus
Chart chartStar
Chart chartX
Connector bentConnector2
Connector bentConnector3
Connector bentConnector4
Connector bentConnector5
Connector curvedConnector2
Connector curvedConnector3
Connector curvedConnector4
Connector curvedConnector5
Connector straightConnector1
FlowChart flowChartAlternateProcess
FlowChart flowChartCollate
FlowChart flowChartConnector
FlowChart flowChartDecision
FlowChart flowChartDelay
FlowChart flowChartDisplay
FlowChart flowChartDocument
FlowChart flowChartExtract
FlowChart flowChartInputOutput
FlowChart flowChartInternalStorage
FlowChart flowChartMagneticDisk
FlowChart flowChartMagneticDrum
FlowChart flowChartMagneticTape
FlowChart flowChartManualInput
FlowChart flowChartManualOperation
FlowChart flowChartMerge
FlowChart flowChartMultidocument
FlowChart flowChartOfflineStorage
FlowChart flowChartOffpageConnector
FlowChart flowChartOnlineStorage
FlowChart flowChartOr
FlowChart flowChartPredefinedProcess
FlowChart flowChartPreparation
FlowChart flowChartProcess
FlowChart flowChartPunchedCard
FlowChart flowChartPunchedTape
FlowChart flowChartSort
FlowChart flowChartSummingJunction
FlowChart flowChartTerminator
Math mathDivide
Math mathEqual
Math mathMinus
Math mathMultiply
Math mathNotEqual
Math mathPlus
Star_Banner arc
Star_Banner bevel
Star_Banner bracePair
Star_Banner bracketPair
Star_Banner chord
Star_Banner cloud
Star_Banner corner
Star_Banner diagStripe
Star_Banner doubleWave
Star_Banner ellipseRibbon
Star_Banner ellipseRibbon2
Star_Banner foldedCorner
Star_Banner frame
Star_Banner halfFrame
Star_Banner horizontalScroll
Star_Banner irregularSeal1
Star_Banner irregularSeal2
Star_Banner leftBrace
Star_Banner leftBracket
Star_Banner leftRightRibbon
Star_Banner plus
Star_Banner ribbon
Star_Banner ribbon2
Star_Banner rightBrace
Star_Banner rightBracket
Star_Banner verticalScroll
Star_Banner wave
Tabs cornerTabs
Tabs plaqueTabs
Tabs squareTabs
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/shape_all.pl>
=head2 Example: sparklines1.pl
Example of how to add sparklines to an Excel::Writer::XLSX file.
Sparklines are small charts that fit in a single cell and are
used to show trends in data. See sparklines2.pl for examples
of more complex sparkline formatting.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/sparklines1.jpg" width="640" height="420" alt="Output from sparklines1.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to add sparklines to an Excel::Writer::XLSX file.
#
# Sparklines are small charts that fit in a single cell and are
# used to show trends in data. See sparklines2.pl for examples
# of more complex sparkline formatting.
#
# reverse ('(c)'), November 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'sparklines1.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Some sample data to plot.
my $data = [
[ -2, 2, 3, -1, 0 ],
[ 30, 20, 33, 20, 15 ],
[ 1, -1, -1, 1, -1 ],
];
# Write the sample data to the worksheet.
$worksheet->write_col( 'A1', $data );
# Add a line sparkline (the default) with markers.
$worksheet->add_sparkline(
{
location => 'F1',
range => 'Sheet1!A1:E1',
markers => 1,
}
);
# Add a column sparkline with non-default style.
$worksheet->add_sparkline(
{
location => 'F2',
range => 'Sheet1!A2:E2',
type => 'column',
style => 12,
}
);
# Add a win/loss sparkline with negative values highlighted.
$worksheet->add_sparkline(
{
location => 'F3',
range => 'Sheet1!A3:E3',
type => 'win_loss',
negative_points => 1,
}
);
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/sparklines1.pl>
=head2 Example: sparklines2.pl
Example of how to add sparklines to an Excel::Writer::XLSX file.
Sparklines are small charts that fit in a single cell and are
used to show trends in data. This example shows the majority of
options that can be applied to sparklines.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/sparklines2.jpg" width="640" height="420" alt="Output from sparklines2.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to add sparklines to an Excel::Writer::XLSX file.
#
# Sparklines are small charts that fit in a single cell and are
# used to show trends in data. This example shows the majority of
# options that can be applied to sparklines.
#
# reverse ('(c)'), November 2011, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'sparklines2.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $bold = $workbook->add_format( bold => 1 );
my $str;
my $row = 1;
# Set the columns widths to make the output clearer.
$worksheet1->set_column( 'A:A', 14 );
$worksheet1->set_column( 'B:B', 50 );
$worksheet1->set_zoom( 150 );
# Headings.
$worksheet1->write( 'A1', 'Sparkline', $bold );
$worksheet1->write( 'B1', 'Description', $bold );
###############################################################################
#
$str = 'A default "line" sparkline.';
$worksheet1->add_sparkline(
{
location => 'A2',
range => 'Sheet2!A1:J1',
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'A default "column" sparkline.';
$worksheet1->add_sparkline(
{
location => 'A3',
range => 'Sheet2!A2:J2',
type => 'column',
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'A default "win/loss" sparkline.';
$worksheet1->add_sparkline(
{
location => 'A4',
range => 'Sheet2!A3:J3',
type => 'win_loss',
}
);
$worksheet1->write( $row++, 1, $str );
$row++;
###############################################################################
#
$str = 'Line with markers.';
$worksheet1->add_sparkline(
{
location => 'A6',
range => 'Sheet2!A1:J1',
markers => 1,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Line with high and low points.';
$worksheet1->add_sparkline(
{
location => 'A7',
range => 'Sheet2!A1:J1',
high_point => 1,
low_point => 1,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Line with first and last point markers.';
$worksheet1->add_sparkline(
{
location => 'A8',
range => 'Sheet2!A1:J1',
first_point => 1,
last_point => 1,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Line with negative point markers.';
$worksheet1->add_sparkline(
{
location => 'A9',
range => 'Sheet2!A1:J1',
negative_points => 1,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Line with axis.';
$worksheet1->add_sparkline(
{
location => 'A10',
range => 'Sheet2!A1:J1',
axis => 1,
}
);
$worksheet1->write( $row++, 1, $str );
$row++;
###############################################################################
#
$str = 'Column with default style (1).';
$worksheet1->add_sparkline(
{
location => 'A12',
range => 'Sheet2!A2:J2',
type => 'column',
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Column with style 2.';
$worksheet1->add_sparkline(
{
location => 'A13',
range => 'Sheet2!A2:J2',
type => 'column',
style => 2,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Column with style 3.';
$worksheet1->add_sparkline(
{
location => 'A14',
range => 'Sheet2!A2:J2',
type => 'column',
style => 3,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Column with style 4.';
$worksheet1->add_sparkline(
{
location => 'A15',
range => 'Sheet2!A2:J2',
type => 'column',
style => 4,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Column with style 5.';
$worksheet1->add_sparkline(
{
location => 'A16',
range => 'Sheet2!A2:J2',
type => 'column',
style => 5,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Column with style 6.';
$worksheet1->add_sparkline(
{
location => 'A17',
range => 'Sheet2!A2:J2',
type => 'column',
style => 6,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Column with a user defined colour.';
$worksheet1->add_sparkline(
{
location => 'A18',
range => 'Sheet2!A2:J2',
type => 'column',
series_color => '#E965E0',
}
);
$worksheet1->write( $row++, 1, $str );
$row++;
###############################################################################
#
$str = 'A win/loss sparkline.';
$worksheet1->add_sparkline(
{
location => 'A20',
range => 'Sheet2!A3:J3',
type => 'win_loss',
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'A win/loss sparkline with negative points highlighted.';
$worksheet1->add_sparkline(
{
location => 'A21',
range => 'Sheet2!A3:J3',
type => 'win_loss',
negative_points => 1,
}
);
$worksheet1->write( $row++, 1, $str );
$row++;
###############################################################################
#
$str = 'A left to right column (the default).';
$worksheet1->add_sparkline(
{
location => 'A23',
range => 'Sheet2!A4:J4',
type => 'column',
style => 20,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'A right to left column.';
$worksheet1->add_sparkline(
{
location => 'A24',
range => 'Sheet2!A4:J4',
type => 'column',
style => 20,
reverse => 1,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
$str = 'Sparkline and text in one cell.';
$worksheet1->add_sparkline(
{
location => 'A25',
range => 'Sheet2!A4:J4',
type => 'column',
style => 20,
}
);
$worksheet1->write( $row, 0, 'Growth' );
$worksheet1->write( $row++, 1, $str );
$row++;
###############################################################################
#
$str = 'A grouped sparkline. Changes are applied to all three.';
$worksheet1->add_sparkline(
{
location => [ 'A27', 'A28', 'A29' ],
range => [ 'Sheet2!A5:J5', 'Sheet2!A6:J6', 'Sheet2!A7:J7' ],
markers => 1,
}
);
$worksheet1->write( $row++, 1, $str );
###############################################################################
#
# Create a second worksheet with data to plot.
#
$worksheet2->set_column( 'A:J', 11 );
my $data = [
# Simple line data.
[ -2, 2, 3, -1, 0, -2, 3, 2, 1, 0 ],
# Simple column data.
[ 30, 20, 33, 20, 15, 5, 5, 15, 10, 15 ],
# Simple win/loss data.
[ 1, 1, -1, -1, 1, -1, 1, 1, 1, -1 ],
# Unbalanced histogram.
[ 5, 6, 7, 10, 15, 20, 30, 50, 70, 100 ],
# Data for the grouped sparkline example.
[ -2, 2, 3, -1, 0, -2, 3, 2, 1, 0 ],
[ 3, -1, 0, -2, 3, 2, 1, 0, 2, 1 ],
[ 0, -2, 3, 2, 1, 0, 1, 2, 3, 1 ],
];
# Write the sample data to the worksheet.
$worksheet2->write_col( 'A1', $data );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/sparklines2.pl>
=head2 Example: stats_ext.pl
Example of formatting using the Excel::Writer::XLSX module
This is a simple example of how to use functions that reference cells in
other worksheets within the same workbook.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/stats_ext.jpg" width="640" height="420" alt="Output from stats_ext.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Example of formatting using the Excel::Writer::XLSX module
#
# This is a simple example of how to use functions that reference cells in
# other worksheets within the same workbook.
#
# reverse ('(c)'), March 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'stats_ext.xlsx' );
my $worksheet1 = $workbook->add_worksheet( 'Test results' );
my $worksheet2 = $workbook->add_worksheet( 'Data' );
# Set the column width for columns 1
$worksheet1->set_column( 'A:A', 20 );
# Create a format for the headings
my $heading = $workbook->add_format();
$heading->set_bold();
# Create a numerical format
my $numformat = $workbook->add_format();
$numformat->set_num_format( '0.00' );
# Write some statistical functions
$worksheet1->write( 'A1', 'Count', $heading );
$worksheet1->write( 'B1', '=COUNT(Data!B2:B9)' );
$worksheet1->write( 'A2', 'Sum', $heading );
$worksheet1->write( 'B2', '=SUM(Data!B2:B9)' );
$worksheet1->write( 'A3', 'Average', $heading );
$worksheet1->write( 'B3', '=AVERAGE(Data!B2:B9)' );
$worksheet1->write( 'A4', 'Min', $heading );
$worksheet1->write( 'B4', '=MIN(Data!B2:B9)' );
$worksheet1->write( 'A5', 'Max', $heading );
$worksheet1->write( 'B5', '=MAX(Data!B2:B9)' );
$worksheet1->write( 'A6', 'Standard Deviation', $heading );
$worksheet1->write( 'B6', '=STDEV(Data!B2:B9)' );
$worksheet1->write( 'A7', 'Kurtosis', $heading );
$worksheet1->write( 'B7', '=KURT(Data!B2:B9)' );
# Write the sample data
$worksheet2->write( 'A1', 'Sample', $heading );
$worksheet2->write( 'A2', 1 );
$worksheet2->write( 'A3', 2 );
$worksheet2->write( 'A4', 3 );
$worksheet2->write( 'A5', 4 );
$worksheet2->write( 'A6', 5 );
$worksheet2->write( 'A7', 6 );
$worksheet2->write( 'A8', 7 );
$worksheet2->write( 'A9', 8 );
$worksheet2->write( 'B1', 'Length', $heading );
$worksheet2->write( 'B2', 25.4, $numformat );
$worksheet2->write( 'B3', 25.4, $numformat );
$worksheet2->write( 'B4', 24.8, $numformat );
$worksheet2->write( 'B5', 25.0, $numformat );
$worksheet2->write( 'B6', 25.3, $numformat );
$worksheet2->write( 'B7', 24.9, $numformat );
$worksheet2->write( 'B8', 25.2, $numformat );
$worksheet2->write( 'B9', 24.8, $numformat );
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/stats_ext.pl>
=head2 Example: stocks.pl
Example of formatting using the Excel::Writer::XLSX module
This example shows how to use a conditional numerical format
with colours to indicate if a share price has gone up or down.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/stocks.jpg" width="640" height="420" alt="Output from stocks.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Example of formatting using the Excel::Writer::XLSX module
#
# This example shows how to use a conditional numerical format
# with colours to indicate if a share price has gone up or down.
#
# reverse ('(c)'), March 2001, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
# Create a new workbook and add a worksheet
my $workbook = Excel::Writer::XLSX->new( 'stocks.xlsx' );
my $worksheet = $workbook->add_worksheet();
# Set the column width for columns 1, 2, 3 and 4
$worksheet->set_column( 0, 3, 15 );
# Create a format for the column headings
my $header = $workbook->add_format();
$header->set_bold();
$header->set_size( 12 );
$header->set_color( 'blue' );
# Create a format for the stock price
my $f_price = $workbook->add_format();
$f_price->set_align( 'left' );
$f_price->set_num_format( '$0.00' );
# Create a format for the stock volume
my $f_volume = $workbook->add_format();
$f_volume->set_align( 'left' );
$f_volume->set_num_format( '#,##0' );
# Create a format for the price change. This is an example of a conditional
# format. The number is formatted as a percentage. If it is positive it is
# formatted in green, if it is negative it is formatted in red and if it is
# zero it is formatted as the default font colour (in this case black).
# Note: the [Green] format produces an unappealing lime green. Try
# [Color 10] instead for a dark green.
#
my $f_change = $workbook->add_format();
$f_change->set_align( 'left' );
$f_change->set_num_format( '[Green]0.0%;[Red]-0.0%;0.0%' );
# Write out the data
$worksheet->write( 0, 0, 'Company', $header );
$worksheet->write( 0, 1, 'Price', $header );
$worksheet->write( 0, 2, 'Volume', $header );
$worksheet->write( 0, 3, 'Change', $header );
$worksheet->write( 1, 0, 'Damage Inc.' );
$worksheet->write( 1, 1, 30.25, $f_price ); # $30.25
$worksheet->write( 1, 2, 1234567, $f_volume ); # 1,234,567
$worksheet->write( 1, 3, 0.085, $f_change ); # 8.5% in green
$worksheet->write( 2, 0, 'Dump Corp.' );
$worksheet->write( 2, 1, 1.56, $f_price ); # $1.56
$worksheet->write( 2, 2, 7564, $f_volume ); # 7,564
$worksheet->write( 2, 3, -0.015, $f_change ); # -1.5% in red
$worksheet->write( 3, 0, 'Rev Ltd.' );
$worksheet->write( 3, 1, 0.13, $f_price ); # $0.13
$worksheet->write( 3, 2, 321, $f_volume ); # 321
$worksheet->write( 3, 3, 0, $f_change ); # 0 in the font color (black)
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/stocks.pl>
=head2 Example: tab_colors.pl
Example of how to set Excel worksheet tab colours.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/tab_colors.jpg" width="640" height="420" alt="Output from tab_colors.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
#######################################################################
#
# Example of how to set Excel worksheet tab colours.
#
# reverse ('(c)'), May 2006, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'tab_colors.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $worksheet3 = $workbook->add_worksheet();
my $worksheet4 = $workbook->add_worksheet();
# Worksheet1 will have the default tab colour.
$worksheet2->set_tab_color( 'red' );
$worksheet3->set_tab_color( 'green' );
$worksheet4->set_tab_color( 0x35 ); # Orange
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/tab_colors.pl>
=head2 Example: tables.pl
Example of how to add tables to an Excel::Writer::XLSX worksheet.
Tables in Excel are used to group rows and columns of data into a single
structure that can be referenced in a formula or formatted collectively.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/tables.jpg" width="640" height="420" alt="Output from tables.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
###############################################################################
#
# Example of how to add tables to an Excel::Writer::XLSX worksheet.
#
# Tables in Excel are used to group rows and columns of data into a single
# structure that can be referenced in a formula or formatted collectively.
#
# reverse ('(c)'), September 2012, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'tables.xlsx' );
my $worksheet1 = $workbook->add_worksheet();
my $worksheet2 = $workbook->add_worksheet();
my $worksheet3 = $workbook->add_worksheet();
my $worksheet4 = $workbook->add_worksheet();
my $worksheet5 = $workbook->add_worksheet();
my $worksheet6 = $workbook->add_worksheet();
my $worksheet7 = $workbook->add_worksheet();
my $worksheet8 = $workbook->add_worksheet();
my $worksheet9 = $workbook->add_worksheet();
my $worksheet10 = $workbook->add_worksheet();
my $worksheet11 = $workbook->add_worksheet();
my $worksheet12 = $workbook->add_worksheet();
my $currency_format = $workbook->add_format( num_format => '$#,##0' );
# Some sample data for the table.
my $data = [
[ 'Apples', 10000, 5000, 8000, 6000 ],
[ 'Pears', 2000, 3000, 4000, 5000 ],
[ 'Bananas', 6000, 6000, 6500, 6000 ],
[ 'Oranges', 500, 300, 200, 700 ],
];
###############################################################################
#
# Example 1.
#
my $caption = 'Default table with no data.';
# Set the columns widths.
$worksheet1->set_column( 'B:G', 12 );
# Write the caption.
$worksheet1->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet1->add_table( 'B3:F7' );
###############################################################################
#
# Example 2.
#
$caption = 'Default table with data.';
# Set the columns widths.
$worksheet2->set_column( 'B:G', 12 );
# Write the caption.
$worksheet2->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet2->add_table( 'B3:F7', { data => $data } );
###############################################################################
#
# Example 3.
#
$caption = 'Table without default autofilter.';
# Set the columns widths.
$worksheet3->set_column( 'B:G', 12 );
# Write the caption.
$worksheet3->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet3->add_table( 'B3:F7', { autofilter => 0 } );
# Table data can also be written separately, as an array or individual cells.
$worksheet3->write_col( 'B4', $data );
###############################################################################
#
# Example 4.
#
$caption = 'Table without default header row.';
# Set the columns widths.
$worksheet4->set_column( 'B:G', 12 );
# Write the caption.
$worksheet4->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet4->add_table( 'B4:F7', { header_row => 0 } );
# Table data can also be written separately, as an array or individual cells.
$worksheet4->write_col( 'B4', $data );
###############################################################################
#
# Example 5.
#
$caption = 'Default table with "First Column" and "Last Column" options.';
# Set the columns widths.
$worksheet5->set_column( 'B:G', 12 );
# Write the caption.
$worksheet5->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet5->add_table( 'B3:F7', { first_column => 1, last_column => 1 } );
# Table data can also be written separately, as an array or individual cells.
$worksheet5->write_col( 'B4', $data );
###############################################################################
#
# Example 6.
#
$caption = 'Table with banded columns but without default banded rows.';
# Set the columns widths.
$worksheet6->set_column( 'B:G', 12 );
# Write the caption.
$worksheet6->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet6->add_table( 'B3:F7', { banded_rows => 0, banded_columns => 1 } );
# Table data can also be written separately, as an array or individual cells.
$worksheet6->write_col( 'B4', $data );
###############################################################################
#
# Example 7.
#
$caption = 'Table with user defined column headers';
# Set the columns widths.
$worksheet7->set_column( 'B:G', 12 );
# Write the caption.
$worksheet7->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet7->add_table(
'B3:F7',
{
data => $data,
columns => [
{ header => 'Product' },
{ header => 'Quarter 1' },
{ header => 'Quarter 2' },
{ header => 'Quarter 3' },
{ header => 'Quarter 4' },
]
}
);
###############################################################################
#
# Example 8.
#
$caption = 'Table with user defined column headers';
# Set the columns widths.
$worksheet8->set_column( 'B:G', 12 );
# Write the caption.
$worksheet8->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet8->add_table(
'B3:G7',
{
data => $data,
columns => [
{ header => 'Product' },
{ header => 'Quarter 1' },
{ header => 'Quarter 2' },
{ header => 'Quarter 3' },
{ header => 'Quarter 4' },
{
header => 'Year',
formula => '=SUM(Table8[@[Quarter 1]:[Quarter 4]])'
},
]
}
);
###############################################################################
#
# Example 9.
#
$caption = 'Table with totals row (but no caption or totals).';
# Set the columns widths.
$worksheet9->set_column( 'B:G', 12 );
# Write the caption.
$worksheet9->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet9->add_table(
'B3:G8',
{
data => $data,
total_row => 1,
columns => [
{ header => 'Product' },
{ header => 'Quarter 1' },
{ header => 'Quarter 2' },
{ header => 'Quarter 3' },
{ header => 'Quarter 4' },
{
header => 'Year',
formula => '=SUM(Table9[@[Quarter 1]:[Quarter 4]])'
},
]
}
);
###############################################################################
#
# Example 10.
#
$caption = 'Table with totals row with user captions and functions.';
# Set the columns widths.
$worksheet10->set_column( 'B:G', 12 );
# Write the caption.
$worksheet10->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet10->add_table(
'B3:G8',
{
data => $data,
total_row => 1,
columns => [
{ header => 'Product', total_string => 'Totals' },
{ header => 'Quarter 1', total_function => 'sum' },
{ header => 'Quarter 2', total_function => 'sum' },
{ header => 'Quarter 3', total_function => 'sum' },
{ header => 'Quarter 4', total_function => 'sum' },
{
header => 'Year',
formula => '=SUM(Table10[@[Quarter 1]:[Quarter 4]])',
total_function => 'sum'
},
]
}
);
###############################################################################
#
# Example 11.
#
$caption = 'Table with alternative Excel style.';
# Set the columns widths.
$worksheet11->set_column( 'B:G', 12 );
# Write the caption.
$worksheet11->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet11->add_table(
'B3:G8',
{
data => $data,
style => 'Table Style Light 11',
total_row => 1,
columns => [
{ header => 'Product', total_string => 'Totals' },
{ header => 'Quarter 1', total_function => 'sum' },
{ header => 'Quarter 2', total_function => 'sum' },
{ header => 'Quarter 3', total_function => 'sum' },
{ header => 'Quarter 4', total_function => 'sum' },
{
header => 'Year',
formula => '=SUM(Table11[@[Quarter 1]:[Quarter 4]])',
total_function => 'sum'
},
]
}
);
###############################################################################
#
# Example 12.
#
$caption = 'Table with column formats.';
# Set the columns widths.
$worksheet12->set_column( 'B:G', 12 );
# Write the caption.
$worksheet12->write( 'B1', $caption );
# Add a table to the worksheet.
$worksheet12->add_table(
'B3:G8',
{
data => $data,
total_row => 1,
columns => [
{ header => 'Product', total_string => 'Totals' },
{
header => 'Quarter 1',
total_function => 'sum',
format => $currency_format,
},
{
header => 'Quarter 2',
total_function => 'sum',
format => $currency_format,
},
{
header => 'Quarter 3',
total_function => 'sum',
format => $currency_format,
},
{
header => 'Quarter 4',
total_function => 'sum',
format => $currency_format,
},
{
header => 'Year',
formula => '=SUM(Table12[@[Quarter 1]:[Quarter 4]])',
total_function => 'sum',
format => $currency_format,
},
]
}
);
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/tables.pl>
=head2 Example: write_handler1.pl
Example of how to add a user defined data handler to the
Excel::Writer::XLSX write() method.
The following example shows how to add a handler for a 7 digit ID number.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/write_handler1.jpg" width="640" height="420" alt="Output from write_handler1.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Example of how to add a user defined data handler to the
# Excel::Writer::XLSX write() method.
#
# The following example shows how to add a handler for a 7 digit ID number.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'write_handler1.xlsx' );
my $worksheet = $workbook->add_worksheet();
###############################################################################
#
# Add a handler for 7 digit id numbers. This is useful when you want a string
# such as 0000001 written as a string instead of a number and thus preserve
# the leading zeroes.
#
# Note: you can get the same effect using the keep_leading_zeros() method but
# this serves as a simple example.
#
$worksheet->add_write_handler( qr[^\d{7}$], \&write_my_id );
###############################################################################
#
# The following function processes the data when a match is found.
#
sub write_my_id {
my $worksheet = shift;
return $worksheet->write_string( @_ );
}
# This format maintains the cell as text even if it is edited.
my $id_format = $workbook->add_format( num_format => '@' );
# Write some numbers in the user defined format
$worksheet->write( 'A1', '0000000', $id_format );
$worksheet->write( 'A2', '0000001', $id_format );
$worksheet->write( 'A3', '0004000', $id_format );
$worksheet->write( 'A4', '1234567', $id_format );
# Write some numbers that don't match the defined format
$worksheet->write( 'A6', '000000', $id_format );
$worksheet->write( 'A7', '000001', $id_format );
$worksheet->write( 'A8', '004000', $id_format );
$worksheet->write( 'A9', '123456', $id_format );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/write_handler1.pl>
=head2 Example: write_handler2.pl
Example of how to add a user defined data handler to the
Excel::Writer::XLSX write() method.
The following example shows how to add a handler for a 7 digit ID number.
It adds an additional constraint to the write_handler1.pl in that it only
filters data that isn't in the third column.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/write_handler2.jpg" width="640" height="420" alt="Output from write_handler2.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Example of how to add a user defined data handler to the
# Excel::Writer::XLSX write() method.
#
# The following example shows how to add a handler for a 7 digit ID number.
# It adds an additional constraint to the write_handler1.pl in that it only
# filters data that isn't in the third column.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'write_handler2.xlsx' );
my $worksheet = $workbook->add_worksheet();
###############################################################################
#
# Add a handler for 7 digit id numbers. This is useful when you want a string
# such as 0000001 written as a string instead of a number and thus preserve
# the leading zeroes.
#
# Note: you can get the same effect using the keep_leading_zeros() method but
# this serves as a simple example.
#
$worksheet->add_write_handler( qr[^\d{7}$], \&write_my_id );
###############################################################################
#
# The following function processes the data when a match is found. The handler
# is set up so that it only filters data if it is in the third column.
#
sub write_my_id {
my $worksheet = shift;
my $col = $_[1];
# col is zero based
if ( $col != 2 ) {
return $worksheet->write_string( @_ );
}
else {
# Reject the match and return control to write()
return undef;
}
}
# This format maintains the cell as text even if it is edited.
my $id_format = $workbook->add_format( num_format => '@' );
# Write some numbers in the user defined format
$worksheet->write( 'A1', '0000000', $id_format );
$worksheet->write( 'B1', '0000001', $id_format );
$worksheet->write( 'C1', '0000002', $id_format );
$worksheet->write( 'D1', '0000003', $id_format );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/write_handler2.pl>
=head2 Example: write_handler3.pl
Example of how to add a user defined data handler to the
Excel::Writer::XLSX write() method.
The following example shows how to add a handler for dates in a specific
format.
See write_handler4.pl for a more rigorous example with error handling.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/write_handler3.jpg" width="640" height="420" alt="Output from write_handler3.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Example of how to add a user defined data handler to the
# Excel::Writer::XLSX write() method.
#
# The following example shows how to add a handler for dates in a specific
# format.
#
# See write_handler4.pl for a more rigorous example with error handling.
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'write_handler3.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $date_format = $workbook->add_format( num_format => 'dd/mm/yy' );
###############################################################################
#
# Add a handler to match dates in the following format: d/m/yyyy
#
# The day and month can be single or double digits.
#
$worksheet->add_write_handler( qr[^\d{1,2}/\d{1,2}/\d{4}$], \&write_my_date );
###############################################################################
#
# The following function processes the data when a match is found.
# See write_handler4.pl for a more rigorous example with error handling.
#
sub write_my_date {
my $worksheet = shift;
my @args = @_;
my $token = $args[2];
$token =~ qr[^(\d{1,2})/(\d{1,2})/(\d{4})$];
# Change to the date format required by write_date_time().
my $date = sprintf "%4d-%02d-%02dT", $3, $2, $1;
$args[2] = $date;
return $worksheet->write_date_time( @args );
}
# Write some dates in the user defined format
$worksheet->write( 'A1', '22/12/2004', $date_format );
$worksheet->write( 'A2', '1/1/1995', $date_format );
$worksheet->write( 'A3', '01/01/1995', $date_format );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/write_handler3.pl>
=head2 Example: write_handler4.pl
Example of how to add a user defined data handler to the
Excel::Writer::XLSX write() method.
The following example shows how to add a handler for dates in a specific
format.
This is a more rigorous version of write_handler3.pl.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/write_handler4.jpg" width="640" height="420" alt="Output from write_handler4.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl -w
###############################################################################
#
# Example of how to add a user defined data handler to the
# Excel::Writer::XLSX write() method.
#
# The following example shows how to add a handler for dates in a specific
# format.
#
# This is a more rigorous version of write_handler3.pl.
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'write_handler4.xlsx' );
my $worksheet = $workbook->add_worksheet();
my $date_format = $workbook->add_format( num_format => 'dd/mm/yy' );
###############################################################################
#
# Add a handler to match dates in the following formats: d/m/yy, d/m/yyyy
#
# The day and month can be single or double digits and the year can be 2 or 4
# digits.
#
$worksheet->add_write_handler( qr[^\d{1,2}/\d{1,2}/\d{2,4}$], \&write_my_date );
###############################################################################
#
# The following function processes the data when a match is found.
#
sub write_my_date {
my $worksheet = shift;
my @args = @_;
my $token = $args[2];
if ( $token =~ qr[^(\d{1,2})/(\d{1,2})/(\d{2,4})$] ) {
my $day = $1;
my $mon = $2;
my $year = $3;
# Use a window for 2 digit dates. This will keep some ragged Perl
# programmer employed in thirty years time. :-)
if ( length $year == 2 ) {
if ( $year < 50 ) {
$year += 2000;
}
else {
$year += 1900;
}
}
my $date = sprintf "%4d-%02d-%02dT", $year, $mon, $day;
# Convert the ISO ISO8601 style string to an Excel date
$date = $worksheet->convert_date_time( $date );
if ( defined $date ) {
# Date was valid
$args[2] = $date;
return $worksheet->write_number( @args );
}
else {
# Not a valid date therefore write as a string
return $worksheet->write_string( @args );
}
}
else {
# Shouldn't happen if the same match is used in the re and sub.
return undef;
}
}
# Write some dates in the user defined format
$worksheet->write( 'A1', '22/12/2004', $date_format );
$worksheet->write( 'A2', '22/12/04', $date_format );
$worksheet->write( 'A3', '2/12/04', $date_format );
$worksheet->write( 'A4', '2/5/04', $date_format );
$worksheet->write( 'A5', '2/5/95', $date_format );
$worksheet->write( 'A6', '2/5/1995', $date_format );
# Some erroneous dates
$worksheet->write( 'A8', '2/5/1895', $date_format ); # Date out of Excel range
$worksheet->write( 'A9', '29/2/2003', $date_format ); # Invalid leap day
$worksheet->write( 'A10', '50/50/50', $date_format ); # Matches but isn't a date
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/write_handler4.pl>
=head2 Example: write_to_scalar.pl
An example of writing an Excel::Writer::XLSX file to a perl scalar.
#!/usr/bin/perl
##############################################################################
#
# An example of writing an Excel::Writer::XLSX file to a perl scalar.
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# Use a scalar as a filehandle.
open my $fh, '>', \my $str or die "Failed to open filehandle: $!";
# Spreadsheet::WriteExce accepts filehandle as well as file names.
my $workbook = Excel::Writer::XLSX->new( $fh );
my $worksheet = $workbook->add_worksheet();
$worksheet->write( 0, 0, 'Hi Excel!' );
$workbook->close();
# The Excel file in now in $str. Remember to binmode() the output
# filehandle before printing it.
open my $out_fh, '>', 'write_to_scalar.xlsx'
or die "Failed to open out filehandle: $!";
binmode $out_fh;
print $out_fh $str;
close $out_fh;
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/write_to_scalar.pl>
=head2 Example: unicode_2022_jp.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Japanese from a file with ISO-2022-JP
encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_2022_jp.jpg" width="640" height="420" alt="Output from unicode_2022_jp.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Japanese from a file with ISO-2022-JP
# encoded text.
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_2022_jp.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_2022_jp.txt';
open FH, '<:encoding(iso-2022-jp)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_2022_jp.pl>
=head2 Example: unicode_8859_11.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Thai from a file with ISO-8859-11 encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_8859_11.jpg" width="640" height="420" alt="Output from unicode_8859_11.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Thai from a file with ISO-8859-11 encoded text.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_8859_11.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_8859_11.txt';
open FH, '<:encoding(iso-8859-11)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_8859_11.pl>
=head2 Example: unicode_8859_7.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Greek from a file with ISO-8859-7 encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_8859_7.jpg" width="640" height="420" alt="Output from unicode_8859_7.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Greek from a file with ISO-8859-7 encoded text.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_8859_7.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_8859_7.txt';
open FH, '<:encoding(iso-8859-7)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_8859_7.pl>
=head2 Example: unicode_big5.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Chinese from a file with BIG5 encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_big5.jpg" width="640" height="420" alt="Output from unicode_big5.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Chinese from a file with BIG5 encoded text.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_big5.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 80 );
my $file = 'unicode_big5.txt';
open FH, '<:encoding(big5)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_big5.pl>
=head2 Example: unicode_cp1251.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Russian from a file with CP1251 encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_cp1251.jpg" width="640" height="420" alt="Output from unicode_cp1251.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Russian from a file with CP1251 encoded text.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_cp1251.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_cp1251.txt';
open FH, '<:encoding(cp1251)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_cp1251.pl>
=head2 Example: unicode_cp1256.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Arabic text from a CP-1256 encoded file.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_cp1256.jpg" width="640" height="420" alt="Output from unicode_cp1256.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Arabic text from a CP-1256 encoded file.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_cp1256.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_cp1256.txt';
open FH, '<:encoding(cp1256)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_cp1256.pl>
=head2 Example: unicode_cyrillic.pl
A simple example of writing some Russian cyrillic text using
Excel::Writer::XLSX.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_cyrillic.jpg" width="640" height="420" alt="Output from unicode_cyrillic.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of writing some Russian cyrillic text using
# Excel::Writer::XLSX.
#
#
#
#
# reverse ('(c)'), March 2005, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
# In this example we generate utf8 strings from character data but in a
# real application we would expect them to come from an external source.
#
# Create a Russian worksheet name in utf8.
my $sheet = pack "U*", 0x0421, 0x0442, 0x0440, 0x0430, 0x043D, 0x0438,
0x0446, 0x0430;
# Create a Russian string.
my $str = pack "U*", 0x0417, 0x0434, 0x0440, 0x0430, 0x0432, 0x0441,
0x0442, 0x0432, 0x0443, 0x0439, 0x0020, 0x041C,
0x0438, 0x0440, 0x0021;
my $workbook = Excel::Writer::XLSX->new( 'unicode_cyrillic.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet( $sheet . '1' );
$worksheet->set_column( 'A:A', 18 );
$worksheet->write( 'A1', $str );
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_cyrillic.pl>
=head2 Example: unicode_koi8r.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Russian from a file with KOI8-R encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_koi8r.jpg" width="640" height="420" alt="Output from unicode_koi8r.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Russian from a file with KOI8-R encoded text.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_koi8r.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_koi8r.txt';
open FH, '<:encoding(koi8-r)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_koi8r.pl>
=head2 Example: unicode_polish_utf8.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Polish from a file with UTF8 encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_polish_utf8.jpg" width="640" height="420" alt="Output from unicode_polish_utf8.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Polish from a file with UTF8 encoded text.
#
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_polish_utf8.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_polish_utf8.txt';
open FH, '<:encoding(utf8)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_polish_utf8.pl>
=head2 Example: unicode_shift_jis.pl
A simple example of converting some Unicode text to an Excel file using
Excel::Writer::XLSX.
This example generates some Japenese text from a file with Shift-JIS
encoded text.
=begin html
<p><center><img src="http://jmcnamara.github.com/excel-writer-xlsx/images/examples/unicode_shift_jis.jpg" width="640" height="420" alt="Output from unicode_shift_jis.pl" /></center></p>
=end html
Source code for this example:
#!/usr/bin/perl
##############################################################################
#
# A simple example of converting some Unicode text to an Excel file using
# Excel::Writer::XLSX.
#
# This example generates some Japenese text from a file with Shift-JIS
# encoded text.
#
# reverse ('(c)'), September 2004, John McNamara, jmcnamara@cpan.org
#
use strict;
use warnings;
use Excel::Writer::XLSX;
my $workbook = Excel::Writer::XLSX->new( 'unicode_shift_jis.xlsx' );
die "Couldn't create new Excel file: $!.\n" unless defined $workbook;
my $worksheet = $workbook->add_worksheet();
$worksheet->set_column( 'A:A', 50 );
my $file = 'unicode_shift_jis.txt';
open FH, '<:encoding(shiftjis)', $file or die "Couldn't open $file: $!\n";
my $row = 0;
while ( <FH> ) {
next if /^#/; # Ignore the comments in the sample file.
chomp;
$worksheet->write( $row++, 0, $_ );
}
__END__
Download this example: L<http://cpansearch.perl.org/src/JMCNAMARA/Excel-Writer-XLSX-0.75/examples/unicode_shift_jis.pl>
=head1 AUTHOR
John McNamara jmcnamara@cpan.org
Contributed examples contain the original author's name.
=head1 COPYRIGHT
Copyright MM-MMXII, John McNamara.
All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
=cut
| Microsoft/StorScore | lib/Excel/Writer/XLSX/Examples.pm | Perl | mit | 310,149 |
package autodie;
use 5.008;
use strict;
use warnings;
use Fatal ();
our @ISA = qw(Fatal);
our $VERSION;
BEGIN {
$VERSION = '2.13';
}
use constant ERROR_WRONG_FATAL => q{
Incorrect version of Fatal.pm loaded by autodie.
The autodie pragma uses an updated version of Fatal to do its
heavy lifting. We seem to have loaded Fatal version %s, which is
probably the version that came with your version of Perl. However
autodie needs version %s, which would have come bundled with
autodie.
You may be able to solve this problem by adding the following
line of code to your main program, before any use of Fatal or
autodie.
use lib "%s";
};
# We have to check we've got the right version of Fatal before we
# try to compile the rest of our code, lest we use a constant
# that doesn't exist.
BEGIN {
# If we have the wrong Fatal, then we've probably loaded the system
# one, not our own. Complain, and give a useful hint. ;)
if ($Fatal::VERSION ne $VERSION) {
my $autodie_path = $INC{'autodie.pm'};
$autodie_path =~ s/autodie\.pm//;
require Carp;
Carp::croak sprintf(
ERROR_WRONG_FATAL, $Fatal::VERSION, $VERSION, $autodie_path
);
}
}
# When passing args to Fatal we want to keep the first arg
# (our package) in place. Hence the splice.
sub import {
splice(@_,1,0,Fatal::LEXICAL_TAG);
goto &Fatal::import;
}
sub unimport {
splice(@_,1,0,Fatal::LEXICAL_TAG);
goto &Fatal::unimport;
}
1;
__END__
=head1 NAME
autodie - Replace functions with ones that succeed or die with lexical scope
=head1 SYNOPSIS
use autodie; # Recommended: implies 'use autodie qw(:default)'
use autodie qw(:all); # Recommended more: defaults and system/exec.
use autodie qw(open close); # open/close succeed or die
open(my $fh, "<", $filename); # No need to check!
{
no autodie qw(open); # open failures won't die
open(my $fh, "<", $filename); # Could fail silently!
no autodie; # disable all autodies
}
=head1 DESCRIPTION
bIlujDI' yIchegh()Qo'; yIHegh()!
It is better to die() than to return() in failure.
-- Klingon programming proverb.
The C<autodie> pragma provides a convenient way to replace functions
that normally return false on failure with equivalents that throw
an exception on failure.
The C<autodie> pragma has I<lexical scope>, meaning that functions
and subroutines altered with C<autodie> will only change their behaviour
until the end of the enclosing block, file, or C<eval>.
If C<system> is specified as an argument to C<autodie>, then it
uses L<IPC::System::Simple> to do the heavy lifting. See the
description of that module for more information.
=head1 EXCEPTIONS
Exceptions produced by the C<autodie> pragma are members of the
L<autodie::exception> class. The preferred way to work with
these exceptions under Perl 5.10 is as follows:
use feature qw(switch);
eval {
use autodie;
open(my $fh, '<', $some_file);
my @records = <$fh>;
# Do things with @records...
close($fh);
};
given ($@) {
when (undef) { say "No error"; }
when ('open') { say "Error from open"; }
when (':io') { say "Non-open, IO error."; }
when (':all') { say "All other autodie errors." }
default { say "Not an autodie error at all." }
}
Under Perl 5.8, the C<given/when> structure is not available, so the
following structure may be used:
eval {
use autodie;
open(my $fh, '<', $some_file);
my @records = <$fh>;
# Do things with @records...
close($fh);
};
if ($@ and $@->isa('autodie::exception')) {
if ($@->matches('open')) { print "Error from open\n"; }
if ($@->matches(':io' )) { print "Non-open, IO error."; }
} elsif ($@) {
# A non-autodie exception.
}
See L<autodie::exception> for further information on interrogating
exceptions.
=head1 CATEGORIES
Autodie uses a simple set of categories to group together similar
built-ins. Requesting a category type (starting with a colon) will
enable autodie for all built-ins beneath that category. For example,
requesting C<:file> will enable autodie for C<close>, C<fcntl>,
C<fileno>, C<open> and C<sysopen>.
The categories are currently:
:all
:default
:io
read
seek
sysread
sysseek
syswrite
:dbm
dbmclose
dbmopen
:file
binmode
close
fcntl
fileno
flock
ioctl
open
sysopen
truncate
:filesys
chdir
closedir
opendir
link
mkdir
readlink
rename
rmdir
symlink
unlink
:ipc
pipe
:msg
msgctl
msgget
msgrcv
msgsnd
:semaphore
semctl
semget
semop
:shm
shmctl
shmget
shmread
:socket
accept
bind
connect
getsockopt
listen
recv
send
setsockopt
shutdown
socketpair
:threads
fork
:system
system
exec
Note that while the above category system is presently a strict
hierarchy, this should not be assumed.
A plain C<use autodie> implies C<use autodie qw(:default)>. Note that
C<system> and C<exec> are not enabled by default. C<system> requires
the optional L<IPC::System::Simple> module to be installed, and enabling
C<system> or C<exec> will invalidate their exotic forms. See L</BUGS>
below for more details.
The syntax:
use autodie qw(:1.994);
allows the C<:default> list from a particular version to be used. This
provides the convenience of using the default methods, but the surety
that no behavorial changes will occur if the C<autodie> module is
upgraded.
C<autodie> can be enabled for all of Perl's built-ins, including
C<system> and C<exec> with:
use autodie qw(:all);
=head1 FUNCTION SPECIFIC NOTES
=head2 flock
It is not considered an error for C<flock> to return false if it fails
due to an C<EWOULDBLOCK> (or equivalent) condition. This means one can
still use the common convention of testing the return value of
C<flock> when called with the C<LOCK_NB> option:
use autodie;
if ( flock($fh, LOCK_EX | LOCK_NB) ) {
# We have a lock
}
Autodying C<flock> will generate an exception if C<flock> returns
false with any other error.
=head2 system/exec
The C<system> built-in is considered to have failed in the following
circumstances:
=over 4
=item *
The command does not start.
=item *
The command is killed by a signal.
=item *
The command returns a non-zero exit value (but see below).
=back
On success, the autodying form of C<system> returns the I<exit value>
rather than the contents of C<$?>.
Additional allowable exit values can be supplied as an optional first
argument to autodying C<system>:
system( [ 0, 1, 2 ], $cmd, @args); # 0,1,2 are good exit values
C<autodie> uses the L<IPC::System::Simple> module to change C<system>.
See its documentation for further information.
Applying C<autodie> to C<system> or C<exec> causes the exotic
forms C<system { $cmd } @args > or C<exec { $cmd } @args>
to be considered a syntax error until the end of the lexical scope.
If you really need to use the exotic form, you can call C<CORE::system>
or C<CORE::exec> instead, or use C<no autodie qw(system exec)> before
calling the exotic form.
=head1 GOTCHAS
Functions called in list context are assumed to have failed if they
return an empty list, or a list consisting only of a single undef
element.
=head1 DIAGNOSTICS
=over 4
=item :void cannot be used with lexical scope
The C<:void> option is supported in L<Fatal>, but not
C<autodie>. To workaround this, C<autodie> may be explicitly disabled until
the end of the current block with C<no autodie>.
To disable autodie for only a single function (eg, open)
use C<no autodie qw(open)>.
C<autodie> performs no checking of called context to determine whether to throw
an exception; the explicitness of error handling with C<autodie> is a deliberate
feature.
=item No user hints defined for %s
You've insisted on hints for user-subroutines, either by pre-pending
a C<!> to the subroutine name itself, or earlier in the list of arguments
to C<autodie>. However the subroutine in question does not have
any hints available.
=back
See also L<Fatal/DIAGNOSTICS>.
=head1 BUGS
"Used only once" warnings can be generated when C<autodie> or C<Fatal>
is used with package filehandles (eg, C<FILE>). Scalar filehandles are
strongly recommended instead.
When using C<autodie> or C<Fatal> with user subroutines, the
declaration of those subroutines must appear before the first use of
C<Fatal> or C<autodie>, or have been exported from a module.
Attempting to use C<Fatal> or C<autodie> on other user subroutines will
result in a compile-time error.
Due to a bug in Perl, C<autodie> may "lose" any format which has the
same name as an autodying built-in or function.
C<autodie> may not work correctly if used inside a file with a
name that looks like a string eval, such as F<eval (3)>.
=head2 autodie and string eval
Due to the current implementation of C<autodie>, unexpected results
may be seen when used near or with the string version of eval.
I<None of these bugs exist when using block eval>.
Under Perl 5.8 only, C<autodie> I<does not> propagate into string C<eval>
statements, although it can be explicitly enabled inside a string
C<eval>.
Under Perl 5.10 only, using a string eval when C<autodie> is in
effect can cause the autodie behaviour to leak into the surrounding
scope. This can be worked around by using a C<no autodie> at the
end of the scope to explicitly remove autodie's effects, or by
avoiding the use of string eval.
I<None of these bugs exist when using block eval>. The use of
C<autodie> with block eval is considered good practice.
=head2 REPORTING BUGS
Please report bugs via the CPAN Request Tracker at
L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=autodie>.
=head1 FEEDBACK
If you find this module useful, please consider rating it on the
CPAN Ratings service at
L<http://cpanratings.perl.org/rate?distribution=autodie> .
The module author loves to hear how C<autodie> has made your life
better (or worse). Feedback can be sent to
E<lt>pjf@perltraining.com.auE<gt>.
=head1 AUTHOR
Copyright 2008-2009, Paul Fenwick E<lt>pjf@perltraining.com.auE<gt>
=head1 LICENSE
This module is free software. You may distribute it under the
same terms as Perl itself.
=head1 SEE ALSO
L<Fatal>, L<autodie::exception>, L<autodie::hints>, L<IPC::System::Simple>
I<Perl tips, autodie> at
L<http://perltraining.com.au/tips/2008-08-20.html>
=head1 ACKNOWLEDGEMENTS
Mark Reed and Roland Giersig -- Klingon translators.
See the F<AUTHORS> file for full credits. The latest version of this
file can be found at
L<http://github.com/pfenwick/autodie/tree/master/AUTHORS> .
=cut
| Bjay1435/capstone | rootfs/usr/share/perl/5.18.2/autodie.pm | Perl | mit | 11,935 |
#
# Copyright 2017 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::pacemaker::local::plugin;
use strict;
use warnings;
use base qw(centreon::plugins::script_simple);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '0.1';
%{$self->{modes}} = (
'crm' => 'apps::pacemaker::local::mode::crm',
'constraints' => 'apps::pacemaker::local::mode::constraints',
'clustat' => 'apps::pacemaker::local::mode::clustat',
);
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Pacemaker through local commands (the plugin can use SSH).
=cut
| maksimatveev/centreon-plugins | apps/pacemaker/local/plugin.pm | Perl | apache-2.0 | 1,481 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/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';
0488 0489
20DD 20E0
20E2 20E4
A670 A672
END
| efortuna/AndroidSDKClone | ndk_experimental/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Gc/Me.pl | Perl | apache-2.0 | 463 |
=pod
=head1 NAME
SSL_CTX_set_generate_session_id, SSL_set_generate_session_id,
SSL_has_matching_session_id, GEN_SESSION_CB
- manipulate generation of SSL session IDs (server only)
=head1 SYNOPSIS
#include <openssl/ssl.h>
typedef int (*GEN_SESSION_CB)(const SSL *ssl, unsigned char *id,
unsigned int *id_len);
int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb);
int SSL_set_generate_session_id(SSL *ssl, GEN_SESSION_CB, cb);
int SSL_has_matching_session_id(const SSL *ssl, const unsigned char *id,
unsigned int id_len);
=head1 DESCRIPTION
SSL_CTX_set_generate_session_id() sets the callback function for generating
new session ids for SSL/TLS sessions for B<ctx> to be B<cb>.
SSL_set_generate_session_id() sets the callback function for generating
new session ids for SSL/TLS sessions for B<ssl> to be B<cb>.
SSL_has_matching_session_id() checks, whether a session with id B<id>
(of length B<id_len>) is already contained in the internal session cache
of the parent context of B<ssl>.
=head1 NOTES
When a new session is established between client and server, the server
generates a session id. The session id is an arbitrary sequence of bytes.
The length of the session id is between 1 and 32 bytes. The session id is not
security critical but must be unique for the server. Additionally, the session id is
transmitted in the clear when reusing the session so it must not contain
sensitive information.
Without a callback being set, an OpenSSL server will generate a unique
session id from pseudo random numbers of the maximum possible length.
Using the callback function, the session id can be changed to contain
additional information like e.g. a host id in order to improve load balancing
or external caching techniques.
The callback function receives a pointer to the memory location to put
B<id> into and a pointer to the maximum allowed length B<id_len>. The
buffer at location B<id> is only guaranteed to have the size B<id_len>.
The callback is only allowed to generate a shorter id and reduce B<id_len>;
the callback B<must never> increase B<id_len> or write to the location
B<id> exceeding the given limit.
The location B<id> is filled with 0x00 before the callback is called, so the
callback may only fill part of the possible length and leave B<id_len>
untouched while maintaining reproducibility.
Since the sessions must be distinguished, session ids must be unique.
Without the callback a random number is used, so that the probability
of generating the same session id is extremely small (2^256 for SSLv3/TLSv1).
In order to assure the uniqueness of the generated session id, the callback must call
SSL_has_matching_session_id() and generate another id if a conflict occurs.
If an id conflict is not resolved, the handshake will fail.
If the application codes e.g. a unique host id, a unique process number, and
a unique sequence number into the session id, uniqueness could easily be
achieved without randomness added (it should however be taken care that
no confidential information is leaked this way). If the application can not
guarantee uniqueness, it is recommended to use the maximum B<id_len> and
fill in the bytes not used to code special information with random data
to avoid collisions.
SSL_has_matching_session_id() will only query the internal session cache,
not the external one. Since the session id is generated before the
handshake is completed, it is not immediately added to the cache. If
another thread is using the same internal session cache, a race condition
can occur in that another thread generates the same session id.
Collisions can also occur when using an external session cache, since
the external cache is not tested with SSL_has_matching_session_id()
and the same race condition applies.
The callback must return 0 if it cannot generate a session id for whatever
reason and return 1 on success.
=head1 EXAMPLES
The callback function listed will generate a session id with the
server id given, and will fill the rest with pseudo random bytes:
const char session_id_prefix = "www-18";
#define MAX_SESSION_ID_ATTEMPTS 10
static int generate_session_id(const SSL *ssl, unsigned char *id,
unsigned int *id_len)
{
unsigned int count = 0;
do {
RAND_pseudo_bytes(id, *id_len);
/*
* Prefix the session_id with the required prefix. NB: If our
* prefix is too long, clip it - but there will be worse effects
* anyway, eg. the server could only possibly create 1 session
* ID (ie. the prefix!) so all future session negotiations will
* fail due to conflicts.
*/
memcpy(id, session_id_prefix,
(strlen(session_id_prefix) < *id_len) ?
strlen(session_id_prefix) : *id_len);
}
while (SSL_has_matching_session_id(ssl, id, *id_len) &&
(++count < MAX_SESSION_ID_ATTEMPTS));
if (count >= MAX_SESSION_ID_ATTEMPTS)
return 0;
return 1;
}
=head1 RETURN VALUES
SSL_CTX_set_generate_session_id() and SSL_set_generate_session_id()
always return 1.
SSL_has_matching_session_id() returns 1 if another session with the
same id is already in the cache.
=head1 SEE ALSO
L<ssl(7)>, L<SSL_get_version(3)>
=head1 COPYRIGHT
Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
Licensed under the OpenSSL license (the "License"). You may not use
this file except in compliance with the License. You can obtain a copy
in the file LICENSE in the source distribution or at
L<https://www.openssl.org/source/license.html>.
=cut
| openweave/openweave-core | third_party/openssl/openssl/doc/ssl/SSL_CTX_set_generate_session_id.pod | Perl | apache-2.0 | 5,705 |
#!/usr/bin/perl -w
# This handler requires JSON::XS, File::Copy.
use strict;
use warnings;
use CGI qw(:standard);
use JSON::XS;
use File::Copy;
use utf8;
my $base_url = "http://localhost"; # The base URL for your file directory
my $root = "/srv/http/jwysiwyg"; # Local URI for file directory
my $action = param("action");
# All responses are strict JSON.
print "Content-type: application/json; charset=utf-8\n\n";
my $JSON = JSON::XS->new()->pretty(1);
my $dir = url_decode(param("dir"));
my $file = url_decode(param("file"));
my $newName = url_decode(param("newName"));
# Rename File Method:
if ($action eq "rename") {
if (-e "$root$dir$file") {
if ($newName =~ /^([\w\.\(\)_\-\s]+)$/) {
$newName = $1;
$file =~ /([\w\.\(\)_\-\s]+)/;
$file = $1;
if (-e "$root$dir$newName") {
print $JSON->encode({ "success" => JSON::XS::false, "error" => "'$newName' already exists." });
} else {
if (move("$root$dir$file", "$root$dir$newName")) {
print $JSON->encode({ "success" => JSON::XS::true, "data" => "'$file' is now '$newName'." });
} else {
print $JSON->encode({ "success" => JSON::XS::false, "error" => "Error while trying to rename: $file" });
}
}
} else {
print $JSON->encode({ "success" => JSON::XS::false, "error" => "New name contains illegal characters." });
}
} else {
print $JSON->encode({ "success" => JSON::XS::false, "error" => "'$file' does not exist." });
}
}
# Method for decoding GET method utf8
sub url_decode {
my $arg = $_[0];
if ($arg =~ /\/?\.\.\/?/) { return 0; } # This is an important safety precaution -> Using firebug it is very easy to access all the data on the server, simply by using the hard-links of the linux system: ../ and ./ to reach higher level directories.
# Support for Unicode, UTF-8:
$arg =~ tr/+/ /;
$arg =~ s/%([a-fA-F0-9]{2})/pack("C", hex($1))/eg;
$arg =~ s/%u0([a-fA-F0-9]{3})/pack("U", hex($1))/eg;
utf8::decode($arg);
return $arg;
}
| allengaller/zenx-tmall | web/public_html/protected/modules/translate/widgets/assets/jwysiwyg/plugins/fileManager/handlers/Perl/rename_handler.pl | Perl | mit | 1,953 |
package DDG::Spice::Lastfm::Album;
# ABSTRACT: Display album info.
use strict;
use DDG::Spice;
spice to => 'http://ws.audioscrobbler.com/2.0/?format=json&method=album.getinfo&album=$1&autocorrect=1&artist=$2&api_key={{ENV{DDG_SPICE_LASTFM_APIKEY}}}&callback={{callback}}';
spice from => '(?:([^/]*)/([^/]*)|)';
triggers query_lc => qr/^([^\s]+(?:\s+[^\s]+)*)\s+(?:albums?|records?|cds?)\s+(?:by|from)?\s+([^\s]+(?:\s+[^\s]+)*)$/;
handle matches => sub {
if($1 and $2) {
return $1, $2;
}
return;
};
1;
| soleo/zeroclickinfo-spice | lib/DDG/Spice/Lastfm/Album.pm | Perl | apache-2.0 | 527 |
package DDG::Spice::Sports::MLB::Games;
# ABSTRACT: MLB Boxscores
use strict;
use DDG::Spice;
spice to => 'https://duckduckgo.com/sports.js?q=$1&callback={{callback}}';
triggers start => '///***never trigger***///';
handle remainder => sub {
return $_;
# return $_ if $_ && !exists $skip{lc $_};
return;
};
1;
| soleo/zeroclickinfo-spice | lib/DDG/Spice/Sports/MLB/Games.pm | Perl | apache-2.0 | 326 |
package Test::Count::Parser;
use warnings;
use strict;
use base 'Test::Count::Base';
use File::Basename (qw(dirname));
use Parse::RecDescent;
=encoding utf8
=head1 NAME
Test::Count::Parser - A Parser for Test::Count.
=cut
our $VERSION = '0.0901';
sub _get_grammar
{
return <<'EOF';
update_count: expression {$thisparser->{count} += $item[1]}
assignments: statement <commit> ';' assignments
| statement
statement: assignment
| expression {$item [1]}
| including_file {$item [1]}
including_file: 'source' string {push @{$thisparser->{includes}}, $item[2];}
assignment: variable '=' statement {$thisparser->{vars}->{$item [1]} = $item [3]}
| variable '+=' statement {$thisparser->{vars}->{$item [1]} += $item [3]}
| variable '-=' statement {$thisparser->{vars}->{$item [1]} -= $item [3]}
| variable '*=' statement {$thisparser->{vars}->{$item [1]} *= $item [3]}
expression: variable '++' {$thisparser->{vars}->{$item [1]}++}
| term '+' expression {$item [1] + $item [3]}
| term '-' expression {$item [1] - $item [3]}
| term
term: factor '*' term {$item [1] * $item [3]}
| factor '/' term {int($item [1] / $item [3])}
| factor
factor: number
| variable {
(exists($thisparser->{vars}->{$item [1]})
? $thisparser->{vars}->{$item [1]}
: do { die "Undefined variable \"$item[1]\""; } )
}
| '+' factor {$item [2]}
| '-' factor {$item [2] * -1}
| '(' statement ')' {$item [2]}
number: /\d+/ {$item [1]}
variable: /\$[a-z_]\w*/i
string: /"[^"]+"/
EOF
}
sub _calc_parser
{
my $self = shift;
my $parser = Parse::RecDescent->new($self->_get_grammar());
$parser->{vars} = {};
$parser->{count} = 0;
$parser->{includes} = [];
return $parser;
}
sub _parser
{
my $self = shift;
if (@_)
{
$self->{'_parser'} = shift;
}
return $self->{'_parser'};
}
sub _current_fns
{
my $self = shift;
if (@_)
{
$self->{'_current_fns'} = shift;
}
return $self->{'_current_fns'};
}
sub _init
{
my $self = shift;
$self->_current_fns([]);
$self->_parser($self->_calc_parser());
return 0;
}
=head1 SYNOPSIS
use Test::Count::Parser;
my $parser = Test::Count::Parser->new();
$parser->update_assignments($string);
$parser->update_count($string);
my $value = $parser->get_count();
=head1 DESCRIPTIONS
After initiating a parser one can input assignment expressions, and count
update experssions. Both of them use arithmetic operations, integers, and
Perl-like variable names.
At the end one should call C<$parser->get_count()> in order to get the
total number of tests.
=head1 FUNCTIONS
=head2 $parser->update_assignments({'text' => $mytext,)
Updates the parser's state based on the assignments in C<$mytext>. For
example if C<$mytext> is:
$myvar=500;$another_var=8+$myvar
Then at the end C<$myvar> would be 500 and C<$another_var> would be 508.
=cut
sub _push_current_filename
{
my $self = shift;
my $filename = shift;
push @{$self->_current_fns()}, $filename;
return;
}
sub _pop_current_filenames
{
my $self = shift;
my $filename = shift;
pop(@{$self->_current_fns()});
return;
}
sub _get_current_filename
{
my $self = shift;
return $self->_current_fns->[-1];
}
sub _parse_filename
{
my $self = shift;
my $filename = shift;
$filename =~ s{\A"}{};
$filename =~ s{"\z}{};
my $dirname = dirname($self->_get_current_filename());
$filename =~ s{\$\^CURRENT_DIRNAME}{$dirname}g;
return $filename;
}
sub update_assignments
{
my ($self, $args) = @_;
$self->_parser->{includes} = [];
my $ret = $self->_parser()->assignments($args->{text});
if (@{$self->_parser->{includes}})
{
foreach my $include_file (@{$self->_parser->{includes}})
{
my $counter =
Test::Count->new(
{
filename => $self->_parse_filename($include_file),
},
);
$counter->process({parser => $self});
}
$self->_parser->{includes} = [];
}
}
=head2 $parser->update_count({'text' => $mytext,)
Adds the expression inside C<$mytext> to the internal counter of the
module. This is in order to count the tests.
=cut
sub update_count
{
my ($self, $args) = @_;
return $self->_parser()->update_count($args->{text});
}
=head2 my $count = $parser->get_count()
Get the total number of tests in the parser.
=cut
sub get_count
{
my $self = shift;
return $self->_parser()->{count};
}
=head1 AUTHOR
Shlomi Fish, L<http://www.shlomifish.org/> .
=head1 BUGS
Please report any bugs or feature requests to
C<bug-test-count-parser at rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test::Count>.
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 Test::Count
You can also look for information at:
=over 4
=item * AnnoCPAN: Annotated CPAN documentation
L<http://annocpan.org/dist/Test::Count>
=item * CPAN Ratings
L<http://cpanratings.perl.org/d/Test::Count>
=item * RT: CPAN's request tracker
L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Test::Count>
=item * Search CPAN
L<http://search.cpan.org/dist/Test::Count>
=back
=head1 ACKNOWLEDGEMENTS
The Parser uses L<Parse::RecDescent> by Damian Conway and is based on the
example code of René Nyffenegger (L<http://www.adp-gmbh.ch/>) available here:
L<http://www.adp-gmbh.ch/perl/rec_descent.html>
=head1 COPYRIGHT & LICENSE
Copyright 2006 Shlomi Fish.
This program is released under the following license: MIT X11.
=cut
1; # End of Test::Count::Parser
| gitpan/Test-Count | lib/Test/Count/Parser.pm | Perl | mit | 6,265 |
:- module(output, [output/1]).
:- use_module(library(irc_client)).
output(Msg) :-
thread_create(output_(Msg), _, [detached(true)]).
output_(Id-Msg) :-
Msg = msg(Prefix, Cmd, Params, Trailer),
format("~s: ~s ~s ~w ~s~n", [Id, Prefix, Cmd, Params, Trailer]).
output_(Id-Msg) :-
Msg = msg(Prefix, Cmd, Params),
\+ is_list(Cmd),
!,
format("~s: ~s ~s ~w~n", [Id, Prefix, Cmd, Params]).
output_(Id-Msg) :-
Msg = msg(Cmd, Params, Trailer),
format("~s: ~s ~w ~s~n", [Id, Cmd, Params, Trailer]).
output_(Id-Msg) :-
Msg = msg(Cmd, Params),
format("~s: ~s ~w~n", [Id, Cmd, Params]).
| eazar001/yesbot | extensions/output.pl | Perl | mit | 590 |
package Ort;
use strict 'vars';
use strict 'refs';
use Data::Dumper;
use File::Basename;
sub new {
my ($filename, $gene_identifying_feature, $format, $genome_codes) = @_;
die "Error: Ort.pm. GIF should be be gene or transcript" if(($gene_identifying_feature ne 'gene') && ($gene_identifying_feature ne 'transcript'));
die "Error: Ort.pm. Format should be RBH, Orthofinder or OMCL" if(($format ne 'RBH') && ($format ne 'Orthofinder') && ($format ne 'OMCL'));
die "Error: Ort.pm. Genome codes required" if(!defined $genome_codes);
my $self = {
filename => $filename,
gene_identifying_feature => $gene_identifying_feature,
format => $format,
genome_codes => $genome_codes
};
bless $self, Ort;
return $self;
}
sub get_filename {
my $self = shift;
return $self->{filename};
}
sub read {
my $self = shift;
$self->read_RBH() if ($self->{format} eq "RBH");
$self->read_OMCL() if($self->{format} eq "OMCL");
$self->read_Orthofinder_Orthogroups_csv_output() if($self->{format} eq "Orthofinder");
@{ $self->{cluster_ids} } = sort { $a <=> $b } keys( %{ $self->{cluster_ids_hash} } );
}
# Output look like so
# genome1 (CNA2_FINAL_CALLGENES_3.annotation.pep.synima-parsed.PEP) tab genome2
# orthogroupName e.g. OG0000000 tab genes in genome 1 separated by ,\w tab genes in genome 2 separated by ,\w etc
sub read_Orthofinder_Orthogroups_csv_output {
my $self = shift;
# Genome index file: for_orthofinder.genome_codes
#EFCM_Com12_VC1 EFCM_Com12_V1_FINAL_CALLGENES_2
my $genome_codes = $self->{genome_codes};
open my $fh, '<', $genome_codes or die "Unable to open OrthoMCL genome index file $genome_codes\n";
warn "Saving genome codes $genome_codes...\n";
while (my $line=<$fh>) {
chomp $line;
my @bits = split /\t|\s/, $line;
my ($org_name, $org_annotation) = @bits;
#warn "$org_name -> $org_annotation\n";
$self->{'org_name'}{$org_annotation} = $org_name;
$self->{'org_annotation'}{$org_name} = $org_annotation;
}
close $fh;
my @species_headers;
my $filename = $self->{filename};
warn "Saving $filename...\n";
open my $fh2, '<', $filename or die "Unable to open file $filename\n";
ORTHOLOGS: while (my $line=<$fh2>) {
chomp $line;
$line =~ s/\r//g;
die "The cluster file $filename seems to be generated by OrthoMCL.\nPlease indicate the correct format." if ($line =~ /^ORTHOMCL/);
next if $line =~ /^\s*$/;
my @bits = split /\t/, $line;
# Headers
if($line=~ m/^\t/) {
#warn "my header line = $line\n";
for(my $i=1; $i<(scalar(@bits)); $i++) {
my $annotation_name = $bits[$i];
if($annotation_name =~ m/\.annotation\.pep\.synima-parsed$/i) { $annotation_name =~ s/\.annotation\.pep\.synima-parsed//i; }
elsif($annotation_name =~ m/\.annotation\.cds\.synima-parsed$/i) { $annotation_name =~ s/\.annotation\.cds\.synima-parsed//i; }
else { die "Error parsing Orthofinder: Expecting the headers (e.g. $annotation_name) in $filename to include .annotation.[pep|cds].synima-parsed...\n"; }
#warn "looking for org_name $annotation_name ??\n";
my $genome_name = $self->{'org_name'}{$annotation_name};
die "no genome name for $annotation_name" if($genome_name eq '');
die "Cannot find a genome_name for $annotation_name in $genome_codes\n" if(!defined $genome_name);
$bits[$i] = $genome_name;
#warn "Match annotation_name $annotation_name with my genome_codes genome name $genome_name\n";
}
#warn "new header line = @bits\n";
@species_headers = @bits;
#die "end here in the headers section!\n";
next ORTHOLOGS;
}
# Ortholog number
my $orts_num = $bits[0];
$orts_num =~ s/^OG//;
$self->{cluster_ids_hash}{$orts_num} = 1;
# OG0000000 7000009599256769, 7000009599264239, 7000009599293440, 7000009599298752, 7000009599305456, 7000009599308997 7000006584184531, 7000006584186760, 7000006584188603, 7000006584201291, 7000006584207955, 7000006584224838 CDWM_001058T0, CDWM_002978T0, CDWM_003014T0, CDWM_003685T0, CDWM_004128T0, CDWM_005912T0
for(my $i=1; $i<(scalar(@bits)); $i++) {
my $curr_field = $bits[$i];
my $org_name = $species_headers[$i];
#warn "species $i $org_name...\n";
my @ind_genes = split /, /, $curr_field;
foreach my $curr_gene(@ind_genes) {
next if((!defined $curr_gene) || ($curr_gene eq ''));
#warn "cg $curr_gene ort $orts_num on $org_name\n";
#die "$gene from $org_name_tmp\n";
push( @{ $self->{orts}[$orts_num]{$org_name} }, $curr_gene );
$self->{gene_index}{$curr_gene} = $orts_num;
$self->{gene}{$curr_gene} = $curr_gene;
$self->{set}{$curr_gene} = "Ortho";
$self->{locus_name}{$curr_gene} = $curr_gene;
$self->{transcript}{$curr_gene} = $curr_gene;
}
#my $org_name = $self->{org_name};
}
#die Dumper($self);
#die "end here\n";
}
#die Dumper($self);
close $fh2;
}
sub read_OMCL {
my $self = shift;
# Genome index file: for_omcl.genome_codes
#EFCM_Com12_V1_FINAL_CALLGENES_2 G001
#ECAS_EC20_V1_FINAL_CALLGENES_1 G002
#EFCM_Com15_V1_FINAL_CALLGENES_1 G003
my $genome_codes = $self->{genome_codes};
open my $fh, '<', $genome_codes or die "Unable to open OrthoMCL genome index file $genome_codes\n";
warn "Saving genome codes $genome_codes...\n";
while (my $line=<$fh>) {
chomp $line;
my @bits = split " ", $line;
my ($org_name, $org_num_hex) = @bits;
$org_num_hex =~ s/^G*//;
my $org_num = hex( $org_num_hex);
$self->{org_num}{$org_name} = $org_num;
$self->{org_name}[$org_num] = $org_name;
}
close $fh;
# Cluster file: all_orthomcl.out
#ORTHOMCL0(9 genes,2 taxa): G001|7000003252690302(G001) G001|7000003252690305(G001) G001|7000003252690389(G001) G001|7000003252690392(G001) G003|7000003071119023(G003) G003|7000003071119026(G003) G003|7000003071120910(G003) G003|7000003071120913(G003) G003|7000003071120922(G003)
#ORTHOMCL1(6 genes,2 taxa): G001|7000003252690296(G001) G001|7000003252690395(G001) G003|7000003071119029(G003) G003|7000003071119032(G003) G003|7000003071120919(G003) G003|7000003071120925(G003)
open ORTS_FILE, $self->{filename} or die "Unable to open file " . $self->{filename} . "\n";
while (my $line=<ORTS_FILE>) {
chomp $line;
my ($orts_num,$orts_fields) = ( $line =~ /^ORTHOMCL(\d+)[\w\W]+?\t\s([\w\W]+)/ );
die "Error: OrthoMCL file parsing: Unrecognizable line:\n $line\n" if((!defined $orts_num) || (!defined $orts_fields));
#push( @{ $self->{cluster_ids} }, $orts_num );
$self->{cluster_ids_hash}{$orts_num} = 1;
my @fields = split " ", $orts_fields;
foreach my $curr_field (@fields) {
my ($org_num_hex, $curr_gene) = ( $curr_field =~ /([\w\W]+?)\|([\w\W]+?)\(/ );
$org_num_hex =~ s/^G*//;
my $org_num = hex($org_num_hex);
my $org_name = $self->{org_name}[$org_num];
push( @{ $self->{orts}[$orts_num]{$org_name} }, $curr_gene );
$self->{gene_index}{$curr_gene} = $orts_num;
$self->{gene}{$curr_gene} = $curr_gene;
$self->{set}{$curr_gene} = "Ortho";
$self->{locus_name}{$curr_gene} = $curr_gene;
$self->{transcript}{$curr_gene} = $curr_gene;
}
}
close ORTS_FILE;
}
#828547707 Ecoli_H112180280 Ecoli_H112180280_POSTPRODIGAL_2 7000006964752101 7000006964752100 None mannose-1-phosphate guanylyltransferase 1
#828547707 Ecoli_TY_2482_BGI Ecoli_TY_2482_BGI_POSTPRODIGAL_2 7000006964764261 7000006964764260 None mannose-1-phosphate guanylyltransferase 1
#828547707 EscCol_55989_GBD3 EscCol_55989_GBD3_POSTPRODIGAL_1 7000006964790339 7000006964790338 None mannose-1-phosphate guanylyltransferase 1
#828547707 Esch_coli_04-8351_V1 Esch_coli_04-8351_V1_POSTPRODIGAL_1 7000006961080847 7000006961080846 EUDG_02241 mannose-1-phosphate guanylyltransferase 1
sub read_RBH {
my $self = shift;
my $filename = $self->{filename};
open my $fh, '<', $filename or die "Unable to open file $filename\n";
while (my $line=<$fh>) {
chomp $line;
die "The cluster file $filename seems to be generated by OrthoMCL.\nPlease indicate the correct format." if ($line =~ /^ORTHOMCL/);
next if $line =~ /^\s*$/;
my @bits = split /\t/, $line;
my ($orts_num, $set, $org_name, $transcript, $gene, $locus_name, $func_annot) = @bits;
$self->{cluster_ids_hash}{$orts_num} = 1;
my $gene_identifier;
if ( $self->{gene_identifying_feature} eq "transcript" ) { $gene_identifier = $transcript; }
elsif ( $self->{gene_identifying_feature} eq "gene" ) { $gene_identifier = $gene; }
elsif ( $self->{gene_identifying_feature} eq "locus_name" ) { $gene_identifier = $locus_name; }
else { die "Unrecognizable gene identifying feature \'" . $self->{gene_identifying_feature} . "\'\n"; }
#warn "Orts num: $orts_num Org name: >>>>>$org_name<<<<< Identifier: $gene_identifier\n";
#getc();
push( @{ $self->{orts}[$orts_num]{$org_name} }, $gene_identifier );
$self->{gene_index}{$gene_identifier} = $orts_num;
$self->{gene_annot}{$gene_identifier} = $func_annot;
$self->{locus_name}{$gene_identifier} = $locus_name;
$self->{transcript}{$gene_identifier} = $transcript;
$self->{gene}{$gene_identifier} = $gene;
$self->{set}{$gene_identifier} = $set;
$self->{org_num}{$org_name} = 1;
}
close $fh;
# Associating a number to each organisms/genome
my $cont_org = 0;
foreach my $curr_org ( keys %{ $self->{org_num} } ) {
$self->{org_num}{$curr_org} = $cont_org;
$self->{org_name}[$cont_org] = $curr_org;
$cont_org++;
}
}
sub add_annotation {
my $self = shift;
my %all_proteins;
my ($file_in) = @_;
open my $fh, '<', $file_in or die "Unable to open file $file_in\n";
while(my $line=<$fh>){
chomp $line;
my @bits = split /\t/, $line;
my ($transcript,$gene_id,$locus_name,$func_annot) = @bits;
my $gene_identifier;
if ($self->{gene_identifying_feature} eq "transcript") { $gene_identifier = $transcript; }
elsif ($self->{gene_identifying_feature} eq "gene") { $gene_identifier = $gene_id; }
elsif ($self->{gene_identifying_feature} eq "locus_name") { $gene_identifier = $locus_name; }
else { die "Unrecognizable gene identifying feature \'" . $self->{gene_identifying_feature} . "\'\n"; }
$self->{gene_annot}{$gene_identifier} = $func_annot;
$self->{locus_name}{$gene_identifier} = $locus_name;
$self->{transcript}{$gene_identifier} = $transcript;
$self->{gene}{$gene_identifier} = $gene_id;
}
close $fh;
}
sub get_gene_annot {
my $self = shift;
my ($gene_name) = @_;
return $self->{gene_annot}{$gene_name};
}
sub combined_annot_cluster {
my $self = shift;
my ($orts_num) = @_;
my %all_annot;
foreach my $org_name ( keys %{ $self->{orts}[$orts_num] } ) {
foreach my $ortholog ( @{ $self->{orts}[$orts_num]{$org_name} } ) {
my $curr_annot = $self->{gene_annot}{$ortholog};
$curr_annot =~ s/name="//g;
$curr_annot =~ s/"//g;
$all_annot{$curr_annot} = 1;
}
}
return join( ' && ', keys %all_annot );
}
sub combined_annot_from_genes {
my $self = shift;
my ($refArrGeneName) = @_;
my %all_annot;
foreach my $curr_gene ( @{$refArrGeneName} ) {
my $curr_annot = $self->{gene_annot}{$curr_gene};
$curr_annot =~ s/name="//g;
$curr_annot =~ s/"//g;
$all_annot{$curr_annot} = 1;
}
return join( ' && ', keys %all_annot );
}
sub get_orgs {
my $self = shift;
# OMCL/RBH eq @, Orthofinder = {}
if($self->{format} eq 'Orthofinder') { return %{ $self->{org_name} }; }
else { return @{ $self->{org_name} }; }
}
sub get_cluster_ids {
my $self = shift;
return @{ $self->{cluster_ids} };
}
sub get_org_name {
my $self = shift;
my ($org_num) = @_;
return $self->{org_name}[$org_num];
}
sub get_org_num {
my $self = shift;
my ($org_name) = @_;
return -1 if not defined $self->{org_num}{$org_name};
return $self->{org_num}{$org_name};
}
sub get_num_orgs {
my $self = shift;
return scalar( @{ $self->{org_name} } );
}
sub get_orts {
my $self = shift;
my ( $gene_name, $org_name ) = @_;
my $orts_num = $self->{gene_index}{$gene_name};
#print STDERR "Org name. $org_name Orts num:" . $orts_num . "\n";
if (!defined $orts_num) {
#print STDERR "Not able to find gene >>>$gene_name<<< in the ortholog clusters file.\n";
return "";
}
elsif (!defined($self->{orts}[$orts_num]{$org_name})) {
#print STDERR "Not able to find orthologs of >>>$org_name<<< on cluster num. $orts_num\n";
return "";
}
elsif (!defined($self->get_org_num($org_name))) {
#print STDERR "Genome >>>$org_name<<< not found in the ortholog clusters file.\n";
return "";
}
return @{ $self->{orts}[$orts_num]{$org_name} };
}
sub get_core {
my $self = shift;
my ( $gene_name, $org_name ) = @_;
my $orts_num = -1;
$orts_num = $self->{gene_index}{$gene_name};
if ( $orts_num == -1 || not defined( $self->{orts}[$orts_num]{$org_name})) {
warn "Not able to find ortholog of gene $gene_name on $org_name\n";
return 0;
}
return @{ $self->{orts}[$orts_num]{$org_name} };
}
sub get_cluster_desc_repo_format {
my $self = shift;
my ($orts_num) = @_;
my $content = '';
my %all_annot;
foreach my $org_name ( keys %{ $self->{orts}[$orts_num] } ) {
die "no org name $org_name for orts $orts_num\n" if((!defined $org_name) || ($org_name eq ''));
#die "what is my org_name $org_name and what is my orts_num $orts_num\n";
foreach my $ortholog ( @{ $self->{orts}[$orts_num]{$org_name} } ) {
my $curr_annot = $self->{gene_annot}{$ortholog};
$curr_annot =~ s/name="//g;
$curr_annot =~ s/"//g;
my $locus_name = $self->{locus_name}{$ortholog};
my $transcript = $self->{transcript}{$ortholog};
my $gene = $self->{gene}{$ortholog};
my $set = $self->{set}{$ortholog};
$content .= join("\t", ($orts_num, $org_name, $set, $transcript, $gene, $locus_name, $curr_annot)) . "\n";
}
}
#die "my content = $content\n";
return $content;
}
sub print_cluster {
my $self = shift;
my ($gene_name) = @_;
my $orts_num = $self->{gene_index}{$gene_name};
#warn "Org name. $org_name Orts num:" . $orts_num . "\n";
if (! defined $orts_num) {
warn "Not able to find gene >>>$gene_name<<< in the ortholog clusters file.\n";
}
foreach my $org_name ( keys %{ $self->{orts}[$orts_num] } ) {
print "Org: $org_name\n";
foreach my $ortholog ( @{ $self->{orts}[$orts_num]{$org_name} } ) {
print "\t$ortholog\n";
}
}
}
sub get_orts_by_cluster_num_org {
my $self = shift;
my ($orts_num, $org_name) = @_;
#print STDERR "Org name. $org_name Orts num:" . $orts_num . "\n";
if ( not defined( $self->{orts}[$orts_num]{$org_name} ) ) {
#warn "Not able to find ortholog on $org_name for cluster $orts_num\n";
return 0;
}
return @{ $self->{orts}[$orts_num]{$org_name} };
}
sub has_at_least_one_ort {
my $self = shift;
my ($gene_name, $orgs_list) = @_;
if (defined $orgs_list) {
my @orgs = split ":", $orgs_list;
foreach my $curr_org (@orgs) {
return 1 if $self->get_orts( $gene_name, $curr_org ) ne '';
}
} else {
foreach my $curr_org ( $self->get_orgs() ) {
return 1 if $self->get_orts( $gene_name, $curr_org ) ne '';
}
}
return 0;
}
return 1;
| rhysf/Synima | modules/Ort.pm | Perl | mit | 14,932 |
=head1 NAME
SGN::Controller::AJAX::Search::GenotypingProtocol - a REST controller class to provide genotyping protocol search
=head1 DESCRIPTION
=head1 AUTHOR
=cut
package SGN::Controller::AJAX::Search::GenotypingProtocol;
use Moose;
use Data::Dumper;
use CXGN::People::Login;
use CXGN::Genotype::Protocol;
use CXGN::Genotype::MarkersSearch;
use JSON;
BEGIN { extends 'Catalyst::Controller::REST' }
__PACKAGE__->config(
default => 'application/json',
stash_key => 'rest',
map => { 'application/json' => 'JSON' },
);
sub genotyping_protocol_search : Path('/ajax/genotyping_protocol/search') : ActionClass('REST') { }
sub genotyping_protocol_search_GET : Args(0) {
my $self = shift;
my $c = shift;
my $bcs_schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
my @protocol_list = $c->req->param('protocol_ids') ? split ',', $c->req->param('protocol_ids') : ();
my @accession_list = $c->req->param('accession_ids') ? split ',', $c->req->param('accession_ids') : ();
my @tissue_sample_list = $c->req->param('tissue_sample_ids') ? split ',', $c->req->param('tissue_sample_ids') : ();
my @genotyping_data_project_list = $c->req->param('genotyping_data_project_ids') ? split ',', $c->req->param('genotyping_data_project_ids') : ();
my $limit;
my $offset;
my $protocol_search_result;
if (scalar(@protocol_list)>0 || scalar(@accession_list)>0 || scalar(@tissue_sample_list)>0 || scalar(@genotyping_data_project_list)>0) {
$protocol_search_result = CXGN::Genotype::Protocol::list($bcs_schema, \@protocol_list, \@accession_list, \@tissue_sample_list, $limit, $offset, \@genotyping_data_project_list);
} else {
$protocol_search_result = CXGN::Genotype::Protocol::list_simple($bcs_schema);
}
my @result;
foreach (@$protocol_search_result){
my $num_markers = $_->{marker_count};
my @trimmed;
my $header_line_count = 0;
foreach (@{$_->{header_information_lines}}){
if ($header_line_count < 10) {
$_ =~ tr/<>//d;
push @trimmed, $_;
}
else {
push @trimmed, "### ----- SHOWING FIRST 10 LINES ONLY ----- ###";
last;
}
$header_line_count++;
}
my $description = join '<br/>', @trimmed;
$description = $description ? $description : 'NA';
push @result,
[
"<a href=\"/breeders_toolbox/protocol/$_->{protocol_id}\">$_->{protocol_name}</a>",
$_->{marker_type},
$description,
$num_markers,
$_->{protocol_description},
$_->{reference_genome_name},
$_->{species_name},
$_->{sample_observation_unit_type_name},
$_->{create_date}
];
}
#print STDERR "PROTOCOL LIST =".Dumper \@result."\n";
$c->stash->{rest} = { data => \@result };
}
sub genotyping_protocol_markers_search : Path('/ajax/genotyping_protocol/markers_search') : ActionClass('REST') { }
sub genotyping_protocol_markers_search_GET : Args(0) {
my $self = shift;
my $c = shift;
my $bcs_schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
my $params = $c->req->params() || {};
my $protocol_id = $params->{protocol_id};
my @marker_names = $params->{marker_names} ? split ',', $params->{marker_names} : ();
my $rows = $params->{length};
my $offset = $params->{start};
my $limit = defined($offset) && defined($rows) ? ($offset+$rows)-1 : undef;
my @result;
my $marker_search = CXGN::Genotype::MarkersSearch->new({
bcs_schema => $bcs_schema,
protocol_id_list => [$protocol_id],
#protocol_name_list => \@protocol_name_list,
marker_name_list => \@marker_names,
#protocolprop_marker_hash_select=>['name', 'chrom', 'pos', 'alt', 'ref'] Use default which is all marker info
limit => $limit,
offset => $offset
});
my ($search_result, $total_count) = $marker_search->search();
foreach (@$search_result) {
push @result, [
$_->{marker_name},
$_->{chrom},
$_->{pos},
$_->{alt},
$_->{ref},
$_->{qual},
$_->{filter},
$_->{info},
$_->{format}
];
}
$c->stash->{rest} = { data => \@result, recordsTotal => $total_count, recordsFiltered => $total_count };
}
sub genotyping_protocol_pcr_markers : Path('/ajax/genotyping_protocol/pcr_markers') : ActionClass('REST') { }
sub genotyping_protocol_pcr_markers_GET : Args(0) {
my $self = shift;
my $c = shift;
my $schema = $c->dbic_schema('Bio::Chado::Schema', 'sgn_chado');
my $protocol_id = $c->req->param('protocol_id');
my $pcr_marker_details_cvterm_id = SGN::Model::Cvterm->get_cvterm_row($schema, 'pcr_marker_details', 'protocol_property')->cvterm_id();
my $q = "SELECT nd_protocolprop.value FROM nd_protocolprop WHERE nd_protocolprop.type_id = ? AND nd_protocolprop.nd_protocol_id = ?";
my $h = $schema->storage->dbh()->prepare($q);
$h->execute($pcr_marker_details_cvterm_id, $protocol_id);
my @info = $h->fetchrow_array();
my $protocol_info_string = $info[0];
my $protocol_info_ref = decode_json $protocol_info_string;
my $marker_details_ref = $protocol_info_ref->{marker_details};
my %marker_details = %{$marker_details_ref};
my @results;
foreach my $marker_name (keys %marker_details) {
my $product_sizes = $marker_details{$marker_name}{'product_sizes'};
my $forward_primer = $marker_details{$marker_name}{'forward_primer'};
my $reverse_primer = $marker_details{$marker_name}{'reverse_primer'};
my $annealing_temperature = $marker_details{$marker_name}{'annealing_temperature'};
my $sequence_motif = $marker_details{$marker_name}{'sequence_motif'};
my $sequence_source = $marker_details{$marker_name}{'sequence_source'};
my $linkage_group = $marker_details{$marker_name}{'linkage_group'};
push @results, [$marker_name, $product_sizes, $forward_primer, $reverse_primer, $annealing_temperature, $sequence_motif, $sequence_source, $linkage_group];
}
print STDERR "MARKER INFO =".Dumper(\@results)."\n";
$c->stash->{rest} = {data => \@results};
}
1;
| solgenomics/sgn | lib/SGN/Controller/AJAX/Search/GenotypingProtocol.pm | Perl | mit | 6,357 |
#!/usr/bin/perl
use strict;
use NF2::RegressLib;
use NF2::PacketLib;
use RegressRouterLib;
use reg_defines_reference_router;
my @interfaces = ("nf2c0", "nf2c1", "nf2c2", "nf2c3", "eth1", "eth2");
nftest_init(\@ARGV,\@interfaces,);
nftest_start(\@interfaces);
my $routerMAC0 = "00:ca:fe:00:00:01";
my $routerMAC1 = "00:ca:fe:00:00:02";
my $routerMAC2 = "00:ca:fe:00:00:03";
my $routerMAC3 = "00:ca:fe:00:00:04";
my $routerIP0 = "192.168.0.40";
my $routerIP1 = "192.168.1.40";
my $routerIP2 = "192.168.2.40";
my $routerIP3 = "192.168.3.40";
# clear LPM table
for (my $i = 0; $i < 32; $i++)
{
nftest_invalidate_LPM_table_entry('nf2c0', $i);
}
# clear ARP table
for (my $i = 0; $i < 32; $i++)
{
nftest_invalidate_ARP_table_entry('nf2c0', $i);
}
# Write the mac and IP addresses
nftest_add_dst_ip_filter_entry ('nf2c0', 0, $routerIP0);
nftest_add_dst_ip_filter_entry ('nf2c1', 1, $routerIP1);
nftest_add_dst_ip_filter_entry ('nf2c2', 2, $routerIP2);
nftest_add_dst_ip_filter_entry ('nf2c3', 3, $routerIP3);
nftest_set_router_MAC ('nf2c0', $routerMAC0);
nftest_set_router_MAC ('nf2c1', $routerMAC1);
nftest_set_router_MAC ('nf2c2', $routerMAC2);
nftest_set_router_MAC ('nf2c3', $routerMAC3);
# add an entry in the routing table:
my $index = 0;
my $subnetIP = "192.168.1.0";
my $subnetIP2 = "192.168.1.1";
my $subnetMask = "255.255.255.0";
my $subnetMask2 = "255.255.255.225";
my $nextHopIP = "192.168.1.54";
my $nextHopIP2 = "0.0.0.0";
my $outPort = 0x1; # output on MAC0
my $outPort2 = 0x4;
my $nextHopMAC = "dd:55:dd:66:dd:77";
nftest_add_LPM_table_entry ('nf2c0',
1,
$subnetIP,
$subnetMask,
$nextHopIP,
$outPort);
nftest_add_LPM_table_entry ('nf2c0',
0,
$subnetIP2,
$subnetMask2,
$nextHopIP2,
$outPort2);
# add an entry in the ARP table
nftest_add_ARP_table_entry('nf2c0',
$index,
$nextHopIP,
$nextHopMAC);
# add an entry in the ARP table
nftest_add_ARP_table_entry('nf2c0',
1,
$subnetIP2,
$nextHopMAC);
my $total_errors = 0;
# loop for 100 packets sending LPM miss packet
for (my $i = 0; $i < 100; $i++)
{
# set parameters
my $DA = $routerMAC0;
my $SA = "aa:bb:cc:dd:ee:ff";
my $TTL = 64;
my $DST_IP = "192.168.1.1";
my $SRC_IP = "192.168.0.1";
my $len = 100;
my $nextHopMAC = "dd:55:dd:66:dd:77";
# create mac header
my $MAC_hdr = NF2::Ethernet_hdr->new(DA => $DA,
SA => $SA,
Ethertype => 0x800
);
#create IP header
my $IP_hdr = NF2::IP_hdr->new(ttl => $TTL,
src_ip => $SRC_IP,
dst_ip => $DST_IP
);
$IP_hdr->checksum(0); # make sure its zero before we calculate it.
$IP_hdr->checksum($IP_hdr->calc_checksum);
# create packet filling.... (IP PDU)
my $PDU = NF2::PDU->new($len - $MAC_hdr->length_in_bytes() - $IP_hdr->length_in_bytes() );
my $start_val = $MAC_hdr->length_in_bytes() + $IP_hdr->length_in_bytes()+1;
my @data = ($start_val..$len);
for (@data) {$_ %= 100}
$PDU->set_bytes(@data);
# get packed packet string
my $sent_pkt = $MAC_hdr->packed . $IP_hdr->packed . $PDU->packed;
# create the expected packet
my $MAC_hdr2 = NF2::Ethernet_hdr->new(DA => $nextHopMAC,
SA => $routerMAC1,
Ethertype => 0x800
);
$IP_hdr->ttl($TTL-1);
$IP_hdr->checksum(0); # make sure its zero before we calculate it.
$IP_hdr->checksum($IP_hdr->calc_checksum);
my $expected_pkt = $MAC_hdr2->packed . $IP_hdr->packed . $PDU->packed;
# send packet out of eth1->nf2c0
nftest_send('eth1', $sent_pkt);
nftest_expect('eth2', $expected_pkt);
}
sleep 1;
my $unmatched_hoh = nftest_finish();
$total_errors += nftest_print_errors($unmatched_hoh);
if ($total_errors==0) {
print "SUCCESS!\n";
exit 0;
}
else {
print "FAIL: $total_errors errors\n";
exit 1;
}
| shkkgs/DE4-multicore-network-processor-with-multiple-hardware-monitors- | DE4_network_processor_4cores_6monitors_release/projects/DE4_Reference_Router_with_DMA/src/sources_ngnp_multicore/to_send/ngnp_added_monitor/ngnp/regress/test_lpm_next_hop/lpm_next_hop.pl | Perl | mit | 3,807 |
#/usr/bin/perl -w
# This script compares matrixes of contacts to check how similar the structures
# are. It compares all pairs from 1 to 8
my $Dir = "contacts";
for (my $i=1;$i<=8;$i++){
for (my $j=1;$j<8;$j++){
my $tot=0;
my $diff=0;
my $file1 = sprintf("${Dir}/res000%i.matrix",$i);
my $file2 = sprintf("${Dir}/res000%i.matrix",$j);
# printf "%i vs %i ",$i,$j;
# print "$file1 $file2\n";
open (FILE1,$file1) || die "Could not open $file1";
open (FILE2,$file2) || die "Could not open $file2";
while (my $line1 = <FILE1>){
my $line2 = <FILE2>;
chomp $line1;
chomp $line2;
for (0..length($line1)){
if (substr($line1, $_, 1) eq 1){
$tot++;
if (substr($line2, $_, 1) eq 0){
$diff++;
}
}
}
}
close FILE1 || die "Could not close $file1";
close FILE2 || die "Could not close $file2";
#printf ("%i %i %.3f\n",$tot-$diff, $tot, 1-$diff/$tot);
printf ("%i ",($tot-$diff-64)/2);
}
print "\n";
}
exit;
| insectopalo/snake-puzzle | lib/diff.pl | Perl | mit | 1,115 |
package Statistics::Basic::Vector;
use strict;
use warnings;
use Carp;
use Scalar::Util qw(blessed weaken looks_like_number);
our $tag_number = 0;
use Statistics::Basic;
use overload
'0+' => sub { croak "attempt to use vector as scalar numerical value" },
'""' => sub {
my $this = $_[0];
local $" = ", ";
my @r = map { defined $_ ? $Statistics::Basic::fmt->format_number($_, $Statistics::Basic::IPRES) : "_" } $this->query;
$Statistics::Basic::DEBUG ? "vector-$this->{tag}:[@r]" : "[@r]";
},
'bool' => sub { 1 },
fallback => 1; # tries to do what it would have done if this wasn't present.
# new {{{
sub new {
my $class = shift;
my $vector = $_[0];
if( blessed($vector) and $vector->isa(__PACKAGE__) ) {
warn "vector->new called with blessed argument, returning $vector instead of making another\n" if $Statistics::Basic::DEBUG >= 3;
return $vector;
}
my $this = bless {tag=>(++$tag_number), s=>0, c=>{}, v=>[]}, $class;
$this->set_vector( @_ );
warn "created new vector $this\n" if $Statistics::Basic::DEBUG >= 3;
return $this;
}
# }}}
# copy {{{
sub copy {
my $this = shift;
my $that = __PACKAGE__->new( [@{$this->{v}}] );
warn "copied vector($this -> $that)\n" if $Statistics::Basic::DEBUG >= 3;
return $that;
}
# }}}
# _set_computer {{{
sub _set_computer {
my $this = shift;
while( my ($k,$v) = splice @_, 0, 2 ) {
warn "$this set_computer($k => " . overload::StrVal($v) . ")\n" if $Statistics::Basic::DEBUG;
weaken($this->{c}{$k} = $v);
$v->_recalc_needed;
}
return;
}
# }}}
# _set_linked_computer {{{
sub _set_linked_computer {
my $this = shift;
my $key = shift;
my $var = shift;
my $new_key = join("_", ($key, sort {$a<=>$b} map {$_->{tag}} @_));
$this->_set_computer( $new_key => $var );
return;
}
# }}}
# _get_computer {{{
sub _get_computer {
my $this = shift;
my $k = shift;
warn "$this get_computer($k): " . overload::StrVal($this->{c}{$k}||"<undef>") . "\n" if $Statistics::Basic::DEBUG;
return $this->{c}{$k};
}
# }}}
# _get_linked_computer {{{
sub _get_linked_computer {
my $this = shift;
my $key = shift;
my $new_key = join("_", ($key, sort {$a<=>$b} map {$_->{tag}} @_));
return $this->_get_computer( $new_key );
}
# }}}
# _inform_computers_of_change {{{
sub _inform_computers_of_change {
my $this = shift;
for my $k (keys %{ $this->{c} }) {
my $v = $this->{c}{$k};
if( defined($v) and blessed($v) ) {
$v->_recalc_needed;
} else {
delete $this->{c}{$k};
}
}
return;
}
# }}}
# _fix_size {{{
sub _fix_size {
my $this = shift;
my $fixed = 0;
my $d = @{$this->{v}} - $this->{s};
if( $d > 0 ) {
splice @{$this->{v}}, 0, $d;
$fixed = 1;
}
unless( $Statistics::Basic::NOFILL ) {
if( $d < 0 ) {
unshift @{$this->{v}}, # unshift so the 0s leave first
map {0} $d .. -1; # add $d of them
$fixed = 1;
}
}
warn "[fix_size $this] [@{ $this->{v} }]\n" if $Statistics::Basic::DEBUG >= 2;
return $fixed;
}
# }}}
# query {{{
sub query {
my $this = shift;
return (wantarray ? @{$this->{v}} : $this->{v});
}
# }}}
# query_filled {{{
sub query_filled {
my $this = shift;
warn "[query_filled $this $this->{s}]\n" if $Statistics::Basic::DEBUG >= 1;
return if @{$this->{v}} < $this->{s};
return 1;
}
# }}}
# insert {{{
sub insert {
my $this = shift;
croak "you must define a vector size before using insert()" unless defined $this->{s};
for my $e (@_) {
if( ref($e) and not blessed($e) ) {
if( ref($e) eq "ARRAY" ) {
push @{ $this->{v} }, @$e;
warn "[insert $this] @$e\n" if $Statistics::Basic::DEBUG >= 1;
} else {
croak "insert() elements do not make sense";
}
} else {
push @{ $this->{v} }, $e;
warn "[insert $this] $e\n" if $Statistics::Basic::DEBUG >= 1;
}
}
$this->_fix_size;
$this->_inform_computers_of_change;
return $this;
}
# }}}
# ginsert {{{
sub ginsert {
my $this = shift;
for my $e (@_) {
if( ref($e) and not blessed($e)) {
if( ref($e) eq "ARRAY" ) {
push @{ $this->{v} }, @$e;
warn "[ginsert $this] @$e\n" if $Statistics::Basic::DEBUG >= 1;
} else {
croak "insert() elements do not make sense";
}
} else {
push @{ $this->{v} }, $e;
warn "[ginsert $this] $e\n" if $Statistics::Basic::DEBUG >= 1;
}
}
$this->{s} = @{$this->{v}} if @{$this->{v}} > $this->{s};
$this->_inform_computers_of_change;
return $this;
}
*append = \&ginsert;
# }}}
# query_size {{{
sub query_size {
my $this = shift;
return scalar @{$this->{v}};
}
# maybe deprecate this later
*size = \&query_size unless $ENV{TEST_AUTHOR};
# }}}
# set_size {{{
sub set_size {
my $this = shift;
my $size = shift;
croak "invalid vector size ($size)" if $size < 0;
if( $this->{s} != $size ) {
$this->{s} = $size;
$this->_fix_size;
$this->_inform_computers_of_change;
}
return $this;
}
# }}}
# set_vector {{{
sub set_vector {
my $this = shift;
my $vector = $_[0];
if( ref($vector) eq "ARRAY" ) {
@{$this->{v}} = @$vector;
$this->{s} = int @$vector;
$this->_inform_computers_of_change;
} elsif( UNIVERSAL::isa($vector, "Statistics::Basic::ComputedVector") ) {
$this->set_vector($vector->{input_vector});
} elsif( UNIVERSAL::isa($vector, "Statistics::Basic::Vector") ) {
$this->{s} = $vector->{s};
@{$this->{v}} = @{$vector->{v}}; # copy the vector
# I don't think this is the behavior that we really want, since they
# stay separate objects, they shouldn't be linked like this.
# $this->{s} = $vector->{s};
# $this->{v} = $vector->{v}; # this links the vectors together
# $this->{c} = $vector->{c}; # so we should link their computers too
} elsif( @_ ) {
@{$this->{v}} = @_;
$this->{s} = int @_;
} elsif( defined $vector ) {
croak "argument to set_vector() too strange";
}
warn "[set_vector $this] [@{ $this->{v} }]\n" if $Statistics::Basic::DEBUG >= 2 and ref($this->{v});
return $this;
}
# }}}
1;
| ppapasaikas/SANJUAN | perllib/Statistics/Basic/Vector.pm | Perl | mit | 6,574 |
package GD::Barcode::EAN8;
use strict;
BEGIN { eval{require 'GD.pm';}; };
use GD::Barcode;
require Exporter;
use vars qw($VERSION @ISA $errStr);
@ISA = qw(GD::Barcode Exporter);
$VERSION=1.10;
my $leftOddBar ={
'0' => '0001101',
'1' => '0011001',
'2' => '0010011',
'3' => '0111101',
'4' => '0100011',
'5' => '0110001',
'6' => '0101111',
'7' => '0111011',
'8' => '0110111',
'9' => '0001011'
};
my $rightBar = {
'0' => '1110010',
'1' => '1100110',
'2' => '1101100',
'3' => '1000010',
'4' => '1011100',
'5' => '1001110',
'6' => '1010000',
'7' => '1000100',
'8' => '1001000',
'9' => '1110100'
};
my $guardBar = 'G0G';
my $centerBar = '0G0G0';
#------------------------------------------------------------------------------
# new (for GD::Barcode::EAN8)
#------------------------------------------------------------------------------
sub new($$) {
my($sClass, $sTxt) = @_;
$errStr ='';
my $oThis = {};
bless $oThis;
return undef if($errStr = $oThis->init($sTxt));
return $oThis;
}
#------------------------------------------------------------------------------
# init (for GD::Barcode::EAN8)
#------------------------------------------------------------------------------
sub init($$){
my($oThis, $sTxt) =@_;
#Check
return 'Invalid Characters' if($sTxt =~ /[^0-9]/);
#CalcCd
if( length($sTxt) == 7 ) {
$sTxt .= calcEAN8CD( $sTxt ) ;
}
elsif(length($sTxt) == 8) {
;
}
else {
return 'Invalid Length';
}
$oThis->{text} = $sTxt;
return '';
}
#------------------------------------------------------------------------------
# calcEAN8CD (for GD::Barcode::EAN8)
#------------------------------------------------------------------------------
sub calcEAN8CD($) {
my( $sTxt ) = @_;
my( $i, $iSum);
my @aWeight = (3, 1, 3, 1, 3, 1, 3);
$iSum = 0;
for( $i = 0; $i < 7; $i++ ){
$iSum += substr($sTxt, $i, 1) * $aWeight[$i];
}
$iSum %= 10;
$iSum = ($iSum == 0)? 0: (10 - $iSum);
return "$iSum";
}
#------------------------------------------------------------------------------
# new (for GD::Barcode::EAN8)
#------------------------------------------------------------------------------
sub barcode($) {
my ($oThis) = @_;
my($i, $sRes);
#(1) Init
my $sTxt = $oThis->{text};
$sRes = $guardBar; #GUARD
#(2) Left 4
for( $i = 0; $i < 4; $i++ ) {
$sRes .= GD::Barcode::barPtn( substr($sTxt, $i, 1), $leftOddBar );
}
#(3) Center
$sRes .= $centerBar;
#(4) Right 4 bytes
for( $i = 4; $i < 8; $i++ ) {
$sRes .= GD::Barcode::barPtn( substr($sTxt, $i, 1), $rightBar );
}
#(5)GUARD
$sRes .= $guardBar;
return $sRes;
}
#------------------------------------------------------------------------------
# plot (for GD::Barcode::EAN8)
#------------------------------------------------------------------------------
sub plot($;%) {
my($oThis, %hParam) =@_;
my $sPtn = $oThis->barcode();
#Create Image
my $iHeight = ($hParam{Height})? $hParam{Height} : 50;
my($oGd, $cBlack);
if($hParam{NoText}) {
($oGd, $cBlack) = GD::Barcode::plot($sPtn, length($sPtn), $iHeight, 0, 0);
}
else {
my($fW,$fH) = (GD::Font->Small->width,GD::Font->Small->height);
my $iWidth = length($sPtn);
#$ ($oGd, $cBlack) = GD::Barcode::plot($sPtn, $iWidth, $iHeight, $fH, $fW+1);
($oGd, $cBlack) = GD::Barcode::plot($sPtn, $iWidth, $iHeight, $fH, 0);
$oGd->string(GD::Font->Small, $fW + 1, $iHeight - $fH, substr($oThis->{text}, 0, 4), $cBlack);
$oGd->string(GD::Font->Small, $fW + 33, $iHeight - $fH, substr($oThis->{text}, 4, 4), $cBlack);
}
return $oGd;
}
1;
__END__
=head1 NAME
GD::Barcode::EAN8 - Create EAN8(JAN8) barcode image with GD
=head1 SYNOPSIS
I<ex. CGI>
use GD::Barcode::EAN8;
binmode(STDOUT);
print "Content-Type: image/png\n\n";
print GD::Barcode::EAN8->new('1234567')->plot->png;
I<with Error Check>
my $oGdBar = GD::Barcode::EAN8->new('123456789');
die $GD::Barcode::EAN8::errStr unless($oGdBar); #Invalid Length
=head1 DESCRIPTION
GD::Barcode::EAN8 is a subclass of GD::Barcode and allows you to
create EAN8(JAN8) barcode image with GD.
This module based on "Generate Barcode Ver 1.02 By Shisei Hanai 97/08/22".
=head2 new
I<$oGdBar> = GD::Barcode::EAN8->new(I<$sTxt>);
Constructor.
Creates a GD::Barcode::EAN8 object for I<$sTxt>.
I<$sTxt> has 7 or 8 numeric characters([0-9]).
If I<$sTxt> has 12 characters, this module calacurates CD for you.
=head2 plot()
I<$oGd> = $oGdBar->plot([Height => I<$iHeight>, NoText => I<0 | 1>]);
creates GD object with barcode image for the I<$sTxt> specified at L<new> method.
I<$iHeight> is height of the image. If I<NoText> is 1, the image has no text image of I<$sTxt>.
ex.
my $oGdB = GD::Barcode::EAN8->new('1234567');
my $oGD = $oGdB->plot(NoText=>1, Height => 20);
# $sGD is a GD image with Height=>20 pixels, with no text.
=head2 barcode()
I<$sPtn> = $oGdBar->barcode();
returns a barcode pattern in string with '1', 'G' and '0'.
'1' means black, 'G' also means black but little bit long,
'0' means white.
ex.
my $oGdB = GD::Barcode::EAN8->new('1234567');
my $sPtn = $oGdB->barcode();
# $sPtn = '';
=head2 $errStr
$GD::Barcode::EAN8::errStr
has error message.
=head2 $text
$oGdBar->{$text}
has barcode text based on I<$sTxt> specified in L<new> method.
=head1 AUTHOR
Kawai Takanori GCD00051@nifty.ne.jp
=head1 COPYRIGHT
The GD::Barocde::EAN8 module is Copyright (c) 2000 Kawai Takanori. Japan.
All rights reserved.
You may distribute under the terms of either the GNU General Public
License or the Artistic License, as specified in the Perl README file.
=head1 SEE ALSO
GD::Barcode
=cut
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/GD/Barcode/EAN8.pm | Perl | mit | 5,762 |
/* Facts */
status(sam, freshman).
status(jack, sophomore).
topic(sam, bio).
topic(sam, eng).
topic(jack, mat).
topic(jack, cse).
class(mat, calculus).
class(mat, algebra).
class(cse, algorithms).
class(cse, databases).
class(bio, taxonomy).
class(bio, evolution).
class(eng, reading).
class(eng, writing).
/* Rule */
/* Question 3.2 */
info(X,Y):-
status(X,Y); topic(X,Y).
/* Question 3.3 */
schedule(X,Y):-
topic(X,Z), class(Z,Y).
| uzeio/CSE240 | 13 (Prolog:scheme)/students.pl | Perl | mit | 448 |
use CGI;
$q = CGI -> new;
print $q->redirect("index.cgi"); | fortesit/online-photo-album | Perl CGI version/index.pl | Perl | mit | 59 |
=head1 LICENSE
Copyright (c) 1999-2011 The European Bioinformatics Institute and
Genome Research Limited. All rights reserved.
This software is distributed under a modified Apache license.
For license details, please see
http://www.ensembl.org/info/about/code_licence.html
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <dev@ensembl.org>.
Questions may also be sent to the Ensembl help desk at
<helpdesk@ensembl.org>.
=cut
=head1 NAME
Bio::EnsEMBL::DBSQL::CoordSystemAdaptor
=head1 SYNOPSIS
use Bio::EnsEMBL::Registry;
Bio::EnsEMBL::Registry->load_registry_from_db(
-host => 'ensembldb.ensembl.org',
-user => 'anonymous'
);
$csa = Bio::EnsEMBL::Registry->get_adaptor( "human", "core",
"coordsystem" );
#
# Get all coord systems in the database:
#
foreach my $cs ( @{ $csa->fetch_all() } ) {
print $cs->name, ' ', $cs->version, "\n";
}
#
# Fetching by name:
#
# use the default version of coord_system 'chromosome' (e.g. NCBI33):
$cs = $csa->fetch_by_name('chromosome');
# get an explicit version of coord_system 'chromosome':
$cs = $csa->fetch_by_name( 'chromsome', 'NCBI34' );
# get all coord_systems of name 'chromosome':
foreach $cs ( @{ $csa->fetch_all_by_name('chromosome') } ) {
print $cs->name, ' ', $cs->version, "\n";
}
#
# Fetching by rank:
#
$cs = $csa->fetch_by_rank(2);
#
# Fetching the pseudo coord system 'toplevel'
#
# Get the default top_level coord system:
$cs = $csa->fetch_top_level();
# can also use an alias in fetch_by_name:
$cs = $csa->fetch_by_name('toplevel');
# can also request toplevel using rank=0
$cs = $csa->fetch_by_rank(0);
#
# Fetching by sequence level:
#
# Get the coord system which is used to store sequence:
$cs = $csa->fetch_sequence_level();
# can also use an alias in fetch_by_name:
$cs = $csa->fetch_by_name('seqlevel');
#
# Fetching by id
#
$cs = $csa->fetch_by_dbID(1);
=head1 DESCRIPTION
This adaptor allows the querying of information from the coordinate
system adaptor.
Note that many coordinate systems do not have a concept of a version
for the entire coordinate system (though they may have a per-sequence
version). The 'chromosome' coordinate system usually has a version
(i.e. the assembly version) but the clonal coordinate system does not
(despite having individual sequence versions). In the case where a
coordinate system does not have a version an empty string ('') is used
instead.
=head1 METHODS
=cut
package Bio::EnsEMBL::DBSQL::CoordSystemAdaptor;
use strict;
use warnings;
use Bio::EnsEMBL::DBSQL::BaseAdaptor;
use Bio::EnsEMBL::Utils::Exception qw(throw warning deprecate);
use Bio::EnsEMBL::CoordSystem;
use vars qw(@ISA);
@ISA = qw(Bio::EnsEMBL::DBSQL::BaseAdaptor);
=head2 new
Arg [1] : See BaseAdaptor for arguments (none specific to this
subclass)
Example : $cs = $db->get_CoordSystemAdaptor(); #better than new()
Description: Creates a new CoordSystem adaptor and caches the contents
of the coord_system table in memory.
Returntype : Bio::EnsEMBL::DBSQL::CoordSystemAdaptor
Exceptions : none
Caller :
Status : Stable
=cut
sub new {
my ( $proto, @args ) = @_;
my $class = ref($proto) || $proto;
my $self = $class->SUPER::new(@args);
#
# Cache the entire contents of the coord_system table cross-referenced
# by dbID and name.
#
# keyed on name, list of coord_system value
$self->{'_name_cache'} = {};
# keyed on id, coord_system value
$self->{'_dbID_cache'} = {};
# keyed on rank
$self->{'_rank_cache'} = {};
# keyed on id, 1/undef values
$self->{'_is_sequence_level'} = {};
$self->{'_is_default_version'} = {};
#cache to store the seq_region_mapping information
#from internal->external
$self->{'_internal_seq_region_mapping'} = {};
#from external->internal
$self->{'_external_seq_region_mapping'} = {};
my $sth = $self->prepare(
'SELECT coord_system_id, name, rank, version, attrib '
. 'FROM coord_system '
. 'WHERE species_id = ?' );
$sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
$sth->execute();
my ( $dbID, $name, $rank, $version, $attrib );
$sth->bind_columns( \( $dbID, $name, $rank, $version, $attrib ) );
while ( $sth->fetch() ) {
my $seq_lvl = 0;
my $default = 0;
if ( defined($attrib) ) {
foreach my $attrib ( split( ',', $attrib ) ) {
$self->{"_is_$attrib"}->{$dbID} = 1;
if ( $attrib eq 'sequence_level' ) {
$seq_lvl = 1;
} elsif ( $attrib eq 'default_version' ) {
$default = 1;
}
}
}
my $cs =
Bio::EnsEMBL::CoordSystem->new( -DBID => $dbID,
-ADAPTOR => $self,
-NAME => $name,
-VERSION => $version,
-RANK => $rank,
-SEQUENCE_LEVEL => $seq_lvl,
-DEFAULT => $default );
$self->{'_dbID_cache'}->{$dbID} = $cs;
$self->{'_name_cache'}->{ lc($name) } ||= [];
$self->{'_rank_cache'}->{$rank} = $cs;
push @{ $self->{'_name_cache'}->{ lc($name) } }, $cs;
} ## end while ( $sth->fetch() )
$sth->finish();
$self->_cache_mapping_paths();
$self->_cache_seq_region_mapping();
return $self;
} ## end sub new
sub _cache_seq_region_mapping {
#
# This cache will load the information from the seq_region_table, if
# any, to allow mapping between internal and external seq_region_id.
#
my ($self) = @_;
# For a given core database, will return the schema_build information.
my $schema_build = $self->db->_get_schema_build();
# Prepare the query to get relation for the current database being
# used.
my $sql = qq(
SELECT s.internal_seq_region_id,
s.external_seq_region_id
FROM seq_region_mapping s,
mapping_set ms,
seq_region sr,
coord_system cs
WHERE ms.mapping_set_id = s.mapping_set_id
AND ms.schema_build = ?
AND s.internal_seq_region_id = sr.seq_region_id
AND sr.coord_system_id = cs.coord_system_id
AND cs.species_id = ?);
my $sth = $self->prepare($sql);
$sth->bind_param( 1, $schema_build, SQL_VARCHAR );
$sth->bind_param( 2, $self->species_id(), SQL_INTEGER );
$sth->execute();
# Load the cache:
foreach my $row ( @{ $sth->fetchall_arrayref() } ) {
# internal->external
$self->{'_internal_seq_region_mapping'}->{ $row->[0] } = $row->[1];
# external->internal
$self->{'_external_seq_region_mapping'}->{ $row->[1] } = $row->[0];
}
$sth->finish();
} ## end sub _cache_seq_region_mapping
sub _cache_mapping_paths {
# Retrieve a list of available mappings from the meta table. This
# may eventually be moved a table of its own if this proves too
# cumbersome.
my ($self) = @_;
my %mapping_paths;
my $mc = $self->db()->get_MetaContainer();
MAP_PATH:
foreach
my $map_path ( @{ $mc->list_value_by_key('assembly.mapping') } )
{
my @cs_strings = split( /[|#]/, $map_path );
if ( scalar(@cs_strings) < 2 ) {
warning( "Incorrectly formatted assembly.mapping value in meta "
. "table: $map_path" );
next MAP_PATH;
}
my @coord_systems;
foreach my $cs_string (@cs_strings) {
my ( $name, $version ) = split( /:/, $cs_string );
my $cs = $self->fetch_by_name( $name, $version );
if ( !defined($cs) ) {
warning( "Unknown coordinate system specified in meta table "
. " assembly.mapping:\n $name:$version" );
next MAP_PATH;
}
push( @coord_systems, $cs );
}
# If the delimiter is a '#' we want a special case, multiple parts
# of the same component map to the same assembly part. As this
# looks like the "long" mapping, we just make the path a bit longer
# :-)
if ( index( $map_path, '#' ) != -1 && scalar(@coord_systems) == 2 )
{
splice( @coord_systems, 1, 0, (undef) );
}
my $cs1 = $coord_systems[0];
my $cs2 = $coord_systems[$#coord_systems];
my $key1 = $cs1->name() . ':' . $cs1->version();
my $key2 = $cs2->name() . ':' . $cs2->version();
if ( exists( $mapping_paths{"$key1|$key2"} ) ) {
warning( "Meta table specifies multiple mapping paths between "
. "coord systems $key1 and $key2.\n"
. "Choosing shorter path arbitrarily." );
if ( scalar( @{ $mapping_paths{"$key1|$key2"} } ) <
scalar(@coord_systems) )
{
next MAP_PATH;
}
}
$mapping_paths{"$key1|$key2"} = \@coord_systems;
} ## end foreach my $map_path ( @{ $mc...
# Create the pseudo coord system 'toplevel' and cache it so that only
# one of these is created for each database.
my $toplevel =
Bio::EnsEMBL::CoordSystem->new( -TOP_LEVEL => 1,
-NAME => 'toplevel',
-ADAPTOR => $self );
$self->{'_top_level'} = $toplevel;
$self->{'_mapping_paths'} = \%mapping_paths;
return 1;
} ## end sub _cache_mapping_paths
=head2 fetch_all
Arg [1] : none
Example : foreach my $cs (@{$csa->fetch_all()}) {
print $cs->name(), ' ', $cs->version(), "\n";
}
Description: Retrieves every coordinate system defined in the DB.
These will be returned in ascending order of rank. I.e.
The highest coordinate system with rank=1 would be first in the
array.
Returntype : listref of Bio::EnsEMBL::CoordSystems
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_all {
my $self = shift;
my @coord_systems;
#order the array by rank in ascending order
foreach my $rank (sort {$a <=> $b} keys %{$self->{'_rank_cache'}}) {
push @coord_systems, $self->{'_rank_cache'}->{$rank};
}
return \@coord_systems;
}
=head2 fetch_by_rank
Arg [1] : int $rank
Example : my $cs = $coord_sys_adaptor->fetch_by_rank(1);
Description: Retrieves a CoordinateSystem via its rank. 0 is a special
rank reserved for the pseudo coordinate system 'toplevel'.
undef is returned if no coordinate system of the specified rank
exists.
Returntype : Bio::EnsEMBL::CoordSystem
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_by_rank {
my $self = shift;
my $rank = shift;
throw("Rank argument must be defined.") if(!defined($rank));
throw("Rank argument must be a non-negative integer.") if($rank !~ /^\d+$/);
if($rank == 0) {
return $self->fetch_top_level();
}
return $self->{'_rank_cache'}->{$rank};
}
=head2 fetch_by_name
Arg [1] : string $name
The name of the coordinate system to retrieve. Alternatively
this may be an alias for a real coordinate system. Valid
aliases are 'toplevel' and 'seqlevel'.
Arg [2] : string $version (optional)
The version of the coordinate system to retrieve. If not
specified the default version will be used.
Example : $coord_sys = $csa->fetch_by_name('clone');
$coord_sys = $csa->fetch_by_name('chromosome', 'NCBI33');
# toplevel is an pseudo coord system representing the highest
# coord system in a given region
# such as the chromosome coordinate system
$coord_sys = $csa->fetch_by_name('toplevel');
#seqlevel is an alias for the sequence level coordinate system
#such as the clone or contig coordinate system
$coord_sys = $csa->fetch_by_name('seqlevel');
Description: Retrieves a coordinate system by its name
Returntype : Bio::EnsEMBL::CoordSystem
Exceptions : throw if no name argument provided
warning if no version provided and default does not exist
Caller : general
Status : Stable
=cut
sub fetch_by_name {
my $self = shift;
my $name = lc(shift); #case insensitve matching
my $version = shift;
throw('Name argument is required.') if(!$name);
$version = lc($version) if($version);
if($name eq 'seqlevel') {
return $self->fetch_sequence_level();
} elsif($name eq 'toplevel') {
return $self->fetch_top_level($version);
}
if(!exists($self->{'_name_cache'}->{$name})) {
if($name =~ /top/) {
warning("Did you mean 'toplevel' coord system instead of '$name'?");
} elsif($name =~ /seq/) {
warning("Did you mean 'seqlevel' coord system instead of '$name'?");
}
return undef;
}
my @coord_systems = @{$self->{'_name_cache'}->{$name}};
foreach my $cs (@coord_systems) {
if($version) {
return $cs if(lc($cs->version()) eq $version);
} elsif($self->{'_is_default_version'}->{$cs->dbID()}) {
return $cs;
}
}
if($version) {
#the specific version we were looking for was not found
return undef;
}
#didn't find a default, just take first one
my $cs = shift @coord_systems;
my $v = $cs->version();
warning("No default version for coord_system [$name] exists. " .
"Using version [$v] arbitrarily");
return $cs;
}
=head2 fetch_all_by_name
Arg [1] : string $name
The name of the coordinate system to retrieve. This can be
the name of an actual coordinate system or an alias for a
coordinate system. Valid aliases are 'toplevel' and 'seqlevel'.
Example : foreach my $cs (@{$csa->fetch_all_by_name('chromosome')}){
print $cs->name(), ' ', $cs->version();
}
Description: Retrieves all coordinate systems of a particular name
Returntype : listref of Bio::EnsEMBL::CoordSystem objects
Exceptions : throw if no name argument provided
Caller : general
Status : Stable
=cut
sub fetch_all_by_name {
my $self = shift;
my $name = lc(shift); #case insensitive matching
throw('Name argument is required') if(!$name);
if($name eq 'seqlevel') {
return [$self->fetch_sequence_level()];
} elsif($name eq 'toplevel') {
return [$self->fetch_top_level()];
}
return $self->{'_name_cache'}->{$name} || [];
}
=head2 fetch_by_dbID
Arg [1] : int dbID
Example : $cs = $csa->fetch_by_dbID(4);
Description: Retrieves a coord_system via its internal
identifier, or undef if no coordinate system with the provided
id exists.
Returntype : Bio::EnsEMBL::CoordSystem or undef
Exceptions : thrown if no coord_system exists for specified dbID
Caller : general
Status : Stable
=cut
sub fetch_by_dbID {
my $self = shift;
my $dbID = shift;
throw('dbID argument is required') if(!$dbID);
my $cs = $self->{'_dbID_cache'}->{$dbID};
return undef if(!$cs);
return $cs;
}
=head2 fetch_top_level
Arg [1] : none
Example : $cs = $csa->fetch_top_level();
Description: Retrieves the toplevel pseudo coordinate system.
Returntype : a Bio::EnsEMBL::CoordSystem object
Exceptions : none
Caller : general
Status : Stable
=cut
sub fetch_top_level {
my $self = shift;
return $self->{'_top_level'};
}
=head2 fetch_sequence_level
Arg [1] : none
Example : ($id, $name, $version) = $csa->fetch_sequence_level();
Description: Retrieves the coordinate system at which sequence
is stored at.
Returntype : Bio::EnsEMBL::CoordSystem
Exceptions : throw if no sequence_level coord system exists at all
throw if multiple sequence_level coord systems exists
Caller : general
Status : Stable
=cut
sub fetch_sequence_level {
my $self = shift;
my @dbIDs = keys %{$self->{'_is_sequence_level'}};
throw('No sequence_level coord_system is defined') if(!@dbIDs);
if(@dbIDs > 1) {
throw('Multiple sequence_level coord_systems are defined.' .
'Only one is currently supported');
}
return $self->{'_dbID_cache'}->{$dbIDs[0]};
}
=head2 get_mapping_path
Arg [1] : Bio::EnsEMBL::CoordSystem $cs1
Arg [2] : Bio::EnsEMBL::CoordSystem $cs2
Example : foreach my $cs @{$csa->get_mapping_path($cs1,$cs2);
Description: Given two coordinate systems this will return a mapping path
between them if one has been defined. Allowed Mapping paths are
explicitly defined in the meta table. The following is an
example:
mysql> select * from meta where meta_key = 'assembly.mapping';
+---------+------------------+--------------------------------------+
| meta_id | meta_key | meta_value |
+---------+------------------+--------------------------------------+
| 20 | assembly.mapping | chromosome:NCBI34|contig |
| 21 | assembly.mapping | clone|contig |
| 22 | assembly.mapping | supercontig|contig |
| 23 | assembly.mapping | chromosome:NCBI34|contig|clone |
| 24 | assembly.mapping | chromosome:NCBI34|contig|supercontig |
| 25 | assembly.mapping | supercontig|contig|clone |
+---------+------------------+--------------------------------------+
For a one-step mapping path to be valid there needs to be
a relationship between the two coordinate systems defined in
the assembly table. Two step mapping paths work by building
on the one-step mapping paths which are already defined.
The first coordinate system in a one step mapping path must
be the assembled coordinate system and the second must be
the component.
Example of use:
my $cs1 = $cs_adaptor->fetch_by_name('contig');
my $cs2 = $cs_adaptor->fetch_by_name('chromosome');
my @path = @{$cs_adaptor->get_mapping_path($cs1,$cs2)};
if(!@path) {
print "No mapping path.";
}
elsif(@path == 2) {
print "2 step mapping path.";
print "Assembled = " . $path[0]->name() . "\n";
print "Component = " . $path[1]->name() . "\n";
} else {
print "Multi step mapping path\n";
}
Returntype : reference to a list of Bio::EnsEMBL::CoordSystem objects
Exceptions : none
Caller : general
Status : Stable
=cut
sub get_mapping_path {
my $self = shift;
my $cs1 = shift;
my $cs2 = shift;
if(!ref($cs1) || !ref($cs2) ||
!$cs1->isa('Bio::EnsEMBL::CoordSystem') ||
!$cs2->isa('Bio::EnsEMBL::CoordSystem')) {
throw('Two Bio::EnsEMBL::CoordSystem arguments expected.');
}
my $key1 = $cs1->name() . ":" . $cs1->version();
my $key2 = $cs2->name() . ":" . $cs2->version();
my $path = $self->{'_mapping_paths'}->{"$key1|$key2"};
return $path if($path);
$path = $self->{'_mapping_paths'}->{"$key2|$key1"};
if(!$path) {
# No path was explicitly defined, but we might be able to guess a
# suitable path. We only guess for missing 2 step paths.
my %mid1;
my %mid2;
foreach my $path (values(%{$self->{'_mapping_paths'}})) {
next if(@$path != 2);
my $match = undef;
if($path->[0]->equals($cs1)) {
$match = 1;
} elsif($path->[1]->equals($cs1)) {
$match = 0;
}
if(defined($match)) {
my $mid = $path->[$match];
my $midkey = $mid->name() . ':' . $mid->version();
# is the same cs mapped to by other cs?
if($mid2{$midkey}) {
my $path = [$cs1,$mid,$cs2];
$self->{'_mapping_paths'}->{"$key1|$key2"} = $path;
$key1 =~ s/\:$//;
$key2 =~ s/\:$//;
$midkey =~ s/\:$//;
warning("Using implicit mapping path between '$key1' and '$key2' " .
"coord systems.\n" .
"An explicit 'assembly.mapping' entry should be added " .
"to the meta table.\nExample: " .
"'$key1|$midkey|$key2'\n");
return $path;
} else {
$mid1{$midkey} = $mid;
}
}
$match = undef;
if($path->[0]->equals($cs2)) {
$match = 1;
} elsif($path->[1]->equals($cs2)) {
$match = 0;
}
if(defined($match)) {
my $mid = $path->[$match];
my $midkey = $mid->name() . ':' . $mid->version();
# is the same cs mapped to by other cs?
if($mid1{$midkey}) {
my $path = [$cs2,$mid,$cs1];
$self->{'_mapping_paths'}->{"$key2|$key1"} = $path;
$key1 =~ s/\:$//;
$key2 =~ s/\:$//;
$midkey =~ s/\:$//;
warning("Using implicit mapping path between '$key1' and '$key2' " .
"coord systems.\n" .
"An explicit 'assembly.mapping' entry should be added " .
"to the meta table.\nExample: " .
"'$key1|$midkey|$key2'\n");
return $path;
} else {
$mid2{$midkey} = $mid;
}
}
}
}
return $path || [];
}
=head2 store_mapping_path
Arg [1] : Bio::EnsEMBL::CoordSystem $cs1
Arg [2] : Bio::EnsEMBL::CoordSystem $cs2
Arg [3..n] : Bio::EnsEMBL::CoordSystems $cs3..$csN
Example : my $pathref = $csa->store_mapping_path($cs1,$cs2);
Description: Given two or more coordinate systems this will store
mapping paths between them in the database.
The 'rank' attrib of the CoordSystems is used to
determine the assembled/component relationships between
them.
For example, if $cs1 represents chrs of version
V1, $cs2 represents contigs, and $cs3 clones then, unless
they already exist, the following entries will be created
in the meta table;
+------------------+---------------------+
| meta_key | meta_value |
+------------------+---------------------+
| assembly.mapping | chr:V1|clone |
| assembly.mapping | clone|contig |
| assembly.mapping | chr:V1|clone|contig |
+------------------+---------------------+
For a one-step mapping path to be valid there needs to be
a relationship between the two coordinate systems defined in
the assembly table. Two step mapping paths work by building
on the one-step mapping paths which are already defined.
The first coordinate system in a one step mapping path must
be the assembled coordinate system and the second must be
the component.
Returntype : reference to a list of lists of new meta_value mapping strings
created for assembly.mapping
Exceptions : CoordSystems with no rank/duplicated rank
Caller : general
Status : Experimental
=cut
sub store_mapping_path{
my $self = shift;
my @csystems = @_;
# Validate and sort the args
my %seen_ranks;
@csystems >= 2 or throw('Need two or more CoordSystems');
my $validate = sub{
ref($_[0]) && $_[0]->isa('Bio::EnsEMBL::CoordSystem') or
throw('CoordSystem argument expected.');
my $rank = $_[0]->rank ||
throw('CoordSystem has no rank: '.$_[0]->name);
$seen_ranks{$rank} &&
throw('CoordSystem '.$_[0]->name." shares rank $rank with ".
$seen_ranks{$rank}->name);
$seen_ranks{$rank} = $_[0];
};
@csystems = sort{$a->rank <=> $b->rank} map{&{$validate}($_)} @csystems;
# Get a list of all existing assembly.mappings
#my %mappings = map{$_=>1} @{$meta->list_value_by_key('assembly.mapping')};
# For each pair in the sorted list, store in the DB
my $meta = $self->db->get_MetaContainer;
my @retlist;
for( my $i=1; $i<@csystems; $i++ ){
for( my $j=0; $j<(@csystems-$i); $j++ ){
my $mapping = join( "|",
map{join( ':', $_->name, ($_->version||()) )}
@csystems[$j..$j+$i] );
my $mapping_key = join( "|",
map{join( ':', $_->name, ($_->version||'') )}
@csystems[$j..$j+$i] );
# Skip existing
next if $self->{'_mapping_paths'}->{$mapping_key};
# Update the database
$meta->store_key_value('assembly.mapping',$mapping);
push @retlist, $mapping;
}
}
if( @retlist ){
# Update mapping path cache
$self->_cache_mapping_paths;
}
# Return the mappings that we have just created
return [@retlist];
}
=head2 fetch_by_attrib
Arg [1] : string attrib
Arg [2] : (optional) string version
Example : $csa->fetch_by_attrib('default_version','NCBIM37');
Description: Retrieves a CoordSystem object from the database that have the specified
attrib and version, if no version is specified, returns the default version
Returntype : Bio::EnsEMBL::CoordSystem object
Exceptions : throw when attrib not present
Caller : general
Status : Stable
=cut
sub fetch_by_attrib {
my $self = shift;
my $attrib = shift;
my $version = shift;
$version = lc($version) if($version);
my @dbIDs = keys %{$self->{"_is_$attrib"}};
throw("No $attrib coordinate system defined") if(!@dbIDs);
foreach my $dbID (@dbIDs) {
my $cs = $self->{'_dbID_cache'}->{$dbID};
if($version) {
return $cs if(lc($version) eq $cs->version());
} elsif($self->{'_is_default_version'}->{$dbID}) {
return $cs;
}
}
#specifically requested attrib system was not found
if($version) {
throw("$attrib coord_system with version [$version] does not exist");
}
#coordsystem with attrib exists but no default is defined:
my $dbID = shift @dbIDs;
my $cs = $self->{'_dbID_cache'}->{$dbID};
my $v = $cs->version();
warning("No default version for $attrib coord_system exists. " .
"Using version [$v] arbitrarily");
return $cs;
}
sub _fetch_by_attrib{
my $self = shift;
my $attrib = shift;
my $version = shift;
deprecate("You should be using the public method fetch_by_attrib ".
"(without initial underscore) instead");
return $self->fetch_by_attrib($attrib,$version);
}
=head2 fetch_all_by_attrib
Arg [1] : string attrib
Example : $csa->fetch_all_by_attrib('default_version');
Description: Retrieves all CoordSystem object from the database that have the specified
attrib.
Returntype : reference to a list of Bio::EnsEMBL::CoordSystem objects
Exceptions : throw when attrib not present
Caller : general
Status : Stable
=cut
sub fetch_all_by_attrib {
my $self = shift;
my $attrib = shift;
my @coord_systems = ();
foreach my $dbID (keys %{$self->{"_is_$attrib"}}) {
push @coord_systems, $self->{"_dbID_cache"}->{$dbID};
}
return \@coord_systems;
}
sub _fetch_all_by_attrib{
my $self = shift;
my $attrib = shift;
deprecate("You should be using the public method fetch_all_by_attrib ".
"(without initial underscore) instead");
return $self->fetch_all_by_attrib($attrib);
}
=head2 store
Arg [1] : Bio::EnsEMBL::CoordSystem
Example : $csa->store($coord_system);
Description: Stores a CoordSystem object in the database.
Returntype : none
Exceptions : Warning if CoordSystem is already stored in this database.
Caller : none
Status : Stable
=cut
sub store {
my $self = shift;
my $cs = shift;
if(!$cs || !ref($cs) || !$cs->isa('Bio::EnsEMBL::CoordSystem')) {
throw('CoordSystem argument expected.');
}
my $db = $self->db();
my $name = $cs->name();
my $version = $cs->version();
my $rank = $cs->rank();
my $seqlevel = $cs->is_sequence_level();
my $default = $cs->is_default();
my $toplevel = $cs->is_top_level();
if($toplevel) {
throw("The toplevel CoordSystem cannot be stored");
}
#
# Do lots of sanity checking to prevent bad data from being entered
#
if($cs->is_stored($db)) {
warning("CoordSystem $name $version is already in db.\n");
return;
}
if($name eq 'toplevel' || $name eq 'seqlevel' || !$name) {
throw("[$name] is not a valid name for a CoordSystem.");
}
if($seqlevel && keys(%{$self->{'_is_sequence_level'}})) {
throw("There can only be one sequence level CoordSystem.");
}
if(exists $self->{'_name_cache'}->{lc($name)}) {
my @coord_systems = @{$self->{'_name_cache'}->{lc($name)}};
foreach my $c (@coord_systems) {
if(lc($c->version()) eq lc($version)) {
warning("CoordSystem $name $version is already in db.\n");
return;
}
if($default && $self->{'_is_default_version'}->{$c->dbID()}) {
throw("There can only be one default version of CoordSystem $name");
}
}
}
if($rank !~ /^\d+$/) {
throw("Rank attribute must be a positive integer not [$rank]");
}
if($rank == 0) {
throw("Only toplevel CoordSystem may have rank of 0.");
}
if(defined($self->{'_rank_cache'}->{$rank})) {
throw("CoordSystem with rank [$rank] already exists.");
}
my @attrib;
push @attrib, 'default_version' if($default);
push @attrib, 'sequence_level' if($seqlevel);
my $attrib_str = (@attrib) ? join(',', @attrib) : undef;
#
# store the coordinate system in the database
#
my $sth =
$db->dbc->prepare( 'INSERT INTO coord_system '
. 'SET name = ?, '
. 'version = ?, '
. 'attrib = ?,'
. 'rank = ?,'
. 'species_id = ?' );
$sth->bind_param( 1, $name, SQL_VARCHAR );
$sth->bind_param( 2, $version, SQL_VARCHAR );
$sth->bind_param( 3, $attrib_str, SQL_VARCHAR );
$sth->bind_param( 4, $rank, SQL_INTEGER );
$sth->bind_param( 5, $self->species_id(), SQL_INTEGER );
$sth->execute();
my $dbID = $sth->{'mysql_insertid'};
$sth->finish();
if(!$dbID) {
throw("Did not get dbID from store of CoordSystem.");
}
$cs->dbID($dbID);
$cs->adaptor($self);
#
# update the internal caches that are used for fetching
#
$self->{'_is_default_version'}->{$dbID} = 1 if($default);
$self->{'_is_sequence_level'}->{$dbID} = 1 if($seqlevel);
$self->{'_name_cache'}->{lc($name)} ||= [];
push @{$self->{'_name_cache'}->{lc($name)}}, $cs;
$self->{'_dbID_cache'}->{$dbID} = $cs;
$self->{'_rank_cache'}->{$rank} = $cs;
return $cs;
}
1;
| adamsardar/perl-libs-custom | EnsemblAPI/ensembl/modules/Bio/EnsEMBL/DBSQL/CoordSystemAdaptor.pm | Perl | apache-2.0 | 31,001 |
#
# (c) Jan Gehring <jan.gehring@gmail.com>
#
# vim: set ts=2 sw=2 tw=0:
# vim: set expandtab:
=head1 NAME
Rex::Commands::MD5 - Calculate MD5 sum of files
=head1 DESCRIPTION
With this module you calculate the md5 sum of a file.
This is just a helper function and will not be reported.
=head1 SYNOPSIS
my $md5 = md5($file);
=head1 EXPORTED FUNCTIONS
=over 4
=cut
package Rex::Commands::MD5;
use strict;
use warnings;
our $VERSION = '0.56.1'; # VERSION
use Rex::Logger;
require Rex::Commands;
use Rex::Interface::Exec;
use Rex::Interface::File;
use Rex::Interface::Fs;
use Rex::Helper::Path;
use Rex::Helper::Run;
require Rex::Exporter;
use base qw(Rex::Exporter);
use vars qw(@EXPORT);
@EXPORT = qw(md5);
=item md5($file)
This function will return the md5 sum (hexadecimal) for the given file.
task "md5", "server01", sub {
my $md5 = md5("/etc/passwd");
};
=cut
sub md5 {
my ($file) = @_;
my $fs = Rex::Interface::Fs->create;
if ( $fs->is_file($file) ) {
Rex::Logger::debug("Calculating Checksum (md5) of $file");
my $exec = Rex::Interface::Exec->create;
my $md5;
my $os = $exec->exec("uname -s");
if ( $os =~ /bsd/i ) {
$md5 = $exec->exec("/sbin/md5 -q '$file'");
}
else {
($md5) = split( /\s/, $exec->exec("md5sum '$file'") );
}
if ( $? != 0 ) {
my $script = q|
use Digest::MD5;
print Digest::MD5::md5_hex(<>) . "\n";
|;
my $rnd_file = get_tmp_file;
my $fh = Rex::Interface::File->create;
$fh->open( ">", $rnd_file );
$fh->write($script);
$fh->close;
if ( Rex::is_local() && $^O =~ m/^MSWin/ ) {
$md5 = $exec->exec("perl $rnd_file \"$file\"");
}
else {
$md5 = i_run "perl $rnd_file '$file'";
}
unless ( $? == 0 ) {
Rex::Logger::info("Unable to get md5 sum of $file");
die("Unable to get md5 sum of $file");
}
Rex::Interface::Fs->create->unlink($rnd_file);
}
Rex::Logger::debug("MD5SUM ($file): $md5");
$md5 =~ s/[\r\n]//gms;
return $md5;
}
else {
Rex::Logger::debug("File $file not found.");
die("File $file not found");
}
}
=back
=cut
1;
| gitpan/Rex | lib/Rex/Commands/MD5.pm | Perl | apache-2.0 | 2,197 |
#
# Copyright 2019 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::sccm::local::mode::databasereplicationstatus;
use base qw(centreon::plugins::templates::counter);
use strict;
use warnings;
use JSON::XS;
use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold);
use centreon::common::powershell::sccm::databasereplicationstatus;
use DateTime;
my %map_link_status = (
1 => 'Degraded',
2 => 'Active',
3 => 'Failed',
);
my %map_status = (
100 => 'SITE_INSTALLING',
105 => 'SITE_INSTALL_COMPLETE',
110 => 'INACTIVE',
115 => 'INITIALIZING',
120 => 'MAINTENANCE_MODE',
125 => 'ACTIVE',
130 => 'DETACHING',
135 => 'READY_TO_DETACH',
199 => 'STATUS_UNKNOWN',
200 => 'SITE_RECOVERED',
205 => 'SITE_PREPARE_FOR_RECOVERY',
210 => 'SITE_PREPARED_FOR_RECOVERY',
215 => 'REPLCONFIG_REINITIALIZING',
220 => 'REPLCONFIG_REINITIALIZED',
225 => 'RECOVERY_IN_PROGRESS',
230 => 'RECOVERING_DELTAS',
250 => 'RECOVERY_RETRY',
255 => 'RECOVERY_FAILED',
);
my %map_type = (
0 => 'Unknown',
1 => 'SECONDARY',
2 => 'PRIMARY',
4 => 'CAS',
);
sub custom_status_output {
my ($self, %options) = @_;
my $msg = sprintf("Overall Link status is '%s'", $self->{result_values}->{status});
return $msg;
}
sub custom_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_LinkStatus'};
return 0;
}
sub custom_site_status_output {
my ($self, %options) = @_;
my $msg = sprintf("status is '%s', Site-to-Site state is '%s' [Type: %s] [Last sync: %s]",
$self->{result_values}->{status},
$self->{result_values}->{site_to_site_state},
$self->{result_values}->{type},
centreon::plugins::misc::change_seconds(value => $self->{result_values}->{last_sync_time}));
return $msg;
}
sub custom_site_status_calc {
my ($self, %options) = @_;
$self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_SiteStatus'};
$self->{result_values}->{type} = $options{new_datas}->{$self->{instance} . '_SiteType'};
$self->{result_values}->{site_to_site_state} = $options{new_datas}->{$self->{instance} . '_SiteToSiteGlobalState'};
$self->{result_values}->{sync_time} = $options{new_datas}->{$self->{instance} . '_SiteToSiteGlobalSyncTime'};
my $tz = centreon::plugins::misc::set_timezone(name => $self->{option_results}->{timezone});
$self->{result_values}->{sync_time} =~ /^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)$/;
my $sync_time = DateTime->new(year => $1, month => $2, day => $3, hour => $4, minute => $5, second => $6, %$tz);
$self->{result_values}->{last_sync_time} = time() - $sync_time->epoch;
return 0;
}
sub set_counters {
my ($self, %options) = @_;
$self->{maps_counters_type} = [
{ name => 'global', type => 0 },
{ name => 'sites', type => 1, cb_prefix_output => 'prefix_output_site', message_multiple => 'All sites status are ok' },
];
$self->{maps_counters}->{global} = [
{ label => 'link-status', threshold => 0, set => {
key_values => [ { name => 'LinkStatus' } ],
closure_custom_calc => $self->can('custom_status_calc'),
closure_custom_output => $self->can('custom_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
];
$self->{maps_counters}->{sites} = [
{ label => 'site-status', threshold => 0, set => {
key_values => [ { name => 'SiteType' }, { name => 'SiteStatus' }, { name => 'SiteToSiteGlobalState' },
{ name => 'SiteToSiteGlobalSyncTime' } ],
closure_custom_calc => $self->can('custom_site_status_calc'),
closure_custom_output => $self->can('custom_site_status_output'),
closure_custom_perfdata => sub { return 0; },
closure_custom_threshold_check => \&catalog_status_threshold,
}
},
];
}
sub prefix_output_site {
my ($self, %options) = @_;
return "Site '" . $options{instance_value}->{display} . "' ";
}
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {
'timeout:s' => { name => 'timeout', default => 30 },
'command:s' => { name => 'command', default => 'powershell.exe' },
'command-path:s' => { name => 'command_path' },
'command-options:s' => { name => 'command_options', default => '-InputFormat none -NoLogo -EncodedCommand' },
'no-ps' => { name => 'no_ps' },
'ps-exec-only' => { name => 'ps_exec_only' },
'warning-link-status:s' => { name => 'warning_link_status', default => '' },
'critical-link-status:s' => { name => 'critical_link_status', default => '' },
'warning-site-status:s' => { name => 'warning_site_status', default => '' },
'critical-site-status:s' => { name => 'critical_site_status', default => '' },
'timezone:s' => { name => 'timezone', default => 'UTC' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::check_options(%options);
$self->change_macros(macros => ['warning_link_status', 'critical_link_status',
'warning_site_status', 'critical_site_status']);
}
sub manage_selection {
my ($self, %options) = @_;
my $ps = centreon::common::powershell::sccm::databasereplicationstatus::get_powershell(
no_ps => $self->{option_results}->{no_ps},
);
$self->{option_results}->{command_options} .= " " . $ps;
my ($stdout) = centreon::plugins::misc::execute(
output => $self->{output},
options => $self->{option_results},
command => $self->{option_results}->{command},
command_path => $self->{option_results}->{command_path},
command_options => $self->{option_results}->{command_options}
);
if (defined($self->{option_results}->{ps_exec_only})) {
$self->{output}->output_add(severity => 'OK',
short_msg => $stdout);
$self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1);
$self->{output}->exit();
}
my $decoded;
eval {
$decoded = JSON::XS->new->utf8->decode($stdout);
};
if ($@) {
$self->{output}->add_option_msg(short_msg => "Cannot decode json response: $@");
$self->{output}->option_exit();
}
if (!defined($decoded->{LinkStatus})) {
$self->{output}->add_option_msg(short_msg => 'No database replication');
$self->{output}->option_exit();
}
$self->{global}->{LinkStatus} = $map_link_status{$decoded->{LinkStatus}};
$self->{sites}->{$decoded->{Site1}} = {
display => $decoded->{Site1},
SiteType => $map_type{$decoded->{SiteType1}},
SiteStatus => $map_status{$decoded->{Site1Status}},
SiteToSiteGlobalState => $decoded->{Site1ToSite2GlobalState},
SiteToSiteGlobalSyncTime => $decoded->{Site1ToSite2GlobalSyncTime},
};
$self->{sites}->{$decoded->{Site2}} = {
display => $decoded->{Site2},
SiteType => $map_type{$decoded->{SiteType2}},
SiteStatus => $map_status{$decoded->{Site2Status}},
SiteToSiteGlobalState => $decoded->{Site2ToSite1GlobalState},
SiteToSiteGlobalSyncTime => $decoded->{Site2ToSite1GlobalSyncTime},
};
}
1;
__END__
=head1 MODE
Check database replication status.
=over 8
=item B<--timeout>
Set timeout time for command execution (Default: 30 sec)
=item B<--no-ps>
Don't encode powershell. To be used with --command and 'type' command.
=item B<--command>
Command to get information (Default: 'powershell.exe').
Can be changed if you have output in a file. To be used with --no-ps option.
=item B<--command-path>
Command path (Default: none).
=item B<--command-options>
Command options (Default: '-InputFormat none -NoLogo -EncodedCommand').
=item B<--ps-exec-only>
Print powershell output.
=item B<--warning-link-status>
Set warning threshold for current synchronisation status (Default: '')
Can used special variables like: %{status}.
=item B<--critical-link-status>
Set critical threshold for current synchronisation status (Default: '').
Can used special variables like: %{status}.
=item B<--warning-site-status>
Set warning threshold for current synchronisation status (Default: '')
Can used special variables like: %{status}, %{type}, %{site_to_site_state}, %{last_sync_time}.
=item B<--critical-site-status>
Set critical threshold for current synchronisation status (Default: '').
Can used special variables like: %{status}, %{type}, %{site_to_site_state}, %{last_sync_time}.
=back
=cut
| Sims24/centreon-plugins | apps/sccm/local/mode/databasereplicationstatus.pm | Perl | apache-2.0 | 9,766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.