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 |
|---|---|---|---|---|---|
#------------------------------------------------------------------------------
# File: CanonRaw.pm
#
# Description: Read Canon RAW (CRW) meta information
#
# Revisions: 11/25/2003 - P. Harvey Created
# 12/02/2003 - P. Harvey Completely reworked and figured out many
# more tags
#
# References: 1) http://www.cybercom.net/~dcoffin/dcraw/
# 2) http://www.wonderland.org/crw/
# 3) http://xyrion.org/ciff/CIFFspecV1R04.pdf
# 4) Dave Nicholson private communication (PowerShot S30)
#------------------------------------------------------------------------------
package Image::ExifTool::CanonRaw;
use strict;
use vars qw($VERSION $AUTOLOAD %crwTagFormat);
use Image::ExifTool qw(:DataAccess :Utils);
use Image::ExifTool::Exif;
use Image::ExifTool::Canon;
$VERSION = '1.58';
sub WriteCRW($$);
sub ProcessCanonRaw($$$);
sub WriteCanonRaw($$$);
sub CheckCanonRaw($$$);
sub InitMakerNotes($);
sub SaveMakerNotes($);
sub BuildMakerNotes($$$$$$);
# formats for CRW tag types (($tag >> 8) & 0x38)
# Note: don't define format for undefined types
%crwTagFormat = (
0x00 => 'int8u',
0x08 => 'string',
0x10 => 'int16u',
0x18 => 'int32u',
# 0x20 => 'undef',
# 0x28 => 'undef',
# 0x30 => 'undef',
);
# Canon raw file tag table
# Note: Tag ID's have upper 2 bits set to zero, since these 2 bits
# just specify the location of the information
%Image::ExifTool::CanonRaw::Main = (
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
PROCESS_PROC => \&ProcessCanonRaw,
WRITE_PROC => \&WriteCanonRaw,
CHECK_PROC => \&CheckCanonRaw,
WRITABLE => 1,
0x0000 => { Name => 'NullRecord', Writable => 'undef' }, #3
0x0001 => { #3
Name => 'FreeBytes',
Format => 'undef',
Binary => 1,
},
0x0032 => { Name => 'CanonColorInfo1', Writable => 0 },
0x0805 => [
# this tag is found in more than one directory...
{
Condition => '$self->{DIR_NAME} eq "ImageDescription"',
Name => 'CanonFileDescription',
Writable => 'string[32]',
},
{
Name => 'UserComment',
Writable => 'string[256]',
},
],
0x080a => {
Name => 'CanonRawMakeModel',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::CanonRaw::MakeModel' },
},
0x080b => { Name => 'CanonFirmwareVersion', Writable => 'string[32]' },
0x080c => { Name => 'ComponentVersion', Writable => 'string' }, #3
0x080d => { Name => 'ROMOperationMode', Writable => 'string[8]' }, #3
0x0810 => { Name => 'OwnerName', Writable => 'string[32]' },
0x0815 => { Name => 'CanonImageType', Writable => 'string[32]' },
0x0816 => { Name => 'OriginalFileName', Writable => 'string[32]' },
0x0817 => { Name => 'ThumbnailFileName', Writable => 'string[32]' },
0x100a => { #3
Name => 'TargetImageType',
Writable => 'int16u',
PrintConv => {
0 => 'Real-world Subject',
1 => 'Written Document',
},
},
0x1010 => { #3
Name => 'ShutterReleaseMethod',
Writable => 'int16u',
PrintConv => {
0 => 'Single Shot',
2 => 'Continuous Shooting',
},
},
0x1011 => { #3
Name => 'ShutterReleaseTiming',
Writable => 'int16u',
PrintConv => {
0 => 'Priority on shutter',
1 => 'Priority on focus',
},
},
0x1016 => { Name => 'ReleaseSetting', Writable => 'int16u' }, #3
0x101c => { Name => 'BaseISO', Writable => 'int16u' }, #3
0x1028=> { #PH
Name => 'CanonFlashInfo',
Writable => 'int16u',
Count => 4,
Unknown => 1,
},
0x1029 => {
Name => 'CanonFocalLength',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::Canon::FocalLength' },
},
0x102a => {
Name => 'CanonShotInfo',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::Canon::ShotInfo' },
},
0x102c => {
Name => 'CanonColorInfo2',
Writable => 0,
# for the S30, the following information has been decoded: (ref 4)
# offset 66: int32u - shutter half press time in ms
# offset 70: int32u - image capture time in ms
# offset 74: int16u - custom white balance flag (0=Off, 512=On)
},
0x102d => {
Name => 'CanonCameraSettings',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::Canon::CameraSettings' },
},
0x1030 => { #4
Name => 'WhiteSample',
Writable => 0,
SubDirectory => {
Validate => 'Image::ExifTool::Canon::Validate($dirData,$subdirStart,$size)',
TagTable => 'Image::ExifTool::CanonRaw::WhiteSample',
},
},
0x1031 => {
Name => 'SensorInfo',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::Canon::SensorInfo' },
},
# this tag has only be verified for the 10D in CRW files, but the D30 and D60
# also produce CRW images and have CustomFunction information in their JPEG's
0x1033 => [
{
Name => 'CustomFunctions10D',
Condition => '$self->{Model} =~ /EOS 10D/',
SubDirectory => {
Validate => 'Image::ExifTool::Canon::Validate($dirData,$subdirStart,$size)',
TagTable => 'Image::ExifTool::CanonCustom::Functions10D',
},
},
{
Name => 'CustomFunctionsD30',
Condition => '$self->{Model} =~ /EOS D30\b/',
SubDirectory => {
Validate => 'Image::ExifTool::Canon::Validate($dirData,$subdirStart,$size)',
TagTable => 'Image::ExifTool::CanonCustom::FunctionsD30',
},
},
{
Name => 'CustomFunctionsD60',
Condition => '$self->{Model} =~ /EOS D60\b/',
SubDirectory => {
# the stored size in the D60 apparently doesn't include the size word:
Validate => 'Image::ExifTool::Canon::Validate($dirData,$subdirStart,$size-2,$size)',
# (D60 custom functions are basically the same as D30)
TagTable => 'Image::ExifTool::CanonCustom::FunctionsD30',
},
},
{
Name => 'CustomFunctionsUnknown',
SubDirectory => {
Validate => 'Image::ExifTool::Canon::Validate($dirData,$subdirStart,$size)',
TagTable => 'Image::ExifTool::CanonCustom::FuncsUnknown',
},
},
],
0x1038 => {
Name => 'CanonAFInfo',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::Canon::AFInfo' },
},
0x1093 => {
Name => 'CanonFileInfo',
SubDirectory => {
Validate => 'Image::ExifTool::Canon::Validate($dirData,$subdirStart,$size)',
TagTable => 'Image::ExifTool::Canon::FileInfo',
},
},
0x10a9 => {
Name => 'ColorBalance',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::Canon::ColorBalance' },
},
0x10b5 => { #PH
Name => 'RawJpgInfo',
SubDirectory => {
Validate => 'Image::ExifTool::Canon::Validate($dirData,$subdirStart,$size)',
TagTable => 'Image::ExifTool::CanonRaw::RawJpgInfo',
},
},
0x10ae => {
Name => 'ColorTemperature',
Writable => 'int16u',
},
0x10b4 => {
Name => 'ColorSpace',
Writable => 'int16u',
PrintConv => {
1 => 'sRGB',
2 => 'Adobe RGB',
0xffff => 'Uncalibrated',
},
},
0x1803 => { #3
Name => 'ImageFormat',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::CanonRaw::ImageFormat' },
},
0x1804 => { Name => 'RecordID', Writable => 'int32u' }, #3
0x1806 => { #3
Name => 'SelfTimerTime',
Writable => 'int32u',
ValueConv => '$val / 1000',
ValueConvInv => '$val * 1000',
PrintConv => '"$val s"',
PrintConvInv => '$val=~s/\s*s.*//;$val',
},
0x1807 => {
Name => 'TargetDistanceSetting',
Format => 'float',
PrintConv => '"$val mm"',
PrintConvInv => '$val=~s/\s*mm$//;$val',
},
0x180b => [
{
# D30
Name => 'SerialNumber',
Condition => '$$self{Model} =~ /EOS D30\b/',
Writable => 'int32u',
PrintConv => 'sprintf("%x-%.5d",$val>>16,$val&0xffff)',
PrintConvInv => '$val=~/(.*)-(\d+)/ ? (hex($1)<<16)+$2 : undef',
},
{
# all EOS models (D30, 10D, 300D)
Name => 'SerialNumber',
Condition => '$$self{Model} =~ /EOS/',
Writable => 'int32u',
PrintConv => 'sprintf("%.10d",$val)',
PrintConvInv => '$val',
},
{
# this is not SerialNumber for PowerShot models (but what is it?) - PH
Name => 'UnknownNumber',
Unknown => 1,
},
],
0x180e => {
Name => 'TimeStamp',
Writable => 0,
SubDirectory => {
TagTable => 'Image::ExifTool::CanonRaw::TimeStamp',
},
},
0x1810 => {
Name => 'ImageInfo',
Writable => 0,
SubDirectory => {
TagTable => 'Image::ExifTool::CanonRaw::ImageInfo',
},
},
0x1813 => { #3
Name => 'FlashInfo',
Writable => 0,
SubDirectory => {
TagTable => 'Image::ExifTool::CanonRaw::FlashInfo',
},
},
0x1814 => { #3
Name => 'MeasuredEV',
Notes => q{
this is the Canon name for what could better be called MeasuredLV, and
should be close to the calculated LightValue for a proper exposure with most
models
},
Format => 'float',
ValueConv => '$val + 5',
ValueConvInv => '$val - 5',
},
0x1817 => {
Name => 'FileNumber',
Writable => 'int32u',
Groups => { 2 => 'Image' },
PrintConv => '$_=$val;s/(\d+)(\d{4})/$1-$2/;$_',
PrintConvInv => '$_=$val;s/-//;$_',
},
0x1818 => { #3
Name => 'ExposureInfo',
Groups => { 1 => 'CIFF' }, # (only so CIFF shows up in group lists)
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::CanonRaw::ExposureInfo' },
},
0x1834 => { #PH
Name => 'CanonModelID',
Writable => 'int32u',
PrintHex => 1,
Notes => q{
this is the complete list of model ID numbers, but note that many of these
models do not produce CRW images
},
SeparateTable => 'Canon CanonModelID',
PrintConv => \%Image::ExifTool::Canon::canonModelID,
},
0x1835 => {
Name => 'DecoderTable',
Writable => 0,
SubDirectory => { TagTable => 'Image::ExifTool::CanonRaw::DecoderTable' },
},
0x183b => { #PH
# display format for serial number
Name => 'SerialNumberFormat',
Writable => 'int32u',
PrintHex => 1,
PrintConv => {
0x90000000 => 'Format 1',
0xa0000000 => 'Format 2',
},
},
0x2005 => {
Name => 'RawData',
Writable => 0,
Binary => 1,
},
0x2007 => {
Name => 'JpgFromRaw',
Groups => { 2 => 'Preview' },
Writable => 'resize', # 'resize' allows this value to change size
Permanent => 0,
RawConv => '$self->ValidateImage(\$val,$tag)',
},
0x2008 => {
Name => 'ThumbnailImage',
Groups => { 2 => 'Preview' },
Writable => 'resize', # 'resize' allows this value to change size
WriteCheck => '$self->CheckImage(\$val)',
Permanent => 0,
RawConv => '$self->ValidateImage(\$val,$tag)',
},
# the following entries are subdirectories
# (any 0x28 and 0x30 tag types are handled automatically by the decoding logic)
0x2804 => {
Name => 'ImageDescription',
SubDirectory => { },
Writable => 0,
},
0x2807 => { #3
Name => 'CameraObject',
SubDirectory => { },
Writable => 0,
},
0x3002 => { #3
Name => 'ShootingRecord',
SubDirectory => { },
Writable => 0,
},
0x3003 => { #3
Name => 'MeasuredInfo',
SubDirectory => { },
Writable => 0,
},
0x3004 => { #3
Name => 'CameraSpecification',
SubDirectory => { },
Writable => 0,
},
0x300a => { #3
Name => 'ImageProps',
SubDirectory => { },
Writable => 0,
},
0x300b => {
Name => 'ExifInformation',
SubDirectory => { },
Writable => 0,
},
);
# Canon binary data blocks
%Image::ExifTool::CanonRaw::MakeModel = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
DATAMEMBER => [ 0, 6 ], # indices of data members to extract when writing
WRITABLE => 1,
FORMAT => 'string',
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
# (can't specify a first entry because this isn't
# a simple binary table with fixed offsets)
0 => {
Name => 'Make',
Format => 'string[6]', # "Canon\0"
DataMember => 'Make',
RawConv => '$self->{Make} = $val',
},
6 => {
Name => 'Model',
Format => 'string', # no size = to the end of the data
Description => 'Camera Model Name',
DataMember => 'Model',
RawConv => '$self->{Model} = $val',
},
);
%Image::ExifTool::CanonRaw::TimeStamp = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int32u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Time' },
0 => {
Name => 'DateTimeOriginal',
Description => 'Date/Time Original',
Shift => 'Time',
ValueConv => 'ConvertUnixTime($val)',
ValueConvInv => 'GetUnixTime($val)',
PrintConv => '$self->ConvertDateTime($val)',
PrintConvInv => '$self->InverseDateTime($val)',
},
1 => { #3
Name => 'TimeZoneCode',
Format => 'int32s',
ValueConv => '$val / 3600',
ValueConvInv => '$val * 3600',
},
2 => { #3
Name => 'TimeZoneInfo',
Notes => 'set to 0x80000000 if TimeZoneCode is valid',
},
);
%Image::ExifTool::CanonRaw::ImageFormat = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int32u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => {
Name => 'FileFormat',
Flags => 'PrintHex',
PrintConv => {
0x00010000 => 'JPEG (lossy)',
0x00010002 => 'JPEG (non-quantization)',
0x00010003 => 'JPEG (lossy/non-quantization toggled)',
0x00020001 => 'CRW',
},
},
1 => {
Name => 'TargetCompressionRatio',
Format => 'float',
},
);
%Image::ExifTool::CanonRaw::RawJpgInfo = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int16u',
FIRST_ENTRY => 1,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
# 0 => 'RawJpgInfoSize',
1 => { #PH
Name => 'RawJpgQuality',
PrintConv => {
1 => 'Economy',
2 => 'Normal',
3 => 'Fine',
5 => 'Superfine',
},
},
2 => { #PH
Name => 'RawJpgSize',
PrintConv => {
0 => 'Large',
1 => 'Medium',
2 => 'Small',
},
},
3 => 'RawJpgWidth', #PH
4 => 'RawJpgHeight', #PH
);
%Image::ExifTool::CanonRaw::FlashInfo = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'float',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => 'FlashGuideNumber',
1 => 'FlashThreshold',
);
%Image::ExifTool::CanonRaw::ExposureInfo = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'float',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
0 => 'ExposureCompensation',
1 => {
Name => 'ShutterSpeedValue',
ValueConv => 'abs($val)<100 ? 1/(2**$val) : 0',
ValueConvInv => '$val>0 ? -log($val)/log(2) : -100',
PrintConv => 'Image::ExifTool::Exif::PrintExposureTime($val)',
PrintConvInv => 'Image::ExifTool::Exif::ConvertFraction($val)',
},
2 => {
Name => 'ApertureValue',
ValueConv => '2 ** ($val / 2)',
ValueConvInv => '$val>0 ? 2*log($val)/log(2) : 0',
PrintConv => 'sprintf("%.1f",$val)',
PrintConvInv => '$val',
},
);
%Image::ExifTool::CanonRaw::ImageInfo = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
FORMAT => 'int32u',
FIRST_ENTRY => 0,
GROUPS => { 0 => 'MakerNotes', 2 => 'Image' },
# Note: Don't make these writable (except rotation) because it confuses
# Canon decoding software if the are changed
0 => 'ImageWidth', #3
1 => 'ImageHeight', #3
2 => { #3
Name => 'PixelAspectRatio',
Format => 'float',
},
3 => {
Name => 'Rotation',
Format => 'int32s',
Writable => 'int32s',
},
4 => 'ComponentBitDepth', #3
5 => 'ColorBitDepth', #3
6 => 'ColorBW', #3
);
# ref 4
%Image::ExifTool::CanonRaw::DecoderTable = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
FORMAT => 'int32u',
FIRST_ENTRY => 0,
0 => 'DecoderTableNumber',
2 => 'CompressedDataOffset',
3 => 'CompressedDataLength',
);
# ref 1/4
%Image::ExifTool::CanonRaw::WhiteSample = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
GROUPS => { 0 => 'MakerNotes', 2 => 'Camera' },
FORMAT => 'int16u',
FIRST_ENTRY => 1,
1 => 'WhiteSampleWidth',
2 => 'WhiteSampleHeight',
3 => 'WhiteSampleLeftBorder',
4 => 'WhiteSampleTopBorder',
5 => 'WhiteSampleBits',
# this is followed by the encrypted white sample values (ref 1)
);
#------------------------------------------------------------------------------
# AutoLoad our writer routines when necessary
#
sub AUTOLOAD
{
return Image::ExifTool::DoAutoLoad($AUTOLOAD, @_);
}
#------------------------------------------------------------------------------
# Process Raw file directory
# Inputs: 0) ExifTool object reference
# 1) directory information reference, 2) tag table reference
# Returns: 1 on success
sub ProcessCanonRaw($$$)
{
my ($et, $dirInfo, $rawTagTable) = @_;
my $blockStart = $$dirInfo{DirStart};
my $blockSize = $$dirInfo{DirLen};
my $raf = $$dirInfo{RAF} or return 0;
my $buff;
my $verbose = $et->Options('Verbose');
my $buildMakerNotes = $et->Options('MakerNotes');
# 4 bytes at end of block give directory position within block
$raf->Seek($blockStart+$blockSize-4, 0) or return 0;
$raf->Read($buff, 4) == 4 or return 0;
my $dirOffset = Get32u(\$buff,0) + $blockStart;
$raf->Seek($dirOffset, 0) or return 0;
$raf->Read($buff, 2) == 2 or return 0;
my $entries = Get16u(\$buff,0); # get number of entries in directory
# read the directory (10 bytes per entry)
$raf->Read($buff, 10 * $entries) == 10 * $entries or return 0;
$verbose and $et->VerboseDir('CIFF', $entries);
my $index;
for ($index=0; $index<$entries; ++$index) {
my $pt = 10 * $index;
my $tag = Get16u(\$buff, $pt);
my $size = Get32u(\$buff, $pt+2);
my $valuePtr = Get32u(\$buff, $pt+6);
my $ptr = $valuePtr + $blockStart; # all pointers relative to block start
if ($tag & 0x8000) {
$et->Warn('Bad CRW directory entry');
return 1;
}
my $tagID = $tag & 0x3fff; # get tag ID
my $tagType = ($tag >> 8) & 0x38; # get tag type
my $valueInDir = ($tag & 0x4000); # flag for value in directory
my $tagInfo = $et->GetTagInfo($rawTagTable, $tagID);
if (($tagType==0x28 or $tagType==0x30) and not $valueInDir) {
# this type of tag specifies a raw subdirectory
my $name;
$tagInfo and $name = $$tagInfo{Name};
$name or $name = sprintf("CanonRaw_0x%.4x", $tag);
my %subdirInfo = (
DirName => $name,
DataLen => 0,
DirStart => $ptr,
DirLen => $size,
Nesting => $$dirInfo{Nesting} + 1,
RAF => $raf,
Parent => $$dirInfo{DirName},
);
if ($verbose) {
my $fakeInfo = { Name => $name, SubDirectory => { } };
$et->VerboseInfo($tagID, $fakeInfo,
'Index' => $index,
'Size' => $size,
'Start' => $ptr,
);
}
$et->ProcessDirectory(\%subdirInfo, $rawTagTable);
next;
}
my ($valueDataPos, $count, $subdir);
my $format = $crwTagFormat{$tagType};
if ($tagInfo) {
$subdir = $$tagInfo{SubDirectory};
$format = $$tagInfo{Format} if $$tagInfo{Format};
$count = $$tagInfo{Count};
}
# get value data
my ($value, $delRawConv);
if ($valueInDir) { # is the value data in the directory?
# this type of tag stores the value in the 'size' and 'ptr' fields
$valueDataPos = $dirOffset + $pt + 4; # (remember, +2 for the entry count)
$size = 8;
$value = substr($buff, $pt+2, $size);
# set count to 1 by default for normal values in directory
$count = 1 if not defined $count and $format and
$format ne 'string' and not $subdir;
} else {
$valueDataPos = $ptr;
if ($size <= 512 or ($verbose > 2 and $size <= 65536)
or ($tagInfo and ($$tagInfo{SubDirectory}
or grep(/^$$tagInfo{Name}$/i, $et->GetRequestedTags()) )))
{
# read value if size is small or specifically requested
# or if this is a SubDirectory
unless ($raf->Seek($ptr, 0) and $raf->Read($value, $size) == $size) {
$et->Warn(sprintf("Error reading %d bytes from 0x%x",$size,$ptr));
next;
}
} else {
$value = "Binary data $size bytes";
if ($tagInfo) {
if ($et->Options('Binary') or $verbose) {
# read the value anyway
unless ($raf->Seek($ptr, 0) and $raf->Read($value, $size) == $size) {
$et->Warn(sprintf("Error reading %d bytes from 0x%x",$size,$ptr));
next;
}
}
# force this to be a binary (scalar reference)
$$tagInfo{RawConv} = '\$val';
$delRawConv = 1;
}
$size = length $value;
undef $format;
}
}
# set count from tagInfo count if necessary
if ($format and not $count) {
# set count according to format and size
my $fnum = $Image::ExifTool::Exif::formatNumber{$format};
my $fsiz = $Image::ExifTool::Exif::formatSize[$fnum];
$count = int($size / $fsiz);
}
if ($verbose) {
my $val = $value;
$format and $val = ReadValue(\$val, 0, $format, $count, $size);
$et->VerboseInfo($tagID, $tagInfo,
Table => $rawTagTable,
Index => $index,
Value => $val,
DataPt => \$value,
DataPos => $valueDataPos,
Size => $size,
Format => $format,
Count => $count,
);
}
if ($buildMakerNotes) {
# build maker notes information if requested
BuildMakerNotes($et, $tagID, $tagInfo, \$value, $format, $count);
}
next unless defined $tagInfo;
if ($subdir) {
my $name = $$tagInfo{Name};
my $newTagTable;
if ($$subdir{TagTable}) {
$newTagTable = GetTagTable($$subdir{TagTable});
unless ($newTagTable) {
warn "Unknown tag table $$subdir{TagTable}\n";
next;
}
} else {
warn "Must specify TagTable for SubDirectory $name\n";
next;
}
my $subdirStart = 0;
#### eval Start ()
$subdirStart = eval $$subdir{Start} if $$subdir{Start};
my $dirData = \$value;
my %subdirInfo = (
Name => $name,
DataPt => $dirData,
DataLen => $size,
DataPos => $valueDataPos,
DirStart => $subdirStart,
DirLen => $size - $subdirStart,
Nesting => $$dirInfo{Nesting} + 1,
RAF => $raf,
DirName => $name,
Parent => $$dirInfo{DirName},
);
#### eval Validate ($dirData, $subdirStart, $size)
if (defined $$subdir{Validate} and not eval $$subdir{Validate}) {
$et->Warn("Invalid $name data");
} else {
$et->ProcessDirectory(\%subdirInfo, $newTagTable, $$subdir{ProcessProc});
}
} else {
# convert to specified format if necessary
$format and $value = ReadValue(\$value, 0, $format, $count, $size);
# save the information
$et->FoundTag($tagInfo, $value);
delete $$tagInfo{RawConv} if $delRawConv;
}
}
return 1;
}
#------------------------------------------------------------------------------
# get information from raw file
# Inputs: 0) ExifTool object reference, 1) dirInfo reference
# Returns: 1 if this was a valid Canon RAW file
sub ProcessCRW($$)
{
my ($et, $dirInfo) = @_;
my ($buff, $sig);
my $raf = $$dirInfo{RAF};
my $buildMakerNotes = $et->Options('MakerNotes');
$raf->Read($buff,2) == 2 or return 0;
SetByteOrder($buff) or return 0;
$raf->Read($buff,4) == 4 or return 0;
$raf->Read($sig,8) == 8 or return 0; # get file signature
$sig =~ /^HEAP(CCDR|JPGM)/ or return 0; # validate signature
my $hlen = Get32u(\$buff, 0);
$raf->Seek(0, 2) or return 0; # seek to end of file
my $filesize = $raf->Tell() or return 0;
# initialize maker note data if building maker notes
$buildMakerNotes and InitMakerNotes($et);
# set the FileType tag unless already done (eg. APP0 CIFF record in JPEG image)
$et->SetFileType();
# build directory information for main raw directory
my %dirInfo = (
DataLen => 0,
DirStart => $hlen,
DirLen => $filesize - $hlen,
Nesting => 0,
RAF => $raf,
Parent => 'CRW',
);
# process the raw directory
my $rawTagTable = GetTagTable('Image::ExifTool::CanonRaw::Main');
my $oldIndent = $$et{INDENT};
$$et{INDENT} .= '| ';
unless (ProcessCanonRaw($et, \%dirInfo, $rawTagTable)) {
$et->Warn('CRW file format error');
}
$$et{INDENT} = $oldIndent;
# finish building maker notes if necessary
$buildMakerNotes and SaveMakerNotes($et);
# process trailers if they exist in CRW file (not in CIFF information!)
if ($$et{FILE_TYPE} eq 'CRW') {
my $trailInfo = Image::ExifTool::IdentifyTrailer($raf);
$et->ProcessTrailers($trailInfo) if $trailInfo;
}
return 1;
}
1; # end
__END__
=head1 NAME
Image::ExifTool::CanonRaw - Read Canon RAW (CRW) meta information
=head1 SYNOPSIS
This module is loaded automatically by Image::ExifTool when required.
=head1 DESCRIPTION
This module contains definitions required by Image::ExifTool to interpret
meta information from Canon CRW raw files. These files are written directly
by some Canon cameras, and contain meta information similar to that found in
the EXIF Canon maker notes.
=head1 NOTES
The CR2 format written by some Canon cameras is very different the CRW
format processed by this module. (CR2 is TIFF-based and uses standard EXIF
tags.)
=head1 AUTHOR
Copyright 2003-2022, Phil Harvey (philharvey66 at gmail.com)
This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
=head1 REFERENCES
=over 4
=item L<http://www.cybercom.net/~dcoffin/dcraw/>
=item L<http://www.wonderland.org/crw/>
=item L<http://xyrion.org/ciff/>
=item L<https://exiftool.org/canon_raw.html>
=back
=head1 ACKNOWLEDGEMENTS
Thanks to Dave Nicholson for decoding a number of new tags.
=head1 SEE ALSO
L<Image::ExifTool::TagNames/CanonRaw Tags>,
L<Image::ExifTool::Canon(3pm)|Image::ExifTool::Canon>,
L<Image::ExifTool(3pm)|Image::ExifTool>
=cut
| mceachen/exiftool_vendored | bin/lib/Image/ExifTool/CanonRaw.pm | Perl | mit | 30,392 |
/*
Translation server. The call
regulus_language_server(<PortNumber>)
starts a translation server that accepts requests on the port <PortNumber>.
The following requests are supported:
Request: client(ClientHost).
Response: accept(ClientHost).
Request: call(Call).
Response: Call. [Call completed, instantiated version returned].
error. [Something went wrong]
Request: client_shutdown.
Response: thread_shutdown.
Note the periods after the requests and responses.
EXAMPLE SESSION
Client: client_shutdown.
Server: thread_shutdown
Socket code adapted from code at http://dlp.cs.vu.nl/~ctv/dlpinfo/srcs/tcp/sicsock.pl.html
*/
:- ensure_loaded('$REGULUS/PrologLib/compatibility').
%----------------------------------------------------------------------------------
:- asserta(library_directory('$REGULUS/PrologLib')).
:- asserta(library_directory('$REGULUS/Prolog')).
:- asserta(library_directory('$REGULUS/Alterf/Prolog')).
:- asserta(library_directory('.')).
%----------------------------------------------------------------------------------
:- use_module(library(regulus_top)).
:- use_module(library(ebl_make_training_data)).
:- use_module(library(ebl_train)).
:- use_module(library(ebl_postprocess)).
:- use_module(library(system)).
:- use_module(library(lists)).
:- use_module(library(sockets)).
:- use_module(library(utilities)).
%----------------------------------------------------------------------------------
% Don't use analysis timeouts in server for now - weird problems with interaction between sockets and timeout (?)
% Manny Rayner, Mar 29 2007
:- disable_timeouts.
%---------------------------------------------------------------
regulus_language_server :-
regulus_language_server(4321).
regulus_language_server(Port) :-
current_host(Host),
regulus_language_server(Host, Port).
%----------------------------------------------------------------------------------
regulus_language_server(_Host, Port) :-
%socket('AF_INET', Socket),
%socket_bind(Socket, 'AF_INET'(Host, Port)),
%socket_listen(Socket, 5),
safe_socket_server_open(Port, Socket),
%socket_accept(Socket, _Client, Stream),
safe_socket_server_accept(Socket, _Client, Stream),
regulus_language_server_loop(Stream),
socket_close(Socket),
format('Exit server~n', []),
halt.
regulus_language_server_loop(Stream) :-
repeat,
read(Stream, ClientRequest),
format('~N~nServer received: ~q~n', [ClientRequest]),
regulus_language_server_input(ClientRequest, ServerReply),
format(' ~nServer response: ~q~n', [ServerReply]),
regulus_language_server_reply(ServerReply, Stream),
ClientRequest == client_shutdown,
!.
regulus_language_server_input(ClientRequest, ServerReply) :-
ClientRequest = client(ClientHost),
!,
ServerReply = accept(ClientHost).
regulus_language_server_input(ClientRequest, ServerReply) :-
ClientRequest = call(Request),
!,
handle_regulus_language_action_request(Request, Response),
ServerReply = Response.
regulus_language_server_input(ClientRequest, ServerReply) :-
ClientRequest = end_of_file,
!,
ServerReply = client_shutdown.
regulus_language_server_input(ClientRequest, ServerReply) :-
ClientRequest = client_shutdown,
!,
ServerReply = thread_shutdown.
regulus_language_server_input(ClientRequest, ServerReply) :-
ServerReply = unknown_request(ClientRequest),
format('Unknown client request: ~w~n', [ClientRequest]).
%----------------------------------------------------------------------------------
regulus_language_server_reply(client_shutdown, _ServerOut) :-
format('Server: end of file.~n'),
!.
regulus_language_server_reply(ServerReply, ServerOut) :-
format(ServerOut, '~q.~n', [ServerReply]),
flush_output(ServerOut).
%----------------------------------------------------------------------------------
handle_regulus_language_action_request(Request, Response) :-
on_exception(
_Exception,
handle_regulus_language_action_request1(Request, Response),
Response = error
),
!.
handle_regulus_language_action_request(_Request, error) :-
!.
%----------------------------------------------------------------------------------
handle_regulus_language_action_request1(Call, Call) :-
call(Call),
!.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/regulus/RegulusLanguageServer/Prolog/server.pl | Perl | mit | 4,194 |
package Apache::ModPerimeterXTestUtils;
use 5.022001;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
# Items to export into callers namespace by default. Note: do not export
# names by default without a very good reason. Use EXPORT_OK instead.
# Do not simply export all your public functions/methods/constants.
# This allows declaration use Apache::ModPerimeterXTestUtils ':all';
# If you do not need this, moving things directly into @EXPORT or @EXPORT_OK
# will save memory.
our %EXPORT_TAGS = ( 'all' => [ qw(
) ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
#bake_cookie
our @EXPORT = qw(
valid_good_cookie
valid_bad_cookie
expired_cookie
);
sub bake_cookie {
use Crypt::KeyDerivation 'pbkdf2';
use Crypt::Misc 'encode_b64', 'decode_b64';
use Crypt::Mac::HMAC 'hmac_hex';
use Crypt::Mode::CBC;
my ( $ip, $ua, $score, $uuid, $vid, $time ) = @_;
my $data = $time . '0' . $score . $uuid . $vid . $ua;
my $password = 'perimeterx';
my $salt = '12345678123456781234567812345678';
my $iteration_count = 1000;
my $hash_name = undef; #default is SHA256
my $len = 48;
my $km = pbkdf2( $password, $salt, $iteration_count, $hash_name, $len );
my $key = substr( $km, 0, 32 );
my $iv = substr( $km, 32, 48 );
my $m = Crypt::Mode::CBC->new('AES');
my $hmac = hmac_hex( 'SHA256', $password, $data );
my $plaintext = '{"t":'
. $time
. ', "s":{"b":'
. $score
. ', "a":0}, "u":"'
. $uuid
. '", "v":"'
. $vid
. '", "h":"'
. $hmac . '"}';
my $ciphertext = $m->encrypt( $plaintext, $key, $iv );
my $cookie = encode_b64($salt) . ":" . 1000 . ":" . encode_b64($ciphertext);
return '_px=' . $cookie;
}
sub valid_good_cookie {
my $time = ( time() + 360 ) * 1000;
return bake_cookie(
"1.2.3.4",
"libwww-perl/0.00",
"20",
"57ecdc10-0e97-11e6-80b6-095df820282c",
"vid",
$time
);
}
sub valid_bad_cookie {
my $time = ( time() + 360 ) * 1000;
return bake_cookie(
"1.2.3.4",
"libwww-perl/0.00",
"100",
"57ecdc10-0e97-11e6-80b6-095df820282c",
"vid",
$time
);
}
sub expired_cookie {
my $expierd_time = ( time() - 24*60*60);
return bake_cookie(
"1.2.3.4",
"libwww-perl/0.00",
"20",
"57ecdc10-0e97-11e6-80b6-095df820282c",
"vid",
$expierd_time
);
}
our $VERSION = '0.01';
# Preloaded methods go here.
1;
__END__
# Below is stub documentation for your module. You'd better edit it!
=head1 NAME
Apache::ModPerimeterXTestUtils - Perl extension for mod_perimeterx Test utils
=head1 SYNOPSIS
use Apache::ModPerimeterXTestUtils;
=head1 DESCRIPTION
Stub documentation for Apache::ModPerimeterXTestUtils, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.
Blah blah blah.
=head2 EXPORT
bake_cookie
=head1 SEE ALSO
Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.
If you have a mailing list set up for your module, mention it here.
If you have a web site set up for your module, mention it here.
=head1 AUTHOR
Aviad Shikloshi, E<lt>aviad@perimeterx.com<gt>
=cut
| PerimeterX/mod_perimeterx | Apache-ModPerimeterXTestUtils/lib/Apache/ModPerimeterXTestUtils.pm | Perl | mit | 3,512 |
#!/usr/bin/perl -w
use strict;
use Statistics::ChisqIndep;
my $sUsage = qq(
perl $0
<homeolog_variation_sites.out>
<vcf file>
<minimum coverage depth>
<output file>
);
die $sUsage unless @ARGV >= 4;
my ($variation_file, $vcf_file, $mid_dep, $output) = @ARGV;
my $chisq_test = new Statistics::ChisqIndep;
my %snps = read_homeolog_variations($variation_file);
open (OUT, ">$output") or die;
print OUT join("\t", qw(SNP Allele_A Allele_B Depth_A Depth_B Pvalue1 Pvalue2)), "\n";
open (V, "$vcf_file") or die;
while (<V>)
{
# BobWhite_mira1_c10 610 . G A 81 . DP=54;VDB=0.0181;AF1=1;AC1=2;DP4=4,1,36,11;MQ=20;FQ=-90;PV4=1,5.1e-16,1,1 GT:PL:GQ 1/1:114,63,0:99
next if /^\#/;
my @t = split /\s+/,$_;
next if length $t[4] > 1;
my $id = join(":", @t[0,1]);
next unless exists $snps{$id};
my ($rf, $rb, $af, $ab) = $_=~/DP4=(\d+)\,(\d+)\,(\d+)\,(\d+)/;
my $total = sum($rf, $rb, $af, $ab);
next if $total < $mid_dep;
my $ref = $rf + $rb;
my $alt = $af + $ab;
$chisq_test->load_data([[sort{$a<=>$b}($ref, $alt)], [int($total/3), int($total*2/3)]]);
my $pvalue_1 = $chisq_test->p_value;
my $pvalue_2;
if($snps{$id} eq $t[3])
{
$chisq_test->load_data([[$ref, $alt], [int($total/3), int($total*2/3)]]);
$pvalue_2 = $chisq_test->p_value;
}
else
{
$chisq_test->load_data([[$alt, $ref], [int($total/3), int($total*2/3)]]);
$pvalue_2 = $chisq_test->p_value;
}
print OUT join("\t", (join(":", @t[0,1]), @t[3,4], $ref, $alt, $pvalue_1, $pvalue_2)), "\n";
}
close OUT;
close V;
sub read_homeolog_variations
{
my $file = shift;
open (IN, $file) or die;
my %return;
while (<IN>)
{
# Kukri_mira1_c31978:394:809 C G
# RAC875_mira1_c35029:1161:1390 G C,G
my $id = $1 if(/^(\S+?:\d+)/);
my @t = split /\s+/,$_;
if(length $t[1] == length $t[2])
{
$return{$id} = $t[1]
}
else
{
my @arr = split /,/, $t[2];
foreach (@arr)
{
$return{$id} = $_ unless $t[1] eq $_;
}
}
}
close IN;
return %return;
}
sub sum
{
my $return = 0;
map{$return += $_} @_;
return $return;
} | swang8/Perl_scripts_misc | chisq_test_for_homeolog_snps.pl | Perl | mit | 2,098 |
#!/usr/bin/perl -I..
################################################################
#
# Author(s) - Mark M. Gosink, Ph.D.
# Company - DSRD, Pfizer Inc.
#
# Creation Date - Wed Oct 28 11:47:48 EDT 2009
# Modified -
#
# Function - Update the MIM entries using the mim2gene file
#
################################################################
use conf::ToxGene_Defaults;
use Getopt::Long;
use DBI;
$result = GetOptions ('user=s' => \$username,
'pass=s' => \$password);
if (($username eq "") || ($password eq "")) {
die "\nUSAGE:\n\t$0 -u(ser) username -p(ass) password -i(d)\n\n";
}
# Set up mysql command and DBI mysql connection string
$dsn = "";
$mysql_cmd = "";
$db_name = $MiscVariables{DATABASE_NAME};
if ($MiscVariables{DATABASE_SOCKET} ne '') {
$dsn = $MiscVariables{DATABASE_TYPE}
. ':database=' . $MiscVariables{DATABASE_NAME}
. ':mysql_socket=' . $MiscVariables{DATABASE_SOCKET};
$mysql_cmd = 'mysql -S' . $MiscVariables{DATABASE_SOCKET} . ' -u' . $username . ' -p' . $password;
}
else {
$dsn = $MiscVariables{DATABASE_TYPE};
my $host = $MiscVariables{DATABASE_HOST};
my $port = $MiscVariables{DATABASE_PORT}
. ':database=' . $MiscVariables{DATABASE_NAME}
. ';host=' . $MiscVariables{DATABASE_HOST}
. ';port=' . $MiscVariables{DATABASE_PORT};
$mysql_cmd = 'mysql -P' . $port . ' -h' . $host . ' -u' . $username . ' -p' . $password;
}
$db_handle = DBI->connect( $dsn, $username, $password, { PrintError => 1 })
or die "Can't connect to the database!!\n\n";
$date = `date`;
chomp($date);
log_err("Running '$0' on '$date'.");
#Required files
$mim2gene_file = $SetupFiles{MIM2GENE};
my @FileInfo = split(/\s+/, `ls -l $mim2gene_file`);
$mim2gene_file_date = $FileInfo[5] . ' ' . $FileInfo[6] . ' ' . $FileInfo[7];
$dominant_omim_file = '../data/omim_result.txt';
my @FileInfo = split(/\s+/, `ls -l $mim2gene_file`);
$mim2gene_file_date = $FileInfo[5] . ' ' . $FileInfo[6] . ' ' . $FileInfo[7];
if ((not(-s $mim2gene_file)) || (not(-T $mim2gene_file))) {
die "\n\tRequired OMIM to Gene file not found or in wrong format at '$mim2gene_file'!\n\n";
}
elsif ((not(-s $dominant_omim_file)) || (not(-T $dominant_omim_file))) {
die "\n\tRequired OMIM dominants file not found or in wrong format at '$dominant_omim_file'!\n\n";
}
# first find out the current MIM GENE pairs
%Entrez_2_idGene = ();
my $sql = "SELECT idGene, entrezID FROM Gene";
$statement = $db_handle->prepare($sql);
$statement->execute;
while (@Row = $statement->fetchrow_array) {
my $idgene = $Row[0];
my $entrezid = $Row[1];
$Entrez_2_idGene{$entrezid} = $idgene;
}
%OMIM_2_idXref = ();
%OMIM_Type = ();
%OMIM_Entrez = ();
my $sql = "SELECT X.idXref, X.Xref_ID, X.Xref_Source, G.idGene, G.entrezID"
. " FROM Xref X, Gene G"
. " WHERE X.idGene = G.idGene"
. " AND (X.Xref_Source = 'MIM' OR X.Xref_Source = 'MIM_DOM')";
$statement = $db_handle->prepare($sql);
$statement->execute;
while (@Row = $statement->fetchrow_array) {
my $idxref = $Row[0];
my $xref_id = $Row[1];
my $xref_source = $Row[2];
my $idgene = $Row[3];
my $entrezid = $Row[4];
$OMIM_2_idXref{$xref_id} = $idxref;
$OMIM_Type{$xref_id} = $xref_source;
$OMIM_Entrez{$xref_id}{$entrezid}++;
}
# generate an updated list of pairs
%Updated_OMIM_Entrez = ();
%Updated_OMIM_Type = ();
open (FILE, $mim2gene_file);
while ($line = <FILE>) {
chomp($line);
if ($line =~ /^#/) { next } # skip comment lines
my ($omim_id, $entrez_id, undef) = split(/\t/, $line);
$Updated_OMIM_Entrez{$omim_id}{$entrez_id}++;
$Updated_OMIM_Type{$omim_id} = 'MIM';
}
close(FILE);
open (FILE, $dominant_omim_file);
while ($line = <FILE>) {
chomp($line);
if ($line =~ /^OMIM:\s+(\d+)/) {
my $dom_omim_id = $1;
my @Genes = keys(%{$Updated_OMIM_Entrez{$dom_omim_id}});
foreach $gene_id (@Genes) {
$Updated_OMIM_Entrez{$dom_omim_id}{$gene_id}++;
$Updated_OMIM_Type{$dom_omim_id} = 'MIM_DOM';
}
}
}
close(FILE);
# next, compare the database to existing pairs
$sql_file = './tmp_files/Update_MIMXrefs.sql';
open(OUTFILE, ">$sql_file");
print OUTFILE "use $db_name;\n";
print OUTFILE "SET autocommit=0;\n";
print OUTFILE "START TRANSACTION;\n";
foreach $omim_id (keys %Updated_OMIM_Type) {
my $type = $Updated_OMIM_Type{$omim_id};
if (not defined $OMIM_Type{$omim_id}) {
# need to add new omim xref entry and its gene links
@Genes = keys(%{$Updated_OMIM_Entrez{$omim_id}});
foreach $entrez_id (@Genes) {
my $idgene = $Entrez_2_idGene{$entrez_id};
if ($idgene eq "") {
print "Warning A! Could not find an idGene entry for Entrez ID '$entrez_id', therefore couldn't add '$omim_id'\n";
}
else {
print OUTFILE "INSERT INTO Xref (idGene, Xref_Source, Xref_ID) VALUES ($idgene, '$type', '$omim_id');\n";
}
}
}
else {
if ($OMIM_Type{$omim_id} ne $Updated_OMIM_Type{$omim_id}) {
# need to update the OMIM type
my $idxref = $OMIM_2_idXref{$omim_id};
if ($idxref eq "") {
print "Warning B! Could not find an idXref entry for OMIM ID '$omim_id' '$type'\n";
}
else {
print OUTFILE "UPDATE Xref SET Xref_Source = '$type' WHERE idXref = '$idxref';\n";
}
}
my @Genes = keys(%{$Updated_OMIM_Entrez{$omim_id}});
foreach $gene_id (@Genes) {
if (not defined $OMIM_Entrez{$omim_id}{$gene_id}) {
my $idgene = $Entrez_2_idGene{$gene_id};
if ($idgene eq "") {
print "Warning C! Could not find an idGene entry for Entrez ID '$gene_id', therefore couldn't add '$omim_id'\n";
}
else {
print OUTFILE "INSERT INTO Xref (idGene, Xref_Source, Xref_ID) VALUES ($idgene, '$type', '$omim_id');\n";
}
}
}
}
}
print OUTFILE "COMMIT;\n";
close(OUTFILE);
$date = `date`;
chomp($date);
log_err("\t... loading '$sql_file' on '$date'.");
$cmd = $mysql_cmd . ' < ' . $sql_file;
`$cmd`;
$date = `date`;
chomp($date);
log_err("Finished '$0' on '$date'.");
exit;
sub make_sql_safe {
my $term = $_[0];
$term =~ s/\\/\\\\/g;
$term =~ s/'/\\'/g;
$term =~ s/"/\\"/g;
return $term;
}
sub log_err {
my $msg = $_[0];
my $log_file = $0 . ".log";
open (LOG, ">>$log_file");
print LOG "$msg\n";
close(LOG);
}
| mgosink/ToxReporter | scripts/Step_06b_Update_MIMXrefs.pl | Perl | mit | 6,077 |
#!/usr/bin/perl
use strict;
use warnings;
use lib "..", "../web";
use Defs;
use DBI;
use Utils;
use Passport;
use MCache;
use Lang;
use Log;
main();
sub main {
my $db = connectDB();
my $lang = Lang->get_handle() || die "Can't get a language handle!";
my $passport = new Passport( db => $db );
my %Data = (
db => $db,
lang => $lang,
cache => new MCache(),
Realm => undef,
);
my $st = qq[
select distinct m.intMemberID, m.strEmail
from tblPassportMember pm
inner join tblMember m on m.intMemberID = pm.intMemberID;
];
my $q = $db->prepare($st);
$q->execute();
my $counter = 0;
while ( my $record = $q->fetchrow_hashref() ) {
$counter++;
my $memberID = $record->{intMemberID};
my $email = $record->{strEmail};
$passport->addModule( 'SPMEMBERSHIPADMIN', $email );
}
INFO "Fixed $counter umpires";
$q->finish();
disconnectDB();
}
| facascante/slimerp | fifs/misc/fix_passport_umpires.pl | Perl | mit | 1,036 |
# I wanted to do this with a shell script but I can't think of a way
# without negating a backreference, which isn't possible.
# I got this far:
#
# cat 7.txt | ggrep -Pv '\[.*(.)(.)\2\1.*\]' | ggrep -P '(.)(.)\2\1'
#
# Which incorrectly matches aaaa[qwer]tyui - it should fail because
# aaaa is not a valid abba form. I want to do something like
# (.)([^\1])\2\1 - but that isn't valid because the backreference could be
# N chars and a char class matches one. Something like it is possible with lookahead
# but that doesn't work here because I need to consume and capture the match.
# So a script it is!
my $count = 0;
while (my $line=<>) {
# print $line
if ($line !~ /\[[^\[\]]*?(.)(.)\2\1[^\[\]]*?\]/) {
while ($line =~ /((.)(.)\3\2)/g) {
if ($3 ne $2) {
$count ++;
last;
}
}
}
}
print $count | jwhitfieldseed/advent-of-code | 2016/7a.pl | Perl | mit | 826 |
package WorkspaceCreator;
# ************************************************************
# Description : Base class for all workspace creators
# Author : Chad Elliott
# Create Date : 5/13/2002
# ************************************************************
# ************************************************************
# Pragmas
# ************************************************************
use strict;
use FileHandle;
use File::Path;
use Creator;
use Options;
use WorkspaceHelper;
use vars qw(@ISA);
@ISA = qw(Creator Options);
# ************************************************************
# Data Section
# ************************************************************
my $wsext = 'mwc';
my $wsbase = 'mwb';
## Valid names for assignments within a workspace
my %validNames = ('cmdline' => 1,
'implicit' => 1,
);
## Singleton hash maps of project information
my %allprinfo;
my %allprojects;
my %allliblocs;
## Global previous workspace names
my %previous_workspace_name;
## Constant aggregated workspace type name
my $aggregated = 'aggregated_workspace';
my $onVMS = DirectoryManager::onVMS();
# ************************************************************
# Subroutine Section
# ************************************************************
sub new {
my($class, $global, $inc, $template, $ti, $dynamic, $static, $relative, $addtemp, $addproj, $progress, $toplevel, $baseprojs, $gfeature, $relative_f, $feature, $features, $hierarchy, $exclude, $makeco, $nmod, $applypj, $genins, $into, $language, $use_env, $expandvars, $gendot, $comments, $foreclipse) = @_;
my $self = Creator::new($class, $global, $inc,
$template, $ti, $dynamic, $static,
$relative, $addtemp, $addproj,
$progress, $toplevel, $baseprojs,
$feature, $features,
$hierarchy, $nmod, $applypj,
$into, $language, $use_env, $expandvars,
'workspace');
## These need to be reset at the end of each
## workspace processed within a .mwc file
$self->{'workspace_name'} = undef;
$self->{'projects'} = [];
$self->{'project_info'} = {};
$self->{'project_files'} = [];
$self->{'modified_count'} = 0;
$self->{'exclude'} = {};
$self->{'associated'} = {};
$self->{'scoped_assign'} = {};
## These are maintained/modified throughout processing
$self->{$self->{'type_check'}} = 0;
$self->{'cacheok'} = 1;
$self->{'lib_locations'} = {};
$self->{'reading_parent'} = [];
$self->{'global_feature_file'} = $gfeature;
$self->{'relative_file'} = $relative_f;
$self->{'project_file_list'} = {};
$self->{'ordering_cache'} = {};
$self->{'handled_scopes'} = {};
$self->{'scoped_basedir'} = undef;
## These are static throughout processing
$self->{'coexistence'} = $makeco;
$self->{'for_eclipse'} = $foreclipse;
$self->{'generate_dot'} = $gendot;
$self->{'generate_ins'} = $genins;
$self->{'into'} = $into;
$self->{'verbose_ordering'} = undef;
$self->{'wctype'} = $self->extractType("$self");
$self->{'workspace_comments'} = $comments;
if (defined $$exclude[0]) {
my $type = $self->{'wctype'};
if (!defined $self->{'exclude'}->{$type}) {
$self->{'exclude'}->{$type} = [];
}
push(@{$self->{'exclude'}->{$type}}, @$exclude);
$self->{'orig_exclude'} = $self->{'exclude'};
}
else {
$self->{'orig_exclude'} = {};
}
## Add a hash reference for our workspace type
if (!defined $previous_workspace_name{$self->{'wctype'}}) {
$previous_workspace_name{$self->{'wctype'}} = {};
}
## Warn users about unnecessary options
if ($self->get_hierarchy() && $self->workspace_per_project()) {
$self->warning("The -hierarchy option is unnecessary " .
"for the " . $self->{'wctype'} . " type.");
}
if ($self->make_coexistence() && !$self->supports_make_coexistence()) {
$self->warning("Using the -make_coexistence option has " .
"no effect on the " . $self->{'wctype'} . " type.");
}
return $self;
}
sub set_verbose_ordering {
my($self, $value) = @_;
$self->{'verbose_ordering'} = $value;
}
sub modify_assignment_value {
my($self, $name, $value) = @_;
## Workspace assignments do not need modification.
return $value;
}
sub parse_line {
my($self, $ih, $line, $flags) = @_;
my($status, $error, @values) = $self->parse_known($line);
## Was the line recognized?
if ($status && defined $values[0]) {
if ($values[0] eq $self->{'grammar_type'}) {
my $name = $values[1];
if (defined $name && $name eq '}') {
if (!defined $self->{'reading_parent'}->[0]) {
## Fill in all the default values
$self->generate_defaults();
## End of workspace; Have subclass write out the file
## Generate the project files
my($gstat, $creator, $err) = $self->generate_project_files();
if ($gstat) {
($status, $error) = $self->write_workspace($creator, 1);
$self->{'assign'} = {};
}
else {
$error = $err;
$status = 0;
}
$self->{'modified_count'} = 0;
$self->{'workspace_name'} = undef;
$self->{'projects'} = [];
$self->{'project_info'} = {};
$self->{'project_files'} = [];
$self->{'exclude'} = $self->{'orig_exclude'};
$self->{'associated'} = {};
$self->{'scoped_assign'} = {};
}
$self->{$self->{'type_check'}} = 0;
}
else {
## Workspace Beginning
## Deal with the inheritance hiearchy first
if (defined $values[2]) {
foreach my $parent (@{$values[2]}) {
## Read in the parent onto ourself
my $file = $self->search_include_path("$parent.$wsbase");
if (!defined $file) {
$file = $self->search_include_path("$parent.$wsext");
}
if (defined $file) {
push(@{$self->{'reading_parent'}}, 1);
$status = $self->parse_file($file);
pop(@{$self->{'reading_parent'}});
$error = "Invalid parent: $parent" if (!$status);
}
else {
$status = 0;
$error = "Unable to locate parent: $parent";
}
}
}
## Set up some initial values
if (defined $name) {
if ($name =~ /[\/\\]/) {
$status = 0;
$error = 'Workspaces can not have a slash ' .
'or a back slash in the name';
}
else {
$name =~ s/^\(\s*//;
$name =~ s/\s*\)$//;
## Replace any *'s with the default name
if (index($name, '*') >= 0) {
$name = $self->fill_type_name(
$name,
$self->get_default_workspace_name());
}
$self->{'workspace_name'} = $name;
}
}
$self->{$self->{'type_check'}} = 1;
}
}
elsif ($values[0] eq '0') {
if (defined $validNames{$values[1]}) {
$self->process_assignment($values[1], $values[2], $flags);
}
else {
$error = "Invalid assignment name: '$values[1]'";
$status = 0;
}
}
elsif ($values[0] eq '1') {
if (defined $validNames{$values[1]}) {
$self->process_assignment_add($values[1], $values[2], $flags);
}
else {
$error = "Invalid addition name: $values[1]";
$status = 0;
}
}
elsif ($values[0] eq '-1') {
if (defined $validNames{$values[1]}) {
$self->process_assignment_sub($values[1], $values[2], $flags);
}
else {
$error = "Invalid subtraction name: $values[1]";
$status = 0;
}
}
elsif ($values[0] eq 'component') {
my %copy = %{defined $flags ? $flags : $self->get_assignment_hash()};
($status, $error) = $self->parse_scope($ih,
$values[1],
$values[2],
\%validNames,
\%copy);
}
else {
$error = "Unrecognized line: $line";
$status = 0;
}
}
elsif ($status == -1) {
## If the line contains a variable, try to replace it with an actual
## value.
$line = $self->relative($line) if (index($line, '$') >= 0);
foreach my $expfile ($line =~ /[\?\*\[\]]/ ? $self->mpc_glob($line) :
$line) {
if ($expfile =~ /\.$wsext$/) {
my %copy = %{defined $flags ? $flags : $self->get_assignment_hash()};
($status, $error) = $self->aggregated_workspace($expfile, \%copy);
last if (!$status);
}
else {
push(@{$self->{'project_files'}}, $expfile);
$status = 1;
}
}
}
return $status, $error;
}
sub aggregated_workspace {
my($self, $file, $flags) = @_;
my $fh = new FileHandle();
if (open($fh, $file)) {
my $oline = $self->get_line_number();
my $tc = $self->{$self->{'type_check'}};
my $ag = $self->{'handled_scopes'}->{$aggregated};
my $psbd = $self->{'scoped_basedir'};
my($status, $error, @values) = (0, 'No recognizable lines');
$self->{'handled_scopes'}->{$aggregated} = undef;
$self->set_line_number(0);
$self->{$self->{'type_check'}} = 0;
$self->{'scoped_basedir'} = $self->mpc_dirname($file);
while(<$fh>) {
my $line = $self->preprocess_line($fh, $_);
($status, $error, @values) = $self->parse_known($line);
## Was the line recognized?
if ($status) {
if (defined $values[0]) {
if ($values[0] eq $self->{'grammar_type'}) {
if (defined $values[2]) {
my $name = $self->mpc_basename($file);
$name =~ s/\.[^\.]+$//;
$status = 0;
$error = 'Aggregated workspace (' . $name .
') can not inherit from another workspace';
}
else {
($status, $error) = $self->parse_scope($fh,
'',
$aggregated,
\%validNames,
$flags);
}
}
else {
$status = 0;
$error = 'Unable to aggregate ' . $file;
}
last;
}
}
else {
last;
}
}
close($fh);
$self->{'scoped_basedir'} = $psbd;
$self->{'handled_scopes'}->{$aggregated} = $ag;
$self->{$self->{'type_check'}} = $tc;
$self->set_line_number($oline);
return $status, $error;
}
return 0, 'Unable to open ' . $file;
}
sub parse_scope {
my($self, $fh, $name, $type, $validNames, $flags, $elseflags) = @_;
if ($type eq $self->get_default_component_name()) {
$type = $self->{'wctype'};
}
if ($name eq 'exclude') {
return $self->parse_exclude($fh, $type, $flags);
}
elsif ($name eq 'associate') {
return $self->parse_associate($fh, $type);
}
else {
return $self->SUPER::parse_scope($fh, $name, $type,
$validNames, $flags, $elseflags);
}
}
sub process_types {
my($self, $typestr) = @_;
my %types;
@types{split(/\s*,\s*/, $typestr)} = ();
## If there is a negation at all, add our
## current type, it may be removed below
if (index($typestr, '!') >= 0) {
$types{$self->{wctype}} = 1;
## Process negated exclusions
foreach my $key (keys %types) {
if ($key =~ /^!\s*(\w+)/) {
## Remove the negated key
delete $types{$key};
## Then delete the key that was negated in the exclusion.
delete $types{$1};
}
}
}
return \%types;
}
sub parse_exclude {
my($self, $fh, $typestr, $flags) = @_;
my $status = 0;
my $errorString = 'Unable to process exclude';
my $negated = (index($typestr, '!') >= 0);
my @exclude;
my $types = $self->process_types($typestr);
my $count = 1;
if (exists $$types{$self->{wctype}}) {
while(<$fh>) {
my $line = $self->preprocess_line($fh, $_);
if ($line eq '') {
}
elsif ($line =~ /^}(.*)$/) {
--$count;
if (defined $1 && $1 ne '') {
$status = 0;
$errorString = "Trailing characters found: '$1'";
}
else {
$status = 1;
$errorString = undef;
}
last if ($count == 0);
}
else {
if ($line =~ /^(\w+)\s*(\([^\)]+\))?\s*{$/) {
++$count;
}
elsif ($self->parse_assignment($line, [])) {
## Ignore all assignments
}
else {
if ($line =~ /^"([^"]+)"$/) {
$line = $1;
}
## If the line contains a variable, try to replace it with an
## actual value.
$line = $self->relative($line) if (index($line, '$') >= 0);
if (defined $self->{'scoped_basedir'} &&
$self->path_is_relative($line)) {
$line = $self->{'scoped_basedir'} . '/' . $line;
}
if ($line =~ /[\?\*\[\]]/) {
push(@exclude, $self->mpc_glob($line));
}
else {
push(@exclude, $line);
}
}
}
}
foreach my $type (keys %$types) {
if (!defined $self->{'exclude'}->{$type}) {
$self->{'exclude'}->{$type} = [];
}
push(@{$self->{'exclude'}->{$type}}, @exclude);
}
}
else {
if ($negated) {
($status, $errorString) = $self->SUPER::parse_scope($fh,
'exclude',
$typestr,
\%validNames,
$flags);
}
else {
## If this exclude block didn't match the current type and the
## exclude wasn't negated, we need to eat the exclude block so that
## these lines don't get included into the workspace.
while(<$fh>) {
my $line = $self->preprocess_line($fh, $_);
if ($line =~ /^(\w+)\s*(\([^\)]+\))?\s*{$/) {
++$count;
}
elsif ($line =~ /^}(.*)$/) {
--$count;
if (defined $1 && $1 ne '') {
$status = 0;
$errorString = "Trailing characters found: '$1'";
}
else {
$status = 1;
$errorString = undef;
}
last if ($count == 0);
}
}
}
}
return $status, $errorString;
}
sub parse_associate {
my($self, $fh, $assoc_key) = @_;
my $status = 0;
my $errorString = 'Unable to process associate';
my $count = 1;
my @projects;
if (!defined $self->{'associated'}->{$assoc_key}) {
$self->{'associated'}->{$assoc_key} = {};
}
while(<$fh>) {
my $line = $self->preprocess_line($fh, $_);
if ($line eq '') {
}
elsif ($line =~ /^}(.*)$/) {
--$count;
if (defined $1 && $1 ne '') {
$errorString = "Trailing characters found: '$1'";
last;
}
else {
$status = 1;
$errorString = undef;
}
last if ($count == 0);
}
else {
if ($line =~ /^(\w+)\s*(\([^\)]+\))?\s*{$/) {
++$count;
}
elsif ($self->parse_assignment($line, [])) {
$errorString = 'Assignments are not ' .
'allowed within an associate scope';
last;
}
else {
if ($line =~ /^"([^"]+)"$/) {
$line = $1;
}
## If the line contains a variable, try to replace it with an
## actual value.
$line = $self->relative($line) if (index($line, '$') >= 0);
if (defined $self->{'scoped_basedir'} &&
$self->path_is_relative($line)) {
$line = $self->{'scoped_basedir'} . '/' . $line;
}
if ($line =~ /[\?\*\[\]]/) {
foreach my $file ($self->mpc_glob($line)) {
$self->{'associated'}->{$assoc_key}->{$file} = 1;
}
}
else {
$self->{'associated'}->{$assoc_key}->{$line} = 1;
}
}
}
}
return $status, $errorString;
}
sub excluded {
my($self, $file) = @_;
foreach my $excluded (@{$self->{'exclude'}->{$self->{'wctype'}}}) {
return 1 if ($excluded eq $file || index($file, "$excluded/") == 0);
}
return 0;
}
sub handle_scoped_end {
my($self, $type, $flags) = @_;
my $status = 1;
my $error;
if ($type eq $aggregated &&
!defined $self->{'handled_scopes'}->{$type}) {
## Replace instances of $PWD with the current directory plus the
## scoped_basedir. We have to do it now otherwise, $PWD will be the
## wrong directory if it's done later.
if (defined $$flags{'cmdline'}) {
my $dir = $self->getcwd() . '/' . $self->{'scoped_basedir'};
$$flags{'cmdline'} =~ s/\$PWD(\W)/$dir$1/g;
$$flags{'cmdline'} =~ s/\$PWD$/$dir/;
}
## Go back to the previous directory and add the directory contents
($status, $error) = $self->handle_scoped_unknown(undef, $type, $flags, '.');
}
$self->{'handled_scopes'}->{$type} = undef;
return $status, $error;
}
sub handle_scoped_unknown {
my($self, $fh, $type, $flags, $line) = @_;
my $status = 1;
my $error;
my $dupchk;
if ($line =~ /^\w+.*{/) {
if (defined $fh) {
my @values;
my $tc = $self->{$self->{'type_check'}};
$self->{$self->{'type_check'}} = 1;
($status, $error, @values) = $self->parse_line($fh, $line, $flags);
$self->{$self->{'type_check'}} = $tc;
}
else {
$status = 0;
$error = 'Unhandled line: ' . $line;
}
return $status, $error;
}
## If the line contains a variable, try to replace it with an actual
## value.
$line = $self->relative($line) if (index($line, '$') >= 0);
if (defined $self->{'scoped_basedir'}) {
if ($self->path_is_relative($line)) {
$line = $self->{'scoped_basedir'} . ($line ne '.' ? "/$line" : '');
}
my %dup;
@dup{@{$self->{'project_files'}}} = ();
$dupchk = \%dup;
## If the aggregated workspace contains a scope (other than exclude)
## it will be processed in the block above and we will eventually get
## here, but by that time $type will no longer be $aggregated. So,
## we just need to set it here to ensure that we don't add everything
## in the scoped_basedir directory in handle_scoped_end()
$self->{'handled_scopes'}->{$aggregated} = 1;
}
if (-d $line) {
my @files;
$self->search_for_files([ $line ], \@files, $$flags{'implicit'});
## If we are generating implicit projects within a scope, then
## we need to remove directories and the parent directories for which
## there is an mpc file. Otherwise, the projects will be added
## twice.
if ($$flags{'implicit'}) {
my %remove;
foreach my $file (@files) {
if ($file =~ /\.mpc$/) {
my $exc = $file;
do {
$exc = $self->mpc_dirname($exc);
$remove{$exc} = 1;
} while($exc ne '.' && $exc !~ /[a-z]:[\/\\]/i);
}
}
my @acceptable;
foreach my $file (@files) {
push(@acceptable, $file) if (!defined $remove{$file});
}
@files = @acceptable;
}
foreach my $file (@files) {
if (!$self->excluded($file)) {
if (defined $dupchk && exists $$dupchk{$file}) {
$self->warning("Duplicate mpc file ($file) added by an " .
'aggregate workspace. It will be ignored.');
}
else {
$self->{'scoped_assign'}->{$file} = $flags;
push(@{$self->{'project_files'}}, $file);
}
}
}
}
else {
foreach my $expfile ($line =~ /[\?\*\[\]]/ ? $self->mpc_glob($line) :
$line) {
if ($expfile =~ /\.$wsext$/) {
## An aggregated workspace within an aggregated workspace or scope.
($status, $error) = $self->aggregated_workspace($expfile, $flags);
last if (!$status);
}
else {
if (!$self->excluded($expfile)) {
if (defined $dupchk && exists $$dupchk{$expfile}) {
$self->warning("Duplicate mpc file ($expfile) added by an " .
'aggregate workspace. It will be ignored.');
}
else {
$self->{'scoped_assign'}->{$expfile} = $flags;
push(@{$self->{'project_files'}}, $expfile);
}
}
}
}
}
$self->{'handled_scopes'}->{$type} = 1;
return $status, $error;
}
sub search_for_files {
my($self, $files, $array, $impl) = @_;
my $excluded = 0;
foreach my $file (@$files) {
if (-d $file) {
my @f = $self->generate_default_file_list(
$file,
$self->{'exclude'}->{$self->{'wctype'}},
\$excluded);
$self->search_for_files(\@f, $array, $impl);
if ($impl) {
$file =~ s/^\.\///;
# Strip out ^ symbols
$file =~ s/\^//g if ($onVMS);
unshift(@$array, $file);
}
}
else {
if ($file =~ /\.mpc$/) {
$file =~ s/^\.\///;
# Strip out ^ symbols
$file =~ s/\^//g if ($onVMS);
unshift(@$array, $file);
}
}
}
return $excluded;
}
sub remove_duplicate_projects {
my($self, $list) = @_;
my $count = scalar(@$list);
for(my $i = 0; $i < $count; ++$i) {
my $file = $$list[$i];
foreach my $inner (@$list) {
if ($file ne $inner &&
$file eq $self->mpc_dirname($inner) && ! -d $inner) {
splice(@$list, $i, 1);
--$count;
--$i;
last;
}
}
}
}
sub generate_default_components {
my($self, $files, $impl, $excluded) = @_;
my $pjf = $self->{'project_files'};
if (defined $$pjf[0]) {
## If we have files, then process directories
my @built;
foreach my $file (@$pjf) {
if (!$self->excluded($file)) {
if (-d $file) {
my @found;
my @gen = $self->generate_default_file_list(
$file,
$self->{'exclude'}->{$self->{'wctype'}});
$self->search_for_files(\@gen, \@found, $impl);
push(@built, @found);
if ($impl || $self->{'scoped_assign'}->{$file}->{'implicit'}) {
push(@built, $file);
}
}
else {
push(@built, $file);
}
}
}
## If the workspace is set to implicit remove duplicates from this
## list.
$self->remove_duplicate_projects(\@built) if ($impl);
## Set the project files
$self->{'project_files'} = \@built;
}
else {
## Add all of the wanted files in this directory
## and in the subdirectories.
$excluded |= $self->search_for_files($files, $pjf, $impl);
## If the workspace is set to implicit remove duplicates from this
## list.
$self->remove_duplicate_projects($pjf) if ($impl);
## If no files were found, then we push the empty
## string, so the Project Creator will generate
## the default project file.
push(@$pjf, '') if (!defined $$pjf[0] && !$excluded);
}
}
sub get_default_workspace_name {
my $self = shift;
my $name = $self->{'current_input'};
if ($name eq '') {
$name = $self->base_directory();
}
else {
## Since files on UNIX can have back slashes, we transform them
## into underscores.
$name =~ s/\\/_/g;
## Take off the extension
$name =~ s/\.[^\.]+$//;
}
return $name;
}
sub generate_defaults {
my $self = shift;
## Generate default workspace name
if (!defined $self->{'workspace_name'}) {
$self->{'workspace_name'} = $self->get_default_workspace_name();
}
## Modify the exclude list if we have changed directory from the original
## starting directory. Just take off the difference from the front.
my @original;
my $top = $self->getcwd() . '/';
my $start = $self->getstartdir() . '/';
if ($start ne $top && $top =~ s/^$start//) {
foreach my $exclude (@{$self->{'exclude'}->{$self->{'wctype'}}}) {
push(@original, $exclude);
$exclude =~ s/^$top//;
}
}
my $excluded = 0;
my @files = $self->generate_default_file_list(
'.',
$self->{'exclude'}->{$self->{'wctype'}},
\$excluded);
## Generate default components
$self->generate_default_components(\@files,
$self->get_assignment('implicit'),
$excluded);
## Return the actual exclude list of we modified it
if (defined $original[0]) {
$self->{'exclude'}->{$self->{'wctype'}} = \@original;
}
}
sub get_workspace_name {
return $_[0]->{'workspace_name'};
}
sub get_current_output_name {
return $_[0]->{'current_output'};
}
sub write_and_compare_file {
my($self, $outdir, $oname, $func, @params) = @_;
my $fh = new FileHandle();
my $error = undef;
## Set the output directory if one wasn't provided
$outdir = $self->get_outdir() if (!defined $outdir);
## Create the full name and pull off the directory. The directory
## portion may not be the same as $outdir, since $name could possibly
## contain a directory portion too.
my $name = "$outdir/$oname";
my $dir = $self->mpc_dirname($name);
## Make the full path if necessary
mkpath($dir, 0, 0777) if ($dir ne '.');
## Set the current output data member to our file's full name
$self->{'current_output'} = $name;
if ($self->compare_output()) {
## First write the output to a temporary file
my $tmp = "$outdir/MWC$>.$$";
my $different = 1;
if (open($fh, ">$tmp")) {
&$func($self, $fh, @params);
close($fh);
$different = 0 if (!$self->files_are_different($name, $tmp));
}
else {
$error = "Unable to open $tmp for output.";
}
if (!defined $error) {
if ($different) {
unlink($name);
$error = "Unable to open $name for output" if (!rename($tmp, $name));
}
else {
## There is no need to rename, so remove our temp file.
unlink($tmp);
}
}
}
else {
if (open($fh, ">$name")) {
&$func($self, $fh, @params);
close($fh);
}
else {
$error = "Unable to open $name for output.";
}
}
return $error;
}
sub write_workspace {
my($self, $creator, $addfile) = @_;
my $status = 1;
my $error;
my $duplicates = 0;
if ($self->get_toplevel()) {
## There is usually a progress indicator callback provided, but if
## the output is being redirected, there will be no progress
## indicator.
my $progress = $self->get_progress_callback();
&$progress() if (defined $progress);
if ($addfile) {
## To be consistent across multiple project types, we disallow
## duplicate project names for all types, not just VC6.
## Note that these name are handled case-insensitive by VC6
my %names;
foreach my $project (@{$self->{'projects'}}) {
my $name = lc($self->{'project_info'}->{$project}->[0]);
if (defined $names{$name}) {
++$duplicates;
$self->error("Duplicate case-insensitive project '$name'. " .
"Look in " . $self->mpc_dirname($project) .
" and " . $self->mpc_dirname($names{$name}) .
" for project name conflicts.");
}
else {
$names{$name} = $project;
}
}
}
else {
$self->{'per_project_workspace_name'} = 1;
}
my $name = $self->transform_file_name($self->workspace_file_name());
my $abort_creation = 0;
if ($duplicates > 0) {
$abort_creation = 1;
$error = "Duplicate case-insensitive project names are " .
"not allowed within a workspace.";
$status = 0;
}
else {
if (!defined $self->{'projects'}->[0]) {
$self->information('No projects were created.');
$abort_creation = 1;
}
}
if (!$abort_creation) {
## Verify and possibly modify the dependencies
if ($addfile) {
$self->verify_build_ordering();
}
if ($addfile || !$self->file_written($name)) {
$error = $self->write_and_compare_file(
undef, $name,
sub {
my($self, $fh) = @_;
$self->pre_workspace($fh, $creator, $addfile);
$self->write_comps($fh, $creator, $addfile);
my $wsHelper = WorkspaceHelper::get($self);
$wsHelper->perform_custom_processing($fh, $creator, $addfile);
$self->post_workspace($fh, $creator, $addfile);
});
if (defined $error) {
$status = 0;
}
else {
$self->add_file_written($name) if ($addfile);
}
}
my $additional = $self->get_additional_output();
foreach my $entry (@$additional) {
$error = $self->write_and_compare_file(@$entry);
if (defined $error) {
$status = 0;
last;
}
}
if ($addfile && $self->{'generate_dot'}) {
my $dh = new FileHandle();
my $wsname = $self->get_workspace_name();
if (open($dh, ">$wsname.dot")) {
my %targnum;
my @list = $self->number_target_deps($self->{'projects'},
$self->{'project_info'},
\%targnum, 0);
print $dh "digraph $wsname {\n";
foreach my $project (@{$self->{'projects'}}) {
if (defined $targnum{$project}) {
my $pname = $self->{'project_info'}->{$project}->[0];
foreach my $number (@{$targnum{$project}}) {
print $dh " $pname -> ",
"$self->{'project_info'}->{$list[$number]}->[0];\n";
}
}
}
print $dh "}\n";
close($dh);
}
else {
$self->warning("Unable to write to $wsname.dot.");
}
}
}
$self->{'per_project_workspace_name'} = undef if (!$addfile);
}
return $status, $error;
}
sub save_project_info {
my($self, $gen, $gpi, $gll, $dir, $projects, $pi, $ll) = @_;
my $c = 0;
## For each file written
foreach my $pj (@$gen) {
## Save the full path to the project file in the array
my $full = ($dir ne '.' ? "$dir/" : '') . $pj;
push(@$projects, $full);
## Get the corresponding generated project info and save it
## in the hash map keyed on the full project file name
$$pi{$full} = $$gpi[$c];
$c++;
}
foreach my $key (keys %$gll) {
$$ll{$key} = $$gll{$key};
}
}
sub topname {
my($self, $file) = @_;
my $dir = '.';
my $rest = $file;
if ($file =~ /^([^\/\\]+)[\/\\](.*)/) {
$dir = $1;
$rest = $2;
}
return $dir, $rest;
}
sub generate_hierarchy {
my($self, $creator, $origproj, $originfo) = @_;
my $current;
my @saved;
my %sinfo;
my $cwd = $self->getcwd();
## Make a copy of these. We will be modifying them.
## It is necessary to sort the projects to get the correct ordering.
## Projects in the current directory must come before projects in
## other directories.
my @projects = sort { return $self->sort_projects_by_directory($a, $b) + 0;
} @{$origproj};
my %projinfo = %{$originfo};
foreach my $prj (@projects) {
my($top, $rest) = $self->topname($prj);
if (!defined $current) {
$current = $top;
push(@saved, $rest);
$sinfo{$rest} = $projinfo{$prj};
}
elsif ($top ne $current) {
if ($current ne '.') {
## Write out the hierachical workspace
$self->cd($current);
$self->generate_hierarchy($creator, \@saved, \%sinfo);
$self->{'projects'} = \@saved;
$self->{'project_info'} = \%sinfo;
$self->{'workspace_name'} = $self->base_directory();
my($status, $error) = $self->write_workspace($creator);
$self->error($error) if (!$status);
$self->cd($cwd);
}
## Start the next one
$current = $top;
@saved = ($rest);
%sinfo = ();
$sinfo{$rest} = $projinfo{$prj};
}
else {
push(@saved, $rest);
$sinfo{$rest} = $projinfo{$prj};
}
}
if (defined $current && $current ne '.') {
$self->cd($current);
$self->generate_hierarchy($creator, \@saved, \%sinfo);
$self->{'projects'} = \@saved;
$self->{'project_info'} = \%sinfo;
$self->{'workspace_name'} = $self->base_directory();
my($status, $error) = $self->write_workspace($creator);
$self->error($error) if (!$status);
$self->cd($cwd);
}
}
sub generate_project_files {
my $self = shift;
my $status = (scalar @{$self->{'project_files'}} == 0 ? 1 : 0);
my @projects;
my %pi;
my %liblocs;
my $creator = $self->project_creator();
my $cwd = $self->getcwd();
my $impl = $self->get_assignment('implicit');
my $postkey = $creator->get_dynamic() .
$creator->get_static() . "-$self";
my $previmpl = $impl;
my $prevcache = $self->{'cacheok'};
my %gstate = $creator->save_state();
my $genimpdep = $self->generate_implicit_project_dependencies();
## Save this project creator setting for later use in the
## number_target_deps() method.
$self->{'dependency_is_filename'} = $creator->dependency_is_filename();
## Remove the address portion of the $self string
$postkey =~ s/=.*//;
## Set the source file callback on our project creator
$creator->set_source_listing_callback([\&source_listing_callback, $self]);
foreach my $ofile (@{$self->{'project_files'}}) {
if (!$self->excluded($ofile)) {
my $file = $ofile;
my $dir = $self->mpc_dirname($file);
my $restore = 0;
if (defined $self->{'scoped_assign'}->{$ofile}) {
## Handle the implicit assignment
my $oi = $self->{'scoped_assign'}->{$ofile}->{'implicit'};
if (defined $oi) {
$previmpl = $impl;
$impl = $oi;
}
## Handle the cmdline assignment
my $cmdline = $self->{'scoped_assign'}->{$ofile}->{'cmdline'};
if (defined $cmdline && $cmdline ne '') {
## Save the cacheok value
$prevcache = $self->{'cacheok'};
## Get the current parameters and process the command line
my %parameters = $self->current_parameters();
$self->process_cmdline($cmdline, \%parameters);
## Set the parameters on the creator
$creator->restore_state(\%parameters);
$restore = 1;
}
}
## If we are generating implicit projects and the file is a
## directory, then we set the dir to the file and empty the file
if ($impl && -d $file) {
$dir = $file;
$file = '';
## If the implicit assignment value was not a number, then
## we will add this value to our base projects.
if ($impl !~ /^\d+$/) {
my $bps = $creator->get_baseprojs();
push(@$bps, split(/\s+/, $impl));
$restore = 1;
$self->{'cacheok'} = 0;
}
}
## Generate the key for this project file
my $prkey = $self->getcwd() . '/' .
($file eq '' ? $dir : $file) . "-$postkey";
## We must change to the subdirectory for
## which this project file is intended
if ($self->cd($dir)) {
my $files_written = [];
my $gen_proj_info = [];
my $gen_lib_locs = {};
if ($self->{'cacheok'} && defined $allprojects{$prkey}) {
$files_written = $allprojects{$prkey};
$gen_proj_info = $allprinfo{$prkey};
$gen_lib_locs = $allliblocs{$prkey};
$status = 1;
}
else {
$status = $creator->generate($self->mpc_basename($file));
## If any one project file fails, then stop
## processing altogether.
if (!$status) {
## We don't restore the state before we leave,
## but that's ok since we will be exiting right now.
return $status, $creator,
"Unable to process " . ($file eq '' ? " in $dir" : $file);
}
## Get the individual project information and
## generated file name(s)
$files_written = $creator->get_files_written();
$gen_proj_info = $creator->get_project_info();
$gen_lib_locs = $creator->get_lib_locations();
if ($self->{'cacheok'}) {
$allprojects{$prkey} = $files_written;
$allprinfo{$prkey} = $gen_proj_info;
$allliblocs{$prkey} = $gen_lib_locs;
}
}
$self->cd($cwd);
$self->save_project_info($files_written, $gen_proj_info,
$gen_lib_locs, $dir,
\@projects, \%pi, \%liblocs);
}
else {
## Unable to change to the directory.
## We don't restore the state before we leave,
## but that's ok since we will be exiting soon.
return 0, $creator, "Unable to change directory to $dir";
}
## Return things to the way they were
$impl = $previmpl if (defined $self->{'scoped_assign'}->{$ofile});
if ($restore) {
$self->{'cacheok'} = $prevcache;
$creator->restore_state(\%gstate);
}
}
else {
## This one was excluded, so status is ok
$status = 1;
}
}
## Add implict project dependencies based on source files
## that have been used by multiple projects. If we do it here
## before we call generate_hierarchy(), we don't have to call it
## in generate_hierarchy() for each workspace.
$self->{'projects'} = \@projects;
$self->{'project_info'} = \%pi;
if ($status && $genimpdep) {
$self->add_implicit_project_dependencies($creator, $cwd);
}
## If we are generating the hierarchical workspaces, then do so
$self->{'lib_locations'} = \%liblocs;
if ($self->get_hierarchy() || $self->workspace_per_project()) {
my $orig = $self->{'workspace_name'};
$self->generate_hierarchy($creator, \@projects, \%pi);
$self->{'workspace_name'} = $orig;
}
## Reset the projects and project_info
$self->{'projects'} = \@projects;
$self->{'project_info'} = \%pi;
return $status, $creator;
}
sub array_contains {
my($self, $left, $right) = @_;
my %check;
## Initialize the hash keys with the left side array
@check{@$left} = ();
## Check each element on the right against the left.
foreach my $r (@$right) {
return 1 if (exists $check{$r});
}
return 0;
}
sub non_intersection {
my($self, $left, $right, $over) = @_;
my $status = 0;
my %check;
## Initialize the hash keys with the left side array
@check{@$left} = ();
## Check each element on the right against the left.
## Store anything that isn't in the left side in the over array.
foreach my $r (@$right) {
if (exists $check{$r}) {
$status = 1;
}
else {
push(@$over, $r);
}
}
return $status;
}
sub indirect_dependency {
my($self, $dir, $ccheck, $cfile) = @_;
$self->{'indirect_checked'}->{$ccheck} = 1;
if (index($self->{'project_info'}->{$ccheck}->[1], $cfile) >= 0) {
return 1;
}
else {
my $deps = $self->create_array(
$self->{'project_info'}->{$ccheck}->[1]);
foreach my $dep (@$deps) {
if (defined $self->{'project_info'}->{"$dir$dep"} &&
!defined $self->{'indirect_checked'}->{"$dir$dep"} &&
$self->indirect_dependency($dir, "$dir$dep", $cfile)) {
return 1;
}
}
}
return 0;
}
sub add_implicit_project_dependencies {
my($self, $creator, $cwd) = @_;
my %bidir;
my %save;
## Take the current working directory and regular expression'ize it.
$cwd = $self->escape_regex_special($cwd);
## Look at each projects file list and check it against all of the
## others. If any of the other projects file lists contains anothers
## file, then they are dependent (due to build parallelism). So, we
## append the dependency and remove the file in question from the
## project so that the next time around the foreach, we don't find it
## as a dependent on the one that we just modified.
my @pflkeys = keys %{$self->{'project_file_list'}};
foreach my $key (@pflkeys) {
foreach my $ikey (@pflkeys) {
## Not the same project and
## The same directory and
## We've not already added a dependency to this project
if ($key ne $ikey &&
($self->{'project_file_list'}->{$key}->[1] eq
$self->{'project_file_list'}->{$ikey}->[1]) &&
(!defined $bidir{$ikey} ||
!$self->array_contains($bidir{$ikey}, [$key]))) {
my @over;
if ($self->non_intersection(
$self->{'project_file_list'}->{$key}->[2],
$self->{'project_file_list'}->{$ikey}->[2],
\@over)) {
## The project contains shared source files, so we need to
## look into adding an implicit inter-project dependency.
$save{$ikey} = $self->{'project_file_list'}->{$ikey}->[2];
$self->{'project_file_list'}->{$ikey}->[2] = \@over;
if (defined $bidir{$key}) {
push(@{$bidir{$key}}, $ikey);
}
else {
$bidir{$key} = [$ikey];
}
my $append = $creator->translate_value('after', $key);
my $file = $self->{'project_file_list'}->{$ikey}->[0];
my $dir = $self->{'project_file_list'}->{$ikey}->[1];
my $cfile = $creator->translate_value('after', $ikey);
## Remove our starting directory from the projects directory
## to get the right part of the directory to prepend.
$dir =~ s/^$cwd[\/\\]*//;
## Turn the append value into a key for 'project_info' and
## prepend the directory to the file.
my $ccheck = $append;
$ccheck =~ s/"//g;
if ($dir ne '') {
$dir .= '/';
$ccheck = "$dir$ccheck";
$file = "$dir$file";
}
## If the append value key contains a reference to the project
## that we were going to append the dependency value, then
## ignore the generated dependency. It is redundant and
## quite possibly wrong.
$self->{'indirect_checked'} = {};
if (defined $self->{'project_info'}->{$file} &&
(!defined $self->{'project_info'}->{$ccheck} ||
!$self->indirect_dependency($dir, $ccheck, $cfile))) {
## Append the dependency
$self->{'project_info'}->{$file}->[1] .= " $append";
}
}
}
}
}
## Restore the modified values in case this method is called again
## which is the case when using the -hierarchy option.
foreach my $skey (keys %save) {
$self->{'project_file_list'}->{$skey}->[2] = $save{$skey};
}
}
sub get_projects {
return $_[0]->{'projects'};
}
sub get_project_info {
return $_[0]->{'project_info'};
}
sub get_lib_locations {
return $_[0]->{'lib_locations'};
}
sub get_first_level_directory {
my($self, $file) = @_;
if (($file =~ tr/\///) > 0) {
my $dir = $file;
$dir =~ s/^([^\/]+\/).*/$1/;
$dir =~ s/\/+$//;
return $dir;
}
return '.';
}
sub get_associated_projects {
return $_[0]->{'associated'};
}
sub sort_within_group {
my($self, $list, $start, $end) = @_;
my $deps;
my %seen;
my $ccount = 0;
my $cmax = ($end - $start) + 1;
my $previ = -1;
my $prevpjs = [];
my $movepjs = [];
## Put the projects in the order specified
## by the project dpendencies.
for(my $i = $start; $i <= $end; ++$i) {
## If our moved project equals our previously moved project then
## we count this as a possible circular dependency.
my $key = "@$list";
if ($seen{$key} ||
(defined $$movepjs[0] && defined $$prevpjs[0] &&
$$movepjs[0] == $$prevpjs[0] && $$movepjs[1] == $$prevpjs[1])) {
++$ccount;
}
else {
$ccount = 0;
}
## Detect circular dependencies
if ($ccount > $cmax) {
my @prjs;
foreach my $mvgr (@$movepjs) {
push(@prjs, $$list[$mvgr]);
}
my $other = $$movepjs[0] - 1;
if ($other < $start || $other == $$movepjs[1] || !defined $$list[$other]) {
$other = undef;
}
$self->warning('Circular dependency detected while processing the ' .
($self->{'current_input'} eq '' ?
'default' : $self->{'current_input'}) .
' workspace. ' .
'The following projects are involved: ' .
(defined $other ? "$$list[$other], " : '') .
join(' and ', @prjs));
return;
}
## Keep track of the previous project movement
$seen{$key} = 1;
$prevpjs = $movepjs;
$movepjs = [] if ($previ < $i);
$previ = $i;
$deps = $self->get_validated_ordering($$list[$i]);
if (defined $$deps[0]) {
my $baseproj = ($self->{'dependency_is_filename'} ?
$self->mpc_basename($$list[$i]) :
$self->{'project_info'}->{$$list[$i]}->[0]);
my $moved = 0;
foreach my $dep (@$deps) {
if ($baseproj ne $dep) {
## See if the dependency is listed after this project
for(my $j = $i + 1; $j <= $end; ++$j) {
my $ldep = ($self->{'dependency_is_filename'} ?
$self->mpc_basename($$list[$j]) :
$self->{'project_info'}->{$$list[$j]}->[0]);
if ($ldep eq $dep) {
$movepjs = [$i, $j];
## If so, move it in front of the current project.
## The original code, which had splices, didn't always
## work correctly (especially on AIX for some reason).
my $save = $$list[$j];
for(my $k = $j; $k > $i; --$k) {
$$list[$k] = $$list[$k - 1];
}
$$list[$i] = $save;
## Mark that an entry has been moved
$moved = 1;
$j--;
}
}
}
}
--$i if ($moved);
}
}
}
sub build_dependency_chain {
my($self, $name, $len, $list, $ni, $glen, $groups, $map, $gdeps) = @_;
my $deps = $self->get_validated_ordering($name);
if (defined $$deps[0]) {
foreach my $dep (@$deps) {
## Find the item in the list that matches our current dependency
my $mapped = $$map{$dep};
if (defined $mapped) {
for(my $i = 0; $i < $len; $i++) {
if ($$list[$i] eq $mapped) {
## Locate the group number to which the dependency belongs
for(my $j = 0; $j < $glen; $j++) {
if ($i >= $$groups[$j]->[0] && $i <= $$groups[$j]->[1]) {
if ($j != $ni) {
## Add every project in the group to the dependency chain
for(my $k = $$groups[$j]->[0]; $k <= $$groups[$j]->[1]; $k++) {
my $ldep = $self->mpc_basename($$list[$k]);
if (!exists $$gdeps{$ldep}) {
$$gdeps{$ldep} = 1;
$self->build_dependency_chain($$list[$k],
$len, $list, $j,
$glen, $groups,
$map, $gdeps);
}
}
}
last;
}
}
last;
}
}
}
$$gdeps{$dep} = 1;
}
}
}
sub sort_by_groups {
my($self, $list, $grindex) = @_;
my @groups = @$grindex;
my $llen = scalar(@$list);
## Check for duplicates first before we attempt to sort the groups.
## If there is a duplicate, we quietly return immediately. The
## duplicates will be flagged as an error when creating the main
## workspace.
my %dupcheck;
foreach my $proj (@$list) {
my $base = $self->mpc_basename($proj);
return undef if (defined $dupcheck{$base});
$dupcheck{$base} = $proj;
}
my %circular_checked;
for(my $gi = 0; $gi <= $#groups; ++$gi) {
## Detect circular dependencies
if (!$circular_checked{$gi}) {
$circular_checked{$gi} = 1;
for(my $i = $groups[$gi]->[0]; $i <= $groups[$gi]->[1]; ++$i) {
my %gdeps;
$self->build_dependency_chain($$list[$i], $llen, $list, $gi,
$#groups + 1, \@groups,
\%dupcheck, \%gdeps);
if (exists $gdeps{$self->mpc_basename($$list[$i])}) {
## There was a cirular dependency, get all of the directories
## involved.
my %dirs;
foreach my $gdep (keys %gdeps) {
$dirs{$self->mpc_dirname($dupcheck{$gdep})} = 1;
}
## If the current directory was involved, translate that into
## a directory relative to the start directory.
if (defined $dirs{'.'}) {
my $cwd = $self->getcwd();
my $start = $self->getstartdir();
if ($cwd ne $start) {
my $startre = $self->escape_regex_special($start);
delete $dirs{'.'};
$cwd =~ s/^$startre[\\\/]//;
$dirs{$cwd} = 1;
}
}
## Display a warining to the user
my @keys = sort keys %dirs;
$self->warning('Circular directory dependency detected in the ' .
($self->{'current_input'} eq '' ?
'default' : $self->{'current_input'}) .
' workspace. ' .
'The following director' .
($#keys == 0 ? 'y is' : 'ies are') .
' involved: ' . join(', ', @keys));
return;
}
}
}
## Build up the group dependencies
my %gdeps;
for(my $i = $groups[$gi]->[0]; $i <= $groups[$gi]->[1]; ++$i) {
my $deps = $self->get_validated_ordering($$list[$i]);
@gdeps{@$deps} = () if (defined $$deps[0]);
}
## Search the rest of the groups for any of the group dependencies
for(my $gj = $gi + 1; $gj <= $#groups; ++$gj) {
for(my $i = $groups[$gj]->[0]; $i <= $groups[$gj]->[1]; ++$i) {
if (exists $gdeps{$self->mpc_basename($$list[$i])}) {
## Move this group ($gj) in front of the current group ($gi)
my @save;
for(my $j = $groups[$gi]->[1] + 1; $j <= $groups[$gj]->[1]; ++$j) {
push(@save, $$list[$j]);
}
my $offset = $groups[$gj]->[1] - $groups[$gi]->[1];
for(my $j = $groups[$gi]->[1]; $j >= $groups[$gi]->[0]; --$j) {
$$list[$j + $offset] = $$list[$j];
}
for(my $j = 0; $j <= $#save; ++$j) {
$$list[$groups[$gi]->[0] + $j] = $save[$j];
}
## Update the group indices
my $shiftamt = ($groups[$gi]->[1] - $groups[$gi]->[0]) + 1;
for(my $j = $gi + 1; $j <= $gj; ++$j) {
$groups[$j]->[0] -= $shiftamt;
$groups[$j]->[1] -= $shiftamt;
}
my @grsave = @{$groups[$gi]};
$grsave[0] += $offset;
$grsave[1] += $offset;
for(my $j = $gi; $j < $gj; ++$j) {
$groups[$j] = $groups[$j + 1];
$circular_checked{$j} = $circular_checked{$j + 1};
}
$groups[$gj] = \@grsave;
$circular_checked{$gj} = 1;
## Start over from the first group
$gi = -1;
## Exit from the outter ($gj) loop
$gj = $#groups;
last;
}
}
}
}
}
sub sort_dependencies {
my($self, $projects, $groups) = @_;
my @list = sort { return $self->sort_projects_by_directory($a, $b) + 0;
} @$projects;
## The list above is sorted by directory in order to keep projects
## within the same directory together. Otherwise, when groups are
## created we may get multiple groups for the same directory.
## Put the projects in the order specified
## by the project dpendencies. We only need to do
## this if there is more than one element in the array.
if ($#list > 0) {
## If the parameter wasn't passed in or it was passed in
## and was true, sort with directory groups in mind
if (!defined $groups || $groups) {
## First determine the individual groups
my @grindex;
my $previous = [0, undef];
for(my $li = 0; $li <= $#list; ++$li) {
my $dir = $self->get_first_level_directory($list[$li]);
if (!defined $previous->[1]) {
$previous = [$li, $dir];
}
elsif ($previous->[1] ne $dir) {
push(@grindex, [$previous->[0], $li - 1]);
$previous = [$li, $dir];
}
}
push(@grindex, [$previous->[0], $#list]);
## Next, sort the individual groups
foreach my $gr (@grindex) {
$self->sort_within_group(\@list, @$gr) if ($$gr[0] != $$gr[1]);
}
## Now sort the groups as single entities
$self->sort_by_groups(\@list, \@grindex) if ($#grindex > 0);
}
else {
$self->sort_within_group(\@list, 0, $#list);
}
}
return @list;
}
sub number_target_deps {
my($self, $projects, $pjs, $targets, $groups) = @_;
my @list = $self->sort_dependencies($projects, $groups);
## This block of code must be done after the list of dependencies
## has been sorted in order to get the correct project numbers.
for(my $i = 0; $i <= $#list; ++$i) {
my $project = $list[$i];
if (defined $$pjs{$project}) {
my($name, $deps) = @{$$pjs{$project}};
if (defined $deps && $deps ne '') {
my @numbers;
my %dhash;
@dhash{@{$self->create_array($deps)}} = ();
## For each dependency, search in the sorted list
## up to the point of this project for the projects
## that this one depends on. When the project is
## found, we put the target number in the numbers array.
for(my $j = 0; $j < $i; ++$j) {
## If the dependency is a filename, then take the basename of
## the project file. Otherwise, get the project name based on
## the project file from the "project_info".
my $key = ($self->{'dependency_is_filename'} ?
$self->mpc_basename($list[$j]) :
$self->{'project_info'}->{$list[$j]}->[0]);
push(@numbers, $j) if (exists $dhash{$key});
}
## Store the array in the hash keyed on the project file.
$$targets{$project} = \@numbers if (defined $numbers[0]);
}
}
}
return @list;
}
sub project_target_translation {
my($self, $case) = @_;
my %map;
## Translate project names to avoid target collision with
## some versions of make.
foreach my $key (keys %{$self->{'project_info'}}) {
my $dir = $self->mpc_dirname($key);
my $name = $self->{'project_info'}->{$key}->[0];
## We want to compare to the upper most directory. This will be the
## one that may conflict with the project name.
$dir =~ s/[\/\\].*//;
if (($case && $dir eq $name) || (!$case && lc($dir) eq lc($name))) {
$map{$key} = "$name-target";
}
else {
$map{$key} = $name;
}
}
return \%map;
}
sub optionError {
my($self, $str) = @_;
$self->warning("$self->{'current_input'}: $str.") if (defined $str);
}
sub process_cmdline {
my($self, $cmdline, $parameters) = @_;
## It's ok to use the cache
$self->{'cacheok'} = 1;
if (defined $cmdline && $cmdline ne '') {
my $args = $self->create_array($cmdline);
## Look for environment variables
foreach my $arg (@$args) {
while($arg =~ /\$(\w+)/) {
my $name = $1;
my $val = '';
if ($name eq 'PWD') {
$val = $self->getcwd();
}
elsif (defined $ENV{$name}) {
$val = $ENV{$name};
}
$arg =~ s/\$\w+/$val/;
}
}
my $options = $self->options('MWC', {}, 0, @$args);
if (defined $options) {
foreach my $key (keys %$options) {
my $type = $self->is_set($key, $options);
if (!defined $type) {
## This option was not used, so we ignore it
}
elsif ($type eq 'ARRAY') {
push(@{$parameters->{$key}}, @{$options->{$key}});
}
elsif ($type eq 'HASH') {
foreach my $hk (keys %{$options->{$key}}) {
$parameters->{$key}->{$hk} = $options->{$key}->{$hk};
}
}
elsif ($type eq 'SCALAR') {
$parameters->{$key} = $options->{$key};
}
}
## Some option data members are named consistently with the MPC
## option name. In this case, we can use this foreach loop.
foreach my $consistent_opt ('exclude', 'for_eclipse', 'gendot',
'gfeature_file', 'into',
'make_coexistence', 'recurse') {
## Issue warnings for the options provided by the user
if ($self->is_set($consistent_opt, $options)) {
$self->optionError("-$consistent_opt is ignored");
}
}
## For those that are inconsistent, we have special code to deal
## with them.
if ($self->is_set('reldefs', $options)) {
$self->optionError('-noreldefs is ignored');
}
## Make sure no input files were specified (we can't handle it).
if (defined $options->{'input'}->[0]) {
$self->optionError('Command line files ' .
'specified in a workspace are ignored');
}
## Determine if it's ok to use the cache
my @cacheInvalidating = ('global', 'include', 'baseprojs',
'template', 'ti', 'relative', 'language',
'addtemp', 'addproj', 'feature_file',
'features', 'use_env', 'expand_vars');
foreach my $key (@cacheInvalidating) {
if ($self->is_set($key, $options)) {
$self->{'cacheok'} = 0;
last;
}
}
}
}
}
sub current_parameters {
my $self = shift;
my %parameters = $self->save_state();
## We always want the project creator to generate a toplevel
$parameters{'toplevel'} = 1;
return %parameters;
}
sub project_creator {
my $self = shift;
my $str = "$self";
## NOTE: If the subclassed WorkspaceCreator name prefix does not
## match the name prefix of the ProjectCreator, this code
## will not work and the subclassed WorkspaceCreator will
## need to override this method.
$str =~ s/Workspace/Project/;
$str =~ s/=HASH.*//;
## Set up values for each project creator
## If we have command line arguments in the workspace, then
## we process them before creating the project creator
my $cmdline = $self->get_assignment('cmdline');
my %parameters = $self->current_parameters();
$self->process_cmdline($cmdline, \%parameters);
## Create the new project creator with the updated parameters
return $str->new($parameters{'global'},
$parameters{'include'},
$parameters{'template'},
$parameters{'ti'},
$parameters{'dynamic'},
$parameters{'static'},
$parameters{'relative'},
$parameters{'addtemp'},
$parameters{'addproj'},
$parameters{'progress'},
$parameters{'toplevel'},
$parameters{'baseprojs'},
$self->{'global_feature_file'},
$parameters{'relative_file'},
$parameters{'feature_file'},
$parameters{'features'},
$parameters{'hierarchy'},
$self->{'exclude'}->{$self->{'wctype'}},
$self->make_coexistence(),
$parameters{'name_modifier'},
$parameters{'apply_project'},
$self->{'generate_ins'} || $parameters{'genins'},
$self->{'into'},
$parameters{'language'},
$parameters{'use_env'},
$parameters{'expand_vars'},
$self->{'gendot'},
$parameters{'comments'},
$self->{'for_eclipse'});
}
sub sort_files {
#my $self = shift;
return 0;
}
sub make_coexistence {
return $_[0]->{'coexistence'};
}
sub get_modified_workspace_name {
my($self, $name, $ext, $nows) = @_;
my $nmod = $self->get_name_modifier();
my $oname = $name;
if (defined $nmod) {
$nmod =~ s/\*/$name/g;
$name = $nmod;
}
## If this is a per project workspace, then we should not
## modify the workspace name. It may overwrite another workspace
## but that's ok, it will only be a per project workspace.
## Also, if we don't want the workspace name attached ($nows) then
## we just return the name plus the extension.
return "$name$ext" if ($nows || $self->{'per_project_workspace_name'});
my $pwd = $self->getcwd();
my $type = $self->{'wctype'};
my $wsname = $self->get_workspace_name();
if (!defined $previous_workspace_name{$type}->{$pwd}) {
$previous_workspace_name{$type}->{$pwd} = $wsname;
$self->{'current_workspace_name'} = undef;
}
else {
my $prefix = ($oname eq $wsname ? $name : "$name.$wsname");
$previous_workspace_name{$type}->{$pwd} = $wsname;
while($self->file_written("$prefix" .
($self->{'modified_count'} > 0 ?
".$self->{'modified_count'}" : '') .
"$ext")) {
++$self->{'modified_count'};
}
$self->{'current_workspace_name'} =
"$prefix" . ($self->{'modified_count'} > 0 ?
".$self->{'modified_count'}" : '') . "$ext";
}
return (defined $self->{'current_workspace_name'} ?
$self->{'current_workspace_name'} : "$name$ext");
}
sub generate_recursive_input_list {
my($self, $dir, $exclude) = @_;
return $self->extension_recursive_input_list($dir, $exclude, $wsext);
}
sub verify_build_ordering {
my $self = shift;
foreach my $project (@{$self->{'projects'}}) {
$self->get_validated_ordering($project);
}
}
sub get_validated_ordering {
my($self, $project) = @_;
my $deps;
if (defined $self->{'ordering_cache'}->{$project}) {
$deps = $self->{'ordering_cache'}->{$project};
}
else {
$deps = [];
if (defined $self->{'project_info'}->{$project}) {
my($name, $dstr) = @{$self->{'project_info'}->{$project}};
if (defined $dstr && $dstr ne '') {
$deps = $self->create_array($dstr);
my $dlen = scalar(@$deps);
for(my $i = 0; $i < $dlen; $i++) {
my $dep = $$deps[$i];
my $found = 0;
## Avoid circular dependencies
if ($dep ne $name && $dep ne $self->mpc_basename($project)) {
foreach my $p (@{$self->{'projects'}}) {
if ($dep eq $self->{'project_info'}->{$p}->[0] ||
$dep eq $self->mpc_basename($p)) {
$found = 1;
last;
}
}
if (!$found) {
if ($self->{'verbose_ordering'}) {
$self->warning("'$name' references '$dep' which has " .
"not been processed.");
}
splice(@$deps, $i, 1);
--$dlen;
--$i;
}
}
else {
## If a project references itself, we must remove it
## from the list of dependencies.
splice(@$deps, $i, 1);
--$dlen;
--$i;
}
}
}
$self->{'ordering_cache'}->{$project} = $deps;
}
}
return $deps;
}
sub source_listing_callback {
my $self = shift;
my $project_file = shift;
my $project_name = shift;
my $cwd = $self->getcwd();
$self->{'project_file_list'}->{$project_name} = [ $project_file,
$cwd, \@_ ];
}
sub sort_projects_by_directory {
my($self, $left, $right) = @_;
my $sa = index($left, '/');
my $sb = index($right, '/');
if ($sa >= 0 && $sb == -1) {
return 1;
}
elsif ($sb >= 0 && $sa == -1) {
return -1;
}
return $left cmp $right;
}
sub get_relative_dep_file {
my($self, $creator, $project, $dep) = @_;
## If the dependency is a filename, we have to find the key that
## matches the project file.
if ($creator->dependency_is_filename()) {
foreach my $key (keys %{$self->{'project_file_list'}}) {
if ($self->{'project_file_list'}->{$key}->[0] eq $dep) {
$dep = $key;
last;
}
}
}
if (defined $self->{'project_file_list'}->{$dep}) {
my $base = $self->{'project_file_list'}->{$dep}->[1];
my @dirs = grep(!/^$/, split('/', $base));
my $last = -1;
$project =~ s/^\///;
for(my $i = 0; $i <= $#dirs; $i++) {
my $dir = $dirs[$i];
if ($project =~ s/^$dir\///) {
$last = $i;
}
else {
last;
}
}
my $dependee = $self->{'project_file_list'}->{$dep}->[0];
if ($last == -1) {
return $base . '/' . $dependee;
}
else {
my $built = '';
for(my $i = $last + 1; $i <= $#dirs; $i++) {
$built .= $dirs[$i] . '/';
}
$built .= $dependee;
my $dircount = ($project =~ tr/\///);
return ('../' x $dircount) . $built;
}
}
return undef;
}
sub create_command_line_string {
my $self = shift;
my @args = @_;
my $str;
foreach my $arg (@args) {
$arg =~ s/^\-\-/-/;
$arg = "\"$arg\"" if ($arg =~ /[\s\*]/);
if (defined $str) {
$str .= " $arg";
}
else {
$str = $arg;
}
}
return $str;
}
sub print_workspace_comment {
my $self = shift;
my $fh = shift;
if ($self->{'workspace_comments'}) {
foreach my $line (@_) {
print $fh $line;
}
}
}
sub get_initial_relative_values {
my $self = shift;
return $self->get_relative(), $self->get_expand_vars();
}
sub get_secondary_relative_values {
return \%ENV, $_[0]->get_expand_vars();
}
sub convert_all_variables {
#my $self = shift;
return 1;
}
sub workspace_file_name {
my $self = shift;
return $self->get_modified_workspace_name($self->get_workspace_name(),
$self->workspace_file_extension());
}
sub relative {
my $self = shift;
my $line = $self->SUPER::relative(shift);
$line =~ s/\\/\//g;
return $line;
}
# ************************************************************
# Virtual Methods To Be Overridden
# ************************************************************
sub supports_make_coexistence {
#my $self = shift;
return 0;
}
sub generate_implicit_project_dependencies {
#my $self = shift;
return 0;
}
sub workspace_file_extension {
#my $self = shift;
return '';
}
sub workspace_per_project {
#my $self = shift;
return 0;
}
sub pre_workspace {
#my $self = shift;
#my $fh = shift;
#my $creator = shift;
#my $top = shift;
}
sub write_comps {
#my $self = shift;
#my $fh = shift;
#my $creator = shift;
#my $top = shift;
}
sub post_workspace {
#my $self = shift;
#my $fh = shift;
#my $creator = shift;
#my $top = shift;
}
sub requires_forward_slashes {
#my $self = shift;
return 0;
}
sub get_additional_output {
#my $self = shift;
## This method should return an array reference of array references.
## For each entry, the array should be laid out as follows:
## [ <directory or undef to use the current output directory>,
## <file name>,
## <function to write body of file, $self and $fh are first params>,
## <optional additional parameter 1>,
## ...,
## <optional additional parameter N>
## ]
return [];
}
1;
| binghuo365/BaseLab | 3rd/ACE-5.7.0/ACE_wrappers/MPC/modules/WorkspaceCreator.pm | Perl | mit | 69,121 |
#!/usr/bin/perl -w
use strict;
use warnings;
use lib "./lib";
# use loadconf;
# my %pref = &loadconf::loadConf;
package getNCBI;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(getNCBI);
our $DESCRIPTION = "Returns NCBI entrances from NCBI IDs with custom headers
\tAccepts as input any NCBI reference number (GI,GB,REF,etc) separated by new lines (enter)
\te.g.\n\tEF636668\n\t209863141\n\tNM_001045191\n\tCR457022
\tAccepts as input fasta files separated by new lines (enter)
\te.g.>gi|165881902|gb|EU192366.1| Malassezia pachydermatis strain ATCC 14522 18S ribosomal RNA gene, partial sequence
\tTTTGGGCTTTGGTGAATATAATAACTTCTCGGATCGCATGGCCTTGTGCCGGCGATGCTTCATTCAAATA
\tTCTGCCCTATCAACTGTCGATGGTAGGATAGAGGCCTACCATGGTTGCAACGGGTAACGGGGAATAAGGG
\t
\t>gi|113681126|ref|NP_001038656.1| si:dkey-98n4.1 [Danio rerio]
\tMSNGAAGSGGLTWVTLFDKNNGAKKEEMNGRGDAGKSEVVKKESSKKMSVERIYQKKTQLEHILLRPDTY
\tIGSVEPVTQQMWVFDEEIGMNLREISFVPGLYKIFDEILVNAADNKQRDKNMTTIKITIDPESNTISVWN
\tReturns a fasta file containing SPECIES NAME _ STRAIN _ ACC NUMBER
\tif SPECIES NAME is not found, Taxon ID is placed
\tSTRAIN only appears when the word \"strain\" appears in the text. then, the next 2 words will be used
";
use Bio::DB::GenBank;
use Bio::SeqIO::fasta;
# &getNCBI("EF636668\n209863141\n209862803\nNM_001045191\nCR457022\n>gi|165881902|gb|EU192366.1| Malassezia pachydermatis strain ATCC 14522 18S ribosomal RNA gene, partial sequence
# TTTGGGCTTTGGTGAATATAATAACTTCTCGGATCGCATGGCCTTGTGCCGGCGATGCTTCATTCAAATA
# TCTGCCCTATCAACTGTCGATGGTAGGATAGAGGCCTACCATGGTTGCAACGGGTAACGGGGAATAAGGG
#
# >gi|113681126|ref|NP_001038656.1| si:dkey-98n4.1 [Danio rerio]
# MSNGAAGSGGLTWVTLFDKNNGAKKEEMNGRGDAGKSEVVKKESSKKMSVERIYQKKTQLEHILLRPDTY
# IGSVEPVTQQMWVFDEEIGMNLREISFVPGLYKIFDEILVNAADNKQRDKNMTTIKITIDPESNTISVWN","getNCBI");
sub getNCBI
{
my $input = $_[0]; # body of the incoming message untreated
my $title = $_[1]; # title of the incoming message untreated
my @input = split("\n",$input);
my @output = &parse_input(\@input);
# print $output[0];
# print $output[1];
my $output = $output[0];
return $output; #body of the outgoing message untreated
}
sub parse_input
{
my @input = @{$_[0]};
my @NCID; my @NCACC; my @NCGI; my @fasta;
my $fasta = 0;
foreach my $unit (@input)
{
if (($unit =~ /^>/) || ($fasta))
{
if ( $unit =~ /^\s+$/ ) #if it is a empty line
{
$fasta = 0; push (@fasta, $unit); #stop fasta but insert the empty line on the array
}
else # if it is not empty, it is the sequence, keep pushing
{
$fasta = 1; push (@fasta, $unit);
};
}
elsif ($unit =~ /\A((NT)|(NC)|(NG)|(NM)|(NP)|(XM)|(XR)|(XP))\_\d{5,8}/i)
{
push (@NCID, $unit);
# print "$unit is ID\n";
}
elsif ($unit =~ /^[a-zA-Z]{2}\d{6,8}/)
{
push (@NCACC, $unit);
# print "$unit is ACC\n";
}
elsif ($unit =~ /\d{6,10}/)
{
push (@NCGI, $unit);
# print "$unit is GI\n";
}
else
{
print "$unit is an unidentified type code\n";
}
}
my @fastaRefs = &get_fasta_id(\@fasta);
my @fastaGI = @{$fastaRefs[0]};
my @fastaGB = @{$fastaRefs[1]};
my @fastaSP = @{$fastaRefs[2]};
my @fastaRef = @{$fastaRefs[3]};
my @fastaCon = @{$fastaRefs[4]};
my $output1;
my $output2;
my @output;
($output1, $output2) = &parse_input(\@fastaCon) if (@fastaCon);
$output[1] = $output1;
$output[2] = $output2;
($output1, $output2) = &queryGB(\@NCID,"id");
$output[1] .= $output1;
$output[2] .= $output2;
($output1, $output2) = &queryGB(\@NCACC,"acc");
$output[1] .= $output1;
$output[2] .= $output2;
($output1, $output2) = &queryGB(\@NCGI,"gi");
$output[1] .= $output1;
$output[2] .= $output2;
return ($output[1], $output[2]);
}
sub queryGB
{
my @input = @{$_[0]};
my $type = $_[1];
my $gb = new Bio::DB::GenBank;
my $output = "";
my $desc = "";
my $seqio;
if ($type eq "id")
{
$seqio = $gb->get_Stream_by_id(\@input);
}
elsif ($type eq "acc")
{
$seqio = $gb->get_Stream_by_acc(\@input);
}
elsif ($type eq "gi")
{
$seqio = $gb->get_Stream_by_gi(\@input);
}
else
{
return "";
}
while ( my $seq = $seqio->next_seq() )
{
my $sequence = $seq->seq();
my $anumber = $seq->accession_number();
my $display_id = $seq->display_id();
my $subseq = $seq->subseq(5,10);
my $alphabet = $seq->alphabet();
my $primary_id = $seq->primary_id();
my $length = $seq->length();
my $description = $seq->description();
my $strain = "";
my $organism;
for my $feats ($seq->get_SeqFeatures)
{
if ($feats->primary_tag eq "source")
{
my @organism = $feats->get_tag_values("organism");
$organism = $organism[0];
}
}
if ( ! $organism )
{
for my $feats ($seq->get_SeqFeatures)
{
if ($feats->primary_tag eq "source")
{
my @organism = $feats->get_tag_values("db_xref");
$organism = $organism[0] if ($organism[0] =~ /taxon:/);
}
}
}
if ( ! $organism )
{
$organism = "unknown";
}
$desc .= "CLASS \t" . $type . "\n"; # type of accession number
$desc .= "DISPLAY ID\t" . $display_id . "\n"; # the human read-able id of the sequence
$desc .= "SUBSEQ \t" . $subseq . "\n"; # part of the sequence as a string
$desc .= "ALPHABET \t" . $alphabet . "\n"; # one of 'dna','rna','protein'
$desc .= "PRIMARY ID\t" . $primary_id . "\n"; # a unique id for this sequence regardless of its display_id or accession number
$desc .= "LENGTH \t" . $length . "\n"; # sequence length
$desc .= "DESCRIPT \t" . $description . "\n"; # a description of the sequence
$desc .= "SEQ \t\n" . &faster($sequence) . "\n"; # string of sequence
$desc .= "ACC NUMBER\t" . $anumber . "\n"; # when there, the accession number
$desc .= "ORGANISM \t" . $organism . "\n";
if ($desc =~ /strain ((\w+) (\w+))/i) { $strain = $1; };
$desc .= "STRAIN \t" . $strain . "\n\n\n";
$output .= &make_fasta($organism,$strain,$anumber,$sequence);;
# for my $feat_object ($seq->get_SeqFeatures)
# {
# print "primary tag: ", $feat_object->primary_tag, "\n";
# for my $tag ($feat_object->get_all_tags)
# {
# print " tag: ", $tag, "\n";
# for my $value ($feat_object->get_tag_values($tag))
# {
# print " value: ", $value, "\n";
# }
# }
# }
}
return ($output, $desc);
}
sub make_fasta
{
my $organism = $_[0];
my $strain = $_[1];
my $anumber = $_[2];
my $sequence = $_[3];
my $title;
$organism =~ tr/a-zA-Z0-9_./_/c;
$organism = "$organism\_";
$strain =~ tr/a-zA-Z0-9_./_/c;
$strain = "$strain\_" if $strain;
$title = ">$organism$strain$anumber";
$sequence = &faster($sequence);
my $concac = "$title\n$sequence\n";
return $concac;
}
sub faster
{
my $seq = $_[0];
my $out = "";
my $len = length($seq); # This time, we will write
my $numLines = int($len / 60); # 60 characters per line
if(($len % 60) != 0) { $numLines++; };
for(my $i = 0; $i < $numLines; $i++)
{
my $sub = substr($seq, ($i * 60), 60) . "\n";
$out .= $sub;
# print "$numLines\t$i\t$sub";
}
return $out;
}
sub get_fasta_id
{
my @fasta = @{$_[0]};
my @gis;
my @gbs;
my @sps;
my @refs;
my @consol;
foreach my $line (@fasta)
{
# print "$line\n";
# >gi|165881902|gb|EU192366.1| Malassezia pachydermatis strain ATCC 14522 18S ribosomal RNA gene, partial sequence
# TTTGGGCTTTGGTGAATATAATAACTTCTCGGATCGCATGGCCTTGTGCCGGCGATGCTTCATTCAAATA
# TCTGCCCTATCAACTGTCGATGGTAGGATAGAGGCCTACCATGGTTGCAACGGGTAACGGGGAATAAGGG
# >gi|113681126|ref|NP_001038656.1| si:dkey-98n4.1 [Danio rerio]
# MSNGAAGSGGLTWVTLFDKNNGAKKEEMNGRGDAGKSEVVKKESSKKMSVERIYQKKTQLEHILLRPDTY
# IGSVEPVTQQMWVFDEEIGMNLREISFVPGLYKIFDEILVNAADNKQRDKNMTTIKITIDPESNTISVWN
my ($gi, $gb, $sp, $ref, $cons);
if ($line =~ /^>/)
{
if ($line =~ /gi\|(\d+)\b/g)
{
$gi = $1;
}
if ($line =~ /gb\|([A-Z]{2}[0-9.]+)/g)
{
$gb = $1;
}
if ($line =~ /sp\|([A-Z]\d{5})\b/g)
{
$sp = $1;
}
if ($line =~ /ref\|([A-Z_]{3}[0-9.]+)\b/g)
{
$ref = $1;
}
push (@gis,$gi) if ($gi);
push (@gbs,$gb) if ($gb);
push (@sps,$sp) if ($sp);
push (@refs,$ref) if ($ref);
if ($gb) { $cons = $gb; } elsif ($ref) { $cons = $ref; } elsif ($gi) { $cons = $gi; };
push(@consol, $cons) if $cons;
}
}
# print "GIS :\t" . join("\n", @gis) . "\n";
# print "GBS :\t" . join("\n", @gbs) . "\n";
# print "SPS :\t" . join("\n", @sps) . "\n";
# print "REF :\t" . join("\n", @refs) . "\n";
# print "CON :\t" . join("\n", @consol) . "\n";
return (\@gis,\@gbs,\@sps,\@refs,\@consol);
}
1;
__END__
# sub parse_input
# {
# my $input = $_[0];
# my %input;
# map { $input{$_}{"working"} = 1; } split("\n",$input);
#
# foreach my $key (keys %input)
# {
# print "$key\n";
# $input{$key}{"raw"} = &query_genbank($key);
# }
# }
# nuc fasta http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?query_key=7&db=nucleotide&qty=1&term=EF636668&c_start=1&uids=&dopt=fasta&dispmax=20&sendto=t&from=begin&to=end
# nuc fasta http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?query_key=7&db=nucleotide&qty=1&term=EF636668&dopt=fasta&dispmax=1&sendto=t
# prot fasta http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?WebEnv=1noB9M_nmYezmAq6g9GWWdqrgL1qovFPrCeVhDfNwLBpUujorfaubbR2xc9-jgqy_dgEJ7QaCyVUbTRRMxqwUT%402644478B9002AD30_0161SID&query_key=13&db=protein&qty=1&term=ABU96614&c_start=1&uids=&dopt=fasta&dispmax=20&sendto=t&from=begin&to=end
#
# nuc ans.1 http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?WebEnv=1F5XsSc_aetk6zoGShVg612s3XRpqggBG6bn_B47aYcD3BqLPQOhOfIPzMoaIoSQ2CJs6Q7f-Azd3xw-1unwtA%402644478B9002AD30_0161SID&db=nucleotide&qty=1&c_start=1&list_uids=156887923&uids=&dopt=asn&dispmax=5&sendto=t&extrafeatpresent=1&ef_CDD=8&ef_MGC=16&ef_HPRD=32&ef_STS=64&ef_tRNA=128&ef_microRNA=256&ef_Exon=512
# nuc ans.1 http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?db=nucleotide&qty=1&c_start=1&list_uids=156887923&uids=&dopt=asn&dispmax=5&sendto=t
# nuc ans.1 http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?query_key=7&db=nucleotide&qty=1&term=EF636668&c_start=1&uids=&dopt=asn&dispmax=20&sendto=t
# prot ans.1 http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?query_key=13&db=protein&qty=1&term=ABU96614&c_start=1&uids=&dopt=asn&dispmax=20&sendto=t
# sub query_genbank_nuc
# {
# my $query = $_[0];
#
# chomp $query;
# my $url = "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?query_key=7&db=nucleotide&qty=1&term=$query&c_start=1&uids=&dopt=asn&dispmax=20&sendto=t";
# my $agent = new LWP::UserAgent();
# my $request = new HTTP::Request('GET' => $url); # get the URL
# my $response = $agent->request($request); # get the response of the request
# my $answer;
#
#
# if ($response->is_success()) # if got the page successifully
# {
# $answer = $response->content();
# print $answer;
# } # END if response success
# else # else (if doesnt get a response from the site)
# {
# print "redo $query\n";
# $answer = &query_genbank_nuc($query);
# print $answer;
# } # END else response success
#
# return $answer;
# } # sub query genbank
#
#
#
#
# sub query_genbank2
# {
# open(TEMP2, "temp2.txt") or die("Error on file oppening: " . "temp2.txt\n");
#
# my $number_of_queries;
#
# while (<TEMP2>)
# {
# ++$number_of_queries;
# `wget "http://www.ncbi.nlm.nih.gov/entrez/viewer.fcgi?val=$_"`;
# }
#
# close(TEMP2) or die("Error on file closing: temp2.txt\n");
#
# for (my $i = 1; $i < 10; ++$i)
# {
# `cat viewer.fcgi?val=$i* >> viewer.out`;
# }
# }
#
#
# sub get_sequences_IDs
# {
# # print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n";
# # print "@@@@@@@@@@> GET SEQUENCES IDs <@@@@@@@@@@\n";
# # print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n";
# # open(LOG, ">>log") or die("Error on file oppening: LOG\n");
# # print LOG "GET SEQUENCES ID: START AT " . `date` . "\n";
# #
# # $nome_final = "temp1_" . $suffix . ".txt";
# # print "LOADING TEMP1 - $nome_final\n";
# # open (TEMP1, "$nome_final") or die("Error on file oppening: TEMP1\n");
# #
# # $nome_final = "temp2_" . $suffix . ".txt";
# # print "LOADING TEMP1 - $nome_final\n";
# # open (TEMP2, ">$nome_final") or die("Error on file oppening: TEMP2\n");
# # print "TEMP1 LOADED\n";
# #
# # while (<TEMP1>)
# # {
# # # se houverem d?gitos na linha
# # if (/\d/)
# # {
# # #>gi|15595213|ref|NP_248705.1| hypothetical protein PA0015 [Pseudomonas aeruginosa PAO1]
# # # ^>
# # # substitua globalmente por nada qualquer um destes nomes mais o que vier depois deles
# # s/(ref|gb|emb|dbj|pir|prf|sp|pdb|pat|bbs|gnl|lcl).+//g;
# # #substitua globalmente ">gi" e "|" por nada, sobrando assim apenas o GI#
# # #>gi|15595213|
# # #^^^^ ^
# # s/(^>gi|\|)//g;
# #
# # print "ID number: " . ++$number_of_IDs . "\n";
# # print "$_";
# # print TEMP2 "$_";
# # }
# # }
# }
# for my $feat_object ($seq->get_SeqFeatures)
# {
# if ($feat_object->has_tag("organism"))
# {
# $organism = $feat_object->get_tag_values("organism");
# print "ORGANISM L11 \t$organism\n";
# }
# if ($feat_object->has_tag("source"))
# {
# $organism = $feat_object->get_tag_values("source");
# print "ORGANISM L12 \t$organism\n";
# }
# elsif ($feat_object->has_tag("db_xref"))
# {
# if ($feat_object->get_tag_values("db_xref") =~ /~taxon:(.*)/)
# {
# $organism = $1;
# print "ORGANISM L2 \t$organism\n";
# }
# else
# {
# print "ORGANISM L3 \t$organism\t";
# print $feat_object->get_tag_values("db_xref");
# print "\n";
# if ( ! $organism )
# {
# $organism = "unknown";
# print "ORGANISM L4 \t$organism\n";
# }
# }
# }
# else
# {
# if ( ! $organism )
# {
# $organism = "unknown";
# print "ORGANISM L5 \t$organism\n";
# }
# }
# } | sauloal/projects | biomail/progs/getNCBI.pm | Perl | mit | 14,115 |
package Bio::SUPERSMART::Service::InferenceService::examl;
use strict;
use warnings;
use Bio::Tools::Run::Phylo::ExaML;
use Bio::SUPERSMART::Service::InferenceService;
use base 'Bio::SUPERSMART::Service::InferenceService';
=head1 NAME
Bio::SUPERSMART::Service::InferenceService::examl - Infers phylogenetic trees
=head1 DESCRIPTION
Provides functionality inferring trees and sets of trees by wrapping ExaML.
=over
=item configure
Provides the $config object to the wrapper so that settings defined in $config object can
be applied to the wrapper.
=cut
sub configure {
my ( $self ) = @_;
my $logger = $self->logger;
my $outfile = $self->outfile;
my $tool = $self->wrapper;
my $config = $self->config;
# set outfile name
$logger->info("going to create output file $outfile");
$tool->outfile_name($outfile);
# set to parallel inference only if we have more nodes than
# desired replicates; otherwise do all inferences without mpi in parallel
if ( $config->NODES > $self->bootstrap ) {
# set mpirun location
$logger->info("going to use mpirun executable ".$config->MPIRUN_BIN);
$tool->mpirun($config->MPIRUN_BIN);
# set number of available nodes
my $nodes = int( $config->NODES / $self->bootstrap );
$logger->info("setting number of MPI nodes ".$nodes);
$tool->nodes($nodes);
}
# set executable location
$logger->info("going to use executable ".$config->EXAML_BIN);
$tool->executable($config->EXAML_BIN);
# set parser location
$logger->info("going to use parser executable ".$config->EXAML_PARSER_BIN);
$tool->parser($config->EXAML_PARSER_BIN);
# set substitution model
$logger->info("setting substitution model ".$config->EXAML_MODEL);
$tool->m($config->EXAML_MODEL);
# set random seed
$tool->p($config->RANDOM_SEED);
}
=item create
Instantiates and configures the wrapper object, returns the instantiated wrapper.
=cut
sub create {
my $self = shift;
my $logger = $self->logger;
my $workdir = $self->workdir;
my $tool = Bio::Tools::Run::Phylo::ExaML->new;
# set working directory
$logger->info("going to use working directory $workdir");
$tool->work_dir($workdir);
return $tool;
}
=item run
Runs the analysis on the provided supermatrix. Returns a tree file.
=cut
sub run {
my ( $self, %args ) = @_;
my $logger = $self->logger;
$self->wrapper->run_id( 'examl-run-' . $$ . '-' . $self->replicate );
my $backbone = $self->wrapper->run(
'-phylip' => $args{'matrix'},
'-intree' => $self->usertree,
);
$logger->info("examl tree inference was succesful") if $backbone;
return $backbone;
}
=item cleanup
Cleans up all intermediate files.
=cut
sub cleanup {
my $self = shift;
my ( $v, $d, $f ) = File::Spec->splitpath( $self->outfile );
my $tempfile = 'ExaML_modelFile.' . $f;
if ( -e $tempfile ) {
unlink $tempfile;
$self->logger->info("removed $tempfile");
}
}
=back
=cut
1;
| naturalis/supersmart | lib/Bio/SUPERSMART/Service/InferenceService/examl.pm | Perl | mit | 3,053 |
package XrefParser::MGIParser;
use strict;
use DBI;
use base qw(XrefParser::BaseParser);
# --------------------------------------------------------------------------------
# Parse command line and run if being run directly
if (!defined(caller())) {
if (scalar(@ARGV) != 1) {
print "\nUsage: MGIParser.pm file <source_id> <species_id>\n\n";
exit(1);
}
run($ARGV[0]);
}
sub run {
my $self = shift if (defined(caller(1)));
my $source_id = shift;
my $species_id = shift;
my $files = shift;
my $release_file = shift;
my $verbose = shift;
my $file = @{$files}[0];
if(!defined($source_id)){
$source_id = XrefParser::BaseParser->get_source_id_for_filename($file);
}
if(!defined($species_id)){
$species_id = XrefParser::BaseParser->get_species_id_for_filename($file);
}
my $file_io = $self->get_filehandle($file);
if ( !defined $file_io ) {
print STDERR "ERROR: Could not open $file\n";
return 1; # 1 is an error
}
my %label;
my %version;
my %description;
my %accession;
my $dbi = $self->dbi();
my $sql = 'select source_id, priority_description from source where name like "MGI"';
my $sth = $dbi->prepare($sql);
$sth->execute();
my ($mgi_source_id, $desc);
$sth->bind_columns(\$mgi_source_id, \$desc);
my @arr;
while($sth->fetch()){
push @arr, $mgi_source_id;
}
$sth->finish;
$sql = "select accession, label, version, description from xref where source_id in (".join(", ",@arr).")";
$sth = $dbi->prepare($sql);
$sth->execute();
my ($acc, $lab, $ver, $desc);
$sth->bind_columns(\$acc, \$lab, \$ver, \$desc);
while (my @row = $sth->fetchrow_array()) {
if(defined($desc)){
$accession{$lab} = $acc;
$label{$acc} = $lab;
$version{$acc} = $ver;
$description{$acc} = $desc;
}
}
$sth->finish;
#synonyms
$sql = "insert into synonym (xref_id, synonym) values (?, ?)";
my $add_syn_sth = $dbi->prepare($sql);
my $syn_hash = $self->get_ext_synonyms("MGI");
my $count = 0;
my $syn_count = 0;
while ( my $line = $file_io->getline() ) {
#MGI:1915941 1110028C15Rik RIKEN cDNA 1110028C15 gene 33.61 1 ENSMUSG00000026004 ENSMUST00000042389 ENSMUST00000068168 ENSMUST00000113987 ENSMUST00000129190 ENSMUST00000132960 ENSMUSP00000036975 ENSMUSP00000063843 ENSMUSP00000109620 ENSMUSP00000118603
if($line =~ /(MGI:\d+).*(ENSMUSG\d+)/){
my $acc = $1;
my $ensid = $2;
my $xref_id = XrefParser::BaseParser->add_xref($acc, $version{$acc}, $label{$acc}, $description{$acc}, $source_id, $species_id, "DIRECT");
XrefParser::BaseParser->add_direct_xref( $xref_id, $ensid, "Gene", '');
if(defined($syn_hash->{$acc})){
foreach my $syn (@{$syn_hash->{$acc}}){
$add_syn_sth->execute($xref_id, $syn);
}
}
$count++;
}
else{
print STDERR "PROBLEM: $line";
}
}
print "$count direct MGI xrefs added\n";
return 0;
}
1;
| adamsardar/perl-libs-custom | EnsemblAPI/ensembl/misc-scripts/xref_mapping/XrefParser/MGIParser.pm | Perl | apache-2.0 | 2,954 |
package Moose::Exception::LazyAttributeNeedsADefault;
our $VERSION = '2.1404';
use Moose;
extends 'Moose::Exception';
with 'Moose::Exception::Role::EitherAttributeOrAttributeName';
sub _build_message {
my $self = shift;
"You cannot have a lazy attribute (".$self->attribute_name.") without specifying a default value for it";
}
1;
| ray66rus/vndrv | local/lib/perl5/x86_64-linux-thread-multi/Moose/Exception/LazyAttributeNeedsADefault.pm | Perl | apache-2.0 | 342 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V8::Services::AdGroupLabelService::MutateAdGroupLabelResult;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {resourceName => $args->{resourceName}};
# 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/V8/Services/AdGroupLabelService/MutateAdGroupLabelResult.pm | Perl | apache-2.0 | 1,059 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package os::windows::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} = '0.1';
%{$self->{modes}} = (
'cpu' => 'snmp_standard::mode::cpu',
'interfaces' => 'snmp_standard::mode::interfaces',
'list-interfaces' => 'snmp_standard::mode::listinterfaces',
'list-storages' => 'snmp_standard::mode::liststorages',
'memory' => 'os::windows::snmp::mode::memory',
'processcount' => 'snmp_standard::mode::processcount',
'service' => 'os::windows::snmp::mode::service',
'storage' => 'snmp_standard::mode::storage',
'swap' => 'os::windows::snmp::mode::swap',
'time' => 'snmp_standard::mode::ntp',
'uptime' => 'snmp_standard::mode::uptime',
);
return $self;
}
1;
__END__
=head1 PLUGIN DESCRIPTION
Check Windows operating systems in SNMP.
=cut
| wilfriedcomte/centreon-plugins | os/windows/snmp/plugin.pm | Perl | apache-2.0 | 2,086 |
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package storage::hp::p2000::xmlapi::mode::health;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use storage::hp::p2000::xmlapi::mode::components::disk;
use storage::hp::p2000::xmlapi::mode::components::vdisk;
use storage::hp::p2000::xmlapi::mode::components::sensors;
use storage::hp::p2000::xmlapi::mode::components::fru;
use storage::hp::p2000::xmlapi::mode::components::enclosure;
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 =>
{
"exclude:s" => { name => 'exclude' },
"component:s" => { name => 'component', default => 'all' },
"no-component:s" => { name => 'no_component' },
});
$self->{components} = {};
$self->{no_components} = undef;
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (defined($self->{option_results}->{no_component})) {
if ($self->{option_results}->{no_component} ne '') {
$self->{no_components} = $self->{option_results}->{no_component};
} else {
$self->{no_components} = 'critical';
}
}
}
sub component {
my ($self, %options) = @_;
if ($self->{option_results}->{component} eq 'all') {
storage::hp::p2000::xmlapi::mode::components::disk::check($self);
storage::hp::p2000::xmlapi::mode::components::vdisk::check($self);
storage::hp::p2000::xmlapi::mode::components::sensors::check($self);
storage::hp::p2000::xmlapi::mode::components::fru::check($self);
storage::hp::p2000::xmlapi::mode::components::enclosure::check($self);
} elsif ($self->{option_results}->{component} eq 'disk') {
storage::hp::p2000::xmlapi::mode::components::disk::check($self);
} elsif ($self->{option_results}->{component} eq 'vdisk') {
storage::hp::p2000::xmlapi::mode::components::vdisk::check($self);
} elsif ($self->{option_results}->{component} eq 'sensor') {
storage::hp::p2000::xmlapi::mode::components::sensors::check($self);
} elsif ($self->{option_results}->{component} eq 'fru') {
storage::hp::p2000::xmlapi::mode::components::fru::check($self);
} elsif ($self->{option_results}->{component} eq 'enclosure') {
storage::hp::p2000::xmlapi::mode::components::enclosure::check($self);
} else {
$self->{output}->add_option_msg(short_msg => "Wrong option. Cannot find component '" . $self->{option_results}->{component} . "'.");
$self->{output}->option_exit();
}
my $total_components = 0;
my $display_by_component = '';
my $display_by_component_append = '';
foreach my $comp (sort(keys %{$self->{components}})) {
# Skipping short msg when no components
next if ($self->{components}->{$comp}->{total} == 0 && $self->{components}->{$comp}->{skip} == 0);
$total_components += $self->{components}->{$comp}->{total} + $self->{components}->{$comp}->{skip};
$display_by_component .= $display_by_component_append . $self->{components}->{$comp}->{total} . '/' . $self->{components}->{$comp}->{skip} . ' ' . $self->{components}->{$comp}->{name};
$display_by_component_append = ', ';
}
$self->{output}->output_add(severity => 'OK',
short_msg => sprintf("All %s components [%s] are ok.",
$total_components,
$display_by_component)
);
if (defined($self->{option_results}->{no_component}) && $total_components == 0) {
$self->{output}->output_add(severity => $self->{no_components},
short_msg => 'No components are checked.');
}
}
sub run {
my ($self, %options) = @_;
$self->{p2000} = $options{custom};
$self->{p2000}->login();
$self->component();
$self->{output}->display();
$self->{output}->exit();
}
sub check_exclude {
my ($self, %options) = @_;
if (defined($options{instance})) {
if (defined($self->{option_results}->{exclude}) && $self->{option_results}->{exclude} =~ /(^|\s|,)${options{section}}[^,]*#\Q$options{instance}\E#/) {
$self->{components}->{$options{section}}->{skip}++;
$self->{output}->output_add(long_msg => sprintf("Skipping $options{section} section $options{instance} instance."));
return 1;
}
} elsif (defined($self->{option_results}->{exclude}) && $self->{option_results}->{exclude} =~ /(^|\s|,)$options{section}(\s|,|$)/) {
$self->{output}->output_add(long_msg => sprintf("Skipping $options{section} section."));
return 1;
}
return 0;
}
1;
__END__
=head1 MODE
Check health status of storage.
=over 8
=item B<--component>
Which component to check (Default: 'all').
Can be: 'disk', 'vdisk', 'sensor', 'enclosure', 'fru'.
=item B<--exclude>
Exclude some parts (comma seperated list) (Example: --exclude=fru)
Can also exclude specific instance: --exclude=disk#disk_1.4#,sensor#Temperature Loc: lower-IOM B#
=item B<--no-component>
Return an error if no compenents are checked.
If total (with skipped) is 0. (Default: 'critical' returns).
=back
=cut | wilfriedcomte/centreon-plugins | storage/hp/p2000/xmlapi/mode/health.pm | Perl | apache-2.0 | 6,294 |
# !/usr/bin/perl
use strict;
use warnings;
use DBI;
use Carp;
use Parser::InvoiceParser;
use DB::Invoices;
use DB::Products;
use Core::InvoiceInfo;
sub usage {
die "add_invoice [invoice filename]";
}
my $invoice_filename = $ARGV[0];
if (!defined($invoice_filename)) {
usage();
}
my $invoice_parser = Parser::InvoiceParser->new();
my $dbh = DBI->connect("dbi:SQLite:dbname=p.db", "", "",
{RaiseError => 1});
$dbh->{AutoCommit} = 0;
my $invoices = DB::Invoices->new($dbh);
$invoice_parser->open($invoice_filename);
my $datetime_of_invoice = $invoice_parser->get_datetime();
my $invoice_id = $invoices->begin_invoice($datetime_of_invoice);
my $products = DB::Products->new($dbh);
while (!$invoice_parser->eof()) {
my %parser_entry = $invoice_parser->get_invoice_entry();
my $item_no = $parser_entry{item_no};
my $qty_received = $parser_entry{qty_received};
my $product = $products->lookup_by_item_no($item_no);
if (!defined($product)) {
$invoice_parser->next();
next;
}
my $invoice_entry = Core::InvoiceInfo->new();
$invoice_entry->set_sku($product->get_sku());
$invoice_entry->set_qty_received($qty_received);
$invoices->insert_into($invoice_id, $invoice_entry);
$invoice_parser->next();
}
$dbh->commit();
| nrusin/inventory | add_invoice.pl | Perl | apache-2.0 | 1,332 |
#!/usr/bin/env perl
use strict;
use warnings;
use Error::Pure::HTTP::Print qw(err);
# Error.
err '1', '2', '3';
# Output:
# Content-type: text/plain
#
# 1 | tupinek/Error-Pure-HTTP | examples/ex9.pl | Perl | bsd-2-clause | 158 |
package Mojo::Webqq::Plugin::UploadQRcode;
our $CALL_ON_LOAD=1;
use strict;
sub call{
my $client = shift;
my $data = shift;
$client->on(input_qrcode=>sub{
my($client,$qrcode_path,$qrcode_data) = @_;
#需要产生随机的云存储路径,防止好像干扰
my $json = $client->http_post('https://sm.ms/api/upload',{json=>1},form=>{
format=>'json',
smfile=>{filename=>$qrcode_path,content=>$qrcode_data},
});
if(not defined $json){
$client->warn("二维码图片上传云存储失败: 响应数据异常");
return;
}
elsif(defined $json and $json->{code} ne 'success' ){
$client->warn("二维码图片上传云存储失败: " . $json->{msg});
return;
}
$client->qrcode_upload_url($json->{data}{url});
$client->info("二维码已上传云存储[ ". $json->{data}{url} . " ]");
});
}
1;
| sjdy521/Mojo-Webqq | lib/Mojo/Webqq/Plugin/UploadQRcode.pm | Perl | bsd-2-clause | 953 |
#########################################################################
# A Simple Parser for automating the specializations crated in FOCUS.
#
# @author Arvind S. Krishna <arvindk@dre.vanderbilt.edu>
#
# This parser, parses the specialization file given as an input argument
# and *individually* visits the tags in a pre-determined order to weave
# in the specializations.
# NOTE: This parser will make N passes over the file, where N equals
# to the number of tags defined in the specialization file. This
# approach is intentional as it servers current needs. Future versions
# may enhance this parser and Visit methods to be more intelligent.
###########################################################################
package FOCUSParser;
# for MY own preferences!
use strict;
# XML related operations
use XML::DOM;
# Generic file operations
use FileHandle;
# Creating files and renaming them
use File::Copy;
# Creating directories
use File::Path;
############################################
# GLOBAL CONSTANTS
###########################################
my $FOCUS_PREPEND_TAG = "\/\/@@ ";
####################################################################
# banner: A function that returns the FOCUS banner transformation
# for just clarity purpose only.
###################################################################
sub FOCUS_banner_start
{
my $banner_str = "// Code woven by FOCUS:\n";
return $banner_str;
}
sub FOCUS_banner_end
{
my $banner_str = "// END Code woven by FOCUS\n";
return $banner_str;
}
#########################################################################
# Visit_ADD: Visit a add element defined in the transform.
# In particular look for the hook defined: search it in the source file
# and add the data in the <data> tags into the file starting from the
# hook, but not including the hook.
##########################################################################
sub Visit_Add
{
my ($add, $copy_file_name) = @_;
# Open the copy and transform it
open (IN, "+<". $copy_file_name) ||
die "cannot open file: " . $copy_file_name;
# To update a file in place, we use the temporary
# file idiom. Perl says this is the best way to
# do this!
my $copy_file_tmp = $copy_file_name . "tmp";
open (OUT, ">". $copy_file_tmp) ||
die "cannot open temporary file for modying file:" . $copy_file_name;
# get the hook element defined in the add element
my $hook = $add->getElementsByTagName ('hook');
# ensure length of hook == 1;
if ($hook->getLength != 1)
{
print "Assertion Error: An <add> element can have only \
one <hook> definition";
# clean up
close (IN);
close (OUT);
# Diagnostic comment
print " [failure]... Reverting changes \n";
unlink ($copy_file_name);
unlink ($copy_file_name . "tmp");
exit (1);
}
# Check if the hook is present in the file at all
my $hook_str = $hook->item(0)->getFirstChild->getNodeValue;
chomp ($hook_str);
#//@@ For now, due to problem with the hook string
my $search_str = $hook_str;
while (<IN>)
{
if (/$search_str/)
{
# Do not remove the hook! It needs to be present
print OUT $_;
# FOCUS banner start
print OUT FOCUS_banner_start;
# parse <data> ... </data> elements for this add tag
my @data_list = $add->getElementsByTagName ('data');
foreach my $data (@data_list)
{
my $data_item = $data->getFirstChild->getNodeValue;
chomp ($data_item);
# Insert the item
print OUT "$data_item \n";
}
# FOCUS banner end
print OUT FOCUS_banner_end;
}
else
{ print OUT $_; }
}
# Everything went well!
close (IN);
close (OUT);
# replace in place the old file with the new one
rename ($copy_file_tmp, $copy_file_name);
}
###########################################################################
# Visit_Remove: Visit a <remove> element defined in the transform.
# In particular look for the hook defined: search it in the source file
# and remove the element's value from the source file being searched.
############################################################################
sub Visit_Remove
{
my ($remove, $copy_file_name) = @_;
# obtain the data to be removed
my $search = $remove->getFirstChild->getNodeValue;
chomp ($search);
# Open the copy and transform it
open (IN, "+<" . $copy_file_name) ||
die "cannot open file: " . $copy_file_name;
# Update the file in place
my $copy_file_name_tmp = $copy_file_name . "tmp";
open (OUT, ">". $copy_file_name_tmp) ||
die "cannot open temporary file for modying file:" . $copy_file_name;;
# Removing something is same as search and replace. Replace with ""
my $replace = "";
foreach my $line (<IN>)
{
if ($line =~/$search/)
{
# We do not print the banner information
# as we have removed something and
# print the banner will be redundant!
# replace <search> with <replace>
$line =~ s/$search/$replace/;
print OUT $line;
}
else { print OUT $line; }
}
# Everything went well!
close (IN);
close (OUT);
# replace in place the old file with the new one
rename ($copy_file_name_tmp, $copy_file_name);
}
#########################################################################
# Visit_Substitute: Visit a <substitute> element defined in the transform.
# In particular look for the <search> element and replace it with the
# <replace> element.
#########################################################################
sub Visit_Substitute
{
my ($substitute, $copy_file_name) = @_;
# Open the copy and transform it
open (IN, "+<". $copy_file_name) ||
die "cannot open file: " . $copy_file_name;
# To update a file in place, we use the temporary
# file idiom. Perl says this is the best way to
# do this!
my $copy_file_name_tmp = $copy_file_name . "tmp";
open (OUT, ">". $copy_file_name . "tmp") ||
die "cannot open temporary file for modying file:" . $copy_file_name;;
# check if the match-line keyword is set or not
my $match_line = $substitute->getAttribute('match-line');
# <search> .... </search>
my $search_list = $substitute->getElementsByTagName ('search');
# ensure length of search == 1;
if ($search_list->getLength != 1 ||
$search_list->getLength == 0)
{
print "Assertion Error: A <substitute> element can have only \
one <search> element";
close (IN);
close (OUT);
# Dianostic comment
print " [failure] reverting changes \n";
unlink ($copy_file_name);
unlink ($copy_file_name_tmp);
exit (1);
}
# <replace> .... </replace>
my $replace_list = $substitute->getElementsByTagName ('replace');
if ($replace_list->getLength != 1 ||
$replace_list->getLength == 0)
{
print "Assertion Error: A <substitute> element can have only \
one <replace> element";
close (IN);
close (OUT);
unlink ($copy_file_name);
unlink ($copy_file_name_tmp);
exit (1);
}
# <search> and <replace> element values
my $search = $search_list->item(0)->getFirstChild->getNodeValue;
my $replace = $replace_list->item(0)->getFirstChild->getNodeValue;
# remove spaces
chomp ($search);
chomp ($replace);
# Search and replace string in the file
foreach my $line (<IN>)
{
# Check if the match line attribute is set. If so then
# ignore word boundaries. If not, honor word boundaries.
my $line_matched = 0;
if (! $match_line)
{
if ($line =~/\b$search\b/)
{
$line_matched = 1;
}
}
else
{
if ($line =~ /$search/)
{
$line_matched = 1;
}
}
# Check if the line matched
if ($line_matched)
{
# FOCUS banner start
print OUT FOCUS_banner_start;
# replace <search> with <replace>
# Caveat: What if <search> occures multiple
# times in the line? Here is how we handle
# it
$line =~ s/$search/$replace/g;
print OUT $line;
# FOCUS banner end
print OUT FOCUS_banner_end;
}
else { print OUT $line; }
}
# everything went well!
close (IN);
close (OUT);
# replace in place the old file with the new one
rename ($copy_file_name_tmp, $copy_file_name);
}
#########################################################################
# Visit_Comment: Visit the comment-region hooks defined in the
# source code and comment out all code between start and finish of that
# region
#########################################################################
sub Visit_Comment
{
my ($comment, $copy_file_name) = @_;
# check for the comment region tags and
# comment out the region
my $start_hook_tag = $comment->getElementsByTagName ('start-hook');
my $end_hook_tag = $comment->getElementsByTagName ('end-hook');
if ($start_hook_tag->getLength != 1 ||
$end_hook_tag->getLength != 1)
{
print "Assertion Error: A <comment> element can have only \
one pair of <start-hook> and <end-hook> tags";
unlink ($copy_file_name);
exit (1);
}
my $start = $start_hook_tag->item(0)->getFirstChild->getNodeValue;
my $end = $end_hook_tag->item(0)->getFirstChild->getNodeValue;
# What are we looking for:
# We need to start from "//" . FOCUS_PREPEND_TAG . $hook
# i.e. //[[@ <blah blah>
# This will be the format for both start and end
# //@@ Problems with the hook string
my $start_hook = $FOCUS_PREPEND_TAG . $start;
my $end_hook = $FOCUS_PREPEND_TAG . $end;
# Open the copy and transform it
open (IN, "+<". $copy_file_name) ||
die "cannot open file: " . $copy_file_name;
my $copy_file_name_tmp = $copy_file_name . "tmp";
open (OUT, ">". $copy_file_name_tmp) ||
die "cannot open temporary file for modying file:" . $copy_file_name;
my $start_commenting = 0;
while (<IN>)
{
if (! /$start_hook/ &&
! /$end_hook/)
{
if ($start_commenting)
{ print OUT "// " . $_; }
else
{ print OUT $_; }
}
else
{
if (/$start_hook/)
{
$start_commenting = 1;
print OUT $_; # print start hook!
}
else
{
$start_commenting = 0;
print OUT $_; # print end hook!
}
}
}
# everything went well!
close (IN);
close (OUT);
rename ($copy_file_name_tmp, $copy_file_name);
}
###############################################################
# Visit_Copy: visit the <copy> tags and weave the code into the
# source file. In particular, open the source file specified
# in the file-source tag. Search for the start hook and
# copy until the end hook is reached.
###############################################################
sub Visit_Copy
{
my ($copy_tag, $copy_file_name, $default_module_name, $prefix_path) = @_;
# Check if a file name has been specified
my $dest_file_tag = $copy_tag->getElementsByTagName ('source');
if (! $dest_file_tag)
{
print "Error: <copy-from-source> does not have the <file> tag..";
print "aborting \n";
exit 1;
}
if ($dest_file_tag->getLength != 1)
{
print "Assertion Error: A <copy-from-source> element can have only \
one <source> tag from which to copy elements";
exit (1);
}
my $dest_file_name = $dest_file_tag->item(0)->getFirstChild->getNodeValue;
#Check if the file exists and one is able to access it
$dest_file_name = $prefix_path . "/" . $default_module_name . "/" . $dest_file_name;
open (DEST, "<". $dest_file_name) ||
die "cannot open $dest_file_name \n Wrong <file> tag within <copy-from-source> exiting" ;
# check for the start and end tags within the target file where
# one needs to start copying from
my $start_tag = $copy_tag->getElementsByTagName ('copy-hook-start');
my $end_tag = $copy_tag->getElementsByTagName ('copy-hook-end');
if (! $start_tag || ! $end_tag)
{
print "Assertion Error: A <copy> element should have a \
<copy-hook-start> tag and <copy-hook-end> tag \n";
exit (1);
}
# Get the <dest-hook> tag that indicates the destination where the
# code between the start and end tags will be placed.
my $dest_hook_tag = $copy_tag->getElementsByTagName ('dest-hook');
if (! $dest_hook_tag)
{
print "Assertion Error: <copy-from-source> should have a <dest-hook> \
tag that dictates where in the source file the code should be \
placed. \n";
exit (1);
}
# Remove any starting and trailing white spaces
chomp ($dest_hook_tag);
# We have everything we need! Do the copy
my $start_tag_name = $start_tag->item(0)->getFirstChild->getNodeValue;
my $end_tag_name = $end_tag->item(0)->getFirstChild->getNodeValue;
my $dest_tag_name = $dest_hook_tag->item(0)->getFirstChild->getNodeValue;
# First we add the FOCUS prepend tags
$start_tag_name = $FOCUS_PREPEND_TAG . $start_tag_name;
$end_tag_name = $FOCUS_PREPEND_TAG . $end_tag_name;
$dest_tag_name = $FOCUS_PREPEND_TAG . $dest_tag_name;
# Step 1: Iterate over the target file till the
# dest-hook is found in that file
my $copy_file_name_tmp = $copy_file_name . "tmp";
open (OUT, ">". $copy_file_name_tmp) ||
die "cannot open temporary file for modying file:" . $copy_file_name;
open (IN, "<" . $copy_file_name) ||
die "cannot open file $copy_file_name specified in the <file> tag \n";
my $dest_tag_found = 0; #check if tag matched
foreach my $line (<IN>)
{
if ($line =~ /$dest_tag_name/)
{ $dest_tag_found = 1; print OUT $line; last; }
print OUT $line;
}
close (IN);
# If we reached the end of file before finding the tag!
if (! $dest_tag_found)
{
print "\n Error: <dest-hook> tag missing in file .. aborting \n";
close (DEST);
close (IN);
close (OUT);
unlink ($copy_file_name_tmp);
exit (1);
}
# Step 2: Now look in the destination file and look for the hooks
# where one needs to copy. There could be multiple places where the
# hook can be present. E.g.
# .......
# //@@ COPY_START_HOOK
# ....
# ....
# //@@ COPY_END_HOOK
# ....
# ....
# //@@ COPY_START_HOOK
# ....
# ....
# //@@ COPY_END_HOOK
# Handle this case
my $line_matched = 0;
my $start_copying = 0; # initially do not copy
foreach my $line (<DEST>)
{
# Check if the line matches the start tag
if ($line =~/$start_tag_name/)
{
$line_matched += 1;
$start_copying = 1;
}
else
{
# Check if the line matches the end tag
if ($line =~/$end_tag_name/)
{
# check if the start tag matched!
if (! $line_matched)
{
print "Assertion error: <copy-hook-end> tag misplaced with \
the <copy-hoook-source> \n";
close (DEST);
close (IN);
close (OUT);
unlink ($copy_file_name_tmp);
exit (1);
}
# decrement the count for nested tags
$line_matched -= 1;
if (! $line_matched )
{ $start_copying = 0; }
}
else
{
# Print out the line
if ($start_copying)
{ print OUT $line; }
}
}
}
# At the end of this loop line_matched should be 0
if ($line_matched)
{
print "Error: in $dest_file_name, number of <copy-hook-source> tags \
did not match the number of <copy-hook-end> tags. Reverting \
changes. \n";
close (DEST);
close (IN);
close (OUT);
unlink ($copy_file_name_tmp);
exit (1);
}
# Step 3: Now copy data after the tag in the original file onto the destination
# file.
open (IN, "<" . $copy_file_name) ||
die "cannot open file $copy_file_name specified in the <file> tag \n";
$dest_tag_found = 0; #used as a flag
foreach my $line (<IN>)
{
if ($dest_tag_found)
{ print OUT $line; }
# If the hook is found, then don't write the hook onto OUT
# as it would have been written earlier
if (! $dest_tag_found &&
$line =~ /$dest_tag_name/)
{ $dest_tag_found = 1; }
}
# Normal exit path
close (IN);
close (OUT);
close (DEST);
# Rename the tmp file to the file modified
rename ($copy_file_name_tmp, $copy_file_name);
}
#################################################################
# commit_files: A procedure to commit all the copy files that
# were specialized back to the orginal files.
#################################################################
sub commit_files
{
my ($path_name, $output_path_name, @files) = @_;
# iterate over the file_name_list
foreach my $file (@files)
{
# <file name="....">
my $file_name = $file->getAttribute('name');
# output_path == input_path then do an in place
# substitution.
if ($output_path_name eq $path_name)
{
rename ($path_name . "/" . $file_name . "copy",
$path_name . "/" . $file_name);
}
else
{
# Check if the path_name exists. The path name
# corresponds to a directory. So create it if it does
# not exist.
if (! -d $output_path_name)
{
#@@? Need to revert the *copy files?
mkpath ($output_path_name, 0, 0744) ||
die "cannot create $output_path_name: commit files failed! \n";
}
# move the specialized file to the output directory
rename ($path_name . "/" . $file_name . "copy",
$output_path_name . "/" . $file_name);
}
}
}
#### Main ########################################################
# Specialize_Component
# procedure to execute the transformations specified in the
# specialization file
##################################################################
sub Specialize_Components
{
# Get the command line arguments
my ($prefix_path, $spl_file, $output_prefix) = @_;
my $parser = XML::DOM::Parser->new();
my $doc = $parser->parsefile($spl_file);
# Check if the prefix path ends with a / or not
# if it does not then manually add the / to it
my $last = substr ($prefix_path, -1);
if ($last ne "/")
{ $prefix_path = $prefix_path . "/"; }
# Entry Point: <transform> element
foreach my $transform ($doc->getElementsByTagName('transform'))
{
# <module tags>
foreach my $module ($transform->getElementsByTagName('module'))
{
# Complete path name to the module
my $module_name = $module->getAttribute('name');
my $path_name = $prefix_path . $module_name;
# <file tags>
my @files = $module->getElementsByTagName('file');
foreach my $file (@files)
{
# <file name="....">
my $file_name = $file->getAttribute('name');
# Rather than modifying the files directly, make a local
# copy of the files and then transform them and commit
# if there is a file called foo we make a file foo_copy
my $file_path_copy = $path_name . "/" . $file_name . "copy";
my $file_path_name = $path_name . "/" . $file_name;
copy ($file_path_name, $file_path_copy);
# Diagnostic comment
print "Instrumenting $file_name ..........";
# <comment> ... </comment>
my @comment_list = $file->getElementsByTagName ('comment');
foreach my $comment (@comment_list)
{ Visit_Comment ($comment, $file_path_copy); }
# <copy-from-source> ... </copy-from-source>
my @copy_from_source_files =
$file->getElementsByTagName ('copy-from-source');
foreach my $copy_from_source (@copy_from_source_files)
{
Visit_Copy ($copy_from_source,
$file_path_copy,
$module_name,
$prefix_path);
}
# <remove> ... </remove>
my @remove_list = $file->getElementsByTagName ('remove');
foreach my $remove (@remove_list)
{ Visit_Remove ($remove, $file_path_copy); }
# <substitute ... </substitute>
my @substitute_list = $file->getElementsByTagName ('substitute');
foreach my $substitute (@substitute_list)
{ Visit_Substitute ($substitute, $file_path_copy); }
# <add> <hook> ...... </hook> <add>
my @add_list = $file->getElementsByTagName ('add');
foreach my $add (@add_list)
{ Visit_Add ($add, $file_path_copy); }
# Everything went well.. Print success
print " [done] \n";
}
}
# At this point all the specializations in all the modules have
# succeeded. It is at this point that we need to commit the
# specializations in each of the modules. That is move the temporary
# file that we created to the main file that was specialized.
# This also means that we need another loop and do the same thing
# as above....
# <module tags>
foreach my $module ($transform->getElementsByTagName('module'))
{
# Complete path name to the module
my $module_name = $module->getAttribute('name');
my $path_name = $prefix_path . $module_name;
# Output path name: append output_prefix to the
# current module name. Append "/" to create a
# directory like /foo/bar/baz/
my $output_path = $output_prefix . "/" . $module_name;
# <file tags>
my @files = $module->getElementsByTagName('file');
# commit the files
commit_files ($path_name, $output_path, @files);
}
}
}
####
# Requiured for a module
####
1;
| wfnex/openbras | src/ace/ACE_wrappers/bin/FOCUS/Parser/FOCUSParser.pm | Perl | bsd-3-clause | 21,227 |
#!/usr/bin/perl -w
use strict;
my @names = ();
my %sizes = ();
my %types = ();
while(<>) {
if( m/.*result = (.*)\$MA_(.*)\$getAttr/ ) {
push( @names, "$1.$2" );
# print scalar(@names) . ": $names[-1]\n";
}
if( m/ (.*)\$MA_(.*)\$.*init\((.*),(.*)\)/ ) {
my ($id,$size,$type) = ("$1.$2",$3,$4);
# print "$id: $size\n";
$size =~ s/sizeof//;
$size =~ s/\(//;
$size =~ s/\)//;
$size =~ s/\s//g;
$sizes{$id} = $size;
$type =~ s/\s//g;
$types{$id} = $type;
}
}
my %TypeSize = (
uint8_t => 1,
uint16_t => 2,
uint32_t => 4,
);
my $i = 0;
for my $name (@names) {
die "Uninitialized attribute: $name (did you call .init(size)?)"
unless defined $sizes{$name};
my $size = $TypeSize{$sizes{$name}} || $sizes{$name};
printf("%-50s %-6d %2d %-20s\n", $name, $i, $size, $types{$name});
$i++;
}
| ekiwi/tinyos-1.x | beta/SystemCore/scripts/mgmtquery_keys.pl | Perl | bsd-3-clause | 855 |
#!/usr/bin/perl
###################################################################################
# This script executes one or more VTR tasks
#
# Usage:
# run_vtr_task.pl <task_name1> <task_name2> ... [OPTIONS]
#
# Options:
# -p <N>: Perform parallel execution using N threads. Note: Large benchmarks
# will use very large amounts of memory (several gigabytes). Because
# of this, parallel execution often saturates the physical memory,
# requiring the use of swap memory, which will cause slower
# execution. Be sure you have allocated a sufficiently large swap
# memory or errors may result.
# -l <task_list_file>: A file containing a list of tasks to execute. Each task
# name should be on a separate line.
#
# -hide_runtime: Do not show runtime estimates
#
# Note: At least one task must be specified, either directly as a parameter or
# through the -l option.
#
# Authors: Jason Luu and Jeff Goeders
#
###################################################################################
use strict;
# This loads the thread libraries, but within an eval so that if they are not available
# the script will not fail. If successful, $threaded = 1
my $threaded = eval 'use threads; use Thread::Queue; 1';
use Cwd;
use File::Spec;
use File::Basename;
use IPC::Open2;
use POSIX qw(strftime);
# Function Prototypes
sub trim;
sub run_single_task;
sub do_work;
sub ret_expected_runtime;
# Get Absolute Path of 'vtr_flow
Cwd::abs_path($0) =~ m/(.*vtr_flow)/;
my $vtr_flow_path = $1;
my @tasks;
my @task_files;
my $token;
my $processors = 1;
my $run_prefix = "run";
my $show_runtime_estimates = 1;
my $system_type = "local";
# Parse Input Arguments
while ( $token = shift(@ARGV) ) {
# Check for -pN
if ( $token =~ /^-p(\d+)$/ ) {
$processors = int($1);
}
# Check for -p N
elsif ( $token eq "-p" ) {
$processors = int( shift(@ARGV) );
}
elsif ( $token eq "-system" ) {
$system_type = shift(@ARGV);
}
# Check for a task list file
elsif ( $token =~ /^-l(.+)$/ ) {
push( @task_files, expand_user_path($1) );
}
elsif ( $token eq "-l" ) {
push( @task_files, expand_user_path( shift(@ARGV) ) );
}
elsif ( $token eq "-hide_runtime" ) {
$show_runtime_estimates = 0;
}
elsif ( $token =~ /^-/ ) {
die "Invalid option: $token\n";
}
# must be a task name
else {
if ( $token =~ /(.*)\/$/ ) {
$token = $1;
}
push( @tasks, $token );
}
}
# Check threaded
if ( $processors > 1 and not $threaded ) {
print
"Multithreaded option specified, but is not supported by this version of perl. Execution will be single threaded.\n";
$processors = 1;
}
# Read Task Files
foreach (@task_files) {
open( FH, $_ ) or die "$! ($_)\n";
while (<FH>) {
push( @tasks, $_ );
}
close(FH);
}
# Remove duplicate tasks
my %hash = map { $_, 1 } @tasks;
@tasks = keys %hash;
#print "Processors: $processors\n";
#print "Tasks: @tasks\n";
if ( $#tasks == -1 ) {
die "\n"
. "Incorect usage. You must specify at least one task to execute\n"
. "\n"
. "USAGE:\n"
. "run_vtr_task.pl <TASK1> <TASK2> ... \n" . "\n"
. "OPTIONS:\n"
. "-l <path_to_task_list.txt> - Provides a text file with a list of tasks\n"
. "-p <N> - Execution is performed in parallel using N threads (Default: 1)\n";
}
##############################################################
# Run tasks
##############################################################
foreach my $task (@tasks) {
chomp($task);
run_single_task($task);
}
##############################################################
# Subroutines
##############################################################
sub run_single_task {
my $circuits_dir;
my $archs_dir;
my $sdc_dir = "sdc";
my $script_default = "run_vtr_flow.pl";
my $script = $script_default;
my $script_path;
my $script_params = "";
my @circuits;
my @archs;
my $cmos_tech_path = "";
my $task = shift(@_);
my $task_dir = "$vtr_flow_path/tasks/$task";
chdir($task_dir) or die "Task directory does not exist ($task_dir): $!";
print "\n$task\n";
print "-----------------------------------------\n";
# Get Task Config Info
my $task_config_file_path = "config/config.txt";
open( CONFIG_FH, $task_config_file_path )
or die
"Cannot find task configuration file ($task_dir/$task_config_file_path)";
while (<CONFIG_FH>) {
my $line = $_;
chomp($line);
if ( $line =~ /^\s*#.*$/ or $line =~ /^\s*$/ ) { next; }
my @data = split( /=/, $line );
my $key = trim( $data[0] );
my $value = trim( $data[1] );
if ( $key eq "circuits_dir" ) {
$circuits_dir = $value;
}
elsif ( $key eq "archs_dir" ) {
$archs_dir = $value;
}
elsif ( $key eq "sdc_dir" ) {
$sdc_dir = $value;
}
elsif ( $key eq "circuit_list_add" ) {
push( @circuits, $value );
}
elsif ( $key eq "arch_list_add" ) {
push( @archs, $value );
}
elsif ( $key eq "script_path" ) {
$script = $value;
}
elsif ( $key eq "script_params" ) {
$script_params = $value;
}
elsif ( $key eq "cmos_tech_behavior" ) {
$cmos_tech_path = $value;
}
elsif ($key eq "parse_file"
or $key eq "qor_parse_file"
or $key eq "pass_requirements_file" )
{
#Used by parser
}
else {
die "Invalid option (" . $key . ") in configuration file.";
}
}
# Using default script
if ( $script eq $script_default ) {
# This is hack to automatically add the option '-temp_dir .' if using the run_vtr_flow.pl script
# This ensures that a 'temp' folder is not created in each circuit directory
if ( !( $script_params =~ /-temp_dir/ ) ) {
$script_params = $script_params . " -temp_dir . ";
}
}
else {
$show_runtime_estimates = 0;
}
$circuits_dir = expand_user_path($circuits_dir);
$archs_dir = expand_user_path($archs_dir);
$sdc_dir = expand_user_path($sdc_dir);
if ( -d "$vtr_flow_path/$circuits_dir" ) {
$circuits_dir = "$vtr_flow_path/$circuits_dir";
}
elsif ( -d $circuits_dir ) {
}
else {
die "Circuits directory not found ($circuits_dir)";
}
if ( -d "$vtr_flow_path/$archs_dir" ) {
$archs_dir = "$vtr_flow_path/$archs_dir";
}
elsif ( -d $archs_dir ) {
}
else {
die "Archs directory not found ($archs_dir)";
}
if ( -d "$vtr_flow_path/$sdc_dir" ) {
$sdc_dir = "$vtr_flow_path/$sdc_dir";
}
elsif ( -d $sdc_dir ) {
}
else {
$sdc_dir = "$vtr_flow_path/sdc";
}
(@circuits) or die "No circuits specified for task $task";
(@archs) or die "No architectures specified for task $task";
# Check script
$script = expand_user_path($script);
if ( -e "$task_dir/config/$script" ) {
$script_path = "$task_dir/config/$script";
}
elsif ( -e "$vtr_flow_path/scripts/$script" ) {
$script_path = "$vtr_flow_path/scripts/$script";
}
elsif ( -e $script ) {
}
else {
die
"Cannot find script for task $task ($script). Looked for $task_dir/config/$script or $vtr_flow_path/scripts/$script";
}
# Check architectures
foreach my $arch (@archs) {
(-f "$archs_dir/$arch") or die "Architecture file not found ($archs_dir/$arch)";
}
# Check circuits
foreach my $circuit (@circuits) {
(-f "$circuits_dir/$circuit") or die "Circuit file not found ($circuits_dir/$circuit)";
}
# Check CMOS tech behavior
if ( $cmos_tech_path ne "" ) {
$cmos_tech_path = expand_user_path($cmos_tech_path);
if ( -e "$task_dir/config/$cmos_tech_path" ) {
$cmos_tech_path = "$task_dir/config/$cmos_tech_path";
}
elsif ( -e "$vtr_flow_path/tech/$cmos_tech_path" ) {
$cmos_tech_path = "$vtr_flow_path/tech/$cmos_tech_path";
}
elsif ( -e $cmos_tech_path ) {
}
else {
die
"Cannot find CMOS technology behavior file for $task ($script). Looked for $task_dir/config/$cmos_tech_path or $vtr_flow_path/tech/$cmos_tech_path";
}
$script_params = $script_params . " -cmos_tech $cmos_tech_path";
}
# Check if golden file exists
my $golden_results_file = "$task_dir/config/golden_results.txt";
if ($show_runtime_estimates) {
if ( not -r $golden_results_file ) {
$show_runtime_estimates = 0;
}
}
##############################################################
# Create a new experiment directory to run experiment in
# Counts up until directory number doesn't exist
##############################################################
my $experiment_number = 1;
while ( -e "$run_prefix$experiment_number" ) {
++$experiment_number;
}
mkdir( "$run_prefix$experiment_number", 0775 )
or die "Failed to make directory ($run_prefix$experiment_number): $!";
chmod( 0775, "$run_prefix$experiment_number" );
chdir("$run_prefix$experiment_number")
or die
"Failed to change to directory ($run_prefix$experiment_number): $!";
# Create the directory structure
# Make this seperately from file script
# just in case failure occurs creating directory
foreach my $arch (@archs) {
mkdir( "$arch", 0775 ) or die "Failed to create directory ($arch): $!";
chmod( 0775, "$arch" );
foreach my $circuit (@circuits) {
mkdir( "$arch/$circuit", 0775 )
or die "Failed to create directory $arch/$circuit: $!";
chmod( 0775, "$arch/$circuit" );
}
}
##############################################################
# Run experiment
##############################################################
if ( $system_type eq "local" ) {
if ( $processors == 1 ) {
foreach my $circuit (@circuits) {
foreach my $arch (@archs) {
if ($show_runtime_estimates) {
my $runtime =
ret_expected_runtime( $circuit, $arch,
$golden_results_file );
print strftime "Current time: %b-%d %I:%M %p. ",
localtime;
print "Expected runtime of next benchmark: " . $runtime
. "\n";
}
chdir(
"$task_dir/$run_prefix${experiment_number}/${arch}/${circuit}"
)
; # or die "Cannot change to directory $StartDir/$run_prefix${experiment_number}/${arch}/${circuit}: $!";
# SDC file defaults to circuit_name.sdc
my $sdc = fileparse( $circuit, '\.[^.]+$' ) . ".sdc";
system(
"$script_path $circuits_dir/$circuit $archs_dir/$arch -sdc_file $sdc_dir/$sdc $script_params\n"
);
}
}
}
else {
my $thread_work = Thread::Queue->new();
my $thread_result = Thread::Queue->new();
my $threads = $processors;
# print "# of Threads: $threads\n";
foreach my $circuit (@circuits) {
foreach my $arch (@archs) {
my $dir =
"$task_dir/$run_prefix${experiment_number}/${arch}/${circuit}";
# SDC file defaults to circuit_name.sdc
my $sdc = fileparse( $circuit, '\.[^.]+$' ) . ".sdc";
my $command =
"$script_path $circuits_dir/$circuit $archs_dir/$arch -sdc_file $sdc_dir/$sdc $script_params";
$thread_work->enqueue("$dir||||$command");
}
}
my @pool =
map { threads->create( \&do_work, $thread_work, $thread_result ) }
1 .. $threads;
for ( 1 .. $threads ) {
while ( my $result = $thread_result->dequeue ) {
chomp($result);
print $result . "\n";
}
}
$_->join for @pool;
}
}
elsif ( $system_type eq "PBS_UBC" ) {
# PBS system
my @job_ids;
foreach my $circuit (@circuits) {
foreach my $arch (@archs) {
open( PBS_FILE,
">$task_dir/$run_prefix${experiment_number}/${arch}/${circuit}/pbs_job.txt"
);
print PBS_FILE "#!/bin/bash\n";
print PBS_FILE "#PBS -S /bin/bash\n";
print PBS_FILE "#PBS -N $task-$arch-$circuit\n";
print PBS_FILE "#PBS -l nodes=1\n";
print PBS_FILE "#PBS -l walltime=168:00:00\n";
if ( $circuit =~ /PEEng/ ) {
print PBS_FILE "#PBS -l mem=6000mb\n";
}
elsif ( $circuit =~ /mcml/ or $circuit =~ /stereovision2/ ) {
print PBS_FILE "#PBS -l mem=5000mb\n";
}
else {
print PBS_FILE "#PBS -l mem=1500mb\n";
}
print PBS_FILE
"#PBS -o $task_dir/$run_prefix${experiment_number}/${arch}/${circuit}/pbs_out.txt\n";
print PBS_FILE
"#PBS -e $task_dir/$run_prefix${experiment_number}/${arch}/${circuit}/pbs_error.txt\n";
print PBS_FILE "#PBS -q g8\n";
print PBS_FILE
"cd $task_dir/$run_prefix${experiment_number}/${arch}/${circuit}\n";
print PBS_FILE
"$script_path $circuits_dir/$circuit $archs_dir/$arch $script_params\n";
close(PBS_FILE);
my $line =
`qsub $task_dir/$run_prefix${experiment_number}/${arch}/${circuit}/pbs_job.txt`;
$line =~ /(\d+)\D/;
push(
@job_ids,
[
$1,
"$task_dir/$run_prefix${experiment_number}/${arch}/${circuit}/pbs_out.txt",
"$task_dir/$run_prefix${experiment_number}/${arch}/${circuit}/pbs_error.txt"
]
);
}
}
# It seems that showq takes a bit of time before the new jobs show up
sleep(30);
# Wait for all of the jobs to finish
while ( ( $#job_ids + 1 ) != 0 ) {
# Check job status at intervals
sleep(5);
# Get showq output
my $showq_out = `showq`;
my $idx;
while ( $idx < ( $#job_ids + 1 ) ) {
if ( $showq_out =~ /^($job_ids[$idx][0])\s/m ) {
$idx++;
}
else {
print `cat $job_ids[$idx][1]`;
print `cat $job_ids[$idx][2]`;
splice @job_ids, $idx, 1;
}
}
}
}
}
sub do_work {
my ( $work_queue, $return_queue ) = @_;
my $tid = threads->tid;
while (1) {
my $work = $work_queue->dequeue_nb();
my @work = split( /\|\|\|\|/, $work );
my $dir = @work[0];
my $command = @work[1];
if ( !$dir ) {
last;
}
system "cd $dir; $command > thread_${tid}.out";
open( OUT_FILE, "$dir/thread_${tid}.out" )
or die "Cannot open $dir/thread_${tid}.out: $!";
my $sys_output = do { local $/; <OUT_FILE> };
#$sys_output =~ s/\n//g;
$return_queue->enqueue($sys_output);
}
$return_queue->enqueue(undef);
#print "$tid exited loop\n"
}
# trim whitespace
sub trim($) {
my $string = shift;
$string =~ s/^\s+//;
$string =~ s/\s+$//;
return $string;
}
sub expand_user_path {
my $str = shift;
$str =~ s/^~\//$ENV{"HOME"}\//;
return $str;
}
sub ret_expected_runtime {
my $circuit_name = shift;
my $arch_name = shift;
my $golden_results_file_path = shift;
my $seconds = 0;
open( GOLDEN, $golden_results_file_path );
my @lines = <GOLDEN>;
close(GOLDEN);
my $header_line = shift(@lines);
my @headers = split( /\s+/, $header_line );
my %index;
@index{@headers} = ( 0 .. $#headers );
my @line_array;
my $found = 0;
foreach my $line (@lines) {
@line_array = split( /\s+/, $line );
if ( $arch_name eq @line_array[0] and $circuit_name eq @line_array[1] )
{
$found = 1;
last;
}
}
if ( not $found ) {
return "Unknown";
}
my $location = $index{"pack_time"};
if ($location) {
$seconds += @line_array[$location];
}
my $location = $index{"place_time"};
if ($location) {
$seconds += @line_array[$location];
}
my $location = $index{"min_chan_width_route_time"};
if ($location) {
$seconds += @line_array[$location];
}
my $location = $index{"crit_path_route_time"};
if ($location) {
$seconds += @line_array[$location];
}
my $location = $index{"route_time"};
if ($location) {
$seconds += @line_array[$location];
}
if ( $seconds != 0 ) {
if ( $seconds < 60 ) {
my $str = sprintf( "%.0f seconds", $seconds );
return $str;
}
elsif ( $seconds < 3600 ) {
my $min = $seconds / 60;
my $str = sprintf( "%.0f minutes", $min );
return $str;
}
else {
my $hour = $seconds / 60 / 60;
my $str = sprintf( "%.0f hours", $hour );
return $str;
}
}
else {
return "Unknown";
}
}
| UGent-HES/ConnectionRouter | vtr_flow/scripts/run_vtr_task.pl | Perl | mit | 15,462 |
:- module(assrt_example, [p/1]).
:- use_module(library(assertions)).
:- use_module(library(plprops)).
:- check pred p(A) :: int(A) + not_fails.
p(1).
p(2).
| TeamSPoon/logicmoo_workspace | packs_lib/assertions/examples/assrt_example.pl | Perl | mit | 159 |
## OpenXPKI::Crypto::Tool::SCEP::Command::create_certificate_reply.pm
## Written 2006 by Alexander Klink for the OpenXPKI project
## (C) Copyright 2006 by The OpenXPKI Project
package OpenXPKI::Crypto::Tool::SCEP::Command::create_certificate_reply;
use strict;
use warnings;
use Class::Std;
use OpenXPKI::Debug;
use OpenXPKI::FileUtils;
use Data::Dumper;
my %fu_of :ATTR; # a FileUtils instance
my %outfile_of :ATTR;
my %tmp_of :ATTR;
my %pkcs7_of :ATTR;
my %cert_of :ATTR;
my %engine_of :ATTR;
my %enc_alg_of :ATTR;
sub START {
my ($self, $ident, $arg_ref) = @_;
$fu_of {$ident} = OpenXPKI::FileUtils->new();
$engine_of {$ident} = $arg_ref->{ENGINE};
$tmp_of {$ident} = $arg_ref->{TMP};
$pkcs7_of {$ident} = $arg_ref->{PKCS7};
$cert_of {$ident} = $arg_ref->{CERTIFICATE};
$enc_alg_of{$ident} = $arg_ref->{ENCRYPTION_ALG};
}
sub get_command {
my $self = shift;
my $ident = ident $self;
# keyfile, signcert, passin
if (! defined $engine_of{$ident}) {
OpenXPKI::Exception->throw(
message => 'I18N_OPENXPKI_CRYPTO_TOOL_SCEP_COMMAND_CREATE_PENDING_REPLY_NO_ENGINE',
);
}
##! 64: 'engine: ' . Dumper($engine_of{$ident})
my $keyfile = $engine_of{$ident}->get_keyfile();
if (! defined $keyfile || $keyfile eq '') {
OpenXPKI::Exception->throw(
message => 'I18N_OPENXPKI_CRYPTO_TOOL_SCEP_COMMAND_CREATE_PENDING_REPLY_KEYFILE_MISSING',
);
}
my $certfile = $engine_of{$ident}->get_certfile();
if (! defined $certfile || $certfile eq '') {
OpenXPKI::Exception->throw(
message => 'I18N_OPENXPKI_CRYPTO_TOOL_SCEP_COMMAND_CREATE_PENDING_REPLY_CERTFILE_MISSING',
);
}
$ENV{pwd} = $engine_of{$ident}->get_passwd();
my $in_filename = $fu_of{$ident}->get_safe_tmpfile({
'TMP' => $tmp_of{$ident},
});
$outfile_of{$ident} = $fu_of{$ident}->get_safe_tmpfile({
'TMP' => $tmp_of{$ident},
});
$fu_of{$ident}->write_file({
FILENAME => $in_filename,
CONTENT => $pkcs7_of{$ident},
FORCE => 1,
});
my $issued_certfile = $fu_of{$ident}->get_safe_tmpfile({
'TMP' => $tmp_of{$ident},
});
$fu_of{$ident}->write_file({
FILENAME => $issued_certfile,
CONTENT => $cert_of{$ident},
FORCE => 1,
});
my $command = " -new -passin env:pwd -signcert $certfile -msgtype CertRep -status SUCCESS -keyfile $keyfile -inform DER -in $in_filename -outform DER -out $outfile_of{$ident} -issuedcert $issued_certfile ";
if ($enc_alg_of{$ident} eq 'DES') {
# if the configured encryption algorithm is DES, append the
# appropriate option. This is for example needed for
# Netscreen devices
$command .= " -des ";
}
return $command;
}
sub hide_output
{
return 0;
}
sub key_usage
{
return 0;
}
sub get_result
{
my $self = shift;
my $ident = ident $self;
my $reply = $fu_of{$ident}->read_file($outfile_of{$ident});
return $reply;
}
sub cleanup {
$ENV{pwd} = '';
}
1;
__END__
=head1 Name
OpenXPKI::Crypto::Tool::SCEP::Command::create_certificate_reply
=head1 Functions
=head2 get_command
=over
=item * PKCS7
=back
=head2 hide_output
returns 0
=head2 key_usage
returns 0
=head2 get_result
Creates an SCEP reply containing the issued certificate.
| durko/openxpki | core/server/OpenXPKI/Crypto/Tool/SCEP/Command/create_certificate_reply.pm | Perl | apache-2.0 | 3,415 |
package VMOMI::HostProfileManager;
use parent 'VMOMI::ProfileManager';
use strict;
use warnings;
our @class_ancestors = (
'ProfileManager',
'ProfileManager',
'ManagedObject',
);
our @class_members = ( );
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1; | stumpr/p5-vmomi | lib/VMOMI/HostProfileManager.pm | Perl | apache-2.0 | 435 |
# The Computer Language Benchmarks Game
# http://shootout.alioth.debian.org/
#
# contributed by David Pyke, March 2005
# optimized by Steffen Mueller, Sept 2007
use integer;
use strict;
sub nsieve {
my ($m) = @_;
my @a = (1) x $m;
my $count = 0;
foreach my $i (2..$m-1) {
if ($a[$i]) {
for (my $j = $i + $i; $j < $m; $j += $i){
$a[$j] = 0;
}
++$count;
}
}
return $count;
}
sub nsieve_test {
my($n) = @_;
my $m = (1<<$n) * 10000;
my $ncount= nsieve($m);
printf "Primes up to %8u %8u\n", $m, $ncount;
}
my $N = ($ARGV[0] < 1) ? 1 : $ARGV[0];
nsieve_test($N);
nsieve_test($N-1) if $N >= 1;
nsieve_test($N-2) if $N >= 2;
| chrislo/sourceclassifier | sources/perl/nsieve.perl-2.perl | Perl | mit | 710 |
use POSIX 'strftime';
$date = strftime '%Y-%m-%d', localtime;
while (<testfiles/*>) {
chomp;
$x = "cp $_";
s/2015-MM-DD/$date/;
$x .= " /tmp/$_\n";
print($x);
system($x);
}
| itsdavidbaxter/Tools | scripts/pahma/batch_barcode/setupTests.pl | Perl | apache-2.0 | 190 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 NAME
Bio::EnsEMBL::Compara::DBSQL::PeptideAlignFeatureAdaptor
=head1 SYNOPSIS
$peptideAlignFeatureAdaptor = $db_adaptor->get_PeptideAlignFeatureAdaptor;
$peptideAlignFeatureAdaptor = $peptideAlignFeatureObj->adaptor;
=head1 DESCRIPTION
Module to encapsulate all db access for persistent class PeptideAlignFeature
There should be just one per application and database connection.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
use strict;
use warnings;
package Bio::EnsEMBL::Compara::DBSQL::PeptideAlignFeatureAdaptor;
use DBI qw(:sql_types);
use Bio::EnsEMBL::Compara::PeptideAlignFeature;
use Bio::EnsEMBL::Utils::Exception;
use base ('Bio::EnsEMBL::Compara::DBSQL::BaseAdaptor');
#############################
#
# fetch methods
#
#############################
=head2 fetch_all_by_qmember_id
Arg [1] : int $member->dbID
the database id for a peptide member
Example : $pafs = $adaptor->fetch_all_by_qmember_id($member->dbID);
Description: Returns all PeptideAlignFeatures from all target species
where the query peptide member is know.
Returntype : array reference of Bio::EnsEMBL::Compara::PeptideAlignFeature objects
Exceptions : thrown if $id is not defined
Caller : general
=cut
sub fetch_all_by_qmember_id{
my $self = shift;
my $seq_member_id = shift;
throw("seq_member_id undefined") unless($seq_member_id);
my $member = $self->db->get_SeqMemberAdaptor->fetch_by_dbID($seq_member_id);
$self->{_curr_gdb_id} = $member->genome_db_id;
my $constraint = 'paf.qmember_id = ?';
$self->bind_param_generic_fetch($seq_member_id, SQL_INTEGER);
return $self->generic_fetch($constraint);
}
=head2 fetch_all_by_hmember_id
Arg [1] : int $member->dbID
the database id for a peptide member
Example : $pafs = $adaptor->fetch_all_by_hmember_id($member->dbID);
Description: Returns all PeptideAlignFeatures from all query species
where the hit peptide member is know.
Returntype : array reference of Bio::EnsEMBL::Compara::PeptideAlignFeature objects
Exceptions : thrown if $id is not defined
Caller : general
=cut
sub fetch_all_by_hmember_id{
my $self = shift;
my $seq_member_id = shift;
throw("seq_member_id undefined") unless($seq_member_id);
my @pafs;
foreach my $genome_db_id ($self->_get_all_genome_db_ids) {
push @pafs, @{$self->fetch_all_by_hmember_id_qgenome_db_id($seq_member_id, $genome_db_id)};
}
return \@pafs;
}
=head2 fetch_all_by_qmember_id_hmember_id
Arg [1] : int $query_member->dbID
the database id for a peptide member
Arg [2] : int $hit_member->dbID
the database id for a peptide member
Example : $pafs = $adaptor->fetch_all_by_qmember_id_hmember_id($qmember_id, $hmember_id);
Description: Returns all PeptideAlignFeatures for a given query member and
hit member. If pair did not align, array will be empty.
Returntype : array reference of Bio::EnsEMBL::Compara::PeptideAlignFeature objects
Exceptions : thrown if either seq_member_id is not defined
Caller : general
=cut
sub fetch_all_by_qmember_id_hmember_id{
my $self = shift;
my $qmember_id = shift;
my $hmember_id = shift;
throw("must specify query member dbID") unless($qmember_id);
throw("must specify hit member dbID") unless($hmember_id);
my $qmember = $self->db->get_SeqMemberAdaptor->fetch_by_dbID($qmember_id);
$self->{_curr_gdb_id} = $qmember->genome_db_id;
my $constraint = 'paf.qmember_id=? AND paf.hmember_id=?';
$self->bind_param_generic_fetch($qmember_id, SQL_INTEGER);
$self->bind_param_generic_fetch($hmember_id, SQL_INTEGER);
return $self->generic_fetch($constraint);
}
=head2 fetch_all_by_qmember_id_hgenome_db_id
Arg [1] : int $query_member->dbID
the database id for a peptide member
Arg [2] : int $hit_genome_db->dbID
the database id for a genome_db
Example : $pafs = $adaptor->fetch_all_by_qmember_id_hgenome_db_id(
$member->dbID, $genome_db->dbID);
Description: Returns all PeptideAlignFeatures for a given query member and
target hit species specified via a genome_db_id
Returntype : array reference of Bio::EnsEMBL::Compara::PeptideAlignFeature objects
Exceptions : thrown if either member->dbID or genome_db->dbID is not defined
Caller : general
=cut
sub fetch_all_by_qmember_id_hgenome_db_id{
my $self = shift;
my $qmember_id = shift;
my $hgenome_db_id = shift;
throw("must specify query member dbID") unless($qmember_id);
throw("must specify hit genome_db dbID") unless($hgenome_db_id);
my $qmember = $self->db->get_SeqMemberAdaptor->fetch_by_dbID($qmember_id);
$self->{_curr_gdb_id} = $qmember->genome_db_id;
my $constraint = 'paf.qmember_id=? AND paf.hgenome_db_id=?';
$self->bind_param_generic_fetch($qmember_id, SQL_INTEGER);
$self->bind_param_generic_fetch($hgenome_db_id, SQL_INTEGER);
return $self->generic_fetch($constraint);
}
=head2 fetch_all_by_hmember_id_qgenome_db_id
Arg [1] : int $hit_member->dbID
the database id for a peptide member
Arg [2] : int $query_genome_db->dbID
the database id for a genome_db
Example : $pafs = $adaptor->fetch_all_by_hmember_id_qgenome_db_id(
$member->dbID, $genome_db->dbID);
Description: Returns all PeptideAlignFeatures for a given hit member and
query species specified via a genome_db_id
Returntype : array reference of Bio::EnsEMBL::Compara::PeptideAlignFeature objects
Exceptions : thrown if either member->dbID or genome_db->dbID is not defined
Caller : general
=cut
sub fetch_all_by_hmember_id_qgenome_db_id{
my $self = shift;
my $hmember_id = shift;
my $qgenome_db_id = shift;
throw("must specify hit member dbID") unless($hmember_id);
throw("must specify query genome_db dbID") unless($qgenome_db_id);
$self->{_curr_gdb_id} = $qgenome_db_id;
# we don't need to add "paf.qgenome_db_id=$qgenome_db_id" because it is implicit from the table name
my $constraint = 'paf.hmember_id=?';
$self->bind_param_generic_fetch($hmember_id, SQL_INTEGER);
return $self->generic_fetch($constraint);
}
sub fetch_all_by_hgenome_db_id{
my $self = shift;
my $hgenome_db_id = shift;
throw("must specify hit genome_db dbID") unless($hgenome_db_id);
my @pafs;
foreach my $genome_db_id ($self->_get_all_genome_db_ids) {
push @pafs, @{$self->fetch_all_by_qgenome_db_id_hgenome_db_id($genome_db_id, $hgenome_db_id)};
}
return \@pafs;
}
sub fetch_all_by_qgenome_db_id{
my $self = shift;
my $qgenome_db_id = shift;
throw("must specify query genome_db dbID") unless($qgenome_db_id);
$self->{_curr_gdb_id} = $qgenome_db_id;
return $self->generic_fetch();
}
sub fetch_all_by_qgenome_db_id_hgenome_db_id{
my $self = shift;
my $qgenome_db_id = shift;
my $hgenome_db_id = shift;
throw("must specify query genome_db dbID") unless($qgenome_db_id);
throw("must specify hit genome_db dbID") unless($hgenome_db_id);
$self->{_curr_gdb_id} = $qgenome_db_id;
my $constraint = 'paf.hgenome_db_id = ?';
$self->bind_param_generic_fetch($hgenome_db_id, SQL_INTEGER);
return $self->generic_fetch($constraint);
}
sub fetch_all_besthit_by_qgenome_db_id{
my $self = shift;
my $qgenome_db_id = shift;
throw("must specify query genome_db dbID") unless($qgenome_db_id);
$self->{_curr_gdb_id} = $qgenome_db_id;
my $constraint = "paf.hit_rank=1";
return $self->generic_fetch($constraint);
}
sub fetch_all_besthit_by_qgenome_db_id_hgenome_db_id{
my $self = shift;
my $qgenome_db_id = shift;
my $hgenome_db_id = shift;
throw("must specify query genome_db dbID") unless($qgenome_db_id);
throw("must specify hit genome_db dbID") unless($hgenome_db_id);
$self->{_curr_gdb_id} = $qgenome_db_id;
my $constraint = 'paf.hgenome_db_id = ? AND paf.hit_rank=1';
$self->bind_param_generic_fetch($hgenome_db_id, SQL_INTEGER);
return $self->generic_fetch($constraint);
}
=head2 fetch_selfhit_by_qmember_id
Arg [1] : int $member->dbID
the database id for a peptide member
Example : $paf = $adaptor->fetch_selfhit_by_qmember_id($member->dbID);
Description: Returns the selfhit PeptideAlignFeature defined by the id $id.
Returntype : Bio::EnsEMBL::Compara::PeptideAlignFeature
Exceptions : thrown if $id is not defined
Caller : general
=cut
sub fetch_selfhit_by_qmember_id {
my $self= shift;
my $qmember_id = shift;
throw("qmember_id undefined") unless($qmember_id);
my $member = $self->db->get_SeqMemberAdaptor->fetch_by_dbID($qmember_id);
$self->{_curr_gdb_id} = $member->genome_db_id;
my $constraint = 'qmember_id=? AND qmember_id=hmember_id';
$self->bind_param_generic_fetch($qmember_id, SQL_INTEGER);
return $self->generic_fetch_one($constraint);
}
#############################
#
# store methods
#
#############################
sub rank_and_store_PAFS {
my ($self, @features) = @_;
my %by_query = ();
foreach my $f (@features) {
push @{$by_query{$f->query_genome_db_id}{$f->query_member_id}}, $f;
};
foreach my $query_genome_db_id (keys %by_query) {
foreach my $sub_features (values %{$by_query{$query_genome_db_id}}) {
my @pafList = sort sort_by_score_evalue_and_pid @$sub_features;
my $rank = 1;
my $prevPaf = undef;
foreach my $paf (@pafList) {
$rank++ if($prevPaf and !pafs_equal($prevPaf, $paf));
$paf->hit_rank($rank);
$prevPaf = $paf;
}
$self->store_PAFS(@pafList);
}
}
}
## WARNING: all the features are supposed to come from the same query_genome_db_id !
sub store_PAFS {
my ($self, @features) = @_;
return unless(@features);
# Query genome db id should always be the same
my $first_qgenome_db_id = $features[0]->query_genome_db_id;
my $tbl_name = 'peptide_align_feature';
if ($first_qgenome_db_id){
my $gdb = $self->db->get_GenomeDBAdaptor->fetch_by_dbID($first_qgenome_db_id);
$tbl_name .= "_$first_qgenome_db_id";
}
my @stored_columns = qw(qmember_id hmember_id qgenome_db_id hgenome_db_id qstart qend hstart hend score evalue align_length identical_matches perc_ident positive_matches perc_pos hit_rank cigar_line);
my $query = sprintf('INSERT INTO %s (%s) VALUES (%s)', $tbl_name, join(',', @stored_columns), join(',', map {'?'} @stored_columns) );
my $sth = $self->prepare($query);
foreach my $paf (@features) {
# print STDERR "== ", $paf->query_member_id, " - ", $paf->hit_member_id, "\n";
$sth->execute($paf->query_member_id, $paf->hit_member_id, $paf->query_genome_db_id, $paf->hit_genome_db_id,
$paf->qstart, $paf->qend, $paf->hstart, $paf->hend,
$paf->score, $paf->evalue, $paf->alignment_length,
$paf->identical_matches, $paf->perc_ident, $paf->positive_matches, $paf->perc_pos, $paf->hit_rank, $paf->cigar_line);
}
}
sub sort_by_score_evalue_and_pid {
$b->score <=> $a->score ||
$a->evalue <=> $b->evalue ||
$b->perc_ident <=> $a->perc_ident ||
$b->perc_pos <=> $a->perc_pos;
}
sub pafs_equal {
my ($paf1, $paf2) = @_;
return 0 unless($paf1 and $paf2);
return 1 if(($paf1->score == $paf2->score) and
($paf1->evalue == $paf2->evalue) and
($paf1->perc_ident == $paf2->perc_ident) and
($paf1->perc_pos == $paf2->perc_pos));
return 0;
}
sub displayHSP {
my($paf) = @_;
my $percent_ident = int($paf->identical_matches*100/$paf->alignment_length);
my $pos = int($paf->positive_matches*100/$paf->alignment_length);
print("=> $paf\n");
print("pep_align_feature :\n" .
" seq_member_id : " . $paf->seq_member_id . "\n" .
" start : " . $paf->start . "\n" .
" end : " . $paf->end . "\n" .
" hseq_member_id : " . $paf->hseq_member_id . "\n" .
" hstart : " . $paf->hstart . "\n" .
" hend : " . $paf->hend . "\n" .
" score : " . $paf->score . "\n" .
" p_value : " . $paf->p_value . "\n" .
" alignment_length : " . $paf->alignment_length . "\n" .
" identical_matches : " . $paf->identical_matches . "\n" .
" perc_ident : " . $percent_ident . "\n" .
" positive_matches : " . $paf->positive_matches . "\n" .
" perc_pos : " . $pos . "\n" .
" cigar_line : " . $paf->cigar_string . "\n");
}
sub displayHSP_short {
my($paf) = @_;
unless(defined($paf)) {
print("qy_stable_id\t\t\thit_stable_id\t\t\tscore\talen\t\%ident\t\%positive\n");
return;
}
my $perc_ident = int($paf->identical_matches*100/$paf->alignment_length);
my $perc_pos = int($paf->positive_matches*100/$paf->alignment_length);
print("HSP ".$paf->seq_member_id."(".$paf->start.",".$paf->end.")".
"\t" . $paf->hseq_member_id. "(".$paf->hstart.",".$paf->hend.")".
"\t" . $paf->score .
"\t" . $paf->alignment_length .
"\t" . $perc_ident .
"\t" . $perc_pos . "\n");
}
############################
#
# INTERNAL METHODS
# (pseudo subclass methods)
#
############################
#internal method used in multiple calls above to build objects from table data
sub _tables {
my $self = shift;
return (['peptide_align_feature_'.$self->{_curr_gdb_id}, 'paf'] );
}
sub _columns {
my $self = shift;
return qw (paf.peptide_align_feature_id
paf.qmember_id
paf.hmember_id
paf.qstart
paf.qend
paf.hstart
paf.hend
paf.score
paf.evalue
paf.align_length
paf.identical_matches
paf.perc_ident
paf.positive_matches
paf.perc_pos
paf.hit_rank
paf.cigar_line
);
}
sub _objs_from_sth {
my ($self, $sth) = @_;
my @pafs = ();
while( my $row_hashref = $sth->fetchrow_hashref()) {
my $paf = Bio::EnsEMBL::Compara::PeptideAlignFeature->new();
$paf->dbID($row_hashref->{'peptide_align_feature_id'});
$paf->adaptor($self);
$paf->qstart($row_hashref->{'qstart'});
$paf->qend($row_hashref->{'qend'});
$paf->hstart($row_hashref->{'hstart'});
$paf->hend($row_hashref->{'hend'});
$paf->score($row_hashref->{'score'});
$paf->evalue($row_hashref->{'evalue'});
$paf->alignment_length($row_hashref->{'align_length'});
$paf->identical_matches($row_hashref->{'identical_matches'});
$paf->perc_ident($row_hashref->{'perc_ident'});
$paf->positive_matches($row_hashref->{'positive_matches'});
$paf->perc_pos($row_hashref->{'perc_pos'});
$paf->hit_rank($row_hashref->{'hit_rank'});
$paf->cigar_line($row_hashref->{'cigar_line'});
$paf->rhit_dbID($row_hashref->{'pafid2'});
my $memberDBA = $self->db->get_SeqMemberAdaptor;
if($row_hashref->{'qmember_id'} and $memberDBA) {
$paf->query_member($memberDBA->fetch_by_dbID($row_hashref->{'qmember_id'}));
}
if($row_hashref->{'hmember_id'} and $memberDBA) {
$paf->hit_member($memberDBA->fetch_by_dbID($row_hashref->{'hmember_id'}));
}
#$paf->display_short();
push @pafs, $paf;
}
$sth->finish;
return \@pafs;
}
sub _get_all_genome_db_ids {
my $self = shift;
return $self->db->get_GenomeDBAdaptor->_id_cache->cache_keys;
}
###############################################################################
#
# General access methods that could be moved
# into a superclass
#
###############################################################################
#sub fetch_by_dbID_qgenome_db_id {
=head2 fetch_by_dbID
Arg [1] : int $id
the unique database identifier for the feature to be obtained
Example : $paf = $adaptor->fetch_by_dbID(1234);
Description: Returns the PeptideAlignFeature created from the database defined by the
the id $id.
Returntype : Bio::EnsEMBL::Compara::PeptideAlignFeature
Exceptions : thrown if $id is not defined
Caller : general
=cut
sub fetch_by_dbID{
my ($self,$id) = @_;
unless(defined $id) {
throw("fetch_by_dbID must have an id");
}
$self->{_curr_gdb_id} = int($id/100000000);
my $constraint = 'peptide_align_feature_id=?';
$self->bind_param_generic_fetch($id, SQL_INTEGER);
return $self->generic_fetch_one($constraint);
}
=head2 fetch_all_by_dbID_list
Arg [1] : array ref $id_list_ref
the unique database identifier for the feature to be obtained
Example : $pafs = $adaptor->fetch_by_dbID( [paf1_id, $paf2_id, $paf3_id] );
Description: Returns the PeptideAlignFeature created from the database defined by the
the id $id.
Returntype : array reference of Bio::EnsEMBL::Compara::PeptideAlignFeature objects
Exceptions : thrown if $id is not defined
Caller : general
=cut
sub fetch_all_by_dbID_list {
my $self = shift;
my $id_list_ref = shift;
return [map {$self->fetch_by_dbID($_)} @$id_list_ref];
}
=head2 fetch_BRH_by_member_genomedb
Arg [1] : seq_member_id of query peptide member
Arg [2] : genome_db_id of hit species
Example : $paf = $adaptor->fetch_BRH_by_member_genomedb(31957, 3);
Description: Returns the PeptideAlignFeature created from the database
This is the old algorithm for pulling BRHs (compara release 20-23)
Returntype : array reference of Bio::EnsEMBL::Compara::PeptideAlignFeature objects
Exceptions : none
Caller : general
=cut
sub fetch_BRH_by_member_genomedb
{
# using trick of specifying table twice so can join to self
my $self = shift;
my $qmember_id = shift;
my $hit_genome_db_id = shift;
#print(STDERR "fetch_all_RH_by_member_genomedb qmember_id=$qmember_id, genome_db_id=$hit_genome_db_id\n");
return unless($qmember_id and $hit_genome_db_id);
my $member = $self->db->get_SeqMemberAdaptor->fetch_by_dbID($qmember_id);
$self->{_curr_gdb_id} = $member->genome_db_id;
my $extrajoin = [
[ ['peptide_align_feature_'.$hit_genome_db_id, 'paf2'],
'paf.qmember_id=paf2.hmember_id AND paf.hmember_id=paf2.qmember_id',
['paf2.peptide_align_feature_id AS pafid2']]
];
my $constraint = "paf.hit_rank=1 AND paf2.hit_rank=1 AND paf.qmember_id=? AND paf.hgenome_db_id=?";
$self->bind_param_generic_fetch($qmember_id, SQL_INTEGER);
$self->bind_param_generic_fetch($hit_genome_db_id, SQL_INTEGER);
return $self->generic_fetch_one($constraint, $extrajoin);
}
=head2 fetch_all_RH_by_member_genomedb
Overview : This an experimental method and not currently used in production
Arg [1] : seq_member_id of query peptide member
Arg [2] : genome_db_id of hit species
Example : $feat = $adaptor->fetch_by_dbID($musBlastAnal, $ratBlastAnal);
Description: Returns all the PeptideAlignFeatures that reciprocal hit the qmember_id
onto the hit_genome_db_id
Returntype : array of Bio::EnsEMBL::Compara::PeptideAlignFeature objects by reference
Exceptions : thrown if $id is not defined
Caller : general
=cut
sub fetch_all_RH_by_member_genomedb
{
# using trick of specifying table twice so can join to self
my $self = shift;
my $qmember_id = shift;
my $hit_genome_db_id = shift;
#print(STDERR "fetch_all_RH_by_member_genomedb qmember_id=$qmember_id, genome_db_id=$hit_genome_db_id\n");
return unless($qmember_id and $hit_genome_db_id);
my $member = $self->db->get_SeqMemberAdaptor->fetch_by_dbID($qmember_id);
$self->{_curr_gdb_id} = $member->genome_db_id;
my $extrajoin = [
[ ['peptide_align_feature_'.$hit_genome_db_id, 'paf2'],
'paf.qmember_id=paf2.hmember_id AND paf.hmember_id=paf2.qmember_id',
['paf2.peptide_align_feature_id AS pafid2']]
];
my $constraint = "paf.qmember_id=? AND paf.hgenome_db_id=?";
my $final_clause = "ORDER BY paf.hit_rank";
$self->bind_param_generic_fetch($qmember_id, SQL_INTEGER);
$self->bind_param_generic_fetch($hit_genome_db_id, SQL_INTEGER);
return $self->generic_fetch($constraint, $extrajoin, $final_clause);
}
=head2 fetch_all_RH_by_member
Overview : This an experimental method and not currently used in production
Arg [1] : seq_member_id of query peptide member
Example : $feat = $adaptor->fetch_by_dbID($musBlastAnal, $ratBlastAnal);
Description: Returns all the PeptideAlignFeatures that reciprocal hit all genomes
Returntype : array of Bio::EnsEMBL::Compara::PeptideAlignFeature objects by reference
Exceptions : thrown if $id is not defined
Caller : general
=cut
sub fetch_all_RH_by_member
{
# using trick of specifying table twice so can join to self
my $self = shift;
my $qmember_id = shift;
my @pafs;
foreach my $genome_db_id ($self->_get_all_genome_db_ids) {
push @pafs, @{$self->fetch_all_RH_by_member_genomedb($qmember_id, $genome_db_id)};
}
return \@pafs;
}
1;
| ckongEbi/ensembl-compara | modules/Bio/EnsEMBL/Compara/DBSQL/PeptideAlignFeatureAdaptor.pm | Perl | apache-2.0 | 21,997 |
# 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.
#
package Bundle::Apache2;
$VERSION = '1.00';
1;
__END__
=head1 NAME
Bundle::Apache2 - Install Apache mod_perl2 and related modules
=head1 SYNOPSIS
C<perl -MCPAN -e 'install Bundle::Apache2'>
=head1 CONTENTS
Bundle::ApacheTest - Needs for testing
CGI 3.11 - Used in testing (it's in core, but some vendors exclude it)
Chatbot::Eliza - Used in testing
Compress::Zlib - Used in testing
Devel::Symdump - Symbol table browsing with Apache::Status
HTML::HeadParser - Used in testing
IPC::Run3 - Used in testing
LWP - Used in testing
=head1 DESCRIPTION
This bundle contains modules used by Apache mod_perl2.
Asking CPAN.pm to install a bundle means to install the bundle itself
along with all the modules contained in the CONTENTS section
above. Modules that are up to date are not installed, of course.
=head1 AUTHOR
mod_perl 2 development team
| gitpan/mod_perl | lib/Bundle/Apache2.pm | Perl | apache-2.0 | 1,723 |
# 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.
package AI::MXNet::InitDesc;
use Mouse;
use AI::MXNet::Function::Parameters;
=head1 NAME
AI::MXNet::InitDesc - A container for the initialization pattern serialization.
=head2 new
Parameters
---------
name : str
name of variable
attrs : hash ref of str to str
attributes of this variable taken from AI::MXNet::Symbol->attr_dict
=cut
has 'name' => (is => 'ro', isa => 'Str', required => 1);
has 'attrs' => (is => 'rw', isa => 'HashRef[Str]', lazy => 1, default => sub { +{} });
use overload '""' => sub { shift->name };
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
return $class->$orig(name => $_[0]) if @_ == 1;
return $class->$orig(@_);
};
# Base class for Initializers
package AI::MXNet::Initializer;
use Mouse;
use AI::MXNet::Base qw(:DEFAULT pzeros pceil);
use AI::MXNet::NDArray;
use JSON::PP;
use overload "&{}" => sub { my $self = shift; sub { $self->call(@_) } },
'""' => sub {
my $self = shift;
my ($name) = ref($self) =~ /::(\w+)$/;
encode_json(
[lc $name,
$self->kwargs//{ map { $_ => "".$self->$_ } $self->meta->get_attribute_list }
]);
},
fallback => 1;
has 'kwargs' => (is => 'rw', init_arg => undef, isa => 'HashRef');
has '_verbose' => (is => 'rw', isa => 'Bool', lazy => 1, default => 0);
has '_print_func' => (is => 'rw', isa => 'CodeRef', lazy => 1,
default => sub {
return sub {
my $x = shift;
return ($x->norm/sqrt($x->size))->asscalar;
};
}
);
=head1 NAME
AI::MXNet::Initializer - Base class for all Initializers
=head2 register
Register an initializer class to the AI::MXNet::Initializer factory.
=cut
=head2 set_verbosity
Switch on/off verbose mode
Parameters
----------
$verbose : bool
switch on/off verbose mode
$print_func : CodeRef
A function that computes statistics of initialized arrays.
Takes an AI::MXNet::NDArray and returns a scalar. Defaults to mean
absolute value |x|/size(x)
=cut
method set_verbosity(Bool $verbose=0, CodeRef $print_func=)
{
$self->_verbose($verbose);
$self->_print_func($print_func) if defined $print_func;
}
method _verbose_print($desc, $init, $arr)
{
if($self->_verbose and defined $self->_print_func)
{
AI::MXNet::Logging->info('Initialized %s as %s: %s', $desc, $init, $self->_print_func->($arr));
}
}
my %init_registry;
method get_init_registry()
{
return \%init_registry;
}
method register()
{
my ($name) = $self =~ /::(\w+)$/;
my $orig_name = $name;
$name = lc $name;
if(exists $init_registry{ $name })
{
my $existing = $init_registry{ $name };
warn(
"WARNING: New initializer $self.$name"
."is overriding existing initializer $existing.$name"
);
}
$init_registry{ $name } = $self;
{
no strict 'refs';
no warnings 'redefine';
*{"$orig_name"} = sub { shift; $self->new(@_) };
*InitDesc = sub { shift; AI::MXNet::InitDesc->new(@_) };
}
}
=head2 init
Parameters
----------
$desc : AI::MXNet::InitDesc|str
a name of corresponding ndarray
or the object that describes the initializer.
$arr : AI::MXNet::NDArray
an ndarray to be initialized.
=cut
method call(Str|AI::MXNet::InitDesc $desc, AI::MXNet::NDArray $arr)
{
return $self->_legacy_init($desc, $arr) unless blessed $desc;
my $init = $desc->attrs->{ __init__ };
if($init)
{
my ($klass, $kwargs);
if(exists $self->get_init_registry->{ lc $init })
{
$klass = $init;
$kwargs = {};
}
else
{
($klass, $kwargs) = @{ decode_json($init) };
}
$self->get_init_registry->{ lc $klass }->new(%{ $kwargs })->_init_weight("$desc", $arr);
$self->_verbose_print($desc, $init, $arr);
}
else
{
$desc = "$desc";
if($desc =~ /(weight|bias|gamma|beta)$/)
{
my $method = "_init_$1";
$self->$method($desc, $arr);
$self->_verbose_print($desc, $1, $arr);
}
else
{
$self->_init_default($desc, $arr)
}
}
}
method _legacy_init(Str $name, AI::MXNet::NDArray $arr)
{
warnings::warnif(
'deprecated',
'Calling initializer with init($str, $NDArray) has been deprecated.'.
'please use init(mx->init->InitDesc(...), NDArray) instead.'
);
if($name =~ /^upsampling/)
{
$self->_init_bilinear($name, $arr);
}
elsif($name =~ /^stn_loc/ and $name =~ /weight$/)
{
$self->_init_zero($name, $arr);
}
elsif($name =~ /^stn_loc/ and $name =~ /bias$/)
{
$self->_init_loc_bias($name, $arr);
}
elsif($name =~ /bias$/)
{
$self->_init_bias($name, $arr);
}
elsif($name =~ /gamma$/)
{
$self->_init_gamma($name, $arr);
}
elsif($name =~ /beta$/)
{
$self->_init_beta($name, $arr);
}
elsif($name =~ /weight$/)
{
$self->_init_weight($name, $arr);
}
elsif($name =~ /moving_mean$/)
{
$self->_init_zero($name, $arr);
}
elsif($name =~ /moving_var$/)
{
$self->_init_one($name, $arr);
}
elsif($name =~ /moving_inv_var$/)
{
$self->_init_zero($name, $arr);
}
elsif($name =~ /moving_avg$/)
{
$self->_init_zero($name, $arr);
}
else
{
$self->_init_default($name, $arr);
}
}
*slice = *call;
method _init_bilinear($name, $arr)
{
my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' });
my $weight = pzeros(
PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' }),
$arr->size
);
my $shape = $arr->shape;
my $size = $arr->size;
my $f = pceil($shape->[3] / 2)->at(0);
my $c = (2 * $f - 1 - $f % 2) / (2 * $f);
for my $i (0..($size-1))
{
my $x = $i % $shape->[3];
my $y = ($i / $shape->[3]) % $shape->[2];
$weight->index($i) .= (1 - abs($x / $f - $c)) * (1 - abs($y / $f - $c));
}
$arr .= $weight->reshape(reverse @{ $shape });
}
method _init_loc_bias($name, $arr)
{
confess("assert error shape[0] == 6")
unless $arr->shape->[0] == 6;
$arr .= [1.0, 0, 0, 0, 1.0, 0];
}
method _init_zero($name, $arr)
{
$arr .= 0;
}
method _init_one($name, $arr)
{
$arr .= 1;
}
method _init_bias($name, $arr)
{
$arr .= 0;
}
method _init_gamma($name, $arr)
{
$arr .= 1;
}
method _init_beta($name, $arr)
{
$arr .= 0;
}
method _init_weight($name, $arr)
{
confess("Virtual method, subclass must override it");
}
method _init_default($name, $arr)
{
confess(
"Unknown initialization pattern for $name. "
.'Default initialization is now limited to '
.'"weight", "bias", "gamma" (1.0), and "beta" (0.0).'
.'Please use mx.sym.Variable(init=mx.init.*) to set initialization pattern'
);
}
=head1 NAME
AI::MXNet::Load - Initialize by loading a pretrained param from a hash ref.
=cut
=head2 new
Parameters
----------
param: HashRef[AI::MXNet::NDArray]
default_init: Initializer
default initializer when a name is not found in the param hash ref.
verbose: bool
log the names when initializing.
=cut
package AI::MXNet::Load;
use Mouse;
extends 'AI::MXNet::Initializer';
has 'param' => (is => "rw", isa => 'HashRef[AI::MXNet::NDArray]', required => 1);
has 'default_init' => (is => "rw", isa => "AI::MXNet::Initializer");
has 'verbose' => (is => "rw", isa => "Int", default => 0);
sub BUILD
{
my $self = shift;
my $param = AI::MXNet::NDArray->load($self->param) unless ref $self->param;
my %self_param;
while(my ($name, $arr) = each %{ $self->param })
{
$name =~ s/^(?:arg|aux)://;
$self_param{ $name } = $arr;
}
$self->param(\%self_param);
}
method call(Str $name, AI::MXNet::NDArray $arr)
{
if(exists $self->param->{ $name })
{
my $target_shape = join(',', @{ $arr->shape });
my $param_shape = join(',', @{ $self->param->{ $name }->shape });
confess(
"Parameter $name cannot be initialized from loading. "
."Shape mismatch, target $target_shape vs loaded $param_shape"
) unless $target_shape eq $param_shape;
$arr .= $self->param->{ $name };
AI::MXNet::Log->info("Initialized $name by loading") if $self->verbose;
}
else
{
confess(
"Cannot Initialize $name. Not found in loaded param "
."and no default Initializer is provided."
) unless defined $self->default_init;
$self->default_init($name, $arr);
AI::MXNet::Log->info("Initialized $name by default") if $self->verbose;
}
}
*slice = *call;
=head1 NAME
AI::MXNet::Mixed - A container for multiple initializer patterns.
=cut
=head2 new
patterns: array ref of str
array ref of regular expression patterns to match parameter names.
initializers: array ref of AI::MXNet::Initializer objects.
array ref of Initializers corresponding to the patterns.
=cut
package AI::MXNet::Mixed;
use Mouse;
extends 'AI::MXNet::Initializer';
has "map" => (is => "rw", init_arg => undef);
has "patterns" => (is => "ro", isa => 'ArrayRef[Str]');
has "initializers" => (is => "ro", isa => 'ArrayRef[AI::MXnet::Initializer]');
sub BUILD
{
my $self = shift;
confess("patterns count != initializers count")
unless (@{ $self->patterns } == @{ $self->initializers });
my %map;
@map{ @{ $self->patterns } } = @{ $self->initializers };
$self->map(\%map);
}
method call(Str $name, AI::MXNet::NDArray $arr)
{
for my $pattern (keys %{ $self->map })
{
if($name =~ /$pattern/)
{
$self->map->{$pattern}->($name, $arr);
return;
}
}
confess(
"Parameter name $name did not match any pattern. Consider"
."add a \".*\" pattern at the and with default Initializer."
);
}
package AI::MXNet::Zero;
use Mouse;
extends 'AI::MXNet::Initializer';
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
$arr .= 0;
}
__PACKAGE__->register;
package AI::MXNet::Zeros;
use Mouse;
extends 'AI::MXNet::Zero';
__PACKAGE__->register;
package AI::MXNet::One;
use Mouse;
extends 'AI::MXNet::Initializer';
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
$arr .= 1;
}
__PACKAGE__->register;
package AI::MXNet::Ones;
use Mouse;
extends 'AI::MXNet::One';
__PACKAGE__->register;
package AI::MXNet::Constant;
use Mouse;
extends 'AI::MXNet::Initializer';
has 'value' => (is => 'ro', isa => 'Num', required => 1);
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
return $class->$orig(value => $_[0]) if @_ == 1;
return $class->$orig(@_);
};
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
$arr .= $self->value;
}
__PACKAGE__->register;
=head1 NAME
AI::MXNet::Uniform - Initialize the weight with uniform random values.
=cut
=head1 DESCRIPTION
Initialize the weight with uniform random values contained within of [-scale, scale]
Parameters
----------
scale : float, optional
The scale of the uniform distribution.
=cut
package AI::MXNet::Uniform;
use Mouse;
extends 'AI::MXNet::Initializer';
has "scale" => (is => "ro", isa => "Num", default => 0.07);
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
return $class->$orig(scale => $_[0]) if @_ == 1;
return $class->$orig(@_);
};
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
AI::MXNet::Random->uniform(-$self->scale, $self->scale, { out => $arr });
}
__PACKAGE__->register;
=head1 NAME
AI::MXNet::Normal - Initialize the weight with gaussian random values.
=cut
=head1 DESCRIPTION
Initialize the weight with gaussian random values contained within of [0, sigma]
Parameters
----------
sigma : float, optional
Standard deviation for the gaussian distribution.
=cut
package AI::MXNet::Normal;
use Mouse;
extends 'AI::MXNet::Initializer';
has "sigma" => (is => "ro", isa => "Num", default => 0.01);
around BUILDARGS => sub {
my $orig = shift;
my $class = shift;
return $class->$orig(sigma => $_[0]) if @_ == 1;
return $class->$orig(@_);
};
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
AI::MXNet::Random->normal(0, $self->sigma, { out => $arr });
}
__PACKAGE__->register;
=head1 NAME
AI::MXNet::Orthogonal - Intialize the weight as an Orthogonal matrix.
=cut
=head1 DESCRIPTION
Intialize weight as Orthogonal matrix
Parameters
----------
scale : float, optional
scaling factor of weight
rand_type: string optional
use "uniform" or "normal" random number to initialize weight
Reference
---------
Exact solutions to the nonlinear dynamics of learning in deep linear neural networks
arXiv preprint arXiv:1312.6120 (2013).
=cut
package AI::MXNet::Orthogonal;
use AI::MXNet::Base;
use Mouse;
use AI::MXNet::Types;
extends 'AI::MXNet::Initializer';
has "scale" => (is => "ro", isa => "Num", default => 1.414);
has "rand_type" => (is => "ro", isa => enum([qw/uniform normal/]), default => 'uniform');
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
my @shape = @{ $arr->shape };
my $nout = $shape[0];
my $nin = AI::MXNet::NDArray->size([@shape[1..$#shape]]);
my $tmp = AI::MXNet::NDArray->zeros([$nout, $nin]);
if($self->rand_type eq 'uniform')
{
AI::MXNet::Random->uniform(-1, 1, { out => $tmp });
}
else
{
AI::MXNet::Random->normal(0, 1, { out => $tmp });
}
$tmp = $tmp->aspdl;
my ($u, $s, $v) = svd($tmp);
my $q;
if(join(',', @{ $u->shape->unpdl }) eq join(',', @{ $tmp->shape->unpdl }))
{
$q = $u;
}
else
{
$q = $v;
}
$q = $self->scale * $q->reshape(reverse(@shape));
$arr .= $q;
}
*slice = *call;
__PACKAGE__->register;
=head1 NAME
AI::MXNet::Xavier - Initialize the weight with Xavier or similar initialization scheme.
=cut
=head1 DESCRIPTION
Parameters
----------
rnd_type: str, optional
Use gaussian or uniform.
factor_type: str, optional
Use avg, in, or out.
magnitude: float, optional
The scale of the random number range.
=cut
package AI::MXNet::Xavier;
use Mouse;
use AI::MXNet::Types;
extends 'AI::MXNet::Initializer';
has "magnitude" => (is => "rw", isa => "Num", default => 3);
has "rnd_type" => (is => "ro", isa => enum([qw/uniform gaussian/]), default => 'uniform');
has "factor_type" => (is => "ro", isa => enum([qw/avg in out/]), default => 'avg');
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
my @shape = @{ $arr->shape };
confess(__PACKAGE__." initializer can not be applied on less than 2D tensor")
if @shape < 2;
my $hw_scale = 1;
if(@shape > 2)
{
$hw_scale = AI::MXNet::NDArray->size([@shape[2..$#shape]]);
}
my ($fan_in, $fan_out) = ($shape[1] * $hw_scale, $shape[0] * $hw_scale);
my $factor;
if($self->factor_type eq "avg")
{
$factor = ($fan_in + $fan_out) / 2;
}
elsif($self->factor_type eq "in")
{
$factor = $fan_in;
}
else
{
$factor = $fan_out;
}
my $scale = sqrt($self->magnitude / $factor);
if($self->rnd_type eq "iniform")
{
AI::MXNet::Random->uniform(-$scale, $scale, { out => $arr });
}
else
{
AI::MXNet::Random->normal(0, $scale, { out => $arr });
}
}
__PACKAGE__->register;
=head1 NAME
AI::MXNet::MSRAPrelu - Custom initialization scheme.
=cut
=head1 DESCRIPTION
Initialize the weight with initialization scheme from
Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification.
Parameters
----------
factor_type: str, optional
Use avg, in, or out.
slope: float, optional
initial slope of any PReLU (or similar) nonlinearities.
=cut
package AI::MXNet::MSRAPrelu;
use Mouse;
extends 'AI::MXNet::Xavier';
has '+rnd_type' => (default => "gaussian");
has '+factor_type' => (default => "avg");
has 'slope' => (is => 'ro', isa => 'Num', default => 0.25);
sub BUILD
{
my $self = shift;
my $magnitude = 2 / (1 + $self->slope ** 2);
$self->magnitude($magnitude);
$self->kwargs({ slope => $self->slope, factor_type => $self->factor_type });
}
__PACKAGE__->register;
package AI::MXNet::Bilinear;
use Mouse;
use AI::MXNet::Base;
extends 'AI::MXNet::Initializer';
method _init_weight($name, $arr)
{
my $pdl_type = PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' });
my $weight = pzeros(
PDL::Type->new(DTYPE_MX_TO_PDL->{ 'float32' }),
$arr->size
);
my $shape = $arr->shape;
my $size = $arr->size;
my $f = pceil($shape->[3] / 2)->at(0);
my $c = (2 * $f - 1 - $f % 2) / (2 * $f);
for my $i (0..($size-1))
{
my $x = $i % $shape->[3];
my $y = ($i / $shape->[3]) % $shape->[2];
$weight->index($i) .= (1 - abs($x / $f - $c)) * (1 - abs($y / $f - $c));
}
$arr .= $weight->reshape(reverse @{ $shape });
}
__PACKAGE__->register;
package AI::MXNet::LSTMBias;
=head1 NAME
AI::MXNet::LSTMBias - Custom initializer for LSTM cells.
=cut
=head1 DESCRIPTION
Initializes all biases of an LSTMCell to 0.0 except for
the forget gate's bias that is set to a custom value.
Parameters
----------
forget_bias: float,a bias for the forget gate.
Jozefowicz et al. 2015 recommends setting this to 1.0.
=cut
use Mouse;
extends 'AI::MXNet::Initializer';
has 'forget_bias' => (is => 'ro', isa => 'Num', required => 1);
around BUILDARGS => \&AI::MXNet::Base::process_arguments;
method python_constructor_arguments() { ['forget_bias'] }
method _init_weight(Str $name, AI::MXNet::NDArray $arr)
{
$arr .= 0;
# in the case of LSTMCell the forget gate is the second
# gate of the 4 LSTM gates, we modify the according values.
my $num_hidden = int($arr->shape->[0] / 4);
$arr->slice([$num_hidden, 2*$num_hidden-1]) .= $self->forget_bias;
}
__PACKAGE__->register;
package AI::MXNet::FusedRNN;
use Mouse;
use JSON::PP;
extends 'AI::MXNet::Initializer';
=head1 NAME
AI::MXNet::FusedRNN - Custom initializer for fused RNN cells.
=cut
=head1 DESCRIPTION
Initializes parameters for fused rnn layer.
Parameters
----------
init : Initializer
initializer applied to unpacked weights.
All parameters below must be exactly the same as ones passed to the
FusedRNNCell constructor.
num_hidden : int
num_layers : int
mode : str
bidirectional : bool
forget_bias : float
=cut
has 'init' => (is => 'rw', isa => 'Str|AI::MXNet::Initializer', required => 1);
has 'forget_bias' => (is => 'ro', isa => 'Num', default => 1);
has [qw/num_hidden
num_layers/] => (is => 'ro', isa => 'Int', required => 1);
has 'mode' => (is => 'ro', isa => 'Str', required => 1);
has 'bidirectional' => (is => 'ro', isa => 'Bool', default => 0);
sub BUILD
{
my $self = shift;
if(not blessed $self->init)
{
my ($klass, $kwargs);
eval {
($klass, $kwargs) = @{ decode_json($self->init) };
};
confess("FusedRNN failed to init $@") if $@;
$self->init($self->get_init_registry->{ lc $klass }->new(%$kwargs));
}
}
method _init_weight($name, $arr)
{
my $cell = AI::MXNet::RNN::FusedCell->new(
num_hidden => $self->num_hidden,
num_layers => $self->num_layers,
mode => $self->mode,
bidirectional => $self->bidirectional,
forget_bias => $self->forget_bias,
prefix => ''
);
my $args = $cell->unpack_weights({ parameters => $arr });
for my $name (keys %{ $args })
{
my $desc = AI::MXNet::InitDesc->new(name => $name);
# for lstm bias, we use a custom initializer
# which adds a bias to the forget gate
if($self->mode eq 'lstm' and $name =~ /f_bias$/)
{
$args->{$name} .= $self->forget_bias;
}
else
{
$self->init->($desc, $args->{$name});
}
}
$arr .= $cell->pack_weights($args)->{parameters};
}
__PACKAGE__->register;
1;
| rahul003/mxnet | perl-package/AI-MXNet/lib/AI/MXNet/Initializer.pm | Perl | apache-2.0 | 21,388 |
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by mktables from the Unicode
# database, Version 6.1.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly.
return <<'END';
1100 115F
11A3 11A7
11FA 11FF
2329 232A
2E80 2E99
2E9B 2EF3
2F00 2FD5
2FF0 2FFB
3001 303E
3041 3096
3099 30FF
3105 312D
3131 318E
3190 31BA
31C0 31E3
31F0 321E
3220 3247
3250 32FE
3300 4DBF
4E00 A48C
A490 A4C6
A960 A97C
AC00 D7A3
D7B0 D7C6
D7CB D7FB
F900 FAFF
FE10 FE19
FE30 FE52
FE54 FE66
FE68 FE6B
1B000 1B001
1F200 1F202
1F210 1F23A
1F240 1F248
1F250 1F251
20000 2FFFD
30000 3FFFD
END
| Dokaponteam/ITF_Project | xampp/perl/lib/unicore/lib/Ea/W.pl | Perl | mit | 795 |
#! /usr/bin/perl -w
# Courtesy Ken Pizzini.
use strict;
#This file released to the public domain.
# Note: error checking is poor; trust the output only if the input
# has been checked by zic.
my $contZone = '';
while (<>) {
my $origline = $_;
my @fields = ();
while (s/^\s*((?:"[^"]*"|[^\s#])+)//) {
push @fields, $1;
}
next unless @fields;
my $type = lc($fields[0]);
if ($contZone) {
@fields >= 3 or warn "bad continuation line";
unshift @fields, '+', $contZone;
$type = 'zone';
}
$contZone = '';
if ($type eq 'zone') {
# Zone NAME GMTOFF RULES/SAVE FORMAT [UNTIL]
my $nfields = @fields;
$nfields >= 5 or warn "bad zone line";
if ($nfields > 6) {
#this splice is optional, depending on one's preference
#(one big date-time field, or componentized date and time):
splice(@fields, 5, $nfields-5, "@fields[5..$nfields-1]");
}
$contZone = $fields[1] if @fields > 5;
} elsif ($type eq 'rule') {
# Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S
@fields == 10 or warn "bad rule line";
} elsif ($type eq 'link') {
# Link TARGET LINK-NAME
@fields == 3 or warn "bad link line";
} elsif ($type eq 'leap') {
# Leap YEAR MONTH DAY HH:MM:SS CORR R/S
@fields == 7 or warn "bad leap line";
} else {
warn "Fubar at input line $.: $origline";
}
print join("\t", @fields), "\n";
}
| evq/utz | vendor/tzdata/zoneinfo2tdf.pl | Perl | mit | 1,409 |
=pod
=head1 NAME
req - PKCS#10 certificate request and certificate generating utility.
=head1 SYNOPSIS
B<openssl> B<req>
[B<-inform PEM|DER>]
[B<-outform PEM|DER>]
[B<-in filename>]
[B<-passin arg>]
[B<-out filename>]
[B<-passout arg>]
[B<-text>]
[B<-pubkey>]
[B<-noout>]
[B<-verify>]
[B<-modulus>]
[B<-new>]
[B<-rand file(s)>]
[B<-newkey rsa:bits>]
[B<-newkey alg:file>]
[B<-nodes>]
[B<-key filename>]
[B<-keyform PEM|DER>]
[B<-keyout filename>]
[B<-keygen_engine id>]
[B<-[digest]>]
[B<-config filename>]
[B<-subj arg>]
[B<-multivalue-rdn>]
[B<-x509>]
[B<-days n>]
[B<-set_serial n>]
[B<-asn1-kludge>]
[B<-no-asn1-kludge>]
[B<-newhdr>]
[B<-extensions section>]
[B<-reqexts section>]
[B<-utf8>]
[B<-nameopt>]
[B<-reqopt>]
[B<-subject>]
[B<-subj arg>]
[B<-batch>]
[B<-verbose>]
[B<-engine id>]
=head1 DESCRIPTION
The B<req> command primarily creates and processes certificate requests
in PKCS#10 format. It can additionally create self signed certificates
for use as root CAs for example.
=head1 COMMAND OPTIONS
=over 4
=item B<-inform DER|PEM>
This specifies the input format. The B<DER> option uses an ASN1 DER encoded
form compatible with the PKCS#10. The B<PEM> form is the default format: it
consists of the B<DER> format base64 encoded with additional header and
footer lines.
=item B<-outform DER|PEM>
This specifies the output format, the options have the same meaning as the
B<-inform> option.
=item B<-in filename>
This specifies the input filename to read a request from or standard input
if this option is not specified. A request is only read if the creation
options (B<-new> and B<-newkey>) are not specified.
=item B<-passin arg>
the input file password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.
=item B<-out filename>
This specifies the output filename to write to or standard output by
default.
=item B<-passout arg>
the output file password source. For more information about the format of B<arg>
see the B<PASS PHRASE ARGUMENTS> section in L<openssl(1)|openssl(1)>.
=item B<-text>
prints out the certificate request in text form.
=item B<-subject>
prints out the request subject (or certificate subject if B<-x509> is
specified)
=item B<-pubkey>
outputs the public key.
=item B<-noout>
this option prevents output of the encoded version of the request.
=item B<-modulus>
this option prints out the value of the modulus of the public key
contained in the request.
=item B<-verify>
verifies the signature on the request.
=item B<-new>
this option generates a new certificate request. It will prompt
the user for the relevant field values. The actual fields
prompted for and their maximum and minimum sizes are specified
in the configuration file and any requested extensions.
If the B<-key> option is not used it will generate a new RSA private
key using information specified in the configuration file.
=item B<-subj arg>
Replaces subject field of input request with specified data and outputs
modified request. The arg must be formatted as
I</type0=value0/type1=value1/type2=...>,
characters may be escaped by \ (backslash), no spaces are skipped.
=item B<-rand file(s)>
a file or files containing random data used to seed the random number
generator, or an EGD socket (see L<RAND_egd(3)|RAND_egd(3)>).
Multiple files can be specified separated by a OS-dependent character.
The separator is B<;> for MS-Windows, B<,> for OpenVMS, and B<:> for
all others.
=item B<-newkey arg>
this option creates a new certificate request and a new private
key. The argument takes one of several forms. B<rsa:nbits>, where
B<nbits> is the number of bits, generates an RSA key B<nbits>
in size. If B<nbits> is omitted, i.e. B<-newkey rsa> specified,
the default key size, specified in the configuration file is used.
All other algorithms support the B<-newkey alg:file> form, where file may be
an algorithm parameter file, created by the B<genpkey -genparam> command
or and X.509 certificate for a key with approriate algorithm.
B<param:file> generates a key using the parameter file or certificate B<file>,
the algorithm is determined by the parameters. B<algname:file> use algorithm
B<algname> and parameter file B<file>: the two algorithms must match or an
error occurs. B<algname> just uses algorithm B<algname>, and parameters,
if neccessary should be specified via B<-pkeyopt> parameter.
B<dsa:filename> generates a DSA key using the parameters
in the file B<filename>. B<ec:filename> generates EC key (usable both with
ECDSA or ECDH algorithms), B<gost2001:filename> generates GOST R
34.10-2001 key (requires B<ccgost> engine configured in the configuration
file). If just B<gost2001> is specified a parameter set should be
specified by B<-pkeyopt paramset:X>
=item B<-pkeyopt opt:value>
set the public key algorithm option B<opt> to B<value>. The precise set of
options supported depends on the public key algorithm used and its
implementation. See B<KEY GENERATION OPTIONS> in the B<genpkey> manual page
for more details.
=item B<-key filename>
This specifies the file to read the private key from. It also
accepts PKCS#8 format private keys for PEM format files.
=item B<-keyform PEM|DER>
the format of the private key file specified in the B<-key>
argument. PEM is the default.
=item B<-keyout filename>
this gives the filename to write the newly created private key to.
If this option is not specified then the filename present in the
configuration file is used.
=item B<-nodes>
if this option is specified then if a private key is created it
will not be encrypted.
=item B<-[digest]>
this specifies the message digest to sign the request with (such as
B<-md5>, B<-sha1>). This overrides the digest algorithm specified in
the configuration file.
Some public key algorithms may override this choice. For instance, DSA
signatures always use SHA1, GOST R 34.10 signatures always use
GOST R 34.11-94 (B<-md_gost94>).
=item B<-config filename>
this allows an alternative configuration file to be specified,
this overrides the compile time filename or any specified in
the B<OPENSSL_CONF> environment variable.
=item B<-subj arg>
sets subject name for new request or supersedes the subject name
when processing a request.
The arg must be formatted as I</type0=value0/type1=value1/type2=...>,
characters may be escaped by \ (backslash), no spaces are skipped.
=item B<-multivalue-rdn>
this option causes the -subj argument to be interpreted with full
support for multivalued RDNs. Example:
I</DC=org/DC=OpenSSL/DC=users/UID=123456+CN=John Doe>
If -multi-rdn is not used then the UID value is I<123456+CN=John Doe>.
=item B<-x509>
this option outputs a self signed certificate instead of a certificate
request. This is typically used to generate a test certificate or
a self signed root CA. The extensions added to the certificate
(if any) are specified in the configuration file. Unless specified
using the B<set_serial> option B<0> will be used for the serial
number.
=item B<-days n>
when the B<-x509> option is being used this specifies the number of
days to certify the certificate for. The default is 30 days.
=item B<-set_serial n>
serial number to use when outputting a self signed certificate. This
may be specified as a decimal value or a hex value if preceded by B<0x>.
It is possible to use negative serial numbers but this is not recommended.
=item B<-extensions section>
=item B<-reqexts section>
these options specify alternative sections to include certificate
extensions (if the B<-x509> option is present) or certificate
request extensions. This allows several different sections to
be used in the same configuration file to specify requests for
a variety of purposes.
=item B<-utf8>
this option causes field values to be interpreted as UTF8 strings, by
default they are interpreted as ASCII. This means that the field
values, whether prompted from a terminal or obtained from a
configuration file, must be valid UTF8 strings.
=item B<-nameopt option>
option which determines how the subject or issuer names are displayed. The
B<option> argument can be a single option or multiple options separated by
commas. Alternatively the B<-nameopt> switch may be used more than once to
set multiple options. See the L<x509(1)|x509(1)> manual page for details.
=item B<-reqopt>
customise the output format used with B<-text>. The B<option> argument can be
a single option or multiple options separated by commas.
See discission of the B<-certopt> parameter in the L<B<x509>|x509(1)>
command.
=item B<-asn1-kludge>
by default the B<req> command outputs certificate requests containing
no attributes in the correct PKCS#10 format. However certain CAs will only
accept requests containing no attributes in an invalid form: this
option produces this invalid format.
More precisely the B<Attributes> in a PKCS#10 certificate request
are defined as a B<SET OF Attribute>. They are B<not OPTIONAL> so
if no attributes are present then they should be encoded as an
empty B<SET OF>. The invalid form does not include the empty
B<SET OF> whereas the correct form does.
It should be noted that very few CAs still require the use of this option.
=item B<-no-asn1-kludge>
Reverses effect of B<-asn1-kludge>
=item B<-newhdr>
Adds the word B<NEW> to the PEM file header and footer lines on the outputted
request. Some software (Netscape certificate server) and some CAs need this.
=item B<-batch>
non-interactive mode.
=item B<-verbose>
print extra details about the operations being performed.
=item B<-engine id>
specifying an engine (by its unique B<id> string) will cause B<req>
to attempt to obtain a functional reference to the specified engine,
thus initialising it if needed. The engine will then be set as the default
for all available algorithms.
=item B<-keygen_engine id>
specifies an engine (by its unique B<id> string) which would be used
for key generation operations.
=back
=head1 CONFIGURATION FILE FORMAT
The configuration options are specified in the B<req> section of
the configuration file. As with all configuration files if no
value is specified in the specific section (i.e. B<req>) then
the initial unnamed or B<default> section is searched too.
The options available are described in detail below.
=over 4
=item B<input_password output_password>
The passwords for the input private key file (if present) and
the output private key file (if one will be created). The
command line options B<passin> and B<passout> override the
configuration file values.
=item B<default_bits>
This specifies the default key size in bits. If not specified then
512 is used. It is used if the B<-new> option is used. It can be
overridden by using the B<-newkey> option.
=item B<default_keyfile>
This is the default filename to write a private key to. If not
specified the key is written to standard output. This can be
overridden by the B<-keyout> option.
=item B<oid_file>
This specifies a file containing additional B<OBJECT IDENTIFIERS>.
Each line of the file should consist of the numerical form of the
object identifier followed by white space then the short name followed
by white space and finally the long name.
=item B<oid_section>
This specifies a section in the configuration file containing extra
object identifiers. Each line should consist of the short name of the
object identifier followed by B<=> and the numerical form. The short
and long names are the same when this option is used.
=item B<RANDFILE>
This specifies a filename in which random number seed information is
placed and read from, or an EGD socket (see L<RAND_egd(3)|RAND_egd(3)>).
It is used for private key generation.
=item B<encrypt_key>
If this is set to B<no> then if a private key is generated it is
B<not> encrypted. This is equivalent to the B<-nodes> command line
option. For compatibility B<encrypt_rsa_key> is an equivalent option.
=item B<default_md>
This option specifies the digest algorithm to use. Possible values
include B<md5 sha1 mdc2>. If not present then MD5 is used. This
option can be overridden on the command line.
=item B<string_mask>
This option masks out the use of certain string types in certain
fields. Most users will not need to change this option.
It can be set to several values B<default> which is also the default
option uses PrintableStrings, T61Strings and BMPStrings if the
B<pkix> value is used then only PrintableStrings and BMPStrings will
be used. This follows the PKIX recommendation in RFC2459. If the
B<utf8only> option is used then only UTF8Strings will be used: this
is the PKIX recommendation in RFC2459 after 2003. Finally the B<nombstr>
option just uses PrintableStrings and T61Strings: certain software has
problems with BMPStrings and UTF8Strings: in particular Netscape.
=item B<req_extensions>
this specifies the configuration file section containing a list of
extensions to add to the certificate request. It can be overridden
by the B<-reqexts> command line switch. See the
L<x509v3_config(5)|x509v3_config(5)> manual page for details of the
extension section format.
=item B<x509_extensions>
this specifies the configuration file section containing a list of
extensions to add to certificate generated when the B<-x509> switch
is used. It can be overridden by the B<-extensions> command line switch.
=item B<prompt>
if set to the value B<no> this disables prompting of certificate fields
and just takes values from the config file directly. It also changes the
expected format of the B<distinguished_name> and B<attributes> sections.
=item B<utf8>
if set to the value B<yes> then field values to be interpreted as UTF8
strings, by default they are interpreted as ASCII. This means that
the field values, whether prompted from a terminal or obtained from a
configuration file, must be valid UTF8 strings.
=item B<attributes>
this specifies the section containing any request attributes: its format
is the same as B<distinguished_name>. Typically these may contain the
challengePassword or unstructuredName types. They are currently ignored
by OpenSSL's request signing utilities but some CAs might want them.
=item B<distinguished_name>
This specifies the section containing the distinguished name fields to
prompt for when generating a certificate or certificate request. The format
is described in the next section.
=back
=head1 DISTINGUISHED NAME AND ATTRIBUTE SECTION FORMAT
There are two separate formats for the distinguished name and attribute
sections. If the B<prompt> option is set to B<no> then these sections
just consist of field names and values: for example,
CN=My Name
OU=My Organization
emailAddress=someone@somewhere.org
This allows external programs (e.g. GUI based) to generate a template file
with all the field names and values and just pass it to B<req>. An example
of this kind of configuration file is contained in the B<EXAMPLES> section.
Alternatively if the B<prompt> option is absent or not set to B<no> then the
file contains field prompting information. It consists of lines of the form:
fieldName="prompt"
fieldName_default="default field value"
fieldName_min= 2
fieldName_max= 4
"fieldName" is the field name being used, for example commonName (or CN).
The "prompt" string is used to ask the user to enter the relevant
details. If the user enters nothing then the default value is used if no
default value is present then the field is omitted. A field can
still be omitted if a default value is present if the user just
enters the '.' character.
The number of characters entered must be between the fieldName_min and
fieldName_max limits: there may be additional restrictions based
on the field being used (for example countryName can only ever be
two characters long and must fit in a PrintableString).
Some fields (such as organizationName) can be used more than once
in a DN. This presents a problem because configuration files will
not recognize the same name occurring twice. To avoid this problem
if the fieldName contains some characters followed by a full stop
they will be ignored. So for example a second organizationName can
be input by calling it "1.organizationName".
The actual permitted field names are any object identifier short or
long names. These are compiled into OpenSSL and include the usual
values such as commonName, countryName, localityName, organizationName,
organizationUnitName, stateOrProvinceName. Additionally emailAddress
is include as well as name, surname, givenName initials and dnQualifier.
Additional object identifiers can be defined with the B<oid_file> or
B<oid_section> options in the configuration file. Any additional fields
will be treated as though they were a DirectoryString.
=head1 EXAMPLES
Examine and verify certificate request:
openssl req -in req.pem -text -verify -noout
Create a private key and then generate a certificate request from it:
openssl genrsa -out key.pem 1024
openssl req -new -key key.pem -out req.pem
The same but just using req:
openssl req -newkey rsa:1024 -keyout key.pem -out req.pem
Generate a self signed root certificate:
openssl req -x509 -newkey rsa:1024 -keyout key.pem -out req.pem
Example of a file pointed to by the B<oid_file> option:
1.2.3.4 shortName A longer Name
1.2.3.6 otherName Other longer Name
Example of a section pointed to by B<oid_section> making use of variable
expansion:
testoid1=1.2.3.5
testoid2=${testoid1}.6
Sample configuration file prompting for field values:
[ req ]
default_bits = 1024
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca
dirstring_type = nobmp
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
localityName = Locality Name (eg, city)
organizationalUnitName = Organizational Unit Name (eg, section)
commonName = Common Name (eg, YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 40
[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
basicConstraints = CA:true
Sample configuration containing all field values:
RANDFILE = $ENV::HOME/.rnd
[ req ]
default_bits = 1024
default_keyfile = keyfile.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
prompt = no
output_password = mypass
[ req_distinguished_name ]
C = GB
ST = Test State or Province
L = Test Locality
O = Organization Name
OU = Organizational Unit Name
CN = Common Name
emailAddress = test@email.address
[ req_attributes ]
challengePassword = A challenge password
=head1 NOTES
The header and footer lines in the B<PEM> format are normally:
-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----
some software (some versions of Netscape certificate server) instead needs:
-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----
which is produced with the B<-newhdr> option but is otherwise compatible.
Either form is accepted transparently on input.
The certificate requests generated by B<Xenroll> with MSIE have extensions
added. It includes the B<keyUsage> extension which determines the type of
key (signature only or general purpose) and any additional OIDs entered
by the script in an extendedKeyUsage extension.
=head1 DIAGNOSTICS
The following messages are frequently asked about:
Using configuration from /some/path/openssl.cnf
Unable to load config info
This is followed some time later by...
unable to find 'distinguished_name' in config
problems making Certificate Request
The first error message is the clue: it can't find the configuration
file! Certain operations (like examining a certificate request) don't
need a configuration file so its use isn't enforced. Generation of
certificates or requests however does need a configuration file. This
could be regarded as a bug.
Another puzzling message is this:
Attributes:
a0:00
this is displayed when no attributes are present and the request includes
the correct empty B<SET OF> structure (the DER encoding of which is 0xa0
0x00). If you just see:
Attributes:
then the B<SET OF> is missing and the encoding is technically invalid (but
it is tolerated). See the description of the command line option B<-asn1-kludge>
for more information.
=head1 ENVIRONMENT VARIABLES
The variable B<OPENSSL_CONF> if defined allows an alternative configuration
file location to be specified, it will be overridden by the B<-config> command
line switch if it is present. For compatibility reasons the B<SSLEAY_CONF>
environment variable serves the same purpose but its use is discouraged.
=head1 BUGS
OpenSSL's handling of T61Strings (aka TeletexStrings) is broken: it effectively
treats them as ISO-8859-1 (Latin 1), Netscape and MSIE have similar behaviour.
This can cause problems if you need characters that aren't available in
PrintableStrings and you don't want to or can't use BMPStrings.
As a consequence of the T61String handling the only correct way to represent
accented characters in OpenSSL is to use a BMPString: unfortunately Netscape
currently chokes on these. If you have to use accented characters with Netscape
and MSIE then you currently need to use the invalid T61String form.
The current prompting is not very friendly. It doesn't allow you to confirm what
you've just entered. Other things like extensions in certificate requests are
statically defined in the configuration file. Some of these: like an email
address in subjectAltName should be input by the user.
=head1 SEE ALSO
L<x509(1)|x509(1)>, L<ca(1)|ca(1)>, L<genrsa(1)|genrsa(1)>,
L<gendsa(1)|gendsa(1)>, L<config(5)|config(5)>,
L<x509v3_config(5)|x509v3_config(5)>
=cut
| domenicosolazzo/philocademy | venv/src/node-v0.10.36/deps/openssl/openssl/doc/apps/req.pod | Perl | mit | 21,989 |
use warnings;
use strict;
package App::Settings::Bug;
use Any::Moose;
extends 'Prophet::Record';
use base qw/Prophet::Record/;
sub new { shift->SUPER::new( @_, type => 'bug' ) }
sub validate_prop_name {
my $self = shift;
my %args = (@_);
return 1 if ( $args{props}->{'name'} eq 'Jesse' );
return 0;
}
sub canonicalize_prop_email {
my $self = shift;
my %args = (@_);
$args{props}->{email} = lc( $args{props}->{email} );
}
sub default_prop_status {'new'}
1;
| gitpan/Prophet | t/Settings/lib/App/Settings/Bug.pm | Perl | mit | 494 |
package IFTest::TestObjectContext;
use common::sense;
use base qw(
IFTest::Type::Datasource
);
use Test::Class;
use Test::More;
use IFTest::Application;
use IF::ObjectContext;
use IF::Query;
use aliased 'IFTest::Entity::Root';
use aliased 'IFTest::Entity::Branch';
use aliased 'IFTest::Entity::Ground';
use aliased 'IFTest::Entity::Trunk';
use aliased 'IFTest::Entity::Globule';
use aliased 'IFTest::Entity::Zab';
use aliased 'IFTest::Entity::Elastic';
sub setUp : Test(setup) {
my ($self) = @_;
$self->{oc}->init();
}
sub testTrackNewObject : Test(4) {
my ($self) = @_;
my $e = Globule->new();
ok( ! $e->isTrackedByObjectContext(), "New object is not being tracked" );
ok( ! $self->{oc}->entityIsTracked($e), "Object context knows nothing of new object" );
$self->{oc}->trackEntity($e);
ok( $e->isTrackedByObjectContext(), "Object was inserted into editing context." );
ok( $self->{oc}->entityIsTracked($e), "Object context knows about new object" );
}
sub testIgnoreObject : Test(4) {
my ($self) = @_;
my $e = Zab->new();
ok( ! $e->isTrackedByObjectContext(), "New object is not being tracked");
$self->{oc}->insertEntity($e);
ok( $e->isTrackedByObjectContext(), "New object is being tracked");
$self->{oc}->forgetEntity($e);
ok( ! $e->isTrackedByObjectContext(), "New object is no longer being tracked");
ok( ! $self->{oc}->entityIsTracked($e), "Object context no longer knows about new object");
}
sub testGetChangedObjects : Test(16) {
my ($self) = @_;
my $e = Zab->newFromDictionary({ title => "Zab 1" });
my $f = Zab->newFromDictionary({ title => "Zab 2" });
my $g = Zab->newFromDictionary({ title => "Zab 3" });
ok( $e->title() eq "Zab 1", "Set title correctly");
ok( ! $e->isTrackedByObjectContext() );
ok( ! $f->isTrackedByObjectContext() );
ok( ! $g->isTrackedByObjectContext() );
$self->{oc}->insertEntity($e);
$self->{oc}->insertEntity($f);
$self->{oc}->insertEntity($g);
ok( $e->isTrackedByObjectContext() );
ok( $f->isTrackedByObjectContext() );
ok( $g->isTrackedByObjectContext() );
ok( scalar @{$self->{oc}->changedEntities()} == 0, "oc has no changed objects");
ok( scalar @{$self->{oc}->addedEntities()} == 3, "oc has three added entities");
ok( scalar @{$self->{oc}->trackedEntities()} == 3, "oc has three tracked entities");
# This should commit the new objects
# diag $self->{oc}->addedEntities();
$self->{oc}->saveChanges();
ok( scalar @{$self->{oc}->changedEntities()} == 0, "oc has no changed objects");
ok( scalar @{$self->{oc}->addedEntities()} == 0, "oc has no added entities");
ok( scalar @{$self->{oc}->trackedEntities()} == 3, "oc has three tracked entities");
$f->setTitle("Zab 2a");
ok( scalar @{$self->{oc}->changedEntities()} == 1, "oc has one changed entity");
ok( $self->{oc}->changedEntities()->[0]->is( $f ), "... and it's f");
$self->{oc}->saveChanges();
ok( scalar @{$self->{oc}->changedEntities()} == 0, "flushed oc has no changed entity");
}
sub testUniquing : Test(16) {
my ($self) = @_;
my $e = Branch->newFromDictionary({ leafCount => 99, length => 16 });
my $f = Branch->newFromDictionary({ leafCount => 12, length => 8 });
my $g = Branch->newFromDictionary({ leafCount => 14, length => 6 });
my $h = Branch->newFromDictionary({ leafCount => 16, length => 4 });
ok( scalar @{$self->{oc}->trackedEntities()} == 0, "no tracked entities yet");
$self->{oc}->trackEntities($e, $f, $g);
ok( scalar @{$self->{oc}->trackedEntities()} == 3, "three tracked entities now");
ok( scalar @{$self->{oc}->addedEntities()} == 3, "three added entities now");
my $t = Trunk->newFromDictionary({ thickness => 3 });
$t->addObjectToBranches($e);
$t->addObjectToBranches($f);
$t->addObjectToBranches($g);
$t->addObjectToBranches($h);
ok( scalar @{$t->relatedEntities()} == 4, "Trunk has four related entities in memory");
# FIXME: this shouldn't be necessary because
# it's related to objects in the OC.
$self->{oc}->trackEntity($t);
ok( scalar @{$self->{oc}->trackedEntities()} == 5, "correct # tracked entities now");
# this commits everyone
$self->{oc}->saveChanges();
ok( $e->id(), "e has an id now");
# now do some basic uniquing checks
my $re = $self->{oc}->entityWithPrimaryKey("Branch", $e->id());
ok( $re == $e, "object fetched with pk should return unique instance");
my $re2 = $self->{oc}->entityWithPrimaryKey("Branch", $e->id());
ok( $re2 == $re, "fetched again, same again");
my $brs = $t->branches();
ok( $brs->containsObject($e), "e is in branches");
ok( $brs->containsObject($f), "f is in branches");
ok( $brs->containsObject($g), "g is in branches");
ok( $brs->containsObject($h), "h is in branches");
# make sure something fetched via a query is uniqued too
my $newb = IF::Query->new("Branch")->filter("leafCount = %@", 12)->first();
ok( $newb == $f, "Fetched result is matched with in-memory result");
# what about traversing across a relationship?
my $newt = IF::Query->new("Trunk")->filter("branches.leafCount = %@", 99)->prefetch("branches")->first();
ok( $newt == $t, "Fetched result is matched with in-memory result");
ok( scalar @{$newt->_cachedEntitiesForRelationshipNamed("branches")} == 4, "Four branches attached to in-memory");
ok( scalar @{$newt->branches()} == 4, "Four branches when fetched via <branches> method");
}
sub testFaultingAndUniquing : Test(7) {
my ($self) = @_;
my $e = Branch->newFromDictionary({ leafCount => 10, length => 16 });
my $f = Branch->newFromDictionary({ leafCount => 12, length => 8 });
my $g = Branch->newFromDictionary({ leafCount => 14, length => 6 });
my $t = Trunk->newFromDictionary({ thickness => 17 });
$t->addObjectToBranches($e);
ok( scalar @{$t->branches()} == 1, "One branch connected");
ok( scalar @{$t->_cachedEntitiesForRelationshipNamed("branches")} == 1, "One cached connected");
# add same one again
$t->addObjectToBranches($e);
ok( scalar @{$t->branches()} == 1, "One branch connected still");
ok( scalar @{$t->_cachedEntitiesForRelationshipNamed("branches")} == 1, "One cached connected still");
#diag $t->branches();
#diag $t->relatedEntities();
$self->{oc}->trackEntity($t);
$self->{oc}->saveChanges();
$self->{oc}->clearTrackedEntities();
my $rt = $self->{oc}->entityWithPrimaryKey("Trunk", $t->id());
#ok( [[rt branches] count] eq 1, "Refetched trunk has 1");
# add another
$rt->addObjectToBranches($f);
# calling branches here should fault in from the DB
ok( scalar @{$rt->_cachedEntitiesForRelationshipNamed("branches")} == 1, "One cached entity");
ok( scalar @{$rt->branches()} == 2, "Now two");
ok( scalar @{$rt->_cachedEntitiesForRelationshipNamed("branches")} == 2, "Two cached entities");
}
sub testTraversedRelationshipsBeforeCommit : Test(4) {
my ($self) = @_;
my $branch = Branch->newFromDictionary({ leafCount => 33, length => 12 });
my $trunk = Trunk->newFromDictionary({ thickness => 20 });
my $root = Root->newFromDictionary({ title => "Big Tree!" });
$self->{oc}->trackEntity($root);
$root->setTrunk($trunk);
$trunk->addObjectToBranches($branch);
ok( $root->trunk(), "in-memory connection made");
ok( scalar @{$trunk->branches()} == 1);
ok( scalar @{$self->{oc}->addedEntities()} == 3, "oc has correct number of added entities");
ok( scalar @{$root->trunk()->branches()} == 1, "traversal gives correct results");
}
sub testTraversedRelationshipsAfterCommit : Test(5) {
my ($self) = @_;
my $branch = Branch->newFromDictionary({ leafCount => 33, length => 12 });
my $trunk = Trunk->newFromDictionary({ thickness => 888 });
my $root = Root->newFromDictionary({ title => "Big Tree!"});
$self->{oc}->trackEntity($root);
$root->setTrunk($trunk);
$trunk->addObjectToBranches($branch);
$self->{oc}->saveChanges();
$self->{oc}->clearTrackedEntities();
$branch = undef;
$trunk = undef;
$root = undef;
# TODO: ensure garbage is collected here?
my $rr = $self->{oc}->entityMatchingQualifier("Root", IF::Qualifier->key("title = %@", "Big Tree!"));
ok( $rr, "Refetch root");
my $rt = $self->{oc}->entityMatchingQualifier("Trunk", IF::Qualifier->key("thickness = %@", 888));
ok( $rt, "Refetch trunk");
my $br = $self->{oc}->entityMatchingQualifier("Branch", IF::Qualifier->key("leafCount = %@", 33));
ok( $br, "Refetch branch");
ok( $rr->trunk() == $rt, "related trunk is same as refetched");
ok( $rt->branches()->[0] == $br, "Related branch is same as refetched");
}
sub testChangedObjects :Test(6) {
my ($self) = @_;
# first flush the OC
$self->{oc}->clearTrackedEntities();
ok( scalar @{$self->{oc}->trackedEntities()} == 0, "OC has been flushed");
ok( $self->{oc}->trackingIsEnabled(), "Tracking is enabled");
# fetch any branch object
my $branch = IF::Query->new("Branch")->first();
ok( $branch, "fetched a branch from the DB");
ok( scalar @{$self->{oc}->trackedEntities()} == 1, "OC is tracking one entity");
# flush the OC
$self->{oc}->clearTrackedEntities();
ok( scalar @{$self->{oc}->trackedEntities()} == 0, "OC has been flushed");
ok( ! $branch->isTrackedByObjectContext(), "branch is no longer being tracked");
}
1; | quile/if-framework | framework/t/IFTest/TestObjectContext.pm | Perl | mit | 9,517 |
########################################################################
# Bio::KBase::ObjectAPI::KBaseFBA::FBAReactionVariable - This is the moose object corresponding to the FBAReactionVariable object
# Authors: Christopher Henry, Scott Devoid, Paul Frybarger
# Contact email: chenry@mcs.anl.gov
# Development location: Mathematics and Computer Science Division, Argonne National Lab
# Date of module creation: 2012-04-28T22:56:11
########################################################################
use strict;
use Bio::KBase::ObjectAPI::KBaseFBA::DB::FBAReactionVariable;
package Bio::KBase::ObjectAPI::KBaseFBA::FBAReactionVariable;
use Moose;
use namespace::autoclean;
extends 'Bio::KBase::ObjectAPI::KBaseFBA::DB::FBAReactionVariable';
#***********************************************************************************************************
# ADDITIONAL ATTRIBUTES:
#***********************************************************************************************************
has reactionID => ( is => 'rw', isa => 'Str',printOrder => '1', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildreactionID');
has reactionName => ( is => 'rw', isa => 'Str',printOrder => '2', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildreactionName');
has modelreaction => ( is => 'rw', isa => 'Ref',printOrder => '2', type => 'msdata', metaclass => 'Typed', lazy => 1, builder => '_buildmodelreaction');
#***********************************************************************************************************
# BUILDERS:
#***********************************************************************************************************
sub _buildreactionID {
my ($self) = @_;
return $self->modelreaction()->reaction()->msid();
}
sub _buildreactionName {
my ($self) = @_;
return $self->modelreaction()->reaction()->msname();
}
sub _buildmodelreaction {
my ($self) = @_;
if ($self->modelreaction_ref() =~ m/~\/modelreactions\/id\/(.+)/) {
$self->modelreaction_ref("~/fbamodel/modelreactions/id/".$1);
}
return $self->getLinkedObject($self->modelreaction_ref());
}
#***********************************************************************************************************
# CONSTANTS:
#***********************************************************************************************************
#***********************************************************************************************************
# FUNCTIONS:
#***********************************************************************************************************
=head3 clearProblem
Definition:
Output = Bio::KBase::ObjectAPI::KBaseFBA::FBAModel->clearProblem();
Output = {
success => 0/1
};
Description:
Builds the FBA problem
=cut
__PACKAGE__->meta->make_immutable;
1;
| cshenry/fba_tools | lib/Bio/KBase/ObjectAPI/KBaseFBA/FBAReactionVariable.pm | Perl | mit | 2,796 |
/*************************************************************************
File: pluggingAlgorithm.pl
Copyright (C) 2004 Patrick Blackburn & Johan Bos
This file is part of BB1, version 1.2 (August 2005).
BB1 is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
BB1 is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with BB1; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
/*========================================================================
Module Declaration
========================================================================*/
:- module(pluggingAlgorithm,[plugUSR/2]).
:- use_module(comsemPredicates,[compose/3,
memberList/2,
selectFromList/3]).
/*========================================================================
Declaration of dynamic predicates
========================================================================*/
:- dynamic plug/2, leq/2, hole/1, label/1.
:- dynamic some/3, all/3, que/4.
:- dynamic not/2, or/3, imp/3, and/3.
:- dynamic pred1/3, pred2/4, eq/3.
/*========================================================================
Main Plugging Predicate (all pluggings)
========================================================================*/
plugUSR(USR,Sem):-
numbervars(USR,0,_), % 1 Skolemise USR
initUSR,
assertUSR(USR), % 2 Break down and assert USR
top(Top),
findall(H,hole(H),Holes),
findall(L,
(label(L),\+ parent(_,L)),
Labels),
plugHoles(Holes,Labels,[]), % 3 Calculate a plugging
url2srl(Top,Sem). % 4 Construct SRL formula
/*========================================================================
Asserting immediate dominance relations to the Prolog database
========================================================================*/
parent(A,B):- imp(A,B,_).
parent(A,B):- imp(A,_,B).
parent(A,B):- or(A,B,_).
parent(A,B):- or(A,_,B).
parent(A,B):- and(A,B,_).
parent(A,B):- and(A,_,B).
parent(A,B):- not(A,B).
parent(A,B):- all(A,_,B).
parent(A,B):- some(A,_,B).
parent(A,B):- que(A,_,B,_).
parent(A,B):- que(A,_,_,B).
parent(A,B):- plug(A,B).
/*========================================================================
Transitive Closure of Dominance
========================================================================*/
dom(X,Y):- dom([],X,Y).
dom(L,X,Y):-
parent(X,Y),
\+ memberList(parent(X,Y),L).
dom(L,X,Y):-
leq(Y,X),
\+ memberList(leq(Y,X),L).
dom(L,X,Z):-
parent(X,Y),
\+ memberList(parent(X,Y),L),
dom([parent(X,Y)|L],Y,Z).
dom(L,X,Z):-
leq(Y,X),
\+ memberList(leq(Y,X),L),
dom([leq(Y,X)|L],Y,Z).
/*========================================================================
Plugging Holes with Labels
========================================================================*/
plugHoles([],_,Plugs):-
admissiblePlugging(Plugs).
plugHoles([H|Holes],Labels1,Plugs):-
admissiblePlugging(Plugs),
selectFromList(L,Labels1,Labels2),
plugHoles(Holes,Labels2,[plug(H,L)|Plugs]).
/*========================================================================
Check whether plugging is propers
========================================================================*/
admissiblePlugging(Plugs):-
retractall(plug(_,_)),
findall(X,(memberList(X,Plugs),assert(X)),_),
\+ dom(A,A),
\+ ( parent(A,B), parent(A,C), \+ B=C, dom(B,D), dom(C,D)).
/*========================================================================
Top of a USR
========================================================================*/
top(X):- dom(X,_), \+ dom(_,X), !.
/*========================================================================
From USRs to FOLs
========================================================================*/
url2srl(H,F):-
hole(H),
plug(H,L),
url2srl(L,F).
url2srl(L,all(X,F)):-
all(L,X,H),
url2srl(H,F).
url2srl(L,some(X,F)):-
some(L,X,H),
url2srl(H,F).
url2srl(L,que(X,F1,F2)):-
que(L,X,H1,H2),
url2srl(H1,F1),
url2srl(H2,F2).
url2srl(L,imp(F1,F2)):-
imp(L,H1,H2),
url2srl(H1,F1),
url2srl(H2,F2).
url2srl(L,and(F1,F2)):-
and(L,H1,H2),
url2srl(H1,F1),
url2srl(H2,F2).
url2srl(L,or(F1,F2)):-
or(L,H1,H2),
url2srl(H1,F1),
url2srl(H2,F2).
url2srl(L,not(F)):-
not(L,H),
url2srl(H,F).
url2srl(L,eq(X,Y)):-
eq(L,X,Y).
url2srl(L,F):-
pred1(L,Symbol,Arg),
compose(F,Symbol,[Arg]).
url2srl(L,F):-
pred2(L,Symbol,Arg1,Arg2),
compose(F,Symbol,[Arg1,Arg2]).
/*========================================================================
Assert USR to Prolog database
========================================================================*/
assertUSR(some(_,F)):-
assertUSR(F).
assertUSR(and(F1,F2)):-
assertUSR(F1),
assertUSR(F2).
assertUSR(F):-
\+ F=and(_,_),
\+ F=some(_,_),
assert(F).
/*========================================================================
Initialisation
========================================================================*/
initUSR:-
retractall(hole(_)), retractall(label(_)), retractall(leq(_,_)),
retractall(some(_,_,_)), retractall(all(_,_,_)), retractall(que(_,_,_,_)),
retractall(pred1(_,_,_)), retractall(pred2(_,_,_,_)), retractall(eq(_,_,_)),
retractall(and(_,_,_)), retractall(or(_,_,_)), retractall(not(_,_)),
retractall(plug(_,_)), retractall(imp(_,_,_)).
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/CURT/bb1/pluggingAlgorithm.pl | Perl | mit | 6,087 |
use c_rt_lib;
use c_fe_lib;
use string;
use hash;
use array;
use dfile;
use ptd;
use nast;
use nparser;
use boolean_t;
use pretty_printer;
use generator_c;
use generator_pm;
use generator_js;
use generator_java;
use translator;
use nlasm;
use post_processing;
use post_processing_t;
use tc_types;
use type_checker;
use module_checker;
use interpreter;
use nl;
use compiler_lib;
use profile;
use nsystem;
use string_utils;
use reference_generator;
sub compiler_priv::get_dir_cache_name;
sub compiler_priv::get_dir_pretty_name;
sub compiler_priv::get_default_deref_file;
sub compiler_priv::get_default_math_file;
sub compiler::parse_check_t;
sub compiler::errors_hash_t;
sub compiler::errors_group_t;
sub compiler::language_t;
sub compiler::destination_t;
sub compiler::module_t;
sub compiler::deref_t;
sub compiler::try_t;
sub compiler::input_type;
sub compiler::file_t;
sub compiler::compile;
sub compiler_priv::get_profile_file_name;
sub compiler_priv::get_known_func;
sub compiler_priv::exec_interpreter;
sub compiler_priv::get_module_name;
sub compiler_priv::has_extension;
sub compiler_priv::get_generator_state;
sub compiler_priv::get_out_ext;
sub compiler_priv::mk_path;
sub compiler_priv::mk_path_module;
sub compiler_priv::get_all_nianio_file;
sub compiler_priv::get_files_to_parse;
sub compiler_priv::parse_module;
sub compiler_priv::get_mathematical_func;
sub compiler_priv::compile_ide;
sub compiler_priv::compile_strict_file;
sub compiler_priv::construct_error_message;
sub compiler_priv::show_and_count_errors;
sub compiler_priv::translate;
sub compiler_priv::check_modules;
sub compiler_priv::serialize_deref;
sub compiler_priv::process_deref;
sub compiler_priv::try_save_file;
sub compiler_priv::generate_modules_to_files;
sub compiler_priv::save_module_to_file;
sub compiler_priv::get_dir;
sub compiler_priv::parse_command_line_args;
return 1;
sub compiler_priv::__get_dir_cache_name() {
my $memory_0;
#line 36
$memory_0 = "cache_nl";
#line 36
return $memory_0;
#line 36
undef($memory_0);
#line 36
return;
}
my $_get_dir_cache_name;
sub compiler_priv::get_dir_cache_name() {
$_get_dir_cache_name = compiler_priv::__get_dir_cache_name() unless defined $_get_dir_cache_name;
return $_get_dir_cache_name;
}
sub compiler_priv::__get_dir_pretty_name() {
my $memory_0;
#line 40
$memory_0 = "pretty_nl";
#line 40
return $memory_0;
#line 40
undef($memory_0);
#line 40
return;
}
my $_get_dir_pretty_name;
sub compiler_priv::get_dir_pretty_name() {
$_get_dir_pretty_name = compiler_priv::__get_dir_pretty_name() unless defined $_get_dir_pretty_name;
return $_get_dir_pretty_name;
}
sub compiler_priv::__get_default_deref_file() {
my $memory_0;
#line 44
$memory_0 = "deref.gr";
#line 44
return $memory_0;
#line 44
undef($memory_0);
#line 44
return;
}
my $_get_default_deref_file;
sub compiler_priv::get_default_deref_file() {
$_get_default_deref_file = compiler_priv::__get_default_deref_file() unless defined $_get_default_deref_file;
return $_get_default_deref_file;
}
sub compiler_priv::__get_default_math_file() {
my $memory_0;
#line 48
$memory_0 = "math_fun.gr";
#line 48
return $memory_0;
#line 48
undef($memory_0);
#line 48
return;
}
my $_get_default_math_file;
sub compiler_priv::get_default_math_file() {
$_get_default_math_file = compiler_priv::__get_default_math_file() unless defined $_get_default_math_file;
return $_get_default_math_file;
}
sub compiler::__parse_check_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;
#line 53
$memory_3 = {
module => "nast",
name => "module_t",
};
#line 53
$memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3);
#line 53
$memory_2 = ptd::hash($memory_3);
#line 53
undef($memory_3);
#line 54
$memory_4 = ptd::sim();
#line 54
$memory_3 = ptd::arr($memory_4);
#line 54
undef($memory_4);
#line 55
$memory_4 = {
module => "tc_types",
name => "deref_types",
};
#line 55
$memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4);
#line 55
$memory_1 = {asts => $memory_2,errors => $memory_3,deref_type => $memory_4,};
#line 55
undef($memory_2);
#line 55
undef($memory_3);
#line 55
undef($memory_4);
#line 55
$memory_0 = ptd::rec($memory_1);
#line 55
undef($memory_1);
#line 55
return $memory_0;
#line 55
undef($memory_0);
#line 55
return;
}
my $_parse_check_t;
sub compiler::parse_check_t() {
$_parse_check_t = compiler::__parse_check_t() unless defined $_parse_check_t;
return $_parse_check_t;
}
sub compiler::__errors_hash_t() {
my $memory_0;my $memory_1;my $memory_2;
#line 60
$memory_2 = {
module => "compiler_lib",
name => "error_t",
};
#line 60
$memory_2 = c_rt_lib::ov_mk_arg('ref', $memory_2);
#line 60
$memory_1 = ptd::arr($memory_2);
#line 60
undef($memory_2);
#line 60
$memory_0 = ptd::hash($memory_1);
#line 60
undef($memory_1);
#line 60
return $memory_0;
#line 60
undef($memory_0);
#line 60
return;
}
my $_errors_hash_t;
sub compiler::errors_hash_t() {
$_errors_hash_t = compiler::__errors_hash_t() unless defined $_errors_hash_t;
return $_errors_hash_t;
}
sub compiler::__errors_group_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;
#line 65
$memory_2 = {
module => "compiler",
name => "errors_hash_t",
};
#line 65
$memory_2 = c_rt_lib::ov_mk_arg('ref', $memory_2);
#line 66
$memory_3 = {
module => "compiler",
name => "errors_hash_t",
};
#line 66
$memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3);
#line 67
$memory_4 = {
module => "compiler",
name => "errors_hash_t",
};
#line 67
$memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4);
#line 68
$memory_5 = {
module => "compiler",
name => "errors_hash_t",
};
#line 68
$memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5);
#line 69
$memory_6 = {
module => "module_checker",
name => "ret_t",
};
#line 69
$memory_6 = c_rt_lib::ov_mk_arg('ref', $memory_6);
#line 69
$memory_1 = {module_errors => $memory_2,module_warnings => $memory_3,type_errors => $memory_4,type_warnings => $memory_5,loop_error => $memory_6,};
#line 69
undef($memory_2);
#line 69
undef($memory_3);
#line 69
undef($memory_4);
#line 69
undef($memory_5);
#line 69
undef($memory_6);
#line 69
$memory_0 = ptd::rec($memory_1);
#line 69
undef($memory_1);
#line 69
return $memory_0;
#line 69
undef($memory_0);
#line 69
return;
}
my $_errors_group_t;
sub compiler::errors_group_t() {
$_errors_group_t = compiler::__errors_group_t() unless defined $_errors_group_t;
return $_errors_group_t;
}
sub compiler::__language_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;
#line 75
$memory_2 = ptd::none();
#line 76
$memory_3 = ptd::none();
#line 77
$memory_4 = ptd::none();
#line 78
$memory_5 = ptd::none();
#line 79
$memory_6 = ptd::none();
#line 80
$memory_9 = ptd::sim();
#line 80
$memory_8 = {namespace => $memory_9,};
#line 80
undef($memory_9);
#line 80
$memory_7 = ptd::rec($memory_8);
#line 80
undef($memory_8);
#line 81
$memory_8 = ptd::none();
#line 82
$memory_9 = ptd::none();
#line 82
$memory_1 = {pm => $memory_2,nla => $memory_3,c => $memory_4,nl => $memory_5,ast => $memory_6,js => $memory_7,java => $memory_8,call_graph => $memory_9,};
#line 82
undef($memory_2);
#line 82
undef($memory_3);
#line 82
undef($memory_4);
#line 82
undef($memory_5);
#line 82
undef($memory_6);
#line 82
undef($memory_7);
#line 82
undef($memory_8);
#line 82
undef($memory_9);
#line 82
$memory_0 = ptd::var($memory_1);
#line 82
undef($memory_1);
#line 82
return $memory_0;
#line 82
undef($memory_0);
#line 82
return;
}
my $_language_t;
sub compiler::language_t() {
$_language_t = compiler::__language_t() unless defined $_language_t;
return $_language_t;
}
sub compiler::__destination_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;
#line 88
$memory_2 = ptd::sim();
#line 89
$memory_3 = ptd::sim();
#line 90
$memory_6 = ptd::sim();
#line 90
$memory_7 = ptd::sim();
#line 90
$memory_5 = {c => $memory_6,h => $memory_7,};
#line 90
undef($memory_6);
#line 90
undef($memory_7);
#line 90
$memory_4 = ptd::rec($memory_5);
#line 90
undef($memory_5);
#line 91
$memory_5 = ptd::sim();
#line 92
$memory_6 = ptd::sim();
#line 93
$memory_7 = ptd::sim();
#line 94
$memory_8 = ptd::sim();
#line 95
$memory_9 = ptd::none();
#line 96
$memory_10 = ptd::none();
#line 96
$memory_1 = {pm => $memory_2,nla => $memory_3,c => $memory_4,nl => $memory_5,ast => $memory_6,js => $memory_7,java => $memory_8,none => $memory_9,call_graph => $memory_10,};
#line 96
undef($memory_2);
#line 96
undef($memory_3);
#line 96
undef($memory_4);
#line 96
undef($memory_5);
#line 96
undef($memory_6);
#line 96
undef($memory_7);
#line 96
undef($memory_8);
#line 96
undef($memory_9);
#line 96
undef($memory_10);
#line 96
$memory_0 = ptd::var($memory_1);
#line 96
undef($memory_1);
#line 96
return $memory_0;
#line 96
undef($memory_0);
#line 96
return;
}
my $_destination_t;
sub compiler::destination_t() {
$_destination_t = compiler::__destination_t() unless defined $_destination_t;
return $_destination_t;
}
sub compiler::__module_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;
#line 101
$memory_3 = ptd::sim();
#line 101
$memory_4 = {
module => "compiler",
name => "destination_t",
};
#line 101
$memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4);
#line 101
$memory_2 = {src => $memory_3,dst => $memory_4,};
#line 101
undef($memory_3);
#line 101
undef($memory_4);
#line 101
$memory_1 = ptd::rec($memory_2);
#line 101
undef($memory_2);
#line 101
$memory_0 = ptd::hash($memory_1);
#line 101
undef($memory_1);
#line 101
return $memory_0;
#line 101
undef($memory_0);
#line 101
return;
}
my $_module_t;
sub compiler::module_t() {
$_module_t = compiler::__module_t() unless defined $_module_t;
return $_module_t;
}
sub compiler::__deref_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;
#line 105
$memory_2 = ptd::sim();
#line 105
$memory_3 = ptd::none();
#line 105
$memory_1 = {yes => $memory_2,no => $memory_3,};
#line 105
undef($memory_2);
#line 105
undef($memory_3);
#line 105
$memory_0 = ptd::var($memory_1);
#line 105
undef($memory_1);
#line 105
return $memory_0;
#line 105
undef($memory_0);
#line 105
return;
}
my $_deref_t;
sub compiler::deref_t() {
$_deref_t = compiler::__deref_t() unless defined $_deref_t;
return $_deref_t;
}
sub compiler::__try_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;
#line 109
$memory_2 = ptd::sim();
#line 109
$memory_3 = ptd::sim();
#line 109
$memory_1 = {err => $memory_2,ok => $memory_3,};
#line 109
undef($memory_2);
#line 109
undef($memory_3);
#line 109
$memory_0 = ptd::var($memory_1);
#line 109
undef($memory_1);
#line 109
return $memory_0;
#line 109
undef($memory_0);
#line 109
return;
}
my $_try_t;
sub compiler::try_t() {
$_try_t = compiler::__try_t() unless defined $_try_t;
return $_try_t;
}
sub compiler::__input_type() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;
#line 114
$memory_3 = ptd::sim();
#line 114
$memory_2 = ptd::arr($memory_3);
#line 114
undef($memory_3);
#line 115
$memory_3 = ptd::sim();
#line 116
$memory_4 = {
module => "compiler",
name => "deref_t",
};
#line 116
$memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4);
#line 118
$memory_7 = ptd::none();
#line 119
$memory_8 = ptd::none();
#line 120
$memory_9 = ptd::none();
#line 121
$memory_10 = ptd::none();
#line 122
$memory_11 = ptd::none();
#line 122
$memory_6 = {o0 => $memory_7,o1 => $memory_8,o2 => $memory_9,o3 => $memory_10,o4 => $memory_11,};
#line 122
undef($memory_7);
#line 122
undef($memory_8);
#line 122
undef($memory_9);
#line 122
undef($memory_10);
#line 122
undef($memory_11);
#line 122
$memory_5 = ptd::var($memory_6);
#line 122
undef($memory_6);
#line 124
$memory_6 = ptd::sim();
#line 125
$memory_9 = ptd::none();
#line 125
$memory_10 = ptd::none();
#line 125
$memory_11 = ptd::none();
#line 125
$memory_12 = ptd::sim();
#line 125
$memory_8 = {strict => $memory_9,exec => $memory_10,ide => $memory_11,idex => $memory_12,};
#line 125
undef($memory_9);
#line 125
undef($memory_10);
#line 125
undef($memory_11);
#line 125
undef($memory_12);
#line 125
$memory_7 = ptd::var($memory_8);
#line 125
undef($memory_8);
#line 126
$memory_8 = {
module => "compiler",
name => "language_t",
};
#line 126
$memory_8 = c_rt_lib::ov_mk_arg('ref', $memory_8);
#line 127
$memory_11 = ptd::none();
#line 127
$memory_12 = ptd::none();
#line 127
$memory_10 = {norm => $memory_11,wall => $memory_12,};
#line 127
undef($memory_11);
#line 127
undef($memory_12);
#line 127
$memory_9 = ptd::var($memory_10);
#line 127
undef($memory_10);
#line 128
$memory_10 = {
module => "boolean_t",
name => "type",
};
#line 128
$memory_10 = c_rt_lib::ov_mk_arg('ref', $memory_10);
#line 129
$memory_11 = {
module => "boolean_t",
name => "type",
};
#line 129
$memory_11 = c_rt_lib::ov_mk_arg('ref', $memory_11);
#line 129
$memory_1 = {input_path => $memory_2,cache_path => $memory_3,deref => $memory_4,optimization => $memory_5,math_fun => $memory_6,mode => $memory_7,language => $memory_8,alarm => $memory_9,check_public_fun => $memory_10,profile => $memory_11,};
#line 129
undef($memory_2);
#line 129
undef($memory_3);
#line 129
undef($memory_4);
#line 129
undef($memory_5);
#line 129
undef($memory_6);
#line 129
undef($memory_7);
#line 129
undef($memory_8);
#line 129
undef($memory_9);
#line 129
undef($memory_10);
#line 129
undef($memory_11);
#line 129
$memory_0 = ptd::rec($memory_1);
#line 129
undef($memory_1);
#line 129
return $memory_0;
#line 129
undef($memory_0);
#line 129
return;
}
my $_input_type;
sub compiler::input_type() {
$_input_type = compiler::__input_type() unless defined $_input_type;
return $_input_type;
}
sub compiler::__file_t() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;
#line 134
$memory_2 = ptd::sim();
#line 134
$memory_3 = ptd::sim();
#line 134
$memory_1 = {ok => $memory_2,err => $memory_3,};
#line 134
undef($memory_2);
#line 134
undef($memory_3);
#line 134
$memory_0 = ptd::var($memory_1);
#line 134
undef($memory_1);
#line 134
return $memory_0;
#line 134
undef($memory_0);
#line 134
return;
}
my $_file_t;
sub compiler::file_t() {
$_file_t = compiler::__file_t() unless defined $_file_t;
return $_file_t;
}
sub compiler::compile($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;$memory_0 = $_[0];
#line 138
$memory_1 = compiler_priv::parse_command_line_args($memory_0);
#line 139
$memory_2 = $memory_1->{'cache_path'};
#line 139
c_fe_lib::mk_path($memory_2);
#line 139
undef($memory_2);
#line 140
$memory_2 = 0;
#line 141
$memory_3 = $memory_1->{'mode'};
#line 141
$memory_3 = c_rt_lib::ov_is($memory_3, 'strict');
#line 141
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 141
if (c_rt_lib::check_true($memory_3)) {goto label_16;}
#line 142
$memory_4 = "strict mode processing...";
#line 142
c_fe_lib::print($memory_4);
#line 142
undef($memory_4);
#line 143
$memory_4 = compiler_priv::compile_strict_file($memory_1);
#line 143
$memory_2 = $memory_4;
#line 143
undef($memory_4);
#line 144
goto label_47;
#line 144
label_16:
#line 144
$memory_3 = $memory_1->{'mode'};
#line 144
$memory_3 = c_rt_lib::ov_is($memory_3, 'ide');
#line 144
if (c_rt_lib::check_true($memory_3)) {goto label_22;}
#line 144
$memory_3 = $memory_1->{'mode'};
#line 144
$memory_3 = c_rt_lib::ov_is($memory_3, 'idex');
#line 144
label_22:
#line 144
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 144
if (c_rt_lib::check_true($memory_3)) {goto label_33;}
#line 145
$memory_4 = "ide mode processing...";
#line 145
c_fe_lib::print($memory_4);
#line 145
undef($memory_4);
#line 146
compiler_priv::compile_ide($memory_1);
#line 147
$memory_4 = 0;
#line 147
$memory_2 = $memory_4;
#line 147
undef($memory_4);
#line 148
goto label_47;
#line 148
label_33:
#line 148
$memory_3 = $memory_1->{'mode'};
#line 148
$memory_3 = c_rt_lib::ov_is($memory_3, 'exec');
#line 148
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 148
if (c_rt_lib::check_true($memory_3)) {goto label_42;}
#line 149
$memory_4 = compiler_priv::exec_interpreter($memory_1);
#line 149
$memory_2 = $memory_4;
#line 149
undef($memory_4);
#line 150
goto label_47;
#line 150
label_42:
#line 151
$memory_4 = [];
#line 151
die(dfile::ssave($memory_4));
#line 151
undef($memory_4);
#line 152
goto label_47;
#line 152
label_47:
#line 152
undef($memory_3);
#line 153
$memory_3 = $memory_1->{'profile'};
#line 153
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 153
if (c_rt_lib::check_true($memory_3)) {goto label_62;}
#line 154
$memory_4 = $memory_1->{'cache_path'};
#line 154
$memory_5 = "/profile";
#line 154
$memory_4 = $memory_4 . $memory_5;
#line 154
undef($memory_5);
#line 155
c_fe_lib::mk_path($memory_4);
#line 156
$memory_5 = compiler_priv::get_profile_file_name($memory_4);
#line 156
profile::save($memory_5);
#line 156
undef($memory_5);
#line 156
undef($memory_4);
#line 157
goto label_62;
#line 157
label_62:
#line 157
undef($memory_3);
#line 158
undef($memory_0);
#line 158
undef($memory_1);
#line 158
return $memory_2;
#line 158
undef($memory_1);
#line 158
undef($memory_2);
#line 158
undef($memory_0);
#line 158
return;
}
sub compiler_priv::get_profile_file_name($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;$memory_0 = $_[0];
#line 162
$memory_1 = "/";
#line 162
$memory_1 = $memory_0 . $memory_1;
#line 163
$memory_3 = nsystem::time();
#line 163
$memory_2 = nsystem::localtime($memory_3);
#line 163
undef($memory_3);
#line 164
$memory_3 = nsystem::get_pid();
#line 165
$memory_4 = nsystem::time_microsec();
#line 166
$memory_5 = 5;
#line 166
$memory_6 = 0;
#line 166
$memory_7 = 1;
#line 166
label_10:
#line 166
$memory_8 = c_rt_lib::to_nl($memory_6 >= $memory_5);
#line 166
if (c_rt_lib::check_true($memory_8)) {goto label_24;}
#line 167
$memory_10 = $memory_2->[$memory_6];
#line 167
$memory_11 = 2;
#line 167
$memory_9 = string_utils::int2str($memory_10, $memory_11);
#line 167
undef($memory_11);
#line 167
undef($memory_10);
#line 167
$memory_10 = $memory_9;
#line 167
if (c_rt_lib::get_arrcount($memory_2) > 1) {$memory_2 = [@{$memory_2}];}$memory_2->[$memory_6] = $memory_10;
#line 167
undef($memory_9);
#line 167
undef($memory_10);
#line 168
$memory_6 = $memory_6 + $memory_7;
#line 168
goto label_10;
#line 168
label_24:
#line 168
undef($memory_5);
#line 168
undef($memory_6);
#line 168
undef($memory_7);
#line 168
undef($memory_8);
#line 169
$memory_7 = 1;
#line 169
$memory_6 = $memory_4->[$memory_7];
#line 169
undef($memory_7);
#line 169
$memory_7 = 1000;
#line 169
$memory_6 = $memory_6 / $memory_7;
#line 169
undef($memory_7);
#line 169
$memory_7 = 3;
#line 169
$memory_5 = string_utils::int2str($memory_6, $memory_7);
#line 169
undef($memory_7);
#line 169
undef($memory_6);
#line 170
$memory_6 = "prof_";
#line 170
$memory_6 = $memory_1 . $memory_6;
#line 170
$memory_8 = 5;
#line 170
$memory_7 = $memory_2->[$memory_8];
#line 170
undef($memory_8);
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_7 = "";
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_8 = 4;
#line 170
$memory_7 = $memory_2->[$memory_8];
#line 170
undef($memory_8);
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_7 = "";
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_8 = 3;
#line 170
$memory_7 = $memory_2->[$memory_8];
#line 170
undef($memory_8);
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_7 = "_";
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_8 = 2;
#line 170
$memory_7 = $memory_2->[$memory_8];
#line 170
undef($memory_8);
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_8 = 1;
#line 170
$memory_7 = $memory_2->[$memory_8];
#line 170
undef($memory_8);
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_8 = 0;
#line 170
$memory_7 = $memory_2->[$memory_8];
#line 170
undef($memory_8);
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_6 = $memory_6 . $memory_5;
#line 170
$memory_7 = "_";
#line 170
$memory_6 = $memory_6 . $memory_7;
#line 170
undef($memory_7);
#line 170
$memory_6 = $memory_6 . $memory_3;
#line 171
$memory_7 = ".txt";
#line 171
$memory_6 = $memory_6 . $memory_7;
#line 171
undef($memory_7);
#line 171
undef($memory_0);
#line 171
undef($memory_1);
#line 171
undef($memory_2);
#line 171
undef($memory_3);
#line 171
undef($memory_4);
#line 171
undef($memory_5);
#line 171
return $memory_6;
#line 171
undef($memory_6);
#line 171
undef($memory_1);
#line 171
undef($memory_2);
#line 171
undef($memory_3);
#line 171
undef($memory_4);
#line 171
undef($memory_5);
#line 171
undef($memory_0);
#line 171
return;
}
sub compiler_priv::__get_known_func() {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;
#line 175
$memory_0 = {};
#line 176
$memory_1 = "nl::print";
#line 176
$memory_3 = {
module => "nl",
name => "print",
};
#line 176
$memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3);
#line 176
$memory_4 = c_rt_lib::ov_mk_none('sequential');
#line 176
$memory_6 = ptd::sim();
#line 176
$memory_5 = [$memory_6];
#line 176
undef($memory_6);
#line 176
$memory_6 = c_rt_lib::ov_mk_none('no');
#line 176
$memory_2 = {func => $memory_3,type => $memory_4,args => $memory_5,return => $memory_6,};
#line 176
undef($memory_3);
#line 176
undef($memory_4);
#line 176
undef($memory_5);
#line 176
undef($memory_6);
#line 176
hash::set_value($memory_0, $memory_1, $memory_2);
#line 176
undef($memory_2);
#line 176
undef($memory_1);
#line 177
return $memory_0;
#line 177
undef($memory_0);
#line 177
return;
}
my $_get_known_func;
sub compiler_priv::get_known_func() {
$_get_known_func = compiler_priv::__get_known_func() unless defined $_get_known_func;
return $_get_known_func;
}
sub compiler_priv::exec_interpreter($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;my $memory_13;my $memory_14;my $memory_15;my $memory_16;my $memory_17;my $memory_18;my $memory_19;$memory_0 = $_[0];
#line 181
$memory_1 = {};
#line 183
$memory_3 = {};
#line 184
$memory_4 = {};
#line 185
$memory_5 = {};
#line 186
$memory_6 = {};
#line 187
$memory_7 = c_rt_lib::ov_mk_none('ok');
#line 187
$memory_2 = {module_errors => $memory_3,module_warnings => $memory_4,type_errors => $memory_5,type_warnings => $memory_6,loop_error => $memory_7,};
#line 187
undef($memory_3);
#line 187
undef($memory_4);
#line 187
undef($memory_5);
#line 187
undef($memory_6);
#line 187
undef($memory_7);
#line 189
$memory_3 = 0;
#line 190
$memory_4 = compiler_priv::get_files_to_parse($memory_0);
#line 191
$memory_7 = c_rt_lib::init_iter($memory_4);
#line 191
label_15:
#line 191
$memory_5 = c_rt_lib::is_end_hash($memory_7);
#line 191
if (c_rt_lib::check_true($memory_5)) {goto label_47;}
#line 191
$memory_5 = c_rt_lib::get_key_iter($memory_7);
#line 191
$memory_6 = c_rt_lib::hash_get_value($memory_4, $memory_5);
#line 192
$memory_9 = $memory_6->{'src'};
#line 192
$memory_8 = compiler_priv::parse_module($memory_5, $memory_9, $memory_2);
#line 192
undef($memory_9);
#line 192
$memory_9 = c_rt_lib::ov_is($memory_8, 'ok');
#line 192
if (c_rt_lib::check_true($memory_9)) {goto label_30;}
#line 194
$memory_9 = c_rt_lib::ov_is($memory_8, 'err');
#line 194
if (c_rt_lib::check_true($memory_9)) {goto label_35;}
#line 194
$memory_9 = "NOMATCHALERT";
#line 194
$memory_9 = [$memory_9,$memory_8];
#line 194
die(dfile::ssave($memory_9));
#line 192
label_30:
#line 192
$memory_10 = c_rt_lib::ov_as($memory_8, 'ok');
#line 193
hash::set_value($memory_1, $memory_5, $memory_10);
#line 193
undef($memory_10);
#line 194
goto label_42;
#line 194
label_35:
#line 194
$memory_10 = c_rt_lib::ov_as($memory_8, 'err');
#line 195
$memory_11 = 1;
#line 195
$memory_3 = $memory_3 + $memory_11;
#line 195
undef($memory_11);
#line 195
undef($memory_10);
#line 196
goto label_42;
#line 196
label_42:
#line 196
undef($memory_8);
#line 196
undef($memory_9);
#line 197
$memory_7 = c_rt_lib::next_iter($memory_7);
#line 197
goto label_15;
#line 197
label_47:
#line 197
undef($memory_5);
#line 197
undef($memory_6);
#line 197
undef($memory_7);
#line 198
$memory_5 = 0;
#line 198
$memory_5 = c_rt_lib::to_nl($memory_3 != $memory_5);
#line 198
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 198
if (c_rt_lib::check_true($memory_5)) {goto label_68;}
#line 199
$memory_6 = {};
#line 199
compiler_priv::show_and_count_errors($memory_2, $memory_0, $memory_6);
#line 199
undef($memory_6);
#line 200
$memory_6 = 1;
#line 200
undef($memory_0);
#line 200
undef($memory_1);
#line 200
undef($memory_2);
#line 200
undef($memory_3);
#line 200
undef($memory_4);
#line 200
undef($memory_5);
#line 200
return $memory_6;
#line 200
undef($memory_6);
#line 201
goto label_68;
#line 201
label_68:
#line 201
undef($memory_5);
#line 202
$memory_5 = $memory_0->{'deref'};
#line 202
$memory_6 = $memory_0->{'check_public_fun'};
#line 202
compiler_priv::check_modules($memory_1, $memory_2, $memory_5, $memory_6);
#line 202
undef($memory_6);
#line 202
undef($memory_5);
#line 203
$memory_6 = {};
#line 203
$memory_5 = compiler_priv::show_and_count_errors($memory_2, $memory_0, $memory_6);
#line 203
undef($memory_6);
#line 203
$memory_6 = 0;
#line 203
$memory_5 = c_rt_lib::to_nl($memory_5 > $memory_6);
#line 203
undef($memory_6);
#line 203
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 203
if (c_rt_lib::check_true($memory_5)) {goto label_93;}
#line 204
$memory_6 = 1;
#line 204
undef($memory_0);
#line 204
undef($memory_1);
#line 204
undef($memory_2);
#line 204
undef($memory_3);
#line 204
undef($memory_4);
#line 204
undef($memory_5);
#line 204
return $memory_6;
#line 204
undef($memory_6);
#line 205
goto label_93;
#line 205
label_93:
#line 205
undef($memory_5);
#line 206
$memory_6 = {};
#line 206
$memory_7 = $memory_0->{'optimization'};
#line 206
$memory_5 = post_processing::init($memory_6, $memory_7);
#line 206
undef($memory_7);
#line 206
undef($memory_6);
#line 207
$memory_6 = compiler_priv::translate($memory_1, $memory_5);
#line 208
$memory_7 = [];
#line 209
$memory_8 = "";
#line 210
$memory_11 = c_rt_lib::init_iter($memory_6);
#line 210
label_104:
#line 210
$memory_9 = c_rt_lib::is_end_hash($memory_11);
#line 210
if (c_rt_lib::check_true($memory_9)) {goto label_139;}
#line 210
$memory_9 = c_rt_lib::get_key_iter($memory_11);
#line 210
$memory_10 = c_rt_lib::hash_get_value($memory_6, $memory_9);
#line 211
$memory_12 = $memory_10->{'functions'};
#line 211
$memory_14 = 0;
#line 211
$memory_15 = 1;
#line 211
$memory_16 = c_rt_lib::array_len($memory_12);
#line 211
label_113:
#line 211
$memory_17 = c_rt_lib::to_nl($memory_14 >= $memory_16);
#line 211
if (c_rt_lib::check_true($memory_17)) {goto label_129;}
#line 211
$memory_13 = $memory_12->[$memory_14];
#line 212
$memory_18 = $memory_13->{'name'};
#line 212
$memory_19 = "main";
#line 212
$memory_18 = c_rt_lib::to_nl($memory_18 eq $memory_19);
#line 212
undef($memory_19);
#line 212
$memory_18 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_18));
#line 212
if (c_rt_lib::check_true($memory_18)) {goto label_125;}
#line 213
$memory_8 = $memory_9;
#line 214
goto label_125;
#line 214
label_125:
#line 214
undef($memory_18);
#line 215
$memory_14 = $memory_14 + $memory_15;
#line 215
goto label_113;
#line 215
label_129:
#line 215
undef($memory_12);
#line 215
undef($memory_13);
#line 215
undef($memory_14);
#line 215
undef($memory_15);
#line 215
undef($memory_16);
#line 215
undef($memory_17);
#line 216
array::push($memory_7, $memory_10);
#line 217
$memory_11 = c_rt_lib::next_iter($memory_11);
#line 217
goto label_104;
#line 217
label_139:
#line 217
undef($memory_9);
#line 217
undef($memory_10);
#line 217
undef($memory_11);
#line 218
$memory_10 = compiler_priv::get_known_func();
#line 218
$memory_9 = interpreter::init($memory_7, $memory_10);
#line 218
undef($memory_10);
#line 219
$memory_12 = "main";
#line 219
$memory_11 = interpreter::start($memory_9, $memory_12, $memory_8);
#line 219
undef($memory_12);
#line 219
$memory_10 = c_rt_lib::ov_is($memory_11, 'ok');
#line 219
if (c_rt_lib::check_true($memory_10)) {goto label_153;}
#line 219
$memory_11 = c_rt_lib::ov_mk_arg('ensure', $memory_11);
#line 219
die(dfile::ssave($memory_11));
#line 219
label_153:
#line 219
undef($memory_10);
#line 219
undef($memory_11);
#line 220
$memory_11 = interpreter::exec_all_code($memory_9);
#line 220
$memory_10 = c_rt_lib::ov_is($memory_11, 'ok');
#line 220
if (c_rt_lib::check_true($memory_10)) {goto label_161;}
#line 220
$memory_11 = c_rt_lib::ov_mk_arg('ensure', $memory_11);
#line 220
die(dfile::ssave($memory_11));
#line 220
label_161:
#line 220
undef($memory_10);
#line 220
undef($memory_11);
#line 221
$memory_10 = 0;
#line 221
undef($memory_0);
#line 221
undef($memory_1);
#line 221
undef($memory_2);
#line 221
undef($memory_3);
#line 221
undef($memory_4);
#line 221
undef($memory_5);
#line 221
undef($memory_6);
#line 221
undef($memory_7);
#line 221
undef($memory_8);
#line 221
undef($memory_9);
#line 221
return $memory_10;
#line 221
undef($memory_10);
#line 221
undef($memory_1);
#line 221
undef($memory_2);
#line 221
undef($memory_3);
#line 221
undef($memory_4);
#line 221
undef($memory_5);
#line 221
undef($memory_6);
#line 221
undef($memory_7);
#line 221
undef($memory_8);
#line 221
undef($memory_9);
#line 221
undef($memory_0);
#line 221
return;
}
sub compiler_priv::get_module_name($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;$memory_0 = $_[0];
#line 225
$memory_1 = string::length($memory_0);
#line 225
$memory_2 = 1;
#line 225
$memory_1 = $memory_1 - $memory_2;
#line 225
undef($memory_2);
#line 226
label_4:
#line 226
$memory_2 = 0;
#line 226
$memory_2 = c_rt_lib::to_nl($memory_1 >= $memory_2);
#line 226
$memory_4 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 226
if (c_rt_lib::check_true($memory_4)) {goto label_15;}
#line 226
$memory_5 = 1;
#line 226
$memory_2 = string::substr($memory_0, $memory_1, $memory_5);
#line 226
undef($memory_5);
#line 226
$memory_5 = "/";
#line 226
$memory_2 = c_rt_lib::to_nl($memory_2 ne $memory_5);
#line 226
undef($memory_5);
#line 226
label_15:
#line 226
undef($memory_4);
#line 226
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 226
if (c_rt_lib::check_true($memory_3)) {goto label_25;}
#line 226
$memory_4 = 1;
#line 226
$memory_2 = string::substr($memory_0, $memory_1, $memory_4);
#line 226
undef($memory_4);
#line 226
$memory_4 = "\\";
#line 226
$memory_2 = c_rt_lib::to_nl($memory_2 ne $memory_4);
#line 226
undef($memory_4);
#line 226
label_25:
#line 226
undef($memory_3);
#line 226
$memory_2 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 226
if (c_rt_lib::check_true($memory_2)) {goto label_49;}
#line 227
$memory_4 = 1;
#line 227
$memory_3 = string::substr($memory_0, $memory_1, $memory_4);
#line 227
undef($memory_4);
#line 227
$memory_4 = ".";
#line 227
$memory_3 = c_rt_lib::to_nl($memory_3 eq $memory_4);
#line 227
undef($memory_4);
#line 227
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 227
if (c_rt_lib::check_true($memory_3)) {goto label_43;}
#line 228
$memory_4 = 1;
#line 228
$memory_1 = $memory_1 - $memory_4;
#line 228
undef($memory_4);
#line 229
undef($memory_3);
#line 229
goto label_49;
#line 230
goto label_43;
#line 230
label_43:
#line 230
undef($memory_3);
#line 231
$memory_3 = 1;
#line 231
$memory_1 = $memory_1 - $memory_3;
#line 231
undef($memory_3);
#line 232
goto label_4;
#line 232
label_49:
#line 232
undef($memory_2);
#line 233
$memory_2 = "";
#line 234
label_52:
#line 234
$memory_3 = 0;
#line 234
$memory_3 = c_rt_lib::to_nl($memory_1 >= $memory_3);
#line 234
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 234
if (c_rt_lib::check_true($memory_5)) {goto label_63;}
#line 234
$memory_6 = 1;
#line 234
$memory_3 = string::substr($memory_0, $memory_1, $memory_6);
#line 234
undef($memory_6);
#line 234
$memory_6 = "/";
#line 234
$memory_3 = c_rt_lib::to_nl($memory_3 ne $memory_6);
#line 234
undef($memory_6);
#line 234
label_63:
#line 234
undef($memory_5);
#line 234
$memory_4 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 234
if (c_rt_lib::check_true($memory_4)) {goto label_73;}
#line 234
$memory_5 = 1;
#line 234
$memory_3 = string::substr($memory_0, $memory_1, $memory_5);
#line 234
undef($memory_5);
#line 234
$memory_5 = "\\";
#line 234
$memory_3 = c_rt_lib::to_nl($memory_3 ne $memory_5);
#line 234
undef($memory_5);
#line 234
label_73:
#line 234
undef($memory_4);
#line 234
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 234
if (c_rt_lib::check_true($memory_3)) {goto label_87;}
#line 235
$memory_5 = 1;
#line 235
$memory_4 = string::substr($memory_0, $memory_1, $memory_5);
#line 235
undef($memory_5);
#line 235
$memory_4 = $memory_4 . $memory_2;
#line 235
$memory_2 = $memory_4;
#line 235
undef($memory_4);
#line 236
$memory_4 = 1;
#line 236
$memory_1 = $memory_1 - $memory_4;
#line 236
undef($memory_4);
#line 237
goto label_52;
#line 237
label_87:
#line 237
undef($memory_3);
#line 238
undef($memory_0);
#line 238
undef($memory_1);
#line 238
return $memory_2;
#line 238
undef($memory_1);
#line 238
undef($memory_2);
#line 238
undef($memory_0);
#line 238
return;
}
sub compiler_priv::has_extension($$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;$memory_0 = $_[0];$memory_1 = $_[1];
#line 242
$memory_2 = string::length($memory_1);
#line 243
$memory_3 = string::length($memory_0);
#line 243
$memory_3 = c_rt_lib::to_nl($memory_3 <= $memory_2);
#line 243
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 243
if (c_rt_lib::check_true($memory_3)) {goto label_13;}
#line 243
$memory_4 = c_rt_lib::to_nl(0);
#line 243
undef($memory_0);
#line 243
undef($memory_1);
#line 243
undef($memory_2);
#line 243
undef($memory_3);
#line 243
return $memory_4;
#line 243
undef($memory_4);
#line 243
goto label_13;
#line 243
label_13:
#line 243
undef($memory_3);
#line 244
$memory_4 = string::length($memory_0);
#line 244
$memory_4 = $memory_4 - $memory_2;
#line 244
$memory_3 = string::substr($memory_0, $memory_4, $memory_2);
#line 244
undef($memory_4);
#line 244
$memory_2 = $memory_3;
#line 244
undef($memory_3);
#line 245
$memory_3 = c_rt_lib::to_nl($memory_2 eq $memory_1);
#line 245
undef($memory_0);
#line 245
undef($memory_1);
#line 245
undef($memory_2);
#line 245
return $memory_3;
#line 245
undef($memory_3);
#line 245
undef($memory_2);
#line 245
undef($memory_0);
#line 245
undef($memory_1);
#line 245
return;
}
sub compiler_priv::get_generator_state($) {
my $memory_0;my $memory_1;$memory_0 = $_[0];
#line 250
$memory_1 = generator_c::get_empty_state();
#line 250
undef($memory_0);
#line 250
return $memory_1;
#line 250
undef($memory_1);
#line 250
undef($memory_0);
#line 250
return;
}
sub compiler_priv::get_out_ext($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;$memory_0 = $_[0];
#line 254
$memory_1 = c_rt_lib::ov_is($memory_0, 'pm');
#line 254
if (c_rt_lib::check_true($memory_1)) {goto label_19;}
#line 256
$memory_1 = c_rt_lib::ov_is($memory_0, 'nla');
#line 256
if (c_rt_lib::check_true($memory_1)) {goto label_26;}
#line 258
$memory_1 = c_rt_lib::ov_is($memory_0, 'c');
#line 258
if (c_rt_lib::check_true($memory_1)) {goto label_33;}
#line 260
$memory_1 = c_rt_lib::ov_is($memory_0, 'ast');
#line 260
if (c_rt_lib::check_true($memory_1)) {goto label_40;}
#line 262
$memory_1 = c_rt_lib::ov_is($memory_0, 'nl');
#line 262
if (c_rt_lib::check_true($memory_1)) {goto label_47;}
#line 264
$memory_1 = c_rt_lib::ov_is($memory_0, 'js');
#line 264
if (c_rt_lib::check_true($memory_1)) {goto label_54;}
#line 266
$memory_1 = c_rt_lib::ov_is($memory_0, 'java');
#line 266
if (c_rt_lib::check_true($memory_1)) {goto label_64;}
#line 268
$memory_1 = c_rt_lib::ov_is($memory_0, 'call_graph');
#line 268
if (c_rt_lib::check_true($memory_1)) {goto label_71;}
#line 268
$memory_1 = "NOMATCHALERT";
#line 268
$memory_1 = [$memory_1,$memory_0];
#line 268
die(dfile::ssave($memory_1));
#line 254
label_19:
#line 255
$memory_2 = ".pm";
#line 255
undef($memory_0);
#line 255
undef($memory_1);
#line 255
return $memory_2;
#line 255
undef($memory_2);
#line 256
goto label_78;
#line 256
label_26:
#line 257
$memory_2 = ".nla";
#line 257
undef($memory_0);
#line 257
undef($memory_1);
#line 257
return $memory_2;
#line 257
undef($memory_2);
#line 258
goto label_78;
#line 258
label_33:
#line 259
$memory_2 = ".c";
#line 259
undef($memory_0);
#line 259
undef($memory_1);
#line 259
return $memory_2;
#line 259
undef($memory_2);
#line 260
goto label_78;
#line 260
label_40:
#line 261
$memory_2 = ".ast";
#line 261
undef($memory_0);
#line 261
undef($memory_1);
#line 261
return $memory_2;
#line 261
undef($memory_2);
#line 262
goto label_78;
#line 262
label_47:
#line 263
$memory_2 = ".nl";
#line 263
undef($memory_0);
#line 263
undef($memory_1);
#line 263
return $memory_2;
#line 263
undef($memory_2);
#line 264
goto label_78;
#line 264
label_54:
#line 264
$memory_2 = c_rt_lib::ov_as($memory_0, 'js');
#line 265
$memory_3 = ".js";
#line 265
undef($memory_0);
#line 265
undef($memory_1);
#line 265
undef($memory_2);
#line 265
return $memory_3;
#line 265
undef($memory_3);
#line 265
undef($memory_2);
#line 266
goto label_78;
#line 266
label_64:
#line 267
$memory_2 = ".java";
#line 267
undef($memory_0);
#line 267
undef($memory_1);
#line 267
return $memory_2;
#line 267
undef($memory_2);
#line 268
goto label_78;
#line 268
label_71:
#line 269
$memory_2 = "_call_graph.df";
#line 269
undef($memory_0);
#line 269
undef($memory_1);
#line 269
return $memory_2;
#line 269
undef($memory_2);
#line 270
goto label_78;
#line 270
label_78:
#line 270
undef($memory_1);
#line 270
undef($memory_0);
#line 270
return;
}
sub compiler_priv::mk_path($$) {
my $memory_0;my $memory_1;my $memory_2;$memory_0 = $_[0];$memory_1 = $_[1];
#line 274
$memory_2 = ".";
#line 274
$memory_2 = c_rt_lib::to_nl($memory_1 eq $memory_2);
#line 274
$memory_2 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 274
if (c_rt_lib::check_true($memory_2)) {goto label_9;}
#line 274
undef($memory_0);
#line 274
undef($memory_1);
#line 274
undef($memory_2);
#line 274
return;
#line 274
goto label_9;
#line 274
label_9:
#line 274
undef($memory_2);
#line 275
$memory_2 = compiler_priv::get_dir($memory_1);
#line 275
compiler_priv::mk_path($memory_0, $memory_2);
#line 275
undef($memory_2);
#line 276
$memory_2 = $memory_0 . $memory_1;
#line 276
c_fe_lib::mk_path($memory_2);
#line 276
undef($memory_2);
#line 276
undef($memory_0);
#line 276
undef($memory_1);
#line 276
return;
}
sub compiler_priv::mk_path_module($$$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;$memory_0 = $_[0];$memory_1 = $_[1];$memory_2 = $_[2];
#line 281
$memory_3 = $memory_2->{'cache_path'};
#line 281
$memory_3 = $memory_3 . $memory_1;
#line 282
$memory_4 = $memory_0->{'file'};
#line 283
$memory_5 = $memory_2->{'language'};
#line 283
$memory_6 = c_rt_lib::ov_is($memory_5, 'pm');
#line 283
if (c_rt_lib::check_true($memory_6)) {goto label_23;}
#line 285
$memory_6 = c_rt_lib::ov_is($memory_5, 'nla');
#line 285
if (c_rt_lib::check_true($memory_6)) {goto label_39;}
#line 287
$memory_6 = c_rt_lib::ov_is($memory_5, 'c');
#line 287
if (c_rt_lib::check_true($memory_6)) {goto label_55;}
#line 289
$memory_6 = c_rt_lib::ov_is($memory_5, 'nl');
#line 289
if (c_rt_lib::check_true($memory_6)) {goto label_76;}
#line 297
$memory_6 = c_rt_lib::ov_is($memory_5, 'ast');
#line 297
if (c_rt_lib::check_true($memory_6)) {goto label_123;}
#line 299
$memory_6 = c_rt_lib::ov_is($memory_5, 'js');
#line 299
if (c_rt_lib::check_true($memory_6)) {goto label_139;}
#line 301
$memory_6 = c_rt_lib::ov_is($memory_5, 'java');
#line 301
if (c_rt_lib::check_true($memory_6)) {goto label_158;}
#line 303
$memory_6 = c_rt_lib::ov_is($memory_5, 'call_graph');
#line 303
if (c_rt_lib::check_true($memory_6)) {goto label_174;}
#line 303
$memory_6 = "NOMATCHALERT";
#line 303
$memory_6 = [$memory_6,$memory_5];
#line 303
die(dfile::ssave($memory_6));
#line 283
label_23:
#line 284
$memory_8 = ".pm";
#line 284
$memory_8 = $memory_3 . $memory_8;
#line 284
$memory_8 = c_rt_lib::ov_mk_arg('pm', $memory_8);
#line 284
$memory_7 = {src => $memory_4,dst => $memory_8,};
#line 284
undef($memory_8);
#line 284
undef($memory_0);
#line 284
undef($memory_1);
#line 284
undef($memory_2);
#line 284
undef($memory_3);
#line 284
undef($memory_4);
#line 284
undef($memory_5);
#line 284
undef($memory_6);
#line 284
return $memory_7;
#line 284
undef($memory_7);
#line 285
goto label_188;
#line 285
label_39:
#line 286
$memory_8 = ".nla";
#line 286
$memory_8 = $memory_3 . $memory_8;
#line 286
$memory_8 = c_rt_lib::ov_mk_arg('nla', $memory_8);
#line 286
$memory_7 = {src => $memory_4,dst => $memory_8,};
#line 286
undef($memory_8);
#line 286
undef($memory_0);
#line 286
undef($memory_1);
#line 286
undef($memory_2);
#line 286
undef($memory_3);
#line 286
undef($memory_4);
#line 286
undef($memory_5);
#line 286
undef($memory_6);
#line 286
return $memory_7;
#line 286
undef($memory_7);
#line 287
goto label_188;
#line 287
label_55:
#line 288
$memory_9 = ".c";
#line 288
$memory_9 = $memory_3 . $memory_9;
#line 288
$memory_10 = ".h";
#line 288
$memory_10 = $memory_3 . $memory_10;
#line 288
$memory_8 = {c => $memory_9,h => $memory_10,};
#line 288
undef($memory_9);
#line 288
undef($memory_10);
#line 288
$memory_8 = c_rt_lib::ov_mk_arg('c', $memory_8);
#line 288
$memory_7 = {src => $memory_4,dst => $memory_8,};
#line 288
undef($memory_8);
#line 288
undef($memory_0);
#line 288
undef($memory_1);
#line 288
undef($memory_2);
#line 288
undef($memory_3);
#line 288
undef($memory_4);
#line 288
undef($memory_5);
#line 288
undef($memory_6);
#line 288
return $memory_7;
#line 288
undef($memory_7);
#line 289
goto label_188;
#line 289
label_76:
#line 290
$memory_8 = $memory_0->{'dir'};
#line 290
$memory_7 = string::length($memory_8);
#line 290
undef($memory_8);
#line 291
$memory_8 = compiler_priv::get_dir($memory_4);
#line 292
$memory_9 = $memory_2->{'cache_path'};
#line 292
$memory_9 = $memory_9 . $memory_8;
#line 292
$memory_10 = "/";
#line 292
$memory_9 = $memory_9 . $memory_10;
#line 292
undef($memory_10);
#line 292
$memory_9 = $memory_9 . $memory_1;
#line 292
$memory_3 = $memory_9;
#line 292
undef($memory_9);
#line 293
$memory_9 = string::length($memory_8);
#line 293
$memory_9 = c_rt_lib::to_nl($memory_7 < $memory_9);
#line 293
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 293
if (c_rt_lib::check_true($memory_9)) {goto label_102;}
#line 294
$memory_10 = $memory_2->{'cache_path'};
#line 294
$memory_12 = 1;
#line 294
$memory_12 = $memory_7 + $memory_12;
#line 294
$memory_11 = string::substr2($memory_8, $memory_12);
#line 294
undef($memory_12);
#line 294
compiler_priv::mk_path($memory_10, $memory_11);
#line 294
undef($memory_11);
#line 294
undef($memory_10);
#line 295
goto label_102;
#line 295
label_102:
#line 295
undef($memory_9);
#line 296
$memory_10 = ".nl";
#line 296
$memory_10 = $memory_3 . $memory_10;
#line 296
$memory_10 = c_rt_lib::ov_mk_arg('nl', $memory_10);
#line 296
$memory_9 = {src => $memory_4,dst => $memory_10,};
#line 296
undef($memory_10);
#line 296
undef($memory_0);
#line 296
undef($memory_1);
#line 296
undef($memory_2);
#line 296
undef($memory_3);
#line 296
undef($memory_4);
#line 296
undef($memory_5);
#line 296
undef($memory_6);
#line 296
undef($memory_7);
#line 296
undef($memory_8);
#line 296
return $memory_9;
#line 296
undef($memory_9);
#line 296
undef($memory_7);
#line 296
undef($memory_8);
#line 297
goto label_188;
#line 297
label_123:
#line 298
$memory_8 = ".ast";
#line 298
$memory_8 = $memory_3 . $memory_8;
#line 298
$memory_8 = c_rt_lib::ov_mk_arg('ast', $memory_8);
#line 298
$memory_7 = {src => $memory_4,dst => $memory_8,};
#line 298
undef($memory_8);
#line 298
undef($memory_0);
#line 298
undef($memory_1);
#line 298
undef($memory_2);
#line 298
undef($memory_3);
#line 298
undef($memory_4);
#line 298
undef($memory_5);
#line 298
undef($memory_6);
#line 298
return $memory_7;
#line 298
undef($memory_7);
#line 299
goto label_188;
#line 299
label_139:
#line 299
$memory_7 = c_rt_lib::ov_as($memory_5, 'js');
#line 300
$memory_9 = ".js";
#line 300
$memory_9 = $memory_3 . $memory_9;
#line 300
$memory_9 = c_rt_lib::ov_mk_arg('js', $memory_9);
#line 300
$memory_8 = {src => $memory_4,dst => $memory_9,};
#line 300
undef($memory_9);
#line 300
undef($memory_0);
#line 300
undef($memory_1);
#line 300
undef($memory_2);
#line 300
undef($memory_3);
#line 300
undef($memory_4);
#line 300
undef($memory_5);
#line 300
undef($memory_6);
#line 300
undef($memory_7);
#line 300
return $memory_8;
#line 300
undef($memory_8);
#line 300
undef($memory_7);
#line 301
goto label_188;
#line 301
label_158:
#line 302
$memory_8 = "_NL.java";
#line 302
$memory_8 = $memory_3 . $memory_8;
#line 302
$memory_8 = c_rt_lib::ov_mk_arg('java', $memory_8);
#line 302
$memory_7 = {src => $memory_4,dst => $memory_8,};
#line 302
undef($memory_8);
#line 302
undef($memory_0);
#line 302
undef($memory_1);
#line 302
undef($memory_2);
#line 302
undef($memory_3);
#line 302
undef($memory_4);
#line 302
undef($memory_5);
#line 302
undef($memory_6);
#line 302
return $memory_7;
#line 302
undef($memory_7);
#line 303
goto label_188;
#line 303
label_174:
#line 304
$memory_8 = c_rt_lib::ov_mk_none('call_graph');
#line 304
$memory_7 = {src => $memory_4,dst => $memory_8,};
#line 304
undef($memory_8);
#line 304
undef($memory_0);
#line 304
undef($memory_1);
#line 304
undef($memory_2);
#line 304
undef($memory_3);
#line 304
undef($memory_4);
#line 304
undef($memory_5);
#line 304
undef($memory_6);
#line 304
return $memory_7;
#line 304
undef($memory_7);
#line 305
goto label_188;
#line 305
label_188:
#line 305
undef($memory_5);
#line 305
undef($memory_6);
#line 305
undef($memory_3);
#line 305
undef($memory_4);
#line 305
undef($memory_0);
#line 305
undef($memory_1);
#line 305
undef($memory_2);
#line 305
return;
}
sub compiler_priv::get_all_nianio_file($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;$memory_0 = $_[0];
#line 309
$memory_1 = [];
#line 310
$memory_4 = ptd::sim();
#line 310
$memory_3 = ptd::arr($memory_4);
#line 310
undef($memory_4);
#line 310
$memory_4 = c_fe_lib::get_module_files_rec($memory_0);
#line 310
$memory_2 = ptd::ensure($memory_3, $memory_4);
#line 310
undef($memory_4);
#line 310
undef($memory_3);
#line 311
$memory_4 = 0;
#line 311
$memory_5 = 1;
#line 311
$memory_6 = c_rt_lib::array_len($memory_2);
#line 311
label_11:
#line 311
$memory_7 = c_rt_lib::to_nl($memory_4 >= $memory_6);
#line 311
if (c_rt_lib::check_true($memory_7)) {goto label_26;}
#line 311
$memory_3 = $memory_2->[$memory_4];
#line 312
$memory_9 = ".nl";
#line 312
$memory_8 = compiler_priv::has_extension($memory_3, $memory_9);
#line 312
undef($memory_9);
#line 312
$memory_8 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_8));
#line 312
if (c_rt_lib::check_true($memory_8)) {goto label_22;}
#line 312
array::push($memory_1, $memory_3);
#line 312
goto label_22;
#line 312
label_22:
#line 312
undef($memory_8);
#line 313
$memory_4 = $memory_4 + $memory_5;
#line 313
goto label_11;
#line 313
label_26:
#line 313
undef($memory_3);
#line 313
undef($memory_4);
#line 313
undef($memory_5);
#line 313
undef($memory_6);
#line 313
undef($memory_7);
#line 314
undef($memory_0);
#line 314
undef($memory_2);
#line 314
return $memory_1;
#line 314
undef($memory_1);
#line 314
undef($memory_2);
#line 314
undef($memory_0);
#line 314
return;
}
sub compiler_priv::get_files_to_parse($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;my $memory_13;my $memory_14;my $memory_15;my $memory_16;$memory_0 = $_[0];
#line 318
$memory_1 = $memory_0->{'cache_path'};
#line 319
$memory_2 = [];
#line 320
$memory_3 = $memory_0->{'input_path'};
#line 320
$memory_5 = 0;
#line 320
$memory_6 = 1;
#line 320
$memory_7 = c_rt_lib::array_len($memory_3);
#line 320
label_6:
#line 320
$memory_8 = c_rt_lib::to_nl($memory_5 >= $memory_7);
#line 320
if (c_rt_lib::check_true($memory_8)) {goto label_47;}
#line 320
$memory_4 = $memory_3->[$memory_5];
#line 321
$memory_10 = ".nl";
#line 321
$memory_9 = compiler_priv::has_extension($memory_4, $memory_10);
#line 321
undef($memory_10);
#line 321
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 321
if (c_rt_lib::check_true($memory_9)) {goto label_21;}
#line 322
$memory_11 = compiler_priv::get_dir($memory_4);
#line 322
$memory_10 = {dir => $memory_11,file => $memory_4,};
#line 322
undef($memory_11);
#line 322
array::push($memory_2, $memory_10);
#line 322
undef($memory_10);
#line 323
goto label_43;
#line 323
label_21:
#line 324
$memory_10 = compiler_priv::get_all_nianio_file($memory_4);
#line 324
$memory_12 = 0;
#line 324
$memory_13 = 1;
#line 324
$memory_14 = c_rt_lib::array_len($memory_10);
#line 324
label_26:
#line 324
$memory_15 = c_rt_lib::to_nl($memory_12 >= $memory_14);
#line 324
if (c_rt_lib::check_true($memory_15)) {goto label_35;}
#line 324
$memory_11 = $memory_10->[$memory_12];
#line 325
$memory_16 = {dir => $memory_4,file => $memory_11,};
#line 325
array::push($memory_2, $memory_16);
#line 325
undef($memory_16);
#line 326
$memory_12 = $memory_12 + $memory_13;
#line 326
goto label_26;
#line 326
label_35:
#line 326
undef($memory_10);
#line 326
undef($memory_11);
#line 326
undef($memory_12);
#line 326
undef($memory_13);
#line 326
undef($memory_14);
#line 326
undef($memory_15);
#line 327
goto label_43;
#line 327
label_43:
#line 327
undef($memory_9);
#line 328
$memory_5 = $memory_5 + $memory_6;
#line 328
goto label_6;
#line 328
label_47:
#line 328
undef($memory_3);
#line 328
undef($memory_4);
#line 328
undef($memory_5);
#line 328
undef($memory_6);
#line 328
undef($memory_7);
#line 328
undef($memory_8);
#line 329
$memory_4 = $memory_0->{'language'};
#line 329
$memory_3 = compiler_priv::get_out_ext($memory_4);
#line 329
undef($memory_4);
#line 330
$memory_4 = {};
#line 331
$memory_5 = c_fe_lib::get_module_files($memory_1);
#line 331
$memory_6 = c_rt_lib::ov_is($memory_5, 'ok');
#line 331
if (c_rt_lib::check_true($memory_6)) {goto label_66;}
#line 336
$memory_6 = c_rt_lib::ov_is($memory_5, 'err');
#line 336
if (c_rt_lib::check_true($memory_6)) {goto label_104;}
#line 336
$memory_6 = "NOMATCHALERT";
#line 336
$memory_6 = [$memory_6,$memory_5];
#line 336
die(dfile::ssave($memory_6));
#line 331
label_66:
#line 331
$memory_7 = c_rt_lib::ov_as($memory_5, 'ok');
#line 332
$memory_10 = ptd::sim();
#line 332
$memory_9 = ptd::arr($memory_10);
#line 332
undef($memory_10);
#line 332
$memory_8 = ptd::ensure($memory_9, $memory_7);
#line 332
undef($memory_9);
#line 332
$memory_10 = 0;
#line 332
$memory_11 = 1;
#line 332
$memory_12 = c_rt_lib::array_len($memory_8);
#line 332
label_76:
#line 332
$memory_13 = c_rt_lib::to_nl($memory_10 >= $memory_12);
#line 332
if (c_rt_lib::check_true($memory_13)) {goto label_95;}
#line 332
$memory_9 = $memory_8->[$memory_10];
#line 333
$memory_14 = compiler_priv::has_extension($memory_9, $memory_3);
#line 333
$memory_14 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_14));
#line 333
$memory_14 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_14));
#line 333
if (c_rt_lib::check_true($memory_14)) {goto label_87;}
#line 333
undef($memory_14);
#line 333
goto label_92;
#line 333
goto label_87;
#line 333
label_87:
#line 333
undef($memory_14);
#line 334
$memory_14 = compiler_priv::get_module_name($memory_9);
#line 334
hash::set_value($memory_4, $memory_14, $memory_9);
#line 334
undef($memory_14);
#line 334
label_92:
#line 335
$memory_10 = $memory_10 + $memory_11;
#line 335
goto label_76;
#line 335
label_95:
#line 335
undef($memory_8);
#line 335
undef($memory_9);
#line 335
undef($memory_10);
#line 335
undef($memory_11);
#line 335
undef($memory_12);
#line 335
undef($memory_13);
#line 335
undef($memory_7);
#line 336
goto label_119;
#line 336
label_104:
#line 336
$memory_7 = c_rt_lib::ov_as($memory_5, 'err');
#line 337
$memory_8 = {};
#line 337
undef($memory_0);
#line 337
undef($memory_1);
#line 337
undef($memory_2);
#line 337
undef($memory_3);
#line 337
undef($memory_4);
#line 337
undef($memory_5);
#line 337
undef($memory_6);
#line 337
undef($memory_7);
#line 337
return $memory_8;
#line 337
undef($memory_8);
#line 337
undef($memory_7);
#line 338
goto label_119;
#line 338
label_119:
#line 338
undef($memory_5);
#line 338
undef($memory_6);
#line 339
$memory_5 = {};
#line 340
$memory_7 = 0;
#line 340
$memory_8 = 1;
#line 340
$memory_9 = c_rt_lib::array_len($memory_2);
#line 340
label_126:
#line 340
$memory_10 = c_rt_lib::to_nl($memory_7 >= $memory_9);
#line 340
if (c_rt_lib::check_true($memory_10)) {goto label_139;}
#line 340
$memory_6 = $memory_2->[$memory_7];
#line 341
$memory_12 = $memory_6->{'file'};
#line 341
$memory_11 = compiler_priv::get_module_name($memory_12);
#line 341
undef($memory_12);
#line 342
$memory_12 = compiler_priv::mk_path_module($memory_6, $memory_11, $memory_0);
#line 343
hash::set_value($memory_5, $memory_11, $memory_12);
#line 343
undef($memory_11);
#line 343
undef($memory_12);
#line 344
$memory_7 = $memory_7 + $memory_8;
#line 344
goto label_126;
#line 344
label_139:
#line 344
undef($memory_6);
#line 344
undef($memory_7);
#line 344
undef($memory_8);
#line 344
undef($memory_9);
#line 344
undef($memory_10);
#line 345
undef($memory_0);
#line 345
undef($memory_1);
#line 345
undef($memory_2);
#line 345
undef($memory_3);
#line 345
undef($memory_4);
#line 345
return $memory_5;
#line 345
undef($memory_1);
#line 345
undef($memory_2);
#line 345
undef($memory_3);
#line 345
undef($memory_4);
#line 345
undef($memory_5);
#line 345
undef($memory_0);
#line 345
return;
}
sub compiler_priv::parse_module($$$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;$memory_0 = $_[0];$memory_1 = $_[1];$memory_2 = $_[2];Scalar::Util::weaken($_[2]) if ref($_[2]);
#line 352
$memory_3 = "processing ";
#line 352
$memory_3 = $memory_3 . $memory_0;
#line 352
$memory_4 = "...";
#line 352
$memory_3 = $memory_3 . $memory_4;
#line 352
undef($memory_4);
#line 352
c_fe_lib::print($memory_3);
#line 352
undef($memory_3);
#line 353
$memory_8 = ptd::sim();
#line 353
$memory_9 = ptd::sim();
#line 353
$memory_7 = {ok => $memory_8,err => $memory_9,};
#line 353
undef($memory_8);
#line 353
undef($memory_9);
#line 353
$memory_6 = ptd::var($memory_7);
#line 353
undef($memory_7);
#line 353
$memory_7 = c_fe_lib::file_to_string($memory_1);
#line 353
$memory_5 = ptd::ensure($memory_6, $memory_7);
#line 353
undef($memory_7);
#line 353
undef($memory_6);
#line 353
$memory_4 = c_rt_lib::ov_is($memory_5, 'ok');
#line 353
if (c_rt_lib::check_true($memory_4)) {goto label_25;}
#line 353
undef($memory_0);
#line 353
undef($memory_1);
#line 353
undef($memory_3);
#line 353
undef($memory_4);
#line 353
$_[2] = $memory_2;return $memory_5;
#line 353
label_25:
#line 353
$memory_3 = c_rt_lib::ov_as($memory_5, 'ok');
#line 353
undef($memory_4);
#line 353
undef($memory_5);
#line 354
$memory_4 = nparser::sparse($memory_3, $memory_0);
#line 355
$memory_5 = c_rt_lib::ov_is($memory_4, 'ok');
#line 355
if (c_rt_lib::check_true($memory_5)) {goto label_37;}
#line 362
$memory_5 = c_rt_lib::ov_is($memory_4, 'error');
#line 362
if (c_rt_lib::check_true($memory_5)) {goto label_101;}
#line 362
$memory_5 = "NOMATCHALERT";
#line 362
$memory_5 = [$memory_5,$memory_4];
#line 362
die(dfile::ssave($memory_5));
#line 355
label_37:
#line 355
$memory_6 = c_rt_lib::ov_as($memory_4, 'ok');
#line 356
$memory_7 = {};
#line 357
$memory_9 = c_rt_lib::to_nl(0);
#line 357
$memory_8 = module_checker::check_module($memory_6, $memory_9, $memory_7);
#line 357
undef($memory_9);
#line 358
$memory_9 = "module_warnings";
#line 358
$memory_9 = c_rt_lib::get_ref_hash($memory_2, $memory_9);
#line 358
$memory_10 = $memory_8->{'warnings'};
#line 358
hash::set_value($memory_9, $memory_0, $memory_10);
#line 358
undef($memory_10);
#line 358
$memory_10 = "module_warnings";
#line 358
c_rt_lib::set_ref_hash($memory_2, $memory_10, $memory_9);
#line 358
undef($memory_10);
#line 358
undef($memory_9);
#line 359
$memory_9 = "module_errors";
#line 359
$memory_9 = c_rt_lib::get_ref_hash($memory_2, $memory_9);
#line 359
$memory_10 = $memory_8->{'errors'};
#line 359
hash::set_value($memory_9, $memory_0, $memory_10);
#line 359
undef($memory_10);
#line 359
$memory_10 = "module_errors";
#line 359
c_rt_lib::set_ref_hash($memory_2, $memory_10, $memory_9);
#line 359
undef($memory_10);
#line 359
undef($memory_9);
#line 360
$memory_10 = $memory_8->{'errors'};
#line 360
$memory_9 = array::len($memory_10);
#line 360
undef($memory_10);
#line 360
$memory_10 = 0;
#line 360
$memory_9 = c_rt_lib::to_nl($memory_9 == $memory_10);
#line 360
undef($memory_10);
#line 360
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 360
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 360
if (c_rt_lib::check_true($memory_9)) {goto label_84;}
#line 360
$memory_10 = "";
#line 360
$memory_10 = c_rt_lib::ov_mk_arg('err', $memory_10);
#line 360
undef($memory_0);
#line 360
undef($memory_1);
#line 360
undef($memory_3);
#line 360
undef($memory_4);
#line 360
undef($memory_5);
#line 360
undef($memory_6);
#line 360
undef($memory_7);
#line 360
undef($memory_8);
#line 360
undef($memory_9);
#line 360
$_[2] = $memory_2;return $memory_10;
#line 360
undef($memory_10);
#line 360
goto label_84;
#line 360
label_84:
#line 360
undef($memory_9);
#line 361
$memory_9 = c_rt_lib::ov_mk_arg('ok', $memory_6);
#line 361
undef($memory_0);
#line 361
undef($memory_1);
#line 361
undef($memory_3);
#line 361
undef($memory_4);
#line 361
undef($memory_5);
#line 361
undef($memory_6);
#line 361
undef($memory_7);
#line 361
undef($memory_8);
#line 361
$_[2] = $memory_2;return $memory_9;
#line 361
undef($memory_9);
#line 361
undef($memory_7);
#line 361
undef($memory_8);
#line 361
undef($memory_6);
#line 362
goto label_131;
#line 362
label_101:
#line 362
$memory_6 = c_rt_lib::ov_as($memory_4, 'error');
#line 363
$memory_7 = "module_warnings";
#line 363
$memory_7 = c_rt_lib::get_ref_hash($memory_2, $memory_7);
#line 363
$memory_8 = [];
#line 363
hash::set_value($memory_7, $memory_0, $memory_8);
#line 363
undef($memory_8);
#line 363
$memory_8 = "module_warnings";
#line 363
c_rt_lib::set_ref_hash($memory_2, $memory_8, $memory_7);
#line 363
undef($memory_8);
#line 363
undef($memory_7);
#line 364
$memory_7 = "module_errors";
#line 364
$memory_7 = c_rt_lib::get_ref_hash($memory_2, $memory_7);
#line 364
hash::set_value($memory_7, $memory_0, $memory_6);
#line 364
$memory_8 = "module_errors";
#line 364
c_rt_lib::set_ref_hash($memory_2, $memory_8, $memory_7);
#line 364
undef($memory_8);
#line 364
undef($memory_7);
#line 365
$memory_7 = "";
#line 365
$memory_7 = c_rt_lib::ov_mk_arg('err', $memory_7);
#line 365
undef($memory_0);
#line 365
undef($memory_1);
#line 365
undef($memory_3);
#line 365
undef($memory_4);
#line 365
undef($memory_5);
#line 365
undef($memory_6);
#line 365
$_[2] = $memory_2;return $memory_7;
#line 365
undef($memory_7);
#line 365
undef($memory_6);
#line 366
goto label_131;
#line 366
label_131:
#line 366
undef($memory_5);
#line 366
undef($memory_3);
#line 366
undef($memory_4);
#line 366
undef($memory_0);
#line 366
undef($memory_1);
#line 366
$_[2] = $memory_2;return;
$_[2] = $memory_2;}
sub compiler_priv::get_mathematical_func($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;$memory_0 = $_[0];
#line 370
$memory_1 = {};
#line 371
$memory_3 = $memory_0->{'math_fun'};
#line 371
$memory_2 = c_fe_lib::file_to_string($memory_3);
#line 371
undef($memory_3);
#line 371
$memory_3 = c_rt_lib::ov_is($memory_2, 'ok');
#line 371
if (c_rt_lib::check_true($memory_3)) {goto label_11;}
#line 384
$memory_3 = c_rt_lib::ov_is($memory_2, 'err');
#line 384
if (c_rt_lib::check_true($memory_3)) {goto label_62;}
#line 384
$memory_3 = "NOMATCHALERT";
#line 384
$memory_3 = [$memory_3,$memory_2];
#line 384
die(dfile::ssave($memory_3));
#line 371
label_11:
#line 371
$memory_4 = c_rt_lib::ov_as($memory_2, 'ok');
#line 372
$memory_5 = "list of mathematical functions loaded";
#line 372
c_fe_lib::print($memory_5);
#line 372
undef($memory_5);
#line 373
$memory_5 = dfile::try_sload($memory_4);
#line 374
$memory_6 = [];
#line 375
$memory_7 = c_rt_lib::ov_is($memory_5, 'ok');
#line 375
if (c_rt_lib::check_true($memory_7)) {goto label_25;}
#line 377
$memory_7 = c_rt_lib::ov_is($memory_5, 'err');
#line 377
if (c_rt_lib::check_true($memory_7)) {goto label_30;}
#line 377
$memory_7 = "NOMATCHALERT";
#line 377
$memory_7 = [$memory_7,$memory_5];
#line 377
die(dfile::ssave($memory_7));
#line 375
label_25:
#line 375
$memory_8 = c_rt_lib::ov_as($memory_5, 'ok');
#line 376
$memory_6 = $memory_8;
#line 376
undef($memory_8);
#line 377
goto label_38;
#line 377
label_30:
#line 377
$memory_8 = c_rt_lib::ov_as($memory_5, 'err');
#line 378
$memory_9 = "could not parse list of mathematical functions:";
#line 378
c_fe_lib::print($memory_9);
#line 378
undef($memory_9);
#line 379
c_fe_lib::print($memory_8);
#line 379
undef($memory_8);
#line 380
goto label_38;
#line 380
label_38:
#line 380
undef($memory_7);
#line 381
$memory_8 = 0;
#line 381
$memory_9 = 1;
#line 381
$memory_10 = c_rt_lib::array_len($memory_6);
#line 381
label_43:
#line 381
$memory_11 = c_rt_lib::to_nl($memory_8 >= $memory_10);
#line 381
if (c_rt_lib::check_true($memory_11)) {goto label_52;}
#line 381
$memory_7 = $memory_6->[$memory_8];
#line 382
$memory_12 = 1;
#line 382
hash::set_value($memory_1, $memory_7, $memory_12);
#line 382
undef($memory_12);
#line 383
$memory_8 = $memory_8 + $memory_9;
#line 383
goto label_43;
#line 383
label_52:
#line 383
undef($memory_7);
#line 383
undef($memory_8);
#line 383
undef($memory_9);
#line 383
undef($memory_10);
#line 383
undef($memory_11);
#line 383
undef($memory_5);
#line 383
undef($memory_6);
#line 383
undef($memory_4);
#line 384
goto label_69;
#line 384
label_62:
#line 384
$memory_4 = c_rt_lib::ov_as($memory_2, 'err');
#line 385
$memory_5 = "NOT LOAD: list of mathematical functions";
#line 385
c_fe_lib::print($memory_5);
#line 385
undef($memory_5);
#line 385
undef($memory_4);
#line 386
goto label_69;
#line 386
label_69:
#line 386
undef($memory_2);
#line 386
undef($memory_3);
#line 387
undef($memory_0);
#line 387
return $memory_1;
#line 387
undef($memory_1);
#line 387
undef($memory_0);
#line 387
return;
}
sub compiler_priv::compile_ide($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;my $memory_13;my $memory_14;my $memory_15;my $memory_16;my $memory_17;my $memory_18;my $memory_19;my $memory_20;my $memory_21;$memory_0 = $_[0];
#line 391
$memory_1 = {};
#line 392
$memory_2 = {};
#line 393
$memory_3 = {};
#line 394
$memory_4 = {};
#line 396
$memory_6 = {};
#line 397
$memory_7 = {};
#line 398
$memory_8 = {};
#line 399
$memory_9 = {};
#line 400
$memory_10 = c_rt_lib::ov_mk_none('ok');
#line 400
$memory_5 = {module_errors => $memory_6,module_warnings => $memory_7,type_errors => $memory_8,type_warnings => $memory_9,loop_error => $memory_10,};
#line 400
undef($memory_6);
#line 400
undef($memory_7);
#line 400
undef($memory_8);
#line 400
undef($memory_9);
#line 400
undef($memory_10);
#line 402
$memory_7 = compiler_priv::get_mathematical_func($memory_0);
#line 402
$memory_8 = $memory_0->{'optimization'};
#line 402
$memory_6 = post_processing::init($memory_7, $memory_8);
#line 402
undef($memory_8);
#line 402
undef($memory_7);
#line 403
$memory_7 = {};
#line 404
$memory_9 = $memory_0->{'language'};
#line 404
$memory_8 = compiler_priv::get_generator_state($memory_9);
#line 404
undef($memory_9);
#line 405
label_24:
#line 406
$memory_9 = {};
#line 406
$memory_10 = $memory_9;
#line 406
if (c_rt_lib::get_hashcount($memory_5) > 1) {$memory_5 = {%{$memory_5}};}$memory_5->{'type_errors'} = $memory_10;
#line 406
undef($memory_9);
#line 406
undef($memory_10);
#line 407
$memory_9 = {};
#line 407
$memory_10 = $memory_9;
#line 407
if (c_rt_lib::get_hashcount($memory_5) > 1) {$memory_5 = {%{$memory_5}};}$memory_5->{'type_warnings'} = $memory_10;
#line 407
undef($memory_9);
#line 407
undef($memory_10);
#line 408
$memory_9 = c_rt_lib::ov_mk_none('ok');
#line 408
$memory_10 = $memory_9;
#line 408
if (c_rt_lib::get_hashcount($memory_5) > 1) {$memory_5 = {%{$memory_5}};}$memory_5->{'loop_error'} = $memory_10;
#line 408
undef($memory_9);
#line 408
undef($memory_10);
#line 409
$memory_9 = compiler_priv::get_files_to_parse($memory_0);
#line 410
$memory_10 = 0;
#line 411
$memory_13 = c_rt_lib::init_iter($memory_9);
#line 411
label_43:
#line 411
$memory_11 = c_rt_lib::is_end_hash($memory_13);
#line 411
if (c_rt_lib::check_true($memory_11)) {goto label_94;}
#line 411
$memory_11 = c_rt_lib::get_key_iter($memory_13);
#line 411
$memory_12 = c_rt_lib::hash_get_value($memory_9, $memory_11);
#line 412
$memory_15 = $memory_12->{'src'};
#line 412
$memory_14 = c_fe_lib::get_modif_time($memory_15);
#line 412
undef($memory_15);
#line 413
$memory_15 = $memory_14;
#line 413
$memory_15 = c_rt_lib::ov_is($memory_15, 'err');
#line 413
$memory_15 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_15));
#line 413
if (c_rt_lib::check_true($memory_15)) {goto label_59;}
#line 413
undef($memory_14);
#line 413
undef($memory_15);
#line 413
goto label_91;
#line 413
goto label_59;
#line 413
label_59:
#line 413
undef($memory_15);
#line 414
$memory_15 = $memory_14;
#line 414
$memory_15 = c_rt_lib::ov_as($memory_15, 'ok');
#line 414
$memory_14 = $memory_15;
#line 414
undef($memory_15);
#line 415
$memory_15 = hash::has_key($memory_1, $memory_11);
#line 415
$memory_15 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_15));
#line 415
if (c_rt_lib::check_true($memory_15)) {goto label_83;}
#line 416
$memory_16 = hash::get_value($memory_1, $memory_11);
#line 417
$memory_17 = c_rt_lib::to_nl($memory_14 > $memory_16);
#line 417
$memory_17 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_17));
#line 417
$memory_17 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_17));
#line 417
if (c_rt_lib::check_true($memory_17)) {goto label_79;}
#line 417
undef($memory_14);
#line 417
undef($memory_15);
#line 417
undef($memory_16);
#line 417
undef($memory_17);
#line 417
goto label_91;
#line 417
goto label_79;
#line 417
label_79:
#line 417
undef($memory_17);
#line 417
undef($memory_16);
#line 418
goto label_83;
#line 418
label_83:
#line 418
undef($memory_15);
#line 419
hash::set_value($memory_1, $memory_11, $memory_14);
#line 420
hash::set_value($memory_4, $memory_11, $memory_12);
#line 421
$memory_15 = 1;
#line 421
$memory_10 = $memory_10 + $memory_15;
#line 421
undef($memory_15);
#line 421
undef($memory_14);
#line 421
label_91:
#line 422
$memory_13 = c_rt_lib::next_iter($memory_13);
#line 422
goto label_43;
#line 422
label_94:
#line 422
undef($memory_11);
#line 422
undef($memory_12);
#line 422
undef($memory_13);
#line 423
$memory_13 = c_rt_lib::init_iter($memory_7);
#line 423
label_99:
#line 423
$memory_11 = c_rt_lib::is_end_hash($memory_13);
#line 423
if (c_rt_lib::check_true($memory_11)) {goto label_143;}
#line 423
$memory_11 = c_rt_lib::get_key_iter($memory_13);
#line 423
$memory_12 = c_rt_lib::hash_get_value($memory_7, $memory_11);
#line 424
$memory_14 = hash::has_key($memory_9, $memory_11);
#line 424
$memory_14 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_14));
#line 424
$memory_14 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_14));
#line 424
if (c_rt_lib::check_true($memory_14)) {goto label_139;}
#line 425
$memory_15 = 1;
#line 425
$memory_10 = $memory_10 + $memory_15;
#line 425
undef($memory_15);
#line 426
$memory_15 = "module_errors";
#line 426
$memory_15 = c_rt_lib::get_ref_hash($memory_5, $memory_15);
#line 426
hash::delete($memory_15, $memory_11);
#line 426
$memory_16 = "module_errors";
#line 426
c_rt_lib::set_ref_hash($memory_5, $memory_16, $memory_15);
#line 426
undef($memory_16);
#line 426
undef($memory_15);
#line 427
$memory_15 = "module_warnings";
#line 427
$memory_15 = c_rt_lib::get_ref_hash($memory_5, $memory_15);
#line 427
hash::delete($memory_15, $memory_11);
#line 427
$memory_16 = "module_warnings";
#line 427
c_rt_lib::set_ref_hash($memory_5, $memory_16, $memory_15);
#line 427
undef($memory_16);
#line 427
undef($memory_15);
#line 428
hash::delete($memory_2, $memory_11);
#line 429
hash::delete($memory_1, $memory_11);
#line 430
hash::delete($memory_4, $memory_11);
#line 431
hash::delete($memory_3, $memory_11);
#line 432
post_processing::clear_module_from_state($memory_6, $memory_11);
#line 433
$memory_15 = $memory_0->{'language'};
#line 433
$memory_15 = c_rt_lib::ov_is($memory_15, 'c');
#line 433
$memory_15 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_15));
#line 433
if (c_rt_lib::check_true($memory_15)) {goto label_136;}
#line 434
generator_c::clear_module_from_state($memory_8, $memory_11);
#line 435
goto label_136;
#line 435
label_136:
#line 435
undef($memory_15);
#line 436
goto label_139;
#line 436
label_139:
#line 436
undef($memory_14);
#line 437
$memory_13 = c_rt_lib::next_iter($memory_13);
#line 437
goto label_99;
#line 437
label_143:
#line 437
undef($memory_11);
#line 437
undef($memory_12);
#line 437
undef($memory_13);
#line 438
$memory_7 = $memory_9;
#line 439
$memory_11 = 0;
#line 439
$memory_11 = c_rt_lib::to_nl($memory_10 == $memory_11);
#line 439
$memory_11 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_11));
#line 439
if (c_rt_lib::check_true($memory_11)) {goto label_160;}
#line 440
$memory_12 = 1;
#line 440
c_fe_lib::sleep($memory_12);
#line 440
undef($memory_12);
#line 441
undef($memory_9);
#line 441
undef($memory_10);
#line 441
undef($memory_11);
#line 441
goto label_24;
#line 442
goto label_160;
#line 442
label_160:
#line 442
undef($memory_11);
#line 443
$memory_11 = {};
#line 444
$memory_14 = c_rt_lib::init_iter($memory_4);
#line 444
label_164:
#line 444
$memory_12 = c_rt_lib::is_end_hash($memory_14);
#line 444
if (c_rt_lib::check_true($memory_12)) {goto label_195;}
#line 444
$memory_12 = c_rt_lib::get_key_iter($memory_14);
#line 444
$memory_13 = c_rt_lib::hash_get_value($memory_4, $memory_12);
#line 445
$memory_16 = $memory_13->{'src'};
#line 445
$memory_15 = compiler_priv::parse_module($memory_12, $memory_16, $memory_5);
#line 445
undef($memory_16);
#line 445
$memory_16 = c_rt_lib::ov_is($memory_15, 'ok');
#line 445
if (c_rt_lib::check_true($memory_16)) {goto label_179;}
#line 448
$memory_16 = c_rt_lib::ov_is($memory_15, 'err');
#line 448
if (c_rt_lib::check_true($memory_16)) {goto label_185;}
#line 448
$memory_16 = "NOMATCHALERT";
#line 448
$memory_16 = [$memory_16,$memory_15];
#line 448
die(dfile::ssave($memory_16));
#line 445
label_179:
#line 445
$memory_17 = c_rt_lib::ov_as($memory_15, 'ok');
#line 446
hash::set_value($memory_2, $memory_12, $memory_17);
#line 447
hash::set_value($memory_3, $memory_12, $memory_17);
#line 447
undef($memory_17);
#line 448
goto label_190;
#line 448
label_185:
#line 448
$memory_17 = c_rt_lib::ov_as($memory_15, 'err');
#line 449
hash::set_value($memory_11, $memory_12, $memory_13);
#line 449
undef($memory_17);
#line 450
goto label_190;
#line 450
label_190:
#line 450
undef($memory_15);
#line 450
undef($memory_16);
#line 451
$memory_14 = c_rt_lib::next_iter($memory_14);
#line 451
goto label_164;
#line 451
label_195:
#line 451
undef($memory_12);
#line 451
undef($memory_13);
#line 451
undef($memory_14);
#line 452
$memory_4 = $memory_11;
#line 453
$memory_12 = hash::size($memory_4);
#line 453
$memory_13 = 0;
#line 453
$memory_12 = c_rt_lib::to_nl($memory_12 > $memory_13);
#line 453
undef($memory_13);
#line 453
$memory_12 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_12));
#line 453
if (c_rt_lib::check_true($memory_12)) {goto label_228;}
#line 454
compiler_priv::show_and_count_errors($memory_5, $memory_0, $memory_9);
#line 455
$memory_13 = string::lf();
#line 455
$memory_14 = "ERROR: while parsing ";
#line 455
$memory_13 = $memory_13 . $memory_14;
#line 455
undef($memory_14);
#line 455
$memory_14 = hash::size($memory_4);
#line 455
$memory_13 = $memory_13 . $memory_14;
#line 455
undef($memory_14);
#line 455
$memory_14 = " modules";
#line 455
$memory_13 = $memory_13 . $memory_14;
#line 455
undef($memory_14);
#line 455
c_fe_lib::print($memory_13);
#line 455
undef($memory_13);
#line 456
$memory_13 = "############################################################";
#line 456
c_fe_lib::print($memory_13);
#line 456
undef($memory_13);
#line 457
undef($memory_9);
#line 457
undef($memory_10);
#line 457
undef($memory_11);
#line 457
undef($memory_12);
#line 457
goto label_24;
#line 458
goto label_228;
#line 458
label_228:
#line 458
undef($memory_12);
#line 459
$memory_12 = $memory_0->{'deref'};
#line 459
$memory_13 = $memory_0->{'check_public_fun'};
#line 459
compiler_priv::check_modules($memory_2, $memory_5, $memory_12, $memory_13);
#line 459
undef($memory_13);
#line 459
undef($memory_12);
#line 460
$memory_12 = compiler_priv::show_and_count_errors($memory_5, $memory_0, $memory_9);
#line 460
$memory_13 = 0;
#line 460
$memory_12 = c_rt_lib::to_nl($memory_12 > $memory_13);
#line 460
undef($memory_13);
#line 460
$memory_12 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_12));
#line 460
if (c_rt_lib::check_true($memory_12)) {goto label_250;}
#line 461
$memory_13 = "############################################################";
#line 461
c_fe_lib::print($memory_13);
#line 461
undef($memory_13);
#line 462
undef($memory_9);
#line 462
undef($memory_10);
#line 462
undef($memory_11);
#line 462
undef($memory_12);
#line 462
goto label_24;
#line 463
goto label_250;
#line 463
label_250:
#line 463
undef($memory_12);
#line 464
$memory_12 = $memory_0->{'language'};
#line 464
$memory_12 = c_rt_lib::ov_is($memory_12, 'ast');
#line 464
if (c_rt_lib::check_true($memory_12)) {goto label_257;}
#line 464
$memory_12 = $memory_0->{'language'};
#line 464
$memory_12 = c_rt_lib::ov_is($memory_12, 'nl');
#line 464
label_257:
#line 464
$memory_12 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_12));
#line 464
$memory_12 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_12));
#line 464
if (c_rt_lib::check_true($memory_12)) {goto label_308;}
#line 465
$memory_13 = "search constants...";
#line 465
c_fe_lib::print($memory_13);
#line 465
undef($memory_13);
#line 466
$memory_13 = {};
#line 467
$memory_14 = compiler_priv::translate($memory_3, $memory_6);
#line 468
$memory_16 = $memory_0->{'cache_path'};
#line 468
$memory_17 = $memory_0->{'language'};
#line 468
$memory_15 = compiler_priv::generate_modules_to_files($memory_14, $memory_9, $memory_16, $memory_8, $memory_17);
#line 468
undef($memory_17);
#line 468
undef($memory_16);
#line 469
$memory_16 = c_rt_lib::ov_is($memory_15, 'err');
#line 469
if (c_rt_lib::check_true($memory_16)) {goto label_278;}
#line 473
$memory_16 = c_rt_lib::ov_is($memory_15, 'ok');
#line 473
if (c_rt_lib::check_true($memory_16)) {goto label_297;}
#line 473
$memory_16 = "NOMATCHALERT";
#line 473
$memory_16 = [$memory_16,$memory_15];
#line 473
die(dfile::ssave($memory_16));
#line 469
label_278:
#line 469
$memory_17 = c_rt_lib::ov_as($memory_15, 'err');
#line 470
$memory_20 = c_rt_lib::init_iter($memory_17);
#line 470
label_281:
#line 470
$memory_18 = c_rt_lib::is_end_hash($memory_20);
#line 470
if (c_rt_lib::check_true($memory_18)) {goto label_291;}
#line 470
$memory_18 = c_rt_lib::get_key_iter($memory_20);
#line 470
$memory_19 = c_rt_lib::hash_get_value($memory_17, $memory_18);
#line 471
$memory_21 = hash::get_value($memory_2, $memory_18);
#line 471
hash::set_value($memory_13, $memory_18, $memory_21);
#line 471
undef($memory_21);
#line 472
$memory_20 = c_rt_lib::next_iter($memory_20);
#line 472
goto label_281;
#line 472
label_291:
#line 472
undef($memory_18);
#line 472
undef($memory_19);
#line 472
undef($memory_20);
#line 472
undef($memory_17);
#line 473
goto label_301;
#line 473
label_297:
#line 473
$memory_17 = c_rt_lib::ov_as($memory_15, 'ok');
#line 473
undef($memory_17);
#line 474
goto label_301;
#line 474
label_301:
#line 474
undef($memory_15);
#line 474
undef($memory_16);
#line 475
$memory_3 = $memory_13;
#line 475
undef($memory_13);
#line 475
undef($memory_14);
#line 476
goto label_356;
#line 476
label_308:
#line 477
$memory_13 = {};
#line 478
$memory_16 = c_rt_lib::init_iter($memory_3);
#line 478
label_311:
#line 478
$memory_14 = c_rt_lib::is_end_hash($memory_16);
#line 478
if (c_rt_lib::check_true($memory_14)) {goto label_349;}
#line 478
$memory_14 = c_rt_lib::get_key_iter($memory_16);
#line 478
$memory_15 = c_rt_lib::hash_get_value($memory_3, $memory_14);
#line 479
$memory_17 = "saving file: ";
#line 479
$memory_17 = $memory_17 . $memory_14;
#line 479
c_fe_lib::print($memory_17);
#line 479
undef($memory_17);
#line 480
$memory_18 = hash::get_value($memory_9, $memory_14);
#line 480
$memory_18 = $memory_18->{'dst'};
#line 480
$memory_17 = compiler_priv::save_module_to_file($memory_15, $memory_18);
#line 480
undef($memory_18);
#line 480
$memory_18 = c_rt_lib::ov_is($memory_17, 'err');
#line 480
if (c_rt_lib::check_true($memory_18)) {goto label_331;}
#line 483
$memory_18 = c_rt_lib::ov_is($memory_17, 'ok');
#line 483
if (c_rt_lib::check_true($memory_18)) {goto label_340;}
#line 483
$memory_18 = "NOMATCHALERT";
#line 483
$memory_18 = [$memory_18,$memory_17];
#line 483
die(dfile::ssave($memory_18));
#line 480
label_331:
#line 480
$memory_19 = c_rt_lib::ov_as($memory_17, 'err');
#line 481
$memory_20 = "ERROR: ";
#line 481
$memory_20 = $memory_20 . $memory_19;
#line 481
c_fe_lib::print($memory_20);
#line 481
undef($memory_20);
#line 482
hash::set_value($memory_13, $memory_14, $memory_15);
#line 482
undef($memory_19);
#line 483
goto label_344;
#line 483
label_340:
#line 483
$memory_19 = c_rt_lib::ov_as($memory_17, 'ok');
#line 483
undef($memory_19);
#line 484
goto label_344;
#line 484
label_344:
#line 484
undef($memory_17);
#line 484
undef($memory_18);
#line 485
$memory_16 = c_rt_lib::next_iter($memory_16);
#line 485
goto label_311;
#line 485
label_349:
#line 485
undef($memory_14);
#line 485
undef($memory_15);
#line 485
undef($memory_16);
#line 486
$memory_3 = $memory_13;
#line 486
undef($memory_13);
#line 487
goto label_356;
#line 487
label_356:
#line 487
undef($memory_12);
#line 488
$memory_12 = hash::size($memory_3);
#line 488
$memory_13 = 0;
#line 488
$memory_12 = c_rt_lib::to_nl($memory_12 > $memory_13);
#line 488
undef($memory_13);
#line 488
$memory_12 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_12));
#line 488
if (c_rt_lib::check_true($memory_12)) {goto label_380;}
#line 489
$memory_13 = "Can not save ";
#line 489
$memory_14 = hash::size($memory_3);
#line 489
$memory_13 = $memory_13 . $memory_14;
#line 489
undef($memory_14);
#line 489
$memory_14 = " files. ";
#line 489
$memory_13 = $memory_13 . $memory_14;
#line 489
undef($memory_14);
#line 490
$memory_14 = string::lf();
#line 490
$memory_15 = "ERROR: ";
#line 490
$memory_14 = $memory_14 . $memory_15;
#line 490
undef($memory_15);
#line 490
$memory_14 = $memory_14 . $memory_13;
#line 490
c_fe_lib::print($memory_14);
#line 490
undef($memory_14);
#line 490
undef($memory_13);
#line 491
goto label_399;
#line 491
label_380:
#line 492
$memory_13 = $memory_0->{'mode'};
#line 492
$memory_13 = c_rt_lib::ov_is($memory_13, 'idex');
#line 492
$memory_13 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_13));
#line 492
if (c_rt_lib::check_true($memory_13)) {goto label_390;}
#line 492
$memory_14 = $memory_0->{'mode'};
#line 492
$memory_14 = c_rt_lib::ov_as($memory_14, 'idex');
#line 492
c_fe_lib::exec_cmd($memory_14);
#line 492
undef($memory_14);
#line 492
goto label_390;
#line 492
label_390:
#line 492
undef($memory_13);
#line 493
$memory_13 = string::lf();
#line 493
$memory_14 = "OK: compile, check types and save changes without errors";
#line 493
$memory_13 = $memory_13 . $memory_14;
#line 493
undef($memory_14);
#line 493
c_fe_lib::print($memory_13);
#line 493
undef($memory_13);
#line 494
goto label_399;
#line 494
label_399:
#line 494
undef($memory_12);
#line 495
$memory_12 = "############################################################";
#line 495
c_fe_lib::print($memory_12);
#line 495
undef($memory_12);
#line 495
undef($memory_9);
#line 495
undef($memory_10);
#line 495
undef($memory_11);
#line 405
goto label_24;
#line 405
undef($memory_1);
#line 405
undef($memory_2);
#line 405
undef($memory_3);
#line 405
undef($memory_4);
#line 405
undef($memory_5);
#line 405
undef($memory_6);
#line 405
undef($memory_7);
#line 405
undef($memory_8);
#line 405
undef($memory_0);
#line 405
return;
}
sub compiler_priv::compile_strict_file($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;$memory_0 = $_[0];
#line 500
$memory_1 = {};
#line 502
$memory_3 = {};
#line 503
$memory_4 = {};
#line 504
$memory_5 = {};
#line 505
$memory_6 = {};
#line 506
$memory_7 = c_rt_lib::ov_mk_none('ok');
#line 506
$memory_2 = {module_errors => $memory_3,module_warnings => $memory_4,type_errors => $memory_5,type_warnings => $memory_6,loop_error => $memory_7,};
#line 506
undef($memory_3);
#line 506
undef($memory_4);
#line 506
undef($memory_5);
#line 506
undef($memory_6);
#line 506
undef($memory_7);
#line 509
$memory_3 = "module parsing";
#line 509
profile::begin($memory_3);
#line 509
undef($memory_3);
#line 510
$memory_3 = 0;
#line 511
$memory_4 = compiler_priv::get_files_to_parse($memory_0);
#line 512
$memory_7 = c_rt_lib::init_iter($memory_4);
#line 512
label_18:
#line 512
$memory_5 = c_rt_lib::is_end_hash($memory_7);
#line 512
if (c_rt_lib::check_true($memory_5)) {goto label_50;}
#line 512
$memory_5 = c_rt_lib::get_key_iter($memory_7);
#line 512
$memory_6 = c_rt_lib::hash_get_value($memory_4, $memory_5);
#line 513
$memory_9 = $memory_6->{'src'};
#line 513
$memory_8 = compiler_priv::parse_module($memory_5, $memory_9, $memory_2);
#line 513
undef($memory_9);
#line 513
$memory_9 = c_rt_lib::ov_is($memory_8, 'ok');
#line 513
if (c_rt_lib::check_true($memory_9)) {goto label_33;}
#line 515
$memory_9 = c_rt_lib::ov_is($memory_8, 'err');
#line 515
if (c_rt_lib::check_true($memory_9)) {goto label_38;}
#line 515
$memory_9 = "NOMATCHALERT";
#line 515
$memory_9 = [$memory_9,$memory_8];
#line 515
die(dfile::ssave($memory_9));
#line 513
label_33:
#line 513
$memory_10 = c_rt_lib::ov_as($memory_8, 'ok');
#line 514
hash::set_value($memory_1, $memory_5, $memory_10);
#line 514
undef($memory_10);
#line 515
goto label_45;
#line 515
label_38:
#line 515
$memory_10 = c_rt_lib::ov_as($memory_8, 'err');
#line 516
$memory_11 = 1;
#line 516
$memory_3 = $memory_3 + $memory_11;
#line 516
undef($memory_11);
#line 516
undef($memory_10);
#line 517
goto label_45;
#line 517
label_45:
#line 517
undef($memory_8);
#line 517
undef($memory_9);
#line 518
$memory_7 = c_rt_lib::next_iter($memory_7);
#line 518
goto label_18;
#line 518
label_50:
#line 518
undef($memory_5);
#line 518
undef($memory_6);
#line 518
undef($memory_7);
#line 519
$memory_5 = "module parsing";
#line 519
profile::end($memory_5);
#line 519
undef($memory_5);
#line 520
$memory_5 = 0;
#line 520
$memory_5 = c_rt_lib::to_nl($memory_3 != $memory_5);
#line 520
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 520
if (c_rt_lib::check_true($memory_5)) {goto label_72;}
#line 521
compiler_priv::show_and_count_errors($memory_2, $memory_0, $memory_4);
#line 522
$memory_6 = 1;
#line 522
undef($memory_0);
#line 522
undef($memory_1);
#line 522
undef($memory_2);
#line 522
undef($memory_3);
#line 522
undef($memory_4);
#line 522
undef($memory_5);
#line 522
return $memory_6;
#line 522
undef($memory_6);
#line 523
goto label_72;
#line 523
label_72:
#line 523
undef($memory_5);
#line 525
$memory_5 = "module checking";
#line 525
profile::begin($memory_5);
#line 525
undef($memory_5);
#line 526
$memory_5 = $memory_0->{'deref'};
#line 526
$memory_6 = $memory_0->{'check_public_fun'};
#line 526
compiler_priv::check_modules($memory_1, $memory_2, $memory_5, $memory_6);
#line 526
undef($memory_6);
#line 526
undef($memory_5);
#line 527
$memory_5 = "module_checking";
#line 527
profile::end($memory_5);
#line 527
undef($memory_5);
#line 528
$memory_5 = compiler_priv::show_and_count_errors($memory_2, $memory_0, $memory_4);
#line 528
$memory_6 = 0;
#line 528
$memory_5 = c_rt_lib::to_nl($memory_5 > $memory_6);
#line 528
undef($memory_6);
#line 528
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 528
if (c_rt_lib::check_true($memory_5)) {goto label_101;}
#line 529
$memory_6 = 1;
#line 529
undef($memory_0);
#line 529
undef($memory_1);
#line 529
undef($memory_2);
#line 529
undef($memory_3);
#line 529
undef($memory_4);
#line 529
undef($memory_5);
#line 529
return $memory_6;
#line 529
undef($memory_6);
#line 530
goto label_101;
#line 530
label_101:
#line 530
undef($memory_5);
#line 531
$memory_5 = $memory_0->{'language'};
#line 531
$memory_5 = c_rt_lib::ov_is($memory_5, 'ast');
#line 531
if (c_rt_lib::check_true($memory_5)) {goto label_108;}
#line 531
$memory_5 = $memory_0->{'language'};
#line 531
$memory_5 = c_rt_lib::ov_is($memory_5, 'nl');
#line 531
label_108:
#line 531
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 531
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 531
if (c_rt_lib::check_true($memory_5)) {goto label_151;}
#line 532
$memory_6 = "post processing";
#line 532
profile::begin($memory_6);
#line 532
undef($memory_6);
#line 533
$memory_7 = $memory_0->{'language'};
#line 533
$memory_6 = compiler_priv::get_generator_state($memory_7);
#line 533
undef($memory_7);
#line 534
$memory_7 = "search constants...";
#line 534
c_fe_lib::print($memory_7);
#line 534
undef($memory_7);
#line 535
$memory_8 = compiler_priv::get_mathematical_func($memory_0);
#line 535
$memory_9 = $memory_0->{'optimization'};
#line 535
$memory_7 = post_processing::init($memory_8, $memory_9);
#line 535
undef($memory_9);
#line 535
undef($memory_8);
#line 536
$memory_8 = "post processing";
#line 536
profile::end($memory_8);
#line 536
undef($memory_8);
#line 538
$memory_8 = "translate to nlasm";
#line 538
profile::begin($memory_8);
#line 538
undef($memory_8);
#line 539
$memory_8 = compiler_priv::translate($memory_1, $memory_7);
#line 540
$memory_9 = "translate to nlasm";
#line 540
profile::end($memory_9);
#line 540
undef($memory_9);
#line 542
$memory_9 = "save files";
#line 542
profile::begin($memory_9);
#line 542
undef($memory_9);
#line 543
$memory_9 = $memory_0->{'cache_path'};
#line 543
$memory_10 = $memory_0->{'language'};
#line 543
compiler_priv::generate_modules_to_files($memory_8, $memory_4, $memory_9, $memory_6, $memory_10);
#line 543
undef($memory_10);
#line 543
undef($memory_9);
#line 544
$memory_9 = "save files";
#line 544
profile::end($memory_9);
#line 544
undef($memory_9);
#line 544
undef($memory_6);
#line 544
undef($memory_7);
#line 544
undef($memory_8);
#line 545
goto label_210;
#line 545
label_151:
#line 546
$memory_8 = c_rt_lib::init_iter($memory_1);
#line 546
label_153:
#line 546
$memory_6 = c_rt_lib::is_end_hash($memory_8);
#line 546
if (c_rt_lib::check_true($memory_6)) {goto label_205;}
#line 546
$memory_6 = c_rt_lib::get_key_iter($memory_8);
#line 546
$memory_7 = c_rt_lib::hash_get_value($memory_1, $memory_6);
#line 547
$memory_9 = "saving file: ";
#line 547
$memory_9 = $memory_9 . $memory_6;
#line 547
c_fe_lib::print($memory_9);
#line 547
undef($memory_9);
#line 548
$memory_10 = hash::get_value($memory_4, $memory_6);
#line 548
$memory_10 = $memory_10->{'dst'};
#line 548
$memory_9 = compiler_priv::save_module_to_file($memory_7, $memory_10);
#line 548
undef($memory_10);
#line 548
$memory_10 = c_rt_lib::ov_is($memory_9, 'err');
#line 548
if (c_rt_lib::check_true($memory_10)) {goto label_173;}
#line 551
$memory_10 = c_rt_lib::ov_is($memory_9, 'ok');
#line 551
if (c_rt_lib::check_true($memory_10)) {goto label_196;}
#line 551
$memory_10 = "NOMATCHALERT";
#line 551
$memory_10 = [$memory_10,$memory_9];
#line 551
die(dfile::ssave($memory_10));
#line 548
label_173:
#line 548
$memory_11 = c_rt_lib::ov_as($memory_9, 'err');
#line 549
$memory_12 = "ERROR: ";
#line 549
$memory_12 = $memory_12 . $memory_11;
#line 549
c_fe_lib::print($memory_12);
#line 549
undef($memory_12);
#line 550
$memory_12 = 1;
#line 550
undef($memory_0);
#line 550
undef($memory_1);
#line 550
undef($memory_2);
#line 550
undef($memory_3);
#line 550
undef($memory_4);
#line 550
undef($memory_5);
#line 550
undef($memory_6);
#line 550
undef($memory_7);
#line 550
undef($memory_8);
#line 550
undef($memory_9);
#line 550
undef($memory_10);
#line 550
undef($memory_11);
#line 550
return $memory_12;
#line 550
undef($memory_12);
#line 550
undef($memory_11);
#line 551
goto label_200;
#line 551
label_196:
#line 551
$memory_11 = c_rt_lib::ov_as($memory_9, 'ok');
#line 551
undef($memory_11);
#line 552
goto label_200;
#line 552
label_200:
#line 552
undef($memory_9);
#line 552
undef($memory_10);
#line 553
$memory_8 = c_rt_lib::next_iter($memory_8);
#line 553
goto label_153;
#line 553
label_205:
#line 553
undef($memory_6);
#line 553
undef($memory_7);
#line 553
undef($memory_8);
#line 554
goto label_210;
#line 554
label_210:
#line 554
undef($memory_5);
#line 555
$memory_5 = 0;
#line 555
undef($memory_0);
#line 555
undef($memory_1);
#line 555
undef($memory_2);
#line 555
undef($memory_3);
#line 555
undef($memory_4);
#line 555
return $memory_5;
#line 555
undef($memory_5);
#line 555
undef($memory_1);
#line 555
undef($memory_2);
#line 555
undef($memory_3);
#line 555
undef($memory_4);
#line 555
undef($memory_0);
#line 555
return;
}
sub compiler_priv::construct_error_message($$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;$memory_0 = $_[0];$memory_1 = $_[1];
#line 559
$memory_2 = "";
#line 563
$memory_4 = $memory_0->{'module'};
#line 563
$memory_3 = string::length($memory_4);
#line 563
undef($memory_4);
#line 563
$memory_4 = 0;
#line 563
$memory_3 = c_rt_lib::to_nl($memory_3 == $memory_4);
#line 563
undef($memory_4);
#line 563
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 563
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 563
if (c_rt_lib::check_true($memory_3)) {goto label_28;}
#line 560
$memory_4 = " mod: ";
#line 560
$memory_6 = $memory_0->{'module'};
#line 560
$memory_5 = hash::has_key($memory_1, $memory_6);
#line 560
undef($memory_6);
#line 560
if (c_rt_lib::check_true($memory_5)) {goto label_17;}
#line 562
$memory_5 = $memory_0->{'module'};
#line 562
goto label_22;
#line 562
label_17:
#line 561
$memory_6 = $memory_0->{'module'};
#line 561
$memory_5 = hash::get_value($memory_1, $memory_6);
#line 561
undef($memory_6);
#line 561
$memory_5 = $memory_5->{'src'};
#line 561
label_22:
#line 561
$memory_4 = $memory_4 . $memory_5;
#line 561
undef($memory_5);
#line 561
$memory_2 = $memory_2 . $memory_4;
#line 561
undef($memory_4);
#line 561
goto label_28;
#line 561
label_28:
#line 561
undef($memory_3);
#line 564
$memory_4 = $memory_0->{'line'};
#line 564
$memory_3 = string::length($memory_4);
#line 564
undef($memory_4);
#line 564
$memory_4 = 0;
#line 564
$memory_3 = c_rt_lib::to_nl($memory_3 == $memory_4);
#line 564
undef($memory_4);
#line 564
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 564
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_3));
#line 564
if (c_rt_lib::check_true($memory_3)) {goto label_46;}
#line 564
$memory_4 = " line: ";
#line 564
$memory_5 = $memory_0->{'line'};
#line 564
$memory_4 = $memory_4 . $memory_5;
#line 564
undef($memory_5);
#line 564
$memory_2 = $memory_2 . $memory_4;
#line 564
undef($memory_4);
#line 564
goto label_46;
#line 564
label_46:
#line 564
undef($memory_3);
#line 565
$memory_3 = string::lf();
#line 565
$memory_4 = " ";
#line 565
$memory_3 = $memory_3 . $memory_4;
#line 565
undef($memory_4);
#line 565
$memory_4 = $memory_0->{'message'};
#line 565
$memory_3 = $memory_3 . $memory_4;
#line 565
undef($memory_4);
#line 565
$memory_2 = $memory_2 . $memory_3;
#line 565
undef($memory_3);
#line 566
undef($memory_0);
#line 566
undef($memory_1);
#line 566
return $memory_2;
#line 566
undef($memory_2);
#line 566
undef($memory_0);
#line 566
undef($memory_1);
#line 566
return;
}
sub compiler_priv::show_and_count_errors($$$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;my $memory_13;my $memory_14;my $memory_15;my $memory_16;my $memory_17;my $memory_18;my $memory_19;$memory_0 = $_[0];$memory_1 = $_[1];$memory_2 = $_[2];
#line 570
$memory_3 = 0;
#line 571
$memory_4 = 0;
#line 572
$memory_5 = $memory_0->{'module_warnings'};
#line 572
$memory_8 = c_rt_lib::init_iter($memory_5);
#line 572
label_4:
#line 572
$memory_6 = c_rt_lib::is_end_hash($memory_8);
#line 572
if (c_rt_lib::check_true($memory_6)) {goto label_146;}
#line 572
$memory_6 = c_rt_lib::get_key_iter($memory_8);
#line 572
$memory_7 = c_rt_lib::hash_get_value($memory_5, $memory_6);
#line 573
$memory_9 = "WAR";
#line 574
$memory_10 = $memory_1->{'alarm'};
#line 574
$memory_10 = c_rt_lib::ov_is($memory_10, 'wall');
#line 574
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 574
if (c_rt_lib::check_true($memory_10)) {goto label_18;}
#line 574
$memory_11 = "ERR";
#line 574
$memory_9 = $memory_11;
#line 574
undef($memory_11);
#line 574
goto label_18;
#line 574
label_18:
#line 574
undef($memory_10);
#line 575
$memory_11 = 0;
#line 575
$memory_12 = 1;
#line 575
$memory_13 = c_rt_lib::array_len($memory_7);
#line 575
label_23:
#line 575
$memory_14 = c_rt_lib::to_nl($memory_11 >= $memory_13);
#line 575
if (c_rt_lib::check_true($memory_14)) {goto label_33;}
#line 575
$memory_10 = $memory_7->[$memory_11];
#line 576
$memory_15 = compiler_priv::construct_error_message($memory_10, $memory_2);
#line 576
$memory_15 = $memory_9 . $memory_15;
#line 576
c_fe_lib::print($memory_15);
#line 576
undef($memory_15);
#line 577
$memory_11 = $memory_11 + $memory_12;
#line 577
goto label_23;
#line 577
label_33:
#line 577
undef($memory_10);
#line 577
undef($memory_11);
#line 577
undef($memory_12);
#line 577
undef($memory_13);
#line 577
undef($memory_14);
#line 578
$memory_10 = array::len($memory_7);
#line 578
$memory_3 = $memory_3 + $memory_10;
#line 578
undef($memory_10);
#line 579
$memory_11 = $memory_0->{'type_warnings'};
#line 579
$memory_10 = hash::has_key($memory_11, $memory_6);
#line 579
undef($memory_11);
#line 579
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 579
if (c_rt_lib::check_true($memory_10)) {goto label_74;}
#line 580
$memory_12 = $memory_0->{'type_warnings'};
#line 580
$memory_11 = hash::get_value($memory_12, $memory_6);
#line 580
undef($memory_12);
#line 581
$memory_13 = 0;
#line 581
$memory_14 = 1;
#line 581
$memory_15 = c_rt_lib::array_len($memory_11);
#line 581
label_53:
#line 581
$memory_16 = c_rt_lib::to_nl($memory_13 >= $memory_15);
#line 581
if (c_rt_lib::check_true($memory_16)) {goto label_63;}
#line 581
$memory_12 = $memory_11->[$memory_13];
#line 582
$memory_17 = compiler_priv::construct_error_message($memory_12, $memory_2);
#line 582
$memory_17 = $memory_9 . $memory_17;
#line 582
c_fe_lib::print($memory_17);
#line 582
undef($memory_17);
#line 583
$memory_13 = $memory_13 + $memory_14;
#line 583
goto label_53;
#line 583
label_63:
#line 583
undef($memory_12);
#line 583
undef($memory_13);
#line 583
undef($memory_14);
#line 583
undef($memory_15);
#line 583
undef($memory_16);
#line 584
$memory_12 = array::len($memory_11);
#line 584
$memory_3 = $memory_3 + $memory_12;
#line 584
undef($memory_12);
#line 584
undef($memory_11);
#line 585
goto label_74;
#line 585
label_74:
#line 585
undef($memory_10);
#line 586
$memory_10 = "ERR";
#line 586
$memory_9 = $memory_10;
#line 586
undef($memory_10);
#line 587
$memory_11 = $memory_0->{'module_errors'};
#line 587
$memory_10 = hash::get_value($memory_11, $memory_6);
#line 587
undef($memory_11);
#line 588
$memory_12 = 0;
#line 588
$memory_13 = 1;
#line 588
$memory_14 = c_rt_lib::array_len($memory_10);
#line 588
label_85:
#line 588
$memory_15 = c_rt_lib::to_nl($memory_12 >= $memory_14);
#line 588
if (c_rt_lib::check_true($memory_15)) {goto label_97;}
#line 588
$memory_11 = $memory_10->[$memory_12];
#line 589
$memory_16 = "ERR";
#line 589
$memory_17 = compiler_priv::construct_error_message($memory_11, $memory_2);
#line 589
$memory_16 = $memory_16 . $memory_17;
#line 589
undef($memory_17);
#line 589
c_fe_lib::print($memory_16);
#line 589
undef($memory_16);
#line 590
$memory_12 = $memory_12 + $memory_13;
#line 590
goto label_85;
#line 590
label_97:
#line 590
undef($memory_11);
#line 590
undef($memory_12);
#line 590
undef($memory_13);
#line 590
undef($memory_14);
#line 590
undef($memory_15);
#line 591
$memory_11 = array::len($memory_10);
#line 591
$memory_4 = $memory_4 + $memory_11;
#line 591
undef($memory_11);
#line 592
$memory_12 = $memory_0->{'type_errors'};
#line 592
$memory_11 = hash::has_key($memory_12, $memory_6);
#line 592
undef($memory_12);
#line 592
$memory_11 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_11));
#line 592
if (c_rt_lib::check_true($memory_11)) {goto label_140;}
#line 593
$memory_13 = $memory_0->{'type_errors'};
#line 593
$memory_12 = hash::get_value($memory_13, $memory_6);
#line 593
undef($memory_13);
#line 594
$memory_14 = 0;
#line 594
$memory_15 = 1;
#line 594
$memory_16 = c_rt_lib::array_len($memory_12);
#line 594
label_117:
#line 594
$memory_17 = c_rt_lib::to_nl($memory_14 >= $memory_16);
#line 594
if (c_rt_lib::check_true($memory_17)) {goto label_129;}
#line 594
$memory_13 = $memory_12->[$memory_14];
#line 595
$memory_18 = "ERR";
#line 595
$memory_19 = compiler_priv::construct_error_message($memory_13, $memory_2);
#line 595
$memory_18 = $memory_18 . $memory_19;
#line 595
undef($memory_19);
#line 595
c_fe_lib::print($memory_18);
#line 595
undef($memory_18);
#line 596
$memory_14 = $memory_14 + $memory_15;
#line 596
goto label_117;
#line 596
label_129:
#line 596
undef($memory_13);
#line 596
undef($memory_14);
#line 596
undef($memory_15);
#line 596
undef($memory_16);
#line 596
undef($memory_17);
#line 597
$memory_13 = array::len($memory_12);
#line 597
$memory_4 = $memory_4 + $memory_13;
#line 597
undef($memory_13);
#line 597
undef($memory_12);
#line 598
goto label_140;
#line 598
label_140:
#line 598
undef($memory_11);
#line 598
undef($memory_9);
#line 598
undef($memory_10);
#line 599
$memory_8 = c_rt_lib::next_iter($memory_8);
#line 599
goto label_4;
#line 599
label_146:
#line 599
undef($memory_5);
#line 599
undef($memory_6);
#line 599
undef($memory_7);
#line 599
undef($memory_8);
#line 600
$memory_5 = $memory_0->{'loop_error'};
#line 600
$memory_6 = c_rt_lib::ov_is($memory_5, 'loop');
#line 600
if (c_rt_lib::check_true($memory_6)) {goto label_159;}
#line 607
$memory_6 = c_rt_lib::ov_is($memory_5, 'ok');
#line 607
if (c_rt_lib::check_true($memory_6)) {goto label_194;}
#line 607
$memory_6 = "NOMATCHALERT";
#line 607
$memory_6 = [$memory_6,$memory_5];
#line 607
die(dfile::ssave($memory_6));
#line 600
label_159:
#line 600
$memory_7 = c_rt_lib::ov_as($memory_5, 'loop');
#line 601
$memory_8 = "";
#line 602
$memory_10 = 0;
#line 602
$memory_11 = 1;
#line 602
$memory_12 = c_rt_lib::array_len($memory_7);
#line 602
label_165:
#line 602
$memory_13 = c_rt_lib::to_nl($memory_10 >= $memory_12);
#line 602
if (c_rt_lib::check_true($memory_13)) {goto label_175;}
#line 602
$memory_9 = $memory_7->[$memory_10];
#line 603
$memory_14 = " -> ";
#line 603
$memory_14 = $memory_9 . $memory_14;
#line 603
$memory_8 = $memory_8 . $memory_14;
#line 603
undef($memory_14);
#line 604
$memory_10 = $memory_10 + $memory_11;
#line 604
goto label_165;
#line 604
label_175:
#line 604
undef($memory_9);
#line 604
undef($memory_10);
#line 604
undef($memory_11);
#line 604
undef($memory_12);
#line 604
undef($memory_13);
#line 605
$memory_9 = "ERR Loop found in module imports: ";
#line 605
$memory_9 = $memory_9 . $memory_8;
#line 605
$memory_10 = ". ";
#line 605
$memory_9 = $memory_9 . $memory_10;
#line 605
undef($memory_10);
#line 605
c_fe_lib::print($memory_9);
#line 605
undef($memory_9);
#line 606
$memory_9 = 1;
#line 606
$memory_4 = $memory_4 + $memory_9;
#line 606
undef($memory_9);
#line 606
undef($memory_8);
#line 606
undef($memory_7);
#line 607
goto label_196;
#line 607
label_194:
#line 608
goto label_196;
#line 608
label_196:
#line 608
undef($memory_5);
#line 608
undef($memory_6);
#line 609
$memory_5 = $memory_1->{'alarm'};
#line 609
$memory_5 = c_rt_lib::ov_is($memory_5, 'wall');
#line 609
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 609
if (c_rt_lib::check_true($memory_5)) {goto label_208;}
#line 610
$memory_4 = $memory_4 + $memory_3;
#line 611
$memory_6 = 0;
#line 611
$memory_3 = $memory_6;
#line 611
undef($memory_6);
#line 612
goto label_208;
#line 612
label_208:
#line 612
undef($memory_5);
#line 613
$memory_5 = "ERR: ";
#line 613
$memory_5 = $memory_5 . $memory_4;
#line 613
$memory_6 = " WAR: ";
#line 613
$memory_5 = $memory_5 . $memory_6;
#line 613
undef($memory_6);
#line 613
$memory_5 = $memory_5 . $memory_3;
#line 613
c_fe_lib::print($memory_5);
#line 613
undef($memory_5);
#line 614
undef($memory_0);
#line 614
undef($memory_1);
#line 614
undef($memory_2);
#line 614
undef($memory_3);
#line 614
return $memory_4;
#line 614
undef($memory_3);
#line 614
undef($memory_4);
#line 614
undef($memory_0);
#line 614
undef($memory_1);
#line 614
undef($memory_2);
#line 614
return;
}
sub compiler_priv::translate($$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;$memory_0 = $_[0];$memory_1 = $_[1];Scalar::Util::weaken($_[1]) if ref($_[1]);
#line 618
$memory_2 = {};
#line 619
$memory_5 = c_rt_lib::init_iter($memory_0);
#line 619
label_2:
#line 619
$memory_3 = c_rt_lib::is_end_hash($memory_5);
#line 619
if (c_rt_lib::check_true($memory_3)) {goto label_12;}
#line 619
$memory_3 = c_rt_lib::get_key_iter($memory_5);
#line 619
$memory_4 = c_rt_lib::hash_get_value($memory_0, $memory_3);
#line 620
$memory_6 = translator::translate($memory_4);
#line 621
hash::set_value($memory_2, $memory_3, $memory_6);
#line 621
undef($memory_6);
#line 622
$memory_5 = c_rt_lib::next_iter($memory_5);
#line 622
goto label_2;
#line 622
label_12:
#line 622
undef($memory_3);
#line 622
undef($memory_4);
#line 622
undef($memory_5);
#line 623
post_processing::find($memory_1, $memory_2);
#line 624
undef($memory_0);
#line 624
$_[1] = $memory_1;return $memory_2;
#line 624
undef($memory_2);
#line 624
undef($memory_0);
#line 624
$_[1] = $memory_1;return;
$_[1] = $memory_1;}
sub compiler_priv::check_modules($$$$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;my $memory_13;my $memory_14;my $memory_15;my $memory_16;my $memory_17;$memory_0 = $_[0];$memory_1 = $_[1];Scalar::Util::weaken($_[1]) if ref($_[1]);$memory_2 = $_[2];$memory_3 = $_[3];
#line 629
$memory_4 = "type checking...";
#line 629
c_fe_lib::print($memory_4);
#line 629
undef($memory_4);
#line 630
$memory_4 = type_checker::check_modules($memory_0, $memory_0);
#line 631
$memory_5 = $memory_3;
#line 631
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 631
if (c_rt_lib::check_true($memory_5)) {goto label_62;}
#line 632
$memory_6 = {};
#line 633
$memory_8 = "public_functions.df";
#line 633
$memory_7 = c_fe_lib::file_to_string($memory_8);
#line 633
undef($memory_8);
#line 633
$memory_8 = c_rt_lib::ov_is($memory_7, 'ok');
#line 633
if (c_rt_lib::check_true($memory_8)) {goto label_18;}
#line 636
$memory_8 = c_rt_lib::ov_is($memory_7, 'err');
#line 636
if (c_rt_lib::check_true($memory_8)) {goto label_32;}
#line 636
$memory_8 = "NOMATCHALERT";
#line 636
$memory_8 = [$memory_8,$memory_7];
#line 636
die(dfile::ssave($memory_8));
#line 633
label_18:
#line 633
$memory_9 = c_rt_lib::ov_as($memory_7, 'ok');
#line 634
$memory_10 = dfile::sload($memory_9);
#line 634
$memory_6 = $memory_10;
#line 634
undef($memory_10);
#line 635
$memory_12 = ptd::sim();
#line 635
$memory_11 = ptd::hash($memory_12);
#line 635
undef($memory_12);
#line 635
$memory_10 = ptd::ensure($memory_11, $memory_6);
#line 635
undef($memory_11);
#line 635
$memory_6 = $memory_10;
#line 635
undef($memory_10);
#line 635
undef($memory_9);
#line 636
goto label_36;
#line 636
label_32:
#line 636
$memory_9 = c_rt_lib::ov_as($memory_7, 'err');
#line 636
undef($memory_9);
#line 637
goto label_36;
#line 637
label_36:
#line 637
undef($memory_7);
#line 637
undef($memory_8);
#line 638
$memory_7 = {};
#line 639
$memory_8 = [];
#line 640
$memory_11 = c_rt_lib::init_iter($memory_0);
#line 640
label_42:
#line 640
$memory_9 = c_rt_lib::is_end_hash($memory_11);
#line 640
if (c_rt_lib::check_true($memory_9)) {goto label_53;}
#line 640
$memory_9 = c_rt_lib::get_key_iter($memory_11);
#line 640
$memory_10 = c_rt_lib::hash_get_value($memory_0, $memory_9);
#line 641
$memory_12 = c_rt_lib::to_nl(1);
#line 641
module_checker::check_module($memory_10, $memory_12, $memory_7);
#line 641
undef($memory_12);
#line 642
array::push($memory_8, $memory_10);
#line 643
$memory_11 = c_rt_lib::next_iter($memory_11);
#line 643
goto label_42;
#line 643
label_53:
#line 643
undef($memory_9);
#line 643
undef($memory_10);
#line 643
undef($memory_11);
#line 645
module_checker::check_used_functions($memory_6, $memory_7, $memory_8, $memory_4);
#line 645
undef($memory_6);
#line 645
undef($memory_7);
#line 645
undef($memory_8);
#line 646
goto label_62;
#line 646
label_62:
#line 646
undef($memory_5);
#line 647
$memory_6 = $memory_4->{'errors'};
#line 647
$memory_5 = array::len($memory_6);
#line 647
undef($memory_6);
#line 648
$memory_6 = $memory_4->{'errors'};
#line 648
$memory_8 = 0;
#line 648
$memory_9 = 1;
#line 648
$memory_10 = c_rt_lib::array_len($memory_6);
#line 648
label_71:
#line 648
$memory_11 = c_rt_lib::to_nl($memory_8 >= $memory_10);
#line 648
if (c_rt_lib::check_true($memory_11)) {goto label_106;}
#line 648
$memory_7 = $memory_6->[$memory_8];
#line 649
$memory_12 = [];
#line 650
$memory_14 = $memory_1->{'type_errors'};
#line 650
$memory_15 = $memory_7->{'module'};
#line 650
$memory_13 = hash::has_key($memory_14, $memory_15);
#line 650
undef($memory_15);
#line 650
undef($memory_14);
#line 650
$memory_13 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_13));
#line 650
if (c_rt_lib::check_true($memory_13)) {goto label_91;}
#line 651
$memory_15 = $memory_1->{'type_errors'};
#line 651
$memory_16 = $memory_7->{'module'};
#line 651
$memory_14 = hash::get_value($memory_15, $memory_16);
#line 651
undef($memory_16);
#line 651
undef($memory_15);
#line 651
$memory_12 = $memory_14;
#line 651
undef($memory_14);
#line 652
goto label_91;
#line 652
label_91:
#line 652
undef($memory_13);
#line 653
array::push($memory_12, $memory_7);
#line 654
$memory_13 = "type_errors";
#line 654
$memory_13 = c_rt_lib::get_ref_hash($memory_1, $memory_13);
#line 654
$memory_14 = $memory_7->{'module'};
#line 654
hash::set_value($memory_13, $memory_14, $memory_12);
#line 654
undef($memory_14);
#line 654
$memory_14 = "type_errors";
#line 654
c_rt_lib::set_ref_hash($memory_1, $memory_14, $memory_13);
#line 654
undef($memory_14);
#line 654
undef($memory_13);
#line 654
undef($memory_12);
#line 655
$memory_8 = $memory_8 + $memory_9;
#line 655
goto label_71;
#line 655
label_106:
#line 655
undef($memory_6);
#line 655
undef($memory_7);
#line 655
undef($memory_8);
#line 655
undef($memory_9);
#line 655
undef($memory_10);
#line 655
undef($memory_11);
#line 656
$memory_6 = $memory_4->{'warnings'};
#line 656
$memory_8 = 0;
#line 656
$memory_9 = 1;
#line 656
$memory_10 = c_rt_lib::array_len($memory_6);
#line 656
label_117:
#line 656
$memory_11 = c_rt_lib::to_nl($memory_8 >= $memory_10);
#line 656
if (c_rt_lib::check_true($memory_11)) {goto label_152;}
#line 656
$memory_7 = $memory_6->[$memory_8];
#line 657
$memory_12 = [];
#line 658
$memory_14 = $memory_1->{'type_warnings'};
#line 658
$memory_15 = $memory_7->{'module'};
#line 658
$memory_13 = hash::has_key($memory_14, $memory_15);
#line 658
undef($memory_15);
#line 658
undef($memory_14);
#line 658
$memory_13 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_13));
#line 658
if (c_rt_lib::check_true($memory_13)) {goto label_137;}
#line 659
$memory_15 = $memory_1->{'type_warnings'};
#line 659
$memory_16 = $memory_7->{'module'};
#line 659
$memory_14 = hash::get_value($memory_15, $memory_16);
#line 659
undef($memory_16);
#line 659
undef($memory_15);
#line 659
$memory_12 = $memory_14;
#line 659
undef($memory_14);
#line 660
goto label_137;
#line 660
label_137:
#line 660
undef($memory_13);
#line 661
array::push($memory_12, $memory_7);
#line 662
$memory_13 = "type_warnings";
#line 662
$memory_13 = c_rt_lib::get_ref_hash($memory_1, $memory_13);
#line 662
$memory_14 = $memory_7->{'module'};
#line 662
hash::set_value($memory_13, $memory_14, $memory_12);
#line 662
undef($memory_14);
#line 662
$memory_14 = "type_warnings";
#line 662
c_rt_lib::set_ref_hash($memory_1, $memory_14, $memory_13);
#line 662
undef($memory_14);
#line 662
undef($memory_13);
#line 662
undef($memory_12);
#line 663
$memory_8 = $memory_8 + $memory_9;
#line 663
goto label_117;
#line 663
label_152:
#line 663
undef($memory_6);
#line 663
undef($memory_7);
#line 663
undef($memory_8);
#line 663
undef($memory_9);
#line 663
undef($memory_10);
#line 663
undef($memory_11);
#line 664
$memory_6 = 0;
#line 664
$memory_6 = c_rt_lib::to_nl($memory_5 == $memory_6);
#line 664
$memory_6 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_6));
#line 664
$memory_6 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_6));
#line 664
if (c_rt_lib::check_true($memory_6)) {goto label_172;}
#line 664
$memory_7 = "Found ";
#line 664
$memory_7 = $memory_7 . $memory_5;
#line 664
$memory_8 = " errors of types. ";
#line 664
$memory_7 = $memory_7 . $memory_8;
#line 664
undef($memory_8);
#line 664
c_fe_lib::print($memory_7);
#line 664
undef($memory_7);
#line 664
goto label_172;
#line 664
label_172:
#line 664
undef($memory_6);
#line 665
$memory_6 = {};
#line 666
$memory_9 = c_rt_lib::init_iter($memory_0);
#line 666
label_176:
#line 666
$memory_7 = c_rt_lib::is_end_hash($memory_9);
#line 666
if (c_rt_lib::check_true($memory_7)) {goto label_206;}
#line 666
$memory_7 = c_rt_lib::get_key_iter($memory_9);
#line 666
$memory_8 = c_rt_lib::hash_get_value($memory_0, $memory_7);
#line 667
$memory_10 = [];
#line 668
$memory_11 = $memory_8->{'import'};
#line 668
$memory_13 = 0;
#line 668
$memory_14 = 1;
#line 668
$memory_15 = c_rt_lib::array_len($memory_11);
#line 668
label_186:
#line 668
$memory_16 = c_rt_lib::to_nl($memory_13 >= $memory_15);
#line 668
if (c_rt_lib::check_true($memory_16)) {goto label_195;}
#line 668
$memory_12 = $memory_11->[$memory_13];
#line 669
$memory_17 = $memory_12->{'name'};
#line 669
array::push($memory_10, $memory_17);
#line 669
undef($memory_17);
#line 670
$memory_13 = $memory_13 + $memory_14;
#line 670
goto label_186;
#line 670
label_195:
#line 670
undef($memory_11);
#line 670
undef($memory_12);
#line 670
undef($memory_13);
#line 670
undef($memory_14);
#line 670
undef($memory_15);
#line 670
undef($memory_16);
#line 671
hash::set_value($memory_6, $memory_7, $memory_10);
#line 671
undef($memory_10);
#line 672
$memory_9 = c_rt_lib::next_iter($memory_9);
#line 672
goto label_176;
#line 672
label_206:
#line 672
undef($memory_7);
#line 672
undef($memory_8);
#line 672
undef($memory_9);
#line 673
$memory_7 = module_checker::search_loops($memory_6);
#line 673
$memory_8 = $memory_7;
#line 673
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'loop_error'} = $memory_8;
#line 673
undef($memory_7);
#line 673
undef($memory_8);
#line 674
$memory_7 = $memory_2;
#line 674
$memory_7 = c_rt_lib::ov_is($memory_7, 'yes');
#line 674
$memory_7 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_7));
#line 674
if (c_rt_lib::check_true($memory_7)) {goto label_255;}
#line 675
$memory_8 = "deleted types: ";
#line 675
$memory_10 = $memory_4->{'deref'};
#line 675
$memory_10 = $memory_10->{'delete'};
#line 675
$memory_9 = array::len($memory_10);
#line 675
undef($memory_10);
#line 675
$memory_8 = $memory_8 . $memory_9;
#line 675
undef($memory_9);
#line 675
c_fe_lib::print($memory_8);
#line 675
undef($memory_8);
#line 676
$memory_8 = "created types: ";
#line 676
$memory_10 = $memory_4->{'deref'};
#line 676
$memory_10 = $memory_10->{'create'};
#line 676
$memory_9 = array::len($memory_10);
#line 676
undef($memory_10);
#line 676
$memory_8 = $memory_8 . $memory_9;
#line 676
undef($memory_9);
#line 676
c_fe_lib::print($memory_8);
#line 676
undef($memory_8);
#line 677
$memory_8 = reference_generator::generate($memory_0);
#line 678
$memory_11 = $memory_2;
#line 678
$memory_11 = c_rt_lib::ov_as($memory_11, 'yes');
#line 678
$memory_13 = $memory_4->{'deref'};
#line 678
$memory_12 = compiler_priv::serialize_deref($memory_13, $memory_8);
#line 678
undef($memory_13);
#line 678
$memory_10 = c_fe_lib::string_to_file($memory_11, $memory_12);
#line 678
undef($memory_12);
#line 678
undef($memory_11);
#line 678
$memory_9 = c_rt_lib::ov_is($memory_10, 'ok');
#line 678
if (c_rt_lib::check_true($memory_9)) {goto label_250;}
#line 678
$memory_10 = c_rt_lib::ov_mk_arg('ensure', $memory_10);
#line 678
die(dfile::ssave($memory_10));
#line 678
label_250:
#line 678
undef($memory_9);
#line 678
undef($memory_10);
#line 678
undef($memory_8);
#line 679
goto label_255;
#line 679
label_255:
#line 679
undef($memory_7);
#line 679
undef($memory_4);
#line 679
undef($memory_5);
#line 679
undef($memory_6);
#line 679
undef($memory_0);
#line 679
undef($memory_2);
#line 679
undef($memory_3);
#line 679
$_[1] = $memory_1;return;
$_[1] = $memory_1;}
sub compiler_priv::serialize_deref($$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;$memory_0 = $_[0];$memory_1 = $_[1];
#line 683
$memory_2 = [];
#line 684
$memory_3 = compiler_priv::process_deref($memory_0);
#line 684
array::append($memory_2, $memory_3);
#line 684
undef($memory_3);
#line 685
array::append($memory_2, $memory_1);
#line 686
$memory_5 = {
module => "reference_generator",
name => "refs",
};
#line 686
$memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5);
#line 686
$memory_4 = ptd::ensure($memory_5, $memory_2);
#line 686
undef($memory_5);
#line 686
$memory_3 = dfile::ssave_net_format($memory_4);
#line 686
undef($memory_4);
#line 686
undef($memory_0);
#line 686
undef($memory_1);
#line 686
undef($memory_2);
#line 686
return $memory_3;
#line 686
undef($memory_3);
#line 686
undef($memory_2);
#line 686
undef($memory_0);
#line 686
undef($memory_1);
#line 686
return;
}
sub compiler_priv::process_deref($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;$memory_0 = $_[0];
#line 691
$memory_1 = [];
#line 692
$memory_2 = $memory_0->{'create'};
#line 692
$memory_4 = 0;
#line 692
$memory_5 = 1;
#line 692
$memory_6 = c_rt_lib::array_len($memory_2);
#line 692
label_5:
#line 692
$memory_7 = c_rt_lib::to_nl($memory_4 >= $memory_6);
#line 692
if (c_rt_lib::check_true($memory_7)) {goto label_15;}
#line 692
$memory_3 = $memory_2->[$memory_4];
#line 693
$memory_8 = c_rt_lib::ov_mk_arg('delete', $memory_3);
#line 693
$memory_8 = c_rt_lib::ov_mk_arg('deref', $memory_8);
#line 693
c_rt_lib::array_push($memory_1, $memory_8);
#line 693
undef($memory_8);
#line 694
$memory_4 = $memory_4 + $memory_5;
#line 694
goto label_5;
#line 694
label_15:
#line 694
undef($memory_2);
#line 694
undef($memory_3);
#line 694
undef($memory_4);
#line 694
undef($memory_5);
#line 694
undef($memory_6);
#line 694
undef($memory_7);
#line 696
$memory_2 = $memory_0->{'delete'};
#line 696
$memory_4 = 0;
#line 696
$memory_5 = 1;
#line 696
$memory_6 = c_rt_lib::array_len($memory_2);
#line 696
label_26:
#line 696
$memory_7 = c_rt_lib::to_nl($memory_4 >= $memory_6);
#line 696
if (c_rt_lib::check_true($memory_7)) {goto label_36;}
#line 696
$memory_3 = $memory_2->[$memory_4];
#line 697
$memory_8 = c_rt_lib::ov_mk_arg('create', $memory_3);
#line 697
$memory_8 = c_rt_lib::ov_mk_arg('deref', $memory_8);
#line 697
c_rt_lib::array_push($memory_1, $memory_8);
#line 697
undef($memory_8);
#line 698
$memory_4 = $memory_4 + $memory_5;
#line 698
goto label_26;
#line 698
label_36:
#line 698
undef($memory_2);
#line 698
undef($memory_3);
#line 698
undef($memory_4);
#line 698
undef($memory_5);
#line 698
undef($memory_6);
#line 698
undef($memory_7);
#line 699
undef($memory_0);
#line 699
return $memory_1;
#line 699
undef($memory_1);
#line 699
undef($memory_0);
#line 699
return;
}
sub compiler_priv::try_save_file($$$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;$memory_0 = $_[0];$memory_1 = $_[1];$memory_2 = $_[2];Scalar::Util::weaken($_[2]) if ref($_[2]);
#line 703
$memory_3 = c_fe_lib::string_to_file($memory_1, $memory_0);
#line 703
$memory_4 = c_rt_lib::ov_is($memory_3, 'ok');
#line 703
if (c_rt_lib::check_true($memory_4)) {goto label_8;}
#line 704
$memory_4 = c_rt_lib::ov_is($memory_3, 'err');
#line 704
if (c_rt_lib::check_true($memory_4)) {goto label_12;}
#line 704
$memory_4 = "NOMATCHALERT";
#line 704
$memory_4 = [$memory_4,$memory_3];
#line 704
die(dfile::ssave($memory_4));
#line 703
label_8:
#line 703
$memory_5 = c_rt_lib::ov_as($memory_3, 'ok');
#line 703
undef($memory_5);
#line 704
goto label_23;
#line 704
label_12:
#line 704
$memory_5 = c_rt_lib::ov_as($memory_3, 'err');
#line 705
$memory_6 = "ERROR: ";
#line 705
$memory_6 = $memory_6 . $memory_5;
#line 705
c_fe_lib::print($memory_6);
#line 705
undef($memory_6);
#line 706
$memory_6 = c_rt_lib::to_nl(1);
#line 706
$memory_2 = $memory_6;
#line 706
undef($memory_6);
#line 706
undef($memory_5);
#line 707
goto label_23;
#line 707
label_23:
#line 707
undef($memory_3);
#line 707
undef($memory_4);
#line 707
undef($memory_0);
#line 707
undef($memory_1);
#line 707
$_[2] = $memory_2;return;
$_[2] = $memory_2;}
sub compiler_priv::generate_modules_to_files($$$$$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;my $memory_13;my $memory_14;my $memory_15;$memory_0 = $_[0];$memory_1 = $_[1];$memory_2 = $_[2];$memory_3 = $_[3];Scalar::Util::weaken($_[3]) if ref($_[3]);$memory_4 = $_[4];
#line 715
$memory_5 = {};
#line 716
$memory_6 = c_rt_lib::ov_is($memory_4, 'nla');
#line 716
if (c_rt_lib::check_true($memory_6)) {goto label_20;}
#line 724
$memory_6 = c_rt_lib::ov_is($memory_4, 'c');
#line 724
if (c_rt_lib::check_true($memory_6)) {goto label_56;}
#line 738
$memory_6 = c_rt_lib::ov_is($memory_4, 'pm');
#line 738
if (c_rt_lib::check_true($memory_6)) {goto label_123;}
#line 747
$memory_6 = c_rt_lib::ov_is($memory_4, 'js');
#line 747
if (c_rt_lib::check_true($memory_6)) {goto label_159;}
#line 756
$memory_6 = c_rt_lib::ov_is($memory_4, 'java');
#line 756
if (c_rt_lib::check_true($memory_6)) {goto label_199;}
#line 765
$memory_6 = c_rt_lib::ov_is($memory_4, 'nl');
#line 765
if (c_rt_lib::check_true($memory_6)) {goto label_235;}
#line 767
$memory_6 = c_rt_lib::ov_is($memory_4, 'ast');
#line 767
if (c_rt_lib::check_true($memory_6)) {goto label_240;}
#line 769
$memory_6 = c_rt_lib::ov_is($memory_4, 'call_graph');
#line 769
if (c_rt_lib::check_true($memory_6)) {goto label_245;}
#line 769
$memory_6 = "NOMATCHALERT";
#line 769
$memory_6 = [$memory_6,$memory_4];
#line 769
die(dfile::ssave($memory_6));
#line 716
label_20:
#line 717
$memory_9 = c_rt_lib::init_iter($memory_0);
#line 717
label_22:
#line 717
$memory_7 = c_rt_lib::is_end_hash($memory_9);
#line 717
if (c_rt_lib::check_true($memory_7)) {goto label_51;}
#line 717
$memory_7 = c_rt_lib::get_key_iter($memory_9);
#line 717
$memory_8 = c_rt_lib::hash_get_value($memory_0, $memory_7);
#line 718
$memory_10 = c_rt_lib::to_nl(0);
#line 719
$memory_11 = hash::get_value($memory_1, $memory_7);
#line 719
$memory_11 = $memory_11->{'dst'};
#line 719
$memory_11 = c_rt_lib::ov_as($memory_11, 'nla');
#line 720
$memory_12 = "saving file: ";
#line 720
$memory_12 = $memory_12 . $memory_7;
#line 720
c_fe_lib::print($memory_12);
#line 720
undef($memory_12);
#line 721
$memory_12 = dfile::ssave($memory_8);
#line 721
compiler_priv::try_save_file($memory_12, $memory_11, $memory_10);
#line 721
undef($memory_12);
#line 722
$memory_12 = $memory_10;
#line 722
$memory_12 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_12));
#line 722
if (c_rt_lib::check_true($memory_12)) {goto label_45;}
#line 722
$memory_13 = "";
#line 722
hash::set_value($memory_5, $memory_7, $memory_13);
#line 722
undef($memory_13);
#line 722
goto label_45;
#line 722
label_45:
#line 722
undef($memory_12);
#line 722
undef($memory_10);
#line 722
undef($memory_11);
#line 723
$memory_9 = c_rt_lib::next_iter($memory_9);
#line 723
goto label_22;
#line 723
label_51:
#line 723
undef($memory_7);
#line 723
undef($memory_8);
#line 723
undef($memory_9);
#line 724
goto label_269;
#line 724
label_56:
#line 725
$memory_7 = generator_c::generate($memory_0, $memory_3);
#line 726
$memory_8 = c_rt_lib::to_nl(0);
#line 727
$memory_9 = $memory_7->{'modules'};
#line 727
$memory_12 = c_rt_lib::init_iter($memory_9);
#line 727
label_61:
#line 727
$memory_10 = c_rt_lib::is_end_hash($memory_12);
#line 727
if (c_rt_lib::check_true($memory_10)) {goto label_98;}
#line 727
$memory_10 = c_rt_lib::get_key_iter($memory_12);
#line 727
$memory_11 = c_rt_lib::hash_get_value($memory_9, $memory_10);
#line 728
$memory_13 = c_rt_lib::to_nl(0);
#line 728
$memory_8 = $memory_13;
#line 728
undef($memory_13);
#line 729
$memory_13 = hash::get_value($memory_1, $memory_10);
#line 729
$memory_13 = $memory_13->{'dst'};
#line 729
$memory_13 = c_rt_lib::ov_as($memory_13, 'c');
#line 730
$memory_14 = "saving file: ";
#line 730
$memory_14 = $memory_14 . $memory_10;
#line 730
c_fe_lib::print($memory_14);
#line 730
undef($memory_14);
#line 731
$memory_14 = $memory_11->{'c'};
#line 731
$memory_15 = $memory_13->{'c'};
#line 731
compiler_priv::try_save_file($memory_14, $memory_15, $memory_8);
#line 731
undef($memory_15);
#line 731
undef($memory_14);
#line 732
$memory_14 = $memory_11->{'h'};
#line 732
$memory_15 = $memory_13->{'h'};
#line 732
compiler_priv::try_save_file($memory_14, $memory_15, $memory_8);
#line 732
undef($memory_15);
#line 732
undef($memory_14);
#line 733
$memory_14 = $memory_8;
#line 733
$memory_14 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_14));
#line 733
if (c_rt_lib::check_true($memory_14)) {goto label_93;}
#line 733
$memory_15 = "";
#line 733
hash::set_value($memory_5, $memory_10, $memory_15);
#line 733
undef($memory_15);
#line 733
goto label_93;
#line 733
label_93:
#line 733
undef($memory_14);
#line 733
undef($memory_13);
#line 734
$memory_12 = c_rt_lib::next_iter($memory_12);
#line 734
goto label_61;
#line 734
label_98:
#line 734
undef($memory_9);
#line 734
undef($memory_10);
#line 734
undef($memory_11);
#line 734
undef($memory_12);
#line 735
$memory_9 = "saving global const file";
#line 735
c_fe_lib::print($memory_9);
#line 735
undef($memory_9);
#line 736
$memory_9 = $memory_7->{'global_const'};
#line 736
$memory_9 = $memory_9->{'c'};
#line 736
$memory_10 = "c_global_const.c";
#line 736
$memory_10 = $memory_2 . $memory_10;
#line 736
compiler_priv::try_save_file($memory_9, $memory_10, $memory_8);
#line 736
undef($memory_10);
#line 736
undef($memory_9);
#line 737
$memory_9 = $memory_7->{'global_const'};
#line 737
$memory_9 = $memory_9->{'h'};
#line 737
$memory_10 = "c_global_const.h";
#line 737
$memory_10 = $memory_2 . $memory_10;
#line 737
compiler_priv::try_save_file($memory_9, $memory_10, $memory_8);
#line 737
undef($memory_10);
#line 737
undef($memory_9);
#line 737
undef($memory_7);
#line 737
undef($memory_8);
#line 738
goto label_269;
#line 738
label_123:
#line 739
$memory_9 = c_rt_lib::init_iter($memory_0);
#line 739
label_125:
#line 739
$memory_7 = c_rt_lib::is_end_hash($memory_9);
#line 739
if (c_rt_lib::check_true($memory_7)) {goto label_154;}
#line 739
$memory_7 = c_rt_lib::get_key_iter($memory_9);
#line 739
$memory_8 = c_rt_lib::hash_get_value($memory_0, $memory_7);
#line 740
$memory_10 = c_rt_lib::to_nl(0);
#line 741
$memory_11 = generator_pm::generate($memory_8);
#line 742
$memory_12 = hash::get_value($memory_1, $memory_7);
#line 742
$memory_12 = $memory_12->{'dst'};
#line 742
$memory_12 = c_rt_lib::ov_as($memory_12, 'pm');
#line 743
$memory_13 = "saving file: ";
#line 743
$memory_13 = $memory_13 . $memory_7;
#line 743
c_fe_lib::print($memory_13);
#line 743
undef($memory_13);
#line 744
compiler_priv::try_save_file($memory_11, $memory_12, $memory_10);
#line 745
$memory_13 = $memory_10;
#line 745
$memory_13 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_13));
#line 745
if (c_rt_lib::check_true($memory_13)) {goto label_147;}
#line 745
$memory_14 = "";
#line 745
hash::set_value($memory_5, $memory_7, $memory_14);
#line 745
undef($memory_14);
#line 745
goto label_147;
#line 745
label_147:
#line 745
undef($memory_13);
#line 745
undef($memory_10);
#line 745
undef($memory_11);
#line 745
undef($memory_12);
#line 746
$memory_9 = c_rt_lib::next_iter($memory_9);
#line 746
goto label_125;
#line 746
label_154:
#line 746
undef($memory_7);
#line 746
undef($memory_8);
#line 746
undef($memory_9);
#line 747
goto label_269;
#line 747
label_159:
#line 747
$memory_7 = c_rt_lib::ov_as($memory_4, 'js');
#line 748
$memory_10 = c_rt_lib::init_iter($memory_0);
#line 748
label_162:
#line 748
$memory_8 = c_rt_lib::is_end_hash($memory_10);
#line 748
if (c_rt_lib::check_true($memory_8)) {goto label_193;}
#line 748
$memory_8 = c_rt_lib::get_key_iter($memory_10);
#line 748
$memory_9 = c_rt_lib::hash_get_value($memory_0, $memory_8);
#line 749
$memory_11 = c_rt_lib::to_nl(0);
#line 750
$memory_13 = $memory_7->{'namespace'};
#line 750
$memory_12 = generator_js::generate($memory_9, $memory_13);
#line 750
undef($memory_13);
#line 751
$memory_13 = hash::get_value($memory_1, $memory_8);
#line 751
$memory_13 = $memory_13->{'dst'};
#line 751
$memory_13 = c_rt_lib::ov_as($memory_13, 'js');
#line 752
$memory_14 = "saving file: ";
#line 752
$memory_14 = $memory_14 . $memory_8;
#line 752
c_fe_lib::print($memory_14);
#line 752
undef($memory_14);
#line 753
compiler_priv::try_save_file($memory_12, $memory_13, $memory_11);
#line 754
$memory_14 = $memory_11;
#line 754
$memory_14 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_14));
#line 754
if (c_rt_lib::check_true($memory_14)) {goto label_186;}
#line 754
$memory_15 = "";
#line 754
hash::set_value($memory_5, $memory_8, $memory_15);
#line 754
undef($memory_15);
#line 754
goto label_186;
#line 754
label_186:
#line 754
undef($memory_14);
#line 754
undef($memory_11);
#line 754
undef($memory_12);
#line 754
undef($memory_13);
#line 755
$memory_10 = c_rt_lib::next_iter($memory_10);
#line 755
goto label_162;
#line 755
label_193:
#line 755
undef($memory_8);
#line 755
undef($memory_9);
#line 755
undef($memory_10);
#line 755
undef($memory_7);
#line 756
goto label_269;
#line 756
label_199:
#line 757
$memory_9 = c_rt_lib::init_iter($memory_0);
#line 757
label_201:
#line 757
$memory_7 = c_rt_lib::is_end_hash($memory_9);
#line 757
if (c_rt_lib::check_true($memory_7)) {goto label_230;}
#line 757
$memory_7 = c_rt_lib::get_key_iter($memory_9);
#line 757
$memory_8 = c_rt_lib::hash_get_value($memory_0, $memory_7);
#line 758
$memory_10 = c_rt_lib::to_nl(0);
#line 759
$memory_11 = generator_java::generate($memory_8);
#line 760
$memory_12 = hash::get_value($memory_1, $memory_7);
#line 760
$memory_12 = $memory_12->{'dst'};
#line 760
$memory_12 = c_rt_lib::ov_as($memory_12, 'java');
#line 761
$memory_13 = "saving file: ";
#line 761
$memory_13 = $memory_13 . $memory_7;
#line 761
c_fe_lib::print($memory_13);
#line 761
undef($memory_13);
#line 762
compiler_priv::try_save_file($memory_11, $memory_12, $memory_10);
#line 763
$memory_13 = $memory_10;
#line 763
$memory_13 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_13));
#line 763
if (c_rt_lib::check_true($memory_13)) {goto label_223;}
#line 763
$memory_14 = "";
#line 763
hash::set_value($memory_5, $memory_7, $memory_14);
#line 763
undef($memory_14);
#line 763
goto label_223;
#line 763
label_223:
#line 763
undef($memory_13);
#line 763
undef($memory_10);
#line 763
undef($memory_11);
#line 763
undef($memory_12);
#line 764
$memory_9 = c_rt_lib::next_iter($memory_9);
#line 764
goto label_201;
#line 764
label_230:
#line 764
undef($memory_7);
#line 764
undef($memory_8);
#line 764
undef($memory_9);
#line 765
goto label_269;
#line 765
label_235:
#line 766
$memory_7 = [];
#line 766
die(dfile::ssave($memory_7));
#line 766
undef($memory_7);
#line 767
goto label_269;
#line 767
label_240:
#line 768
$memory_7 = [];
#line 768
die(dfile::ssave($memory_7));
#line 768
undef($memory_7);
#line 769
goto label_269;
#line 769
label_245:
#line 770
$memory_7 = post_processing::get_call_graph($memory_0);
#line 771
$memory_8 = c_rt_lib::to_nl(0);
#line 772
$memory_9 = "Saving call_graph file...";
#line 772
c_fe_lib::print($memory_9);
#line 772
undef($memory_9);
#line 773
$memory_9 = dfile::ssave($memory_7);
#line 773
$memory_10 = "_call_graph.df";
#line 773
$memory_10 = $memory_2 . $memory_10;
#line 773
compiler_priv::try_save_file($memory_9, $memory_10, $memory_8);
#line 773
undef($memory_10);
#line 773
undef($memory_9);
#line 774
$memory_9 = $memory_8;
#line 774
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 774
if (c_rt_lib::check_true($memory_9)) {goto label_264;}
#line 775
$memory_10 = "Error while saving to file.";
#line 775
c_fe_lib::print($memory_10);
#line 775
undef($memory_10);
#line 776
goto label_264;
#line 776
label_264:
#line 776
undef($memory_9);
#line 776
undef($memory_7);
#line 776
undef($memory_8);
#line 777
goto label_269;
#line 777
label_269:
#line 777
undef($memory_6);
#line 778
$memory_6 = hash::size($memory_5);
#line 778
$memory_7 = 0;
#line 778
$memory_6 = c_rt_lib::to_nl($memory_6 > $memory_7);
#line 778
undef($memory_7);
#line 778
$memory_6 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_6));
#line 778
if (c_rt_lib::check_true($memory_6)) {goto label_287;}
#line 779
$memory_7 = c_rt_lib::ov_mk_arg('err', $memory_5);
#line 779
undef($memory_0);
#line 779
undef($memory_1);
#line 779
undef($memory_2);
#line 779
undef($memory_4);
#line 779
undef($memory_5);
#line 779
undef($memory_6);
#line 779
$_[3] = $memory_3;return $memory_7;
#line 779
undef($memory_7);
#line 780
goto label_299;
#line 780
label_287:
#line 781
$memory_7 = "";
#line 781
$memory_7 = c_rt_lib::ov_mk_arg('ok', $memory_7);
#line 781
undef($memory_0);
#line 781
undef($memory_1);
#line 781
undef($memory_2);
#line 781
undef($memory_4);
#line 781
undef($memory_5);
#line 781
undef($memory_6);
#line 781
$_[3] = $memory_3;return $memory_7;
#line 781
undef($memory_7);
#line 782
goto label_299;
#line 782
label_299:
#line 782
undef($memory_6);
#line 782
undef($memory_5);
#line 782
undef($memory_0);
#line 782
undef($memory_1);
#line 782
undef($memory_2);
#line 782
undef($memory_4);
#line 782
$_[3] = $memory_3;return;
$_[3] = $memory_3;}
sub compiler_priv::save_module_to_file($$) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;$memory_0 = $_[0];$memory_1 = $_[1];
#line 786
$memory_2 = c_rt_lib::ov_is($memory_1, 'nla');
#line 786
if (c_rt_lib::check_true($memory_2)) {goto label_21;}
#line 788
$memory_2 = c_rt_lib::ov_is($memory_1, 'c');
#line 788
if (c_rt_lib::check_true($memory_2)) {goto label_28;}
#line 790
$memory_2 = c_rt_lib::ov_is($memory_1, 'pm');
#line 790
if (c_rt_lib::check_true($memory_2)) {goto label_35;}
#line 792
$memory_2 = c_rt_lib::ov_is($memory_1, 'js');
#line 792
if (c_rt_lib::check_true($memory_2)) {goto label_42;}
#line 794
$memory_2 = c_rt_lib::ov_is($memory_1, 'java');
#line 794
if (c_rt_lib::check_true($memory_2)) {goto label_49;}
#line 796
$memory_2 = c_rt_lib::ov_is($memory_1, 'nl');
#line 796
if (c_rt_lib::check_true($memory_2)) {goto label_56;}
#line 798
$memory_2 = c_rt_lib::ov_is($memory_1, 'ast');
#line 798
if (c_rt_lib::check_true($memory_2)) {goto label_74;}
#line 800
$memory_2 = c_rt_lib::ov_is($memory_1, 'none');
#line 800
if (c_rt_lib::check_true($memory_2)) {goto label_92;}
#line 802
$memory_2 = c_rt_lib::ov_is($memory_1, 'call_graph');
#line 802
if (c_rt_lib::check_true($memory_2)) {goto label_97;}
#line 802
$memory_2 = "NOMATCHALERT";
#line 802
$memory_2 = [$memory_2,$memory_1];
#line 802
die(dfile::ssave($memory_2));
#line 786
label_21:
#line 786
$memory_3 = c_rt_lib::ov_as($memory_1, 'nla');
#line 787
$memory_4 = [];
#line 787
die(dfile::ssave($memory_4));
#line 787
undef($memory_4);
#line 787
undef($memory_3);
#line 788
goto label_102;
#line 788
label_28:
#line 788
$memory_3 = c_rt_lib::ov_as($memory_1, 'c');
#line 789
$memory_4 = [];
#line 789
die(dfile::ssave($memory_4));
#line 789
undef($memory_4);
#line 789
undef($memory_3);
#line 790
goto label_102;
#line 790
label_35:
#line 790
$memory_3 = c_rt_lib::ov_as($memory_1, 'pm');
#line 791
$memory_4 = [];
#line 791
die(dfile::ssave($memory_4));
#line 791
undef($memory_4);
#line 791
undef($memory_3);
#line 792
goto label_102;
#line 792
label_42:
#line 792
$memory_3 = c_rt_lib::ov_as($memory_1, 'js');
#line 793
$memory_4 = [];
#line 793
die(dfile::ssave($memory_4));
#line 793
undef($memory_4);
#line 793
undef($memory_3);
#line 794
goto label_102;
#line 794
label_49:
#line 794
$memory_3 = c_rt_lib::ov_as($memory_1, 'java');
#line 795
$memory_4 = [];
#line 795
die(dfile::ssave($memory_4));
#line 795
undef($memory_4);
#line 795
undef($memory_3);
#line 796
goto label_102;
#line 796
label_56:
#line 796
$memory_3 = c_rt_lib::ov_as($memory_1, 'nl');
#line 797
$memory_5 = {
module => "compiler",
name => "file_t",
};
#line 797
$memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5);
#line 797
$memory_7 = pretty_printer::print_module_to_str($memory_0);
#line 797
$memory_6 = c_fe_lib::string_to_file($memory_3, $memory_7);
#line 797
undef($memory_7);
#line 797
$memory_4 = ptd::ensure($memory_5, $memory_6);
#line 797
undef($memory_6);
#line 797
undef($memory_5);
#line 797
undef($memory_0);
#line 797
undef($memory_1);
#line 797
undef($memory_2);
#line 797
undef($memory_3);
#line 797
return $memory_4;
#line 797
undef($memory_4);
#line 797
undef($memory_3);
#line 798
goto label_102;
#line 798
label_74:
#line 798
$memory_3 = c_rt_lib::ov_as($memory_1, 'ast');
#line 799
$memory_5 = {
module => "compiler",
name => "file_t",
};
#line 799
$memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5);
#line 799
$memory_7 = dfile::ssave($memory_0);
#line 799
$memory_6 = c_fe_lib::string_to_file($memory_3, $memory_7);
#line 799
undef($memory_7);
#line 799
$memory_4 = ptd::ensure($memory_5, $memory_6);
#line 799
undef($memory_6);
#line 799
undef($memory_5);
#line 799
undef($memory_0);
#line 799
undef($memory_1);
#line 799
undef($memory_2);
#line 799
undef($memory_3);
#line 799
return $memory_4;
#line 799
undef($memory_4);
#line 799
undef($memory_3);
#line 800
goto label_102;
#line 800
label_92:
#line 801
$memory_3 = [];
#line 801
die(dfile::ssave($memory_3));
#line 801
undef($memory_3);
#line 802
goto label_102;
#line 802
label_97:
#line 803
$memory_3 = [];
#line 803
die(dfile::ssave($memory_3));
#line 803
undef($memory_3);
#line 804
goto label_102;
#line 804
label_102:
#line 804
undef($memory_2);
#line 804
undef($memory_0);
#line 804
undef($memory_1);
#line 804
return;
}
sub compiler_priv::get_dir($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;$memory_0 = $_[0];
#line 808
$memory_1 = string::length($memory_0);
#line 808
$memory_2 = 1;
#line 808
$memory_1 = $memory_1 - $memory_2;
#line 808
undef($memory_2);
#line 809
$memory_3 = 1;
#line 809
$memory_2 = string::substr($memory_0, $memory_1, $memory_3);
#line 809
undef($memory_3);
#line 809
$memory_3 = "/";
#line 809
$memory_2 = c_rt_lib::to_nl($memory_2 eq $memory_3);
#line 809
undef($memory_3);
#line 809
if (c_rt_lib::check_true($memory_2)) {goto label_17;}
#line 809
$memory_3 = 1;
#line 809
$memory_2 = string::substr($memory_0, $memory_1, $memory_3);
#line 809
undef($memory_3);
#line 809
$memory_3 = "\\";
#line 809
$memory_2 = c_rt_lib::to_nl($memory_2 eq $memory_3);
#line 809
undef($memory_3);
#line 809
label_17:
#line 809
$memory_2 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 809
if (c_rt_lib::check_true($memory_2)) {goto label_24;}
#line 809
$memory_3 = 1;
#line 809
$memory_1 = $memory_1 - $memory_3;
#line 809
undef($memory_3);
#line 809
goto label_24;
#line 809
label_24:
#line 809
undef($memory_2);
#line 810
label_26:
#line 810
$memory_2 = 0;
#line 810
$memory_2 = c_rt_lib::to_nl($memory_1 >= $memory_2);
#line 810
$memory_4 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 810
if (c_rt_lib::check_true($memory_4)) {goto label_37;}
#line 810
$memory_5 = 1;
#line 810
$memory_2 = string::substr($memory_0, $memory_1, $memory_5);
#line 810
undef($memory_5);
#line 810
$memory_5 = "/";
#line 810
$memory_2 = c_rt_lib::to_nl($memory_2 ne $memory_5);
#line 810
undef($memory_5);
#line 810
label_37:
#line 810
undef($memory_4);
#line 810
$memory_3 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 810
if (c_rt_lib::check_true($memory_3)) {goto label_47;}
#line 810
$memory_4 = 1;
#line 810
$memory_2 = string::substr($memory_0, $memory_1, $memory_4);
#line 810
undef($memory_4);
#line 810
$memory_4 = "\\";
#line 810
$memory_2 = c_rt_lib::to_nl($memory_2 ne $memory_4);
#line 810
undef($memory_4);
#line 810
label_47:
#line 810
undef($memory_3);
#line 810
$memory_2 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 810
if (c_rt_lib::check_true($memory_2)) {goto label_55;}
#line 810
$memory_3 = 1;
#line 810
$memory_1 = $memory_1 - $memory_3;
#line 810
undef($memory_3);
#line 810
goto label_26;
#line 810
label_55:
#line 810
undef($memory_2);
#line 811
$memory_2 = 0;
#line 811
$memory_2 = c_rt_lib::to_nl($memory_1 <= $memory_2);
#line 811
$memory_2 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_2));
#line 811
if (c_rt_lib::check_true($memory_2)) {goto label_68;}
#line 811
$memory_3 = ".";
#line 811
undef($memory_0);
#line 811
undef($memory_1);
#line 811
undef($memory_2);
#line 811
return $memory_3;
#line 811
undef($memory_3);
#line 811
goto label_68;
#line 811
label_68:
#line 811
undef($memory_2);
#line 812
$memory_3 = 0;
#line 812
$memory_2 = string::substr($memory_0, $memory_3, $memory_1);
#line 812
undef($memory_3);
#line 812
undef($memory_0);
#line 812
undef($memory_1);
#line 812
return $memory_2;
#line 812
undef($memory_2);
#line 812
undef($memory_1);
#line 812
undef($memory_0);
#line 812
return;
}
sub compiler_priv::parse_command_line_args($) {
my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6;my $memory_7;my $memory_8;my $memory_9;my $memory_10;my $memory_11;my $memory_12;$memory_0 = $_[0];
#line 817
$memory_2 = c_rt_lib::ov_mk_none('c');
#line 818
$memory_3 = c_rt_lib::ov_mk_none('strict');
#line 819
$memory_5 = ".";
#line 819
$memory_4 = [$memory_5];
#line 819
undef($memory_5);
#line 820
$memory_5 = c_rt_lib::ov_mk_none('o1');
#line 821
$memory_6 = c_rt_lib::ov_mk_none('no');
#line 822
$memory_7 = compiler_priv::get_default_math_file();
#line 823
$memory_8 = "";
#line 824
$memory_9 = c_rt_lib::ov_mk_none('norm');
#line 825
$memory_10 = c_rt_lib::to_nl(0);
#line 826
$memory_11 = c_rt_lib::to_nl(0);
#line 826
$memory_1 = {language => $memory_2,mode => $memory_3,input_path => $memory_4,optimization => $memory_5,deref => $memory_6,math_fun => $memory_7,cache_path => $memory_8,alarm => $memory_9,check_public_fun => $memory_10,profile => $memory_11,};
#line 826
undef($memory_2);
#line 826
undef($memory_3);
#line 826
undef($memory_4);
#line 826
undef($memory_5);
#line 826
undef($memory_6);
#line 826
undef($memory_7);
#line 826
undef($memory_8);
#line 826
undef($memory_9);
#line 826
undef($memory_10);
#line 826
undef($memory_11);
#line 828
$memory_2 = c_rt_lib::to_nl(0);
#line 829
$memory_3 = compiler_priv::get_dir_cache_name();
#line 830
$memory_4 = 1;
#line 830
label_26:
#line 830
$memory_5 = array::len($memory_0);
#line 830
$memory_5 = c_rt_lib::to_nl($memory_4 < $memory_5);
#line 830
$memory_5 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_5));
#line 830
if (c_rt_lib::check_true($memory_5)) {goto label_444;}
#line 831
$memory_6 = $memory_0->[$memory_4];
#line 832
$memory_7 = string::length($memory_6);
#line 832
$memory_9 = 2;
#line 832
$memory_7 = c_rt_lib::to_nl($memory_7 >= $memory_9);
#line 832
undef($memory_9);
#line 832
$memory_8 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_7));
#line 832
if (c_rt_lib::check_true($memory_8)) {goto label_46;}
#line 832
$memory_9 = 0;
#line 832
$memory_10 = 2;
#line 832
$memory_7 = string::substr($memory_6, $memory_9, $memory_10);
#line 832
undef($memory_10);
#line 832
undef($memory_9);
#line 832
$memory_9 = "--";
#line 832
$memory_7 = c_rt_lib::to_nl($memory_7 eq $memory_9);
#line 832
undef($memory_9);
#line 832
label_46:
#line 832
undef($memory_8);
#line 832
$memory_7 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_7));
#line 832
if (c_rt_lib::check_true($memory_7)) {goto label_413;}
#line 833
$memory_9 = 2;
#line 833
$memory_10 = string::length($memory_6);
#line 833
$memory_11 = 2;
#line 833
$memory_10 = $memory_10 - $memory_11;
#line 833
undef($memory_11);
#line 833
$memory_8 = string::substr($memory_6, $memory_9, $memory_10);
#line 833
undef($memory_10);
#line 833
undef($memory_9);
#line 834
$memory_9 = "deref";
#line 834
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 834
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 834
if (c_rt_lib::check_true($memory_9)) {goto label_69;}
#line 835
$memory_10 = "";
#line 835
$memory_10 = c_rt_lib::ov_mk_arg('yes', $memory_10);
#line 835
$memory_11 = $memory_10;
#line 835
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'deref'} = $memory_11;
#line 835
undef($memory_10);
#line 835
undef($memory_11);
#line 836
goto label_409;
#line 836
label_69:
#line 836
$memory_9 = "nla";
#line 836
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 836
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 836
if (c_rt_lib::check_true($memory_9)) {goto label_80;}
#line 837
$memory_10 = c_rt_lib::ov_mk_none('nla');
#line 837
$memory_11 = $memory_10;
#line 837
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 837
undef($memory_10);
#line 837
undef($memory_11);
#line 838
goto label_409;
#line 838
label_80:
#line 838
$memory_9 = "ast";
#line 838
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 838
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 838
if (c_rt_lib::check_true($memory_9)) {goto label_91;}
#line 839
$memory_10 = c_rt_lib::ov_mk_none('ast');
#line 839
$memory_11 = $memory_10;
#line 839
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 839
undef($memory_10);
#line 839
undef($memory_11);
#line 840
goto label_409;
#line 840
label_91:
#line 840
$memory_9 = "pm";
#line 840
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 840
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 840
if (c_rt_lib::check_true($memory_9)) {goto label_102;}
#line 841
$memory_10 = c_rt_lib::ov_mk_none('pm');
#line 841
$memory_11 = $memory_10;
#line 841
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 841
undef($memory_10);
#line 841
undef($memory_11);
#line 842
goto label_409;
#line 842
label_102:
#line 842
$memory_9 = "c";
#line 842
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 842
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 842
if (c_rt_lib::check_true($memory_9)) {goto label_113;}
#line 843
$memory_10 = c_rt_lib::ov_mk_none('c');
#line 843
$memory_11 = $memory_10;
#line 843
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 843
undef($memory_10);
#line 843
undef($memory_11);
#line 844
goto label_409;
#line 844
label_113:
#line 844
$memory_9 = "js";
#line 844
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 844
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 844
if (c_rt_lib::check_true($memory_9)) {goto label_135;}
#line 845
$memory_10 = $memory_1->{'language'};
#line 845
$memory_10 = c_rt_lib::ov_is($memory_10, 'js');
#line 845
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 845
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 845
if (c_rt_lib::check_true($memory_10)) {goto label_132;}
#line 846
$memory_12 = "nl";
#line 846
$memory_11 = {namespace => $memory_12,};
#line 846
undef($memory_12);
#line 846
$memory_11 = c_rt_lib::ov_mk_arg('js', $memory_11);
#line 846
$memory_12 = $memory_11;
#line 846
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_12;
#line 846
undef($memory_11);
#line 846
undef($memory_12);
#line 847
goto label_132;
#line 847
label_132:
#line 847
undef($memory_10);
#line 848
goto label_409;
#line 848
label_135:
#line 848
$memory_9 = "call_graph";
#line 848
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 848
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 848
if (c_rt_lib::check_true($memory_9)) {goto label_146;}
#line 849
$memory_10 = c_rt_lib::ov_mk_none('call_graph');
#line 849
$memory_11 = $memory_10;
#line 849
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 849
undef($memory_10);
#line 849
undef($memory_11);
#line 850
goto label_409;
#line 850
label_146:
#line 850
$memory_9 = "java";
#line 850
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 850
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 850
if (c_rt_lib::check_true($memory_9)) {goto label_157;}
#line 851
$memory_10 = c_rt_lib::ov_mk_none('java');
#line 851
$memory_11 = $memory_10;
#line 851
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 851
undef($memory_10);
#line 851
undef($memory_11);
#line 852
goto label_409;
#line 852
label_157:
#line 852
$memory_9 = "nl";
#line 852
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 852
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 852
if (c_rt_lib::check_true($memory_9)) {goto label_171;}
#line 853
$memory_10 = c_rt_lib::ov_mk_none('nl');
#line 853
$memory_11 = $memory_10;
#line 853
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 853
undef($memory_10);
#line 853
undef($memory_11);
#line 854
$memory_10 = compiler_priv::get_dir_pretty_name();
#line 854
$memory_3 = $memory_10;
#line 854
undef($memory_10);
#line 855
goto label_409;
#line 855
label_171:
#line 855
$memory_9 = "ide";
#line 855
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 855
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 855
if (c_rt_lib::check_true($memory_9)) {goto label_182;}
#line 856
$memory_10 = c_rt_lib::ov_mk_none('ide');
#line 856
$memory_11 = $memory_10;
#line 856
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'mode'} = $memory_11;
#line 856
undef($memory_10);
#line 856
undef($memory_11);
#line 857
goto label_409;
#line 857
label_182:
#line 857
$memory_9 = "idex";
#line 857
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 857
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 857
if (c_rt_lib::check_true($memory_9)) {goto label_208;}
#line 858
$memory_10 = 1;
#line 858
$memory_4 = $memory_4 + $memory_10;
#line 858
undef($memory_10);
#line 859
$memory_10 = array::len($memory_0);
#line 859
$memory_10 = c_rt_lib::to_nl($memory_4 < $memory_10);
#line 859
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 859
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 859
if (c_rt_lib::check_true($memory_10)) {goto label_198;}
#line 859
$memory_11 = [];
#line 859
die(dfile::ssave($memory_11));
#line 859
goto label_198;
#line 859
label_198:
#line 859
undef($memory_10);
#line 859
undef($memory_11);
#line 860
$memory_10 = $memory_0->[$memory_4];
#line 860
$memory_10 = c_rt_lib::ov_mk_arg('idex', $memory_10);
#line 860
$memory_11 = $memory_10;
#line 860
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'mode'} = $memory_11;
#line 860
undef($memory_10);
#line 860
undef($memory_11);
#line 861
goto label_409;
#line 861
label_208:
#line 861
$memory_9 = "strict";
#line 861
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 861
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 861
if (c_rt_lib::check_true($memory_9)) {goto label_219;}
#line 862
$memory_10 = c_rt_lib::ov_mk_none('strict');
#line 862
$memory_11 = $memory_10;
#line 862
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'mode'} = $memory_11;
#line 862
undef($memory_10);
#line 862
undef($memory_11);
#line 863
goto label_409;
#line 863
label_219:
#line 863
$memory_9 = "exec";
#line 863
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 863
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 863
if (c_rt_lib::check_true($memory_9)) {goto label_230;}
#line 864
$memory_10 = c_rt_lib::ov_mk_none('exec');
#line 864
$memory_11 = $memory_10;
#line 864
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'mode'} = $memory_11;
#line 864
undef($memory_10);
#line 864
undef($memory_11);
#line 865
goto label_409;
#line 865
label_230:
#line 865
$memory_9 = "o";
#line 865
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 865
if (c_rt_lib::check_true($memory_9)) {goto label_236;}
#line 865
$memory_9 = "out";
#line 865
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 865
label_236:
#line 865
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 865
if (c_rt_lib::check_true($memory_9)) {goto label_262;}
#line 866
$memory_10 = 1;
#line 866
$memory_4 = $memory_4 + $memory_10;
#line 866
undef($memory_10);
#line 867
$memory_10 = array::len($memory_0);
#line 867
$memory_10 = c_rt_lib::to_nl($memory_4 < $memory_10);
#line 867
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 867
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 867
if (c_rt_lib::check_true($memory_10)) {goto label_250;}
#line 867
$memory_11 = [];
#line 867
die(dfile::ssave($memory_11));
#line 867
goto label_250;
#line 867
label_250:
#line 867
undef($memory_10);
#line 867
undef($memory_11);
#line 868
$memory_10 = $memory_0->[$memory_4];
#line 868
$memory_11 = "/";
#line 868
$memory_10 = $memory_10 . $memory_11;
#line 868
undef($memory_11);
#line 868
$memory_11 = $memory_10;
#line 868
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'cache_path'} = $memory_11;
#line 868
undef($memory_10);
#line 868
undef($memory_11);
#line 869
goto label_409;
#line 869
label_262:
#line 869
$memory_9 = "math";
#line 869
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 869
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 869
if (c_rt_lib::check_true($memory_9)) {goto label_287;}
#line 870
$memory_10 = 1;
#line 870
$memory_4 = $memory_4 + $memory_10;
#line 870
undef($memory_10);
#line 871
$memory_10 = array::len($memory_0);
#line 871
$memory_10 = c_rt_lib::to_nl($memory_4 < $memory_10);
#line 871
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 871
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 871
if (c_rt_lib::check_true($memory_10)) {goto label_278;}
#line 871
$memory_11 = [];
#line 871
die(dfile::ssave($memory_11));
#line 871
goto label_278;
#line 871
label_278:
#line 871
undef($memory_10);
#line 871
undef($memory_11);
#line 872
$memory_10 = $memory_0->[$memory_4];
#line 872
$memory_11 = $memory_10;
#line 872
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'math_fun'} = $memory_11;
#line 872
undef($memory_10);
#line 872
undef($memory_11);
#line 873
goto label_409;
#line 873
label_287:
#line 873
$memory_9 = "O0";
#line 873
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 873
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 873
if (c_rt_lib::check_true($memory_9)) {goto label_298;}
#line 874
$memory_10 = c_rt_lib::ov_mk_none('o0');
#line 874
$memory_11 = $memory_10;
#line 874
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'optimization'} = $memory_11;
#line 874
undef($memory_10);
#line 874
undef($memory_11);
#line 875
goto label_409;
#line 875
label_298:
#line 875
$memory_9 = "O1";
#line 875
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 875
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 875
if (c_rt_lib::check_true($memory_9)) {goto label_309;}
#line 876
$memory_10 = c_rt_lib::ov_mk_none('o1');
#line 876
$memory_11 = $memory_10;
#line 876
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'optimization'} = $memory_11;
#line 876
undef($memory_10);
#line 876
undef($memory_11);
#line 877
goto label_409;
#line 877
label_309:
#line 877
$memory_9 = "O2";
#line 877
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 877
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 877
if (c_rt_lib::check_true($memory_9)) {goto label_320;}
#line 878
$memory_10 = c_rt_lib::ov_mk_none('o2');
#line 878
$memory_11 = $memory_10;
#line 878
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'optimization'} = $memory_11;
#line 878
undef($memory_10);
#line 878
undef($memory_11);
#line 879
goto label_409;
#line 879
label_320:
#line 879
$memory_9 = "O3";
#line 879
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 879
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 879
if (c_rt_lib::check_true($memory_9)) {goto label_331;}
#line 880
$memory_10 = c_rt_lib::ov_mk_none('o3');
#line 880
$memory_11 = $memory_10;
#line 880
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'optimization'} = $memory_11;
#line 880
undef($memory_10);
#line 880
undef($memory_11);
#line 881
goto label_409;
#line 881
label_331:
#line 881
$memory_9 = "O4";
#line 881
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 881
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 881
if (c_rt_lib::check_true($memory_9)) {goto label_342;}
#line 882
$memory_10 = c_rt_lib::ov_mk_none('o4');
#line 882
$memory_11 = $memory_10;
#line 882
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'optimization'} = $memory_11;
#line 882
undef($memory_10);
#line 882
undef($memory_11);
#line 883
goto label_409;
#line 883
label_342:
#line 883
$memory_9 = "Wall";
#line 883
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 883
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 883
if (c_rt_lib::check_true($memory_9)) {goto label_353;}
#line 884
$memory_10 = c_rt_lib::ov_mk_none('wall');
#line 884
$memory_11 = $memory_10;
#line 884
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'alarm'} = $memory_11;
#line 884
undef($memory_10);
#line 884
undef($memory_11);
#line 885
goto label_409;
#line 885
label_353:
#line 885
$memory_9 = "check_public_fun";
#line 885
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 885
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 885
if (c_rt_lib::check_true($memory_9)) {goto label_364;}
#line 886
$memory_10 = c_rt_lib::to_nl(1);
#line 886
$memory_11 = $memory_10;
#line 886
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'check_public_fun'} = $memory_11;
#line 886
undef($memory_10);
#line 886
undef($memory_11);
#line 887
goto label_409;
#line 887
label_364:
#line 887
$memory_9 = "profile";
#line 887
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 887
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 887
if (c_rt_lib::check_true($memory_9)) {goto label_375;}
#line 888
$memory_10 = c_rt_lib::to_nl(1);
#line 888
$memory_11 = $memory_10;
#line 888
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'profile'} = $memory_11;
#line 888
undef($memory_10);
#line 888
undef($memory_11);
#line 889
goto label_409;
#line 889
label_375:
#line 889
$memory_9 = "namespace";
#line 889
$memory_9 = c_rt_lib::to_nl($memory_8 eq $memory_9);
#line 889
$memory_9 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_9));
#line 889
if (c_rt_lib::check_true($memory_9)) {goto label_403;}
#line 890
$memory_10 = 1;
#line 890
$memory_4 = $memory_4 + $memory_10;
#line 890
undef($memory_10);
#line 891
$memory_10 = array::len($memory_0);
#line 891
$memory_10 = c_rt_lib::to_nl($memory_4 < $memory_10);
#line 891
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 891
$memory_10 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_10));
#line 891
if (c_rt_lib::check_true($memory_10)) {goto label_391;}
#line 891
$memory_11 = [];
#line 891
die(dfile::ssave($memory_11));
#line 891
goto label_391;
#line 891
label_391:
#line 891
undef($memory_10);
#line 891
undef($memory_11);
#line 892
$memory_11 = $memory_0->[$memory_4];
#line 892
$memory_10 = {namespace => $memory_11,};
#line 892
undef($memory_11);
#line 892
$memory_10 = c_rt_lib::ov_mk_arg('js', $memory_10);
#line 892
$memory_11 = $memory_10;
#line 892
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'language'} = $memory_11;
#line 892
undef($memory_10);
#line 892
undef($memory_11);
#line 893
goto label_409;
#line 893
label_403:
#line 894
$memory_10 = "unknown compiler option: ";
#line 894
$memory_10 = $memory_10 . $memory_6;
#line 894
c_fe_lib::print($memory_10);
#line 894
undef($memory_10);
#line 895
goto label_409;
#line 895
label_409:
#line 895
undef($memory_9);
#line 895
undef($memory_8);
#line 896
goto label_437;
#line 896
label_413:
#line 897
$memory_8 = $memory_2;
#line 897
$memory_8 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_8));
#line 897
$memory_8 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_8));
#line 897
if (c_rt_lib::check_true($memory_8)) {goto label_424;}
#line 897
$memory_9 = [];
#line 897
$memory_10 = $memory_9;
#line 897
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'input_path'} = $memory_10;
#line 897
undef($memory_9);
#line 897
undef($memory_10);
#line 897
goto label_424;
#line 897
label_424:
#line 897
undef($memory_8);
#line 898
$memory_8 = "input_path";
#line 898
$memory_8 = c_rt_lib::get_ref_hash($memory_1, $memory_8);
#line 898
array::push($memory_8, $memory_6);
#line 898
$memory_9 = "input_path";
#line 898
c_rt_lib::set_ref_hash($memory_1, $memory_9, $memory_8);
#line 898
undef($memory_9);
#line 898
undef($memory_8);
#line 899
$memory_8 = c_rt_lib::to_nl(1);
#line 899
$memory_2 = $memory_8;
#line 899
undef($memory_8);
#line 900
goto label_437;
#line 900
label_437:
#line 900
undef($memory_7);
#line 900
undef($memory_6);
#line 830
$memory_6 = 1;
#line 830
$memory_4 = $memory_4 + $memory_6;
#line 830
undef($memory_6);
#line 901
goto label_26;
#line 901
label_444:
#line 901
undef($memory_4);
#line 901
undef($memory_5);
#line 902
$memory_4 = $memory_1->{'cache_path'};
#line 902
$memory_5 = "";
#line 902
$memory_4 = c_rt_lib::to_nl($memory_4 eq $memory_5);
#line 902
undef($memory_5);
#line 902
$memory_4 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_4));
#line 902
if (c_rt_lib::check_true($memory_4)) {goto label_463;}
#line 903
$memory_5 = "./";
#line 903
$memory_5 = $memory_5 . $memory_3;
#line 903
$memory_6 = "/";
#line 903
$memory_5 = $memory_5 . $memory_6;
#line 903
undef($memory_6);
#line 903
$memory_6 = $memory_5;
#line 903
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'cache_path'} = $memory_6;
#line 903
undef($memory_5);
#line 903
undef($memory_6);
#line 904
goto label_463;
#line 904
label_463:
#line 904
undef($memory_4);
#line 905
$memory_4 = $memory_1->{'deref'};
#line 905
$memory_4 = c_rt_lib::ov_is($memory_4, 'yes');
#line 905
$memory_4 = c_rt_lib::to_nl(!c_rt_lib::check_true($memory_4));
#line 905
if (c_rt_lib::check_true($memory_4)) {goto label_479;}
#line 905
$memory_5 = $memory_1->{'cache_path'};
#line 905
$memory_6 = compiler_priv::get_default_deref_file();
#line 905
$memory_5 = $memory_5 . $memory_6;
#line 905
undef($memory_6);
#line 905
$memory_5 = c_rt_lib::ov_mk_arg('yes', $memory_5);
#line 905
$memory_6 = $memory_5;
#line 905
if (c_rt_lib::get_hashcount($memory_1) > 1) {$memory_1 = {%{$memory_1}};}$memory_1->{'deref'} = $memory_6;
#line 905
undef($memory_5);
#line 905
undef($memory_6);
#line 905
goto label_479;
#line 905
label_479:
#line 905
undef($memory_4);
#line 906
undef($memory_0);
#line 906
undef($memory_2);
#line 906
undef($memory_3);
#line 906
return $memory_1;
#line 906
undef($memory_1);
#line 906
undef($memory_2);
#line 906
undef($memory_3);
#line 906
undef($memory_0);
#line 906
return;
}
| nianiolang/nl | bin/nianio_lang_pm/compiler.pm | Perl | mit | 161,828 |
package ITS::WICS::XML2XLIFF;
use strict;
use warnings;
use Carp;
our @CARP_NOT = qw(ITS);
use Log::Any qw($log);
use ITS qw(its_ns);
use ITS::DOM;
use ITS::DOM::Element qw(new_element);
use ITS::WICS::LogUtils qw(node_log_id log_match);
use ITS::WICS::XML2XLIFF::ITSProcessor qw(
its_requires_inline
convert_atts
localize_rules
transfer_inline_its
);
use ITS::WICS::XML2XLIFF::ITSSegmenter qw(extract_convert_its);
use ITS::WICS::XML2XLIFF::CustomSegmenter qw(extract_convert_custom);
our $XLIFF_NS = 'urn:oasis:names:tc:xliff:document:1.2';
our $ITSXLF_NS = 'http://www.w3.org/ns/its-xliff/';
# ABSTRACT: Extract ITS-decorated XML into XLIFF
# VERSION
#default: convert and print input
print ${ __PACKAGE__->new()->convert($ARGV[0]) } unless caller;
=head1 SYNOPSIS
use ITS;
use ITS::WICS::XML2XLIFF;
my $converter = ITS::WICS::XML2XLIFF->new('Page Title');
my $ITS = ITS->new('xml', doc => \'<xml>some text</xml>');
my $result = $converter->convert(
$ITS, group => ['sec'], tu => ['para']);
print $$result;
=head1 DESCRIPTION
This module extracts strings from an XML file to create an XLIFF file,
keeping the original ITS information intact.
=head1 CAVEATS
This module is very preliminary, and there are plenty of things to
implement still. Only a few ITS data categories are converted, and no
inherited ITS information is saved. Also, the ITS segmentation scheme
is currently not very developed and may produce invalid XLIFF.
=head1 SEE ALSO
This module relies on the L<ITS> module for processing ITS markup and rules.
The ITS 2.0 specification for XML and HTML5: L<http://www.w3.org/TR/its20/>.
The spec for representing ITS in XLIFF:
L<http://www.w3.org/International/its/wiki/XLIFF_1.2_Mapping>.
ITS interest group mail archives:
L<http://lists.w3.org/Archives/Public/public-i18n-its-ig/>
=head1 METHODS
=head2 C<new>
Creates a new converter instance.
=cut
sub new {
my ($class) = @_;
return bless {}, $class;
}
=head2 C<convert>
Extracts strings from the input ITS object containing an XML document
into an XLIFF document, preserving ITS information.
Return value is a string pointer containing the output XLIFF string.
There are two segmentation schemes: the default behavior is to extract
all strings in the document, using ITS C<withinText> values (currently
only implemented with local markup) to decide which elements are inline
or structural.
You may also pass in C<tu> and C<group> parameters after the ITS document
to get a different segmentation behavior. Each parameter should be an
array ref containing names of elements to be used for extracting
C<trans-unit>s and C<group>s, repsectively. Children of C<trans-unit>s are
placed escaped and placed as-is (tags and all) in C<ph> tags. If no C<group>
element names are specified, then C<trans-units> for the whole document are
placed in one C<group>.
For example, the following will extract C<para> elements and their children
as C<trans-units>, and place them in groups with other C<trans-units> extracted
from the same C<sec> elements:
my $xliff = $XML2XLIFF->convert($ITS, group => ['sec'], tu => ['para']);
=cut
sub convert {
my ($self, $ITS, %seg) = @_;
if($ITS->get_doc_type ne 'xml'){
croak 'Cannot process document of type ' . $ITS->get_doc_type;
}
my $doc = $ITS->get_doc;
if(!_is_legal_doc($doc)){
croak 'cannot process a file with ITS element ' .
'as root (except span). Include this file within ' .
'another ITS document instead.';
}
# Check if segmentation rules were provided
# TODO: check input a little better
if(keys %seg){
$self->{group_els} = $seg{group} or
$log->info('Group elements not specified');
$self->{tu_els} = $seg{tu} or
croak 'Trans-unit elements not specified';
$self->{seg} = 'custom';
}else{
$self->{seg} = 'its';
}
$self->{match_index} = {};
#iterate all document rules and their matches, indexing each one
for my $rule (@{ $ITS->get_rules }){
my $matches = $ITS->get_matches($rule);
$self->_index_match($rule, $_) for @$matches;
}
# extract $doc into an XLIFF document;
my ($xlf_doc) = $self->_xlfize($doc);
return \($xlf_doc->string);
}
# returns true if the root of the given document not an ITS element
# (or is an ITS span element)
sub _is_legal_doc {
my ($doc) = @_;
my $root = $doc->get_root;
if($root->namespace_URI eq its_ns() &&
$root->local_name ne 'span'){
return 0;
}
return 1;
}
# index a single set of rule matches
# This sub saves ITS info in $self like so:
# $self->{match_index}->{$node->unique_key}->{its name} = "its value"
sub _index_match {
my ($self, $rule, $matches) = @_;
log_match($rule, $matches, $log);
my $node = $matches->{selector};
delete $matches->{selector};
# create a hash containing all ITS info given to the selected node
my $its_info = {};
for my $att (@{ $rule->value_atts }){
$its_info->{$att} = $rule->element->att($att);
}
#for <its:locNote> or similar (in future ITS standards)
if(my @children = @{ $rule->element->child_els }){
for (@children){
$its_info->{$_->local_name} = $_->text;
}
}
# $name is 'selector', 'locNotePointer', etc.
# Store string its_info for all pointer matches
while (my ($name, $match) = each %$matches) {
$name =~ s/Pointer$//;
if((ref $match) =~ /Value$/){
$its_info->{$name} = $match->value;
}elsif($match->type eq 'ELT'){
$its_info->{$name} = $match->text;
}else{
$its_info->{$name} = $match->value;
}
}
# merge the new ITS info with whatever ITS info may already exist
# for the given node
@{ $self->{match_index}->{$node->unique_key} }{keys %$its_info} =
values %$its_info;
return;
}
# Pass in document to be the source of an XLIFF file and segmentation arguments
# return the new XLIFF document
sub _xlfize {
my ($self, $doc) = @_;
# traverse every document element, extracting text for trans-units
# and saving standoff/rules markup
if($self->{seg} eq 'its'){
$log->debug('Segmenting document using ITS metadata');
($self->{tu}, $self->{its_els}) =
extract_convert_its($doc->get_root, $self->{match_index});
}else{
$log->debug('Segmenting document using custom rules');
($self->{tu}, $self->{its_els}) =
extract_convert_custom(
$doc->get_root,
$self->{group_els},
$self->{tu_els},
$self->{match_index}
);
}
return $self->_xliff_structure($doc->get_source);
}
# Place extracted translation units into an XLIFF skeleton, and
# standoff markup into header element.
# Single argument is the source of the original document.
# The XLIFF document is returned.
sub _xliff_structure {
my ($self, $source) = @_;
$log->debug('wrapping document in XLIFF structure')
if $log->is_debug;
#put its and itsxlf namespace declarations in root, and its:version
my $xlf_doc = ITS::DOM->new(
'xml', \("<xliff xmlns='$XLIFF_NS' xmlns:itsxlf='$ITSXLF_NS' " .
'xmlns:its="' . its_ns() . q<" > .
"its:version='2.0'/>"));
my $root = $xlf_doc->get_root;
my $file = new_element('file', {
datatype => 'plaintext',
original => $source,
'source-language' => 'en'
}
);
$file->set_namespace($XLIFF_NS);
$file->paste($root);
my $body = new_element('body');
$body->set_namespace($XLIFF_NS);
$body->paste($file);
# paste all trans-unit/group elements
$_->paste($body) for @{ $self->{tu} };
if(@{ $self->{its_els} }){
my $header = new_element('header');
$header->set_namespace($XLIFF_NS);
$header->paste($file);
# paste all standoff markup
$_->paste($header) for @{ $self->{its_els} };
}
return ($xlf_doc);
}
1; | renatb/ITS2.0-WICS-converter | lib/ITS/WICS/XML2XLIFF.pm | Perl | mit | 7,787 |
# File: Updater.pm
#
# Purpose: Migrates data files from older versions to newer versions.
#
# Updates data/configration files to new locations/formats based
# on versioning information. Ensures data/configuration files are in the
# proper location and using the latest data structure.
# SPDX-FileCopyrightText: 2021 Pragmatic Software <pragma78@gmail.com>
# SPDX-License-Identifier: MIT
package PBot::Core::Updater;
use parent 'PBot::Core::Class';
use PBot::Imports;
use File::Basename;
sub initialize {
my ($self, %conf) = @_;
$self->{data_dir} = $conf{data_dir};
$self->{update_dir} = $conf{update_dir};
}
sub update {
my ($self) = @_;
$self->{pbot}->{logger}->log("Checking if update needed...\n");
my $current_version = $self->get_current_version;
my $last_update_version = $self->get_last_update_version;
$self->{pbot}->{logger}->log("Current version: $current_version; last update version: $last_update_version\n");
if ($last_update_version >= $current_version) {
$self->{pbot}->{logger}->log("No update necessary.\n");
return $self->put_last_update_version($current_version);
}
my @updates = $self->get_available_updates($last_update_version);
if (not @updates ) {
$self->{pbot}->{logger}->log("No updates available.\n");
return $self->put_last_update_version($current_version);
}
foreach my $update (@updates) {
$self->{pbot}->{logger}->log("Executing update script: $update\n");
my $output = `$update "$self->{data_dir}" $current_version $last_update_version`;
my $exit = $? >> 8;
foreach my $line (split /\n/, $output) {
$self->{pbot}->{logger}->log(" $line\n");
}
$self->{pbot}->{logger}->log("Update script completed " . ($exit ? "unsuccessfully (exit $exit)" : 'successfully') . "\n");
return $exit if $exit != 0;
}
return $self->put_last_update_version($current_version);
}
sub get_available_updates {
my ($self, $last_update_version) = @_;
my @updates = sort glob "$self->{update_dir}/*.pl";
return grep { my ($version) = split /_/, basename $_; $version > $last_update_version } @updates;
}
sub get_current_version {
return PBot::VERSION::BUILD_REVISION;
}
sub get_last_update_version {
my ($self) = @_;
open(my $fh, '<', "$self->{data_dir}/last_update") or return 0;
chomp(my $last_update = <$fh>);
close $fh;
return $last_update;
}
sub put_last_update_version {
my ($self, $version) = @_;
if (open(my $fh, '>', "$self->{data_dir}/last_update")) {
print $fh "$version\n";
close $fh;
return 0;
} else {
$self->{pbot}->{logger}->log("Could not save last update version to $self->{data_dir}/last_update: $!\n");
return 1;
}
}
1;
| pragma-/pbot | lib/PBot/Core/Updater.pm | Perl | mit | 2,826 |
#!/usr/bin/perl -w
use strict;
use Irssi;
use Irssi::Irc;
sub handle_cmd {
my ($server, $msg, $nick, $address, $target) = @_;
if ($msg eq ".eatpizza") {
$server->command("msg $target .............................................pizza");
}
if ($msg eq ".payback") {
$server->command("msg $target ($nick) PAYBACK IS TODAY!");
}
if ($msg eq ".lenny" && $target eq "#metal") {
$server->command("msg $target ( ͡° ͜ʖ ͡°)");
}
}
Irssi::signal_add('message public', 'handle_cmd');
| n7st/irssi-scripts | pizza/pizza-extra.pl | Perl | mit | 499 |
#------------------------------------------------------------------------------
# File: PanasonicRaw.pm
#
# Description: Read/write Panasonic/Leica RAW/RW2/RWL meta information
#
# Revisions: 2009/03/24 - P. Harvey Created
# 2009/05/12 - PH Added RWL file type (same format as RW2)
#
# References: 1) CPAN forum post by 'hardloaf' (http://www.cpanforum.com/threads/2183)
# 2) http://www.cybercom.net/~dcoffin/dcraw/
# 3) http://syscall.eu/#pana
# 4) Iliah Borg private communication (LibRaw)
# JD) Jens Duttke private communication (TZ3,FZ30,FZ50)
#------------------------------------------------------------------------------
package Image::ExifTool::PanasonicRaw;
use strict;
use vars qw($VERSION);
use Image::ExifTool qw(:DataAccess :Utils);
use Image::ExifTool::Exif;
$VERSION = '1.09';
sub ProcessJpgFromRaw($$$);
sub WriteJpgFromRaw($$$);
sub WriteDistortionInfo($$$);
sub ProcessDistortionInfo($$$);
my %jpgFromRawMap = (
IFD1 => 'IFD0',
EXIF => 'IFD0', # to write EXIF as a block
ExifIFD => 'IFD0',
GPS => 'IFD0',
SubIFD => 'IFD0',
GlobParamIFD => 'IFD0',
PrintIM => 'IFD0',
InteropIFD => 'ExifIFD',
MakerNotes => 'ExifIFD',
IFD0 => 'APP1',
MakerNotes => 'ExifIFD',
Comment => 'COM',
);
my %wbTypeInfo = (
PrintConv => \%Image::ExifTool::Exif::lightSource,
SeparateTable => 'EXIF LightSource',
);
# Tags found in Panasonic RAW/RW2/RWL images (ref PH)
%Image::ExifTool::PanasonicRaw::Main = (
GROUPS => { 0 => 'EXIF', 1 => 'IFD0', 2 => 'Image'},
WRITE_PROC => \&Image::ExifTool::Exif::WriteExif,
CHECK_PROC => \&Image::ExifTool::Exif::CheckExif,
WRITE_GROUP => 'IFD0', # default write group
NOTES => 'These tags are found in IFD0 of Panasonic/Leica RAW, RW2 and RWL images.',
0x01 => {
Name => 'PanasonicRawVersion',
Writable => 'undef',
},
0x02 => 'SensorWidth', #1/PH
0x03 => 'SensorHeight', #1/PH
0x04 => 'SensorTopBorder', #JD
0x05 => 'SensorLeftBorder', #JD
0x06 => 'SensorBottomBorder', #PH
0x07 => 'SensorRightBorder', #PH
# observed values for unknown tags - PH
# 0x08: 1
# 0x09: 1,3,4
# 0x0a: 12
0x08 => { #4
Name => 'BlackLevel1',
Writable => 'int16u',
Notes => q{
summing BlackLevel1+2+3 values gives the common bias that must be added to
the BlackLevelRed/Green/Blue tags below
},
},
0x09 => { Name => 'BlackLevel2', Writable => 'int16u' }, #4
0x0a => { Name => 'BlackLevel3', Writable => 'int16u' }, #4
# 0x0b: 0x860c,0x880a,0x880c
# 0x0c: 2 (only Leica Digilux 2)
# 0x0d: 0,1
# 0x0e,0x0f,0x10: 4095
0x0e => { Name => 'LinearityLimitRed', Writable => 'int16u' }, #4
0x0f => { Name => 'LinearityLimitGreen', Writable => 'int16u' }, #4
0x10 => { Name => 'LinearityLimitBlue', Writable => 'int16u' }, #4
0x11 => { #JD
Name => 'RedBalance',
Writable => 'int16u',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + 0.5)',
Notes => 'found in Digilux 2 RAW images',
},
0x12 => { #JD
Name => 'BlueBalance',
Writable => 'int16u',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + 0.5)',
},
0x13 => { #4
Name => 'WBInfo',
SubDirectory => { TagTable => 'Image::ExifTool::PanasonicRaw::WBInfo' },
},
0x17 => { #1
Name => 'ISO',
Writable => 'int16u',
},
# 0x18,0x19,0x1a: 0
0x18 => { #4
Name => 'HighISOMultiplierRed',
Writable => 'int16u',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + 0.5)',
},
0x19 => { #4
Name => 'HighISOMultiplierGreen',
Writable => 'int16u',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + 0.5)',
},
0x1a => { #4
Name => 'HighISOMultiplierBlue',
Writable => 'int16u',
ValueConv => '$val / 256',
ValueConvInv => 'int($val * 256 + 0.5)',
},
# 0x1b: [binary data] (something to do with the camera ISO cababilities: int16u count N,
# followed by table of N entries: int16u ISO, int16u[3] RGB gains - ref 4)
0x1c => { Name => 'BlackLevelRed', Writable => 'int16u' }, #4
0x1d => { Name => 'BlackLevelGreen', Writable => 'int16u' }, #4
0x1e => { Name => 'BlackLevelBlue', Writable => 'int16u' }, #4
0x24 => { #2
Name => 'WBRedLevel',
Writable => 'int16u',
},
0x25 => { #2
Name => 'WBGreenLevel',
Writable => 'int16u',
},
0x26 => { #2
Name => 'WBBlueLevel',
Writable => 'int16u',
},
0x27 => { #4
Name => 'WBInfo2',
SubDirectory => { TagTable => 'Image::ExifTool::PanasonicRaw::WBInfo2' },
},
# 0x27,0x29,0x2a,0x2b,0x2c: [binary data]
# 0x2d: 2,3
0x2e => { #JD
Name => 'JpgFromRaw', # (writable directory!)
Groups => { 2 => 'Preview' },
Writable => 'undef',
# protect this tag because it contains all the metadata
Flags => [ 'Binary', 'Protected', 'NestedHtmlDump', 'BlockExtract' ],
Notes => 'processed as an embedded document because it contains full EXIF',
WriteCheck => '$val eq "none" ? undef : $self->CheckImage(\$val)',
DataTag => 'JpgFromRaw',
RawConv => '$self->ValidateImage(\$val,$tag)',
SubDirectory => {
# extract information from embedded image since it is metadata-rich,
# unless HtmlDump option set (note that the offsets will be relative,
# not absolute like they should be in verbose mode)
TagTable => 'Image::ExifTool::JPEG::Main',
WriteProc => \&WriteJpgFromRaw,
ProcessProc => \&ProcessJpgFromRaw,
},
},
0x2f => { Name => 'CropTop', Writable => 'int16u' },
0x30 => { Name => 'CropLeft', Writable => 'int16u' },
0x31 => { Name => 'CropBottom', Writable => 'int16u' },
0x32 => { Name => 'CropRight', Writable => 'int16u' },
0x10f => {
Name => 'Make',
Groups => { 2 => 'Camera' },
Writable => 'string',
DataMember => 'Make',
# save this value as an ExifTool member variable
RawConv => '$self->{Make} = $val',
},
0x110 => {
Name => 'Model',
Description => 'Camera Model Name',
Groups => { 2 => 'Camera' },
Writable => 'string',
DataMember => 'Model',
# save this value as an ExifTool member variable
RawConv => '$self->{Model} = $val',
},
0x111 => {
Name => 'StripOffsets',
# (this value is 0xffffffff for some models, and RawDataOffset must be used)
Flags => [ 'IsOffset', 'PanasonicHack' ],
OffsetPair => 0x117, # point to associated byte counts
ValueConv => 'length($val) > 32 ? \$val : $val',
},
0x112 => {
Name => 'Orientation',
Writable => 'int16u',
PrintConv => \%Image::ExifTool::Exif::orientation,
Priority => 0, # so IFD1 doesn't take precedence
},
0x116 => {
Name => 'RowsPerStrip',
Priority => 0,
},
0x117 => {
Name => 'StripByteCounts',
# (note that this value may represent something like uncompressed byte count
# for RAW/RW2/RWL images from some models, and is zero for some other models)
OffsetPair => 0x111, # point to associated offset
ValueConv => 'length($val) > 32 ? \$val : $val',
},
0x118 => {
Name => 'RawDataOffset', #PH (RW2/RWL)
IsOffset => '$$et{TIFF_TYPE} =~ /^(RW2|RWL)$/', # (invalid in DNG-converted files)
PanasonicHack => 1,
OffsetPair => 0x117, # (use StripByteCounts as the offset pair)
},
0x119 => {
Name => 'DistortionInfo',
SubDirectory => { TagTable => 'Image::ExifTool::PanasonicRaw::DistortionInfo' },
},
# 0x11b - chromatic aberration correction (ref 3)
0x2bc => { # PH Extension!!
Name => 'ApplicationNotes', # (writable directory!)
Writable => 'int8u',
Format => 'undef',
Flags => [ 'Binary', 'Protected' ],
SubDirectory => {
DirName => 'XMP',
TagTable => 'Image::ExifTool::XMP::Main',
},
},
0x83bb => { # PH Extension!!
Name => 'IPTC-NAA', # (writable directory!)
Format => 'undef', # convert binary values as undef
Writable => 'int32u', # but write int32u format code in IFD
WriteGroup => 'IFD0',
Flags => [ 'Binary', 'Protected' ],
SubDirectory => {
DirName => 'IPTC',
TagTable => 'Image::ExifTool::IPTC::Main',
},
},
0x8769 => {
Name => 'ExifOffset',
Groups => { 1 => 'ExifIFD' },
Flags => 'SubIFD',
SubDirectory => {
TagTable => 'Image::ExifTool::Exif::Main',
DirName => 'ExifIFD',
Start => '$val',
},
},
0x8825 => {
Name => 'GPSInfo',
Groups => { 1 => 'GPS' },
Flags => 'SubIFD',
SubDirectory => {
DirName => 'GPS',
TagTable => 'Image::ExifTool::GPS::Main',
Start => '$val',
},
},
# 0xffff => 'DCSHueShiftValues', #exifprobe (NC)
);
# white balance information (ref 4)
# (PanasonicRawVersion<200: Digilux 2)
%Image::ExifTool::PanasonicRaw::WBInfo = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int16u',
FIRST_ENTRY => 0,
0 => 'NumWBEntries',
1 => { Name => 'WBType1', %wbTypeInfo },
2 => { Name => 'WB_RBLevels1', Format => 'int16u[2]' },
4 => { Name => 'WBType2', %wbTypeInfo },
5 => { Name => 'WB_RBLevels2', Format => 'int16u[2]' },
7 => { Name => 'WBType3', %wbTypeInfo },
8 => { Name => 'WB_RBLevels3', Format => 'int16u[2]' },
10 => { Name => 'WBType4', %wbTypeInfo },
11 => { Name => 'WB_RBLevels4', Format => 'int16u[2]' },
13 => { Name => 'WBType5', %wbTypeInfo },
14 => { Name => 'WB_RBLevels5', Format => 'int16u[2]' },
16 => { Name => 'WBType6', %wbTypeInfo },
17 => { Name => 'WB_RBLevels6', Format => 'int16u[2]' },
19 => { Name => 'WBType7', %wbTypeInfo },
20 => { Name => 'WB_RBLevels7', Format => 'int16u[2]' },
);
# white balance information (ref 4)
# (PanasonicRawVersion>=200: D-Lux2, D-Lux3, DMC-FZ18/FZ30/LX1/L10)
%Image::ExifTool::PanasonicRaw::WBInfo2 = (
PROCESS_PROC => \&Image::ExifTool::ProcessBinaryData,
WRITE_PROC => \&Image::ExifTool::WriteBinaryData,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
WRITABLE => 1,
FORMAT => 'int16u',
FIRST_ENTRY => 0,
0 => 'NumWBEntries',
1 => { Name => 'WBType1', %wbTypeInfo },
2 => { Name => 'WB_RGBLevels1', Format => 'int16u[3]' },
5 => { Name => 'WBType2', %wbTypeInfo },
6 => { Name => 'WB_RGBLevels2', Format => 'int16u[3]' },
9 => { Name => 'WBType3', %wbTypeInfo },
10 => { Name => 'WB_RGBLevels3', Format => 'int16u[3]' },
13 => { Name => 'WBType4', %wbTypeInfo },
14 => { Name => 'WB_RGBLevels4', Format => 'int16u[3]' },
17 => { Name => 'WBType5', %wbTypeInfo },
18 => { Name => 'WB_RGBLevels5', Format => 'int16u[3]' },
21 => { Name => 'WBType6', %wbTypeInfo },
22 => { Name => 'WB_RGBLevels6', Format => 'int16u[3]' },
25 => { Name => 'WBType7', %wbTypeInfo },
26 => { Name => 'WB_RGBLevels7', Format => 'int16u[3]' },
);
# lens distortion information (ref 3)
# (distortion correction equation: Ru = scale*(Rd + a*Rd^3 + b*Rd^5 + c*Rd^7), ref 3)
%Image::ExifTool::PanasonicRaw::DistortionInfo = (
PROCESS_PROC => \&ProcessDistortionInfo,
WRITE_PROC => \&WriteDistortionInfo,
CHECK_PROC => \&Image::ExifTool::CheckBinaryData,
# (don't make this family 0 MakerNotes because we don't want it to be a deletable group)
GROUPS => { 0 => 'PanasonicRaw', 1 => 'PanasonicRaw', 2 => 'Image'},
WRITABLE => 1,
FORMAT => 'int16s',
FIRST_ENTRY => 0,
NOTES => 'Lens distortion correction information.',
# 0,1 - checksums
2 => {
Name => 'DistortionParam02',
ValueConv => '$val / 32768',
ValueConvInv => '$val * 32768',
},
# 3 - usually 0, but seen 0x026b when value 5 is non-zero
4 => {
Name => 'DistortionParam04',
ValueConv => '$val / 32768',
ValueConvInv => '$val * 32768',
},
5 => {
Name => 'DistortionScale',
ValueConv => '1 / (1 + $val/32768)',
ValueConvInv => '(1/$val - 1) * 32768',
},
# 6 - seen 0x0000-0x027f
7.1 => {
Name => 'DistortionCorrection',
Mask => 0x0f,
# (have seen the upper 4 bits set for GF5 and GX1, giving a value of -4095 - PH)
PrintConv => { 0 => 'Off', 1 => 'On' },
},
8 => {
Name => 'DistortionParam08',
ValueConv => '$val / 32768',
ValueConvInv => '$val * 32768',
},
9 => {
Name => 'DistortionParam09',
ValueConv => '$val / 32768',
ValueConvInv => '$val * 32768',
},
# 10 - seen 0xfc,0x0101,0x01f4,0x021d,0x0256
11 => {
Name => 'DistortionParam11',
ValueConv => '$val / 32768',
ValueConvInv => '$val * 32768',
},
12 => {
Name => 'DistortionN',
Unknown => 1,
},
# 13 - seen 0x0000,0x01f9-0x02b2
# 14,15 - checksums
);
# PanasonicRaw composite tags
%Image::ExifTool::PanasonicRaw::Composite = (
ImageWidth => {
Require => {
0 => 'IFD0:SensorLeftBorder',
1 => 'IFD0:SensorRightBorder',
},
ValueConv => '$val[1] - $val[0]',
},
ImageHeight => {
Require => {
0 => 'IFD0:SensorTopBorder',
1 => 'IFD0:SensorBottomBorder',
},
ValueConv => '$val[1] - $val[0]',
},
);
# add our composite tags
Image::ExifTool::AddCompositeTags('Image::ExifTool::PanasonicRaw');
#------------------------------------------------------------------------------
# checksum algorithm for lens distortion correction information (ref 3)
# Inputs: 0) data ref, 1) start position, 2) number of bytes, 3) incement
# Returns: checksum value
sub Checksum($$$$)
{
my ($dataPt, $start, $num, $inc) = @_;
my $csum = 0;
my $i;
for ($i=0; $i<$num; ++$i) {
$csum = (73 * $csum + Get8u($dataPt, $start + $i * $inc)) % 0xffef;
}
return $csum;
}
#------------------------------------------------------------------------------
# Read lens distortion information
# Inputs: 0) ExifTool ref, 1) dirInfo ref, 2) tag table ref
# Returns: 1 on success
sub ProcessDistortionInfo($$$)
{
my ($et, $dirInfo, $tagTablePtr) = @_;
my $dataPt = $$dirInfo{DataPt};
my $start = $$dirInfo{DirStart} || 0;
my $size = $$dirInfo{DataLen} || (length($$dataPt) - $start);
if ($size == 32) {
# verify the checksums (ref 3)
my $csum1 = Checksum($dataPt, $start + 4, 12, 1);
my $csum2 = Checksum($dataPt, $start + 16, 12, 1);
my $csum3 = Checksum($dataPt, $start + 2, 14, 2);
my $csum4 = Checksum($dataPt, $start + 3, 14, 2);
my $res = $csum1 ^ Get16u($dataPt, $start + 2) ^
$csum2 ^ Get16u($dataPt, $start + 28) ^
$csum3 ^ Get16u($dataPt, $start + 0) ^
$csum4 ^ Get16u($dataPt, $start + 30);
$et->Warn('Invalid DistortionInfo checksum',1) if $res;
} else {
$et->Warn('Invalid DistortionInfo',1);
}
return $et->ProcessBinaryData($dirInfo, $tagTablePtr);
}
#------------------------------------------------------------------------------
# Write lens distortion information
# Inputs: 0) ExifTool ref, 1) dirInfo ref, 2) tag table ref
# Returns: updated distortion information or undef on error
sub WriteDistortionInfo($$$)
{
my ($et, $dirInfo, $tagTablePtr) = @_;
$et or return 1; # (allow dummy access)
my $dat = $et->WriteBinaryData($dirInfo, $tagTablePtr);
if (defined $dat and length($dat) == 32) {
# fix checksums (ref 3)
Set16u(Checksum(\$dat, 4, 12, 1), \$dat, 2);
Set16u(Checksum(\$dat, 16, 12, 1), \$dat, 28);
Set16u(Checksum(\$dat, 2, 14, 2), \$dat, 0);
Set16u(Checksum(\$dat, 3, 14, 2), \$dat, 30);
} else {
$et->Warn('Error wriing DistortionInfo',1);
}
return $dat;
}
#------------------------------------------------------------------------------
# Patch for writing non-standard Panasonic RAW/RW2/RWL raw data
# Inputs: 0) offset info ref, 1) raf ref, 2) IFD number
# Returns: error string, or undef on success
# OffsetInfo is a hash by tag ID of lists with the following elements:
# 0 - tag info ref
# 1 - pointer to int32u offset in IFD or value data
# 2 - value count
# 3 - reference to list of original offset values
# 4 - IFD format number
sub PatchRawDataOffset($$$)
{
my ($offsetInfo, $raf, $ifd) = @_;
my $stripOffsets = $$offsetInfo{0x111};
my $stripByteCounts = $$offsetInfo{0x117};
my $rawDataOffset = $$offsetInfo{0x118};
my $err;
$err = 1 unless $ifd == 0;
$err = 1 unless $stripOffsets and $stripByteCounts and $$stripOffsets[2] == 1;
if ($rawDataOffset) {
$err = 1 unless $$rawDataOffset[2] == 1;
$err = 1 unless $$stripOffsets[3][0] == 0xffffffff or $$stripByteCounts[3][0] == 0;
}
$err and return 'Unsupported Panasonic/Leica RAW variant';
if ($rawDataOffset) {
# update StripOffsets along with this tag if it contains a reasonable value
unless ($$stripOffsets[3][0] == 0xffffffff) {
# save pointer to StripOffsets value for updating later
push @$rawDataOffset, $$stripOffsets[1];
}
# handle via RawDataOffset instead of StripOffsets
$stripOffsets = $$offsetInfo{0x111} = $rawDataOffset;
delete $$offsetInfo{0x118};
}
# determine the length of the raw data
my $pos = $raf->Tell();
$raf->Seek(0, 2) or $err = 1; # seek to end of file
my $len = $raf->Tell() - $$stripOffsets[3][0];
$raf->Seek($pos, 0);
# quick check to be sure the raw data length isn't unreasonable
# (the 22-byte length is for '<Dummy raw image data>' in our tests)
$err = 1 if ($len < 1000 and $len != 22) or $len & 0x80000000;
$err and return 'Error reading Panasonic raw data';
# update StripByteCounts info with raw data length
# (note that the original value is maintained in the file)
$$stripByteCounts[3][0] = $len;
return undef;
}
#------------------------------------------------------------------------------
# Write meta information to Panasonic JpgFromRaw in RAW/RW2/RWL image
# Inputs: 0) ExifTool object ref, 1) dirInfo ref, 2) tag table ref
# Returns: updated image data, or undef if nothing changed
sub WriteJpgFromRaw($$$)
{
my ($et, $dirInfo, $tagTablePtr) = @_;
my $dataPt = $$dirInfo{DataPt};
my $byteOrder = GetByteOrder();
my $fileType = $$et{FILE_TYPE}; # RAW, RW2 or RWL
my $dirStart = $$dirInfo{DirStart};
if ($dirStart) { # DirStart is non-zero in DNG-converted RW2/RWL
my $dirLen = $$dirInfo{DirLen} | length($$dataPt) - $dirStart;
my $buff = substr($$dataPt, $dirStart, $dirLen);
$dataPt = \$buff;
}
my $raf = new File::RandomAccess($dataPt);
my $outbuff;
my %dirInfo = (
RAF => $raf,
OutFile => \$outbuff,
);
$$et{BASE} = $$dirInfo{DataPos};
$$et{FILE_TYPE} = $$et{TIFF_TYPE} = 'JPEG';
# use a specialized map so we don't write XMP or IPTC (or other junk) into the JPEG
my $editDirs = $$et{EDIT_DIRS};
my $addDirs = $$et{ADD_DIRS};
$et->InitWriteDirs(\%jpgFromRawMap);
# don't add XMP segment (IPTC won't get added because it is in Photoshop record)
delete $$et{ADD_DIRS}{XMP};
my $result = $et->WriteJPEG(\%dirInfo);
# restore variables we changed
$$et{BASE} = 0;
$$et{FILE_TYPE} = 'TIFF';
$$et{TIFF_TYPE} = $fileType;
$$et{EDIT_DIRS} = $editDirs;
$$et{ADD_DIRS} = $addDirs;
SetByteOrder($byteOrder);
return $result > 0 ? $outbuff : $$dataPt;
}
#------------------------------------------------------------------------------
# Extract meta information from an Panasonic JpgFromRaw
# Inputs: 0) ExifTool object reference, 1) dirInfo reference
# Returns: 1 on success, 0 if this wasn't a valid JpgFromRaw image
sub ProcessJpgFromRaw($$$)
{
my ($et, $dirInfo, $tagTablePtr) = @_;
my $dataPt = $$dirInfo{DataPt};
my $byteOrder = GetByteOrder();
my $fileType = $$et{FILE_TYPE}; # RAW, RW2 or RWL
my $tagInfo = $$dirInfo{TagInfo};
my $verbose = $et->Options('Verbose');
my ($indent, $out);
$tagInfo or $et->Warn('No tag info for Panasonic JpgFromRaw'), return 0;
my $dirStart = $$dirInfo{DirStart};
if ($dirStart) { # DirStart is non-zero in DNG-converted RW2/RWL
my $dirLen = $$dirInfo{DirLen} | length($$dataPt) - $dirStart;
my $buff = substr($$dataPt, $dirStart, $dirLen);
$dataPt = \$buff;
}
$$et{BASE} = $$dirInfo{DataPos} + ($dirStart || 0);
$$et{FILE_TYPE} = $$et{TIFF_TYPE} = 'JPEG';
$$et{DOC_NUM} = 1;
# extract information from embedded JPEG
my %dirInfo = (
Parent => 'RAF',
RAF => new File::RandomAccess($dataPt),
);
if ($verbose) {
my $indent = $$et{INDENT};
$$et{INDENT} = ' ';
$out = $et->Options('TextOut');
print $out '--- DOC1:JpgFromRaw ',('-'x56),"\n";
}
my $rtnVal = $et->ProcessJPEG(\%dirInfo);
# restore necessary variables for continued RW2/RWL processing
$$et{BASE} = 0;
$$et{FILE_TYPE} = 'TIFF';
$$et{TIFF_TYPE} = $fileType;
delete $$et{DOC_NUM};
SetByteOrder($byteOrder);
if ($verbose) {
$$et{INDENT} = $indent;
print $out ('-'x76),"\n";
}
return $rtnVal;
}
1; # end
__END__
=head1 NAME
Image::ExifTool::PanasonicRaw - Read/write Panasonic/Leica RAW/RW2/RWL meta information
=head1 SYNOPSIS
This module is loaded automatically by Image::ExifTool when required.
=head1 DESCRIPTION
This module contains definitions required by Image::ExifTool to read and
write meta information in Panasonic/Leica RAW, RW2 and RWL images.
=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 REFERENCES
=over 4
=item L<http://www.cybercom.net/~dcoffin/dcraw/>
=back
=head1 SEE ALSO
L<Image::ExifTool::TagNames/PanasonicRaw Tags>,
L<Image::ExifTool(3pm)|Image::ExifTool>
=cut
| rizzles/convert | imageprocessor/processorcommand/lib/Image/ExifTool/PanasonicRaw.pm | Perl | mit | 22,888 |
:- compile('$REGULUS/Prolog/dialogue_server').
:- use_module('$REGULUS/Examples/Calendar/Prolog/database1').
%:- server(1985, '$REGULUS/Examples/Calendar/scripts/calendar.cfg').
:- server(1985,
'$REGULUS/Examples/Calendar/scripts/calendar.cfg',
["EBL_LOAD", "LOAD_DIALOGUE", "LOAD_HELP"],
'$REGULUS/logfiles').
:- halt.
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/regulus/Examples/Calendar/scripts/load_and_run_server_regulus_parser.pl | Perl | mit | 334 |
:- use_module(library('linda/server')).
:- use_module(library(system),[pid/1]).
start(Host:Port):-
open('/tmp/curtHostPort',write,Stream1),
format(Stream1,"host_port('~p',~p).~n",[Host,Port]),
close(Stream1),
pid(Pid),
open('/tmp/curtServerPid',write,Stream2),
format(Stream2,"pid(~p).~n",[Pid]),
close(Stream2).
:- linda((Host:Port)-(user:start(Host:Port))).
| TeamSPoon/logicmoo_workspace | packs_sys/logicmoo_nlu/ext/CURT/bb0/curtServer.pl | Perl | mit | 427 |
$a = 1;
$aval0 = ($a == 1);
$aval1 = ($a != 1);
$aval2 = ($a > 1);
$aval3 = ($a < 1);
$aval4 = ($a >= 1);
$aval5 = ($a <= 1);
$aval6 = ($a <=> 1);
$b = 1;
$bval0 = ($b eq 1);
$bval1 = ($b ne 1);
$bval2 = ($b gt 1);
$bval3 = ($b lt 1);
$bval4 = ($b ge 1);
$bval5 = ($b le 1);
$bval6 = ($b cmp 1);
| nanobowers/perl5-to-ruby | test/working/test_compare.pl | Perl | mit | 298 |
#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/say/;
use utf8;
use Data::Printer;
use Mojo::UserAgent;
use Storable;
use open qw/:std :utf8/;
my $courses;
if (-r '.cache') {
$courses = retrieve('.cache');
goto PROCESS;
}
my $ua = Mojo::UserAgent->new;
my $dom = $ua->get('http://mfk.msu.ru/season5.php')
->res
->dom;
my $links = $dom->find('#rightlower > p > a:nth-child(1)')
->map(sub {[$_->all_text, 'http://mfk.msu.ru/' . $_->attr('href')]})
->to_array;
sub parse_student
{
my $str = $_[0];
if ($str =~ m/\A(?<l>[\w-]++(\h\w+)*)\h(?<f>\w\.)(\h(?<p>\w\.))?\h\((?<t>[\w-]++(\hформа,\h\w++)?),\h(?<c>\d)\hкурс\)\z/) {
return {lastname => $+{l}, firstname => $+{f}, patronymic => $+{p}, type => $+{t}, course => $+{c}}
} else {
warn("parsing error: $str\n");
return undef;
}
}
foreach(@$links) {
my $link = $_->[1];
my $dom = $ua->get($link)
->res
->dom;
my $faculty = '';
my $students = $dom->find('#rightlower > ol > li[value], #rightlower > h4')
->map(sub{ if ($_->matches('h4')) {$faculty = $_->text; undef} else { my $s = parse_student($_->text); if ($s) { $s->{faculty} = $faculty; $s } else {undef}} })
->compact
->to_array;
$courses->{$_->[0]}{link} = $link;
$courses->{$_->[0]}{students} = $students;
}
store $courses, '.cache';
PROCESS:
#output in prolog
sub student_term
{
my $str = "student(";
foreach my $key (qw/lastname firstname patronymic faculty type/) {
$str .= $_[0]->{$key} ? "'$_[0]->{$key}', " : "'notexist', "
}
$str .= "$_[0]->{course})";
$str
}
my @students;
foreach (keys $courses) {
foreach (@{ $courses->{$_}->{students} }) {
push @students, student_term($_)
}
}
@students = sort @students;
#uniq
my $last = '';
@students = grep {if ($last ne $_) {$last = $_; 1} else {0}} @students;
my @courses;
foreach (keys $courses) {
push @courses, "course('$_')"
}
my @enroll;
foreach (keys $courses) {
my $course = $_;
my $students = '[' . join(', ', map {student_term($_)} @{ $courses->{$_}->{students} }) . ']';
push @enroll, "enroll('$course', $students)";
}
say ':- use_module(library(lists)).';
say '';
say '';
say 'lastname(X) :- student(X,_,_,_,_,_).';
say 'firstname(X) :- student(_,X,_,_,_,_).';
say 'patronymic(X) :- student(_,_,X,_,_,_).';
say 'faculty(X) :- student(_,_,_,X,_,_).';
say 'st_type(X) :- student(_,_,_,_,X,_).';
say 'st_course(X) :- student(_,_,_,_,_,X).';
say '';
say '';
say join(".\n", @students) . ".";
say '';
say join(".\n", @courses) . ".";
say '';
say join(".\n", @enroll) . ".";
| evdenis/ifc | ifc.pl | Perl | mit | 2,751 |
%% Utility Procedures %%
%% Alan Bundy, 31.1.12 %%
%% Revised By Boris Mitrovic, 16.05.13; 11.06.16 %%
%% pprint(E): convert to input form and print
pprint(vble(X)) :- print(X),!.
pprint(vble(X)) :- print(X),!.
pprint([F|Args]) :- atomic(F), !,
convert(E,[F|Args]), print(E).
pprint([]).
pprint([NE1=NE2|NEL]) :- !,
convert(E1,NE1), convert(E2,NE2),
print(E1=E2), print(', '), pprint(NEL).
pprint([NE1/NE2|NEL]) :- !,
convert(E1,NE1), convert(E2,NE2),
print(E1/E2), print(', '), pprint(NEL).
% verbose(Switch): if Switch is on, use pretty printing
:- dynamic verbose/1.
verbose(off).
%% switch verbose on or off
switch :- verbose(S),retractall(verbose(S)), opposite(S,NS), assert(verbose(NS)),!.
%% opposite(S,NS): S and NS are opposites
opposite(on,off).
opposite(off,on).
% Keeps track of the current result of unification (FS) which is known at the end of recursion in reform2.
:- dynamic refsuccess/0.
refsuccess(success) :- refsuccess,!.
refsuccess(fail) :- \+(refsuccess),!.
%% convert(In,Out): convert normal Prolog syntax to internal representation or
%% vice versa.
% X is a variable
convert(X,vble(X)) :- % Convert X into a variable
atomic(X), atom_chars(X,[H|_]), % if first letter
char_code(H,N), 109<N, N<123, !. % is n-z
% A is a constant
convert(A,[A]) :- % Convert A into a constant
atomic(A), atom_chars(A,[H|_]), % If first letter
char_code(H,N), 96<N, N<110, !. % Is a-m
% A is a number
convert(A,[A]) :- % Convert A into a constant
number(A), !. % if it is a number
%% These variable/constant conventions need revisiting for serious use
% E is compound
convert(E,[F|NArgs]) :-
var(E), !, % If E is output and input compound
maplist(convert,Args,NArgs), E=..[F|Args]. % Recurse on all args of F
convert(E,[F|NArgs]) :- % If E is input and compound then
\+ var(E), \+ atomic(E), !, E=..[F|Args], % break it into components
maplist(convert,Args,NArgs). % and recurse on them
%% orlist(F,List): check F true on any element of List
% Step case
orlist(F,[H|T]) :- (call(F,H); orlist(F,T)). % True if either true on head or tail
%% pairwise(L1,L2,Pairlist): pairs up corresponding elements of two lists.
% Base case
pairwise([],[],[]). % If input two empty lists then return one.
% Step case
pairwise([H1|T1],[H2|T2],[H1=H2|T]) :- % Otherwise, pair up the heads
pairwise(T1,T2,T). % and recurse on the tails.
%% disjoin(D1,D2,D): return either D1 or D2 as D
% If they are the same, just return one.
disjoin(D,D,D) :- !.
% If either is empty, return the other.
disjoin([],D,D) :- !.
disjoin(D,[],D) :- !.
% Otherwise, just return one
disjoin(D1,D2,D) :- !, (D1=D ; D2=D).
% contains(vble(X):Sx,Rest): is vble(X):Sx contained in the Rest on either side
contains(vble(X),Rest) :- orlist(contains2(vble(X)),Rest), !.
contains2(vble(X),vble(X)=_) :- !.
contains2(vble(X),_=vble(X)) :- !.
contains2(vble(X),[_|Args]=_) :- orlist(contains2(vble(X)),Args), !.
contains2(vble(X),_=[_|Args]) :- orlist(contains2(vble(X)),Args), !.
containsR(X,Rep,Reps) :- orlist(containsRep(X,Rep),Reps).
containsRep(X,Rep,Rep) :- Rep =..[_|Args], orlist(containsA(X), Args),!. % TODO: get all Repairs
containsA(X,X) :- !.
% containsDifferent(vble(X):Sx,Rest): is vble(X):Sx contained in the Rest on either side,
% and is it unified against a different term (TODO: make it ununifiable)
containsDifferent(vble(X),Term,Rest) :- orlist(containsDifferent2(vble(X),Term),Rest), !.
containsDifferent2(vble(X),Term,vble(X)=Term2) :- Term \== Term2,!.
containsDifferent2(vble(X),Term,Term2=vble(X)) :- Term \== Term2,!.
containsDifferent2(vble(X),[_|Args]=Term) :- orlist(containsDifferent2(vble(X),Term),Args), !.
containsDifferent2(vble(X),Term=[_|Args]) :- orlist(containsDifferent2(vble(X),Term),Args), !.
%% occurs(vble(X):Sx,E): variable vble(X):Sx occurs in compound expression E
% Occurs check succeeds if it succeeds on any argument
occurs(vble(X),[_|Args]) :- orlist(occurs2(vble(X)),Args), !.
occurs(V,+T) :- !, occurs(V,T).
occurs(V,-T) :- !, occurs(V,T).
occurs(V,Clause) :- !, orlist(occurs(V),Clause).
%% occurs2(vble(X),E): variable vble(X) occurs in any expression E
% Base case
occurs2(vble(X),vble(X)) :- !.
% Step case
occurs2(vble(X),[_|Args]) :- !, orlist(occurs2(vble(X)),Args).
% subst(V/E,E1,E2): E2 is the result of substituting E for V in E1.
subst(vble(X)/C, vble(X), C) :- !.
subst(vble(X)/_, vble(Y), vble(Y)) :- X\==Y, !.
subst(Subst,[F|Args1],[F|Args2]) :-
atomic(F), maplist(subst(Subst),Args1,Args2),!. % If E1 is compound then recurse on args.
subst(Subst,[E1=E2|Tl],[NE1=NE2|NTl]) :- % If E1 is unification problem then
subst(Subst,E1,NE1), subst(Subst,E2,NE2), % apply substitution to both sides
subst(Subst,Tl,NTl),!. % then recurse on tails
subst(Subst,[+E|T],[+NE|NT]) :- % for substituting resolution ready clauses
subst(Subst,E,NE),
subst(Subst,T,NT),!.
subst(Subst,[-E|T],[-NE|NT]) :-
subst(Subst,E,NE),
subst(Subst,T,NT),!.
subst(Subst,[V/E|T],[V/NE|NT]) :- % If E1 is substitution then
subst(Subst,E,NE), % apply substitution to value
subst(Subst,T,NT),!. % then recurse on tails
subst([Subst|Substs], E,NE) :- subst(Subst,E,NE1), subst(Substs,NE1,NE), !.
subst(_,[],[]) :-!. % If E1 is empty problem then do nothing
subst([],E,E) :-!.
substR(X/Y,Old,New) :- Old=..[F|Args], New=..[F|NewArgs], substA(X/Y,Args,NewArgs),!.
substA(X/Y,[X|Rest],[Y|NewRest]) :- substA(X/Y,Rest,NewRest),!.
substA(X/Y,[Z|Rest],[Z|NewRest]) :- Z\==X, substA(X/Y,Rest,NewRest),!.
substA(_,[],[]).
%% compose(Sub,SublistIn,SublistOut): SublistOut is the result of composing
%% singleton substitution Subst with substitution SublistIn
compose(Sub,SublistIn,[Sub|SublistMid]) :- % Append new substitution
subst(Sub,SublistIn,SublistMid). % after applying it to the old one
%% and(FS1,FS2,FS): conjoin FS1 and FS2 to get FS
and(fail,fail,fail).
and(fail,success,fail).
and(success,fail,fail).
and(success,success,success).
%% gensym(In,Out): generate new symbol Out as In with suffix
gensym(In,Out) :-
atom_chars(In,InList), % Turn atom into list of characters
append(InList,[d,a,s,h],Outlist), % Append a dash to the list
atom_chars(Out,Outlist). % and turn it back into an atom
% This simplistic renaming needs rethinking for serious use
%% position(Sub,Exp,Posn): Sub is at position Posn in Exp
% Base Case
position(Exp,Exp,[]). % The current expression is at the empty position
% Step Case
position(Sub,[_|Args],[I|Posn]) :- % Otherwise, get the args of a compound expression
append(Front,[Arg|_],Args), % Use append backwards to identify each argument in turn
length(Front,I1), I is I1+1, % Work out what its position is
position(Sub,Arg,Posn). % Recurse on each argument
%% replace(P,E1,Sub,E2): replace position P in E1 with Sub to get E2
% Base case: found position.
replace([],_,Sub,Sub). % To replace the current position return Sub
% Step case: find Ith argument and recurse on it
replace([I|Posn],[F|Args1],Sub,[F|Args2]) :- % To replace anyother position
I1 is I-1, length(Front,I1), % Front is the first I-1 args
append(Front,[Arg1|Back],Args1), % Arg1 is the Ith
replace(Posn,Arg1,Sub,Arg2), % Recurse on the Ith arg then
append(Front,[Arg2|Back],Args2). % place new Ith arg back in the expression.
% quick sort by value for a list of pairs (value, repair)
quicksort(List,Sorted):-q_sort(List,[],Sorted).
q_sort([],Acc,Acc) :- !.
q_sort([H|T],Acc,Sorted):-
pivoting(H,T,L1,L2),
q_sort(L1,Acc,Sorted1),q_sort(L2,[H|Sorted1],Sorted).
pivoting(_,[],[],[]) :- !.
pivoting(((H1,H2),Vh),[((X1,X2),Vx)|T],[((X1,X2),Vx)|L],G):- (X1>H1; X1==H1,X2=<H2), pivoting(((H1,H2),Vh),T,L,G), !.
pivoting(((H1,H2),Vh),[((X1,X2),Vx)|T],L,[((X1,X2),Vx)|G]):- pivoting(((H1,H2),Vh),T,L,G).
pickSnds(Pairs,Snds) :- maplist(pickSnd,Pairs,Snds).
pickSnd((_,Y),Y).
% detect negation
truefalse(-_,fail) :-!.
truefalse(_,success).
% converting between lists and tuples
list2tuple([A],A) :-!.
list2tuple([A|B1],','(A,B)) :- !, list2tuple(B1,B).
tuple2list(','(A,B), [A|B1]) :- !, tuple2list(B,B1).
tuple2list(A,[A]).
vprint(X) :- verbose(on),!, print(X); true.
vnl :- verbose(on),!,nl; true.
%% switch(L,R): switch left for right and vice versa
switch(left,right).
switch(right,left).
%% Procedures not in Sictus, but in SWI
%% maplist(Pred,InList,Outlist): apply Pred to each element in Inlist to form Outlist
maplist(_, [], []).
maplist(Pred, [H1|T1], [H2|T2]) :-
Pred =.. PL,
append(PL, [H1, H2], NewPred),
Call =.. NewPred,
call(Call),
maplist(Pred, T1, T2).
%% nth1(N,List,Element): Element is Nth element of List
nth1(1,[X|_],X) :- !.
nth1(Idx,[_|List],X) :-
Idx > 1,
Idx1 is Idx-1,
nth1(Idx1,List,X).
%% is_list(List): List is a list
is_list([_|_]).
is_list([]).
| BorisMitrovic/reformation | util.pl | Perl | mit | 9,636 |
package namespace::clean;
=head1 NAME
namespace::clean - Keep imports and functions out of your namespace
=cut
use warnings;
use strict;
use vars qw( $VERSION $STORAGE_VAR $SCOPE_HOOK_KEY $SCOPE_EXPLICIT );
use Symbol qw( qualify_to_ref gensym );
use B::Hooks::EndOfScope;
use Sub::Identify qw(sub_fullname);
use Sub::Name qw(subname);
=head1 VERSION
0.13
=cut
$VERSION = '0.13';
$STORAGE_VAR = '__NAMESPACE_CLEAN_STORAGE';
=head1 SYNOPSIS
package Foo;
use warnings;
use strict;
use Carp qw(croak); # 'croak' will be removed
sub bar { 23 } # 'bar' will be removed
# remove all previously defined functions
use namespace::clean;
sub baz { bar() } # 'baz' still defined, 'bar' still bound
# begin to collection function names from here again
no namespace::clean;
sub quux { baz() } # 'quux' will be removed
# remove all functions defined after the 'no' unimport
use namespace::clean;
# Will print: 'No', 'No', 'Yes' and 'No'
print +(__PACKAGE__->can('croak') ? 'Yes' : 'No'), "\n";
print +(__PACKAGE__->can('bar') ? 'Yes' : 'No'), "\n";
print +(__PACKAGE__->can('baz') ? 'Yes' : 'No'), "\n";
print +(__PACKAGE__->can('quux') ? 'Yes' : 'No'), "\n";
1;
=head1 DESCRIPTION
=head2 Keeping packages clean
When you define a function, or import one, into a Perl package, it will
naturally also be available as a method. This does not per se cause
problems, but it can complicate subclassing and, for example, plugin
classes that are included via multiple inheritance by loading them as
base classes.
The C<namespace::clean> pragma will remove all previously declared or
imported symbols at the end of the current package's compile cycle.
Functions called in the package itself will still be bound by their
name, but they won't show up as methods on your class or instances.
By unimporting via C<no> you can tell C<namespace::clean> to start
collecting functions for the next C<use namespace::clean;> specification.
You can use the C<-except> flag to tell C<namespace::clean> that you
don't want it to remove a certain function or method. A common use would
be a module exporting an C<import> method along with some functions:
use ModuleExportingImport;
use namespace::clean -except => [qw( import )];
If you just want to C<-except> a single sub, you can pass it directly.
For more than one value you have to use an array reference.
=head2 Explicitely removing functions when your scope is compiled
It is also possible to explicitely tell C<namespace::clean> what packages
to remove when the surrounding scope has finished compiling. Here is an
example:
package Foo;
use strict;
# blessed NOT available
sub my_class {
use Scalar::Util qw( blessed );
use namespace::clean qw( blessed );
# blessed available
return blessed shift;
}
# blessed NOT available
=head2 Moose
When using C<namespace::clean> together with L<Moose> you want to keep
the installed C<meta> method. So your classes should look like:
package Foo;
use Moose;
use namespace::clean -except => 'meta';
...
Same goes for L<Moose::Role>.
=head2 Cleaning other packages
You can tell C<namespace::clean> that you want to clean up another package
instead of the one importing. To do this you have to pass in the C<-cleanee>
option like this:
package My::MooseX::namespace::clean;
use strict;
use namespace::clean (); # no cleanup, just load
sub import {
namespace::clean->import(
-cleanee => scalar(caller),
-except => 'meta',
);
}
If you don't care about C<namespace::clean>s discover-and-C<-except> logic, and
just want to remove subroutines, try L</clean_subroutines>.
=head1 METHODS
You shouldn't need to call any of these. Just C<use> the package at the
appropriate place.
=cut
=head2 clean_subroutines
This exposes the actual subroutine-removal logic.
namespace::clean->clean_subroutines($cleanee, qw( subA subB ));
will remove C<subA> and C<subB> from C<$cleanee>. Note that this will remove the
subroutines B<immediately> and not wait for scope end. If you want to have this
effect at a specific time (e.g. C<namespace::clean> acts on scope compile end)
it is your responsibility to make sure it runs at that time.
=cut
my $RemoveSubs = sub {
my $cleanee = shift;
my $store = shift;
SYMBOL:
for my $f (@_) {
my $fq = "${cleanee}::$f";
# ignore already removed symbols
next SYMBOL if $store->{exclude}{ $f };
no strict 'refs';
next SYMBOL unless exists ${ "${cleanee}::" }{ $f };
if (ref(\${ "${cleanee}::" }{ $f }) eq 'GLOB') {
# convince the Perl debugger to work
# it assumes that sub_fullname($sub) can always be used to find the CV again
# since we are deleting the glob where the subroutine was originally
# defined, that assumption no longer holds, so we need to move it
# elsewhere and point the CV's name to the new glob.
my $sub = \&$fq;
if ( sub_fullname($sub) eq $fq ) {
my $new_fq = "namespace::clean::deleted::$fq";
subname($new_fq, $sub);
*{$new_fq} = $sub;
}
local *__tmp;
# keep original value to restore non-code slots
{ no warnings 'uninitialized'; # fix possible unimports
*__tmp = *{ ${ "${cleanee}::" }{ $f } };
delete ${ "${cleanee}::" }{ $f };
}
SLOT:
# restore non-code slots to symbol.
# omit the FORMAT slot, since perl erroneously puts it into the
# SCALAR slot of the new glob.
for my $t (qw( SCALAR ARRAY HASH IO )) {
next SLOT unless defined *__tmp{ $t };
*{ "${cleanee}::$f" } = *__tmp{ $t };
}
}
else {
# A non-glob in the stash is assumed to stand for some kind
# of function. So far they all do, but the core might change
# this some day. Watch perl5-porters.
delete ${ "${cleanee}::" }{ $f };
}
}
};
sub clean_subroutines {
my ($nc, $cleanee, @subs) = @_;
$RemoveSubs->($cleanee, {}, @subs);
}
=head2 import
Makes a snapshot of the current defined functions and installs a
L<B::Hooks::EndOfScope> hook in the current scope to invoke the cleanups.
=cut
sub import {
my ($pragma, @args) = @_;
my (%args, $is_explicit);
ARG:
while (@args) {
if ($args[0] =~ /^\-/) {
my $key = shift @args;
my $value = shift @args;
$args{ $key } = $value;
}
else {
$is_explicit++;
last ARG;
}
}
my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
if ($is_explicit) {
on_scope_end {
$RemoveSubs->($cleanee, {}, @args);
};
}
else {
# calling class, all current functions and our storage
my $functions = $pragma->get_functions($cleanee);
my $store = $pragma->get_class_store($cleanee);
# except parameter can be array ref or single value
my %except = map {( $_ => 1 )} (
$args{ -except }
? ( ref $args{ -except } eq 'ARRAY' ? @{ $args{ -except } } : $args{ -except } )
: ()
);
# register symbols for removal, if they have a CODE entry
for my $f (keys %$functions) {
next if $except{ $f };
next unless $functions->{ $f }
and *{ $functions->{ $f } }{CODE};
$store->{remove}{ $f } = 1;
}
# register EOF handler on first call to import
unless ($store->{handler_is_installed}) {
on_scope_end {
$RemoveSubs->($cleanee, $store, keys %{ $store->{remove} });
};
$store->{handler_is_installed} = 1;
}
return 1;
}
}
=head2 unimport
This method will be called when you do a
no namespace::clean;
It will start a new section of code that defines functions to clean up.
=cut
sub unimport {
my ($pragma, %args) = @_;
# the calling class, the current functions and our storage
my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
my $functions = $pragma->get_functions($cleanee);
my $store = $pragma->get_class_store($cleanee);
# register all unknown previous functions as excluded
for my $f (keys %$functions) {
next if $store->{remove}{ $f }
or $store->{exclude}{ $f };
$store->{exclude}{ $f } = 1;
}
return 1;
}
=head2 get_class_store
This returns a reference to a hash in a passed package containing
information about function names included and excluded from removal.
=cut
sub get_class_store {
my ($pragma, $class) = @_;
no strict 'refs';
return \%{ "${class}::${STORAGE_VAR}" };
}
=head2 get_functions
Takes a class as argument and returns all currently defined functions
in it as a hash reference with the function name as key and a typeglob
reference to the symbol as value.
=cut
sub get_functions {
my ($pragma, $class) = @_;
return {
map { @$_ } # key => value
grep { *{ $_->[1] }{CODE} } # only functions
map { [$_, qualify_to_ref( $_, $class )] } # get globref
grep { $_ !~ /::$/ } # no packages
do { no strict 'refs'; keys %{ "${class}::" } } # symbol entries
};
}
=head1 BUGS
C<namespace::clean> will clobber any formats that have the same name as
a deleted sub. This is due to a bug in perl that makes it impossible to
re-assign the FORMAT ref into a new glob.
=head1 IMPLEMENTATION DETAILS
This module works through the effect that a
delete $SomePackage::{foo};
will remove the C<foo> symbol from C<$SomePackage> for run time lookups
(e.g., method calls) but will leave the entry alive to be called by
already resolved names in the package itself. C<namespace::clean> will
restore and therefor in effect keep all glob slots that aren't C<CODE>.
A test file has been added to the perl core to ensure that this behaviour
will be stable in future releases.
Just for completeness sake, if you want to remove the symbol completely,
use C<undef> instead.
=head1 SEE ALSO
L<B::Hooks::EndOfScope>
=head1 AUTHOR AND COPYRIGHT
Robert 'phaylon' Sedlacek C<E<lt>rs@474.atE<gt>>, with many thanks to
Matt S Trout for the inspiration on the whole idea.
=head1 LICENSE
This program is free software; you can redistribute it and/or modify
it under the same terms as perl itself.
=cut
no warnings;
'Danger! Laws of Thermodynamics may not apply.'
| carlgao/lenga | images/lenny64-peon/usr/share/perl5/namespace/clean.pm | Perl | mit | 10,875 |
#!/usr/bin/perl
# ----------------------------------------------------------------- #
# The HMM-Based Speech Synthesis System (HTS) #
# developed by HTS Working Group #
# http://hts.sp.nitech.ac.jp/ #
# ----------------------------------------------------------------- #
# #
# Copyright (c) 2008-2012 Nagoya Institute of Technology #
# Department of Computer Science #
# #
# 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 HTS working group nor the names of its #
# contributors may be used to endorse or promote products derived #
# from this software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND #
# CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, #
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF #
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE #
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS #
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, #
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED #
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, #
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON #
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, #
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY #
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# ----------------------------------------------------------------- #
#return filter coefficient by given sampling rate
$target = 6000; # 0000Hz-6000Hz
@coefficient = (
# 0000Hz-0500Hz
[ -0.00302890, -0.00701117, -0.01130619, -0.01494082, -0.01672586, -0.01544189, -0.01006619, 0.00000000, 0.01474923, 0.03347158, 0.05477206, 0.07670890, 0.09703726, 0.11352143, 0.12426379, 0.12799355, 0.12426379, 0.11352143, 0.09703726, 0.07670890, 0.05477206, 0.03347158, 0.01474923, 0.00000000, -0.01006619, -0.01544189, -0.01672586, -0.01494082, -0.01130619, -0.00701117, -0.00302890 ],
# 0500Hz-1000Hz
[ -0.00249420, -0.00282091, 0.00257679, 0.01451271, 0.02868120, 0.03621179, 0.02784469, -0.00000000, -0.04079870, -0.07849207, -0.09392213, -0.07451087, -0.02211575, 0.04567473, 0.10232715, 0.12432599, 0.10232715, 0.04567473, -0.02211575, -0.07451087, -0.09392213, -0.07849207, -0.04079870, -0.00000000, 0.02784469, 0.03621179, 0.02868120, 0.01451271, 0.00257679, -0.00282091, -0.00249420 ],
# 1000Hz-2000Hz
[ -0.00231491, 0.00990113, 0.02086129, -0.00000000, -0.03086123, -0.02180695, 0.00769333, -0.00000000, -0.01127245, 0.04726837, 0.10106105, -0.00000000, -0.17904543, -0.16031428, 0.09497157, 0.25562154, 0.09497157, -0.16031428, -0.17904543, -0.00000000, 0.10106105, 0.04726837, -0.01127245, -0.00000000, 0.00769333, -0.02180695, -0.03086123, -0.00000000, 0.02086129, 0.00990113, -0.00231491 ],
# 2000Hz-3000Hz
[ 0.00231491, 0.00990113, -0.02086129, 0.00000000, 0.03086123, -0.02180695, -0.00769333, -0.00000000, 0.01127245, 0.04726837, -0.10106105, 0.00000000, 0.17904543, -0.16031428, -0.09497157, 0.25562154, -0.09497157, -0.16031428, 0.17904543, 0.00000000, -0.10106105, 0.04726837, 0.01127245, -0.00000000, -0.00769333, -0.02180695, 0.03086123, 0.00000000, -0.02086129, 0.00990113, 0.00231491 ],
# 3000Hz-4000Hz
[ 0.00554149, -0.00981750, 0.00856805, -0.00000000, -0.01267517, 0.02162277, -0.01841647, 0.00000000, 0.02698425, -0.04686914, 0.04150730, -0.00000000, -0.07353666, 0.15896026, -0.22734513, 0.25346255, -0.22734513, 0.15896026, -0.07353666, -0.00000000, 0.04150730, -0.04686914, 0.02698425, 0.00000000, -0.01841647, 0.02162277, -0.01267517, -0.00000000, 0.00856805, -0.00981750, 0.00554149 ]
);
if ( @ARGV < 2 ) {
print "makefilter.pl sampling_rate flag\n";
exit(0);
}
$samprate = $ARGV[0];
$flag = $ARGV[1]; # 0: low-pass 1: high-pass
$rate = $target / $samprate;
if ( $rate <= 3 / 48 ) {
$low_e = 1;
}
elsif ( $rate <= 6 / 48 ) {
$low_e = 2;
}
elsif ( $rate <= 12 / 48 ) {
$low_e = 3;
}
elsif ( $rate <= 18 / 48 ) {
$low_e = 4;
}
else {
$low_e = 5;
}
@low = ();
@high = ();
for ( $i = 0 ; $i < 31 ; $i++ ) {
push( @low, 0.0 );
push( @high, 0.0 );
}
for ( $i = 0 ; $i < 5 ; $i++ ) {
if ( $i < $low_e ) {
for ( $j = 0 ; $j < 31 ; $j++ ) {
$low[$j] += $coefficient[$i][$j];
}
}
else {
for ( $j = 0 ; $j < 31 ; $j++ ) {
$high[$j] += $coefficient[$i][$j];
}
}
}
for ( $i = 0 ; $i < 31 ; $i++ ) {
if ( $i > 0 ) {
print " ";
}
if ( $flag == 0 ) {
print "$low[$i]";
}
else {
print "$high[$i]";
}
}
| yutarochan/JavaOpenJtalk | util/HTS-demo_NIT-ATR503-M001/data/scripts/makefilter.pl | Perl | mit | 5,856 |
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
package Google::Ads::GoogleAds::V8::Services::CustomerManagerLinkService::MoveManagerLinkResponse;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {resourceName => $args->{resourceName}};
# 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/V8/Services/CustomerManagerLinkService/MoveManagerLinkResponse.pm | Perl | apache-2.0 | 1,065 |
#!/usr/bin/perl
package Picard::MarkDuplicates;
use strict;
use warnings;
use File::Basename;
use CQS::PBS;
use CQS::ConfigUtils;
use CQS::SystemUtils;
use CQS::FileUtils;
use CQS::Task;
use CQS::NGSCommon;
use CQS::StringUtils;
our @ISA = qw(CQS::Task);
sub new {
my ($class) = @_;
my $self = $class->SUPER::new();
$self->{_name} = __PACKAGE__;
$self->{_suffix} = "_rd";
bless $self, $class;
return $self;
}
sub perform {
my ( $self, $config, $section ) = @_;
my ( $task_name, $path_file, $pbs_desc, $target_dir, $log_dir, $pbs_dir, $result_dir, $option, $sh_direct, $cluster, $thread ) = $self->init_parameter( $config, $section );
my $picard_jar = get_param_file( $config->{$section}{picard_jar}, "picard_jar", 1, not $self->using_docker() );
my $remove_duplicates = get_option($config, $section, "remove_duplicates", 1);
my $remove_duplicates_option = $remove_duplicates?"true":"false";
my %raw_files = %{ get_raw_files( $config, $section ) };
my $shfile = $self->get_task_filename( $pbs_dir, $task_name );
open( my $sh, ">$shfile" ) or die "Cannot create $shfile";
print $sh get_run_command($sh_direct) . "\n";
for my $sample_name ( sort keys %raw_files ) {
my @sample_files = @{ $raw_files{$sample_name} };
my $sampleFile = $sample_files[0];
my $rmdupFile = $sample_name . ".rmdup.bam";
my $sortedPrefix = $sample_name . ".rmdup_sorted";
my $sortedFile = $sortedPrefix . ".bam";
my $pbs_file = $self->get_pbs_filename( $pbs_dir, $sample_name );
my $pbs_name = basename($pbs_file);
my $log = $self->get_log_filename( $log_dir, $sample_name );
my $cur_dir = create_directory_or_die( $result_dir . "/$sample_name" );
print $sh "\$MYCMD ./$pbs_name \n";
my $log_desc = $cluster->get_log_description($log);
my $pbs = $self->open_pbs( $pbs_file, $pbs_desc, $log_desc, $path_file, $cur_dir, $sortedFile );
print $pbs "
if [ ! -s $rmdupFile ]; then
echo RemoveDuplicate=`date`
java $option -jar $picard_jar MarkDuplicates I=$sampleFile O=$rmdupFile ASSUME_SORTED=true REMOVE_DUPLICATES=$remove_duplicates_option VALIDATION_STRINGENCY=SILENT M=${rmdupFile}.metrics
fi
if [[ -s $rmdupFile && ! -s $sortedFile ]]; then
echo BamSort=`date`
samtools sort $rmdupFile $sortedPrefix
fi
if [[ -s $sortedFile && ! -s ${sortedFile}.bai ]]; then
echo BamIndex=`date`
samtools index $sortedFile
rm $rmdupFile
fi
";
$self->close_pbs( $pbs, $pbs_file );
}
close $sh;
if ( is_linux() ) {
chmod 0755, $shfile;
}
print "!!!shell file $shfile created, you can run this shell file to submit all Picard::MarkDuplicates tasks.\n";
}
sub result {
my ( $self, $config, $section, $pattern ) = @_;
my ( $task_name, $path_file, $pbs_desc, $target_dir, $log_dir, $pbs_dir, $result_dir, $option, $sh_direct ) = $self->init_parameter( $config, $section, 0 );
my %raw_files = %{ get_raw_files( $config, $section ) };
my $result = {};
for my $sample_name ( keys %raw_files ) {
my $sortedFile = $sample_name . ".rmdup_sorted.bam";
my @result_files = ();
push( @result_files, "${result_dir}/${sample_name}/${sortedFile}" );
$result->{$sample_name} = filter_array( \@result_files, $pattern );
}
return $result;
}
1;
| shengqh/ngsperl | lib/Picard/MarkDuplicates.pm | Perl | apache-2.0 | 3,386 |
package Google::Ads::AdWords::v201809::AdGroupCriterionService::getResponse;
use strict;
use warnings;
{ # BLOCK to scope variables
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' }
__PACKAGE__->__set_name('getResponse');
__PACKAGE__->__set_nillable();
__PACKAGE__->__set_minOccurs();
__PACKAGE__->__set_maxOccurs();
__PACKAGE__->__set_ref();
use base qw(
SOAP::WSDL::XSD::Typelib::Element
Google::Ads::SOAP::Typelib::ComplexType
);
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %rval_of :ATTR(:get<rval>);
__PACKAGE__->_factory(
[ qw( rval
) ],
{
'rval' => \%rval_of,
},
{
'rval' => 'Google::Ads::AdWords::v201809::AdGroupCriterionPage',
},
{
'rval' => 'rval',
}
);
} # end BLOCK
} # end of BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201809::AdGroupCriterionService::getResponse
=head1 DESCRIPTION
Perl data type class for the XML Schema defined element
getResponse from the namespace https://adwords.google.com/api/adwords/cm/v201809.
=head1 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=item * rval
$element->set_rval($data);
$element->get_rval();
=back
=head1 METHODS
=head2 new
my $element = Google::Ads::AdWords::v201809::AdGroupCriterionService::getResponse->new($data);
Constructor. The following data structure may be passed to new():
{
rval => $a_reference_to, # see Google::Ads::AdWords::v201809::AdGroupCriterionPage
},
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| googleads/googleads-perl-lib | lib/Google/Ads/AdWords/v201809/AdGroupCriterionService/getResponse.pm | Perl | apache-2.0 | 1,798 |
#!/usr/bin/env perl
#this program takes the two accessions from a blast entry an then puts them back in alphabetical order
#this is done because otherwise we have to create a potentially huge hash that uses a lot of RAM
#essentially puts forward and reverse matches to the accessions are in the same order
#later sorted with linux sort and then filtered so we do not have to do a lot of in memory sorting
#this was a significant problem, especially with larger datasets
#version 0.9.4 program created
use Getopt::Long;
$result=GetOptions ("in=s" => \$in,
"fasta=s" => \$fasta,
"out=s" => \$out);
open IN, $in or die "cannot open alphabetize input file\n";
open OUT, ">$out" or die "cannot write to output file\n";
open FASTA, $fasta or die "Could not open fasta $fasta\n";
$sequence="";
while (<FASTA>){
$line=$_;
chomp $line;
if($line=~/^>(\w{6,10})$/ or $line=~/^>(\w{6,10}\:\d+\:\d+)$/){
$seqlengths{$key}=length $sequence;
$sequence="";
$key=$1;
}else{
$sequence.=$line;
}
}
$seqlengths{$key}=length $sequence;
close FASTA;
while(<IN>){
$line=$_;
chomp $line;
$line=~/^([A-Za-z0-9:]+)\t([A-Za-z0-9:]+)\t(.*)$/;
if($1 lt $2){
print OUT "$line\t$seqlengths{$1}\t$seqlengths{$2}\n";
#print "forward\n";
}else{
print OUT "$2\t$1\t$3\t$seqlengths{$2}\t$seqlengths{$1}\n";
#print "reverse\n";
}
} | EnzymeFunctionInitiative/est-precompute-bw | include/efiest-0.9.5/alphabetize.pl | Perl | apache-2.0 | 1,371 |
#!/usr/bin/perl -w
# titlebytes - find the title and size of documents
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Response;
use URI::Heuristic;
my $raw_url = "http://ec2-23-21-234-240.compute-1.amazonaws.com:8080/jenkins/job/Tools_Cloc-All/lastBuild/consoleText"; #shift or die "usage: $0 url\n";
my $url = URI::Heuristic::uf_urlstr($raw_url);
$| = 1; # to flush next line
printf "%s =>\n\t", $url;
my $ua = LWP::UserAgent->new();
$ua->agent("Schmozilla/v9.14 Platinum"); # give it time, it'll get there
my $req = HTTP::Request->new(GET => $url);
$req->referer("http://dev-ci.rtsaic.com");
# perplex the log analysers
my $response = $ua->request($req);
if ($response->is_error()) {
printf " Cannot connect to %s<br>\n", $raw_url;
printf " %s\n", $response->status_line;
}
else {
my $count;
my $bytes;
my $content = $response->content();
$bytes = length $content;
$count = ($content =~ tr/\n/\n/);
printf " Connection response: %s\n", $response->status_line;
printf "%d lines, %d bytes\n", $response->title(), $count, $bytes;
#printf "\n%s\n", $content;
# \d+ matches one or more integer numbers
my @contentLines = split(/\n/, $content);
my %langCode = ();
my %langFiles = ();
my %langBlank = ();
my %langComment = ();
my $inBlock = "0";
foreach my $line (@contentLines) {
#trim whitespace
my $contentLine = $line;
$contentLine =~ s/^\s+//;
$contentLine =~ s/\s+$//;
#print "line: $contentLine\n";
if ($inBlock eq "0" && $contentLine =~ /\[exec\]\s+Language\s+files\s+blank\s+comment\s+code/) {
#print "In Block\n";
$inBlock = "1";
}
elsif ($inBlock eq "1" && $contentLine =~ /\[exec\]\s+SUM:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/) {
#print "Out Block\n";
$inBlock = "0";
}
elsif ($inBlock eq "1") {
#print "Check Block: $contentLine\n";
if ($contentLine =~ /\[exec\]\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/) {
#print "Str2 Match $0 $1 $2 $3 $4\n";
$langFiles{$1} += $2;
$langBlank{$1} += $3;
$langComment{$1} += $4;
$langCode{$1} += $5;
}
else {
#print "Str2 No Match on $contentLine\n";
}
}
}
my $sumFiles = 0;
my $sumBlank = 0;
my $sumComment = 0;
my $sumCode = 0;
print "-------------------------------------------------------------------------------\n";
print "Language files blank comment code\n";
print "-------------------------------------------------------------------------------\n";
foreach my $lang (keys %langFiles) {
# sum counts
$sumFiles += $langFiles{$lang};
$sumBlank += $langBlank{$lang};
$sumComment += $langComment{$lang};
$sumCode += $langCode{$lang};
# output in formatted form
printf "%-19s %14s %14s %14s %14s\n", $lang, $langFiles{$lang}, $langBlank{$lang}, $langComment{$lang}, $langCode{$lang};
}
print "-------------------------------------------------------------------------------\n";
printf "SUM: %14s %14s %14s %14s\n", $sumFiles, $sumBlank, $sumComment, $sumCode;
print "-------------------------------------------------------------------------------\n";
#my $str1 = " [exec] Language files blank comment code";
#my $str2 = " [exec] Java 30 665 457 1822";
#my $str3 = " [exec] SUM: 31 667 458 1823";
#
#if ($str1 =~ /\s+\[exec\]\s+Language\s+files\s+blank\s+comment\s+code\s*/) {
# print "Str1 Match\n";
#}
#if ($str2 =~ /\s+\[exec\]\s+(\S+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*/) {
# print "Str2 Match $0 $1 $2 $3 $4 $5 $6\n";
#}
#if ($str3 =~ /\s+\[exec\]\s+SUM:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*/) {
# print "Str3 Match\n";
#}
}
| deleidos/digitaledge-platform | commons/buildtools/cloc/cloc-output-summation.pl | Perl | apache-2.0 | 4,331 |
package Paws::EC2::ImportImage;
use Moose;
has Architecture => (is => 'ro', isa => 'Str');
has ClientData => (is => 'ro', isa => 'Paws::EC2::ClientData');
has ClientToken => (is => 'ro', isa => 'Str');
has Description => (is => 'ro', isa => 'Str');
has DiskContainers => (is => 'ro', isa => 'ArrayRef[Paws::EC2::ImageDiskContainer]', traits => ['NameInRequest'], request_name => 'DiskContainer' );
has DryRun => (is => 'ro', isa => 'Bool');
has Hypervisor => (is => 'ro', isa => 'Str');
has LicenseType => (is => 'ro', isa => 'Str');
has Platform => (is => 'ro', isa => 'Str');
has RoleName => (is => 'ro', isa => 'Str');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'ImportImage');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::EC2::ImportImageResult');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::EC2::ImportImage - Arguments for method ImportImage on Paws::EC2
=head1 DESCRIPTION
This class represents the parameters used for calling the method ImportImage on the
Amazon Elastic Compute Cloud service. Use the attributes of this class
as arguments to method ImportImage.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ImportImage.
As an example:
$service_obj->ImportImage(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 Architecture => Str
The architecture of the virtual machine.
Valid values: C<i386> | C<x86_64>
=head2 ClientData => L<Paws::EC2::ClientData>
The client-specific data.
=head2 ClientToken => Str
The token to enable idempotency for VM import requests.
=head2 Description => Str
A description string for the import image task.
=head2 DiskContainers => ArrayRef[L<Paws::EC2::ImageDiskContainer>]
Information about the disk containers.
=head2 DryRun => Bool
Checks whether you have the required permissions for the action,
without actually making the request, and provides an error response. If
you have the required permissions, the error response is
C<DryRunOperation>. Otherwise, it is C<UnauthorizedOperation>.
=head2 Hypervisor => Str
The target hypervisor platform.
Valid values: C<xen>
=head2 LicenseType => Str
The license type to be used for the Amazon Machine Image (AMI) after
importing.
B<Note:> You may only use BYOL if you have existing licenses with
rights to use these licenses in a third party cloud like AWS. For more
information, see Prerequisites in the VM Import/Export User Guide.
Valid values: C<AWS> | C<BYOL>
=head2 Platform => Str
The operating system of the virtual machine.
Valid values: C<Windows> | C<Linux>
=head2 RoleName => Str
The name of the role to use when not using the default role,
'vmimport'.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method ImportImage 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/ImportImage.pm | Perl | apache-2.0 | 3,395 |
#
# Copyright 2021 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package apps::mq::activemq::jmx::mode::listbrokers;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$options{options}->add_options(arguments => {
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
}
sub manage_selection {
my ($self, %options) = @_;
my $request = [
{
mbean => 'org.apache.activemq:brokerName=*,type=Broker',
attributes => [
{ name => 'BrokerName' }
]
}
];
my $datas = $options{custom}->get_attributes(request => $request);
my $results = {};
foreach (keys %$datas) {
$results->{$datas->{$_}->{BrokerName}} = { name => $datas->{$_}->{BrokerName} };
}
return $results;
}
sub run {
my ($self, %options) = @_;
my $results = $self->manage_selection(custom => $options{custom});
foreach (sort keys %$results) {
$self->{output}->output_add(
long_msg => sprintf(
'[name = %s]',
$_
)
);
}
$self->{output}->output_add(
severity => 'OK',
short_msg => 'List brokers:'
);
$self->{output}->display(nolabel => 1, force_ignore_perfdata => 1, force_long_output => 1);
$self->{output}->exit();
}
sub disco_format {
my ($self, %options) = @_;
$self->{output}->add_disco_format(elements => ['name']);
}
sub disco_show {
my ($self, %options) = @_;
my $results = $self->manage_selection(custom => $options{custom});
foreach (sort keys %$results) {
$self->{output}->add_disco_entry(
name => $_
);
}
}
1;
__END__
=head1 MODE
List brokers.
=over 8
=back
=cut
| Tpo76/centreon-plugins | apps/mq/activemq/jmx/mode/listbrokers.pm | Perl | apache-2.0 | 2,649 |
package Google::Ads::AdWords::v201402::ConstantDataService::getUserInterestCriterionResponse;
use strict;
use warnings;
{ # BLOCK to scope variables
sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' }
__PACKAGE__->__set_name('getUserInterestCriterionResponse');
__PACKAGE__->__set_nillable();
__PACKAGE__->__set_minOccurs();
__PACKAGE__->__set_maxOccurs();
__PACKAGE__->__set_ref();
use base qw(
SOAP::WSDL::XSD::Typelib::Element
Google::Ads::SOAP::Typelib::ComplexType
);
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %rval_of :ATTR(:get<rval>);
__PACKAGE__->_factory(
[ qw( rval
) ],
{
'rval' => \%rval_of,
},
{
'rval' => 'Google::Ads::AdWords::v201402::CriterionUserInterest',
},
{
'rval' => 'rval',
}
);
} # end BLOCK
} # end of BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201402::ConstantDataService::getUserInterestCriterionResponse
=head1 DESCRIPTION
Perl data type class for the XML Schema defined element
getUserInterestCriterionResponse from the namespace https://adwords.google.com/api/adwords/cm/v201402.
=head1 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=item * rval
$element->set_rval($data);
$element->get_rval();
=back
=head1 METHODS
=head2 new
my $element = Google::Ads::AdWords::v201402::ConstantDataService::getUserInterestCriterionResponse->new($data);
Constructor. The following data structure may be passed to new():
{
rval => $a_reference_to, # see Google::Ads::AdWords::v201402::CriterionUserInterest
},
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| gitpan/GOOGLE-ADWORDS-PERL-CLIENT | lib/Google/Ads/AdWords/v201402/ConstantDataService/getUserInterestCriterionResponse.pm | Perl | apache-2.0 | 1,893 |
# 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::Services::SmartCampaignSuggestService::SuggestSmartCampaignBudgetOptionsRequest;
use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
sub new {
my ($class, $args) = @_;
my $self = {
campaign => $args->{campaign},
customerId => $args->{customerId},
suggestionInfo => $args->{suggestionInfo}};
# 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/Services/SmartCampaignSuggestService/SuggestSmartCampaignBudgetOptionsRequest.pm | Perl | apache-2.0 | 1,177 |
package Paws::SSM::DescribeDocument;
use Moose;
has DocumentVersion => (is => 'ro', isa => 'Str');
has Name => (is => 'ro', isa => 'Str', required => 1);
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeDocument');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::SSM::DescribeDocumentResult');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::SSM::DescribeDocument - Arguments for method DescribeDocument on Paws::SSM
=head1 DESCRIPTION
This class represents the parameters used for calling the method DescribeDocument on the
Amazon Simple Systems Manager (SSM) service. Use the attributes of this class
as arguments to method DescribeDocument.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeDocument.
As an example:
$service_obj->DescribeDocument(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 DocumentVersion => Str
The document version for which you want information. Can be a specific
version or the default version.
=head2 B<REQUIRED> Name => Str
The name of the Systems Manager document.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method DescribeDocument in L<Paws::SSM>
=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/SSM/DescribeDocument.pm | Perl | apache-2.0 | 1,797 |
package Paws::Route53::DeleteTrafficPolicyResponse;
use Moose;
use MooseX::ClassAttribute;
class_has _payload => (is => 'ro', default => '');
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::Route53::DeleteTrafficPolicyResponse
=head1 ATTRIBUTES
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/Route53/DeleteTrafficPolicyResponse.pm | Perl | apache-2.0 | 325 |
=head1 TITLE
wait() and waitpid() should return false on failure
=head1 VERSION
Maintainer: Nathan Torkington <gnat@frii.com>
Date: 13 Sep 2000
Mailing List: perl6-language@perl.org
Number: 220
Version: 1
Status: Developing
=head1 ABSTRACT
All system calls in Perl should return false on failure.
=head1 DESCRIPTION
wait() and waitpid() return -1 on failure. They should
return C<undef>, and return C<"0 but true"> if the system call
returned 0.
=head1 IMPLEMENTATION
Straightforward. The perl526 translator simply wraps the perl6 wait()
and waitpid():
do { my $r = waitpid(...); return -1 if !defined $r;
return 0 if !$r; $r }
=head1 REFERENCES
the perlfunc manpage for information on waitpid() and wait()
| autarch/perlweb | docs/dev/perl6/rfc/220.pod | Perl | apache-2.0 | 743 |
#
# Copyright 2015 Electric Cloud, 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.
#
##########################
# cleanup.pl
##########################
use warnings;
use strict;
use Encode;
use utf8;
use open IO => ':encoding(utf8)';
my $opts;
# Configuration: A commander configuration previously created.
$opts->{connection_config} = q{$[connection_config]};
# Server: Id for the server to delete.
$opts->{server_id} = q{$[server_id]};
# Resource: name of the resource to delete.
$opts->{resource_name} = q{$[resource_name]};
$[/myProject/procedure_helpers/preamble]
$openstack->cleanup();
exit($opts->{exitcode});
| electric-cloud/EC-OpenStack | src/main/resources/project/procedures/cleanup.pl | Perl | apache-2.0 | 1,137 |
package Paws::DeviceFarm::ListOfferingPromotions;
use Moose;
has NextToken => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'nextToken' );
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListOfferingPromotions');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::DeviceFarm::ListOfferingPromotionsResult');
class_has _result_key => (isa => 'Str', is => 'ro');
1;
### main pod documentation begin ###
=head1 NAME
Paws::DeviceFarm::ListOfferingPromotions - Arguments for method ListOfferingPromotions on Paws::DeviceFarm
=head1 DESCRIPTION
This class represents the parameters used for calling the method ListOfferingPromotions on the
AWS Device Farm service. Use the attributes of this class
as arguments to method ListOfferingPromotions.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListOfferingPromotions.
As an example:
$service_obj->ListOfferingPromotions(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 NextToken => Str
An identifier that was returned from the previous call to this
operation, which can be used to return the next set of items in the
list.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method ListOfferingPromotions in L<Paws::DeviceFarm>
=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/DeviceFarm/ListOfferingPromotions.pm | Perl | apache-2.0 | 1,819 |
=head1 LICENSE
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2017] EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker -
=head1 SYNOPSIS
my $repeat_masker = Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker->
new(
-input_id => 'contig::AL805961.22.1.166258:1:166258:1',
-db => $db,
-analysis => $analysis,
);
$repeat_masker->fetch_input;
$repeat_masker->run;
$repeat_masker->write_output;
=head1 DESCRIPTION
This module provides an interface between the ensembl database and
the Runnable RepeatMasker which wraps the program RepeatMasker
This module can fetch appropriate input from the database
pass it to the runnable then write the results back to the database
in the repeat_feature and repeat_consensus tables
=head1 METHODS
=cut
package Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveRepeatMasker;
use strict;
use warnings;
use feature 'say';
use Bio::EnsEMBL::Analysis;
use Bio::EnsEMBL::Analysis::Runnable::RepeatMasker;
use parent ('Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveBaseRunnableDB');
=head2 fetch_input
Arg [1] : Bio::EnsEMBL::Analysis::RunnableDB::RepeatMasker
Function : fetch data out of database and create runnable
Returntype: 1
Exceptions: none
Example :
=cut
sub fetch_input{
my ($self) = @_;
my $dba = $self->hrdb_get_dba($self->param('target_db'));
$self->hrdb_set_con($dba,'target_db');
my $input_id = $self->param('iid');
my $slice = $self->fetch_sequence($input_id,$dba);
$self->query($slice);
my $analysis = Bio::EnsEMBL::Analysis->new(
-logic_name => $self->param('logic_name'),
-module => $self->param('module'),
-program_file => $self->param('repeatmasker_path'),
-parameters => $self->param('commandline_params'),
);
$self->param('analysis',$analysis);
my %parameters;
if($self->parameters_hash){
%parameters = %{$self->parameters_hash};
}
my $runnable = Bio::EnsEMBL::Analysis::Runnable::RepeatMasker->new
(
-query => $self->query,
-program => $analysis->program_file,
-analysis => $self->param('analysis'),
%parameters,
);
$self->runnable($runnable);
say "Runnable ref: ".ref($self->runnable);
return 1;
}
sub run {
my ($self) = @_;
foreach my $runnable(@{$self->runnable}){
$runnable->run;
$self->output($runnable->output);
}
return 1;
}
sub write_output {
my ($self) = @_;
my $rf_adaptor = $self->hrdb_get_con('target_db')->get_RepeatFeatureAdaptor;
my $analysis = $self->param('analysis');
# Keep track of the analysis_id we have here, because the store()
# method might change it if the analysis does not already exist in
# the output database, which will make running the next job difficult
# or impossible (because the analysis tables weren't in sync). If we
# find that the analysis ID changes, throw() so that the genebuilder
# realizes that she has to sync thhe analysis tables.
foreach my $feature ( @{ $self->output() } ) {
$feature->analysis($analysis);
if ( !defined( $feature->slice() ) ) {
$feature->slice( $self->query() );
}
$self->feature_factory->validate($feature);
eval { $rf_adaptor->store($feature); };
if ($@) {
$self->throw("RunnableDB::write_output() failed:failed to store '".$feature."' into database '".$rf_adaptor->dbc()->dbname()."': ".$@);
}
}
my $output_hash = {};
$output_hash->{'iid'} = $self->param('iid');
$self->dataflow_output_id($output_hash,4);
$self->dataflow_output_id($output_hash,1);
return 1;
}
1;
| james-monkeyshines/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/Hive/RunnableDB/HiveAssemblyLoading/HiveRepeatMasker.pm | Perl | apache-2.0 | 4,702 |
=head1 LICENSE
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2018] EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::Analysis::RunnableDB::AlignmentNets -
=head1 SYNOPSIS
my $db = Bio::EnsEMBL::DBAdaptor->new($locator);
my $genscan = Bio::EnsEMBL::Analysis::RunnableDB::AlignmentNets->new (
-db => $db,
-input_id => $input_id
-analysis => $analysis );
$genscan->fetch_input();
$genscan->run();
$genscan->write_output(); #writes to DB
=head1 DESCRIPTION
Given an compara MethodLinkSpeciesSet identifer, and a reference genomic
slice identifer, fetches the GenomicAlignBlocks from the given compara
database, infers chains from the group identifiers, and then forms
an alignment net from the chains and writes the result
back to the database.
This module (at least for now) relies heavily on Jim Kent\'s Axt tools.
=head1 METHODS
=cut
package Bio::EnsEMBL::Analysis::RunnableDB::AlignmentNets;
use warnings ;
use vars qw(@ISA);
use strict;
use Bio::EnsEMBL::Analysis::RunnableDB;
use Bio::EnsEMBL::Analysis::Config::General;
use Bio::EnsEMBL::Analysis::RunnableDB::AlignmentFilter;
use Bio::EnsEMBL::Analysis::Config::AlignmentFilter;
use Bio::EnsEMBL::Analysis::Runnable::AlignmentNets;
use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor;
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::DnaDnaAlignFeature;
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::Utils::Argument qw( rearrange );
@ISA = qw(Bio::EnsEMBL::Analysis::RunnableDB::AlignmentFilter);
############################################################
sub new {
my ($class,@args) = @_;
my $self = $class->SUPER::new(@args);
$self->read_and_check_config($NET_CONFIG_BY_LOGIC);
return $self;
}
############################################################
sub fetch_input {
my( $self) = @_;
$self->throw("No input id") unless defined($self->input_id);
my ($seq_name, $seq_start, $seq_end);
if ($self->input_id =~ /^([^:]+):(\d+):(\d+)$/) {
($seq_name, $seq_start, $seq_end) = ($1, $2, $3);
} elsif ($self->input_id =~ /(\S+)/) {
$seq_name = $1;
} else {
throw("Input id could not be parsed: ", $self->input_id);
}
if ($self->QUERY_CORE_DB) {
my $q_dbh = Bio::EnsEMBL::DBSQL::DBAdaptor->new(%{$self->QUERY_CORE_DB});
my $sl = $q_dbh->get_SliceAdaptor->fetch_by_region('toplevel',
$seq_name);
my @segs = @{$sl->project('seqlevel')};
$self->query_seq_level_projection(\@segs);
#foreach my $seg (@segs) {
# printf("FROM_START %d FROM_END %d TO_SLICE %s TO_START %d TO_END %d\n",
# $seg->from_start, $seg->from_end, $seg->to_Slice->seq_region_name,
# $seg->to_Slice->start, $seg->to_Slice->end);
#}
}
my $compara_dbh = Bio::EnsEMBL::Compara::DBSQL::DBAdaptor->new(%{$self->COMPARA_DB});
my $query_species = $self->QUERY_SPECIES;
my $target_species = $self->TARGET_SPECIES;
my $q_gdb = $compara_dbh->get_GenomeDBAdaptor->fetch_by_name_assembly($query_species);
my $t_gdb = $compara_dbh->get_GenomeDBAdaptor->fetch_by_name_assembly($target_species);
throw("Could not get GenomeDB for '$query_species'") if not defined $q_gdb;
throw("Could not get GenomeDB for '$target_species'") if not defined $t_gdb;
################################################################
# get the compara data: MethodLinkSpeciesSet, reference DnaFrag,
# and GenomicAlignBlocks
################################################################
my $mlss = $compara_dbh->get_MethodLinkSpeciesSetAdaptor
->fetch_by_method_link_type_GenomeDBs($self->INPUT_METHOD_LINK_TYPE,
[$q_gdb, $t_gdb]);
throw("No MethodLinkSpeciesSet for :\n" .
$self->INPUT_METHOD_LINK_TYPE . "\n" .
$query_species . "\n" .
$target_species)
if not $mlss;
my $out_mlss = $compara_dbh->get_MethodLinkSpeciesSetAdaptor
->fetch_by_method_link_type_GenomeDBs($self->OUTPUT_METHOD_LINK_TYPE,
[$q_gdb, $t_gdb]);
throw("No MethodLinkSpeciesSet for :\n" .
$self->OUTPUT_METHOD_LINK_TYPE . "\n" .
$query_species . "\n" .
$target_species)
if not $out_mlss;
######## needed for output####################
$self->output_MethodLinkSpeciesSet($out_mlss);
my $ref_dnafrag = $compara_dbh->get_DnaFragAdaptor->fetch_by_GenomeDB_and_name($q_gdb,
$seq_name);
my $gen_al_blocks = $compara_dbh->get_GenomicAlignBlockAdaptor
->fetch_all_by_MethodLinkSpeciesSet_DnaFrag($mlss, $ref_dnafrag, $seq_start, $seq_end);
###################################################################
# get the target slices and bin the GenomicAlignBlocks by group id
###################################################################
my (%features_by_group);
foreach my $block (@$gen_al_blocks) {
my ($qy_al) = $block->reference_genomic_align;
my ($tg_al) = @{$block->get_all_non_reference_genomic_aligns};
if (not exists($self->query_DnaFrag_hash->{$qy_al->dnafrag->name})) {
######### needed for output ######################################
$self->query_DnaFrag_hash->{$qy_al->dnafrag->name} = $qy_al->dnafrag;
}
if (not exists($self->target_DnaFrag_hash->{$tg_al->dnafrag->name})) {
######### needed for output #######################################
$self->target_DnaFrag_hash->{$tg_al->dnafrag->name} = $tg_al->dnafrag;
}
my $daf_cigar = $self->daf_cigar_from_compara_cigars($qy_al->cigar_line,
$tg_al->cigar_line);
my $daf = Bio::EnsEMBL::DnaDnaAlignFeature->new
(-seqname => $qy_al->dnafrag->name,
-start => $qy_al->dnafrag_start,
-end => $qy_al->dnafrag_end,
-strand => $qy_al->dnafrag_strand,
-hseqname => $tg_al->dnafrag->name,
-hstart => $tg_al->dnafrag_start,
-hend => $tg_al->dnafrag_end,
-hstrand => $tg_al->dnafrag_strand,
-score => $block->score,
-cigar_string => $daf_cigar,
-group_id => $block->group_id);
push @{$features_by_group{$block->group_id}}, $daf;
}
$self->chains($self->sort_chains_by_max_block_score([values %features_by_group]));
if ($self->METHOD eq 'STANDARD' or $self->METHOD eq 'SYNTENIC') {
my $run = $self->make_runnable($self->METHOD eq 'SYNTENIC');
$self->runnable($run);
}
}
############################################################
sub run{
my ($self) = @_;
if (@{$self->runnable}) {
$self->SUPER::run;
} else {
my $filtered_chains;
if ($self->METHOD eq 'SIMPLE_HIGH') {
$filtered_chains = $self->calculate_simple_high_net($self->chains);
} elsif ($self->METHOD eq 'SIMPLE_LOW') {
$filtered_chains = $self->calculate_simple_low_net($self->chains);
}
if (defined $filtered_chains) {
my $converted_out = $self->convert_output($filtered_chains);
$self->output($converted_out);
}
}
}
###############################################################
sub calculate_simple_high_net {
my ($self, $chains) = @_;
my (@net_chains, @retained_blocks, %contigs_of_kept_blocks);
# Junk chains that have extent overlap
# with retained chains so far
foreach my $c (@$chains) {
my @b = sort { $a->start <=> $b->start } @$c;
my $c_st = $b[0]->start;
my $c_en = $b[-1]->end;
my $keep_chain = 1;
foreach my $oc (@net_chains) {
my @ob = sort { $a->start <=> $b->start } @$oc;
my $oc_st = $ob[0]->start;
my $oc_en = $ob[-1]->end;
if ($oc_st <= $c_en and $oc_en >= $c_st) {
# overlap; junk
$keep_chain = 0;
last;
}
}
if ($keep_chain) {
my (%contigs_of_blocks, @split_blocks);
foreach my $bl (@b) {
my ($inside_seg, @overlap_segs);
foreach my $seg (@{$self->query_seq_level_projection}) {
if ($bl->start >= $seg->from_start and
$bl->end <= $seg->from_end) {
$inside_seg = $seg;
last;
} elsif ($seg->from_start <= $bl->end and
$seg->from_end >= $bl->start) {
push @overlap_segs, $seg;
} elsif ($seg->from_start > $bl->end) {
last;
}
}
if (defined $inside_seg) {
push @split_blocks, $bl;
$contigs_of_blocks{$bl} = $inside_seg;
} else {
my @cut_blocks;
foreach my $seg (@overlap_segs) {
my ($reg_start, $reg_end) = ($bl->start, $bl->end);
$reg_start = $seg->from_start if $seg->from_start > $reg_start;
$reg_end = $seg->from_end if $seg->from_end < $reg_end;
my $cut_block = $bl->restrict_between_positions($reg_start,
$reg_end,
"SEQ");
if (defined $cut_block) {
push @cut_blocks, $cut_block;
$contigs_of_blocks{$cut_block} = $seg;
}
}
push @split_blocks, @cut_blocks;
}
}
@b = @split_blocks;
my %new_block;
map { $new_block{$_} = 1 } @b;
my @new_list = (@retained_blocks, @b);
@new_list = sort { $a->start <=> $b->start } @new_list;
NEWBLOCK:
for(my $i = 0; $i < @new_list; $i++) {
my $bl = $new_list[$i];
if (exists($new_block{$bl})) {
my ($flank_left, $flank_right);
if ($i > 0 and
not exists($new_block{$new_list[$i-1]})) {
$flank_left = $new_list[$i-1];
}
if ($i < scalar(@new_list) - 1 and
not exists($new_block{$new_list[$i+1]})) {
$flank_right = $new_list[$i+1];
}
if (defined $flank_left and
$contigs_of_blocks{$bl}->to_Slice->seq_region_name eq
$contigs_of_kept_blocks{$flank_left}->to_Slice->seq_region_name
) {
$keep_chain = 0;
last NEWBLOCK;
}
if (defined $flank_right and
$contigs_of_blocks{$bl}->to_Slice->seq_region_name eq
$contigs_of_kept_blocks{$flank_right}->to_Slice->seq_region_name
) {
$keep_chain = 0;
last NEWBLOCK;
}
}
}
if ($keep_chain) {
foreach my $bid (keys %contigs_of_blocks) {
$contigs_of_kept_blocks{$bid} = $contigs_of_blocks{$bid};
}
push @net_chains, \@b;
push @retained_blocks, @b;
@retained_blocks = sort { $a->start <=> $b->start } @retained_blocks;
}
}
}
return \@net_chains;
}
################################################################
sub calculate_simple_low_net {
my ($self, $chains) = @_;
my (@net_chains, @retained_blocks, %contigs_of_kept_blocks);
foreach my $c (@$chains) {
my @b = sort { $a->start <=> $b->start } @$c;
my $keep_chain = 1;
BLOCK: foreach my $b (@b) {
OTHER_BLOCK: foreach my $ob (@retained_blocks) {
if ($ob->start <= $b->end and $ob->end >= $b->start) {
$keep_chain = 0;
last BLOCK;
} elsif ($ob->start > $b->end) {
last OTHER_BLOCK;
}
}
}
if ($keep_chain) {
my (%contigs_of_blocks, @split_blocks);
foreach my $bl (@b) {
my ($inside_seg, @overlap_segs);
foreach my $seg (@{$self->query_seq_level_projection}) {
if ($bl->start >= $seg->from_start and
$bl->end <= $seg->from_end) {
$inside_seg = $seg;
last;
} elsif ($seg->from_start <= $bl->end and
$seg->from_end >= $bl->start) {
push @overlap_segs, $seg;
} elsif ($seg->from_start > $bl->end) {
last;
}
}
if (defined $inside_seg) {
push @split_blocks, $bl;
$contigs_of_blocks{$bl} = $inside_seg;
} else {
my @cut_blocks;
foreach my $seg (@overlap_segs) {
my ($reg_start, $reg_end) = ($bl->start, $bl->end);
$reg_start = $seg->from_start if $seg->from_start > $reg_start;
$reg_end = $seg->from_end if $seg->from_end < $reg_end;
my $cut_block = $bl->restrict_between_positions($reg_start,
$reg_end,
"SEQ");
if (defined $cut_block) {
push @cut_blocks, $cut_block;
$contigs_of_blocks{$cut_block} = $seg;
}
}
push @split_blocks, @cut_blocks;
}
}
@b = @split_blocks;
my %new_block;
map { $new_block{$_} = 1 } @b;
my @new_list = (@retained_blocks, @b);
@new_list = sort { $a->start <=> $b->start } @new_list;
NEWBLOCK:
for(my $i = 0; $i < @new_list; $i++) {
my $bl = $new_list[$i];
if (exists($new_block{$bl})) {
my ($flank_left, $flank_right);
if ($i > 0 and
not exists($new_block{$new_list[$i-1]})) {
$flank_left = $new_list[$i-1];
}
if ($i < scalar(@new_list) - 1 and
not exists($new_block{$new_list[$i+1]})) {
$flank_right = $new_list[$i+1];
}
if (defined $flank_left and
#($flank_left->hseqname ne $bl->hseqname or
# $flank_left->hstrand != $bl->hstrand or
# ($bl->hstrand > 0 and $flank_left->hend >= $bl->hstart) or
# ($bl->hstrand < 0 and $flank_left->hstart <= $bl->hend)) and
$contigs_of_blocks{$bl}->to_Slice->seq_region_name eq
$contigs_of_kept_blocks{$flank_left}->to_Slice->seq_region_name
) {
$keep_chain = 0;
last NEWBLOCK;
}
if (defined $flank_right and
#($flank_right->hseqname ne $bl->hseqname or
# $flank_right->hstrand != $bl->hstrand or
# ($bl->hstrand > 0 and $flank_right->hstart <= $bl->hend) or
# ($bl->hstrand < 0 and $flank_right->hend >= $bl->hstart)) and
$contigs_of_blocks{$bl}->to_Slice->seq_region_name eq
$contigs_of_kept_blocks{$flank_right}->to_Slice->seq_region_name
) {
$keep_chain = 0;
last NEWBLOCK;
}
}
}
if ($keep_chain) {
foreach my $bid (keys %contigs_of_blocks) {
$contigs_of_kept_blocks{$bid} = $contigs_of_blocks{$bid};
}
push @net_chains, \@b;
push @retained_blocks, @b;
@retained_blocks = sort { $a->start <=> $b->start } @retained_blocks;
}
}
}
return \@net_chains;
}
############################################################
sub make_runnable {
my ($self, $syntenic) = @_;
my (%query_lengths, %target_lengths);
foreach my $nm (keys %{$self->query_DnaFrag_hash}) {
$query_lengths{$nm} = $self->query_DnaFrag_hash->{$nm}->length;
}
foreach my $nm (keys %{$self->target_DnaFrag_hash}) {
$target_lengths{$nm} = $self->target_DnaFrag_hash->{$nm}->length;
}
my %parameters = (-analysis => $self->analysis,
-chains => $self->chains,
-query_lengths => \%query_lengths,
-target_lengths => \%target_lengths,
-min_chain_score => $self->MIN_CHAIN_SCORE,
-filter_non_syntenic => $syntenic);
$parameters{-chainNet} = $self->CHAIN_NET
? $self->CHAIN_NET
: $BIN_DIR . "/" . "chainNet";
$parameters{-netSyntenic} = $self->NET_SYNTENIC
? $self->NET_SYNTENIC
: $BIN_DIR . "/" . "netSyntenic";
$parameters{-netFilter} = $self->NET_FILTER
? $self->NET_FILTER
: $BIN_DIR . "/" . "netFilter";
my $run = Bio::EnsEMBL::Analysis::Runnable::AlignmentNets->new(%parameters);
return $run;
}
##############################################################
sub chains {
my ($self,$value) = @_;
if (defined $value) {
$self->{_chains} = $value;
}
return $self->{_chains};
}
sub query_seq_level_projection {
my ($self, $val) = @_;
if (defined $val) {
$self->{_query_proj_segs} = $val;
}
return $self->{_query_proj_segs};
}
####################################
# config variable holders
####################################
sub read_and_check_config {
my ($self, $hash) = @_;
$self->SUPER::read_and_check_config($hash);
my $logic = $self->analysis->logic_name;
foreach my $var (qw(INPUT_METHOD_LINK_TYPE
OUTPUT_METHOD_LINK_TYPE
QUERY_SPECIES
TARGET_SPECIES
COMPARA_DB
METHOD)) {
throw("You must define $var in config for logic '$logic'" .
" or in the DEFAULT entry")
if not $self->$var;
}
# check for sanity
my %allowable_methods =
(
STANDARD => 1,
SYNTENIC => 1,
SIMPLE_HIGH => 1,
SIMPLE_MEDIUM => 1,
SIMPLE_LOW => 1,
);
if ($self->METHOD and
not $allowable_methods{$self->METHOD}) {
throw("You must set METHOD to one of the reserved names\n" .
"See the .example file for these names");
}
}
sub QUERY_CORE_DB {
my ($self, $val) = @_;
if (defined $val) {
$self->{_query_core_db} = $val;
}
return $self->{_query_core_db};
}
sub QUERY_SPECIES {
my ($self, $val) = @_;
if (defined $val) {
$self->{_query_species} = $val;
}
return $self->{_query_species};
}
sub TARGET_SPECIES {
my ($self, $val) = @_;
if (defined $val) {
$self->{_target_species} = $val;
}
return $self->{_target_species};
}
sub METHOD {
my ($self, $val) = @_;
if (defined $val) {
$self->{_primary_method} = $val;
}
return $self->{_primary_method};
}
sub CHAIN_NET {
my ($self, $val) = @_;
if (defined $val) {
$self->{_chain_net_prog} = $val;
}
return $self->{_chain_net_prog};
}
sub NET_SYNTENIC {
my ($self, $val) = @_;
if (defined $val) {
$self->{_net_syntenic_prog} = $val;
}
return $self->{_net_syntenic_prog};
}
sub NET_FILTER {
my ($self, $val) = @_;
if (defined $val) {
$self->{_net_filter_prog} = $val;
}
return $self->{_net_filter_prog};
}
1;
| kiwiroy/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/RunnableDB/AlignmentNets.pm | Perl | apache-2.0 | 19,849 |
package VMOMI::ClusterActionHistory;
use parent 'VMOMI::DynamicData';
use strict;
use warnings;
our @class_ancestors = (
'DynamicData',
);
our @class_members = (
['action', 'ClusterAction', 0, ],
['time', undef, 0, ],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/ClusterActionHistory.pm | Perl | apache-2.0 | 455 |
package VMOMI::ClusterDasHostRecommendation;
use parent 'VMOMI::DynamicData';
use strict;
use warnings;
our @class_ancestors = (
'DynamicData',
);
our @class_members = (
['host', 'ManagedObjectReference', 0, ],
['drsRating', undef, 0, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/ClusterDasHostRecommendation.pm | Perl | apache-2.0 | 476 |
package resources::server;
use strict;
use warnings;
no warnings('once');
use Conf;
use Data::Dumper;
use Cache::Memcached;
use parent qw(resources::resource);
use WebApplicationDBHandle;
# Override parent constructor
sub new {
my ($class, @args) = @_;
# Call the constructor of the parent class
my $self = $class->SUPER::new(@args);
# Add name / attributes
$self->{name} = "server";
$self->{attributes} = { "id" => [ 'string', 'unique identifier of this server' ],
"version" => [ 'string', 'version number of the server' ],
"status" => [ 'string', 'status of the server' ],
"info" => [ 'string', 'informational text, i.e. downtime warnings' ],
"metagenomes" => [ 'integer', 'total number of metagenomes' ],
"public_metagenomes" => [ 'integer', 'total number of public metagenomes' ],
"sequences" => [ 'integer', 'total number of sequences' ],
"basepairs" => [ 'integer', 'total number of basepairs' ],
"url" => [ 'uri', 'resource location of this object instance' ]
};
return $self;
}
# resource is called without any parameters
# this method must return a description of the resource
sub info {
my ($self) = @_;
my $content = { 'name' => $self->name,
'url' => $self->cgi->url."/".$self->name,
'description' => "The server resource returns information about a server.",
'type' => 'object',
'documentation' => $self->cgi->url.'/api.html#'.$self->name,
'requests' => [ { 'name' => "info",
'request' => $self->cgi->url."/".$self->name,
'description' => "Returns the server information.",
'method' => "GET" ,
'type' => "synchronous" ,
'attributes' => "self",
'parameters' => { 'options' => {},
'required' => {},
'body' => {} } },
{ 'name' => "instance",
'request' => $self->cgi->url."/".$self->name."/{ID}",
'description' => "Returns a single user object.",
'example' => [ 'curl -X GET "'.$self->cgi->url."/".$self->name.'/MG-RAST"',
"info for the MG-RAST server" ],
'method' => "GET",
'type' => "synchronous" ,
'attributes' => $self->attributes,
'parameters' => { 'options' => {},
'required' => { "id" => [ "string", "unique server ID" ] },
'body' => {} } },
]
};
$self->return_data($content);
}
# the resource is called with an id parameter
sub instance {
my ($self) = @_;
my $master = $self->connect_to_datasource();
my $dis_msg;
my $disabled = "MG-RAST.disabled";
if (-e $disabled) {
open(MSG, "$disabled");
$dis_msg = <MSG>;
close(MSG);
}
my $inf_msg = "";
my $motd_file = "MG-RAST.motd";
if (-f $motd_file && open(FILE, $motd_file)) {
while (<FILE>) {
$inf_msg .= $_;
}
close FILE;
}
# cache DB counts
my $counts = {};
my $memd = new Cache::Memcached {'servers' => $Conf::web_memcache, 'debug' => 0, 'compress_threshold' => 10_000 };
my $cache_key = "mgcounts";
my $cdata = $memd->get("mgcounts");
if ($cdata) {
$counts = $cdata;
} else {
$counts = {
"metagenomes" => $master->Job->count_all(),
"public_metagenomes" => $master->Job->count_public(),
"sequences" => $master->Job->count_total_sequences(),
"basepairs" => $master->Job->count_total_bp()
};
$memd->set("mgcounts", $counts, 7200);
}
$memd->disconnect_all;
# prepare data
my $data = {
"id" => "MG-RAST",
"version" => $Conf::server_version,
"status" => $dis_msg ? "server down" : "ok",
"info" => $dis_msg ? $dis_msg : $inf_msg,
"metagenomes" => $counts->{metagenomes},
"public_metagenomes" => $counts->{public_metagenomes},
"sequences" => $counts->{sequences},
"basepairs" => $counts->{basepairs},
"url" => $self->cgi->url."/".$self->name."/MG-RAST"
};
$self->return_data($data);
}
1;
| wilke/MG-RAST | src/MGRAST/lib/resources/server.pm | Perl | bsd-2-clause | 5,152 |
package t::StapThread;
use strict;
use warnings;
our $GCScript = <<'_EOC_';
global ids, cur
global in_req = 0
global alive_reqs
function gen_id(k) {
if (ids[k]) return ids[k]
ids[k] = ++cur
return cur
}
F(ngx_http_handler) {
if (!alive_reqs[$r] && $r == $r->main) {
in_req++
alive_reqs[$r] = 1
if (in_req == 1) {
delete ids
cur = 0
}
}
}
F(ngx_http_free_request) {
if (alive_reqs[$r]) {
in_req--
delete alive_reqs[$r]
}
}
F(ngx_http_terminate_request) {
if (alive_reqs[$r]) {
in_req--
delete alive_reqs[$r]
}
}
M(http-lua-user-thread-spawn) {
p = gen_id($arg2)
c = gen_id($arg3)
printf("spawn user thread %x in %x\n", c, p)
}
M(http-lua-thread-delete) {
t = gen_id($arg2)
printf("delete thread %x\n", t)
}
M(http-lua-user-coroutine-create) {
p = gen_id($arg2)
c = gen_id($arg3)
printf("create %x in %x\n", c, p)
}
M(http-lua-coroutine-done) {
t = gen_id($arg2)
printf("terminate %d: %s\n", t, $arg3 ? "ok" : "fail")
#print_ubacktrace()
}
_EOC_
our $StapScript = <<'_EOC_';
global ids, cur
global timers
global in_req = 0
global co_status
global alive_reqs
function gen_id(k) {
if (ids[k]) return ids[k]
ids[k] = ++cur
return cur
}
F(ngx_http_handler) {
if (!alive_reqs[$r] && $r == $r->main) {
in_req++
alive_reqs[$r] = 1
printf("in req: %d\n", in_req)
if (in_req == 1) {
delete ids
cur = 0
co_status[0] = "running"
co_status[1] = "suspended"
co_status[2] = "normal"
co_status[3] = "dead"
}
}
}
F(ngx_http_free_request) {
if (alive_reqs[$r]) {
in_req--
println("free request")
delete alive_reqs[$r]
}
}
F(ngx_http_terminate_request) {
if (alive_reqs[$r]) {
in_req--
println("terminate request")
delete alive_reqs[$r]
}
}
F(ngx_http_lua_post_thread) {
id = gen_id($coctx->co)
printf("post thread %d\n", id)
}
M(timer-add) {
timers[$arg1] = $arg2
printf("add timer %d\n", $arg2)
}
M(timer-del) {
printf("delete timer %d\n", timers[$arg1])
delete timers[$arg1]
}
M(timer-expire) {
printf("expire timer %d\n", timers[$arg1])
delete timers[$arg1]
}
F(ngx_http_lua_sleep_handler) {
printf("sleep handler called\n")
}
F(ngx_http_lua_run_thread) {
id = gen_id($ctx->cur_co_ctx->co)
printf("run thread %d\n", id)
#if (id == 1) {
#print_ubacktrace()
#}
}
probe process("/usr/local/openresty-debug/luajit/lib/libluajit-5.1.so.2").function("lua_resume") {
id = gen_id($L)
printf("lua resume %d\n", id)
}
M(http-lua-user-thread-spawn) {
p = gen_id($arg2)
c = gen_id($arg3)
printf("spawn uthread %x in %x\n", c, p)
}
M(http-lua-thread-delete) {
t = gen_id($arg2)
uthreads = @cast($arg3, "ngx_http_lua_ctx_t")->uthreads
printf("delete thread %x (uthreads %d)\n", t, uthreads)
#print_ubacktrace()
}
M(http-lua-run-posted-thread) {
t = gen_id($arg2)
printf("run posted thread %d (status %s)\n", t, co_status[$arg3])
}
M(http-lua-user-coroutine-resume) {
p = gen_id($arg2)
c = gen_id($arg3)
printf("resume %x in %x\n", c, p)
}
M(http-lua-thread-yield) {
t = gen_id($arg2)
printf("thread %d yield\n", t)
}
/*
F(ngx_http_lua_coroutine_yield) {
printf("yield %x\n", gen_id($L))
}
*/
M(http-lua-user-coroutine-yield) {
p = gen_id($arg2)
c = gen_id($arg3)
printf("yield %x in %x\n", c, p)
}
F(ngx_http_lua_atpanic) {
printf("lua atpanic(%d):", gen_id($L))
print_ubacktrace();
}
F(ngx_http_lua_run_posted_threads) {
printf("run posted threads\n")
}
F(ngx_http_finalize_request) {
printf("finalize request %s: rc:%d c:%d a:%d\n", ngx_http_req_uri($r), $rc, $r->main->count, $r == $r->main);
#if ($rc == -1) {
#print_ubacktrace()
#}
}
F(ngx_http_lua_post_subrequest) {
printf("post subreq: %s rc=%d, status=%d a=%d\n", ngx_http_req_uri($r), $rc,
$r->headers_out->status, $r == $r->main)
#print_ubacktrace()
}
M(http-subrequest-done) {
printf("subrequest %s done\n", ngx_http_req_uri($r))
}
M(http-subrequest-wake-parent) {
printf("subrequest wake parent %s\n", ngx_http_req_uri($r->parent))
}
M(http-lua-user-coroutine-create) {
p = gen_id($arg2)
c = gen_id($arg3)
printf("create %x in %x\n", c, p)
}
F(ngx_http_lua_ngx_exec) { println("exec") }
F(ngx_http_lua_ngx_exit) { println("exit") }
F(ngx_http_lua_ffi_exit) { println("exit") }
F(ngx_http_lua_req_body_cleanup) {
println("lua req body cleanup")
}
F(ngx_http_read_client_request_body) {
println("read client request body")
}
F(ngx_http_lua_finalize_coroutines) {
println("finalize coroutines")
}
F(ngx_http_lua_ngx_exit) {
println("ngx.exit() called")
}
F(ngx_http_lua_ffi_exit) {
println("ngx.exit() called")
}
F(ngx_http_lua_sleep_resume) {
println("lua sleep resume")
}
M(http-lua-coroutine-done) {
t = gen_id($arg2)
printf("terminate coro %d: %s, waited by parent:%d, child cocotx: %p\n", t, $arg3 ? "ok" : "fail", $ctx->cur_co_ctx->waited_by_parent, $ctx->cur_co_ctx)
//print_ubacktrace()
}
F(ngx_http_lua_ngx_echo) {
println("ngx.print or ngx.say")
}
F(ngx_http_lua_del_all_threads) {
println("del all threads")
}
/*
M(http-lua-info) {
msg = user_string($arg1)
printf("lua info: %s\n", msg)
}
*/
M(http-lua-user-thread-wait) {
p = gen_id($arg1)
c = gen_id($arg2)
printf("lua thread %d waiting on %d, child coctx: %p\n", p, c, $sub_coctx)
}
_EOC_
1;
| caidongyun/nginx-openresty-windows | ngx_lua/t/StapThread.pm | Perl | bsd-2-clause | 5,955 |
use strict;
open( INFILE, "<", $ARGV[0] )
or die("Cannot open file $ARGV[0] for reading: $!");
while ( my $line = <INFILE> ) {
next if ( $line =~ m/^\s$/ );
my ( $n, $m ) = ( $line =~ /([^,]+),([^\n])/ );
printf( "%d\n", rindex( $n, $m ) );
}
close(INFILE);
| nikai3d/ce-challenges | easy/rightmost.pl | Perl | bsd-3-clause | 272 |
# vgetty-lib.pl
# Common functions for editing the vgetty config files
# XXX options under ring_type
# XXX DTMF command shells http://vocp.sourceforge.net/
# XXX DTMF terminals http://telephonectld.sourceforge.net/
BEGIN { push(@INC, ".."); };
use WebminCore;
&init_config();
# vgetty_inittabs()
# Returns a list of inittab entries for mgetty, with options parsed
sub vgetty_inittabs
{
local @rv;
foreach $i (&inittab::parse_inittab()) {
if ($i->{'process'} =~ /^(\S*vgetty)\s*(.*)\s+((\/.*)?tty\S+)(\s+(\S+))?$/) {
$i->{'vgetty'} = $1;
$i->{'args'} = $2;
$i->{'tty'} = $3;
$i->{'ttydefs'} = $6;
push(@rv, $i);
}
elsif ($i->{'process'} =~ /^(\S*mgetty)\s*(.*)\s+((\/.*)?tty\S+)/) {
$i->{'mgetty'} = $1;
$i->{'tty'} = $3;
push(@rv, $i);
}
}
return @rv;
}
# get_config()
# Parse the vgetty config file into a series of directives
sub get_config
{
local @rv;
local $lnum = 0;
open(CONFIG, $config{'vgetty_config'});
while(<CONFIG>) {
s/\r|\n//g;
s/#.*$//;
local @v;
while(/^\s*"([^"]*)"(.*)/ ||
/^\s*'([^']*)'(.*)/ ||
/^\s*(\S+)(.*)/) {
push(@v, $1);
$_ = $2;
}
if (@v) {
push(@rv, { 'line' => $lnum,
'index' => scalar(@rv),
'name' => shift(@v),
'values' => \@v });
}
$lnum++;
}
close(CONFIG);
return @rv;
}
# find(name, &config)
# Finds one more more config entries with the given name
sub find
{
local ($c, @rv);
foreach $c (@{$_[1]}) {
push(@rv, $c) if (lc($c->{'name'}) eq lc($_[0]));
}
return wantarray ? @rv : $rv[0];
}
# find_value(name, &config)
sub find_value
{
local @v = &find($_[0], $_[1]);
return undef if (!@v);
return wantarray ? @{$v[0]->{'values'}} : $v[0]->{'values'}->[0];
}
# tty_opt_file(base, tty)
sub tty_opt_file
{
local $tf = $_[1];
$tf =~ s/^\/dev\///;
$tf =~ s/\//\./g;
$tf = "$_[0].$tf";
return $tf;
}
# answer_mode_input(value, name)
sub answer_mode_input
{
local @modes = ( '', 'voice', 'fax', 'data' );
local @am = split(/:/, $_[0]);
local ($i, $rv);
for($i=0; $i<3; $i++) {
$rv .= "<select name=$_[1]_$i>\n";
foreach $m (@modes) {
$rv .= sprintf "<option value='%s' %s>%s\n",
$m, $am[$i] eq $m ? "selected" : "", $text{"vgetty_ans_$m"};
}
$rv .= "</select> ";
}
return $rv;
}
# parse_answer_mode(name)
sub parse_answer_mode
{
local (@rv, $i, $m);
for($i=0; defined($m = $in{"$_[0]_$i"}); $i++) {
push(@rv, $m) if ($m);
}
return join(":", @rv);
}
# receive_dir(&config)
sub receive_dir
{
local $vdir = &find_value("voice_dir", \@conf);
local $rdir = &find_value("receive_dir", \@conf);
return $rdir =~ /^\// ? $rdir : "$vdir/$rdir";
}
# messages_dir(&config)
sub messages_dir
{
local $vdir = &find_value("voice_dir", \@conf);
local $rdir = &find_value("message_dir", \@conf);
return $rdir =~ /^\// ? $rdir : "$vdir/$rdir";
}
# messages_index(&config)
sub messages_index
{
local $dir = &messages_dir($_[0]);
local $ifile = &find_value("message_list", \@conf);
return "$dir/$ifile";
}
# rmd_file_info(file)
sub rmd_file_info
{
local $out = `rmdfile '$_[0]' 2>&1`;
return undef if ($?);
local @st = stat($_[0]);
$_[0] =~ /\/([^\/]+)$/;
local $rv = { 'file' => "$1",
'path' => $_[0],
'size' => $st[7],
'date' => $st[9],
'speed' => $out =~ /speed:\s+(\d+)/i ? "$1" : undef,
'type' => $out =~ /type\s+is:\s+"([^"]+)"/i ? "$1" : undef,
'bits' => $out =~ /sample:\s+(\d+)/i ? "$1" : undef
};
return $rv;
}
# list_rmd_formats()
sub list_rmd_formats
{
local @rv;
open(RMD, "pvftormd -L 2>&1 |");
while(<RMD>) {
if (/^\s+\-\s+(\S+)\s+([0-9, ]+)\s+(.*)/) {
local $code = $1;
local $bits = $2;
local $desc = $3;
$bits =~ s/\s//g;
foreach $b (split(/,/, $bits)) {
push(@rv, { 'code' => $code,
'bits' => $b,
'desc' => &text('pvfdesc',
"$code ($desc)", $b),
'index' => scalar(@rv) });
}
}
}
close(RMD);
return @rv;
}
# save_directive(&config, name, value)
sub save_directive
{
local $lref = &read_file_lines($config{'vgetty_config'});
local $old = &find($_[1], $_[0]);
if ($old) {
$lref->[$old->{'line'}] = "$_[1] $_[2]";
}
else {
push(@$lref, "$_[1] $_[2]");
}
}
# apply_configuration()
# Apply the vgetty serial port configuration. Returns undef on success, or an
# error message on failure
sub apply_configuration
{
local $out = &backquote_logged("telinit q 2>&1 </dev/null");
return "<tt>$out</tt>" if ($?);
&system_logged("killall vgetty");
return undef;
}
1;
| xtso520ok/webmin | vgetty/vgetty-lib.pl | Perl | bsd-3-clause | 4,398 |
# SNMP::Info::RapidCity
# $Id$
#
# Copyright (c) 2014 Eric Miller
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the University of California, Santa Cruz nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
package SNMP::Info::RapidCity;
use strict;
use Exporter;
use SNMP::Info;
@SNMP::Info::RapidCity::ISA = qw/SNMP::Info Exporter/;
@SNMP::Info::RapidCity::EXPORT_OK = qw//;
use vars qw/$VERSION %FUNCS %GLOBALS %MIBS %MUNGE/;
$VERSION = '3.34';
%MIBS = (
'RAPID-CITY' => 'rapidCity',
# These are distinct from RAPID-CITY but are potentially used by
# classes which inherit the RAPID-CITY class
'NORTEL-NETWORKS-RAPID-SPANNING-TREE-MIB' => 'nnRstDot1dStpVersion',
'NORTEL-NETWORKS-MULTIPLE-SPANNING-TREE-MIB' => 'nnMstBrgAddress',
);
%GLOBALS = (
'rc_serial' => 'rcChasSerialNumber',
'chassis' => 'rcChasType',
'slots' => 'rcChasNumSlots',
'tftp_host' => 'rcTftpHost',
'tftp_file' => 'rcTftpFile',
'tftp_action' => 'rcTftpAction',
'tftp_result' => 'rcTftpResult',
'rc_ch_rev' => 'rcChasHardwareRevision',
'rc_base_mac' => 'rc2kChassisBaseMacAddr',
'rc_virt_ip' => 'rcSysVirtualIpAddr',
'rc_virt_mask' => 'rcSysVirtualNetMask',
);
%FUNCS = (
# From RAPID-CITY::rcPortTable
'rc_index' => 'rcPortIndex',
'rc_duplex' => 'rcPortOperDuplex',
'rc_duplex_admin' => 'rcPortAdminDuplex',
'rc_speed_admin' => 'rcPortAdminSpeed',
'rc_auto' => 'rcPortAutoNegotiate',
'rc_alias' => 'rcPortName',
# From RAPID-CITY::rc2kCpuEthernetPortTable
'rc_cpu_ifindex' => 'rc2kCpuEthernetPortIfIndex',
'rc_cpu_admin' => 'rc2kCpuEthernetPortAdminStatus',
'rc_cpu_oper' => 'rc2kCpuEthernetPortOperStatus',
'rc_cpu_ip' => 'rc2kCpuEthernetPortAddr',
'rc_cpu_mask' => 'rc2kCpuEthernetPortMask',
'rc_cpu_auto' => 'rc2kCpuEthernetPortAutoNegotiate',
'rc_cpu_duplex_admin' => 'rc2kCpuEthernetPortAdminDuplex',
'rc_cpu_duplex' => 'rc2kCpuEthernetPortOperDuplex',
'rc_cpu_speed_admin' => 'rc2kCpuEthernetPortAdminSpeed',
'rc_cpu_speed_oper' => 'rc2kCpuEthernetPortOperSpeed',
'rc_cpu_mac' => 'rc2kCpuEthernetPortMgmtMacAddr',
# From RAPID-CITY::rcVlanPortTable
'rc_i_vlan_if' => 'rcVlanPortIndex',
'rc_i_vlan_num' => 'rcVlanPortNumVlanIds',
'rc_i_vlan' => 'rcVlanPortVlanIds',
'rc_i_vlan_type' => 'rcVlanPortType',
'rc_i_vlan_pvid' => 'rcVlanPortDefaultVlanId',
'rc_i_vlan_tag' => 'rcVlanPortPerformTagging',
# From RAPID-CITY::rcVlanTable
'rc_vlan_id' => 'rcVlanId',
'v_name' => 'rcVlanName',
'rc_vlan_color' => 'rcVlanColor',
'rc_vlan_if' => 'rcVlanIfIndex',
'rc_vlan_stg' => 'rcVlanStgId',
'rc_vlan_type' => 'rcVlanType',
'rc_vlan_members' => 'rcVlanPortMembers',
'rc_vlan_no_join' => 'rcVlanNotAllowToJoin',
'rc_vlan_mac' => 'rcVlanMacAddress',
'rc_vlan_rstatus' => 'rcVlanRowStatus',
# From RAPID-CITY::rcIpAddrTable
'rc_ip_index' => 'rcIpAdEntIfIndex',
'rc_ip_addr' => 'rcIpAdEntAddr',
'rc_ip_type' => 'rcIpAdEntIfType',
# From RAPID-CITY::rcChasFanTable
'rc_fan_op' => 'rcChasFanOperStatus',
# From RAPID-CITY::rcChasPowerSupplyTable
'rc_ps_op' => 'rcChasPowerSupplyOperStatus',
# From RAPID-CITY::rcChasPowerSupplyDetailTable
'rc_ps_type' => 'rcChasPowerSupplyDetailType',
'rc_ps_serial' => 'rcChasPowerSupplyDetailSerialNumber',
'rc_ps_rev' => 'rcChasPowerSupplyDetailHardwareRevision',
'rc_ps_part' => 'rcChasPowerSupplyDetailPartNumber',
'rc_ps_detail' => 'rcChasPowerSupplyDetailDescription',
# From RAPID-CITY::rcCardTable
'rc_c_type' => 'rcCardType',
'rc_c_serial' => 'rcCardSerialNumber',
'rc_c_rev' => 'rcCardHardwareRevision',
'rc_c_part' => 'rcCardPartNumber',
# From RAPID-CITY::rc2kCardTable
'rc2k_c_ftype' => 'rc2kCardFrontType',
'rc2k_c_fdesc' => 'rc2kCardFrontDescription',
'rc2k_c_fserial' => 'rc2kCardFrontSerialNum',
'rc2k_c_frev' => 'rc2kCardFrontHwVersion',
'rc2k_c_fpart' => 'rc2kCardFrontPartNumber',
'rc2k_c_fdate' => 'rc2kCardFrontDateCode',
'rc2k_c_fdev' => 'rc2kCardFrontDeviations',
'rc2k_c_btype' => 'rc2kCardBackType',
'rc2k_c_bdesc' => 'rc2kCardBackDescription',
'rc2k_c_bserial' => 'rc2kCardBackSerialNum',
'rc2k_c_brev' => 'rc2kCardBackHwVersion',
'rc2k_c_bpart' => 'rc2kCardBackPartNumber',
'rc2k_c_bdate' => 'rc2kCardBackDateCode',
'rc2k_c_bdev' => 'rc2kCardBackDeviations',
# From RAPID-CITY::rc2kMdaCardTable
'rc2k_mda_type' => 'rc2kMdaCardType',
'rc2k_mda_desc' => 'rc2kMdaCardDescription',
'rc2k_mda_serial' => 'rc2kMdaCardSerialNum',
'rc2k_mda_rev' => 'rc2kMdaCardHwVersion',
'rc2k_mda_part' => 'rc2kMdaCardPartNumber',
'rc2k_mda_date' => 'rc2kMdaCardDateCode',
'rc2k_mda_dev' => 'rc2kMdaCardDeviations',
# From RAPID-CITY::rcMltTable
'rc_mlt_ports' => 'rcMltPortMembers',
'rc_mlt_index' => 'rcMltIfIndex',
'rc_mlt_dp' => 'rcMltDesignatedPort',
# From RAPID-CITY::rcBridgeSpbmMacTable
'rc_spbm_fw_port' => 'rcBridgeSpbmMacCPort',
'rc_spbm_fw_status' => 'rcBridgeSpbmMacStatus',
'rc_spbm_fw_vlan' => 'rcBridgeSpbmMacCVlanId',
# From RAPID-CITY::rcStgTable
'stp_i_id' => 'rcStgId',
'rc_stp_i_mac' => 'rcStgBridgeAddress',
'rc_stp_i_time' => 'rcStgTimeSinceTopologyChange',
'rc_stp_i_ntop' => 'rcStgTopChanges',
'rc_stp_i_root' => 'rcStgDesignatedRoot',
'rc_stp_i_root_port' => 'rcStgRootPort',
'rc_stp_i_priority' => 'rcStgPriority',
# From RAPID-CITY::rcStgPortTable
'rc_stp_p_id' => 'rcStgPort',
'stp_p_stg_id' => 'rcStgPortStgId',
'rc_stp_p_priority' => 'rcStgPortPriority',
'rc_stp_p_state' => 'rcStgPortState',
'rc_stp_p_cost' => 'rcStgPortPathCost',
'rc_stp_p_root' => 'rcStgPortDesignatedRoot',
'rc_stp_p_bridge' => 'rcStgPortDesignatedBridge',
'rc_stp_p_port' => 'rcStgPortDesignatedPort',
);
%MUNGE = (
'rc_base_mac' => \&SNMP::Info::munge_mac,
'rc_vlan_mac' => \&SNMP::Info::munge_mac,
'rc_cpu_mac' => \&SNMP::Info::munge_mac,
'rc_vlan_members' => \&SNMP::Info::munge_port_list,
'rc_vlan_no_join' => \&SNMP::Info::munge_port_list,
'rc_mlt_ports' => \&SNMP::Info::munge_port_list,
'rc_stp_i_mac' => \&SNMP::Info::munge_mac,
'rc_stp_i_root' => \&SNMP::Info::munge_prio_mac,
'rc_stp_p_root' => \&SNMP::Info::munge_prio_mac,
'rc_stp_p_bridge' => \&SNMP::Info::munge_prio_mac,
'rc_stp_p_port' => \&SNMP::Info::munge_prio_port,
);
# Need to override here since overridden in Layer2 and Layer3 classes
sub serial {
my $rapidcity = shift;
my $ver = $rapidcity->rc_serial();
return $ver unless !defined $ver;
return;
}
sub i_duplex {
my $rapidcity = shift;
my $partial = shift;
my $rc_duplex = $rapidcity->rc_duplex($partial) || {};
my $rc_cpu_duplex = $rapidcity->rc_cpu_duplex($partial) || {};
my %i_duplex;
foreach my $if ( keys %$rc_duplex ) {
my $duplex = $rc_duplex->{$if};
next unless defined $duplex;
$duplex = 'half' if $duplex =~ /half/i;
$duplex = 'full' if $duplex =~ /full/i;
$i_duplex{$if} = $duplex;
}
# Get CPU Ethernet Interfaces for 8600 Series
foreach my $iid ( keys %$rc_cpu_duplex ) {
my $c_duplex = $rc_cpu_duplex->{$iid};
next unless defined $c_duplex;
$i_duplex{$iid} = $c_duplex;
}
return \%i_duplex;
}
sub i_duplex_admin {
my $rapidcity = shift;
my $partial = shift;
my $rc_duplex_admin = $rapidcity->rc_duplex_admin() || {};
my $rc_auto = $rapidcity->rc_auto($partial) || {};
my $rc_cpu_auto = $rapidcity->rc_cpu_auto($partial) || {};
my $rc_cpu_duplex_admin = $rapidcity->rc_cpu_duplex_admin($partial) || {};
my %i_duplex_admin;
foreach my $if ( keys %$rc_duplex_admin ) {
my $duplex = $rc_duplex_admin->{$if};
next unless defined $duplex;
my $auto = $rc_auto->{$if} || 'false';
my $string = 'other';
$string = 'half' if ( $duplex =~ /half/i and $auto =~ /false/i );
$string = 'full' if ( $duplex =~ /full/i and $auto =~ /false/i );
$string = 'auto' if $auto =~ /true/i;
$i_duplex_admin{$if} = $string;
}
# Get CPU Ethernet Interfaces for 8600 Series
foreach my $iid ( keys %$rc_cpu_duplex_admin ) {
my $c_duplex = $rc_cpu_duplex_admin->{$iid};
next unless defined $c_duplex;
my $c_auto = $rc_cpu_auto->{$iid};
my $string = 'other';
$string = 'half' if ( $c_duplex =~ /half/i and $c_auto =~ /false/i );
$string = 'full' if ( $c_duplex =~ /full/i and $c_auto =~ /false/i );
$string = 'auto' if $c_auto =~ /true/i;
$i_duplex_admin{$iid} = $string;
}
return \%i_duplex_admin;
}
sub set_i_duplex_admin {
my $rapidcity = shift;
my ( $duplex, $iid ) = @_;
$duplex = lc($duplex);
return unless ( $duplex =~ /(half|full|auto)/ and $iid =~ /\d+/ );
# map a textual duplex to an integer one the switch understands
my %duplexes = qw/full 2 half 1/;
my $i_auto = $rapidcity->rc_auto($iid);
if ( $duplex eq "auto" ) {
return $rapidcity->set_rc_auto( '1', $iid );
}
elsif ( ( $duplex ne "auto" ) and ( $i_auto->{$iid} eq "1" ) ) {
return unless ( $rapidcity->set_rc_auto( '2', $iid ) );
return $rapidcity->set_rc_duplex_admin( $duplexes{$duplex}, $iid );
}
else {
return $rapidcity->set_rc_duplex_admin( $duplexes{$duplex}, $iid );
}
return;
}
sub set_i_speed_admin {
my $rapidcity = shift;
my ( $speed, $iid ) = @_;
return unless ( $speed =~ /(10|100|1000|auto)/i and $iid =~ /\d+/ );
# map a textual duplex to an integer one the switch understands
my %speeds = qw/10 1 100 2 1000 3/;
my $i_auto = $rapidcity->rc_auto($iid);
if ( $speed eq "auto" ) {
return $rapidcity->set_rc_auto( '1', $iid );
}
elsif ( ( $speed ne "auto" ) and ( $i_auto->{$iid} eq "1" ) ) {
return unless ( $rapidcity->set_rc_auto( '2', $iid ) );
return $rapidcity->set_rc_speed_admin( $speeds{$speed}, $iid );
}
else {
return $rapidcity->set_rc_speed_admin( $speeds{$speed}, $iid );
}
return;
}
sub v_index {
my $rapidcity = shift;
my $partial = shift;
return $rapidcity->rc_vlan_id($partial);
}
sub i_vlan {
my $rapidcity = shift;
my $partial = shift;
my $i_pvid = $rapidcity->rc_i_vlan_pvid($partial) || {};
return $i_pvid;
}
sub i_vlan_membership {
my $rapidcity = shift;
my $rc_v_ports = $rapidcity->rc_vlan_members();
my $i_vlan_membership = {};
foreach my $vlan ( keys %$rc_v_ports ) {
my $portlist = $rc_v_ports->{$vlan};
my $ret = [];
# Convert portlist bit array to ifIndex array
for ( my $i = 0; $i <= scalar(@$portlist); $i++ ) {
push( @{$ret}, $i ) if ( @$portlist[$i] );
}
#Create HoA ifIndex -> VLAN array
foreach my $port ( @{$ret} ) {
push( @{ $i_vlan_membership->{$port} }, $vlan );
}
}
return $i_vlan_membership;
}
sub i_vlan_membership_untagged {
my $rapidcity = shift;
# Traditionally access ports have one VLAN untagged and trunk ports have
# one or more VLANs all tagged
# Newer VOSS device trunks have PerformTagging true or false and also can
# UntagDefaultVlan
# Newer BOSS device trunks have four PerformTagging options true, false,
# tagPvidOnly, and untagPvidOnly
my $p_members = $rapidcity->i_vlan_membership();
my $i_vlan = $rapidcity->i_vlan();
my $p_tag_opt = $rapidcity->rcVlanPortPerformTagging() || {};
my $p_untag_def = $rapidcity->rcVlanPortUntagDefaultVlan() || {};
my $p_type = $rapidcity->rcVlanPortType() || {};
my $members_untagged = {};
foreach my $port ( keys %$p_type ) {
my $type = $p_type->{$port};
next unless $type;
# Easiest case first access ports
if ($type eq 'access') {
# Access ports should only have one VLAN and it should be
# untagged
$members_untagged->{$port} = $p_members->{$port};
}
else {
# If PerformTagging has a value do all checks otherwise we're
# just a trunk and everything is tagged
if ($p_tag_opt->{$port}) {
if ($p_tag_opt->{$port} eq 'untagPvidOnly') {
my $vlan = $i_vlan->{$port};
push( @{ $members_untagged->{$port} }, $vlan );
}
elsif (($p_tag_opt->{$port} eq 'true') and
($p_untag_def->{$port} and $p_untag_def->{$port} eq 'true'))
{
my $vlan = $i_vlan->{$port};
push( @{ $members_untagged->{$port} }, $vlan );
}
elsif ($p_tag_opt->{$port} eq 'tagPvidOnly') {
my $vlan = $i_vlan->{$port};
my @arr = $p_members->{$port};
my $index = 0;
my $count = scalar @arr;
$index++ until $arr[$index] eq $vlan or $index==$count;
splice(@arr, $index, 1);
$members_untagged->{$port} = @arr;
}
# Don't know if this is a legal configuration, but included
# for completeness
elsif ($p_tag_opt->{$port} eq 'false') {
$members_untagged->{$port} = $p_members->{$port};
}
else {
next;
}
}
}
}
return $members_untagged;
}
sub set_i_pvid {
my $rapidcity = shift;
my ( $vlan_id, $ifindex ) = @_;
return unless ( $rapidcity->_validate_vlan_param( $vlan_id, $ifindex ) );
unless ( $rapidcity->set_rc_i_vlan_pvid( $vlan_id, $ifindex ) ) {
$rapidcity->error_throw(
"Unable to change PVID to $vlan_id on IfIndex: $ifindex");
return;
}
return 1;
}
sub set_i_vlan {
my $rapidcity = shift;
my ( $new_vlan_id, $ifindex ) = @_;
return
unless ( $rapidcity->_validate_vlan_param( $new_vlan_id, $ifindex ) );
my $vlan_p_type = $rapidcity->rc_i_vlan_type($ifindex);
unless ( $vlan_p_type->{$ifindex} =~ /access/ ) {
$rapidcity->error_throw("Not an access port");
return;
}
my $i_pvid = $rapidcity->rc_i_vlan_pvid($ifindex);
# Store current untagged VLAN to remove it from the port list later
my $old_vlan_id = $i_pvid->{$ifindex};
# Check that haven't been given the same VLAN we are currently using
if ( $old_vlan_id eq $new_vlan_id ) {
$rapidcity->error_throw(
"Current PVID: $old_vlan_id and New VLAN: $new_vlan_id the same, no change."
);
return;
}
print "Changing VLAN: $old_vlan_id to $new_vlan_id on IfIndex: $ifindex\n"
if $rapidcity->debug();
# Check if port in forbidden list for the VLAN, haven't seen this used,
# but we'll check anyway
return
unless (
$rapidcity->_check_forbidden_ports( $new_vlan_id, $ifindex ) );
my $old_vlan_members = $rapidcity->rc_vlan_members($old_vlan_id);
my $new_vlan_members = $rapidcity->rc_vlan_members($new_vlan_id);
print "Modifying egress list for VLAN: $new_vlan_id \n"
if $rapidcity->debug();
my $new_egress
= $rapidcity->modify_port_list( $new_vlan_members->{$new_vlan_id},
$ifindex, '1' );
print "Modifying egress list for VLAN: $old_vlan_id \n"
if $rapidcity->debug();
my $old_egress
= $rapidcity->modify_port_list( $old_vlan_members->{$old_vlan_id},
$ifindex, '0' );
my $vlan_set = [
[ 'rc_vlan_members', "$new_vlan_id", "$new_egress" ],
# ['rc_vlan_members',"$old_vlan_id","$old_egress"],
];
return
unless ( $rapidcity->set_multi($vlan_set) );
my $vlan_set2 = [ [ 'rc_vlan_members', "$old_vlan_id", "$old_egress" ], ];
return
unless ( $rapidcity->set_multi($vlan_set2) );
# Set new untagged / native VLAN
# Some models/versions do this for us also, so check to see if we need to set
$i_pvid = $rapidcity->rc_i_vlan_pvid($ifindex);
my $cur_i_pvid = $i_pvid->{$ifindex};
print "Current PVID: $cur_i_pvid\n" if $rapidcity->debug();
unless ( $cur_i_pvid eq $new_vlan_id ) {
return unless ( $rapidcity->set_i_pvid( $new_vlan_id, $ifindex ) );
}
print
"Successfully changed VLAN: $old_vlan_id to $new_vlan_id on IfIndex: $ifindex\n"
if $rapidcity->debug();
return 1;
}
sub set_add_i_vlan_tagged {
my $rapidcity = shift;
my ( $vlan_id, $ifindex ) = @_;
return unless ( $rapidcity->_validate_vlan_param( $vlan_id, $ifindex ) );
print "Adding VLAN: $vlan_id to IfIndex: $ifindex\n"
if $rapidcity->debug();
# Check if port in forbidden list for the VLAN, haven't seen this used, but we'll check anyway
return
unless ( $rapidcity->_check_forbidden_ports( $vlan_id, $ifindex ) );
my $iv_members = $rapidcity->rc_vlan_members($vlan_id);
print "Modifying egress list for VLAN: $vlan_id \n"
if $rapidcity->debug();
my $new_egress
= $rapidcity->modify_port_list( $iv_members->{$vlan_id}, $ifindex,
'1' );
unless ( $rapidcity->set_qb_v_egress( $new_egress, $vlan_id ) ) {
print
"Error: Unable to add VLAN: $vlan_id to Index: $ifindex egress list.\n"
if $rapidcity->debug();
return;
}
print
"Successfully added IfIndex: $ifindex to VLAN: $vlan_id egress list\n"
if $rapidcity->debug();
return 1;
}
sub set_remove_i_vlan_tagged {
my $rapidcity = shift;
my ( $vlan_id, $ifindex ) = @_;
return unless ( $rapidcity->_validate_vlan_param( $vlan_id, $ifindex ) );
print "Removing VLAN: $vlan_id from IfIndex: $ifindex\n"
if $rapidcity->debug();
my $iv_members = $rapidcity->rc_vlan_members($vlan_id);
print "Modifying egress list for VLAN: $vlan_id \n"
if $rapidcity->debug();
my $new_egress
= $rapidcity->modify_port_list( $iv_members->{$vlan_id}, $ifindex,
'0' );
unless ( $rapidcity->set_qb_v_egress( $new_egress, $vlan_id ) ) {
print
"Error: Unable to add VLAN: $vlan_id to Index: $ifindex egress list.\n"
if $rapidcity->debug();
return;
}
print
"Successfully removed IfIndex: $ifindex from VLAN: $vlan_id egress list\n"
if $rapidcity->debug();
return 1;
}
sub set_create_vlan {
my $rapidcity = shift;
my ( $name, $vlan_id ) = @_;
return unless ( $vlan_id =~ /\d+/ );
my $vlan_set = [
[ 'v_name', "$vlan_id", "$name" ],
[ 'rc_vlan_rstatus', "$vlan_id", 4 ],
];
unless ( $rapidcity->set_multi($vlan_set) ) {
print "Error: Unable to create VLAN: $vlan_id\n"
if $rapidcity->debug();
return;
}
return 1;
}
sub set_delete_vlan {
my $rapidcity = shift;
my ($vlan_id) = shift;
return unless ( $vlan_id =~ /^\d+$/ );
unless ( $rapidcity->set_rc_vlan_rstatus( '6', $vlan_id ) ) {
$rapidcity->error_throw("Unable to delete VLAN: $vlan_id");
return;
}
return 1;
}
#
# These are internal methods and are not documented. Do not use directly.
#
sub _check_forbidden_ports {
my $rapidcity = shift;
my ( $vlan_id, $ifindex ) = @_;
my $iv_forbidden = $rapidcity->rc_vlan_no_join($vlan_id);
my @forbidden_ports
= split( //, unpack( "B*", $iv_forbidden->{$vlan_id} ) );
print "Forbidden ports: @forbidden_ports\n" if $rapidcity->debug();
if ( defined( $forbidden_ports[$ifindex] )
and ( $forbidden_ports[$ifindex] eq "1" ) )
{
$rapidcity->error_throw(
"IfIndex: $ifindex in forbidden list for VLAN: $vlan_id unable to add"
);
return;
}
return 1;
}
sub _validate_vlan_param {
my $rapidcity = shift;
my ( $vlan_id, $ifindex ) = @_;
# VID and ifIndex should both be numeric
unless (defined $vlan_id
and defined $ifindex
and $vlan_id =~ /^\d+$/
and $ifindex =~ /^\d+$/ )
{
$rapidcity->error_throw("Invalid parameter");
return;
}
# Check that ifIndex exists on device
my $index = $rapidcity->interfaces($ifindex);
unless ( exists $index->{$ifindex} ) {
$rapidcity->error_throw("ifIndex $ifindex does not exist");
return;
}
#Check that VLAN exists on device
unless ( $rapidcity->rc_vlan_id($vlan_id) ) {
$rapidcity->error_throw(
"VLAN $vlan_id does not exist or is not operational");
return;
}
return 1;
}
sub agg_ports {
my $rapidcity = shift;
# TODO: implement partial
my $ports = $rapidcity->rc_mlt_ports;
my $trunks = $rapidcity->rc_mlt_index;
my $dps = $rapidcity->rc_mlt_dp || {};
return {}
unless ref {} eq ref $trunks
and scalar keys %$trunks
and ref {} eq ref $ports
and scalar keys %$ports;
my $ret = {};
foreach my $m ( keys %$trunks ) {
my $idx = $trunks->{$m};
next unless $idx;
$idx = $dps->{$m} ? $dps->{$m} : $idx;
my $portlist = $ports->{$m};
next unless $portlist;
for ( my $i = 0; $i <= scalar(@$portlist); $i++ ) {
$ret->{$i} = $idx if ( @$portlist[$i] );
}
}
return $ret;
}
# break up the rcBridgeSpbmMacEntry INDEX into ISID and MAC Address.
sub _spbm_fdbtable_index {
my $idx = shift;
my @values = split( /\./, $idx );
my $isid = shift(@values);
return ( $isid, join( ':', map { sprintf "%02x", $_ } @values ) );
}
sub rc_spbm_fw_mac {
my $rapidcity = shift;
my $partial = shift;
my $spbm_fw_ports = $rapidcity->rc_spbm_fw_port($partial);
my $spbm_fw_mac = {};
foreach my $idx ( keys %$spbm_fw_ports ) {
my ( $isid, $mac ) = _spbm_fdbtable_index($idx);
$spbm_fw_mac->{$idx} = $mac;
}
return $spbm_fw_mac;
}
sub rc_spbm_fw_isid {
my $rapidcity = shift;
my $partial = shift;
my $spbm_fw_ports = $rapidcity->rc_spbm_fw_port($partial);
my $spbm_fw_isid = {};
foreach my $idx ( keys %$spbm_fw_ports ) {
my ( $isid, $mac ) = _spbm_fdbtable_index($idx);
$spbm_fw_isid->{$idx} = $isid;
}
return $spbm_fw_isid;
}
sub stp_ver {
my $rapidcity = shift;
return $rapidcity->rcSysSpanningTreeOperMode()
|| $rapidcity->SUPER::stp_ver();
}
# RSTP and ieee8021d operating modes do not populate RAPID-CITY::rcStgTable
# or RAPID-CITY::rcStgPortTable but do populate BRIDGE-MIB so check both
sub stp_i_mac {
my $rapidcity = shift;
return $rapidcity->rc_stp_i_mac()
|| $rapidcity->SUPER::stp_i_mac();
}
sub stp_i_time {
my $rapidcity = shift;
return $rapidcity->rc_stp_i_time()
|| $rapidcity->SUPER::stp_i_time();
}
sub stp_i_ntop {
my $rapidcity = shift;
return $rapidcity->rc_stp_i_ntop()
|| $rapidcity->SUPER::stp_i_ntop();
}
sub stp_i_root {
my $rapidcity = shift;
return $rapidcity->rc_stp_i_root()
|| $rapidcity->SUPER::stp_i_root();
}
sub stp_i_root_port {
my $rapidcity = shift;
return $rapidcity->rc_stp_i_root_port()
|| $rapidcity->SUPER::stp_i_root_port();
}
sub stp_i_priority {
my $rapidcity = shift;
return $rapidcity->rc_stp_i_priority()
|| $rapidcity->SUPER::stp_i_priority();
}
sub stp_p_id {
my $rapidcity = shift;
return $rapidcity->rc_stp_p_id()
|| $rapidcity->SUPER::stp_p_id();
}
sub stp_p_priority {
my $rapidcity = shift;
return $rapidcity->rc_stp_p_priority()
|| $rapidcity->SUPER::stp_p_priority();
}
sub stp_p_state {
my $rapidcity = shift;
return $rapidcity->rc_stp_p_state()
|| $rapidcity->SUPER::stp_p_state();
}
sub stp_p_cost {
my $rapidcity = shift;
return $rapidcity->rc_stp_p_cost()
|| $rapidcity->SUPER::stp_p_cost();
}
sub stp_p_root {
my $rapidcity = shift;
return $rapidcity->rc_stp_p_root()
|| $rapidcity->SUPER::stp_p_root();
}
sub stp_p_bridge {
my $rapidcity = shift;
return $rapidcity->rc_stp_p_bridge()
|| $rapidcity->SUPER::stp_p_bridge();
}
sub stp_p_port {
my $rapidcity = shift;
return $rapidcity->rc_stp_p_port()
|| $rapidcity->SUPER::stp_p_port();
}
sub mst_vlan2instance {
my $rapidcity = shift;
my $partial = shift;
return $rapidcity->rcVlanStgId($partial);
}
sub i_bpduguard_enabled {
my $rapidcity = shift;
my $partial = shift;
return $rapidcity->rcPortBpduFilteringOperEnabled();
}
sub i_stp_state {
my $rapidcity = shift;
my $partial = shift;
my $bp_index = $rapidcity->bp_index($partial);
my $stp_p_state = $rapidcity->dot1dStpPortState($partial);
my %i_stp_state;
foreach my $index ( keys %$stp_p_state ) {
my $state = $stp_p_state->{$index};
my $iid = $bp_index->{$index};
next unless defined $iid;
next unless defined $state;
$i_stp_state{$iid} = $state;
}
return \%i_stp_state;
}
1;
__END__
=head1 NAME
SNMP::Info::RapidCity - SNMP Interface to the Avaya/Nortel RapidCity MIB
=head1 AUTHOR
Eric Miller
=head1 SYNOPSIS
# Let SNMP::Info determine the correct subclass for you.
my $rapidcity = new SNMP::Info(
AutoSpecify => 1,
Debug => 1,
# These arguments are passed directly to SNMP::Session
DestHost => 'myswitch',
Community => 'public',
Version => 2
)
or die "Can't connect to DestHost.\n";
my $class = $rapidcity->class();
print "SNMP::Info determined this device to fall under subclass : $class\n";
=head1 DESCRIPTION
SNMP::Info::RapidCity is a subclass of SNMP::Info that provides an interface
to the C<RAPID-CITY> MIB. This MIB is used across the Avaya/Nortel Ethernet
Routing Switch and Ethernet Switch product lines (Formerly known as Passport,
BayStack, and Accelar), as well as, the VSP 9000 and 7000 series.
Use or create in a subclass of SNMP::Info. Do not use directly.
=head2 Inherited Classes
None.
=head2 Required MIBs
=over
=item RAPID-CITY
=back
=head1 GLOBAL METHODS
These are methods that return scalar values from SNMP
=over
=item $rapidcity->rc_base_mac()
(C<rc2kChassisBaseMacAddr>)
=item $rapidcity->rc_serial()
(C<rcChasSerialNumber>)
=item $rapidcity->rc_ch_rev()
(C<rcChasHardwareRevision>)
=item $rapidcity->chassis()
(C<rcChasType>)
=item $rapidcity->slots()
(C<rcChasNumSlots>)
=item $rapidcity->rc_virt_ip()
(C<rcSysVirtualIpAddr>)
=item $rapidcity->rc_virt_mask()
(C<rcSysVirtualNetMask>)
=item $rapidcity->tftp_host()
(C<rcTftpHost>)
=item $rapidcity->tftp_file()
(C<rcTftpFile>)
=item $rapidcity->tftp_action()
(C<rcTftpAction>)
=item $rapidcity->tftp_result()
(C<rcTftpResult>)
=back
=head2 Overrides
=over
=item $rapidcity->serial()
Returns serial number of the chassis
=item $rapidcity->stp_ver()
Returns the particular STP version running on this device.
Values: C<nortelStpg>, C<pvst>, C<rstp>, C<mstp>, C<ieee8021d>
(C<rcSysSpanningTreeOperMode>)
=back
=head1 TABLE METHODS
These are methods that return tables of information in the form of a reference
to a hash.
=over
=item $rapidcity->i_duplex()
Returns reference to map of IIDs to current link duplex.
=item $rapidcity->i_duplex_admin()
Returns reference to hash of IIDs to admin duplex setting.
=item $rapidcity->i_vlan()
Returns a mapping between C<ifIndex> and the PVID or default VLAN.
=item $rapidcity->i_vlan_membership()
Returns reference to hash of arrays: key = C<ifIndex>, value = array of VLAN
IDs. These are the VLANs which are members of the egress list for the port.
Example:
my $interfaces = $rapidcity->interfaces();
my $vlans = $rapidcity->i_vlan_membership();
foreach my $iid (sort keys %$interfaces) {
my $port = $interfaces->{$iid};
my $vlan = join(',', sort(@{$vlans->{$iid}}));
print "Port: $port VLAN: $vlan\n";
}
=item $rapidcity->i_vlan_membership_untagged()
Returns reference to hash of arrays: key = C<ifIndex>, value = array of VLAN
IDs. These are the VLANs which are members of the untagged egress list for
the port.
=item $rapidcity->v_index()
Returns VLAN IDs
(C<rcVlanId>)
=item $rapidcity->agg_ports()
Returns a HASH reference mapping from slave to master port for each member of
a port bundle (MLT) on the device. Keys are ifIndex of the slave ports,
Values are ifIndex of the corresponding master ports.
=item $rapidcity->i_stp_state()
Returns the mapping of (C<dot1dStpPortState>) to the interface
index (iid).
=item $rapidcity->mst_vlan2instance()
Returns the mapping of VLAN to Spanning Tree Group (STG) instance in the
form of a hash reference with key = VLAN id, value = STG instance
(C<rcVlanStgId>)
=item $rapidcity->i_bpduguard_enabled()
Returns true or false depending on whether C<BpduGuard> is enabled on a given
port. Format is a hash reference with key = C<ifIndex>, value = [true|false]
(C<rcPortBpduFilteringOperEnabled>)
=back
=head2 RAPID-CITY Port Table (C<rcPortTable>)
=over
=item $rapidcity->rc_index()
(C<rcPortIndex>)
=item $rapidcity->rc_duplex()
(C<rcPortOperDuplex>)
=item $rapidcity->rc_duplex_admin()
(C<rcPortAdminDuplex>)
=item $rapidcity->rc_speed_admin()
(C<rcPortAdminSpeed>)
=item $rapidcity->rc_auto()
(C<rcPortAutoNegotiate>)
=item $rapidcity->rc_alias()
(C<rcPortName>)
=back
=head2 RAPID-CITY CPU Ethernet Port Table (C<rc2kCpuEthernetPortTable>)
=over
=item $rapidcity->rc_cpu_ifindex()
(C<rc2kCpuEthernetPortIfIndex>)
=item $rapidcity->rc_cpu_admin()
(C<rc2kCpuEthernetPortAdminStatus>)
=item $rapidcity->rc_cpu_oper()
(C<rc2kCpuEthernetPortOperStatus>)
=item $rapidcity->rc_cpu_ip()
(C<rc2kCpuEthernetPortAddr>)
=item $rapidcity->rc_cpu_mask()
(C<rc2kCpuEthernetPortMask>)
=item $rapidcity->rc_cpu_auto()
(C<rc2kCpuEthernetPortAutoNegotiate>)
=item $rapidcity->rc_cpu_duplex_admin()
(C<rc2kCpuEthernetPortAdminDuplex>)
=item $rapidcity->rc_cpu_duplex()
(C<rc2kCpuEthernetPortOperDuplex>)
=item $rapidcity->rc_cpu_speed_admin()
(C<rc2kCpuEthernetPortAdminSpeed>)
=item $rapidcity->rc_cpu_speed_oper()
(C<rc2kCpuEthernetPortOperSpeed>)
=item $rapidcity->rc_cpu_mac()
(C<rc2kCpuEthernetPortMgmtMacAddr>)
=back
=head2 RAPID-CITY VLAN Port Table (C<rcVlanPortTable>)
=over
=item $rapidcity->rc_i_vlan_if()
(C<rcVlanPortIndex>)
=item $rapidcity->rc_i_vlan_num()
(C<rcVlanPortNumVlanIds>)
=item $rapidcity->rc_i_vlan()
(C<rcVlanPortVlanIds>)
=item $rapidcity->rc_i_vlan_type()
(C<rcVlanPortType>)
=item $rapidcity->rc_i_vlan_pvid()
(C<rcVlanPortDefaultVlanId>)
=item $rapidcity->rc_i_vlan_tag()
(C<rcVlanPortPerformTagging>)
=back
=head2 RAPID-CITY VLAN Table (C<rcVlanTable>)
=over
=item $rapidcity->rc_vlan_id()
(C<rcVlanId>)
=item $rapidcity->v_name()
(C<rcVlanName>)
=item $rapidcity->rc_vlan_color()
(C<rcVlanColor>)
=item $rapidcity->rc_vlan_if()
(C<rcVlanIfIndex>)
=item $rapidcity->rc_vlan_stg()
(C<rcVlanStgId>)
=item $rapidcity->rc_vlan_type()
(C<rcVlanType>)
=item $rapidcity->rc_vlan_members()
(C<rcVlanPortMembers>)
=item $rapidcity->rc_vlan_mac()
(C<rcVlanMacAddress>)
=back
=head2 RAPID-CITY IP Address Table (C<rcIpAddrTable>)
=over
=item $rapidcity->rc_ip_index()
(C<rcIpAdEntIfIndex>)
=item $rapidcity->rc_ip_addr()
(C<rcIpAdEntAddr>)
=item $rapidcity->rc_ip_type()
(C<rcIpAdEntIfType>)
=back
=head2 RAPID-CITY Chassis Fan Table (C<rcChasFanTable>)
=over
=item $rapidcity->rc_fan_op()
(C<rcChasFanOperStatus>)
=back
=head2 RAPID-CITY Power Supply Table (C<rcChasPowerSupplyTable>)
=over
=item $rapidcity->rc_ps_op()
(C<rcChasPowerSupplyOperStatus>)
=back
=head2 RAPID-CITY Power Supply Detail Table (C<rcChasPowerSupplyDetailTable>)
=over
=item $rapidcity->rc_ps_type()
(C<rcChasPowerSupplyDetailType>)
=item $rapidcity->rc_ps_serial()
(C<rcChasPowerSupplyDetailSerialNumber>)
=item $rapidcity->rc_ps_rev()
(C<rcChasPowerSupplyDetailHardwareRevision>)
=item $rapidcity->rc_ps_part()
(C<rcChasPowerSupplyDetailPartNumber>)
=item $rapidcity->rc_ps_detail()
(C<rcChasPowerSupplyDetailDescription>)
=back
=head2 RAPID-CITY Card Table (C<rcCardTable>)
=over
=item $rapidcity->rc_c_type()
(C<rcCardType>)
=item $rapidcity->rc_c_serial()
(C<rcCardSerialNumber>)
=item $rapidcity->rc_c_rev()
(C<rcCardHardwareRevision>)
=item $rapidcity->rc_c_part()
(C<rcCardPartNumber>)
=back
=head2 RAPID-CITY 2k Card Table (C<rc2kCardTable>)
=over
=item $rapidcity->rc2k_c_ftype()
(C<rc2kCardFrontType>)
=item $rapidcity->rc2k_c_fdesc()
(C<rc2kCardFrontDescription>)
=item $rapidcity->rc2k_c_fserial()
(C<rc2kCardFrontSerialNum>)
=item $rapidcity->rc2k_c_frev()
(C<rc2kCardFrontHwVersion>)
=item $rapidcity->rc2k_c_fpart()
(C<rc2kCardFrontPartNumber>)
=item $rapidcity->rc2k_c_fdate()
(C<rc2kCardFrontDateCode>)
=item $rapidcity->rc2k_c_fdev()
(C<rc2kCardFrontDeviations>)
=item $rapidcity->rc2k_c_btype()
(C<rc2kCardBackType>)
=item $rapidcity->rc2k_c_bdesc()
(C<rc2kCardBackDescription>)
=item $rapidcity->rc2k_c_bserial()
(C<rc2kCardBackSerialNum>)
=item $rapidcity->rc2k_c_brev()
(C<rc2kCardBackHwVersion>)
=item $rapidcity->rc2k_c_bpart()
(C<rc2kCardBackPartNumber>)
=item $rapidcity->rc2k_c_bdate()
(C<rc2kCardBackDateCode>)
=item $rapidcity->rc2k_c_bdev()
(C<rc2kCardBackDeviations>)
=back
=head2 RAPID-CITY MDA Card Table (C<rc2kMdaCardTable>)
=over
=item $rapidcity->rc2k_mda_type()
(C<rc2kMdaCardType>)
=item $rapidcity->rc2k_mda_desc()
(C<rc2kMdaCardDescription>)
=item $rapidcity->rc2k_mda_serial()
(C<rc2kMdaCardSerialNum>)
=item $rapidcity->rc2k_mda_rev()
(C<rc2kMdaCardHwVersion>)
=item $rapidcity->rc2k_mda_part()
(C<rc2kMdaCardPartNumber>)
=item $rapidcity->rc2k_mda_date()
(C<rc2kMdaCardDateCode>)
=item $rapidcity->rc2k_mda_dev()
(C<rc2kMdaCardDeviations>)
=back
=head2 RAPID-CITY Bridge SPBM MAC Table (C<rcBridgeSpbmMacTable>)
=over
=item $rapidcity->rc_spbm_fw_mac()
Returns reference to hash of forwarding table MAC Addresses
(C<rcBridgeSpbmMacAddr>)
=item $rapidcity->rc_spbm_fw_port()
Returns reference to hash of forwarding table entries port interface
identifier (iid)
(C<rcBridgeSpbmMacCPort>)
=item $rapidcity->rc_spbm_fw_status()
Returns reference to hash of forwarding table entries status
(C<rcBridgeSpbmMacStatus>)
=item $rapidcity->rc_spbm_fw_vlan()
Returns reference to hash of forwarding table entries Customer VLAN ID
(C<rcBridgeSpbmMacCVlanId>)
=item $rapidcity->rc_spbm_fw_isid()
Returns reference to hash of forwarding table entries ISID
(C<rcBridgeSpbmMacIsid>)
=back
=head2 Spanning Tree Instance Globals
C<RSTP> and C<ieee8021d> operating modes do not populate the
C<RAPID-CITY::rcStgTable> but do populate F<BRIDGE-MIB>. These methods check
F<RAPID-CITY> first and fall back to F<BRIDGE-MIB>.
=over
=item $rapidcity->stp_i_mac()
Returns the bridge address
=item $rapidcity->stp_i_time()
Returns time since last topology change detected. (100ths/second)
=item $rapidcity->stp_i_ntop()
Returns the total number of topology changes detected.
=item $rapidcity->stp_i_root()
Returns root of STP.
=item $rapidcity->stp_i_root_port()
Returns the port number of the port that offers the lowest cost path
to the root bridge.
=item $rapidcity->stp_i_priority()
Returns the port number of the port that offers the lowest cost path
to the root bridge.
=back
=head2 Spanning Tree Protocol Port Table
C<RSTP> and C<ieee8021d> operating modes do not populate the
C<RAPID-CITY::rcStgPortTable> but do populate F<BRIDGE-MIB>. These methods
check F<RAPID-CITY> first and fall back to F<BRIDGE-MIB>.
=over
=item $rapidcity->stp_p_id()
"The port number of the port for which this entry contains Spanning Tree
Protocol management information."
=item $rapidcity->stp_p_priority()
"The value of the priority field which is contained in the first
(in network byte order) octet of the (2 octet long) Port ID. The other octet
of the Port ID is given by the value of C<dot1dStpPort>."
=item $rapidcity->stp_p_state()
"The port's current state as defined by application of the Spanning Tree
Protocol."
=item $rapidcity->stp_p_cost()
"The contribution of this port to the path cost of paths towards the spanning
tree root which include this port."
=item $rapidcity->stp_p_root()
"The unique Bridge Identifier of the Bridge recorded as the Root in the
Configuration BPDUs transmitted by the Designated Bridge for the segment to
which the port is attached."
=item $rapidcity->stp_p_bridge()
"The Bridge Identifier of the bridge which this port considers to be the
Designated Bridge for this port's segment."
=item $rapidcity->stp_p_port()
"The Port Identifier of the port on the Designated Bridge for this port's
segment."
=back
=head1 SET METHODS
These are methods that provide SNMP set functionality for overridden methods
or provide a simpler interface to complex set operations. See
L<SNMP::Info/"SETTING DATA VIA SNMP"> for general information on set
operations.
=over
=item $rapidcity->set_i_speed_admin(speed, ifIndex)
Sets port speed, must be supplied with speed and port C<ifIndex>. Speed
choices are 'auto', '10', '100', '1000'.
Example:
my %if_map = reverse %{$rapidcity->interfaces()};
$rapidcity->set_i_speed_admin('auto', $if_map{'1.1'})
or die "Couldn't change port speed. ",$rapidcity->error(1);
=item $rapidcity->set_i_duplex_admin(duplex, ifIndex)
Sets port duplex, must be supplied with duplex and port C<ifIndex>. Speed
choices are 'auto', 'half', 'full'.
Example:
my %if_map = reverse %{$rapidcity->interfaces()};
$rapidcity->set_i_duplex_admin('auto', $if_map{'1.1'})
or die "Couldn't change port duplex. ",$rapidcity->error(1);
=item $rapidcity->set_i_vlan(vlan, ifIndex)
Changes an access (untagged) port VLAN, must be supplied with the numeric
VLAN ID and port C<ifIndex>. This method will modify the port's VLAN
membership and PVID (default VLAN). This method should only be used on end
station (non-trunk) ports.
Example:
my %if_map = reverse %{$rapidcity->interfaces()};
$rapidcity->set_i_vlan('2', $if_map{'1.1'})
or die "Couldn't change port VLAN. ",$rapidcity->error(1);
=item $rapidcity->set_i_pvid(pvid, ifIndex)
Sets port PVID or default VLAN, must be supplied with the numeric VLAN ID and
port C<ifIndex>. This method only changes the PVID, to modify an access
(untagged) port use set_i_vlan() instead.
Example:
my %if_map = reverse %{$rapidcity->interfaces()};
$rapidcity->set_i_pvid('2', $if_map{'1.1'})
or die "Couldn't change port PVID. ",$rapidcity->error(1);
=item $rapidcity->set_add_i_vlan_tagged(vlan, ifIndex)
Adds the port to the egress list of the VLAN, must be supplied with the
numeric VLAN ID and port C<ifIndex>.
Example:
my %if_map = reverse %{$rapidcity->interfaces()};
$rapidcity->set_add_i_vlan_tagged('2', $if_map{'1.1'})
or die "Couldn't add port to egress list. ",$rapidcity->error(1);
=item $rapidcity->set_remove_i_vlan_tagged(vlan, ifIndex)
Removes the port from the egress list of the VLAN, must be supplied with the
numeric VLAN ID and port C<ifIndex>.
Example:
my %if_map = reverse %{$rapidcity->interfaces()};
$rapidcity->set_remove_i_vlan_tagged('2', $if_map{'1.1'})
or die "Couldn't add port to egress list. ",$rapidcity->error(1);
=item $rapidcity->set_delete_vlan(vlan)
Deletes the specified VLAN from the device.
=item $rapidcity->set_create_vlan(name, vlan)
Creates the specified VLAN on the device.
Note: This method only allows creation of Port type VLANs and does not allow
for the setting of the Spanning Tree Group (STG) which defaults to 1.
=back
=cut
| 42wim/snmp-info | Info/RapidCity.pm | Perl | bsd-3-clause | 41,931 |
#
# Copyright 2016 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
package hardware::pdu::apc::snmp::mode::hardware;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
use centreon::plugins::misc;
my $thresholds = {
humidity => [
['notPresent', 'OK'],
['belowMin', 'CRITICAL'],
['belowLow', 'WARNING'],
['normal', 'OK'],
['aboveHigh', 'WARNING'],
['aboveMax', 'CRITICAL'],
],
temperature => [
['notPresent', 'OK'],
['belowMin', 'CRITICAL'],
['belowLow', 'WARNING'],
['normal', 'OK'],
['aboveHigh', 'WARNING'],
['aboveMax', 'CRITICAL'],
],
psu => [
['ok', 'OK'],
['failed', 'CRITICAL'],
['notPresent', 'OK'],
],
};
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 =>
{
"filter:s@" => { name => 'filter' },
"absent-problem:s@" => { name => 'absent_problem' },
"component:s" => { name => 'component', default => '.*' },
"no-component:s" => { name => 'no_component' },
"threshold-overload:s@" => { name => 'threshold_overload' },
"warning:s@" => { name => 'warning' },
"critical:s@" => { name => 'critical' },
});
$self->{components} = {};
$self->{no_components} = undef;
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
if (defined($self->{option_results}->{no_component})) {
if ($self->{option_results}->{no_component} ne '') {
$self->{no_components} = $self->{option_results}->{no_component};
} else {
$self->{no_components} = 'critical';
}
}
$self->{filter} = [];
foreach my $val (@{$self->{option_results}->{filter}}) {
next if (!defined($val) || $val eq '');
my @values = split (/,/, $val);
push @{$self->{filter}}, { filter => $values[0], instance => $values[1] };
}
$self->{absent_problem} = [];
foreach my $val (@{$self->{option_results}->{absent_problem}}) {
next if (!defined($val) || $val eq '');
my @values = split (/,/, $val);
push @{$self->{absent_problem}}, { filter => $values[0], instance => $values[1] };
}
$self->{overload_th} = {};
foreach my $val (@{$self->{option_results}->{threshold_overload}}) {
next if (!defined($val) || $val eq '');
my @values = split (/,/, $val);
if (scalar(@values) < 3) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload option '" . $val . "'.");
$self->{output}->option_exit();
}
my ($section, $instance, $status, $filter);
if (scalar(@values) == 3) {
($section, $status, $filter) = @values;
$instance = '.*';
} else {
($section, $instance, $status, $filter) = @values;
}
if ($section !~ /^humidity|temperature|psu$/) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload section '" . $val . "'.");
$self->{output}->option_exit();
}
if ($self->{output}->is_litteral_status(status => $status) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload status '" . $val . "'.");
$self->{output}->option_exit();
}
$self->{overload_th}->{$section} = [] if (!defined($self->{overload_th}->{$section}));
push @{$self->{overload_th}->{$section}}, {filter => $filter, status => $status, instance => $instance };
}
$self->{numeric_threshold} = {};
foreach my $option (('warning', 'critical')) {
foreach my $val (@{$self->{option_results}->{$option}}) {
next if (!defined($val) || $val eq '');
if ($val !~ /^(.*?),(.*?),(.*)$/) {
$self->{output}->add_option_msg(short_msg => "Wrong $option option '" . $val . "'.");
$self->{output}->option_exit();
}
my ($section, $instance, $value) = ($1, $2, $3);
if ($section !~ /^humidity|temperature$/) {
$self->{output}->add_option_msg(short_msg => "Wrong $option option '" . $val . "'.");
$self->{output}->option_exit();
}
my $position = 0;
if (defined($self->{numeric_threshold}->{$section})) {
$position = scalar(@{$self->{numeric_threshold}->{$section}});
}
if (($self->{perfdata}->threshold_validate(label => $option . '-' . $section . '-' . $position, value => $value)) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong $option threshold '" . $value . "'.");
$self->{output}->option_exit();
}
$self->{numeric_threshold}->{$section} = [] if (!defined($self->{numeric_threshold}->{$section}));
push @{$self->{numeric_threshold}->{$section}}, { label => $option . '-' . $section . '-' . $position, threshold => $option, instance => $instance };
}
}
}
sub run {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
my $snmp_request = [];
my @components = ('psu', 'humidity', 'temperature');
foreach (@components) {
if (/$self->{option_results}->{component}/) {
my $mod_name = "hardware::pdu::apc::snmp::mode::components::$_";
centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $mod_name,
error_msg => "Cannot load module '$mod_name'.");
my $func = $mod_name->can('load');
$func->(request => $snmp_request);
}
}
if (scalar(@{$snmp_request}) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong option. Cannot find component '" . $self->{option_results}->{component} . "'.");
$self->{output}->option_exit();
}
$self->{results} = $self->{snmp}->get_multiple_table(oids => $snmp_request);
foreach (@components) {
if (/$self->{option_results}->{component}/) {
my $mod_name = "hardware::pdu::apc::snmp::mode::components::$_";
my $func = $mod_name->can('check');
$func->($self);
}
}
my $total_components = 0;
my $display_by_component = '';
my $display_by_component_append = '';
foreach my $comp (sort(keys %{$self->{components}})) {
# Skipping short msg when no components
next if ($self->{components}->{$comp}->{total} == 0 && $self->{components}->{$comp}->{skip} == 0);
$total_components += $self->{components}->{$comp}->{total} + $self->{components}->{$comp}->{skip};
my $count_by_components = $self->{components}->{$comp}->{total} + $self->{components}->{$comp}->{skip};
$display_by_component .= $display_by_component_append . $self->{components}->{$comp}->{total} . '/' . $count_by_components . ' ' . $self->{components}->{$comp}->{name};
$display_by_component_append = ', ';
}
$self->{output}->output_add(severity => 'OK',
short_msg => sprintf("All %s components are ok [%s].",
$total_components,
$display_by_component)
);
if (defined($self->{option_results}->{no_component}) && $total_components == 0) {
$self->{output}->output_add(severity => $self->{no_components},
short_msg => 'No components are checked.');
}
$self->{output}->display();
$self->{output}->exit();
}
sub absent_problem {
my ($self, %options) = @_;
foreach (@{$self->{absent_problem}}) {
if ($options{section} =~ /$_->{filter}/) {
if (!defined($_->{instance}) || $options{instance} =~ /$_->{instance}/) {
$self->{output}->output_add(severity => 'CRITICAL',
short_msg => sprintf("Component '%s' instance '%s' is not present",
$options{section}, $options{instance}));
$self->{output}->output_add(long_msg => sprintf("Skipping $options{section} section $options{instance} instance (not present)"));
$self->{components}->{$options{section}}->{skip}++;
return 1;
}
}
}
return 0;
}
sub check_filter {
my ($self, %options) = @_;
foreach (@{$self->{filter}}) {
if ($options{section} =~ /$_->{filter}/) {
if (!defined($options{instance}) && !defined($_->{instance})) {
$self->{output}->output_add(long_msg => sprintf("Skipping $options{section} section."));
return 1;
} elsif (defined($options{instance}) && $options{instance} =~ /$_->{instance}/) {
$self->{components}->{$options{section}}->{skip}++ if (defined($self->{components}->{$options{section}}));
$self->{output}->output_add(long_msg => sprintf("Skipping $options{section} section $options{instance} instance."));
return 1;
}
}
}
return 0;
}
sub get_severity_numeric {
my ($self, %options) = @_;
my $status = 'OK'; # default
my $thresholds = { warning => undef, critical => undef };
my $checked = 0;
if (defined($self->{numeric_threshold}->{$options{section}})) {
my $exits = [];
foreach (@{$self->{numeric_threshold}->{$options{section}}}) {
if ($options{instance} =~ /$_->{instance}/) {
push @{$exits}, $self->{perfdata}->threshold_check(value => $options{value}, threshold => [ { label => $_->{label}, exit_litteral => $_->{threshold} } ]);
$thresholds->{$_->{threshold}} = $self->{perfdata}->get_perfdata_for_output(label => $_->{label});
$checked = 1;
}
}
$status = $self->{output}->get_most_critical(status => $exits) if (scalar(@{$exits}) > 0);
}
return ($status, $thresholds->{warning}, $thresholds->{critical}, $checked);
}
sub get_severity {
my ($self, %options) = @_;
my $status = 'UNKNOWN'; # default
if (defined($self->{overload_th}->{$options{section}})) {
foreach (@{$self->{overload_th}->{$options{section}}}) {
if ($options{value} =~ /$_->{filter}/i &&
(!defined($options{instance}) || $options{instance} =~ /$_->{instance}/)) {
$status = $_->{status};
return $status;
}
}
}
my $label = defined($options{label}) ? $options{label} : $options{section};
foreach (@{$thresholds->{$label}}) {
if ($options{value} =~ /$$_[0]/i) {
$status = $$_[1];
return $status;
}
}
return $status;
}
1;
__END__
=head1 MODE
Check components (humidity, temperature, power supplies).
=over 8
=item B<--component>
Which component to check (Default: '.*').
Can be: 'psu', 'humidity', 'temperature'.
=item B<--filter>
Exclude some parts (comma seperated list) (Example: --filter=temperature --filter=humidity)
Can also exclude specific instance: --filter=temperature,1
=item B<--absent-problem>
Return an error if an entity is not 'present' (default is skipping) (comma seperated list)
Can be specific or global: --absent-problem=psu
=item B<--no-component>
Return an error if no compenents are checked.
If total (with skipped) is 0. (Default: 'critical' returns).
=item B<--threshold-overload>
Set to overload default threshold values (syntax: section,[instance,]status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='temperature,CRITICAL,^(?!(normal)$)'
=item B<--warning>
Set warning threshold for temperatures (syntax: type,instance,threshold)
Example: --warning='temperature,.*,30'
=item B<--critical>
Set critical threshold for temperatures (syntax: type,instance,threshold)
Example: --critical='temperature,.*,40'
=back
=cut | bcournaud/centreon-plugins | hardware/pdu/apc/snmp/mode/hardware.pm | Perl | apache-2.0 | 13,315 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::MappedSliceContainer - container for mapped slices
=head1 SYNOPSIS
# get a reference slice
my $slice =
$slice_adaptor->fetch_by_region( 'chromosome', 14, 900000, 950000 );
# create MappedSliceContainer based on the reference slice
my $msc = Bio::EnsEMBL::MappedSliceContainer->new( -SLICE => $slice );
# set the adaptor for fetching AssemblySlices
my $asa = $slice->adaptor->db->get_AssemblySliceAdaptor;
$msc->set_AssemblySliceAdaptor($asa);
# add an AssemblySlice to your MappedSliceContainer
$msc->attach_AssemblySlice('NCBIM36');
foreach my $mapped_slice ( @{ $msc->get_all_MappedSlices } ) {
print $mapped_slice->name, "\n";
foreach my $sf ( @{ $mapped_slice->get_all_SimpleFeatures } ) {
print " ", &to_string($sf), "\n";
}
}
=head1 DESCRIPTION
NOTE: this code is under development and not fully functional nor tested
yet. Use only for development.
A MappedSliceContainer holds a collection of one or more
Bio::EnsEMBL::MappedSlices. It is based on a real reference slice and
contains an artificial "container slice" which defines the common
coordinate system used by all attached MappedSlices. There is also a
mapper to convert coordinates between the reference and the container
slice.
Attaching MappedSlices to the container is delegated to adaptors
(which act more as object factories than as traditional Ensembl db
adaptors). The adaptors will also modify the container slice and
associated mapper if required. This design allows us to keep the
MappedSliceContainer generic and encapsulate the data source specific
code in the adaptor/factory module.
In the simplest use case, all required MappedSlices are attached to the
MappedSliceContainer at once (by a single call to the adaptor). This
object should also allow "hot-plugging" of MappedSlices (e.g. attach a
MappedSlice representing a strain to a container that already contains a
multi-species alignment). The methods for attaching new MappedSlice will
be responsable to perform the necessary adjustments to coordinates and
mapper on the existing MappedSlices.
=head1 METHODS
new
set_adaptor
get_adaptor
set_AssemblySliceAdaptor
get_AssemblySliceAdaptor
set_AlignSliceAdaptor (not implemented yet)
get_AlignSliceAdaptor (not implemented yet)
set_StrainSliceAdaptor (not implemented yet)
get_StrainSliceAdaptor (not implemented yet)
attach_AssemblySlice
attach_AlignSlice (not implemented yet)
attach_StrainSlice (not implemented yet)
get_all_MappedSlices
sub_MappedSliceContainer (not implemented yet)
ref_slice
container_slice
mapper
expanded
=head1 RELATED MODULES
Bio::EnsEMBL::MappedSlice
Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor
Bio::EnsEMBL::Compara::AlignSlice
Bio::EnsEMBL::Compara::AlignSlice::Slice
Bio::EnsEMBL::AlignStrainSlice
Bio::EnsEMBL::StrainSlice
=cut
package Bio::EnsEMBL::MappedSliceContainer;
use strict;
use warnings;
no warnings 'uninitialized';
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw warning);
use Bio::EnsEMBL::CoordSystem;
use Bio::EnsEMBL::Slice;
use Bio::EnsEMBL::Mapper;
# define avalable adaptormajs to use with this container
my %adaptors = map { $_ => 1 } qw(assembly align strain);
=head2 new
Arg [SLICE] : Bio::EnsEMBL::Slice $slice - the reference slice for this
container
Arg [EXPANDED] : (optional) Boolean $expanded - set expanded mode (default:
collapsed)
Example : my $slice = $slice_adaptor->fetch_by_region('chromosome', 1,
9000000, 9500000);
my $msc = Bio::EnsEMBL::MappedSliceContainer->new(
-SLICE => $slice,
-EXPANDED => 1,
);
Description : Constructor. See the general documentation of this module for
details about this object. Note that the constructor creates an
empty container, so you'll have to attach MappedSlices to it to
be useful (this is usually done by an adaptor/factory).
Return type : Bio::EnsEMBL::MappedSliceContainer
Exceptions : thrown on wrong or missing argument
Caller : general
Status : At Risk
: under development
=cut
sub new {
my $caller = shift;
my $class = ref($caller) || $caller;
my ($ref_slice, $expanded) = rearrange([qw(SLICE EXPANDED)], @_);
# argument check
unless ($ref_slice and ref($ref_slice) and
($ref_slice->isa('Bio::EnsEMBL::Slice') or $ref_slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
throw("You must provide a reference slice.");
}
my $self = {};
bless ($self, $class);
# initialise object
$self->{'ref_slice'} = $ref_slice;
$self->{'expanded'} = $expanded || 0;
$self->{'mapped_slices'} = [];
# create the container slice
$self->_create_container_slice($ref_slice);
return $self;
}
#
# Create an artificial slice which represents the common coordinate system used
# for this MappedSliceContainer
#
sub _create_container_slice {
my $self = shift;
my $ref_slice = shift;
# argument check
unless ($ref_slice and ref($ref_slice) and
($ref_slice->isa('Bio::EnsEMBL::Slice') or $ref_slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
throw("You must provide a reference slice.");
}
# create an artificial coordinate system for the container slice
my $cs = Bio::EnsEMBL::CoordSystem->new(
-NAME => 'container',
-RANK => 1,
);
# Create a new artificial slice spanning your container. Initially this will
# simply span your reference slice
my $container_slice = Bio::EnsEMBL::Slice->new(
-COORD_SYSTEM => $cs,
-START => 1,
-END => $ref_slice->length,
-STRAND => 1,
-SEQ_REGION_NAME => 'container',
);
$self->{'container_slice'} = $container_slice;
# Create an Mapper to map to/from the reference slice to the container coord
# system.
my $mapper = Bio::EnsEMBL::Mapper->new('ref_slice', 'container');
$mapper->add_map_coordinates(
$ref_slice->seq_region_name,
$ref_slice->start,
$ref_slice->end,
1,
$container_slice->seq_region_name,
$container_slice->start,
$container_slice->end,
);
$self->{'mapper'} = $mapper;
}
=head2 set_adaptor
Arg[1] : String $type - the type of adaptor to set
Arg[2] : Adaptor $adaptor - the adaptor to set
Example : my $adaptor = Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor->new;
$msc->set_adaptor('assembly', $adaptor);
Description : Parameterisable wrapper for all methods that set adaptors (see
below).
Return type : same as Arg 2
Exceptions : thrown on missing type
Caller : general
Status : At Risk
: under development
=cut
sub set_adaptor {
my $self = shift;
my $type = shift;
my $adaptor = shift;
# argument check
unless ($type and $adaptors{$type}) {
throw("Missing or unknown adaptor type.");
}
$type = ucfirst($type);
my $method = "set_${type}SliceAdaptor";
return $self->$method($adaptor);
}
=head2 get_adaptor
Arg[1] : String $type - the type of adaptor to get
Example : my $assembly_slice_adaptor = $msc->get_adaptor('assembly');
Description : Parameterisable wrapper for all methods that get adaptors (see
below).
Return type : An adaptor for the requested type of MappedSlice.
Exceptions : thrown on missing type
Caller : general
Status : At Risk
: under development
=cut
sub get_adaptor {
my $self = shift;
my $type = shift;
# argument check
unless ($type and $adaptors{$type}) {
throw("Missing or unknown adaptor type.");
}
$type = ucfirst($type);
my $method = "get_${type}SliceAdaptor";
return $self->$method;
}
=head2 set_AssemblySliceAdaptor
Arg[1] : Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor - the adaptor to set
Example : my $adaptor = Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor->new;
$msc->set_AssemblySliceAdaptor($adaptor);
Description : Sets an AssemblySliceAdaptor for this container. The adaptor can
be used to attach MappedSlice for alternative assemblies.
Return type : Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor
Exceptions : thrown on wrong or missing argument
Caller : general, $self->get_adaptor
Status : At Risk
: under development
=cut
sub set_AssemblySliceAdaptor {
my $self = shift;
my $assembly_slice_adaptor = shift;
unless ($assembly_slice_adaptor and ref($assembly_slice_adaptor) and
$assembly_slice_adaptor->isa('Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor')) {
throw("Need a Bio::EnsEMBL::AssemblySliceAdaptor.");
}
$self->{'adaptors'}->{'AssemblySlice'} = $assembly_slice_adaptor;
}
=head2 get_AssemblySliceAdaptor
Example : my $assembly_slice_adaptor = $msc->get_AssemblySliceAdaptor;
Description : Gets a AssemblySliceAdaptor from this container. The adaptor can
be used to attach MappedSlice for alternative assemblies.
Return type : Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor
Exceptions : thrown on wrong or missing argument
Caller : general, $self->get_adaptor
Status : At Risk
: under development
=cut
sub get_AssemblySliceAdaptor {
my $self = shift;
unless ($self->{'adaptors'}->{'AssemblySlice'}) {
warning("No AssemblySliceAdaptor attached to MappedSliceContainer.");
}
return $self->{'adaptors'}->{'AssemblySlice'};
}
# [todo]
sub set_AlignSliceAdaptor {
throw("Not implemented yet!");
}
# [todo]
sub get_AlignSliceAdaptor {
throw("Not implemented yet!");
}
# [todo]
sub set_StrainSliceAdaptor {
my $self = shift;
my $strain_slice_adaptor = shift;
unless ($strain_slice_adaptor and ref($strain_slice_adaptor) and
$strain_slice_adaptor->isa('Bio::EnsEMBL::DBSQL::StrainSliceAdaptor')) {
throw("Need a Bio::EnsEMBL::StrainSliceAdaptor.");
}
$self->{'adaptors'}->{'StrainSlice'} = $strain_slice_adaptor;
}
# [todo]
sub get_StrainSliceAdaptor {
my $self = shift;
unless ($self->{'adaptors'}->{'StrainSlice'}) {
warning("No StrainSliceAdaptor attached to MappedSliceContainer.");
}
return $self->{'adaptors'}->{'StrainSlice'};
}
=head2 attach_AssemblySlice
Arg[1] : String $version - assembly version to attach
Example : $msc->attach_AssemblySlice('NCBIM36');
Description : Attaches a MappedSlice for an alternative assembly to this
container.
Return type : none
Exceptions : thrown on missing argument
Caller : general, Bio::EnsEMBL::DBSQL::AssemblySliceAdaptor
Status : At Risk
: under development
=cut
sub attach_AssemblySlice {
my $self = shift;
my $version = shift;
throw("Need a version.") unless ($version);
my $asa = $self->get_AssemblySliceAdaptor;
return unless ($asa);
my @mapped_slices = @{ $asa->fetch_by_version($self, $version) };
push @{ $self->{'mapped_slices'} }, @mapped_slices;
}
=head2 attach_StrainSlice
Arg[1] : String $strain - name of strain to attach
Example : $msc->attach_StrainSlice('Watson');
Description : Attaches a MappedSlice for an alternative strain to this
container.
Return type : none
Exceptions : thrown on missing argument
Caller : general, Bio::EnsEMBL::DBSQL::StrainSliceAdaptor
Status : At Risk
: under development
=cut
sub attach_StrainSlice {
my $self = shift;
my $strain = shift;
throw("Need a strain.") unless ($strain);
my $ssa = $self->get_StrainSliceAdaptor;
return unless ($ssa);
my @mapped_slices = @{ $ssa->fetch_by_name($self, $strain) };
push @{ $self->{'mapped_slices'} }, @mapped_slices;
}
=head2 get_all_MappedSlices
Example : foreach my $mapped_slice (@{ $msc->get_all_MappedSlices }) {
print $mapped_slice->name, "\n";
}
Description : Returns all MappedSlices attached to this container.
Return type : listref of Bio::EnsEMBL::MappedSlice
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub get_all_MappedSlices {
my $self = shift;
return $self->{'mapped_slices'};
}
# [todo]
sub sub_MappedSliceContainer {
throw("Not implemented yet!");
}
=head2 ref_slice
Arg[1] : (optional) Bio::EnsEMBL::Slice - the reference slice to set
Example : my $ref_slice = $mapped_slice_container->ref_slice;
print "This MappedSliceContainer is based on the reference
slice ", $ref_slice->name, "\n";
Description : Getter/setter for the reference slice.
Return type : Bio::EnsEMBL::Slice
Exceptions : thrown on wrong argument type
Caller : general
Status : At Risk
: under development
=cut
sub ref_slice {
my $self = shift;
if (@_) {
my $slice = shift;
unless (ref($slice) and ($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice'))) {
throw("Need a Bio::EnsEMBL::Slice.");
}
$self->{'ref_slice'} = $slice;
}
return $self->{'ref_slice'};
}
=head2 container_slice
Arg[1] : (optional) Bio::EnsEMBL::Slice - the container slice to set
Example : my $container_slice = $mapped_slice_container->container_slice;
print "The common slice used by this MappedSliceContainer is ",
$container_slice->name, "\n";
Description : Getter/setter for the container slice. This is an artificial
slice which defines the common coordinate system used by the
MappedSlices attached to this container.
Return type : Bio::EnsEMBL::Slice
Exceptions : thrown on wrong argument type
Caller : general
Status : At Risk
: under development
=cut
sub container_slice {
my $self = shift;
if (@_) {
my $slice = shift;
unless (ref($slice) and ($slice->isa('Bio::EnsEMBL::Slice') or $slice->isa('Bio::EnsEMBL::LRGSlice')) ) {
throw("Need a Bio::EnsEMBL::Slice.");
}
$self->{'container_slice'} = $slice;
}
return $self->{'container_slice'};
}
=head2 mapper
Arg[1] : (optional) Bio::EnsEMBL::Mapper - the mapper to set
Example : my $mapper = Bio::EnsEMBL::Mapper->new('ref', 'mapped');
$mapped_slice_container->mapper($mapper);
Description : Getter/setter for the mapper to map between reference slice and
the artificial container coord system.
Return type : Bio::EnsEMBL::Mapper
Exceptions : thrown on wrong argument type
Caller : internal, Bio::EnsEMBL::MappedSlice->AUTOLOAD
Status : At Risk
: under development
=cut
sub mapper {
my $self = shift;
if (@_) {
my $mapper = shift;
unless (ref($mapper) and $mapper->isa('Bio::EnsEMBL::Mapper')) {
throw("Need a Bio::EnsEMBL::Mapper.");
}
$self->{'mapper'} = $mapper;
}
return $self->{'mapper'};
}
=head2 expanded
Arg[1] : (optional) Boolean - expanded mode to set
Example : if ($mapped_slice_container->expanded) {
# do more elaborate mapping than in collapsed mode
[...]
}
Description : Getter/setter for expanded mode.
By default, MappedSliceContainer use collapsed mode, which
means that no inserts in the reference sequence are allowed
when constructing the MappedSlices. in this mode, the
mapped_slice artificial coord system will be identical with the
ref_slice coord system.
By setting expanded mode, you allow inserts in the reference
sequence.
Return type : Boolean
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub expanded {
my $self = shift;
$self->{'expanded'} = shift if (@_);
return $self->{'expanded'};
}
=head2 seq
Example : my $seq = $container->seq()
Description : Retrieves the expanded sequence of the artificial container
slice, including "-" characters where there are inserts in any
of the attached mapped slices.
Return type : String
Exceptions : none
Caller : general
Status : At Risk
: under development
=cut
sub seq {
my $self = shift;
my $container_seq = '';
# check there's a mapper
if(defined($self->mapper)) {
my $start = 0;
my $slice = $self->ref_slice();
my $seq = $slice->seq();
foreach my $coord($self->mapper->map_coordinates($slice->seq_region_name, $slice->start, $slice->end, $slice->strand, 'ref_slice')) {
# if it is a normal coordinate insert sequence
if(!$coord->isa('Bio::EnsEMBL::Mapper::IndelCoordinate')) {
$container_seq .= substr($seq, $start, $coord->length());
$start += $coord->length;
}
# if it is a gap or indel insert "-"
else {
$container_seq .= '-' x $coord->length();
}
}
}
return $container_seq;
}
1;
| mjg17/ensembl | modules/Bio/EnsEMBL/MappedSliceContainer.pm | Perl | apache-2.0 | 18,151 |
#!/usr/bin/perl
use strict;
use warnings;
# use lib './blib/lib';
use DBI;
use IO::File;
use File::Spec;
use Getopt::Long;
use Bio::DB::GFF;
use Bio::DB::GFF::Util::Binning 'bin';
use constant MYSQL => 'mysql';
use constant FDATA => 'fdata';
use constant FTYPE => 'ftype';
use constant FGROUP => 'fgroup';
use constant FDNA => 'fdna';
use constant FATTRIBUTE => 'fattribute';
use constant FATTRIBUTE_TO_FEATURE => 'fattribute_to_feature';
=head1 NAME
bp_bulk_load_gff.pl - Bulk-load a Bio::DB::GFF database from GFF files.
=head1 SYNOPSIS
% bp_bulk_load_gff.pl -d testdb dna1.fa dna2.fa features1.gff features2.gff ...
=head1 DESCRIPTION
This script loads a Bio::DB::GFF database with the features contained
in a list of GFF files and/or FASTA sequence files. You must use the
exact variant of GFF described in L<Bio::DB::GFF>. Various
command-line options allow you to control which database to load and
whether to allow an existing database to be overwritten.
This script differs from bp_load_gff.pl in that it is hard-coded to use
MySQL and cannot perform incremental loads. See L<bp_load_gff.pl> for an
incremental loader that works with all databases supported by
Bio::DB::GFF, and L<bp_fast_load_gff.pl> for a MySQL loader that supports
fast incremental loads.
=head2 NOTES
If the filename is given as "-" then the input is taken from standard
input. Compressed files (.gz, .Z, .bz2) are automatically
uncompressed.
FASTA format files are distinguished from GFF files by their filename
extensions. Files ending in .fa, .fasta, .fast, .seq, .dna and their
uppercase variants are treated as FASTA files. Everything else is
treated as a GFF file. If you wish to load -fasta files from STDIN,
then use the -f command-line swith with an argument of '-', as in
gunzip my_data.fa.gz | bp_fast_load_gff.pl -d test -f -
The nature of the bulk load requires that the database be on the local
machine and that the indicated user have the "file" privilege to load
the tables and have enough room in /usr/tmp (or whatever is specified
by the \$TMPDIR environment variable), to hold the tables transiently.
Local data may now be uploaded to a remote server via the --local option
with the database host specified in the dsn, e.g. dbi:mysql:test:db_host
The adaptor used is dbi::mysqlopt. There is currently no way to
change this.
About maxfeature: the default value is 100,000,000 bases. If you have
features that are close to or greater that 100Mb in length, then the
value of maxfeature should be increased to 1,000,000,000. This value
must be a power of 10.
Note that Windows users must use the --create option.
If the list of GFF or fasta files exceeds the kernel limit for the
maximum number of command-line arguments, use the
--long_list /path/to/files option.
=head1 COMMAND-LINE OPTIONS
Command-line options can be abbreviated to single-letter options.
e.g. -d instead of --database.
--database <dsn> Database name (default dbi:mysql:test)
--adaptor Adaptor name (default mysql)
--create Reinitialize/create data tables without asking
--user Username to log in as
--fasta File or directory containing fasta files to load
--long_list Directory containing a very large number of
GFF and/or FASTA files
--password Password to use for authentication
(Does not work with Postgres, password must be
supplied interactively or be left empty for
ident authentication)
--maxbin Set the value of the maximum bin size
--local Flag to indicate that the data source is local
--maxfeature Set the value of the maximum feature size (power of 10)
--group A list of one or more tag names (comma or space separated)
to be used for grouping in the 9th column.
--gff3_munge Activate GFF3 name munging (see Bio::DB::GFF)
--summary Generate summary statistics for drawing coverage histograms.
This can be run on a previously loaded database or during
the load.
--Temporary Location of a writable scratch directory
=head1 SEE ALSO
L<Bio::DB::GFF>, L<fast_load_gff.pl>, L<load_gff.pl>
=head1 AUTHOR
Lincoln Stein, lstein@cshl.org
Copyright (c) 2002 Cold Spring Harbor Laboratory
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself. See DISCLAIMER.txt for
disclaimers of warranty.
=cut
package Bio::DB::GFF::Adaptor::fauxmysql;
use Bio::DB::GFF::Adaptor::dbi::mysqlopt;
use vars '@ISA';
@ISA = 'Bio::DB::GFF::Adaptor::dbi::mysqlopt';
sub insert_sequence {
my $self = shift;
my ($id,$offset,$seq) = @_;
print join("\t",$id,$offset,$seq),"\n";
};
package Bio::DB::GFF::Adaptor::fauxmysqlcmap;
use Bio::DB::GFF::Adaptor::dbi::mysqlcmap;
use vars '@ISA';
@ISA = 'Bio::DB::GFF::Adaptor::dbi::mysqlcmap';
sub insert_sequence {
my $self = shift;
my ($id,$offset,$seq) = @_;
print join("\t",$id,$offset,$seq),"\n";
};
package Bio::DB::GFF::Adaptor::fauxpg;
use Bio::DB::GFF::Adaptor::dbi::pg;
use vars '@ISA';
@ISA = 'Bio::DB::GFF::Adaptor::dbi::pg';
#these two subs are to separate the table creation from the
#index creation
sub do_initialize {
my $self = shift;
my $erase = shift;
$self->drop_all if $erase;
my $dbh = $self->features_db;
my $schema = $self->schema;
foreach my $table_name ($self->tables) {
my $create_table_stmt = $schema->{$table_name}{table} ;
$dbh->do($create_table_stmt) || warn $dbh->errstr;
# $self->create_other_schema_objects(\%{$schema->{$table_name}});
}
1;
}
sub _create_indexes_etc {
my $self = shift;
my $dbh = $self->features_db;
my $schema = $self->schema;
foreach my $table_name ($self->tables) {
$self->create_other_schema_objects(\%{$schema->{$table_name}});
}
}
sub insert_sequence {
my $self = shift;
my ($id,$offset,$seq) = @_;
print "$id\t$offset\t$seq\n";
}
package main;
eval "use Time::HiRes"; undef $@;
my $timer = defined &Time::HiRes::time;
my $bWINDOWS = 0; # Boolean: is this a MSWindows operating system?
if ($^O =~ /MSWin32/i) {
$bWINDOWS = 1;
}
my ($DSN,$ADAPTOR,$FORCE,$USER,$PASSWORD,$FASTA,$LOCAL,$MAX_BIN,$GROUP_TAG,$LONG_LIST,$MUNGE,$TMPDIR);
GetOptions ('database:s' => \$DSN,
'adaptor:s' => \$ADAPTOR,
'create' => \$FORCE,
'user:s' => \$USER,
'password:s' => \$PASSWORD,
'fasta:s' => \$FASTA,
'local' => \$LOCAL,
'maxbin|maxfeature:s' => \$MAX_BIN,
'group:s' => \$GROUP_TAG,
'long_list:s' => \$LONG_LIST,
'gff3_munge' => \$MUNGE,
'Temporary:s' => \$TMPDIR,
) or (system('pod2text', $0), exit -1);
# If called as pg_bulk_load_gff.pl behave as that did.
if ($0 =~/pg_bulk_load_gff.pl/){
$ADAPTOR ||= 'Pg';
$DSN ||= 'test';
}
$DSN ||= 'dbi:mysql:test';
$MAX_BIN ||= 1_000_000_000; # to accomodate human-sized chromosomes
if ($bWINDOWS && not $FORCE) {
die "Note that Windows users must use the --create option.\n";
}
unless ($FORCE) {
die "This will delete all existing data in database $DSN. If you want to do this, rerun with the --create option.\n"
if $bWINDOWS;
open (TTY,"/dev/tty") or die "/dev/tty: $!\n"; #TTY use removed for win compatability
print STDERR "This operation will delete all existing data in database $DSN. Continue? ";
my $f = <TTY>;
die "Aborted\n" unless $f =~ /^[yY]/;
close TTY;
}
# postgres DBD::Pg allows 'database', but also 'dbname', and 'db':
# and it must be Pg (not pg)
$DSN=~s/pg:database=/Pg:/i;
$DSN=~s/pg:dbname=/Pg:/i;
$DSN=~s/pg:db=/Pg:/i;
# leave these lines for mysql
$DSN=~s/database=//i;
$DSN=~s/;host=/:/i; #cater for dsn in the form of "dbi:mysql:database=$dbname;host=$host"
my($DBI,$DBD,$DBNAME,$HOST)=split /:/,$DSN;
$DBNAME=$DSN unless $DSN=~/:/;
$ADAPTOR ||= $DBD;
$ADAPTOR ||= 'mysql';
if ($DBD eq 'Pg') {
# rebuild DSN, DBD::Pg requires full dbname=<name> format
$DSN = "dbi:Pg:dbname=$DBNAME";
if ($HOST) { $DSN .= ";host=$HOST"; }
}
my ($use_mysql,$use_mysqlcmap,$use_pg) = (0,0,0);
if ( $ADAPTOR eq 'mysqlcmap' ) {
$use_mysqlcmap = 1;
}
elsif ( $ADAPTOR =~ /^mysql/ ) {
$use_mysql = 1;
}
elsif ( $ADAPTOR eq "Pg" ) {
$use_pg = 1;
}
else{
die "$ADAPTOR is not an acceptable database adaptor.";
}
my (@auth,$AUTH);
if (defined $USER) {
push @auth,(-user=>$USER);
if ( $use_mysql or $use_mysqlcmap ) {
$AUTH .= " -u$USER";
}
elsif ( $use_pg ) {
$AUTH .= " -U $USER ";
}
}
if (defined $PASSWORD) {
push @auth,(-pass=>$PASSWORD);
if ( $use_mysql or $use_mysqlcmap ) {
$AUTH .= " -p$PASSWORD";
}
# elsif ( $use_pg ) {
# $AUTH .= " -W $PASSWORD ";
# }
}
if (defined $HOST) {
$AUTH .= " -h$HOST";
}
if (defined $DBNAME) {
if ( $use_mysql or $use_mysqlcmap ) {
$AUTH .= " -D$DBNAME ";
}
}
if (defined $LOCAL) {
$LOCAL='local';
$AUTH.=' --local-infile=1';
}else {
$LOCAL='';
}
my $faux_adaptor;
if ( $use_mysqlcmap ) {
$faux_adaptor = "fauxmysqlcmap";
}
elsif ( $use_mysql ) {
$faux_adaptor = "fauxmysql";
}
elsif ( $use_pg ) {
$faux_adaptor = "fauxpg";
}
my $db = Bio::DB::GFF->new(-adaptor=>$faux_adaptor,-dsn => $DSN,@auth)
or die "Can't open database: ",Bio::DB::GFF->error,"\n";
$db->gff3_name_munging(1) if $MUNGE;
$MAX_BIN ? $db->initialize(-erase=>1,-MAX_BIN=>$MAX_BIN) : $db->initialize(1);
$MAX_BIN ||= $db->meta('max_bin') || 100_000_000;
# deal with really long lists of files
if ($LONG_LIST) {
-d $LONG_LIST or die "The --long_list argument must be a directory\n";
opendir GFFDIR,$LONG_LIST or die "Could not open $LONG_LIST for reading: $!";
@ARGV = map { "$LONG_LIST\/$_" } readdir GFFDIR;
closedir GFFDIR;
if (defined $FASTA && -d $FASTA) {
opendir FASTA,$FASTA or die "Could not open $FASTA for reading: $!";
push @ARGV, map { "$FASTA\/$_" } readdir FASTA;
closedir FASTA;
}
elsif (defined $FASTA && -f $FASTA) {
push @ARGV, $FASTA;
}
}
foreach (@ARGV) {
$_ = "gunzip -c $_ |" if /\.gz$/;
$_ = "uncompress -c $_ |" if /\.Z$/;
$_ = "bunzip2 -c $_ |" if /\.bz2$/;
}
my (@gff,@fasta);
foreach (@ARGV) {
if (/\.(fa|fasta|dna|seq|fast)(?:$|\.)/i) {
push @fasta,$_;
} else {
push @gff,$_;
}
}
@ARGV = @gff;
push @fasta,$FASTA if defined $FASTA;
# drop everything that was there before
my %FH;
my $tmpdir = File::Spec->tmpdir() || '/tmp';
$tmpdir =~ s!\\!\\\\!g if $bWINDOWS; #eliminates backslash mis-interpretation
-d $tmpdir or die <<END;
I could not find a suitable temporary directory to write scratch files into ($tmpdir by default).
Please select a directory and indicate its location by setting the TMP environment variable, or
by using the --Temporary switch.
END
my @fasta_files_to_be_unlinked;
my @files = (FDATA,FTYPE,FGROUP,FDNA,FATTRIBUTE,FATTRIBUTE_TO_FEATURE);
foreach (@files) {
$FH{$_} = IO::File->new(">$tmpdir/$_.$$") or die $_,": $!";
$FH{$_}->autoflush;
}
if ( $use_pg ) {
$FH{FDATA() }->print("COPY fdata (fid, fref, fstart, fstop, fbin, ftypeid, fscore, fstrand, fphase, gid, ftarget_start, ftarget_stop) FROM stdin;\n");
$FH{FTYPE() }->print("COPY ftype (ftypeid, fmethod, fsource) FROM stdin;\n");
$FH{FGROUP() }->print("COPY fgroup (gid, gclass, gname) FROM stdin;\n");
$FH{FATTRIBUTE() }->print("COPY fattribute (fattribute_id, fattribute_name) FROM stdin;\n");
$FH{FATTRIBUTE_TO_FEATURE()}->print("COPY fattribute_to_feature (fid, fattribute_id, fattribute_value) FROM stdin;\n");
}
my $FID = 1;
my $GID = 1;
my $FTYPEID = 1;
my $ATTRIBUTEID = 1;
my %GROUPID = ();
my %FTYPEID = ();
my %ATTRIBUTEID = ();
my %DONE = ();
my $FEATURES = 0;
my %tmpfiles; # keep track of temporary fasta files
my $count;
my $fasta_sequence_id;
my $gff3;
my $current_file; #used to reset GFF3 flag in mix of GFF and GFF3 files
$db->preferred_groups(split (/[,\s]+/,$GROUP_TAG)) if defined $GROUP_TAG;
my $last = Time::HiRes::time() if $timer;
my $start = $last;
# avoid hanging on standalone --fasta load
if (!@ARGV) {
$FH{NULL} = IO::File->new(">$tmpdir/null");
push @ARGV, "$tmpdir/null";
}
my ($cmap_db);
if ($use_mysqlcmap){
my $options = {
AutoCommit => 1,
FetchHashKeyName => 'NAME_lc',
LongReadLen => 3000,
LongTruncOk => 1,
RaiseError => 1,
};
$cmap_db = DBI->connect( $DSN, $USER, $PASSWORD, $options );
}
# Only load CMap::Utils if using cmap
unless (!$use_mysqlcmap or
eval {
require Bio::GMOD::CMap::Utils;
Bio::GMOD::CMap::Utils->import('next_number');
1;
}
) {
print STDERR "Error loading Bio::GMOD::CMap::Utils\n";
}
while (<>) {
$current_file ||= $ARGV;
# reset GFF3 flag if new filehandle
unless($current_file eq $ARGV){
undef $gff3;
$current_file = $ARGV;
}
chomp;
my ($ref,$source,$method,$start,$stop,$score,$strand,$phase,$group);
# close sequence filehandle if required
if ( /^\#|\s+|^$|^>|\t/ && defined $FH{FASTA}) {
$FH{FASTA}->close;
delete $FH{FASTA};
}
# print to fasta file if the handle is open
if ( defined $FH{FASTA} ) {
$FH{FASTA}->print("$_\n");
next;
}
elsif (/^>(\S+)/) { # uh oh, sequence coming
$FH{FASTA} = IO::File->new(">$tmpdir/$1\.fa") or die "FASTA: $!\n";
$FH{FASTA}->print("$_\n");
print STDERR "Preparing embedded sequence $1\n";
push @fasta, "$tmpdir/$1\.fa";
push @fasta_files_to_be_unlinked,"$tmpdir/$1\.fa";
$tmpfiles{"$tmpdir/$1\.fa"}++;
next;
}
elsif (/^\#\#\s*gff-version\s+(\d+)/) {
$gff3 = ($1 >= 3);
$db->print_gff3_warning() if $gff3;
next;
}
elsif (/^\#\#\s*group-tags\s+(.+)/) {
$db->preferred_groups(split(/\s+/,$1));
next;
}
elsif (/^\#\#\s*sequence-region\s+(\S+)\s+(\d+)\s+(\d+)/i) { # header line
($ref,$source,$method,$start,$stop,$score,$strand,$phase,$group) =
($1,'reference','Component',$2,$3,'.','.','.',$gff3 ? "ID=Sequence:$1": qq(Sequence "$1"));
}
elsif (/^\#/) {
next;
}
else {
($ref,$source,$method,$start,$stop,$score,$strand,$phase,$group) = split "\t";
}
if ( not defined( $ref ) or length ($ref) == 0) {
warn "\$ref is null. source = $source, method = $method, group = $group\n";
next;
}
$FEATURES++;
my $size = $stop-$start+1;
warn "Feature $group ($size) is larger than $MAX_BIN. You will have trouble retrieving this feature.\nRerun script with --maxfeature set to a higher power of 10.\n" if $size > $MAX_BIN;
$source = '\N' unless defined $source;
$score = '\N' if $score eq '.';
$strand = '\N' if $strand eq '.';
$phase = '\N' if $phase eq '.';
my ($group_class,$group_name,$target_start,$target_stop,$attributes) = $db->split_group($group,$gff3);
# GFF2/3 transition
$group_class = [$group_class] unless ref $group_class;
$group_name = [$group_name] unless ref $group_name;
for (my $i=0; $i < @$group_name; $i++) {
$group_class->[$i] ||= '\N';
$group_name->[$i] ||= '\N';
$target_start ||= '\N';
$target_stop ||= '\N';
$method ||= '\N';
$source ||= '\N';
my $fid = $FID++;
my $gid = $GROUPID{lc join('',$group_class->[$i],$group_name->[$i])} ||= $GID++;
my $ftypeid = $FTYPEID{lc join('',$source,$method)} ||= $FTYPEID++;
my $bin = bin($start,$stop,$db->min_bin);
$FH{ FDATA() }->print( join("\t",$fid,$ref,$start,$stop,$bin,$ftypeid,$score,$strand,$phase,$gid,$target_start,$target_stop),"\n" );
if ($use_mysqlcmap){
my $feature_id = next_number(
db => $cmap_db,
table_name => 'cmap_feature',
id_field => 'feature_id',
)
or die 'No feature id';
my $direction = $strand eq '-' ? -1:1;
$FH{ FGROUP() }->print(
join("\t",$feature_id,$feature_id,'NULL',0, $group_name->[$i],0,0,'NULL',1,$direction, $group_class->[$i],)
,"\n"
) unless $DONE{"G$gid"}++;
}
else {
$FH{ FGROUP() }->print( join("\t",$gid,$group_class->[$i],$group_name->[$i]),"\n") unless $DONE{"G$gid"}++;
}
$FH{ FTYPE() }->print( join("\t",$ftypeid,$method,$source),"\n" ) unless $DONE{"T$ftypeid"}++;
foreach (@$attributes) {
my ($key,$value) = @$_;
my $attributeid = $ATTRIBUTEID{$key} ||= $ATTRIBUTEID++;
$FH{ FATTRIBUTE() }->print( join("\t",$attributeid,$key),"\n" ) unless $DONE{"A$attributeid"}++;
$FH{ FATTRIBUTE_TO_FEATURE() }->print( join("\t",$fid,$attributeid,$value),"\n");
}
if ( $fid % 1000 == 0) {
my $now = Time::HiRes::time() if $timer;
my $elapsed = $timer ? sprintf(" in %5.2fs",$now - $last) : '';
$last = $now;
print STDERR "$fid features parsed$elapsed...";
print STDERR -t STDOUT && !$ENV{EMACS} ? "\r" : "\n";
}
}
}
$FH{FASTA}->close if exists $FH{FASTA};
for my $file (@fasta) {
warn "Preparing DNA file $file....\n";
if ($use_pg){
$FH{FDNA() }->print("COPY fdna (fref, foffset, fdna) FROM stdin;\n");
}
my $old = select($FH{FDNA()});
$db->load_fasta($file) or warn "Couldn't load fasta file $file: $!";
if ($use_pg){
$FH{FDNA() }->print("\\.\n\n");
}
warn "done...\n";
select $old;
unlink $file if $tmpfiles{$file};
}
if ($use_pg) {
$FH{FDATA() }->print("\\.\n\n");
$FH{FTYPE() }->print("\\.\n\n");
$FH{FGROUP() }->print("\\.\n\n");
$FH{FATTRIBUTE() }->print("\\.\n\n");
$FH{FATTRIBUTE_TO_FEATURE()}->print("\\.\n\n");
}
$_->close foreach values %FH;
printf STDERR "Total parse time %5.2fs\n",(Time::HiRes::time() - $start) if $timer;
warn "Loading feature data and analyzing tables. You may see RDBMS messages here...\n";
if ($use_pg){
warn "Loading feature data. You may see Postgres comments...\n";
foreach (@files) {
my $file = "$tmpdir/$_.$$";
$AUTH ? system("psql $AUTH -f $file $DBNAME")
: system('psql','-f', $file, $DBNAME);
unlink $file;
}
warn "Updating sequences ...\n";
$db->update_sequences();
warn "Creating indexes ...\n";
$db->_create_indexes_etc();
warn "done...\n";
}
elsif( $use_mysql or $use_mysqlcmap ) {
$start = time();
my $success = 1;
my $TERMINATEDBY = $bWINDOWS ? q( LINES TERMINATED BY '\r\n') : '';
for my $f (@files) {
my $table = function_to_table($f,$ADAPTOR);
my $sql = join ('; ',
"lock tables $table write",
"delete from $table",
"load data $LOCAL infile '$tmpdir/$f.$$' replace into table $table $TERMINATEDBY",
"unlock tables");
my $command = MYSQL . qq[$AUTH -s -e "$sql"];
$command =~ s/\n/ /g;
$success &&= system($command) == 0;
unlink "$tmpdir/$f.$$";
}
printf STDERR "Total load time %5.2fs\n",(time() - $start) if $timer;
print STDERR "done...\n";
print STDERR "Analyzing/optimizing tables. You will see database messages...\n";
$start = time();
my $sql = '';
for my $f (@files) {
my $table = function_to_table($f,$ADAPTOR);
$sql .= "analyze table $table;";
}
my $command = MYSQL . qq[$AUTH -N -s -e "$sql"];
$success &&= system($command) == 0;
printf STDERR "Optimization time time %5.2fs\n",(time() - $start);
if ($success) {
print "$FEATURES features successfully loaded\n";
} else {
print "FAILURE: Please see standard error for details\n";
exit -1;
}
}
foreach (@fasta_files_to_be_unlinked) {
unlink "$tmpdir/$_.$$";
}
warn "Building summary statistics for coverage histograms...\n";
my (@args,$AUTH);
if (defined $USER) {
push @args,(-user=>$USER);
$AUTH .= " -u$USER";
}
if (defined $PASSWORD) {
push @args,(-pass=>$PASSWORD);
$AUTH .= " -p$PASSWORD";
}
push @args,(-preferred_groups=>[split(/[,\s+]+/,$GROUP_TAG)]) if defined $GROUP_TAG;
my $db = Bio::DB::GFF->new(-adaptor=>"dbi::$ADAPTOR",-dsn => $DSN,@args)
or die "Can't open database: ",Bio::DB::GFF->error,"\n";
$db->build_summary_statistics;
exit 0;
sub function_to_table {
my $function = shift;
my $adaptor = shift;
if ($function eq 'fdata'){
return 'fdata';
}
elsif ($function eq 'ftype'){
return 'ftype';
}
elsif ($function eq 'fgroup'){
return 'cmap_feature' if ($adaptor eq 'mysqlcmap');
return 'fgroup';
}
elsif ($function eq 'fdna'){
return 'fdna';
}
elsif ($function eq 'fattribute'){
return 'fattribute';
}
elsif ($function eq 'fattribute_to_feature'){
return 'fattribute_to_feature';
}
return '';
}
__END__
| irusri/Extract-intron-from-gff3 | scripts/bp_bulk_load_gff.pl | Perl | mit | 20,903 |
print "Help Desk -- What Editor do you use? ";
chomp($editor = <STDIN>);
if ($editor =~ /emacs/i) {
print "Why aren't you using vi?\n";
} elsif ($editor =~ /vi/i) {
print "Why aren't you using emacs?\n";
} else {
print "I think that's the problem\n";
}
| pop-idol/pop_examples | pop/lint-notes/Perl-Tidy-20140328/docs/testfile.pl | Perl | apache-2.0 | 260 |
#!/usr/bin/perl -wl
# CommonAccord - bringing the world to agreement
# Written in 2014 by Primavera De Filippi To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
# You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
use warnings;
use strict;
my $path = "./Doc/";
my %imports;
sub tree_parse {
my ($file) = @_; my $f; open $f, $file or die "error opening ($file): $!\n";
$imports{$file} = [];
while(<$f>) {
my($one, $two);
if( ( ($one,$two) = $_ =~m/^([^=]*)=\[(.+?)\]/ ) ) {
push @{ $imports{$file} }, $path . $two;
tree_parse($path. $two);
}
}
}
tree_parse($ARGV[0]);
print " [ \n";
foreach my $k (keys(%imports)) {
print ' { "name": "'.$k.'", "imports": [';
print '"'. $_ .'",' foreach @{ $imports{$k} };
print '] },';
}
print " ] \n";
| CommonAccord/Cmacc-Tech | vendor/library/tree-parse.pl | Perl | mit | 1,092 |
#!/usr/bin/env perl
#
use strict;
my ($include_dir, $data_dir, $feature_file);
if( @ARGV ) {
die "Invalid number of arguments" if scalar @ARGV != 3;
($include_dir, $data_dir, $feature_file) = @ARGV;
-d $include_dir or die "No such directory: $include_dir\n";
-d $data_dir or die "No such directory: $data_dir\n";
} else {
$include_dir = 'include/mbedtls';
$data_dir = 'scripts/data_files';
$feature_file = 'library/version_features.c';
unless( -d $include_dir && -d $data_dir ) {
chdir '..' or die;
-d $include_dir && -d $data_dir
or die "Without arguments, must be run from root or scripts\n"
}
}
my $feature_format_file = $data_dir.'/version_features.fmt';
my @sections = ( "System support", "mbed TLS modules",
"mbed TLS feature support" );
my $line_separator = $/;
undef $/;
open(FORMAT_FILE, "$feature_format_file") or die "Opening feature format file '$feature_format_file': $!";
my $feature_format = <FORMAT_FILE>;
close(FORMAT_FILE);
$/ = $line_separator;
open(CONFIG_H, "$include_dir/config.h") || die("Failure when opening config.h: $!");
my $feature_defines = "";
my $in_section = 0;
while (my $line = <CONFIG_H>)
{
next if ($in_section && $line !~ /#define/ && $line !~ /SECTION/);
next if (!$in_section && $line !~ /SECTION/);
if ($in_section) {
if ($line =~ /SECTION/) {
$in_section = 0;
next;
}
my ($define) = $line =~ /#define (\w+)/;
$feature_defines .= "#if defined(${define})\n";
$feature_defines .= " \"${define}\",\n";
$feature_defines .= "#endif /* ${define} */\n";
}
if (!$in_section) {
my ($section_name) = $line =~ /SECTION: ([\w ]+)/;
my $found_section = grep $_ eq $section_name, @sections;
$in_section = 1 if ($found_section);
}
};
$feature_format =~ s/FEATURE_DEFINES\n/$feature_defines/g;
open(ERROR_FILE, ">$feature_file") or die "Opening destination file '$feature_file': $!";
print ERROR_FILE $feature_format;
close(ERROR_FILE);
| erja-gp/openthread | third_party/mbedtls/repo/scripts/generate_features.pl | Perl | bsd-3-clause | 2,085 |
#Copyright 2009, 2010 Daniel Gaston, Andrew Roger Lab
#This code is copyrighted under the GNU General Public License Version 3.0
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long qw(:config no_ignore_case);
use PhyloTree_new;
use Seq;
use Node;
use Extras;
use QmmRAxML;
use RAxML;
use iqtree;
use Math::BigFloat;
use List::Util qw(min max);
################################################################################
#Author: Daniel Gaston
#Last Modified: July 2016
#Version: 1.1
################################################################################
################################################################################
# Constants #
################################################################################
my $OPTDIR = "Optimization/";
my $NUM_CLASSES = 10;
my $phy_file_name;
my $optimal_lh;
my $branch_opt;
my $max_opt;
my $step = 0.02;#####
################################################################################
# Main #
################################################################################
if(scalar(@ARGV) == 0){
runMenuMode(@_);
}else{
runCLIMode(@_);
}
################################################################################
# Subroutines #
################################################################################
sub runCLIMode{
if(scalar(@ARGV) == 0){
@ARGV = @_;
}
open(LOG, ">>FunDi.log") or die "Could not open FunDi.log...\n\n";
print LOG "FunDi running with specified options @ARGV\n";
my $intree = "";
my $inalign = "";
my $outroot = "subtree";
my $subtree = "subtree.def";
my $midroot;
my $model = "LG+C20+F+G"; ####
my $num_rates = 4;
my $parallel = 0;
my $help = 0;
my $verbose = 0;
my $program = "iqtree"; ####
my $length = 10000;
my $debug = 0;
my $mask_cut = 1.0;
my $num_cpus = 1;
my $retree_command = "retree";
my @masked_sites;
my $seed = 20120821;
my $branch_len_opt = 1;
GetOptions(
'tree=s' => \$intree, 'align=s' => \$inalign,
'outroot=s' => \$outroot, 'Midroot' => \$midroot,
'subtree=s' => \$subtree, 'parallel' => \$parallel,
'debug' => \$debug, 'help' => \$help,
'verbose' => \$verbose, 'length=i' => \$length,
'model=s' => \$model, 'rates=i' => \$num_rates,
'Program=s' => \$program, 'cutoff=f' => \$mask_cut,
'Num_cpus=s' => \$num_cpus, 'Opt_bl' => \$branch_len_opt
);
if($inalign eq "" || $help){
printHelp();
exit();
}
$program = lc $program;
if($program ne 'qmmraxml' && $program ne 'raxml' && $program ne 'iqtree'){
print "Unknown phylogeny program selected. Must be either qmmraxml, iqtree or raxml.\nExiting...\n\n";
exit();
}
if($parallel && $num_cpus == 1){
$num_cpus = 2;
}
# Not being used
if($mask_cut < 1.0){
my $ref;
($inalign, $ref) = maskAlignment($inalign, $mask_cut);
@masked_sites = @{$ref};
}
# Convert FASTA file to PHYLIP
if($inalign =~ /\.fasta$/ || $inalign =~ /\.fst$/ || $inalign =~ /\.faa$/){
print "Detected by file extension that $inalign is a FASTA formated file. Exporting Phylip\n";
my %seq = Seq::readFasta($inalign);
my $out = $inalign . ".phy";
print "Printing as $out\n";
Seq::printPhylip($out, \%seq);
$inalign = $out;
}
$phy_file_name = $inalign; # This gets used for output files but $inalign is already .phy file name by this point
# Retrieving from .def and creating a 2D array and subtrees
print "Retrieving subtree definitions from $subtree...\n";
my @subtrees = getSubtreesFile($subtree);
# Optimize branch lengths of the input tree using the chosen ML program and model
if($program eq 'qmmraxml'){
print "Optimizing branch lengths of user input tree using QmmRAxML\n";
my $raxml_out = "$inalign" . "_optimized.out";
my $raxml_model = "PROTGAMMA" . "$model";
my $dirichlet = "9componentsDirichlet_" . "$model" . ".dat";
my $raxml_string = "-s $inalign -t $intree -n $raxml_out -m $raxml_model -u $dirichlet -f e";
print "Executing QmmRAxML with following command-line: $raxml_string\n";
callQmmRAxML($raxml_string);
}elsif($program eq 'iqtree'){
print "Optimizing branch lengths of user input tree using IQ-Tree\n";
my $iqtree_out = "$inalign" . ".treefile"; ####
my $iqtree_string = "-s $inalign -te $intree -m $model -nt $num_cpus -wsl";
calliqtree($iqtree_string);
}else{
print "Optimizing branch lengths of input user tree using RAxML\n";
my $raxml_out = "$inalign" . "_optimized.out";
my $raxml_model = "PROTGAMMA" . "$model" . "F";
my $raxml_string = "-s $inalign -t $intree -n $raxml_out -m $raxml_model -f e";
if($parallel){
$raxml_string = $raxml_string . " -T $num_cpus";
callParallelRAxML($raxml_string);
}else{
callRAxML($raxml_string);
}
}
print "Finished optimizing\n";
# Get the optimized likelihood value of the tree from the appropriate info file
# depending on ML program used
my $lh;
my $info_file;
if ($program eq 'iqtree'){
$info_file = "$inalign" . ".log"; ####
open(IN, "$info_file") or die "Could not open $info_file. Exiting...\n\n";
my @info = <IN>;
close(IN);
foreach(@info){
if($_ =~ /Optimal log-likelihood:/){
my @temp = split /: /, $_;
$lh = $temp[1];
$lh =~ s/[\r\n]+//g;
last();
}
}
}else{
$info_file = "RAxML_info." . "$inalign" . "_optimized.out";
open(IN, "$info_file") or die "Could not open $info_file . Exiting...\n\n";
my @info = <IN>;
close(IN);
foreach(@info){
if($_ =~ /Final GAMMA likelihood:/){
my @temp = split /: /, $_;
$lh = $temp[1];
$lh =~ s/[\r\n]+//g;
last();
}
}
}
if($lh eq ""){
print "WARNING: Could not locate likelihood value in $info_file . Exiting...\n\n";
exit();
}
$optimal_lh = $lh;
print "Finished Likelihood calculation: $optimal_lh\n";
# Renaming tree file
if($program eq 'iqtree'){
$intree = "$inalign" . ".treefile";
}else{
$intree = "$inalign" . "_optimized.tre";
}
# Reading optimized newick tree file and printing out to a new file name (treefile or optimized)
my $file;
if($program eq 'iqtree'){
$file = "$inalign" . ".treefile";
}else{
$file = "RAxML_result." . "$inalign" . "_optimized.out";
}
print "Reading input tree file $file\n";
open(IN, "$file") or die "Could not find $file . Exiting...\n";
my $sep = $/;
$/ = undef;
my $data = <IN>;
close(IN);
$/ = $sep;
print "Tree with branchlengths re-optimized by $program had lh of $lh...\n";
print LOG "Tree with branchlengths re-optimized by $program had lh of $lh...\n";
open(OUT, ">$intree") or die "could not create $intree!\n";
print OUT $data;
close(OUT);
# Code for handling some special cases of running in midroot mode (Not recommended)
# to re-roote the tree
if($midroot && $program ne 'puzzle'){
print "Checking to see if file outtree already exists...\n";
if(-f "outtree"){
print "File outtree already exists, moving...\n";
`mv outree old_outree.tre-bak`;
}
print "Creating Phylip Retree config file...\n";
open(CONFIG, ">retree.config") or die "Could not create retree.config!\n";
print CONFIG "y\n$intree\nm\nw\nr\nq\n";
close(CONFIG);
print "Passing $intree to retree to midroot tree...\n";
`$retree_command < retree.config`;
print "Renaming outtree to outtree_midroot.tre\n";
$intree = "outtree_midroot.tre";
`mv outtree $intree`;
}
print "Parsing $intree and $inalign to create subtree files...\n"; # $intree = "$inalign" . ".treefile"
my @files = treeParse($debug, $intree, $inalign, $outroot, $midroot, \@subtrees);
print "files" . @files . "\n"; ####
my @subfiles = @{$files[0]};
print @subfiles; ####
my @lcas = @{$files[1]};
print @lcas; ####
my $tree = $files[2];
print $tree; ####
print "\n=============================================\n\n";
my $test_file = runMixtureModel($inalign, \@subtrees, \@subfiles, \@lcas, $tree, $midroot, $program, $num_rates, $model, $parallel, $num_cpus, \@masked_sites, $branch_len_opt);
#my $command = "rm *_subtree*";
#system($command);
print "\nFinished running!\n";
close(LOG);
}
sub runMixtureModel{
my $startTime = time;
my ($alignment, $subref, $subfilesref, $lcas_ref, $tree, $midroot, $program, $num_rates, $model, $parallel, $num_cpus, $masked_ref, $branch_len_opt) = @_;###added $branch_len_opt
my @subtrees = @{$subref};
my @subfiles = @{$subfilesref};
my @old_lcas = @{$lcas_ref};
my @masked_sites = @{$masked_ref};
my $branchlength = 0;
print "Running Mixture Model\n";
# Using the LCA Node objects to read the input tree file and get the starting internal
# branch length between the subtrees
my $tree_file = $tree -> get_file();
my $new_tree = new PhyloTree_new(file => "$tree_file");
$new_tree -> read_tree();
my @nodes = $new_tree -> get_nodes();
my @ids;
foreach(@old_lcas){
my $id = $_ -> get_node_id();
push @ids, $id;
}
my @lcas;
foreach my $node (@nodes){
my $temp_id = $node -> get_node_id;
foreach my $id (@ids){
if($temp_id == $id){
if(! $node -> is_root()){
push @lcas, $node;
}
}
}
}
if($midroot){
print "Running in Midroot Mode...\n";
if(scalar(@lcas) != 2){
print "Running in midroot mode but there are " + scalar(@lcas) + " lcas\n";
exit();
}
}
print "Retrieving branch length information...\n";
if(scalar(@lcas) == 2 && $midroot){
foreach(@lcas){
my $temp_branch = $_ -> get_branchlength();
$branchlength = $branchlength + $temp_branch;
}
print "Internal branch length of midrooted tree is $branchlength\n";
print LOG "Internal branch length of midrooted tree is $branchlength\n";
}elsif(scalar(@lcas) == 1){
$branchlength = $lcas[0] -> get_branchlength();
print "Internal branch length is $branchlength\n";
print LOG "Internal branch length is $branchlength\n";
}else{
print "More than one LCA?\n";
print "Currently only support use of two clusters in midroot or unrooted mode\n";
exit();
}
print "\n=============================================\n\n";
# Subtree files should already be sorted but this guarantees that subgroups are together and that for each
# subgroup the alignment file comes first [i] and the treefile comes next [j]
my @sorted_out = sort @subfiles;
my @subtree_lh_fh;
print "Evaluating subtrees...(@sorted_out)\n";
# These don't appear to be used anywhere. Commenting out for now
# my @raxml_info_files;
# my @iqtree_info_files;
# Run ML program of choice on defined subtrees and place the resulting sitelh
# files into the subtree_lh_fh array
for(my $i = 0; $i < scalar(@sorted_out); $i = $i + 2){
my $lh_fh;
if($program eq 'qmmraxml'){
my $j = $i + 1;
print "Running QmmRAxML step for $sorted_out[$i] and $sorted_out[$j]\n";
my $raxml_out = "$sorted_out[$j]" . "_optimized.out";
# my $info = "RAxML_info." . "$raxml_out";
# push @raxml_info_files, $info;
my $raxml_model = "PROTGAMMA" . "$model";
my $dirichlet = "9componentsDirichlet_" . "$model" . ".dat";
$lh_fh = "$sorted_out[$j]" . ".sitelh";
my $raxml_string = "-s $sorted_out[$i] -t $sorted_out[$j] -n $raxml_out -m $raxml_model -u $dirichlet -L $lh_fh -f e";
callQmmRAxML($raxml_string);
}elsif($program eq 'iqtree'){
my $j = $i + 1;
print "Running IQ-Tree step for $sorted_out[$i] and $sorted_out[$j]\n";
my $iqtree_out = "$sorted_out[$i]" . ".treefile"; ####
$lh_fh = "$sorted_out[$i]" . ".sitelh";
#push @iqtree_info_files, $info;
my $iqtree_model = "$model";
my $iqtree_string = "-s $sorted_out[$i] -te $sorted_out[$j] -m $model -nt $num_cpus -wsl -fixbr";
calliqtree($iqtree_string);
}elsif($program eq 'raxml'){
my $j = $i + 1;
print "Running RAxML step for $sorted_out[$i] and $sorted_out[$j]\n"; # _subtree0.phy and _subtree0.tre
my $raxml_out = "$sorted_out[$j]" . "_optimized.out";
# my $info = "RAxML_info." . "$raxml_out";
# push @raxml_info_files, $info;
my $raxml_model = "PROTGAMMA" . "$model";
my $raxml_string = "-s $sorted_out[$i] -z $sorted_out[$j] -n $raxml_out -m $raxml_model -f g";
$lh_fh = "RAxML_perSiteLLs." . $raxml_out;
if($parallel){
$raxml_string = $raxml_string . " -T $num_cpus";
callParallelRAxML($raxml_string);
}else{
callRAxML($raxml_string);
}
}else{
print "Unknown phylogeny program. Exiting...\n\n";
exit();
}
print ("*******************************************\n");
push @subtree_lh_fh, $lh_fh;
}
# Calculate the constant value for the subtree site likelihoods
print "Calculating subtree site likelihoods (independence model)\n";
my @subtree_lhs;
my $last;
# Retrieving subtree site likelihoods and pushing into a 2D array
foreach(@subtree_lh_fh){
my @lhs ;
if($program eq 'puzzle'){
@lhs = getSiteLH($_);
}elsif($program eq 'qmmraxml'){
@lhs = getSiteCombLH($_);
}elsif($program eq 'iqtree'){
@lhs = getiqtreeSiteLH($_);
}else{
@lhs = getRAxMLSiteLH($_);
}
my $length = scalar(@lhs);
if($last){
if($length != $last){
print "Subtree likelihood files did not contain the same number of entries.\n";
print "Exiting...\n";
exit();
}
}
$last = $length;
push @subtree_lhs, [@lhs];
}
# Sum the likelihoods of the subtrees at each site
# Modified by kr to calculate site log-likelihoods for FD on May 13, 2016
# This modification prevents underflow issues with very small likelihoods
my @subtree_site_lnls;
# Loop through the 2D array, doing each subtree independently. The outer for Loop
# loops through the total number of sites which were counted previously into $last
for(my $i = 0; $i < $last; $i++){
my $total_lh = 0;
# This foreach loop loops over each subgroup/subtree
foreach(@subtree_lhs){
my @temp = @{$_}; # Temp holds the column
$total_lh = $total_lh + $temp[$i]; # Sum of the subtree likelihoods at the site
# print ("$total_lh\n");
}
push @subtree_site_lnls, $total_lh; # 1D array
}
print "\n=============================================\n\n";
# Coarse grain grid search optimization of internal branchlength and rho
print "Performing coarse grain optimization...\n";
my $p_lower = 0.00000000001;
my $p_upper = 1;
my $p_step = 0.01;
my $upper = $branchlength;
my $lower = 0.0;
my @branch_files;
my @add_tree_files;
if ($branch_len_opt eq 1){
@add_tree_files = create_new_tree_file($tree_file, $branchlength, $step);
} else {
$tree_file =~ s/[\r\n]+//g;
push @add_tree_files, $tree_file;
print "No internal optmization of internal branchlength. Evaluating site likelihoods...\n";
}
my $array_size = scalar(@add_tree_files);
print "\n $array_size \n";
foreach my $temp_tree_file(@add_tree_files){
# In the case of QmmRAxML insert the wholetree RAxML info file onto the first of the data files array to
# preserve the internal order. Wholetree followed by subtrees.
print "Using Tree File: $temp_tree_file\n";
if($program eq 'qmmraxml'){
print "Running QmmRAxML for $alignment and $temp_tree_file...\n";
my $raxml_out = "$temp_tree_file" . ".out";
#my $info = "RAxML_info." . "$raxml_out";
#unshift @raxml_info_files, $info;
my $raxml_model = "PROTGAMMA" . "$model";
my $site_file = "$temp_tree_file" . ".sitelh";
my $dirichlet = "9componentsDirichlet_" . "$model" . ".dat";
my $raxml_string = "-s $alignment -t $temp_tree_file -n $raxml_out -m $raxml_model -u $dirichlet -L $site_file -f e";
callQmmRAxML($raxml_string);
}elsif($program eq 'iqtree'){
print "Running IQ-Tree for $alignment and $temp_tree_file...\n";
my $iqtree_out = "$temp_tree_file" . ".treefile";
my $iqtree_model = "$model";
my $iqtree_string;
if ($branch_len_opt eq 1){
$iqtree_string = "-s $alignment -te $temp_tree_file -m $model -nt $num_cpus -wsl -fixbr";
} else {
$iqtree_string = "-s $alignment -te $temp_tree_file -m $model -nt $num_cpus -wsl";
}
# Rename the sitelh file to match up to assumptions later in the code
# which are based on the treefile name as opposed to the alignment name
# This is because of pre-existing code that was for dealing with the internal
# branchlength optimization code that previously existed
my $site_file = "$alignment" . ".sitelh";
my $lh_fh = "$temp_tree_file" . ".sitelh";
`cp $site_file $lh_fh`;
my $command = "rm *ckp.gz";
system($command);
calliqtree($iqtree_string); ####
}elsif($program eq 'raxml'){
print "Running RAxML for $alignment and $temp_tree_file...\n";
my $raxml_out = "$temp_tree_file" . ".out";
#my $info = "RAxML_info." . "$raxml_out";
#unshift @raxml_info_files, $info;
my $raxml_model = "PROTGAMMA" . "$model";
my $raxml_string = "-s $alignment -z $temp_tree_file -n $raxml_out -m $raxml_model -f g";
my $site_file = "RAxML_perSiteLLs." . "$raxml_out";
if($parallel){
$raxml_string = $raxml_string . " -T $num_cpus";
callParallelRAxML($raxml_string);
}else{
callRAxML($raxml_string);
}
# Rename the sitelh file to match up to assumptions later in the code
# which are based on the treefile name as opposed to the alignment name
# This is because of pre-existing code that was for dealing with the internal
# branchlength optimization code that previously existed
my $lh_fh = "$temp_tree_file" . ".sitelh";
`cp $site_file $lh_fh`;
}else{
print "Unknown phylogeny program. Exiting...\n\n";
exit();
}
# Branchfiles is an array, left over from dealing with optimizing the internal
# branch length between subgroups as well as the Rho parameter.
push @branch_files, $temp_tree_file;
}
my @values = optimizeRho("Rough", 0, 0.000000000001, $branch_files[1], \@branch_files, \@subtree_site_lnls, $p_lower, $p_upper, $p_step, $program);
print "\n=============================================\n\n";
#print @branch_files; # so far contains only one treefile, after adding bl optimization, should contain more than one treefile files. -added
#print @subtree_site_lnls; # contains site_likelihoods -the result of each site is the sum of the 2 subtrees
#print "\n=============================================\n\n";
# Fine scale optimization of branchlength and rho
my $rough_p = $values[0];
my $rough_b_fh = $values[1];
my $prior_max = $values[2];
my @fine_branch_files;
my $branch_upper;
my $branch_lower;
$tree_file =~ s/[\r\n]+//g;
push @fine_branch_files, $tree_file;
my $new_p_lower = $rough_p - (2 * $p_step);
my $new_p_upper = $rough_p + (2 * $p_step);
my $new_p_step = $p_step / 100;
if($new_p_upper > 1){
$new_p_upper = 1.0;
}
my @new_values = optimizeRho("Fine", $prior_max, $rough_p, $rough_b_fh, \@branch_files, \@subtree_site_lnls, $new_p_lower, $new_p_upper, $new_p_step, $program);
print "\n=============================================\n\n";
my @new_temp = split /-/, $new_values[1];
my $bfh = $new_temp[-1];
$bfh =~ s/[\n\r]+//g;
$bfh =~ s/\.sitelh//;
my @mm_site_loglhs = @{$new_values[3]};
# print "\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n\n";
# print @mm_site_loglhs;
# print "\n&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n\n";
# Class posteriors tree file order: Wholetree then subtrees
my @site_likelihoods;
my $rho = $new_values[0];
my @class_posteriors;
if($program eq 'puzzle'){
@site_likelihoods = getSiteLH($new_values[1]);
}elsif($program eq 'qmmraxml'){
@site_likelihoods = getSiteCombLH($new_values[1]);
@class_posteriors = getSiteClassPost($new_values[1], \@subtree_lh_fh, $NUM_CLASSES);
}elsif($program eq 'iqtree'){
@site_likelihoods = getiqtreeSiteLH($new_values[1]);
}else{
@site_likelihoods = getRAxMLSiteLH($new_values[1]);
}
# Calculate the posterior probability of functional divergence
open(POST, ">FunDi_Posterior_Scores." .$phy_file_name .".txt") or die "Could not create FunDi_Posterior_Scores.txt\n\n";
#print POST "Site\tP(FD)\tMixture Model Site Log-Likelihood\tMixture Model Likelihood\tSubtree Combined Likelihood\tSWeighted Subtree Likelihood\n";
print POST "Site\tPosterior Prob of FD\tMixture Model Site Log-Likelihood\tPosterior Prob Denominator\tSubtree Combined Log-Likelihood\n";
my $site = 0;
my @sites;
for(my $i = 0; $i < scalar(@site_likelihoods); $i++){
if(scalar(@masked_sites) > 0 && $site == $masked_sites[0]){
print POST "$site\tNONE\tNONE\n";
shift @masked_sites;
$site++;
$i--;
next();
}
my $lnjntnfd = log($rho) + $site_likelihoods[$i];
my $lnjntfd = log(1 - $rho) + $subtree_site_lnls[$i];
my @lnjnts = ($lnjntfd, $lnjntnfd);
my $lnnfd_denominator = max(@lnjnts) + log(1 + exp(min(@lnjnts) - max(@lnjnts)));
my $lnpost = log($rho) + $site_likelihoods[$i] - $lnnfd_denominator;
my $nfd_posterior = exp($lnpost);
my $posterior = 1 - $nfd_posterior;
print POST "$site\t$posterior\t$mm_site_loglhs[$i]\t$lnnfd_denominator\t$subtree_site_lnls[$i]\n";
if($posterior > 0.5){
push @sites, $posterior;
}
$site++;
}
close(POST);
my $fraction = scalar(@sites) / scalar(@site_likelihoods);
print "Iterated over $site sites\n";
print "Posterior probabilities written to Posteriors.txt\n";
print "Fraction of sites with posterior probability of functional divergence above 0.5 is: $fraction\n";
print LOG "Fraction of sites with posterior probability of functional divergence above 0.5 is: $fraction\n";
print "Rho (FD Weight): " . (1 - $rho) . "\n"; # Rho is actually the weight associated with Non FD in the code
my $endTime = time;
print $endTime - $startTime, " seconds to run " . "\n";
close(LOG);
my $test_file = "rho." . $phy_file_name . ".txt";
print $test_file;
open (TEST, ">$test_file") or die "file could not be opened";
print TEST "Fraction of sites with posterior probability of FD above 0.5: " . $fraction . "\n";
print TEST "Rho (FD weight): " . (1 - $rho) . "\n";
print TEST "Internal branch length: " . $branchlength ."\n";
print TEST "Optimal Log-Likelihood (IQ-Tree): " . $optimal_lh ."\n";
print TEST "Optimal Log-Likelihood (After Branch Length Optimization): " . $max_opt ."\n";
print TEST "Optimal Internal branch length: " . ($branch_opt) ."\n"; #####
close(TEST);
return $test_file;
}
# Optimization of the p parameter (mixture model weight) for each branchlength
sub optimizeRho{
my ($method, $prior_max, $opt_p, $opt_b, $branch_ref, $subtree_ref, $lower, $upper, $in_function_step, $program) = @_;
my @branch_files = @{$branch_ref};
#my @subtree_site_probs = @{$subtree_ref};
my @subtree_site_lnls = @{$subtree_ref};
my @values;
print "Optimizing rho parameter... $method\n";
my $max;
if($prior_max){
$max = $prior_max;
}
my @site_loglhs;
# Loop over all provided branch files (Leftover from branch length optimization)
foreach my $file_name (@branch_files){
$file_name = "$file_name" . ".sitelh";
print "Retrieving site likelihoods for $file_name...\n";
my @lhs;
if($program eq 'puzzle'){
@lhs = getSiteLH($file_name);
}
elsif($program eq 'qmmraxml'){
@lhs = getSiteCombLH($file_name);
}
elsif($program eq 'iqtree'){
#$file_name =~ s/treefile.//ig;
@lhs = getiqtreeSiteLH($file_name);
}
else{
@lhs = getRAxMLSiteLH($file_name);
}
# Calculation of mixture model equation with a given value of p
print ("Lower bound: $lower Upper Bound: $upper Step Size: $in_function_step\n");
for(my $p = $lower; $p <= $upper; $p = $p + $in_function_step){
if(scalar(@lhs) != scalar(@subtree_site_lnls)){
print "ERROR: During optimization of rho with value of $p arrays for probabilities of whole tree and subtrees not same length\n";
print "Exiting...\n";
exit();
}
my $total = 0;
my @temp_site_loglhs;
for(my $i = 0; $i < scalar(@lhs); $i++){
my $lnjntnfd = log($p) + $lhs[$i];
my $lnjntfd = log(1-$p) + $subtree_site_lnls[$i];
my @lnjnts = ($lnjntfd, $lnjntnfd);
my $lnprob = max(@lnjnts) + log(1 + exp(min(@lnjnts) - max(@lnjnts)));
push @temp_site_loglhs, $lnprob;
$total = $total + $lnprob;
}
my @temp = split /-/, $file_name;
my $branchlength = $temp[-1];
$branchlength =~ s/\.sitelh//;
if($max && $total > $max){
$opt_p = $p;
$opt_b = $file_name;
$max = $total;
@site_loglhs = @temp_site_loglhs; # temp_site_loglhs contains # of columns in the alignment
}
elsif($max && $total < $max){
next();
}
else{
$opt_p = $p;
$opt_b = $file_name;
$max = $total;
@site_loglhs = @temp_site_loglhs;
}
}
}
#print "Opt P: $opt_p Opt b: $opt_b Max: $max\n";
$max_opt = $max;
push @values, $opt_p;
push @values, $opt_b;
push @values, $max;
push @values, \@site_loglhs;
my @tab = split( /\./ ,$opt_b);
if (scalar(@tab) >4 ){
# $branch_opt = $tab[6].".".$tab[7];
# $branch_opt = $tab[3].".".$tab[4];
$branch_opt = $tab[3].".".$tab[4];
#Taking the branch_opt minus the last step as we always do a step forward
if ($branch_opt - $step > 0){
$branch_opt = $branch_opt - $step;
}
#print $branch_opt . "\n";
#print $max_opt . "\n";
}
print "Opt P: $opt_p branch_Opt: $branch_opt Max: $max\n";
#push @values, $branch_opt;
return @values;
}
sub getSubtreesFile{
my $file = shift;
open(IN, "$file") or die "Could not open $file\n";
my @subtrees;
my @temp;
while(<IN>){
if($_ !~ m/^#/ && $_ ne "\n"){
@temp = split;
foreach(@temp){
$_ =~ s/\n//g;
$_ =~ s/ //g;
}
push(@subtrees, [ @temp ]);
}
}
close(IN);
return @subtrees;
}
sub treeParse{
my ($debug, $intree, $align, $out_root, $midroot, $subtree_ref) = @_;
my @subtrees = @{$subtree_ref};
my @outfiles;
my @lcas;
print "creating phylotree using tree $intree\n";
my $tree = new PhyloTree_new(file => "$intree"); # $intree = "$inalign" . "_optimized" . ".treefile"
$tree -> read_tree();
my @taxa = $tree -> get_leaf_nodes();
print "Parsed tree with " . scalar(@taxa) . " leaf nodes\n";
print "entering loop ===================\n"; ####
my $done = 0;
my $count = 0;
my $num_of_times_i_ran = 0;
while(!$done){
for(my $i = 0; $i < scalar(@subtrees); $i++){
my @temp_subtree = @{$subtrees[$i]};
my @subtree_taxa;
#print "this is the value of temp_subtree:" . @temp_subtree . "\n"; ####
#print "this is the value of taxa:" . @taxa . "\n"; ####
foreach my $node (@temp_subtree){
print "this is the value of node:" . $node . "\n"; ####
foreach my $taxon (@taxa){
my $taxon_name = $taxon -> get_name();
if($taxon_name eq $node){
print "this is the value of taxon_name:" . $taxon_name . "\n"; ####
push @subtree_taxa, $taxon;
}
}
}
#print "finished that loop ====\n";####
my $subtree_out = "$out_root" . "$count" . ".tre";
my $lca = $tree -> get_lca(\@subtree_taxa);
#print "got lca" . $lca . "\n"; ####
my $subtree = create_subtree($lca, $subtree_out);
#print "got subtree" . $subtree . "\n";
my $ok = check_subtree($subtree, \@subtrees, $i);
print "checking if ok\n";
if($ok){
if(!$debug){
# The 1 indicates that this is a subtree, needed for print_tree
$subtree -> print_tree($subtree_out, 1);
}
print "Pushing lca to lcas \n";
push @lcas, $lca;
if($align){
my $subtree_align_out = "$out_root" . "$count" . ".phy";
push @outfiles, $subtree_align_out;
if(!$debug){
format_subtree_align($align, $subtree, $subtree_align_out);
}
}else{
die "Alignment file was not provided!\n";
}
push @outfiles, $subtree_out; # Pushes into an array and at the end creates subtreex.tre file
if(scalar(@subtrees) > 1){
if(!$midroot){
$tree -> prune($lca);
}
splice @subtrees, $i, 1;
$i--;
$count++;
}else{
$done = 1;
}
}
}
if(scalar(@subtrees) == 0){
$done = 1;
}
$num_of_times_i_ran++;
if ($num_of_times_i_ran > 5 ){
die "Cannot parse the subtrees, exiting...\n";
}
}
return (\@outfiles, \@lcas, $tree);
}
sub create_subtree{
my $lca = shift;
my $subtree_out = shift;
$lca -> set_root();
$lca -> clear_branchlength('');
my @subtree_nodes = $lca -> get_all_descendents();
unshift @subtree_nodes, $lca;
my $subtree = new PhyloTree_new(file => "$subtree_out");
$subtree -> set_nodes(\@subtree_nodes);
return $subtree;
}
sub check_subtree{
my ($subtree, $list_ref, $element) = @_;
my @subtree_list = @{$list_ref};
splice @subtree_list, $element, 1;
my @other_taxa;
foreach(@subtree_list){
my @temp = @{$_};
foreach my $taxa (@temp){
push @other_taxa, $taxa;
}
}
my $ok = 1;
my @subtree_taxa = $subtree -> get_leaf_nodes();
foreach(@subtree_taxa){
my $id = $_ -> get_name();
foreach my $name (@other_taxa){
if($name eq $id){
$ok = 0;
}
}
}
if($ok){
return 1;
}else{
return 0;
}
}
sub format_subtree_align{
my ($align, $subtree, $out) = @_;
open(ALIGN, "$align") or die "Could not read $align!\n";
my @align = <ALIGN>;
close(ALIGN);
open(OUT, ">$out") or die "Could not open $out for writing!\n";
my @taxa = $subtree -> get_leaf_nodes();
my @lines;
shift @align;
foreach my $line (@align){
my $name;
if($line =~ /\s/){
my @temp = split /\s+/, $line;
$name = $temp[0];
}else{
$name = substr($line, 0, 10);
}
$name =~ s/ //g;
foreach my $taxon (@taxa){
my $id = $taxon -> get_name();
if($name eq $id){
push @lines, $line;
}
}
}
my $num_taxa = scalar(@lines);
my $sequence = $lines[0];
$sequence =~ s/^(.+) +(.+)[\n\t]$/$2/;
$sequence =~ s/[\n\r]+//;
my $length = length $sequence;
print OUT " $num_taxa $length\n";
foreach(@lines){
print OUT $_;
}
close(OUT);
}
sub runMenuMode{
my $set = 0;
my $intree;
my $inalign;
my $outroot = "subtree";
my $subtree = "subtree.def";
my $parallel = 0;
my $mask_cut = 1.0;
my $program = "iqtree"; #qmmraxml
my $model = "LG+C20+F+G"; #LG
my $num_rates = 4;
my $help = 0;
my $verbose = 0;
my $midroot = 0;
my $Num_cpus = 1;
my $branch_len_opt = 1;
print "Now running in Menu Mode...\n";
print "\nPlease enter an alignment file: ";
$inalign = <STDIN>;
chomp $inalign;
print "\n";
my @trees0 = <RAxML_result.*>;
my @tree0 = <*.treefile>; ###
my @trees1 = <*.tre>;
# Not relevant
my @trees2 = <*.tree>;
my @trees3 = <RAxML_bipartitions.*>;
my @trees;
push @trees, @trees0;
push @trees, @trees1;
push @trees, @trees2;
push @trees, @trees3;
if(@trees){
for(my $i = 0; $i < scalar(@trees); $i++){
print "$i \t$trees[$i]\n";
}
print "\nThe following tree files were found. Press the corresponding number to select one or n for none:";
my $input = <STDIN>;
chomp $input;
if($input ne 'n' || $input ne 'N'){
$intree = $trees[$input];
}
}
do{
print "FILE OPTIONS\n";
print "t \tUser input tree: \t\t\t$intree\n";
print "a \tUser input alignment: \t\t\t$inalign\n";
print "c \tMask Alignment Column Gap Cut-off: \t$mask_cut\n";
print "s \tSubtree definition file: \t\t$subtree\n";
print "o \tSubtree outfile root name: \t\t$outroot\n\n";
print "GENERAL OPTIONS\n";
print "p \tParallel Mode: \t\t\t\t" , ($parallel ? "yes" : "no"), "\n";
if($parallel){
print "N \t Number of CPUs: \t\t\t\t $Num_cpus\n";
}
print "P \tPhylogenetic Program: \t\t\t$program\n";
print "m \tModel of Evolution: \t\t\t$model\n";
print "M \tMidroot Mode: \t\t\t\t" , ($midroot ? "yes" : "no") , "\n";
print "Quit [q], Help [h], Run [Y] or Selection (case-sensitive): ";
my $sel = <STDIN>;
chomp $sel;
if($sel eq 'q'){
exit();
}elsif($sel eq 'Y'){
$set = 1;
}elsif($sel eq 't'){
print "\nPlease enter a tree file: ";
$intree = <STDIN>;
chomp $intree;
print "\n";
}elsif($sel eq 'a'){
print "\nPlease enter an alignment file: ";
$inalign = <STDIN>;
chomp $inalign;
print "\n";
}elsif($sel eq 'c'){
print "Please enter new column gap score cut-off. 1 leaves alignment as is: ";
$mask_cut = <STDIN>;
chomp $mask_cut;
if($mask_cut == 1){
$mask_cut = 1.0;
}
if($mask_cut < 0.0 || $mask_cut > 1.0){
print "Cutoff must be expressed as a number betwen 0 and 1\n";
$mask_cut = 1.0;
}
print "\n";
}elsif($sel eq 's'){
print "\nPlease enter subtree definition file: ";
$subtree = <STDIN>;
chomp $subtree;
print "\n";
}elsif($sel eq 'o'){
print "\nPlease subtree outfile root name: ";
$outroot = <STDIN>;
chomp $outroot;
print "\n";
}elsif($sel eq 'p'){
print "Would you like to run in parallel mode (y/n)? ";
my $choice = <STDIN>;
chomp $choice;
if($choice eq 'y'){
$parallel = 1;
}elsif($choice eq 'n'){
$parallel = 0;
}else{
print "$choice is not a valid selection, keeping previous\n";
}
}elsif($sel eq 'O'){
print "Would you like to perform Branch Length Optimization (y/n)? ";
my $choice = <STDIN>;
chomp $choice;
if($choice eq 'y'){
$branch_len_opt = 'true';
}elsif($choice eq 'n'){
$branch_len_opt = 'false';
}else{
print "$choice is not a valid selection, keeping previous\n";
}
}elsif($sel eq 'N'){
print "Enter number of processors to use: ";
my $choice = <STDIN>;
chomp $choice;
$Num_cpus = $choice;
print "\n";
}elsif($sel eq 'P'){
print "Please choose program (raxml/qmmraxml/iqtree): ";
my $choice = <STDIN>;
chomp($choice);
$choice = lc $choice;
if($choice ne 'qmmraxml' && $choice ne 'raxml' && $choice ne 'iqtree'){
print "Choice invalid. Leaving as default...\n";
}else{
$program = $choice;
if($program eq 'qmmraxml'){
print "Setting number of gamme rates to 4\n";
$num_rates = 4;
}elsif($program eq 'iqtree'){ ##########
print "Setting relevant model\n";
$model = 'LG+C20+F+G';
}else{
if($model eq 'LG'){
print "LG model of amino acid substitution only available with qmmraxml. Switching to JTT\n"; ####fix
$model = 'JTT';
}
}
}
}elsif($sel eq 'M'){
print "Would you like to run in midpoint rooted mode (y/n)? ";
my $choice = <STDIN>;
chomp $choice;
if($choice eq 'y'){
$midroot = 1;
}elsif($choice eq 'n'){
$midroot = 0;
}else{
print "$choice is not a valid selection, keeping previous\n";
}
}elsif($sel eq 'h'){
printHelp();
print "Press any key to continue: ";
my $key = <STDIN>;
}elsif($sel eq 'r'){
if($program eq 'qmmraxml'){
print "Cannot change number of rate categories from 4 when using qmmraxml.\n";
}else{
print "Enter number of rate categories: \n";
my $choice = <STDIN>;
chomp $choice;
if($choice !~ /[0-9]+/){
print "Invalid rate choice. Must enter a positive integer.\n";
}elsif($choice == 0){
print "Invalid rate choice. Must enter a positive integer.\n";
}else{
$num_rates = $choice;
}
}
}elsif($sel eq 'm'){
print "Model of protein sequence evolution JTT/WAG/LG/LG+C20+F+G: ";
my $choice = <STDIN>;
chomp $choice;
$choice = uc $choice;
if($choice ne 'JTT' && $choice ne 'WAG' && $choice ne 'LG' && $choice ne 'LG+C20+F+G'){ #####
print "Invalid selection. Keeping previous choice\n";
}elsif($choice eq 'LG' && $program eq 'puzzle'){
print "LG model of sequence evolution is only usable with qmmraxml. Keeping previous\n";
}else{
$model = $choice;
}
}else{
print "I'm sorry but $sel is not a valid selection, please try again\n\n";
}
}while(!$set);
my $command = "-a $inalign -o $outroot -m $model -s $subtree -P $program -r $num_rates ";
if($intree){
$command = $command . "-t $intree ";
}
if($midroot){
$command = $command . "-M ";
}
if($verbose){
$command = $command . "-v ";
}
if($mask_cut < 1.0){
$command = $command . "-c $mask_cut ";
}
if($parallel){
$command = $command . "-p -N $Num_cpus "
}
if($branch_len_opt){
$command = $command . "-O ";
}
open("LOG", ">>FunDi.log") or die "Could not open FunDi.log...\n\n";
print "Running FunDi with specified options $command\n";
print LOG "Running FunDi with specified options $command\n";
close(LOG);
@_ = split / /, $command;
runCLIMode(@_);
}
sub printHelp{
print <<HELP;
Usage (Command Line Mode): perl FunDi.pl [options] -t intree -a inalignment
Usage (Phylip Style Menu Mode): perl FunDi.pl
Options:
-h Help: Print this Help message and exit
-o Output root: Sets the root filename for subtree files. Default: subtree
-n Normalization: Defines the normalization method for site rate comparisons.
Default: Simple division by sum
Other options:
-sum_divide: Divide by sum of rates
-log_ratio: Ratio of logs of rates
-mean_divide: Divide by mean of rates
-v Verbose: Run in verbose mode (Not yet Implemented. Always verbose)
-p Parallel: Use Parallel Version of RAxML
-s Subtree: Name of subtree definition file (Default: subtree.def)
-M Midpoint: Run in midpoint mode rooted mode. (Default: unrooted tree)
-l Length: Set length of simulated sequences (Only in non mixture mode. Default: 1000)
-x Mixture Model: Run mixture model mode (Default)
-m Model: Model of sequence evolution (JTT, WAG, LG, LG+C20+F+G) LG in QMMRAxML only (Default: LG+C20+F+G)
-O Optimization: Run internal branchlength optimization? (yes/no). (Available in PUZZLE and IQ-Tree only)
-r Gamma rates: Number of gamma rates. Selectable in PUZZLE only. (QmmRAxML always 4)
-P Program: Phylogenetic program (puzzle/qmmraxml). QmmRAxML contains class frequency models (Default: qmmraxml)
HELP
}
sub create_new_tree_file{
my ($tree_file, $branch_len, $step) = @_;
#my $count;
my @list_of_new_trees;
if ($branch_len){
my $branch_len_num_of_digits = length($branch_len);
my $temp_branch_length = $branch_len - 1 > rem($branch_len,$step) ? $branch_len - 1 : rem($branch_len,$step);
while ($temp_branch_length <= $branch_len + 1.001){
if (length($temp_branch_length) > $branch_len_num_of_digits){
$temp_branch_length = substr($temp_branch_length, 0, $branch_len_num_of_digits);
}
# Creating a class variable of PhyloTree_new from $tree_file
my $new_tree = new PhyloTree_new(file => $tree_file);
$new_tree -> read_tree();
my @nodes = $new_tree -> get_nodes();
my $replaced='false';
# Searching for the node that holds the branch length and then replacing it with the modified branchlength
foreach(@nodes){
my $bl = $_ -> get_branchlength();
if ($bl == $branch_len){
$_ -> set_branchlength($temp_branch_length);
$replaced='true';
}
}
if ($replaced eq 'true'){
print "Successfully replaced old branch length $branch_len with $temp_branch_length in $tree_file \n";
my $subtree_out = "$tree_file" . "." . "$temp_branch_length" . ".nw";
$new_tree -> print_tree($subtree_out, 0);
push @list_of_new_trees, $subtree_out;
$temp_branch_length = $temp_branch_length + $step;
}
else {
die "Failed to replace branch length $branch_len in file $tree_file";
}
}
} else {
die "No branch length given";
}
return @list_of_new_trees;
}
sub rem { $_[1]*frac($_[0]/$_[1]) }
sub frac { $_[0]-int($_[0]) } | GastonLab/fundi-dev | FunDi.pl | Perl | mit | 45,279 |
package Date::Manip::TZdata;
# Copyright (c) 2008-2015 Sullivan Beck. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the same terms as Perl itself.
###############################################################################
require 5.010000;
use IO::File;
use Date::Manip::Base;
use strict;
use integer;
use warnings;
our $VERSION;
$VERSION='6.52';
END { undef $VERSION; }
###############################################################################
# GLOBAL VARIABLES
###############################################################################
our ($Verbose,@StdFiles,$dmb);
END {
undef $Verbose;
undef @StdFiles;
undef $dmb;
}
$dmb = new Date::Manip::Base;
# Whether to print some debugging stuff.
$Verbose = 0;
# Standard tzdata files that need to be parsed.
@StdFiles = qw(africa
antarctica
asia
australasia
europe
northamerica
pacificnew
southamerica
etcetera
backward
);
our ($TZ_DOM,$TZ_LAST,$TZ_GE,$TZ_LE);
END {
undef $TZ_DOM;
undef $TZ_LAST;
undef $TZ_GE;
undef $TZ_LE;
}
$TZ_DOM = 1;
$TZ_LAST = 2;
$TZ_GE = 3;
$TZ_LE = 4;
our ($TZ_STANDARD,$TZ_RULE,$TZ_OFFSET);
END {
undef $TZ_STANDARD;
undef $TZ_RULE;
undef $TZ_OFFSET;
}
$TZ_STANDARD = 1;
$TZ_RULE = 2;
$TZ_OFFSET = 3;
###############################################################################
# BASE METHODS
###############################################################################
#
# The Date::Manip::TZdata object is a hash of the form:
#
# { dir => DIR where to find the tzdata directory
# zone => { ZONE => [ ZONEDESC ] }
# ruleinfo => { INFO => [ VAL ... ] }
# zoneinfo => { INFO => [ VAL ... ] }
# zonelines => { ZONE => [ VAL ... ] }
# }
sub new {
my($class,$dir) = @_;
$dir = '.' if (! $dir);
if (! -d "$dir/tzdata") {
die "ERROR: no tzdata directory found\n";
}
my $self = {
'dir' => $dir,
'zone' => {},
'ruleinfo' => {},
'zoneinfo' => {},
'zonelines' => {},
};
bless $self, $class;
$self->_tzd_ParseFiles();
return $self;
}
###############################################################################
# RULEINFO
###############################################################################
my($Error);
# @info = $tzd->ruleinfo($rule,@args);
#
# This takes the name of a set of rules (e.g. NYC or US as defined in
# the zoneinfo database) and returns information based on the arguments
# given.
#
# @args
# ------------
#
# rules YEAR : Return a list of all rules used during that year
# stdlett YEAR : The letter(s) used during standard time that year
# savlett YEAR : The letter(s) used during saving time that year
# lastoff YEAR : Returns the last DST offset of the year
# rdates YEAR : Returns a list of critical dates for the given
# rule during a year. It returns:
# (date dst_offset timetype lett ...)
# where dst_offset is the daylight saving time offset
# that starts at that date and timetype is 'u', 'w', or
# 's', and lett is the letter to use in the abbrev.
#
sub _ruleInfo {
my($self,$rule,$info,@args) = @_;
my $year = shift(@args);
if (exists $$self{'ruleinfo'}{$info} &&
exists $$self{'ruleinfo'}{$info}{$rule} &&
exists $$self{'ruleinfo'}{$info}{$rule}{$year}) {
if (ref $$self{'ruleinfo'}{$info}{$rule}{$year}) {
return @{ $$self{'ruleinfo'}{$info}{$rule}{$year} };
} else {
return $$self{'ruleinfo'}{$info}{$rule}{$year};
}
}
if ($info eq 'rules') {
my @ret;
foreach my $r ($self->_tzd_Rule($rule)) {
my($y0,$y1,$ytype,$mon,$flag,$dow,$num,$timetype,$time,$offset,
$lett) = @$r;
next if ($y0>$year || $y1<$year);
push(@ret,$r) if ($ytype eq "-" ||
$year == 9999 ||
($ytype eq 'even' && $year =~ /[02468]$/) ||
($ytype eq 'odd' && $year =~ /[13579]$/));
}
# We'll sort them... if there are ever two time changes in a
# single month, this will cause problems... hopefully there
# never will be.
@ret = sort { $$a[3] <=> $$b[3] } @ret;
$$self{'ruleinfo'}{$info}{$rule}{$year} = [ @ret ];
return @ret;
} elsif ($info eq 'stdlett' ||
$info eq 'savlett') {
my @rules = $self->_ruleInfo($rule,'rules',$year);
my %lett = ();
foreach my $r (@rules) {
my($y0,$y1,$ytype,$mon,$flag,$dow,$num,$timetype,$time,$offset,
$lett) = @$r;
$lett{$lett} = 1
if ( ($info eq 'stdlett' && $offset eq '00:00:00') ||
($info eq 'savlett' && $offset ne '00:00:00') );
}
my $ret;
if (! %lett) {
$ret = '';
} else {
$ret = join(",",sort keys %lett);
}
$$self{'ruleinfo'}{$info}{$rule}{$year} = $ret;
return $ret;
} elsif ($info eq 'lastoff') {
my $ret;
my @rules = $self->_ruleInfo($rule,'rules',$year);
return '00:00:00' if (! @rules);
my $r = pop(@rules);
my($y0,$y1,$ytype,$mon,$flag,$dow,$num,$timetype,$time,$offset,
$lett) = @$r;
$$self{'ruleinfo'}{$info}{$rule}{$year} = $offset;
return $offset;
} elsif ($info eq 'rdates') {
my @ret;
my @rules = $self->_ruleInfo($rule,'rules',$year);
foreach my $r (@rules) {
my($y0,$y1,$ytype,$mon,$flag,$dow,$num,$timetype,$time,$offset,
$lett) = @$r;
my($date) = $self->_tzd_ParseRuleDate($year,$mon,$dow,$num,$flag,$time);
push(@ret,$date,$offset,$timetype,$lett);
}
$$self{'ruleinfo'}{$info}{$rule}{$year} = [ @ret ];
return @ret;
}
}
###############################################################################
# ZONEINFO
###############################################################################
# zonelines is:
# ( ZONE => numlines => N,
# I => { start => DATE,
# end => DATE,
# stdoff => OFFSET,
# dstbeg => OFFSET,
# dstend => OFFSET,
# letbeg => LETTER,
# letend => LETTER,
# abbrev => ABBREV,
# rule => RULE
# }
# )
# where I = 1..N
# start, end the wallclock start/end time of this period
# stdoff the standard GMT offset during this period
# dstbeg the DST offset at the start of this period
# dstend the DST offset at the end of this period
# letbeg the letter (if any) used at the start of this period
# letend the letter (if any) used at the end of this period
# abbrev the zone abbreviation during this period
# rule the rule that applies (if any) during this period
# @info = $tzd->zoneinfo($zone,@args);
#
# Obtain information from a zone
#
# @args
# ------------
#
# zonelines Y : Return the full zone line(s) which apply for
# a given year.
# rules YEAR : Returns a list of rule names and types which
# apply for the given year.
#
sub _zoneInfo {
my($self,$zone,$info,@args) = @_;
if (! exists $$self{'zonelines'}{$zone}) {
$self->_tzd_ZoneLines($zone);
}
my @z = $self->_tzd_Zone($zone);
shift(@z); # Get rid of timezone name
my $ret;
# if ($info eq 'numzonelines') {
# return $$self{'zonelines'}{$zone}{'numlines'};
# } elsif ($info eq 'zoneline') {
# my ($i) = @args;
# my @ret = map { $$self{'zonelines'}{$zone}{$i}{$_} }
# qw(start end stdoff dstbeg dstend letbeg letend abbrev rule);
# return @ret;
# }
my $y = shift(@args);
if (exists $$self{'zoneinfo'}{$info} &&
exists $$self{'zoneinfo'}{$info}{$zone} &&
exists $$self{'zoneinfo'}{$info}{$zone}{$y}) {
if (ref($$self{'zoneinfo'}{$info}{$zone}{$y})) {
return @{ $$self{'zoneinfo'}{$info}{$zone}{$y} };
} else {
return $$self{'zoneinfo'}{$info}{$zone}{$y};
}
}
if ($info eq 'zonelines') {
my (@ret);
while (@z) {
# y = 1920
# until = 1919 NO
# until = 1920 NO
# until = 1920 Feb... YES
# until = 1921... YES, last
my $z = shift(@z);
my($offset,$ruletype,$rule,$abbrev,$yr,$mon,$dow,$num,$flag,$time,
$timetype,$start,$end) = @$z;
next if ($yr < $y);
next if ($yr == $y && $flag == $TZ_DOM &&
$mon == 1 && $num == 1 && $time eq '00:00:00');
push(@ret,$z);
last if ($yr > $y);
}
$$self{'zoneinfo'}{$info}{$zone}{$y} = [ @ret ];
return @ret;
} elsif ($info eq 'rules') {
my (@ret);
@z = $self->_zoneInfo($zone,'zonelines',$y);
foreach my $z (@z) {
my($offset,$ruletype,$rule,$abbrev,$yr,$mon,$dow,$num,$flag,$time,
$timetype,$start,$end) = @$z;
push(@ret,$rule,$ruletype);
}
$$self{'zoneinfo'}{$info}{$zone}{$y} = [ @ret ];
return @ret;
}
}
########################################################################
# PARSING TZDATA FILES
########################################################################
# These routine parses the raw tzdata file. Files contain three types
# of lines:
#
# Link CANONICAL ALIAS
# Rule NAME FROM TO TYPE IN ON AT SAVE LETTERS
# Zone NAME GMTOFF RULE FORMAT UNTIL
# GMTOFF RULE FORMAT UNTIL
# ...
# GMTOFF RULE FORMAT
# Parse all files
sub _tzd_ParseFiles {
my($self) = @_;
print "PARSING FILES...\n" if ($Verbose);
foreach my $file (@StdFiles) {
$self->_tzd_ParseFile($file);
}
$self->_tzd_CheckData();
}
# Parse a file
sub _tzd_ParseFile {
my($self,$file) = @_;
my $in = new IO::File;
my $dir = $$self{'dir'};
print "... $file\n" if ($Verbose);
if (! $in->open("$dir/tzdata/$file")) {
warn "WARNING: [parse_file] unable to open file: $file: $!\n";
return;
}
my @in = <$in>;
$in->close;
chomp(@in);
# strip out comments
foreach my $line (@in) {
$line =~ s/^\s+//;
$line =~ s/#.*$//;
$line =~ s/\s+$//;
}
# parse all lines
my $n = 0; # line number
my $zone = ''; # current zone (if in a multi-line zone section)
while (@in) {
if (! $in[0]) {
$n++;
shift(@in);
} elsif ($in[0] =~ /^Zone/) {
$self->_tzd_ParseZone($file,\$n,\@in);
} elsif ($in[0] =~ /^Link/) {
$self->_tzd_ParseLink($file,\$n,\@in);
} elsif ($in[0] =~ /^Rule/) {
$self->_tzd_ParseRule($file,\$n,\@in);
} else {
$n++;
my $line = shift(@in);
warn "WARNING: [parse_file] unknown line: $n\n" .
" $line\n";
}
}
}
sub _tzd_ParseLink {
my($self,$file,$n,$lines) = @_;
$$n++;
my $line = shift(@$lines);
my(@tmp) = split(/\s+/,$line);
if ($#tmp != 2 || lc($tmp[0]) ne 'link') {
warn "ERROR: [parse_file] invalid Link line: $file: $$n\n" .
" $line\n";
return;
}
my($tmp,$zone,$alias) = @tmp;
if ($self->_tzd_Alias($alias)) {
warn "WARNING: [parse_file] alias redefined: $file: $$n: $alias\n";
}
$self->_tzd_Alias($alias,$zone);
}
sub _tzd_ParseRule {
my($self,$file,$n,$lines) = @_;
$$n++;
my $line = shift(@$lines);
my(@tmp) = split(/\s+/,$line);
if ($#tmp != 9 || lc($tmp[0]) ne 'rule') {
warn "ERROR: [parse_file] invalid Rule line: $file: $$n:\n" .
" $line\n";
return;
}
my($tmp,$name,$from,$to,$type,$in,$on,$at,$save,$letters) = @tmp;
$self->_tzd_Rule($name,[ $from,$to,$type,$in,$on,$at,$save,$letters ]);
}
sub _tzd_ParseZone {
my($self,$file,$n,$lines) = @_;
# Remove "Zone America/New_York" from the first line
$$n++;
my $line = shift(@$lines);
my @tmp = split(/\s+/,$line);
if ($#tmp < 4 || lc($tmp[0]) ne 'zone') {
warn "ERROR: [parse_file] invalid Zone line: $file :$$n\n" .
" $line\n";
return;
}
shift(@tmp);
my $zone = shift(@tmp);
$line = join(' ',@tmp);
unshift(@$lines,$line);
# Store the zone name information
if ($self->_tzd_Zone($zone)) {
warn "ERROR: [parse_file] zone redefined: $file: $$n: $zone\n";
$self->_tzd_DeleteZone($zone);
}
$self->_tzd_Alias($zone,$zone);
# Parse all zone lines
while (1) {
last if (! @$lines);
$line = $$lines[0];
return if ($line =~ /^(zone|link|rule)/i);
$$n++;
shift(@$lines);
next if (! $line);
@tmp = split(/\s+/,$line);
if ($#tmp < 2) {
warn "ERROR: [parse_file] invalid Zone line: $file: $$n\n" .
" $line\n";
return;
}
my($gmt,$rule,$format,@until) = @tmp;
$self->_tzd_Zone($zone,[ $gmt,$rule,$format,@until ]);
}
}
sub _tzd_CheckData {
my($self) = @_;
print "CHECKING DATA...\n" if ($Verbose);
$self->_tzd_CheckRules();
$self->_tzd_CheckZones();
$self->_tzd_CheckAliases();
}
########################################################################
# LINKS (ALIASES)
########################################################################
sub _tzd_Alias {
my($self,$alias,$zone) = @_;
if (defined $zone) {
$$self{'alias'}{$alias} = $zone;
return;
} elsif (exists $$self{'alias'}{$alias}) {
return $$self{'alias'}{$alias};
} else {
return '';
}
}
sub _tzd_DeleteAlias {
my($self,$alias) = @_;
delete $$self{'alias'}{$alias};
}
sub _tzd_AliasKeys {
my($self) = @_;
return keys %{ $$self{'alias'} };
}
# TZdata file:
#
# Link America/Denver America/Shiprock
#
# Stored locally as:
#
# (
# "us/eastern" => "America/New_York"
# "america/new_york" => "America/New_York"
# )
sub _tzd_CheckAliases {
my($self) = @_;
# Replace
# ALIAS1 -> ALIAS2 -> ... -> ZONE
# with
# ALIAS1 -> ZONE
print "... aliases\n" if ($Verbose);
ALIAS:
foreach my $alias ($self->_tzd_AliasKeys()) {
my $zone = $self->_tzd_Alias($alias);
my %tmp;
$tmp{$alias} = 1;
while (1) {
if ($self->_tzd_Zone($zone)) {
$self->_tzd_Alias($alias,$zone);
next ALIAS;
} elsif (exists $tmp{$zone}) {
warn "ERROR: [check_aliases] circular alias definition: $alias\n";
$self->_tzd_DeleteAlias($alias);
next ALIAS;
} elsif ($self->_tzd_Alias($zone)) {
$tmp{$zone} = 1;
$zone = $self->_tzd_Alias($zone);
next;
}
warn "ERROR: [check_aliases] unresolved alias definition: $alias\n";
$self->_tzd_DeleteAlias($alias);
next ALIAS;
}
}
}
########################################################################
# PARSING RULES
########################################################################
sub _tzd_Rule {
my($self,$rule,$listref) = @_;
if (defined $listref) {
if (! exists $$self{'rule'}{$rule}) {
$$self{'rule'}{$rule} = [];
}
push @{ $$self{'rule'}{$rule} }, [ @$listref ];
} elsif (exists $$self{'rule'}{$rule}) {
return @{ $$self{'rule'}{$rule} };
} else {
return ();
}
}
sub _tzd_DeleteRule {
my($self,$rule) = @_;
delete $$self{'rule'}{$rule};
}
sub _tzd_RuleNames {
my($self) = @_;
return keys %{ $$self{'rule'} };
}
sub _tzd_CheckRules {
my($self) = @_;
print "... rules\n" if ($Verbose);
foreach my $rule ($self->_tzd_RuleNames()) {
$Error = 0;
my @rule = $self->_tzd_Rule($rule);
$self->_tzd_DeleteRule($rule);
while (@rule) {
my($from,$to,$type,$in,$on,$at,$save,$letters) =
@{ shift(@rule) };
my($dow,$num,$attype);
$from = $self->_rule_From ($rule,$from);
$to = $self->_rule_To ($rule,$to,$from);
$type = $self->_rule_Type ($rule,$type);
$in = $self->_rule_In ($rule,$in);
($on,$dow,$num) = $self->_rule_On ($rule,$on);
($attype,$at) = $self->_rule_At ($rule,$at);
$save = $self->_rule_Save ($rule,$save);
$letters = $self->_rule_Letters($rule,$letters);
if (! $Error) {
$self->_tzd_Rule($rule,[ $from,$to,$type,$in,$on,$dow,$num,$attype,
$at,$save,$letters ]);
}
}
$self->_tzd_DeleteRule($rule) if ($Error);
}
}
# TZdata file:
#
# #Rule NAME FROM TO TYPE IN ON AT SAVE LETTER
# Rule NYC 1920 only - Mar lastSun 2:00 1:00 D
# Rule NYC 1920 only - Oct lastSun 2:00 0 S
# Rule NYC 1921 1966 - Apr lastSun 2:00 1:00 D
# Rule NYC 1921 1954 - Sep lastSun 2:00 0 S
# Rule NYC 1955 1966 - Oct lastSun 2:00 0 S
#
# Stored locally as:
#
# %Rule = (
# 'NYC' =>
# [
# [ 1920 1920 - 3 2 7 0 w 02:00:00 01:00:00 D ],
# [ 1920 1920 - 10 2 7 0 w 02:00:00 00:00:00 S ],
# [ 1921 1966 - 4 2 7 0 w 02:00:00 01:00:00 D ],
# [ 1921 1954 - 9 2 7 0 w 02:00:00 00:00:00 S ],
# [ 1955 1966 - 10 2 7 0 w 02:00:00 00:00:00 S ],
# ],
# 'US' =>
# [
# [ 1918 1919 - 3 2 7 0 w 02:00:00 01:00:00 W ],
# [ 1918 1919 - 10 2 7 0 w 02:00:00 00:00:00 S ],
# [ 1942 1942 - 2 1 0 9 w 02:00:00 01:00:00 W ],
# [ 1945 1945 - 9 1 0 30 w 02:00:00 00:00:00 S ],
# [ 1967 9999 - 10 2 7 0 u 02:00:00 00:00:00 S ],
# [ 1967 1973 - 4 2 7 0 w 02:00:00 01:00:00 D ],
# [ 1974 1974 - 1 1 0 6 w 02:00:00 01:00:00 D ],
# [ 1975 1975 - 2 1 0 23 w 02:00:00 01:00:00 D ],
# [ 1976 1986 - 4 2 7 0 w 02:00:00 01:00:00 D ],
# [ 1987 9999 - 4 3 7 1 u 02:00:00 01:00:00 D ],
# ]
# )
#
# Each %Rule list consists of:
# Y0 Y1 YTYPE MON FLAG DOW NUM TIMETYPE TIME OFFSET LETTER
# where
# Y0, Y1 : the year range for which this rule line might apply
# YTYPE : type of year where the rule does apply
# even : only applies to even numbered years
# odd : only applies to odd numbered years
# - : applies to all years in the range
# MON : the month where a change occurs
# FLAG/DOW/NUM : specifies the day a time change occurs (interpreted
# the same way the as in the zone description below)
# TIMETYPE : the type of time that TIME is
# w : wallclock time
# u : univeral time
# s : standard time
# TIME : HH:MM:SS where the time change occurs
# OFFSET : the offset (which is added to standard time offset)
# starting at that time
# LETTER : letters that are substituted for %s in abbreviations
# Parses a day-of-month which can be given as a # (1-31), lastSun, or
# Sun>=13 or Sun<=24 format.
sub _rule_DOM {
my($self,$dom) = @_;
my %days = qw(mon 1 tue 2 wed 3 thu 4 fri 5 sat 6 sun 7);
my($dow,$num,$flag,$err) = (0,0,0,0);
my($i);
if ($dom =~ /^(\d\d?)$/) {
($dow,$num,$flag)=(0,$1,$TZ_DOM);
} elsif ($dom =~ /^last(.+)$/) {
($dow,$num,$flag)=($1,0,$TZ_LAST);
} elsif ($dom =~ /^(.+)>=(\d\d?)$/) {
($dow,$num,$flag)=($1,$2,$TZ_GE);
} elsif ($dom =~ /^(.+)<=(\d\d?)$/) {
($dow,$num,$flag)=($1,$2,$TZ_LE);
} else {
$err = 1;
}
if ($dow) {
if (exists $days{ lc($dow) }) {
$dow = $days{ lc($dow) };
} else {
$err = 1;
}
}
$err = 1 if ($num>31);
return ($dow,$num,$flag,$err);
}
# Parses a month from a string
sub _rule_Month {
my($self,$mmm) = @_;
my %months = qw(jan 1 feb 2 mar 3 apr 4 may 5 jun 6
jul 7 aug 8 sep 9 oct 10 nov 11 dec 12);
if (exists $months{ lc($mmm) }) {
return $months{ lc($mmm) };
} else {
return 0;
}
}
# Returns a time. The time (HH:MM:SS) which may optionally be signed (if $sign
# is 1), and may optionally (if $type is 1) be followed by a type
# ('w', 'u', or 's').
sub _rule_Time {
my($self,$time,$sign,$type) = @_;
my($s,$t);
if ($type) {
$t = 'w';
if ($type && $time =~ s/(w|u|s)$//i) {
$t = lc($1);
}
}
if ($sign) {
if ($time =~ s/^-//) {
$s = "-";
} else {
$s = '';
$time =~ s/^\+//;
}
} else {
$s = '';
}
return '' if ($time !~ /^(\d\d?)(?::(\d\d))?(?::(\d\d))?$/);
my($hr,$mn,$se)=($1,$2,$3);
$hr = '00' if (! $hr);
$mn = '00' if (! $mn);
$se = '00' if (! $se);
$hr = "0$hr" if (length($hr)<2);
$mn = "0$mn" if (length($mn)<2);
$se = "0$se" if (length($se)<2);
$time = "$s$hr:$mn:$se";
if ($type) {
return ($time,$t);
} else {
return $time;
}
}
# a year or 'minimum'
sub _rule_From {
my($self,$rule,$from) = @_;
$from = lc($from);
if ($from =~ /^\d\d\d\d$/) {
return $from;
} elsif ($from eq 'minimum' || $from eq 'min') {
return '0001';
}
warn "ERROR: [rule_from] invalid: $rule: $from\n";
$Error = 1;
return '';
}
# a year, 'maximum', or 'only'
sub _rule_To {
my($self,$rule,$to,$from) = @_;
$to = lc($to);
if ($to =~ /^\d\d\d\d$/) {
return $to;
} elsif ($to eq 'maximum' || $to eq 'max') {
return '9999';
} elsif (lc($to) eq 'only') {
return $from;
}
warn "ERROR: [rule_to] invalid: $rule: $to\n";
$Error = 1;
return '';
}
# "-", 'even', or 'odd'
sub _rule_Type {
my($self,$rule,$type) = @_;
return lc($type) if (lc($type) eq "-" ||
lc($type) eq 'even' ||
lc($type) eq 'odd');
warn "ERROR: [rule_type] invalid: $rule: $type\n";
$Error = 1;
return '';
}
# a month
sub _rule_In {
my($self,$rule,$in) = @_;
my($i) = $self->_rule_Month($in);
if (! $i) {
warn "ERROR: [rule_in] invalid: $rule: $in\n";
$Error = 1;
}
return $i;
}
# DoM (1-31), lastDow (lastSun), DoW<=number (Mon<=12),
# DoW>=number (Sat>=14)
#
# Returns: (flag,dow,num)
sub _rule_On {
my($self,$rule,$on) = @_;
my($dow,$num,$flag,$err) = $self->_rule_DOM($on);
if ($err) {
warn "ERROR: [rule_on] invalid: $rule: $on\n";
$Error = 1;
}
return ($flag,$dow,$num);
}
# a time followed by 'w' (default), 'u', or 's';
sub _rule_At {
my($self,$rule,$at) = @_;
my($ret,$attype) = $self->_rule_Time($at,0,1);
if (! $ret) {
warn "ERROR: [rule_at] invalid: $rule: $at\n";
$Error = 1;
}
return($attype,$ret);
}
# a signed time (or "-" which is equivalent to 0)
sub _rule_Save {
my($self,$rule,$save) = @_;
$save = '00:00:00' if ($save eq "-");
my($ret) = $self->_rule_Time($save,1);
if (! $ret) {
warn "ERROR: [rule_save] invalid: $rule: $save\n";
$Error=1;
}
return $ret;
}
# letters (or "-")
sub _rule_Letters {
my($self,$rule,$letters)=@_;
return '' if ($letters eq "-");
return $letters;
}
########################################################################
# PARSING ZONES
########################################################################
my($TZ_START) = $dmb->join('date',['0001',1,2,0,0,0]);
my($TZ_END) = $dmb->join('date',['9999',12,30,23,59,59]);
sub _tzd_Zone {
my($self,$zone,$listref) = @_;
if (defined $listref) {
if (! exists $$self{'zone'}{$zone}) {
$$self{'zone'}{$zone} = [$zone];
}
push @{ $$self{'zone'}{$zone} }, [ @$listref ];
} elsif (exists $$self{'zone'}{$zone}) {
return @{ $$self{'zone'}{$zone} };
} else {
return ();
}
}
sub _tzd_DeleteZone {
my($self,$zone) = @_;
delete $$self{'zone'}{$zone};
return;
}
sub _tzd_ZoneKeys {
my($self) = @_;
return keys %{ $$self{'zone'} };
}
sub _tzd_CheckZones {
my($self) = @_;
print "... zones\n" if ($Verbose);
foreach my $zone ($self->_tzd_ZoneKeys()) {
my($start) = $TZ_START;
$Error = 0;
my ($name,@zone) = $self->_tzd_Zone($zone);
$self->_tzd_DeleteZone($zone);
while (@zone) {
my($gmt,$rule,$format,@until) = @{ shift(@zone) };
my($ruletype);
$gmt = $self->_zone_GMTOff($zone,$gmt);
($ruletype,$rule) = $self->_zone_Rule ($zone,$rule);
$format = $self->_zone_Format($zone,$format);
my($y,$m,$dow,$num,$flag,$t,$type,$end,$nextstart)
= $self->_zone_Until ($zone,@until);
if (! $Error) {
$self->_tzd_Zone($zone,[ $gmt,$ruletype,$rule,$format,$y,$m,$dow,
$num,$flag,$t,$type,$start,$end ]);
$start = $nextstart;
}
}
$self->_tzd_DeleteZone($zone) if ($Error);
}
return;
}
# TZdata file:
#
# #Zone NAME GMTOFF RULES FORMAT [UNTIL]
# Zone America/New_York -4:56:02 - LMT 1883 Nov 18 12:03:58
# -5:00 US E%sT 1920
# -5:00 NYC E%sT 1942
# -5:00 US E%sT 1946
# -5:00 NYC E%sT 1967
# -5:00 US E%sT
#
# Stored locally as:
#
# %Zone = (
# "America/New_York" =>
# [
# "America/New_York",
# [ -04:56:02 1 - LMT 1883 11 0 18 1 12:03:58 w START END ]
# ,[ -05:00:00 2 US E%sT 1920 01 0 01 1 00:00:00 w START END ]
# ,[ -05:00:00 2 NYC E%sT 1942 01 0 01 1 00:00:00 w START END ]
# ,[ -05:00:00 2 US E%sT 1946 01 0 01 1 00:00:00 w START END ]
# ,[ -05:00:00 2 NYC E%sT 1967 01 0 01 1 00:00:00 w START END ]
# ,[ -05:00:00 2 US E%sT 9999 12 0 31 1 00:00:00 u START END ]
# ]
# )
#
# Each %Zone list consists of:
# GMTOFF RULETYPE RULE ABBREV YEAR MON DOW NUM FLAG TIME TIMETYPE START
# where
# GMTOFF : the standard time offset for the time period starting
# at the end of the previous peried, and ending at the
# time specified by TIME/TIMETYPE
# RULETYPE : what type of value RULE can have
# $TZ_STANDARD the entire period is standard time
# $TZ_RULE the name of a rule to use for this period
# $TZ_OFFSET an additional offset to apply for the
# entire period (which is in saving time)
# RULE : a dash (-), the name of the rule, or an offset
# ABBREV : an abbreviation for the timezone (which may include a %s
# where letters from a rule are substituted)
# YEAR/MON : the year and month where the time period ends
# DOW/NUM/FLAG : the day of the month where the time period ends (see
# note below)
# TIME : HH:MM:SS where the time period ends
# TIMETYPE : how the time is to be interpreted
# u in UTC
# w wallclock time
# s in standard time
# START : This is the wallclock time when this zoneline starts. If the
# wallclock time cannot be decided yet, it is left blank. In
# the case of a non-wallclock time, the change should NOT
# occur on Dec 31 or Jan 1.
# END : The wallclock date/time when the zoneline ends. Blank if
# it cannot be decided.
#
# The time stored in the until fields (which is turned into the
# YEAR/MON/DOW/NUM/FLAG fields) actually refers to the exact second when
# the following zone line takes affect. When a rule specifies a time
# change exactly at that time (unfortunately, this situation DOES occur),
# the change will only apply to the next zone line.
#
# In interpreting DOW, NUM, FLAG, the value of FLAG determines how it is
# done. Values are:
# $TZ_DOM NUM is the day of month (1-31), DOW is ignored
# $TZ_LAST NUM is ignored, DOW is the day of week (1-7); the day
# of month is the last DOW in the month
# $TZ_GE NUM is a cutoff date (1-31), DOW is the day of week; the
# day of month is the first DOW in the month on or after
# the cutoff date
# $TZ_LE Similar to $TZ_GE but the day of month is the last DOW in
# the month on or before the cutoff date
#
# In a time period which uses a named rule, if the named rule doesn't
# cover a year, just use the standard time for that year.
# The total period covered by zones is from Jan 2, 0001 (00:00:00) to
# Dec 30, 9999 (23:59:59). The first and last days are ignored so that
# they can safely be expressed as wallclock time.
# a signed time
sub _zone_GMTOff {
my($self,$zone,$gmt) = @_;
my($ret) = $self->_rule_Time($gmt,1);
if (! $ret) {
warn "ERROR: [zone_gmtoff] invalid: $zone: $gmt\n";
$Error = 1;
}
return $ret;
}
# rule, a signed time, or "-"
sub _zone_Rule {
my($self,$zone,$rule) = @_;
return ($TZ_STANDARD,$rule) if ($rule eq "-");
my($ret) = $self->_rule_Time($rule,1);
return ($TZ_OFFSET,$ret) if ($ret);
if (! $self->_tzd_Rule($rule)) {
warn "ERROR: [zone_rule] rule undefined: $zone: $rule\n";
$Error = 1;
}
return ($TZ_RULE,$rule);
}
# a format
sub _zone_Format {
my($self,$zone,$format)=@_;
return $format;
}
# a date (YYYY MMM DD TIME)
sub _zone_Until {
my($self,$zone,$y,$m,$d,$t) = @_;
my($tmp,$type,$dow,$num,$flag,$err);
if (! $y) {
# Until '' == Until '9999 Dec 31 00:00:00'
$y = 9999;
$m = 12;
$d = 31;
$t = '00:00:00';
} else {
# Until '1975 ...'
if ($y !~ /^\d\d\d\d$/) {
warn "ERROR: [zone_until] invalid year: $zone: $y\n";
$Error = 1;
return ();
}
if (! $m) {
# Until '1920' == Until '1920 Jan 1 00:00:00'
$m = 1;
$d = 1;
$t = '00:00:00';
} else {
# Until '1920 Mar ...'
$tmp = $self->_rule_Month($m);
if (! $tmp) {
warn "ERROR: [zone_until] invalid month: $zone: $m\n";
$Error = 1;
return ();
}
$m = $tmp;
if (! $d) {
# Until '1920 Feb' == Until '1920 Feb 1 00:00:00'
$d = 1;
$t = '00:00:00';
} elsif ($d =~ /^last(.*)/) {
# Until '1920 Feb lastSun ...'
my(@tmp) = $self->_rule_DOM($d);
my($dow) = $tmp[0];
my $ymd = $dmb->nth_day_of_week($y,-1,$dow,$m);
$d = $$ymd[2];
} elsif ($d =~ />=/) {
my(@tmp) = $self->_rule_DOM($d);
my $dow = $tmp[0];
$d = $tmp[1];
my $ddow = $dmb->day_of_week([$y,$m,$d]);
if ($dow > $ddow) {
my $ymd = $dmb->calc_date_days([$y,$m,$d],$dow-$ddow);
$d = $$ymd[2];
} elsif ($dow < $ddow) {
my $ymd = $dmb->calc_date_days([$y,$m,$d],7-($ddow-$dow));
$d = $$ymd[2];
}
} elsif ($d =~ /<=/) {
my(@tmp) = $self->_rule_DOM($d);
my $dow = $tmp[0];
$d = $tmp[1];
my $ddow = $dmb->day_of_week([$y,$m,$d]);
if ($dow < $ddow) {
my $ymd = $dmb->calc_date_days([$y,$m,$d],$ddow-$dow,1);
$d = $$ymd[2];
} elsif ($dow > $ddow) {
my $ymd = $dmb->calc_date_days([$y,$m,$d],7-($dow-$ddow),1);
$d = $$ymd[2];
}
} else {
# Until '1920 Feb 20 ...'
}
if (! $t) {
# Until '1920 Feb 20' == Until '1920 Feb 20 00:00:00'
$t = '00:00:00';
}
}
}
# Make sure that day and month are valid and formatted correctly
($dow,$num,$flag,$err) = $self->_rule_DOM($d);
if ($err) {
warn "ERROR: [zone_until] invalid day: $zone: $d\n";
$Error = 1;
return ();
}
$m = "0$m" if (length($m)<2);
# Get the time type
if ($y == 9999) {
$type = 'w';
} else {
($tmp,$type) = $self->_rule_Time($t,0,1);
if (! $tmp) {
warn "ERROR: [zone_until] invalid time: $zone: $t\n";
$Error = 1;
return ();
}
$t = $tmp;
}
# Get the wallclock end of this zone line (and the start of the
# next one 1 second later) if possible. Since we cannot assume that
# the rules are present yet, we can only do this for wallclock time
# types. 'u' and 's' time types will be done later.
my ($start,$end) = ('','');
if ($type eq 'w') {
# Start of next time is Y-M-D-TIME
$start = $dmb->join('date',[$y,$m,$d,@{ $dmb->split('hms',$t) }]);
# End of this time is Y-M-D-TIME minus 1 second
$end = $dmb->_calc_date_time_strings($start,'0:0:1',1);
}
return ($y,$m,$dow,$num,$flag,$t,$type,$end,$start);
}
###############################################################################
# ROUTINES FOR GETTING INFORMATION OUT OF RULES/ZONES
###############################################################################
sub _tzd_ZoneLines {
my($self,$zone) = @_;
my @z = $self->_tzd_Zone($zone);
shift(@z);
# This will fill in any missing start/end values using the rules
# (which are now all present).
my $i = 0;
my($lastend,$lastdstend) = ('','00:00:00');
foreach my $z (@z) {
my($offset,$ruletype,$rule,$abbrev,$yr,$mon,$dow,$num,$flag,$time,
$timetype,$start,$end) = @$z;
# Make sure that we have a start wallclock time. We ALWAYS have the
# start time of the first zone line, and we will always have the
# end time of the zoneline before (if this is not the first) since
# we will determine it below.
if (! $start) {
$start = $dmb->_calc_date_time_strings($lastend,'0:0:1',0);
}
# If we haven't got a wallclock end, we can't get it yet... but
# we can get an unadjusted end which we'll use for determining
# what offsets apply from the rules.
my $fixend = 0;
if (! $end) {
$end = $self->_tzd_ParseRuleDate($yr,$mon,$dow,$num,$flag,$time);
$fixend = 1;
}
# Now we need to get the DST offset at the start and end of
# the period.
my($dstbeg,$dstend,$letbeg,$letend);
if ($ruletype == $TZ_RULE) {
$dstbeg = $lastdstend;
# Get the year from the end time for the zone line
# Get the dates for this rule.
# Find the latest one which is less than the end date.
# That's the end DST offset.
my %lett = ();
my $tmp = $dmb->split('date',$end);
my $y = $$tmp[0];
my(@rdate) = $self->_ruleInfo($rule,'rdates',$y);
my $d = $start;
while (@rdate) {
my($date,$off,$type,$lett,@tmp) = @rdate;
$lett{$off} = $lett;
@rdate = @tmp;
next if ($date lt $d || $date gt $end);
$d = $date;
$dstend = $off;
}
# If we didn't find $dstend, it's because the zone line
# ends before any rules can go into affect. If that is
# the case, we'll do one of two things:
#
# If the zone line starts this year, no time changes
# occured, so we set $dstend to the same as $dstbeg.
#
# Otherwise, set it to the last DST offset of the year
# before.
if (! $dstend) {
my($yrbeg) = $dmb->join('date',[$y,1,1,0,0,0]);
if ($start ge $yrbeg) {
$dstend = $dstbeg;
} else {
$dstend = $self->_ruleInfo($rule,'lastoff',$y);
}
}
$letbeg = $lett{$dstbeg};
$letend = $lett{$dstend};
} elsif ($ruletype == $TZ_STANDARD) {
$dstbeg = '00:00:00';
$dstend = $dstbeg;
$letbeg = '';
$letend = '';
} else {
$dstbeg = $rule;
$dstend = $dstbeg;
$letbeg = '';
$letend = '';
}
# Now we calculate the wallclock end time (if we don't already
# have it).
if ($fixend) {
if ($timetype eq 'u') {
# UT time -> STD time
$end = $dmb->_calc_date_time_strings($end,$offset,0);
}
# STD time -> wallclock time
$end = $dmb->_calc_date_time_strings($end,$dstend,1);
}
# Store the information
$i++;
$$self{'zonelines'}{$zone}{$i}{'start'} = $start;
$$self{'zonelines'}{$zone}{$i}{'end'} = $end;
$$self{'zonelines'}{$zone}{$i}{'stdoff'} = $offset;
$$self{'zonelines'}{$zone}{$i}{'dstbeg'} = $dstbeg;
$$self{'zonelines'}{$zone}{$i}{'dstend'} = $dstend;
$$self{'zonelines'}{$zone}{$i}{'letbeg'} = $letbeg;
$$self{'zonelines'}{$zone}{$i}{'letend'} = $letend;
$$self{'zonelines'}{$zone}{$i}{'abbrev'} = $abbrev;
$$self{'zonelines'}{$zone}{$i}{'rule'} = ($ruletype == $TZ_RULE ?
$rule : '');
$lastend = $end;
$lastdstend = $dstend;
}
$$self{'zonelines'}{$zone}{'numlines'} = $i;
return;
}
# Parses date information from a single rule and returns a date.
# The date is not adjusted for standard time or daylight saving time
# offsets.
sub _tzd_ParseRuleDate {
my($self,$year,$mon,$dow,$num,$flag,$time) = @_;
# Calculate the day-of-month
my($dom);
if ($flag==$TZ_DOM) {
$dom = $num;
} elsif ($flag==$TZ_LAST) {
($year,$mon,$dom) = @{ $dmb->nth_day_of_week($year,-1,$dow,$mon) };
} elsif ($flag==$TZ_GE) {
($year,$mon,$dom) = @{ $dmb->nth_day_of_week($year,1,$dow,$mon) };
while ($dom<$num) {
$dom += 7;
}
} elsif ($flag==$TZ_LE) {
($year,$mon,$dom) = @{ $dmb->nth_day_of_week($year,-1,$dow,$mon) };
while ($dom>$num) {
$dom -= 7;
}
}
# Split the time and then form the date
my($h,$mn,$s) = split(/:/,$time);
return $dmb->join('date',[$year,$mon,$dom,$h,$mn,$s]);
}
1;
# Local Variables:
# mode: cperl
# indent-tabs-mode: nil
# cperl-indent-level: 3
# cperl-continued-statement-offset: 2
# cperl-continued-brace-offset: 0
# cperl-brace-offset: 0
# cperl-brace-imaginary-offset: 0
# cperl-label-offset: 0
# End:
| jkb78/extrajnm | local/lib/perl5/Date/Manip/TZdata.pm | Perl | mit | 39,298 |
#!C:\Perl\bin\perl.exe
###############
#
# Filename: skype2google.pl
# Project: skype2google
# Number of Files: 1
# Language: Perl
# Platform: Windows
# Summary: Convert a Skype contact file into the format of a Google
# Contacts CSV file.
#
###############
use strict;
my $csv = "Name,E-mail,Notes,Section 1 - Description,Section 1 - Email,"
. "Section 1 - IM,Section 1 - Phone,Section 1 - Mobile,"
. "Section 1 - Pager,Section 1 - Fax,Section 1 - Company,"
. "Section 1 - Title,Section 1 - Other,Section 1 - Address,"
. "Section 2 - Description,Section 2 - Email,Section 2 - IM,"
. "Section 2 - Phone,Section 2 - Mobile,Section 2 - Pager,"
. "Section 2 - Fax,Section 2 - Company,Section 2 - Title,"
. "Section 2 - Other,Section 2 - Address,Section 3 - Description,"
. "Section 3 - Email,Section 3 - IM,Section 3 - Phone,"
. "Section 3 - Mobile,Section 3 - Pager,Section 3 - Fax,"
. "Section 3 - Company,Section 3 - Title,Section 3 - Other,"
. "Section 3 - Address";
if( $#ARGV != 0 ) {
print "Usage: skype2google [vCard filename]";
exit;
}
if( ! -e $ARGV[0] ) {
print "vCard doesn't exist";
exit;
}
open( FILE, "<" . $ARGV[0] );
my $blurb = "";
my @contacts;
while( my $temp = <FILE> ) {
if( $temp ne "\n" ) {
$blurb .= $temp;
}
if( $temp =~ m/END:VCARD/xms ) {
push(@contacts, $blurb);
$blurb = "";
}
}
foreach my $value (@contacts) {
my $phone, my $name, my $skype;
if( $value =~ /X-SKYPE-PSTNNUMBER:(\+\d+)/xms ) {
$phone = $1;
}
if( $value =~ /X-SKYPE-DISPLAYNAME:(\S+\s*\S*)/xms ) {
$name = $1;
}
if( $value =~ /X-SKYPE-USERNAME:(\S+)/xms ) {
$skype = $1;
}
if( $name && $name ne "Skype Test" ) {
if( $skype ) {
$csv .= "$name,,,Other,,SKYPE: $skype,,,,,,,,,"
. "Personal,,,,$phone,,,,,,\n";
} else {
$csv .= "$name,,,Personal,,,,$phone,,,,,,\n";
}
}
}
open( CSV, ">contacts.csv" );
print CSV $csv;
| codemonkey2841/skype2google | skype2google.pl | Perl | mit | 2,091 |
# File: Rank.pm
#
# Purpose: Ranks players by various keywords.
# SPDX-FileCopyrightText: 2021 Pragmatic Software <pragma78@gmail.com>
# SPDX-License-Identifier: MIT
package PBot::Plugin::Spinach::Rank;
use PBot::Imports;
use FindBin;
use lib "$FindBin::RealBin/../../..";
use PBot::Plugin::Spinach::Stats;
use Math::Expression::Evaluator;
sub new {
Carp::croak("Options to " . __FILE__ . " should be key/value pairs, not hash reference") if ref $_[1] eq 'HASH';
my ($class, %conf) = @_;
my $self = bless {}, $class;
$self->initialize(%conf);
return $self;
}
sub initialize {
my ($self, %conf) = @_;
$self->{pbot} = $conf{pbot} // Carp::croak("Missing pbot reference to " . __FILE__);
$self->{channel} = $conf{channel} // Carp::croak("Missing channel reference to " . __FILE__);
$self->{filename} = $conf{filename} // 'stats.sqlite';
$self->{stats} = PBot::Plugin::Spinach::Stats->new(pbot => $self->{pbot}, filename => $self->{filename});
}
sub sort_generic {
my ($self, $key) = @_;
if ($self->{rank_direction} eq '+') { return $b->{$key} <=> $a->{$key}; }
else { return $a->{$key} <=> $b->{$key}; }
}
sub print_generic {
my ($self, $key, $player) = @_;
return undef if $player->{games_played} == 0;
return "$player->{nick}: $player->{$key}";
}
sub print_avg_score {
my ($self, $player) = @_;
return undef if $player->{games_played} == 0;
my $result = int $player->{avg_score};
return "$player->{nick}: $result";
}
sub sort_bad_lies {
my ($self) = @_;
if ($self->{rank_direction} eq '+') { return $b->{questions_played} - $b->{good_lies} <=> $a->{questions_played} - $a->{good_lies}; }
else { return $a->{questions_played} - $a->{good_lies} <=> $b->{questions_played} - $b->{good_lies}; }
}
sub print_bad_lies {
my ($self, $player) = @_;
return undef if $player->{games_played} == 0;
my $result = $player->{questions_played} - $player->{good_lies};
return "$player->{nick}: $result";
}
sub sort_mentions {
my ($self) = @_;
if ($self->{rank_direction} eq '+') {
return $b->{games_played} - $b->{times_first} - $b->{times_second} - $b->{times_third} <=> $a->{games_played} - $a->{times_first} - $a->{times_second} -
$a->{times_third};
} else {
return $a->{games_played} - $a->{times_first} - $a->{times_second} - $a->{times_third} <=> $b->{games_played} - $b->{times_first} - $b->{times_second} -
$b->{times_third};
}
}
sub print_mentions {
my ($self, $player) = @_;
return undef if $player->{games_played} == 0;
my $result = $player->{games_played} - $player->{times_first} - $player->{times_second} - $player->{times_third};
return "$player->{nick}: $result";
}
sub sort_expr {
my ($self) = @_;
my $result = eval {
my $result_a = $self->{expr}->val(
{
highscore => $a->{high_score},
lowscore => $a->{low_score},
avgscore => $a->{avg_score},
goodlies => $a->{good_lies},
badlies => $a->{questions_played} - $a->{good_lies},
first => $a->{times_first},
second => $a->{times_second},
third => $a->{times_third},
mentions => $a->{games_played} - $a->{times_first} - $a->{times_second} - $a->{times_third},
games => $a->{games_played},
questions => $a->{questions_played},
goodguesses => $a->{good_guesses},
badguesses => $a->{bad_guesses},
deceptions => $a->{players_deceived}
}
);
my $result_b = $self->{expr}->val(
{
highscore => $b->{high_score},
lowscore => $b->{low_score},
avgscore => $b->{avg_score},
goodlies => $b->{good_lies},
badlies => $b->{questions_played} - $b->{good_lies},
first => $b->{times_first},
second => $b->{times_second},
third => $b->{times_third},
mentions => $b->{games_played} - $b->{times_first} - $b->{times_second} - $b->{times_third},
games => $b->{games_played},
questions => $b->{questions_played},
goodguesses => $b->{good_guesses},
badguesses => $b->{bad_guesses},
deceptions => $b->{players_deceived}
}
);
if ($self->{rank_direction} eq '+') { return $result_b <=> $result_a; }
else { return $result_a <=> $result_b; }
};
if ($@) {
$self->{pbot}->{logger}->log("expr sort error: $@\n");
return 0;
}
return $result;
}
sub print_expr {
my ($self, $player) = @_;
return undef if $player->{games_played} == 0;
my $result = eval {
$self->{expr}->val(
{
highscore => $player->{high_score},
lowscore => $player->{low_score},
avgscore => $player->{avg_score},
goodlies => $player->{good_lies},
badlies => $player->{questions_played} - $player->{good_lies},
first => $player->{times_first},
second => $player->{times_second},
third => $player->{times_third},
mentions => $player->{games_played} - $player->{times_first} - $player->{times_second} - $player->{times_third},
games => $player->{games_played},
questions => $player->{questions_played},
goodguesses => $player->{good_guesses},
badguesses => $player->{bad_guesses},
deceptions => $player->{players_deceived}
}
);
};
if ($@) {
$self->{pbot}->{logger}->log("Error in expr print: $@\n");
return undef;
}
return "$player->{nick}: $result";
}
sub rank {
my ($self, $arguments) = @_;
my %ranks = (
highscore => {
sort => sub { $self->sort_generic('high_score', @_) },
print => sub { $self->print_generic('high_score', @_) },
title => 'high score'
},
lowscore => {
sort => sub { $self->sort_generic('low_score', @_) },
print => sub { $self->print_generic('low_score', @_) },
title => 'low score'
},
avgscore => {
sort => sub { $self->sort_generic('avg_score', @_) },
print => sub { $self->print_avg_score(@_) },
title => 'average score'
},
goodlies => {
sort => sub { $self->sort_generic('good_lies', @_) },
print => sub { $self->print_generic('good_lies', @_) },
title => 'good lies'
},
badlies => {
sort => sub { $self->sort_bad_lies(@_) },
print => sub { $self->print_bad_lies(@_) },
title => 'bad lies'
},
first => {
sort => sub { $self->sort_generic('times_first', @_) },
print => sub { $self->print_generic('times_first', @_) },
title => 'first place'
},
second => {
sort => sub { $self->sort_generic('times_second', @_) },
print => sub { $self->print_generic('times_second', @_) },
title => 'second place'
},
third => {
sort => sub { $self->sort_generic('times_third', @_) },
print => sub { $self->print_generic('times_third', @_) },
title => 'third place'
},
mentions => {
sort => sub { $self->sort_mentions(@_) },
print => sub { $self->print_mentions(@_) },
title => 'mentions'
},
games => {
sort => sub { $self->sort_generic('games_played', @_) },
print => sub { $self->print_generic('games_played', @_) },
title => 'games played'
},
questions => {
sort => sub { $self->sort_generic('questions_played', @_) },
print => sub { $self->print_generic('questions_played', @_) },
title => 'questions played'
},
goodguesses => {
sort => sub { $self->sort_generic('good_guesses', @_) },
print => sub { $self->print_generic('good_guesses', @_) },
title => 'good guesses'
},
badguesses => {
sort => sub { $self->sort_generic('bad_guesses', @_) },
print => sub { $self->print_generic('bad_guesses', @_) },
title => 'bad guesses'
},
deceptions => {
sort => sub { $self->sort_generic('players_deceived', @_) },
print => sub { $self->print_generic('players_deceived', @_) },
title => 'players deceived'
},
expr => {
sort => sub { $self->sort_expr(@_) },
print => sub { $self->print_expr(@_) },
title => 'expr'
},
);
my @order = qw/highscore lowscore avgscore first second third mentions games questions goodlies badlies deceptions goodguesses badguesses expr/;
if (not $arguments) {
my $result = "Usage: rank [-]<keyword> [offset] or rank [-]<nick>; available keywords: ";
$result .= join ', ', @order;
$result .= ".\n";
$result .= "Prefix with a dash to invert sort.\n";
return $result;
}
$arguments = lc $arguments;
if ($arguments =~ s/^([+-])//) { $self->{rank_direction} = $1; }
else { $self->{rank_direction} = '+'; }
my $offset = 1;
if ($arguments =~ s/\s+(\d+)$//) { $offset = $1; }
my $opt_arg;
if ($arguments =~ /^expr/) {
if ($arguments =~ s/^expr (.+)$/expr/) { $opt_arg = $1; }
else { return "Usage: spinach rank expr <expression>"; }
}
if (not exists $ranks{$arguments}) {
$self->{stats}->begin;
my $player_id = $self->{stats}->get_player_id($arguments, $self->{channel}, 1);
my $player_data = $self->{stats}->get_player_data($player_id);
if (not defined $player_id) {
$self->{stats}->end;
return "I don't know anybody named $arguments.";
}
my $players = $self->{stats}->get_all_players($self->{channel});
my @rankings;
foreach my $key (@order) {
next if $key eq 'expr';
my $sort_method = $ranks{$key}->{sort};
@$players = sort $sort_method @$players;
my $rank = 0;
my $stats;
my $last_value = -1;
foreach my $player (@$players) {
$stats = $ranks{$key}->{print}->($player);
if (defined $stats) {
my ($value) = $stats =~ /[^:]+:\s+(.*)/;
$rank++ if $value ne $last_value;
$last_value = $value;
} else {
$rank++ if lc $player->{nick} eq $arguments;
}
last if lc $player->{nick} eq $arguments;
}
if (not $rank) { push @rankings, "$ranks{key}->{title}: N/A"; }
else {
if (not $stats) { push @rankings, "$ranks{$key}->{title}: N/A"; }
else {
$stats =~ s/[^:]+:\s+//;
push @rankings, "$ranks{$key}->{title}: #$rank ($stats)";
}
}
}
my $result = "$player_data->{nick}'s rankings: ";
$result .= join ', ', @rankings;
$self->{stats}->end;
return $result;
}
$self->{stats}->begin;
my $players = $self->{stats}->get_all_players($self->{channel});
if ($arguments eq 'expr') {
$self->{expr} = eval { Math::Expression::Evaluator->new($opt_arg) };
if ($@) {
my $error = $@;
$error =~ s/ at .*//ms;
return "Bad expression: $error";
}
$self->{expr}->optimize;
}
my $sort_method = $ranks{$arguments}->{sort};
@$players = sort $sort_method @$players;
my @ranking;
my $rank = 0;
my $last_value = -1;
foreach my $player (@$players) {
my $entry = $ranks{$arguments}->{print}->($player);
if (defined $entry) {
my ($value) = $entry =~ /[^:]+:\s+(.*)/;
$rank++ if $value ne $last_value;
$last_value = $value;
next if $rank < $offset;
push @ranking, "#$rank $entry" if defined $entry;
last if scalar @ranking >= 15;
}
}
my $result;
if (not scalar @ranking) {
if ($offset > 1) { $result = "No rankings available for $self->{channel} at offset #$offset.\n"; }
else { $result = "No rankings available for $self->{channel} yet.\n"; }
} else {
if ($arguments eq 'expr') { $result = "Rankings for $opt_arg: "; }
else { $result = "Rankings for $ranks{$arguments}->{title}: "; }
$result .= join ', ', @ranking;
}
$self->{stats}->end;
return $result;
}
1;
| pragma-/pbot | lib/PBot/Plugin/Spinach/Rank.pm | Perl | mit | 13,385 |
#! /usr/bin/env perl
# Read the recent few days of survey day, update summary tables;
# Create CSV files for dygraphs javascript charting library
use Getopt::Long;
use POSIX strftime;
use IO::File;
use Socket6;
use Data::Dumper;
use JSON;
use DBI;
use strict;
$| = 1;
my ( $MirrorConfig, $PrivateConfig, $dbh, $midnight );
$ENV{"TZ"} = "UTC";
my %SUPPRESS = map { $_ => 1 } qw(
2010-03-31
#2016-06-05
#2016-06-06
);
################################################################
# getopt #
################################################################
my ( $usage, %argv, %input ) = "";
$usage = <<"EOF";
[--export 750] or [--since 2010/05/01]
If --since is used, it will be used in preference.
Otherwise, --export will be used; with a default
of just over two years.
Examples:
$0 --config /var/www/test-ipv6.example.com/site/config.js --days 750
$0 --config /var/www/test-ipv6.example.com/site/config.js --since 2010/05/01
EOF
%input = (
"rescan=i" => "rescan this many days (3)",
"config=s" => "config.js file (REQUIRED)",
"sitedir=s" => "site directory(default: same as config)",
"private=s" => "private.js file (default: same place as config.js)",
"days=i" => "export number of days (750) to export/graph",
"since=s" => "export since this date YYYY/MM/DD ie 2010/05/01",
"v|verbose" => "spew extra data to the screen",
"h|help" => "show option help"
);
my $result = GetOptions( \%argv, keys %input );
$argv{"rescan"} ||= 3;
if ( ( $argv{"config"} ) && ( !$argv{"private"} ) ) {
$argv{"private"} = $argv{"config"};
$argv{"private"} =~ s#[^/]+$#private.js#;
}
if ( !$argv{"sitedir"} ) {
$argv{"sitedir"} = $argv{"config"};
$argv{"sitedir"} =~ s#/[^/]+$##; # Strip filename, keep rest
}
if ( ( !$result ) || ( !$argv{"config"} ) || ( $argv{h} ) ) {
&showOptionsHelp;
exit 0;
}
$argv{"days"}||=750;
################################################################
# configs #
################################################################
sub get_file {
my ($file) = @_;
my $handle = new IO::File "<$file" or die "Could not open $file : $!";
my $buffer;
read $handle, $buffer, -s $file;
close $handle;
return $buffer;
}
sub get_config {
my ( $file, $varname ) = @_;
my $got = get_file($file);
# Remove varname
$got =~ s#^\s*$varname\s*=\s*##ms;
# Remove comments like /* and */ and //
$got =~ s#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t](//).*)##mg;
# And trailing commas
$got =~ s/,\s*([\]}])/$1/mg;
my $ref = decode_json($got);
if ( !$ref ) {
die "Could not json parse $file\n";
}
return $ref;
}
sub validate_private_config {
my ($ref) = @_;
die "Missing private.js: db password" unless ( $ref->{db}{password} );
die "Missing private.js: db db" unless ( $ref->{db}{db} );
die "Missing private.js: db username" unless ( $ref->{db}{username} );
die "Missing private.js: db host" unless ( $ref->{db}{host} );
}
################################################################
# utilities #
################################################################
sub get_db_handle {
my ($dbref) = @_;
my $dsn =
sprintf( "DBI:mysql:database=%s;host=%s", $dbref->{db}, $dbref->{host} );
my $dbh = DBI->connect( $dsn, $dbref->{username}, $dbref->{password} );
die "Failed to connect to mysql" unless ($dbh);
return $dbh;
}
my %my_mkdir;
sub my_mkdir {
my ($dir) = @_;
return if ( $my_mkdir{$dir}++ );
return if ( -d $dir );
system( "mkdir", "-p", $dir );
return if ( -d $dir );
die "Unable to create $dir\: $!";
}
sub showOptionsHelp {
my ( $left, $right, $a, $b, $key );
my (@array);
print "Usage: $0 [options] $usage\n";
print "where options can be:\n";
foreach $key ( sort keys(%input) ) {
( $left, $right ) = split( /[=:]/, $key );
( $a, $b ) = split( /\|/, $left );
if ($b) {
$left = "-$a --$b";
}
else {
$left = " --$a";
}
$left = substr( "$left" . ( ' ' x 20 ), 0, 20 );
push( @array, "$left $input{$key}\n" );
}
print sort @array;
}
################################################################
# Prep daily and monthly summaries in the database #
################################################################
sub update_daily_summary {
my ($rescan) = @_;
my $unix = $midnight - $rescan * 86400 + 86400;
while ( $unix <= $midnight ) {
my $day = strftime( '%Y-%m-%d', localtime $unix );
my $start = "$day 00:00:00";
my $stop = "$day 23:59:59";
print "Process: $start to $stop\n" if ( $argv{"v"} );
$unix += 86400;
my %byvalues;
{
my $sql_template =
"select status_a,status_aaaa,status_ds4,status_ds6,ip6,ip6,cookie,tokens from survey where timestamp >= ? and timestamp <= ? order by timestamp;";
my $sth = $dbh->prepare($sql_template);
$sth->execute( $start, $stop ) or die $sth->errstr;
while ( my $ref = $sth->fetchrow_hashref() ) {
print "." if ( $argv{"v"} );
my $cookie = ${$ref}{"cookie"};
my $tokens = ${$ref}{"tokens"};
my $ip4 = ${$ref}{"ip4"};
my $ip6 = ${$ref}{"ip6"};
my $status_a = ${$ref}{"status_a"};
my $status_aaaa = ${$ref}{"status_aaaa"};
my $status_ds4 = ${$ref}{"status_ds4"};
my $status_ds6 = ${$ref}{"status_ds6"};
$tokens =
check_results($ref); # Ignore prior state. Re-evaluate.
$byvalues{$cookie} = $tokens;
} ## end while ( my $ref = $sth->fetchrow_hashref() )
$sth->finish();
print "\n" if ( $argv{"v"} );
}
# Now do something with %bycookie;
# invert
my %bystatus;
foreach my $key ( keys %byvalues ) {
$bystatus{ $byvalues{$key} }++;
}
# Delete the previous count for this date, in preparation to update it.
{
my $sql_template = "delete from daily_summary where datestamp = ?;";
my $sth = $dbh->prepare($sql_template);
$sth->execute($day) or die $sth->errstr;
$sth->finish();
}
# Insert new records
{
my $sql_template =
"insert into daily_summary (datestamp,total,tokens) values (?,?,?);";
my $sth = $dbh->prepare($sql_template);
foreach my $tokens ( keys %bystatus ) {
my $count = $bystatus{$tokens};
$sth->execute( $day, $count, $tokens ) or die $sth->errstr;
print "$sql_template ($day, $count, $tokens)\n"
if ( $argv{"v"} );
}
$sth->finish();
}
} ## end while ( $unix <= $midnight )
} ## end sub update_daily_summary
sub update_monthly_summary {
my ($rescan) = @_;
my $unix = $midnight - $rescan * 86400;
my %did_month;
while ( $unix <= $midnight + 86400 ) {
my $month = strftime( '%Y-%m', localtime $unix );
$unix += 86400;
next if ( $did_month{$month}++ ); # Don't want the repeat business.
my $start = "$month-01";
my $stop;
{
my $sql_template = "SELECT LAST_DAY(?);";
my $sth = $dbh->prepare($sql_template);
$sth->execute($start) or die $sth->errstr;
($stop) = $sth->fetchrow_array;
$sth->finish();
}
print "Process: $start to $stop\n" if ( $argv{"v"} );
my %bystatus;
{
my $sql_template =
"select total,tokens from daily_summary where datestamp >= ? and datestamp <= ?;";
my $sth = $dbh->prepare($sql_template);
$sth->execute( $start, $stop ) or die $sth->errstr;
while ( my $ref = $sth->fetchrow_hashref() ) {
my $tokens = ${$ref}{tokens};
my $total = ${$ref}{total};
$bystatus{$tokens} += $total;
}
$sth->finish();
}
# Delete the previous count for this date, in preparation to update it.
{
my $sql_template =
"delete from monthly_summary where datestamp = ?;";
my $sth = $dbh->prepare($sql_template);
$sth->execute($stop) or die $sth->errstr;
$sth->execute($start) or die $sth->errstr;
$sth->finish();
}
# Insert new records
{
my $sql_template =
"insert into monthly_summary (datestamp,total,tokens) values (?,?,?);";
my $sth = $dbh->prepare($sql_template);
foreach my $tokens ( keys %bystatus ) {
my $count = $bystatus{$tokens};
$sth->execute( $stop, $count, $tokens ) or die $sth->errstr;
}
$sth->finish();
}
} ## end while ( $unix <= $midnight + 86400 )
} ## end sub update_monthly_summary
################################################################
# Check results #
################################################################
my %states = (
"a aaaa ds4 ds6" => "status",
"oooo" => "Confused",
"ooob" => "Dual Stack - IPv4 Preferred",
"oobo" => "Dual Stack - IPv6 Preferred",
"oobb" => "Broken DS",
"oboo" => "Confused",
"obob" => "IPv4 only",
"obbo" => "Dual Stack - IPv6 Preferred", # Whoa. What's with that one?
"obbb" => "Broken DS",
"booo" => "Confused",
"boob" => "Dual Stack - IPv4 Preferred", # Whoa. What's with that one?
"bobo" => "IPv6 only",
"bobb" => "Broken DS",
"bboo" => "Web Filter",
"bbob" => "Web Filter",
"bbbo" => "Web Filter",
"bbbb" => "Web Filter",
);
sub check_results {
my $ref = shift @_;
my $status_a = ${$ref}{"status_a"};
my $status_aaaa = ${$ref}{"status_aaaa"};
my $status_ds4 = ${$ref}{"status_ds4"};
my $status_ds6 = ${$ref}{"status_ds6"};
my $lookup =
substr( $status_a, 0, 1 )
. substr( $status_aaaa, 0, 1 )
. substr( $status_ds4, 0, 1 )
. substr( $status_ds6, 0, 1 );
$lookup =~ s/s/o/g; # Slow? treat as OK for this
$lookup =~ s/t/b/g; # Timeout? treat as bad for this
my $token = $states{$lookup};
# print "$lookup $token\n" if ($argv{"v"});
if ( !$token ) {
$token ||= "Missing";
# print join( "\t", $lookup, $status_a, $status_aaaa, $status_ds4, $status_ds6, $token ) . "\n";
}
return $token;
} ## end sub check_results
################################################################
# create_csv creates the csv files #
################################################################
sub create_csv {
my ($days,$since) = @_;
my $start_date =
strftime( '%Y-%m-%d', gmtime( $midnight - $days * 86400 ) );
if ($since ne "") {
$start_date = $since;
}
my $stop_date = strftime( '%Y-%m-%d', gmtime( $midnight + 1 * 86400 ) );
my $dir = $argv{"sitedir"};
if ( ( ( $start_date cmp "2010-05-01" ) < 0 ) ) {
$start_date = "2010-05-01";
}
my %buckets;
my %dates;
{
my $sql_template =
"select unix_timestamp(datestamp) as unixtime, tokens, total from daily_summary where datestamp >= ? and datestamp <= ? order by unixtime;";
my $sth = $dbh->prepare($sql_template);
$sth->execute( $start_date, $stop_date ) or die $sth->errstr;
while ( my $ref = $sth->fetchrow_hashref() ) {
my $unixtime = ${$ref}{"unixtime"};
my $total = ${$ref}{"total"};
my $bucket = ${$ref}{"tokens"};
next if ( $bucket eq "skip" );
next if ( $bucket eq "Missing" );
if ( $argv{"v"} ) {
# print STDERR "Unclear: ${$ref}{tokens}\n" if ( $bucket =~ /unclear/i );
}
$buckets{$bucket} += $total;
$buckets{"total"} += $total;
$dates{$unixtime}{$bucket} += $total;
$dates{$unixtime}{"total"} += $total;
}
$sth->finish();
}
my @dates = sort keys %dates;
my @buckets = sort keys %buckets;
# Make sure these are each created.
my @buckets = (
"IPv4 only",
"IPv6 only",
"Dual Stack - IPv4 Preferred",
"Dual Stack - IPv6 Preferred",
"Broken DS",
"Confused",
"Missing",
"Web Filter"
);
{
my $filename = "$dir/graphdata_100.csv";
my $fh = IO::File->new(">$filename.new")
or die "failed to create $filename.new: $!";
my $legend = join( ",", grep( $_ ne "total", @buckets ) );
print $fh "X,$legend\n";
foreach my $date (@dates) {
my $d = strftime( '%Y-%m-%d', gmtime $date );
next if (exists $SUPPRESS{$d});
my @val = map( $dates{$date}{$_}, grep( $_ ne "total", @buckets ) );
my $total = $dates{$date}{"total"};
if ( $total > 0 ) {
foreach my $val (@val) {
$val = sprintf( "%.2f", 100.00 * $val / $total );
}
}
my $val = join( ",", @val );
print $fh "$d,$val\n";
}
close $fh;
rename( "$filename.new", "$filename" )
or die "Rename $filename.new $filename: $!";
}
{
my $filename = "$dir/graphdata.csv";
my $fh = IO::File->new(">$filename.new")
or die "failed to create $filename.new: $!";
my $legend = join( ",", @buckets );
print $fh "X,$legend\n";
foreach my $date (@dates) {
my $d = strftime( '%Y-%m-%d', gmtime $date );
next if (exists $SUPPRESS{$d});
my @val = map( $dates{$date}{$_}, @buckets );
my $val = join( ",", @val );
print $fh "$d,$val\n";
}
close $fh;
rename( "$filename.new", "$filename" )
or die "Rename $filename.new $filename: $!";
}
} ## end sub generate_rrd_db
################################################################
# main #
################################################################
$midnight = int( time / 86400 ) * 86400;
$MirrorConfig = get_config( $argv{"config"}, "MirrorConfig" );
$PrivateConfig = get_config( $argv{"private"}, "PrivateConfig" );
validate_private_config($PrivateConfig);
$dbh = get_db_handle( $PrivateConfig->{db} );
update_daily_summary( $argv{"rescan"} );
update_monthly_summary( $argv{"rescan"} );
create_csv($argv{"days"},$argv{"since"}); # A bit over 2 years
| falling-sky/extras | falling-sky-dyngraphs-csv.pl | Perl | mit | 15,167 |
package # hidden from PAUSE
TestApp::Controller::Root;
use strict;
use warnings;
use parent 'Catalyst::Controller';
#
# Sets the actions in this controller to be registered with no prefix
# so they function identically to actions created in MyApp.pm
#
__PACKAGE__->config->{namespace} = '';
=head1 NAME
TestApp::Controller::Root - Root Controller for TestApp
=head1 DESCRIPTION
[enter your description here]
=head1 METHODS
=cut
=head2 index
=cut
sub index :Path :Args(0) {
my ( $self, $c ) = @_;
# Hello World
$c->response->body( $c->welcome_message );
}
sub default :Path {
my ( $self, $c ) = @_;
$c->response->body( 'Page not found' );
$c->response->status(404);
}
use Data::Dumper;
sub test_params :Path('test_params') {
my ($self, $c) = @_;
my $test = {
a => $c->req->param('a'),
b => $c->req->param('b'),
c => $c->req->param('c'),
};
$c->res->body(Dumper(\$test));
}
sub test_params2 :Path('test_params2') {
my ($self, $c) = @_;
my $test = {
a => $c->req->params->{'a'},
b => $c->req->params->{'b'},
c => $c->req->params->{'c'},
};
$c->res->body(Dumper(\$test));
}
=head2 end
Attempt to render a view, if needed.
=cut
sub end : ActionClass('RenderView') {}
=head1 AUTHOR
Catalyst developer
=head1 LICENSE
This library is free software. You can redistribute it and/or modify
it under the same terms as Perl itself.
=cut
1;
| gitpan/Book-Chinese-MasterPerlToday | eg/Catalyst/TestApp/lib/TestApp/Controller/Root.pm | Perl | mit | 1,475 |
#!/usr/bin/env perl
use strict;
use warnings;
my $ival = 12;
my $fval = 3.14;
my $sci = 1.82e45;
my $dval = 0xffffffff;
my $oval = 0457;
my $bin = 0b0101;
my $readable = 10_000_000;
my $str1 = "hello, it's not a joke";
$str1 = qq#hello, it's not a joke#;
my $str2 = 'hello, it\'s not a joke';
$str2 = q(hello, it's not a joke);
my $rval = \$str1;
my $long = <<EOF;
#!/usr/bin/env perl
use strict;
use warnings;
my $ival = 12;
my $fval = 3.14;
my $sci = 1.82e45;
my $dval=0xffffffff;
my $oval=0457;
my $bin=0b0101;
my $readable=10_000_000;
my $str1="hello, it's not a joke";
my $str2='hello, it\'s not a joke';
my $rval=\$str1;
EOF
print $long; | chuanqinggao/daily-mark | perl/junior/variable/scalar.pl | Perl | mit | 713 |
=head1 LICENSE
Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=cut
# A set of types used by the REST API namespaced to avoid coercsion collisions
package EnsEMBL::REST::Types;
use Moose;
use Moose::Util::TypeConstraints;
subtype 'EnsRESTValueList', as 'ArrayRef[Value]';
coerce 'EnsRESTValueList' => from 'Value' => via { [$_] };
1;
| willmclaren/ensembl-rest | lib/EnsEMBL/REST/Types.pm | Perl | apache-2.0 | 982 |
=head1 LICENSE
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
=head1 CONTACT
Please email comments or questions to the public Ensembl
developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
Questions may also be sent to the Ensembl help desk at
<http://www.ensembl.org/Help/Contact>.
=cut
=head1 NAME
Bio::EnsEMBL::Analysis::Runnable::PSILC -
=head1 SYNOPSIS
my $PSILC = Bio::EnsEMBL::Analysis::Runnable::PSILC->new
(
'-trans' => $transcript,
'-homologs' => $homologs,
'-analysis' => $analysis,
'-domain' => $domains,
'-input_id' => $self->input_id,
);
$runnabledb->fetch_input();
$runnabledb->run();
my @array = @{$runnabledb->output};
$runnabledb->write_output();
=head1 DESCRIPTION
Runnable for PSILC
=head1 METHODS
=cut
package Bio::EnsEMBL::Analysis::Runnable::PSILC;
use strict;
use warnings;
use Bio::EnsEMBL::Analysis::Runnable;
use Bio::EnsEMBL::Analysis::Config::Pseudogene;
use Bio::Tools::Run::Alignment::Clustalw;
use Bio::Align::Utilities qw(aa_to_dna_aln);
use Bio::AlignIO;
use Bio::SimpleAlign;
use vars qw(@ISA);
@ISA = qw(Bio::EnsEMBL::Analysis::Runnable);
=head2 new
Arg [1] : none
Description: Creates runnable
Returntype : none
Exceptions : none
Caller : general
=cut
sub new {
my ($class,@args) = @_;
my $self = $class->SUPER::new(@args);
$self->{'_trans'} = {}; # transcript to test;
$self->{'_homologs'} = (); # array of holmologs to cluster with transcript;
$self->{'_domains'} = (); # array ref of protein feature ids;
my($trans,$domains,$homologs,$input_id, $psilc_work_dir) = $self->_rearrange([qw(
TRANS
DOMAIN
HOMOLOGS
INPUT_ID
PSILC_WORK_DIR
)], @args);
if ($trans) {
$self->trans($trans);
}
if ($homologs) {
$self->homologs($homologs);
}
if ($domains) {
$self->domains($domains);
}
$self->output_dir($input_id);
$self->program('/nfs/acari/sw4/Pseudogenes/PSILC/psilc1.21/psilc.jar');
return $self;
}
=head2 run
Arg [1] : none
Description: Makes alignment out of transcripts and runs PSILC
Returntype : none
Exceptions : none
Caller : general
=cut
sub run{
my ($self) = @_;
$self->checkdir();
$self->write_pfam_ids;
my $filename = $self->create_filename('PSILC','fasta');
$self->make_codon_based_alignment;
$self->run_analysis();
$self->files_to_be_deleted($filename);
$self->parse_results;
# $self->delete_files;
}
=head2 write_pfam_ids
Arg [1] : none
Description: Writes identifiers for PFAM domains that PSILC will search for
in the protein alignment
Returntype : none
Exceptions : throws if it cannot open the file to write to
Caller : general
=cut
sub write_pfam_ids{
my ($self)=@_;
my $dir = $self->workdir;
my $domains = $self->domains;
print STDERR "writing pfam ids to $dir/pfamA\n";
open (IDS,">$dir/pfamA") or $self->throw("Cannot open file for writing pfam ids $dir/pfamA\n");
print IDS "$domains";
close IDS;
return 1;
}
=head2 run_analysis
Arg [1] : scalar - program name
Description: runs the PSILC executable
Returntype : none
Exceptions : throws if program is not executable
Caller : general
=cut
sub run_analysis{
my ($self, $program) = @_;
if(!$program){
$program = $self->program;
}
throw($program." is not executable Runnable::run_analysis ")
unless($program && -x $program);
my $file = $self->queryfile;
my $dir = $self->workdir;
$file =~ s/^$dir\///;
my $command = "java -Xmx400m -jar $program";
$command .= " --align $file.aln";
$command .= " --seq ".$self->id;
$command .= " --restrict 1";
# $command .= " --alignMethod 1";
$command .= " --max_nodes 10:6";
$command .= " --repository /ecs2/work2/sw4/PFAM";
$command .= " > ".$self->resultsfile;
print "Running analysis ".$command."\n";
system($command) == 0 or $self->throw("FAILED to run ".$command);
}
=head2 parse_results
Arg [1] : scalar - filename
Description: parses PSILC results
Returntype : none
Exceptions : warns if the results are unreadable
Caller : general
=cut
sub parse_results{
my ($self, $filename) =@_;
my ($nuc_dom,$prot_dom,$postPMax,$postNmax) = 0;
my $dir = $self->workdir;
my $trans = $self->trans;
my $id = $self->id;
open (PSILC,"$dir/PSILC_WAG_HKY/summary") or $self->warn("Cannot open results file $dir/PSILC_WAG_HKY/summary\n$@\n");
while(<PSILC>){
chomp;
next unless $_ =~ /^$id\/\S+\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)/;
$nuc_dom = $1;
$prot_dom = $2;
$postPMax = $3;
$postNmax = $4;
last;
}
close PSILC;
unless ($nuc_dom){
$self->warn("ERROR unable to parse results file $dir/PSILC_WAG_HKY/summary\n");
$self->warn("Failed for $id");
return 0;
}
my %results = (
'id' => $id,
'prot_dom' => $prot_dom,
'nuc_dom' => $nuc_dom,
'postPMax' => $postPMax,
'postNMax' => $postNmax,
);
$self->output(\%results);
return 1;
}
=head2 files_to_be_deleted
Arg [1] : scalar - filename
Description: marks the PSILC output files for deletion
Returntype : none
Exceptions : none
Caller : general
=cut
sub files_to_be_deleted{
my ($self,$filename) = @_;
my $dir = $self->workdir;
my $domains = $self->domains;
$domains =~ s/PF.+\t//;
chomp $domains;
# Break filename into its component parts
my @fnc = split /\./,$filename;
# $self->files_to_delete($filename.".aln");
$self->files_to_delete($filename.".out");
$self->files_to_delete($fnc[0].".nhx");
$self->files_to_delete("$dir/pfamA");
$self->files_to_delete("$dir/PSILC_WAG_HKY/domdom");
$self->files_to_delete("$dir/PSILC_WAG_HKY/posteriorN");
$self->files_to_delete("$dir/PSILC_WAG_HKY/posteriorP");
$self->files_to_delete("$dir/PSILC_WAG_HKY/psilcN");
$self->files_to_delete("$dir/PSILC_WAG_HKY/psilcP");
# $self->files_to_delete("$dir/PSILC_WAG_HKY/summary");
$self->files_to_delete("$dir/PSILC_WAG_HKY/$domains");
return 1;
}
=head2 output_dir
Arg [1] : scalar - input id of the anlysis
Description: Creates the output directory for the PSILC files
Returntype : none
Exceptions : none
Caller : general
=cut
sub output_dir{
my ($self,$input_id) = @_;
my $output_dir;
$output_dir = $self->id;
if ($self->psilc_work_dir){
system("mkdir $self->psilc_work_dir/$$input_id/$output_dir");
$self->workdir($self->psilc_work_dir."/$$input_id/$output_dir");
}
else{
$self->throw("Cannot make output directory\n");
}
return 1;
}
sub id {
my ($self) = @_;
if ($self->trans->stable_id){
return $self->trans->stable_id;
}
return $self->trans->dbID;
}
=head2 make_codon_based_alignment
Arg [1] : none
Description: Makes a dna alignment based on a protein alignment using
Bio::Align::Utilities DNA alignment is for the translateable part of the
transcript only
Returntype : none
Exceptions : none
Caller : general
=cut
sub make_codon_based_alignment{
my ($self) = @_;
my @aaseqs;
my $aaseq;
my %dnaseqs;
# make alignment file for output
my $filename = $self->queryfile.".aln";
my $alignIO = Bio::AlignIO->new
(
-file => ">$filename",
-format => "clustalw",
);
my $pep_alignIO = Bio::AlignIO->new
(
-file => ">$filename.pep",
-format => "clustalw",
);
# run clustal
my $clustalw = Bio::Tools::Run::Alignment::Clustalw->new();
# prepare sequences, aaseqs has the proteins used for the alignment
# dnaseqs is a hash of the tranlateable nucleotide sequence
# Both sets need to use transcript ids which as also used as the hash keys
$aaseq = $self->trans->translate;
# change id of translation to match transcript
$aaseq->display_id($self->id);
push @aaseqs,$aaseq;
$dnaseqs{$self->id} = Bio::Seq->new
(
-display_id => $self->id,
-seq => $self->trans->translateable_seq,
);
foreach my $homolog(@{$self->homologs}){
next if ($homolog->stable_id eq $self->id);
$aaseq = $homolog->translate;
# change id of translation to match transcript
$aaseq->display_id($homolog->stable_id);
push @aaseqs,$aaseq;
$dnaseqs{$homolog->stable_id} = Bio::Seq->new
(
-display_id => $homolog->stable_id,
-seq => $homolog->translateable_seq,
);
}
foreach my $seq (@aaseqs){
print $seq->display_id."\n";
}
my $alignment = $clustalw->align(\@aaseqs);
my $dna_aln = aa_to_dna_aln($alignment,\%dnaseqs);
foreach my $seq ($dna_aln->each_seq){
print $seq->display_id."\n";
}
$pep_alignIO->write_aln($alignment);
$alignIO->write_aln($dna_aln);
return 1;
}
#######################################
# Containers
=head2 trans
Arg [1] : array ref
Description: get/set trans set to run over
Returntype : array ref to Bio::EnsEMBL::Transcript objects
Exceptions : throws if not a Bio::EnsEMBL::Transcript
Caller : general
=cut
sub trans {
my ($self, $trans) = @_;
if ($trans) {
unless ($trans->isa("Bio::EnsEMBL::Transcript")){
$self->throw("Input isn't a Bio::EnsEMBL::Transcript, it is a $trans\n$@");
}
$self->{'_trans'} = $trans;
}
return $self->{'_trans'};
}
=head2 homologs
Arg [1] : array ref
Description: get/set gene set to run over
Returntype : array ref to Bio::EnsEMBL::Gene objects
Exceptions : throws if not a Bio::EnsEMBL::Gene
Caller : general
=cut
sub homologs {
my ($self, $homologs) = @_;
if ($homologs) {
foreach my $hom (@{$homologs}){
unless ($hom->isa("Bio::EnsEMBL::Transcript")){
$self->throw("Input isn't a Bio::EnsEMBL::Transcript, it is a $hom\n$@");
}
}
$self->{'_homologs'} = $homologs;
}
return $self->{'_homologs'};
}
=head2 domains
Arg [1] : array ref
Description: get/set pfam domain identifiers
Returntype : string of pfam identifiers
Exceptions : none
Caller : general
=cut
sub domains {
my ($self, $domains) = @_;
if ($domains) {
$self->{'_domains'} = $$domains;
}
return $self->{'_domains'};
}
=head2 output
Arg [1] : hash_ref
Description: overrides output array
Returntype : hash_ref
Exceptions : none
Caller : general
=cut
sub output {
my ($self, $hash_ref) = @_;
if ($hash_ref) {
$self->{'_output'} = $hash_ref;
}
return $self->{'_output'};
}
=head2 psilc_work_dir
Arg [1] : String
Description: path to work dir
Returntype : string
Exceptions : none
Caller : general
=cut
sub psilc_work_dir {
my ($self, $path) = @_;
if ($path) {
$self->{'_psilc_work_dir'} = $path;
}
return $self->{'_psilc_work_dir'};
}
1;
| mn1/ensembl-analysis | modules/Bio/EnsEMBL/Analysis/Runnable/PSILC.pm | Perl | apache-2.0 | 11,286 |
#
# Copyright 2015 SmartBear Software
#
# 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.
#
#
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
#
package WWW::SwaggerClient::ConversionApi;
require 5.6.0;
use strict;
use warnings;
use utf8;
use Exporter;
use Carp qw( croak );
use Log::Any qw($log);
use WWW::SwaggerClient::ApiClient;
use WWW::SwaggerClient::Configuration;
use base "Class::Data::Inheritable";
__PACKAGE__->mk_classdata('method_documentation' => {});
sub new {
my $class = shift;
my (%self) = (
'api_client' => WWW::SwaggerClient::ApiClient->instance,
@_
);
#my $self = {
# #api_client => $options->{api_client}
# api_client => $default_api_client
#};
bless \%self, $class;
}
#
# jobs_job_id_conversions_get
#
# Get list of conversions defined for the current job.
#
# @param string $job_id ID of job that needs to be fetched (required)
# @param string $x_oc_token Token for authentication for the current job (optional)
# @param string $x_oc_api_key Api key for the user to filter. (optional)
{
my $params = {
'job_id' => {
data_type => 'string',
description => 'ID of job that needs to be fetched',
required => '1',
},
'x_oc_token' => {
data_type => 'string',
description => 'Token for authentication for the current job',
required => '0',
},
'x_oc_api_key' => {
data_type => 'string',
description => 'Api key for the user to filter.',
required => '0',
},
};
__PACKAGE__->method_documentation->{ jobs_job_id_conversions_get } = {
summary => 'Get list of conversions defined for the current job.',
params => $params,
returns => 'ARRAY[Conversion]',
};
}
# @return ARRAY[Conversion]
#
sub jobs_job_id_conversions_get {
my ($self, %args) = @_;
# verify the required parameter 'job_id' is set
unless (exists $args{'job_id'}) {
croak("Missing the required parameter 'job_id' when calling jobs_job_id_conversions_get");
}
# parse inputs
my $_resource_path = '/jobs/{job_id}/conversions';
$_resource_path =~ s/{format}/json/; # default format to json
my $_method = 'GET';
my $query_params = {};
my $header_params = {};
my $form_params = {};
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept('application/json');
if ($_header_accept) {
$header_params->{'Accept'} = $_header_accept;
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json');
# header params
if ( exists $args{'x_oc_token'}) {
$header_params->{'X-Oc-Token'} = $self->{api_client}->to_header_value($args{'x_oc_token'});
}# header params
if ( exists $args{'x_oc_api_key'}) {
$header_params->{'X-Oc-Api-Key'} = $self->{api_client}->to_header_value($args{'x_oc_api_key'});
}
# path params
if ( exists $args{'job_id'}) {
my $_base_variable = "{" . "job_id" . "}";
my $_base_value = $self->{api_client}->to_path_value($args{'job_id'});
$_resource_path =~ s/$_base_variable/$_base_value/g;
}
my $_body_data;
# authentication setting, if any
my $auth_settings = [qw()];
# make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
return;
}
my $_response_object = $self->{api_client}->deserialize('ARRAY[Conversion]', $response);
return $_response_object;
}
#
# jobs_job_id_conversions_post
#
# Adds a new conversion to the given job.
#
# @param Conversion $body information for the conversion. (required)
# @param string $job_id ID of job that needs to be fetched (required)
# @param string $x_oc_token Token for authentication for the current job (optional)
# @param string $x_oc_api_key Api key for the user to filter. (optional)
{
my $params = {
'body' => {
data_type => 'Conversion',
description => 'information for the conversion.',
required => '1',
},
'job_id' => {
data_type => 'string',
description => 'ID of job that needs to be fetched',
required => '1',
},
'x_oc_token' => {
data_type => 'string',
description => 'Token for authentication for the current job',
required => '0',
},
'x_oc_api_key' => {
data_type => 'string',
description => 'Api key for the user to filter.',
required => '0',
},
};
__PACKAGE__->method_documentation->{ jobs_job_id_conversions_post } = {
summary => 'Adds a new conversion to the given job.',
params => $params,
returns => 'Conversion',
};
}
# @return Conversion
#
sub jobs_job_id_conversions_post {
my ($self, %args) = @_;
# verify the required parameter 'body' is set
unless (exists $args{'body'}) {
croak("Missing the required parameter 'body' when calling jobs_job_id_conversions_post");
}
# verify the required parameter 'job_id' is set
unless (exists $args{'job_id'}) {
croak("Missing the required parameter 'job_id' when calling jobs_job_id_conversions_post");
}
# parse inputs
my $_resource_path = '/jobs/{job_id}/conversions';
$_resource_path =~ s/{format}/json/; # default format to json
my $_method = 'POST';
my $query_params = {};
my $header_params = {};
my $form_params = {};
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept('application/json');
if ($_header_accept) {
$header_params->{'Accept'} = $_header_accept;
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json');
# header params
if ( exists $args{'x_oc_token'}) {
$header_params->{'X-Oc-Token'} = $self->{api_client}->to_header_value($args{'x_oc_token'});
}# header params
if ( exists $args{'x_oc_api_key'}) {
$header_params->{'X-Oc-Api-Key'} = $self->{api_client}->to_header_value($args{'x_oc_api_key'});
}
# path params
if ( exists $args{'job_id'}) {
my $_base_variable = "{" . "job_id" . "}";
my $_base_value = $self->{api_client}->to_path_value($args{'job_id'});
$_resource_path =~ s/$_base_variable/$_base_value/g;
}
my $_body_data;
# body params
if ( exists $args{'body'}) {
$_body_data = $args{'body'};
}
# authentication setting, if any
my $auth_settings = [qw()];
# make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
return;
}
my $_response_object = $self->{api_client}->deserialize('Conversion', $response);
return $_response_object;
}
#
# jobs_job_id_conversions_conversion_id_get
#
# Get list of conversions defined for the current job.
#
# @param string $job_id ID of job that needs to be fetched (required)
# @param string $conversion_id Identifier for the job conversion. (required)
# @param string $x_oc_token Token for authentication for the current job (optional)
# @param string $x_oc_api_key Api key for the user to filter. (optional)
{
my $params = {
'job_id' => {
data_type => 'string',
description => 'ID of job that needs to be fetched',
required => '1',
},
'conversion_id' => {
data_type => 'string',
description => 'Identifier for the job conversion.',
required => '1',
},
'x_oc_token' => {
data_type => 'string',
description => 'Token for authentication for the current job',
required => '0',
},
'x_oc_api_key' => {
data_type => 'string',
description => 'Api key for the user to filter.',
required => '0',
},
};
__PACKAGE__->method_documentation->{ jobs_job_id_conversions_conversion_id_get } = {
summary => 'Get list of conversions defined for the current job.',
params => $params,
returns => 'Conversion',
};
}
# @return Conversion
#
sub jobs_job_id_conversions_conversion_id_get {
my ($self, %args) = @_;
# verify the required parameter 'job_id' is set
unless (exists $args{'job_id'}) {
croak("Missing the required parameter 'job_id' when calling jobs_job_id_conversions_conversion_id_get");
}
# verify the required parameter 'conversion_id' is set
unless (exists $args{'conversion_id'}) {
croak("Missing the required parameter 'conversion_id' when calling jobs_job_id_conversions_conversion_id_get");
}
# parse inputs
my $_resource_path = '/jobs/{job_id}/conversions/{conversion_id}';
$_resource_path =~ s/{format}/json/; # default format to json
my $_method = 'GET';
my $query_params = {};
my $header_params = {};
my $form_params = {};
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept('application/json');
if ($_header_accept) {
$header_params->{'Accept'} = $_header_accept;
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json');
# header params
if ( exists $args{'x_oc_token'}) {
$header_params->{'X-Oc-Token'} = $self->{api_client}->to_header_value($args{'x_oc_token'});
}# header params
if ( exists $args{'x_oc_api_key'}) {
$header_params->{'X-Oc-Api-Key'} = $self->{api_client}->to_header_value($args{'x_oc_api_key'});
}
# path params
if ( exists $args{'job_id'}) {
my $_base_variable = "{" . "job_id" . "}";
my $_base_value = $self->{api_client}->to_path_value($args{'job_id'});
$_resource_path =~ s/$_base_variable/$_base_value/g;
}# path params
if ( exists $args{'conversion_id'}) {
my $_base_variable = "{" . "conversion_id" . "}";
my $_base_value = $self->{api_client}->to_path_value($args{'conversion_id'});
$_resource_path =~ s/$_base_variable/$_base_value/g;
}
my $_body_data;
# authentication setting, if any
my $auth_settings = [qw()];
# make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
return;
}
my $_response_object = $self->{api_client}->deserialize('Conversion', $response);
return $_response_object;
}
#
# jobs_job_id_conversions_conversion_id_delete
#
# Removes the conversion for a job.
#
# @param string $job_id ID of job that needs to be fetched (required)
# @param string $conversion_id Identifier for the job conversion. (required)
# @param string $x_oc_token Token for authentication for the current job (optional)
# @param string $x_oc_api_key Api key for the user to filter. (optional)
{
my $params = {
'job_id' => {
data_type => 'string',
description => 'ID of job that needs to be fetched',
required => '1',
},
'conversion_id' => {
data_type => 'string',
description => 'Identifier for the job conversion.',
required => '1',
},
'x_oc_token' => {
data_type => 'string',
description => 'Token for authentication for the current job',
required => '0',
},
'x_oc_api_key' => {
data_type => 'string',
description => 'Api key for the user to filter.',
required => '0',
},
};
__PACKAGE__->method_documentation->{ jobs_job_id_conversions_conversion_id_delete } = {
summary => 'Removes the conversion for a job.',
params => $params,
returns => 'Conversion',
};
}
# @return Conversion
#
sub jobs_job_id_conversions_conversion_id_delete {
my ($self, %args) = @_;
# verify the required parameter 'job_id' is set
unless (exists $args{'job_id'}) {
croak("Missing the required parameter 'job_id' when calling jobs_job_id_conversions_conversion_id_delete");
}
# verify the required parameter 'conversion_id' is set
unless (exists $args{'conversion_id'}) {
croak("Missing the required parameter 'conversion_id' when calling jobs_job_id_conversions_conversion_id_delete");
}
# parse inputs
my $_resource_path = '/jobs/{job_id}/conversions/{conversion_id}';
$_resource_path =~ s/{format}/json/; # default format to json
my $_method = 'DELETE';
my $query_params = {};
my $header_params = {};
my $form_params = {};
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept('application/json');
if ($_header_accept) {
$header_params->{'Accept'} = $_header_accept;
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json');
# header params
if ( exists $args{'x_oc_token'}) {
$header_params->{'X-Oc-Token'} = $self->{api_client}->to_header_value($args{'x_oc_token'});
}# header params
if ( exists $args{'x_oc_api_key'}) {
$header_params->{'X-Oc-Api-Key'} = $self->{api_client}->to_header_value($args{'x_oc_api_key'});
}
# path params
if ( exists $args{'job_id'}) {
my $_base_variable = "{" . "job_id" . "}";
my $_base_value = $self->{api_client}->to_path_value($args{'job_id'});
$_resource_path =~ s/$_base_variable/$_base_value/g;
}# path params
if ( exists $args{'conversion_id'}) {
my $_base_variable = "{" . "conversion_id" . "}";
my $_base_value = $self->{api_client}->to_path_value($args{'conversion_id'});
$_resource_path =~ s/$_base_variable/$_base_value/g;
}
my $_body_data;
# authentication setting, if any
my $auth_settings = [qw()];
# make the API Call
my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
return;
}
my $_response_object = $self->{api_client}->deserialize('Conversion', $response);
return $_response_object;
}
1;
| onlineconvert/onlineconvert-api-sdk-perl | lib/WWW/SwaggerClient/ConversionApi.pm | Perl | apache-2.0 | 15,345 |
#!/usr/bin/perl
&usage, exit 1 if ($#ARGV+1) != 2;
my $ConfigFile = shift;
my $CMakeListFile = shift;
my $CMakeListFile_Tmp = "CMakeLists.txt_tmp";
my $CMakeListFile_Build = "CMakeLists.txt_build";
my %CompileParameter = {};
my $Key;
my $Value;
my $Endian = "BIG";
my $Cmd;
open CONFIG, "<$ConfigFile" or die "Cannot open $ConfigFile: $!";
while(<CONFIG>) {
if(/^\s*(\w+)\s*=\s*([^\s]+)\n$/) {
$Key = $1;
$Value = $2;
$CompileParameter{$Key} = $Value;
if($Value =~ /\$\((\w+)\)/) {
$CompileParameter{$Key} = $`. $CompileParameter{$1} . $';
}
}
}
foreach $k (keys %CompileParameter) {
if($k =~ /RTP_ENDIAN/) {
if($CompileParameter{$k} =~ /LITTLE/) {
$Endian = "LITTLE";
}
}
if($k =~ /RTP_JTHREAD/) {
if($CompileParameter{$k} =~ /ENABLE/) {
$CompileParameter{$k} = "1";
} else {
$CompileParameter{$k} = "0";
}
}
}
close CONFIG;
my $CmakeConfig = "./cmake_config.mips";
my $CmakeConfigBuild = "./cmake_config_build.mips";
open CONFIG_CMAKE, "<$CmakeConfig" or die "Cannot open $CmakeConfig: $!";
open CONFIG_CMAKE_BUILD, ">$CmakeConfigBuild" or die "Cannot open $CmakeConfigBuild: $!";
while(<CONFIG_CMAKE>) {
if(s/TOOLCHAIN_DIR\s*<SET_VALUE>\s*/TOOLCHAIN_DIR $CompileParameter{"CROSS_COMPILE_DIR"}/) {
} elsif(s/CMAKE_C_COMPILER\s*<SET_VALUE>\s*/CMAKE_C_COMPILER $CompileParameter{"C_COMPILER"}/) {
} elsif(s/CMAKE_CXX_COMPILER\s*<SET_VALUE>\s*/CMAKE_CXX_COMPILER $CompileParameter{"CPLUSPLUS_COMPILER"}/) {
} elsif(s/JTHREAD_FOUND\s*<BOOL>\s*/JTHREAD_FOUND $CompileParameter{"RTP_JTHREAD"}/) {
}
print CONFIG_CMAKE_BUILD $_;
}
close CONFIG_CMAKE;
close CONFIG_CMAKE_BUILD;
$Cmd = "cat $CmakeConfigBuild $CMakeListFile > $CMakeListFile_Tmp";
system($Cmd);
open CMAKE_LIST_FILE_TMP, "<$CMakeListFile_Tmp" or die "Cannot open $CMakeListFile_Tmp: $!";
open CMAKE_LIST_FILE_BUILD, ">$CMakeListFile_Build" or die "Cannot open $CMakeListFile_Build: $!";
while(<CMAKE_LIST_FILE_TMP>) {
my $l = $_;
if($Endian =~ "LITTLE") {
if($l =~ "#define RTP_BIG_ENDIAN") {
$l = "# $l";
}
}
print CMAKE_LIST_FILE_BUILD $l;
}
close CMAKE_LIST_FILE_TMP;
close CMAKE_LIST_FILE_BUILD;
$Cmd = "cp $CMakeListFile_Build ../CMakeLists.txt";
system($Cmd);
unlink $CMakeListFile_Tmp, $CMakeListFile_Build;
sub usage {
print "perl config_armlinux.pl config.<os-platform>\n";
}
| Ansersion/myRtspClient | third_party/JRTPLIB/myRtspClientConfig/config_mips.pl | Perl | apache-2.0 | 2,337 |
#!/usr/bin/env perl
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2022] EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
use warnings ;
use strict;
use Getopt::Long qw(:config no_ignore_case);
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Analysis::Tools::Utilities;
use Bio::EnsEMBL::Utils::Exception;
use Bio::EnsEMBL::Analysis::Config::Databases;
my $host;
my $port=3306;
my $dbname;
my $user;
my $pass;
my $config_dbname;
my $seq_region;
my $coord_system = 'toplevel';
my $transcript = 1;
my $gene = 1;
my $write;
GetOptions(
'dbhost|host|h:s' => \$host,
'dbport|port|P:n' => \$port,
'dbname|db|D:s' => \$dbname,
'dbuser|user|u:s' => \$user,
'dbpass|pass|p:s' => \$pass,
'config_dbname:s' => \$config_dbname,
'seq_region_name:s' => \$seq_region,
'coord_system:s' => \$coord_system,
'write!' => \$write,
);
my $db;
if($config_dbname){
$db = get_db_adaptor_by_string($config_dbname);
}elsif($dbname && $host){
$db = new Bio::EnsEMBL::DBSQL::DBAdaptor(
-host => $host,
-user => $user,
-port => $port,
-dbname => $dbname,
-pass => $pass,
);
}else{
throw("Need to pass either -dbhost $host and -dbname $dbname or ".
"-config_dbname $config_dbname for the script to work");
}
print "Have database ".$db."\n";
my $sa = $db->get_SliceAdaptor;
my $slices;
if($seq_region){
my $slice = $sa->fetch_by_region($coord_system, $seq_region);
push(@$slices, $slice);
}else{
$slices = $sa->fetch_all($coord_system);
}
print "Have ".@$slices." slices\n";
my %attributes;
my $aa = $db->get_AttributeAdaptor;
SLICE:while(my $slice = shift(@$slices)){
print "Looking at ".$slice->name."\n";
my $genes = $slice->get_all_Genes;
print "Have ".@$genes." genes\n";
GENE:while(my $gene = shift(@$genes)){
if(!$attributes{$gene->biotype}){
my $attrib = create_Attribute($gene->biotype);
$attributes{$gene->biotype} = $attrib;
}
my $attrib = $attributes{$gene->biotype};
$gene->add_Attributes($attrib);
if($write){
$aa->store_on_Gene($gene->dbID, [$attrib]);
}
foreach my $transcript(@{$gene->get_all_Transcripts}){
if(!$attributes{$transcript->biotype}){
my $attrib = create_Attribute($transcript->biotype);
$attributes{$transcript->biotype} = $attrib;
}
my $attrib = $attributes{$transcript->biotype};
$transcript->add_Attributes($attrib);
if($write){
$aa->store_on_Transcript($transcript->dbID, [$attrib]);
}
}
}
}
sub create_Attribute{
my ($reason, $adaptor) = @_;
#print "Creating attribute for ".$reason."\n";
my $sql = "select attrib_type_id from attrib_type where code = ?";
my $sth = $aa->dbc->prepare($sql);
my $length = length($reason);
my $code;
if($length >= 16){
CODE:foreach (my $offset = 15;$offset > 0; $offset--){
#print "Looking at ".$offset." compared to ".$length."\n";
my $real_offset = $offset - $length;
$code = substr($reason, 0, $real_offset);
throw("Still have a ".$code." which is too long from ".$reason." ".
"using ".$real_offset) if(length($code) >= 16);
#print "Executing sql\n";
$sth->execute($code);
#print "RUNNING ".$sql." with ".$code."\n";
my ($id) = $sth->fetchrow;
#print "HAVE found ".$id." id\n" if($id);
last CODE if(!$id);
}
}else{
$code = $reason;
}
my $attrib = Bio::EnsEMBL::Attribute->new(
-code => $code,
-name => $reason,
-description => $reason,
-value => $reason,
);
return $attrib;
}
| Ensembl/ensembl-analysis | scripts/genebuild/make_biotypes_attributes.pl | Perl | apache-2.0 | 4,717 |
new9(A,B,C,D,E,F) :- B=0.
new9(A,B,C,D,E,F) :- G=1+E, B=< -1, new5(A,C,D,G,F).
new9(A,B,C,D,E,F) :- G=1+E, B>=1, new5(A,C,D,G,F).
new7(A,B,C,D,E) :- F=1, B-D=<0, new9(A,F,B,C,D,E).
new7(A,B,C,D,E) :- F=0, B-D>=1, new9(A,F,B,C,D,E).
new5(A,B,C,D,E) :- D-E=< -1, new7(A,B,C,D,E).
new5(A,B,C,D,E) :- F=1+C, D-E>=0, new4(A,B,F,D,E).
new4(A,B,C,D,E) :- C-E=< -1, new5(A,B,C,C,E).
new4(A,B,C,D,E) :- F=1+B, C-E>=0, new3(A,F,C,D,E).
new3(A,B,C,D,E) :- B-E=< -1, new4(A,B,B,D,E).
new2(A) :- B=0, new3(A,B,C,D,E).
new1 :- new2(A).
false :- new1.
| bishoksan/RAHFT | benchmarks_scp/misc/programs-clp/INVGEN-nested5.map.c.map.pl | Perl | apache-2.0 | 537 |
use Paws::JsonParamsService::Method2;
package Paws::QueryParamsService;
use Moose;
sub service { 'queryparams' }
sub version { '2010-03-31' }
sub flattened_arrays { 0 }
has max_attempts => (is => 'ro', isa => 'Int', default => 5);
has retry => (is => 'ro', isa => 'HashRef', default => sub {
{ base => 'rand', type => 'exponential', growth_factor => 2 }
});
has retriables => (is => 'ro', isa => 'ArrayRef', default => sub { [
] });
with 'Paws::API::Caller', 'Paws::API::EndpointResolver', 'Paws::Net::V4Signature', 'Paws::Net::QueryCaller', 'Paws::Net::XMLResponse';
sub Method1 {
my $self = shift;
my $call_object = $self->new_with_coercions('Paws::JsonParamsService::Method1', @_);
return $self->caller->do_call($self, $call_object);
}
sub Method2 {
my $self = shift;
my $call_object = $self->new_with_coercions('Paws::JsonParamsService::Method2', @_);
return $self->caller->do_call($self, $call_object);
}
sub Method3 {
my $self = shift;
my $call_object = $self->new_with_coercions('Paws::JsonParamsService::Method3', @_);
return $self->caller->do_call($self, $call_object);
}
sub operations { return qw/Method1 Method2 Method3/ }
1;
| ioanrogers/aws-sdk-perl | t/lib/Paws/QueryParamsService.pm | Perl | apache-2.0 | 1,220 |
package Paws::ELBv2::ModifyTargetGroup;
use Moose;
has HealthCheckIntervalSeconds => (is => 'ro', isa => 'Int');
has HealthCheckPath => (is => 'ro', isa => 'Str');
has HealthCheckPort => (is => 'ro', isa => 'Str');
has HealthCheckProtocol => (is => 'ro', isa => 'Str');
has HealthCheckTimeoutSeconds => (is => 'ro', isa => 'Int');
has HealthyThresholdCount => (is => 'ro', isa => 'Int');
has Matcher => (is => 'ro', isa => 'Paws::ELBv2::Matcher');
has TargetGroupArn => (is => 'ro', isa => 'Str', required => 1);
has UnhealthyThresholdCount => (is => 'ro', isa => 'Int');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'ModifyTargetGroup');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::ELBv2::ModifyTargetGroupOutput');
class_has _result_key => (isa => 'Str', is => 'ro', default => 'ModifyTargetGroupResult');
1;
### main pod documentation begin ###
=head1 NAME
Paws::ELBv2::ModifyTargetGroup - Arguments for method ModifyTargetGroup on Paws::ELBv2
=head1 DESCRIPTION
This class represents the parameters used for calling the method ModifyTargetGroup on the
Elastic Load Balancing service. Use the attributes of this class
as arguments to method ModifyTargetGroup.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ModifyTargetGroup.
As an example:
$service_obj->ModifyTargetGroup(Att1 => $value1, Att2 => $value2, ...);
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
=head1 ATTRIBUTES
=head2 HealthCheckIntervalSeconds => Int
The approximate amount of time, in seconds, between health checks of an
individual target. For Application Load Balancers, the range is 5 to
300 seconds. For Network Load Balancers, the supported values are 10 or
30 seconds.
=head2 HealthCheckPath => Str
[HTTP/HTTPS health checks] The ping path that is the destination for
the health check request.
=head2 HealthCheckPort => Str
The port the load balancer uses when performing health checks on
targets.
=head2 HealthCheckProtocol => Str
The protocol the load balancer uses when performing health checks on
targets. The TCP protocol is supported only if the protocol of the
target group is TCP.
Valid values are: C<"HTTP">, C<"HTTPS">, C<"TCP">
=head2 HealthCheckTimeoutSeconds => Int
[HTTP/HTTPS health checks] The amount of time, in seconds, during which
no response means a failed health check.
=head2 HealthyThresholdCount => Int
The number of consecutive health checks successes required before
considering an unhealthy target healthy.
=head2 Matcher => L<Paws::ELBv2::Matcher>
[HTTP/HTTPS health checks] The HTTP codes to use when checking for a
successful response from a target.
=head2 B<REQUIRED> TargetGroupArn => Str
The Amazon Resource Name (ARN) of the target group.
=head2 UnhealthyThresholdCount => Int
The number of consecutive health check failures required before
considering the target unhealthy. For Network Load Balancers, this
value must be the same as the healthy threshold count.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method ModifyTargetGroup in L<Paws::ELBv2>
=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/ELBv2/ModifyTargetGroup.pm | Perl | apache-2.0 | 3,587 |
package VMOMI::ArrayOfNetIpStackInfoDefaultRouter;
use parent 'VMOMI::ComplexType';
use strict;
use warnings;
our @class_ancestors = ( );
our @class_members = (
['NetIpStackInfoDefaultRouter', 'NetIpStackInfoDefaultRouter', 1, 1],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| stumpr/p5-vmomi | lib/VMOMI/ArrayOfNetIpStackInfoDefaultRouter.pm | Perl | apache-2.0 | 459 |
#!/usr/bin/perl
use strict;
use warnings;
use Net::Proxy;
# show some information on STDERR
Net::Proxy->set_verbosity(1);
# run this on your workstation
my $proxy = Net::Proxy->new(
{ in =>
{
# local port for local SSH client
port => 2222,
type => 'tcp',
},
out =>
{
host => 'home.example.com',
port => 443,
proxy_host => 'proxy.company.com',
proxy_port => 8080,
proxy_user => 'id23494',
proxy_pass => 's3kr3t',
proxy_agent => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)',
},
}
);
$proxy->register();
Net::Proxy->mainloop();
| jmcveigh/komodo-tools | scripts/perl/run_two_services_on_a_single_tcp_port/verbose_proxy.pl | Perl | bsd-2-clause | 723 |
#!/usr/bin/perl -w
# PPath@Cornell
# Surya Saha Mar 18, 2011
use strict;
use warnings;
use Getopt::Long;
use POSIX;
eval {
require Bio::SearchIO;
require Bio::SeqIO;
};
use Bio::SearchIO;
use Bio::SeqIO;
=head1 NAME
getAlignedPairs_blastn.v1.pl - Get the pairs which align to the reference genome with correct orientation
=head1 SYNOPSIS
getAlignedPairs.v1.pl -blastnrep blastn.out -pairedreads file -out file -outformat Fasta/fastq
=head1 DESCRIPTION
This script reads in blast output of paired read fasta file to reference genomes and pulls out all
pairs that align with correct orientation and spacing. It then goes through the paired reads file
and pulls out all qualifying read pairs and writes out selected paired reads. also writes out a XLS
file of mapping info. Using hash of 2D arrays to store blast hits.
=head1 VERSION HISTORY
Version 1: Only pulls out reads that match to wolbachia genomes. Handles only innies, i.e. short insert
PE libs or revcomped MP libs without any PE contamination.
BUG: Counting space between end of fwd and end of rev instead of end of fwd and start of rev
=head1 TODO
1. Figure out how to use outlier and other endosymbiont results
2. How to screen against host genome?
=head1 COMMAND-LINE OPTIONS
Command-line options can be abbreviated to single-letter options, e.g. -f instead of --file. Some options
are mandatory (see below).
--blastnrep <blastn.out> Blastn report file (required)
--matlen <100> Minimum match length(bp), if identical match is reqd for 100 bp, then 100 (required)
--pairedreads <file> Input sequence file (required)
--readlen <100> Length of input reads (required)
--inslen <int> Insert length in bp (required)
--stdev <float> Standard deviation of insert length in bp (required)
--out <file> Output reads core file name (required)
--format <Fasta/fastq> Format of input/output files (required)
=head1 AUTHOR
Surya Saha, ss2489@cornell.edu
=cut
my ($i,$j,$k,$l,$m,$blastnrep,$pairedreads,$rlen,$mlen,$inslen,$stdev,$format,$out,@temp,$flag,
@temp1,$minins,$maxins,$ctr,%genomes,$debug);
#remember cmd line..KLUDGE!!
$j=''; foreach $i (@ARGV){ $j.="$i ";}
GetOptions (
'blastnrep=s' => \$blastnrep,
'matlen=i' => \$mlen,
'pairedreads=s' => \$pairedreads,
'readlen=i' => \$rlen,
'inslen=i' => \$inslen,
'stdev=f' => \$stdev,
'out=s' => \$out,
'format=s' => \$format,
'debug:i' => \$debug,) or (system('pod2text',$0), exit 1);
# defaults and checks
defined($blastnrep) or (system('pod2text',$0), exit 1);
if (!(-e $blastnrep)){print STDERR "$blastnrep not found: $!\n"; exit 1;}
$out ||= "aligned.${pairedreads}";
if(($format ne 'Fasta') && ($format ne 'fastq')){
system('pod2text',$0), exit 1;
}
unless(open(XLS,">mappingInfo.${out}.xls")){print "not able to open mappingInfo.${out}.xls\n\n";exit 1;}
print XLS "\t\tMAPPING REPORT\n\n\nParams: $j\n";
print XLS "\nCombined reads:\t$out\nBlastn:\t$blastnrep\nFwd reads:\tfwd.wol.${out}\nRev reads:\trev.wol.${out}\n";
$minins=$inslen-(2*$rlen)-$stdev;#now insert size does not include read lengths
$maxins=$inslen-(2*$rlen)+$stdev;
print STDERR "Minimum match cutoff: $mlen bp ...\n";
print STDERR "Insert size range: $minins to $maxins bp \(exluding read lengths, negative value implies overlap of paired reads\)...\n";
if($format eq 'fastq'){print STDERR "Presuming $pairedreads is in $format format\n\n";}
#reference and outlier genome list
%genomes = (
'gi|50083297|ref|NC_005966.1| Acinetobacter sp. ADP1 chromosome, complete genome' => 'dce',
'gi|213155358|ref|NC_011585.1| Acinetobacter baumannii AB0057 plasmid pAB0057, complete sequence' => 'dce',
'gi|213155370|ref|NC_011586.1| Acinetobacter baumannii AB0057, complete genome' => 'dce',
'gi|215481761|ref|NC_011595.1| Acinetobacter baumannii AB307-0294, complete genome' => 'dce',
'gi|184159988|ref|NC_010605.1| Acinetobacter baumannii ACICU plasmid pACICU1, complete sequence' => 'dce',
'gi|184160017|ref|NC_010606.1| Acinetobacter baumannii ACICU plasmid pACICU2, complete sequence' => 'dce',
'gi|184156320|ref|NC_010611.1| Acinetobacter baumannii ACICU, complete genome' => 'dce',
'gi|126640097|ref|NC_009083.1| Acinetobacter baumannii ATCC 17978 plasmid pAB1, complete sequence' => 'dce',
'gi|126640109|ref|NC_009084.1| Acinetobacter baumannii ATCC 17978 plasmid pAB2, complete sequence' => 'dce',
'gi|126640115|ref|NC_009085.1| Acinetobacter baumannii ATCC 17978, complete genome' => 'dce',
'gi|169302972|ref|NC_010401.1| Acinetobacter baumannii AYE plasmid p1ABAYE, complete sequence' => 'dce',
'gi|169302980|ref|NC_010402.1| Acinetobacter baumannii AYE plasmid p2ABAYE, complete sequence' => 'dce',
'gi|169302992|ref|NC_010403.1| Acinetobacter baumannii AYE plasmid p4ABAYE, complete sequence' => 'dce',
'gi|169786889|ref|NC_010404.1| Acinetobacter baumannii AYE plasmid p3ABAYE, complete sequence' => 'dce',
'gi|169794206|ref|NC_010410.1| Acinetobacter baumannii AYE, complete genome' => 'dce',
'gi|169302963|ref|NC_010395.1| Acinetobacter baumannii SDF plasmid p1ABSDF, complete sequence' => 'dce',
'gi|169786833|ref|NC_010396.1| Acinetobacter baumannii SDF plasmid p2ABSDF, complete sequence' => 'dce',
'gi|169786864|ref|NC_010398.1| Acinetobacter baumannii SDF plasmid p3ABSDF, complete sequence' => 'dce',
'gi|169632029|ref|NC_010400.1| Acinetobacter baumannii SDF, complete genome' => 'dce',
'gi|299768250|ref|NC_014259.1| Acinetobacter sp. DR1 chromosome, complete genome' => 'dce',
'gi|82701135|ref|NC_007614.1| Nitrosospira multiformis ATCC 25196 chromosome, complete sequence' => 'dce',
'gi|82703893|ref|NC_007615.1| Nitrosospira multiformis ATCC 25196 plasmid 1, complete sequence' => 'dce',
'gi|82703911|ref|NC_007616.1| Nitrosospira multiformis ATCC 25196 plasmid 2, complete sequence' => 'dce',
'gi|82703928|ref|NC_007617.1| Nitrosospira multiformis ATCC 25196 plasmid 3, complete sequence' => 'dce',
'gi|124265193|ref|NC_008825.1| Methylibium petroleiphilum PM1 chromosome, complete genome' => 'bce',
'gi|124262546|ref|NC_008826.1| Methylibium petroleiphilum PM1 plasmid RPME01, complete sequence' => 'bce',
'gi|152979768|ref|NC_009659.1| Janthinobacterium sp. Marseille, complete genome' => 'dce',
'gi|134093294|ref|NC_009138.1| Herminiimonas arsenicoxydans chromosome, complete genome' => 'dce',
'gi|300309346|ref|NC_014323.1| Herbaspirillum seropedicae SmR1 chromosome, complete genome' => 'dce',
'gi|307069503|ref|NC_014497.1| Candidatus Zinderia insecticola CARI chromosome, complete genome' => 'dce',
'gi|116334902|ref|NC_008512.1| Candidatus Carsonella ruddii PV, complete genome' => 'bce',
'gi|305672698|ref|NC_014479.1| Bacillus subtilis subsp. spizizenii str. W23 chromosome, complete genome' => 'o',
'gi|49175990|ref|NC_000913.2| Escherichia coli str. K-12 substr. MG1655 chromosome, complete genome' => 'o',
'gi|190570478|ref|NC_010981.1| Wolbachia endosymbiont of Culex quinquefasciatus Pel, complete genome' => 'w',
'gi|42519920|ref|NC_002978.6| Wolbachia endosymbiont of Drosophila melanogaster, complete genome' => 'w',
'gi|58584261|ref|NC_006833.1| Wolbachia endosymbiont strain TRS of Brugia malayi, complete genome' => 'w',
'gi|225629872|ref|NC_012416.1| Wolbachia sp. wRi, complete genome' => 'w',);
#read in the blastn report and record qualifying reads
my(%blastnwreads,%blastndcereads,$in,$result,$hit,$hsp,$tothsplen);
$in = new Bio::SearchIO(-format => 'blast', -file => $blastnrep);
$ctr=0; print STDERR "Reading blastn results..\n";
while($result = $in->next_result) {## $result is a Bio::Search::Result::ResultI compliant object
if($result->no_hits_found()){next;}
#get hit data
if($result->num_hits>0){
#debug
if($debug){print STDERR "For ",$result->query_name,"\n";}
@temp=();
while($hit = $result->next_hit ) {# $hit is a Bio::Search::Hit::HitI compliant object
$i=$hit->name().' '.$hit->description();#CHECK
if($genomes{$i} eq 'w'){#if hit is a wolbachia species
while($hsp = $hit->next_hsp()){# $hsp is Bio::Search::HSP::HSPI compliant object
if($hsp->length('query') >= $mlen){#if length of read involved in HSP > match length
#record name, ref genome strand/end/
#recording end since the inslen for each lib does not include read lengths
push @temp,$hit->name(); push @temp,$hsp->strand('subject');
push @temp,$hsp->end('subject');
}
}
}
}
#debug
if($debug){foreach $i (0..$#temp){if(($i%3==0)&&($i!=0)){print STDERR "\n"; } print STDERR "\t$temp[$i]";}}
#store in hash
$blastnwreads{$result->query_name()}=[@temp];
$ctr++; if($ctr%100000 == 0){print STDERR "$ctr..";}
#debug
if($debug){print STDERR "\n";}
}
}
print STDERR "Read $ctr blastn results..\n";
if($debug){ $i=scalar (keys (%blastnwreads)); print STDERR "Length of blastnwreads hash: $i\n";}
#compute the qualifying reads
my(%qualwreads,%qualdcereads,$fwd,@fwdarr,$rev,@revarr);
$ctr=0; print STDERR "Searching for qualifying read pairs..";
if($debug){print STDERR "\n";}
while(($i,$j)=each(%blastnwreads)){
if($i=~ /1$/){#forward read
$fwd=$i; @fwdarr=@$j;
$i=~ s/1$/2/;
if(exists $blastnwreads{$i}){# get rev read data
$rev=$i; $j=$blastnwreads{$i}; @revarr=@$j;
#name,strand,location triplets in array
for($i=0;$i<@fwdarr;$i+=3){
for($j=0;$j<@revarr;$j+=3){
#if hit on same genome and diff strand and within range
if(($fwdarr[$i] eq $revarr[$j]) && ($fwdarr[$i+1] != $revarr[$j+1])){
#BUG counting space between end of fwd and end of rev instead of end of fwd and start of rev
#fwd on pos and rev on comp strand
if (($fwdarr[$i+1] == 1) && ($revarr[$j+1] == -1) && ($fwdarr[$i+2]+$minins <= $revarr[$j+2])
&& ($fwdarr[$i+2]+$maxins >= $revarr[$j+2])){
$qualwreads{$fwd}=$fwdarr[$i];#record fwd read name and genome it aligned to
$qualwreads{$rev}=$revarr[$j+2]-$fwdarr[$i+2];# rev read name and insert length
if($debug){print STDERR "\tSelected Fwd: $fwd and Rev: $rev with insert length: $qualwreads{$rev}\n";}
$ctr++; if($ctr%1000 == 0){print STDERR "$ctr..";} goto OUT1;#done for this pair so get out
}
#fwd on neg and rev on pos strand
elsif (($fwdarr[$i+1] == -1) && ($revarr[$j+1] == 1) && ($revarr[$j+2]+$minins <= $fwdarr[$i+2])
&& ($revarr[$j+2]+$maxins >= $fwdarr[$i+2])){
$qualwreads{$fwd}=$fwdarr[$i];#record fwd read name and genome it aligned to
$qualwreads{$rev}=$fwdarr[$i+2]-$revarr[$j+2];# rev read name and insert length
if($debug){print STDERR "\tSelected Fwd: $fwd and Rev: $rev with insert length: $qualwreads{$rev}\n";}
$ctr++; if($ctr%1000 == 0){print STDERR "$ctr..";} goto OUT1;#done for this pair so get out
}
else{
if($debug){print STDERR "\tRejected Fwd: $fwd and Rev: $rev due to \n\t\tinsert length: ",
$fwdarr[$i+2]-$revarr[$j+2],"\tFwd strand: ",$fwdarr[$i+1],"\tRev strand: ",$revarr[$j+1],"\n";}
}
}
}
}
}
OUT1:
#delete both reads from hash
delete $blastnwreads{$rev};
delete $blastnwreads{$fwd};
}
elsif($i=~ /2$/){#reverse read
$rev=$i; @revarr=@$j;
$i=~ s/2$/1/;
if(exists $blastnwreads{$i}){# get fwd read data
$fwd=$i; $j=$blastnwreads{$i}; @fwdarr=@$j;
#name,strand,location triplets in array
for($i=0;$i<@fwdarr;$i+=3){
for($j=0;$j<@revarr;$j+=3){
#if hit on same genome and diff strand and within range
if(($fwdarr[$i] eq $revarr[$j]) && ($fwdarr[$i+1] != $revarr[$j+1])){
#BUG counting space between end of fwd and end of rev instead of end of fwd and start of rev
#fwd on pos and rev on comp strand
if (($fwdarr[$i+1] == 1) && ($revarr[$j+1] == -1) && ($fwdarr[$i+2]+$minins <= $revarr[$j+2])
&& ($fwdarr[$i+2]+$maxins >= $revarr[$j+2])){
$qualwreads{$fwd}=$fwdarr[$i];#record fwd read name and genome it aligned to
$qualwreads{$rev}=$revarr[$j+2]-$fwdarr[$i+2];# rev read name and insert length
if($debug){print STDERR "\tSelected Fwd: $fwd and Rev: $rev with insert length: $qualwreads{$rev}\n";}
$ctr++; if($ctr%1000 == 0){print STDERR "$ctr..";} goto OUT2;#done for this pair so get out
}
#fwd on neg and rev on pos strand
elsif (($fwdarr[$i+1] == -1) && ($revarr[$j+1] == 1) && ($revarr[$j+2]+$minins <= $fwdarr[$i+2])
&& ($revarr[$j+2]+$maxins >= $fwdarr[$i+2])){
$qualwreads{$fwd}=$fwdarr[$i];#record fwd read name and genome it aligned to
$qualwreads{$rev}=$fwdarr[$i+2]-$revarr[$j+2];# rev read name and insert length
if($debug){print STDERR "\tSelected Fwd: $fwd and Rev: $rev with insert length: $qualwreads{$rev}\n";}
$ctr++; if($ctr%1000 == 0){print STDERR "$ctr..";} goto OUT2;#done for this pair so get out
}
else{
if($debug){print STDERR "\tRejected Fwd: $fwd and Rev: $rev due to \n\t\tinsert length: ",
$fwdarr[$i+2]-$revarr[$j+2],"\tFwd strand: ",$fwdarr[$i+1],"\tRev strand: ",$revarr[$j+1],"\n";}
}
}
}
}
}
OUT2:
#delete both reads from hash
delete $blastnwreads{$fwd};
delete $blastnwreads{$rev};
}
}
print STDERR "\nFound $ctr qualifying read pairs..\n";
#parse reads and write out the qualifying reads
my($fout,$rout,$seq,$uout);
$fout = Bio::SeqIO->new(-file=>">fwd.wol.${out}", -format=>$format);#NEED SEPARATE READS FILES??
$rout = Bio::SeqIO->new(-file=>">rev.wol.${out}", -format=>$format);
$uout = Bio::SeqIO->new(-file=>">unmapped.${out}", -format=>$format);
print XLS "\n\nPair No\tFwd read\tRev read\tGenome\tInsert size\n";
$i=$ctr=0; print STDERR "Writing qualifying and unmapped reads..";
$in = Bio::SeqIO->new(-file=>"<$pairedreads", -format=>$format);
while ($seq = $in->next_seq()){
if(exists $qualwreads{$seq->display_id()}){
if($seq->display_id()=~ /1$/){
if($format eq 'fastq'){ $fout->write_fastq($seq);}
else{$fout->write_seq($seq);}
$j=$qualwreads{$seq->display_id()};
}
elsif($seq->display_id()=~ /2$/){
if($format eq 'fastq'){ $rout->write_fastq($seq);}
else{$rout->write_seq($seq);}
$k=$seq->display_id(); $k=~ s/2$/1/;
#writing on rev since genome recorded from fwd
print XLS (($ctr+1)/2),"\t",$k,"\t",$seq->display_id(),"\t",$j,"\t",$qualwreads{$seq->display_id()},"\n";
}
$ctr++; if($ctr%10000 == 0){print STDERR "$ctr..";}
}
else{
if($format eq 'fastq'){ $uout->write_fastq($seq);}
else{$uout->write_seq($seq);}
$i++;
}
}
close(XLS);
print STDERR "\nWrote $ctr qualifying reads and $i unmapped reads\n";
my($user_t,$system_t,$cuser_t,$csystem_t); ($user_t,$system_t,$cuser_t,$csystem_t) = times;
print STDERR "System time for process: ",sprintf("%.3f",$system_t/3600)," hrs\n"; print STDERR "User time for process: ",sprintf("%.3f",$user_t/3600)," hrs\n";
exit; | suryasaha/NGS | archive/getAlignedPairs_blastn.v1.pl | Perl | bsd-2-clause | 14,734 |
# SNMP::Info::Layer3::PacketFront
# $Id$
#
# Copyright (c) 2011 Jeroen van Ingen
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the University of California, Santa Cruz nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
package SNMP::Info::Layer3::PacketFront;
use strict;
use Exporter;
use SNMP::Info::Layer3;
@SNMP::Info::Layer3::PacketFront::ISA = qw/SNMP::Info::Layer3 Exporter/;
@SNMP::Info::Layer3::PacketFront::EXPORT_OK = qw//;
use vars qw/$VERSION %GLOBALS %MIBS %FUNCS %MUNGE/;
$VERSION = '3.34';
%MIBS = (
%SNMP::Info::Layer3::MIBS,
'UCD-SNMP-MIB' => 'versionTag',
'NET-SNMP-TC' => 'netSnmpAgentOIDs',
'HOST-RESOURCES-MIB' => 'hrSystem',
'PACKETFRONT-PRODUCTS-MIB' => 'drg100',
'PACKETFRONT-DRG-MIB' => 'productName',
);
%GLOBALS = (
%SNMP::Info::Layer3::GLOBALS,
'snmpd_vers' => 'versionTag',
'hrSystemUptime' => 'hrSystemUptime',
);
%FUNCS = ( %SNMP::Info::Layer3::FUNCS, );
%MUNGE = ( %SNMP::Info::Layer3::MUNGE, );
sub vendor {
return 'packetfront';
}
sub os {
# Only DRGOS for now (not tested with other product lines than DRG series)
my $pfront = shift;
my $descr = $pfront->description();
if ( $descr =~ /drgos/i ) {
return 'drgos';
} else {
return;
}
}
sub os_ver {
my $pfront = shift;
my $descr = $pfront->description();
my $os_ver = undef;
if ( $descr =~ /Version:\sdrgos-(\w+)-([\w\-\.]+)/ ) {
$os_ver = $2;
}
return $os_ver;
}
sub serial {
my $pfront = shift;
return $pfront->productSerialNo();
}
sub i_ignore {
my $l3 = shift;
my $partial = shift;
my $interfaces = $l3->interfaces($partial) || {};
my %i_ignore;
foreach my $if ( keys %$interfaces ) {
# lo0 etc
if ( $interfaces->{$if} =~ /\blo\d*\b/i ) {
$i_ignore{$if}++;
}
}
return \%i_ignore;
}
sub layers {
my $pfront = shift;
my $layers = $pfront->SUPER::layers();
# Some models or softwware versions don't report L2 properly
# so add L2 capability to the output if the device has bridge ports.
my $bports = $pfront->b_ports();
if ($bports) {
my $l = substr $layers, 6, 1, "1";
}
return $layers;
}
1;
__END__
=head1 NAME
SNMP::Info::Layer3::PacketFront - SNMP Interface to PacketFront devices
=head1 AUTHORS
Jeroen van Ingen
initial version based on SNMP::Info::Layer3::NetSNMP by Bradley Baetz and Bill Fenner
=head1 SYNOPSIS
# Let SNMP::Info determine the correct subclass for you.
my $pfront = new SNMP::Info(
AutoSpecify => 1,
Debug => 1,
DestHost => 'myrouter',
Community => 'public',
Version => 2
)
or die "Can't connect to DestHost.\n";
my $class = $pfront->class();
print "SNMP::Info determined this device to fall under subclass : $class\n";
=head1 DESCRIPTION
Subclass for PacketFront devices
=head2 Inherited Classes
=over
=item SNMP::Info::Layer3
=back
=head2 Required MIBs
=over
=item F<UCD-SNMP-MIB>
=item F<NET-SNMP-TC>
=item F<HOST-RESOURCES-MIB>
=item F<PACKETFRONT-PRODUCTS-MIB>
=item F<PACKETFRONT-DRG-MIB>
=item Inherited Classes' MIBs
See L<SNMP::Info::Layer3> for its own MIB requirements.
=back
=head1 GLOBALS
These are methods that return scalar value from SNMP
=over
=item $pfront->vendor()
Returns C<'packetfront'>.
=item $pfront->os()
Returns the OS extracted from C<sysDescr>.
=item $pfront->os_ver()
Returns the software version extracted from C<sysDescr>.
=item $pfront->serial()
Returns the value of C<productSerialNo>.
=back
=head2 Globals imported from SNMP::Info::Layer3
See documentation in L<SNMP::Info::Layer3> for details.
=head1 TABLE ENTRIES
These are methods that return tables of information in the form of a reference
to a hash.
=head2 Overrides
=over
=item $pfront->i_ignore()
Returns reference to hash. Increments value of IID if port is to be ignored.
Ignores loopback
=item $pfront->layers()
L2 capability isn't always reported correctly by the device itself; what the
device reports is augmented with L2 capability if the device has bridge ports.
=back
=head2 Table Methods imported from SNMP::Info::Layer3
See documentation in L<SNMP::Info::Layer3> for details.
=cut
| 42wim/snmp-info | Info/Layer3/PacketFront.pm | Perl | bsd-3-clause | 5,860 |
#! /usr/bin/perl
use Getopt::Std;
getopts("qc:t:o:");
require $opt_c;
use File::Find;
use File::Glob;
use File::Basename;
use File::Path;
use IO::Compress::Gzip;
my $generator = "CDoc";
my $doc_type = $opt_t;
my $doc_output = $opt_o;
my $doc_quiet = $opt_q;
sub print_stdout {
if (!$doc_quiet) {
print STDOUT @ARGN;
}
}
sub read_source {
my $source_name = shift;
my $module = shift;
my $variables = shift;
my $macros = shift;
my $references = shift;
$$module{source} = basename($source_name);
$$module{name} = $$module{source};
$$module{name} =~ s/$source_pattern//;
my $in_block = 0;
my @block;
my $source = "";
open(source_file, $source_name);
while (<source_file>) {
$line = $_;
if ($line =~ /$comment_pattern/) {
my $comment = $1;
if ($comment =~ /$block_pattern/) {
$in_block = 1;
@block = ($1);
}
elsif ($in_block) {
@block = (@block, $1);
}
else {
@block = ($comment);
}
}
else {
my $brief;
my @macro_params = ();
my @non_directive = ();
my $in_variable = 0;
my $in_parameter = 0;
for my $block_line (@block) {
if ($block_line =~ /$directive_pattern/) {
my $directive = $1;
my $arguments = $2;
if ($directive =~ /$module_pattern/) {
$$module{name} = $arguments;
}
if ($directive =~ /$brief_pattern/) {
$brief = $arguments;
}
if ($directive =~ /$variable_pattern/) {
if ($arguments =~ /$variable_arguments_pattern/) {
$in_variable = 1;
my $variable_name = $1;
my $variable_description = $2;
@$variables = (@$variables, {
name => $variable_name,
description => $variable_description
});
}
}
else {
$in_variable = 0;
}
if ($directive =~ /$param_pattern/) {
$in_parameter = 1;
my $param_tag = $1;
my $param_spec = $2;
if ($arguments =~ /$param_arguments_pattern/) {
my $param_key = $1;
my $param_name = $2;
my $param_type = $value_pattern;
my $param_description = $3;
foreach my $param_type_key (keys %param_type_patterns) {
if ($param_spec =~ /$param_type_patterns{$param_type_key}/) {
$param_type = $param_type_key;
break;
}
}
@macro_params = (@macro_params, {
tag => $param_tag,
key => $param_key,
name => $param_name,
type => $param_type,
description => $param_description
});
}
}
else {
$in_parameter = 0;
}
}
else {
if ($in_variable) {
$$variables[$#$variables]->{description} .= " $block_line";
}
elsif ($in_parameter) {
$macro_params[$#macro_params]->{description} .= " $block_line";
}
else {
@non_directive = (@non_directive, $block_line);
}
}
}
if ($line =~ /$include_pattern/) {
my $include = $1;
if ($include =~ /$name_pattern/) {
$$references{$include} = $include;
}
}
elsif ($line =~ /$macro_pattern/) {
my $name = $1;
@$macros = (@$macros, {
name => $name,
brief => $brief,
description => join("\n", @non_directive),
parameters => [@macro_params]
});
}
elsif (!@$macros) {
if (!$$module{brief}) {
$$module{brief} = $brief;
}
if ($$module{brief} and !$$module{description}) {
$$module{description} = join("\n", @non_directive);
}
}
@block = ();
$in_block = 0;
}
}
close(source_file);
}
sub generate_man {
my $man_name = shift;
my $module = shift;
my $variables = shift;
my $macros = shift;
my $references = shift;
my $man = shift;
my @time = localtime();
my $date = sprintf("%d-%02d-%02d", $time[5]+1900, $time[4],
$time[3]);
$$man .= ".TH \"".uc($man_name)."\" $man_extension \"$date\" ".
"Linux \"$project_name Module Documentation\"\n";
$$man .= ".SH NAME\n";
my @macro_names;
for my $macro (@$macros) {
@macro_names = (@macro_names, $macro->{name});
}
$$man .= join(", ", @macro_names);
if ($$module{brief}) {
$$man .= " - $$module{brief}";
}
$$man .= "\n";
$$man .= ".SH SYNOPSIS\n";
$$man .= ".BR \"include($$module{name})\"\n";
$$man .= ".sp\n";
for my $macro (@$macros) {
my $macro_signature;
my @param_signatures;
for my $param (@{$macro->{parameters}}) {
my $param_signature;
if ($param->{name}) {
if ($param->{type} =~ /$list_pattern/) {
$param_signature = "\" $param->{name}1 \" [\" $param->{name}2 \" ...]";
}
elsif ($param->{type} =~ /$option_pattern/) {
$param_signature = "$param->{name}";
}
else {
$param_signature = "\" ".$param->{name}." \"";
}
}
if ($param->{key}) {
$param_signature = "$param->{key} $param_signature";
}
$param_signature =~ s/^\s*|\s*$//g;
if ($param->{tag} =~ /$optional_pattern/) {
$param_signature = "[$param_signature]";
}
@param_signatures = (@param_signatures, $param_signature);
}
$macro_signature = join(" ", @param_signatures);
$macro->{signature} = $macro_signature;
$$man .= ".BR \"$macro->{name}($macro->{signature})\"\n";
$$man .= ".br\n";
}
$$man .= ".SH DESCRIPTION\n";
if ($$module{description}) {
my $description = $$module{description};
$description =~ s/\n\n/\n.PP\n/g;
$$man .= "$description\n";
}
elsif ($$module{name} =~ /^$project_name$/) {
$$man .= "$project_summary\n";
}
else {
$$man .= "This module requires documentation.\n";
}
if (@$variables) {
$$man3 .= ".SH VARIABLES\n";
for my $variable (@$variables) {
$$man .= ".TP\n";
$$man .= ".B \"$variable->{name}\"\n";
if ($variable->{description}) {
$$man .= "$variable->{description}\n";
}
}
}
$$man .= ".SH MACROS\n";
for my $macro (@$macros) {
$$man .= ".TP\n";
$$man .= ".BI \"$macro->{name}($macro->{signature})\"\n";
$$man .= ".RS\n";
if ($macro->{brief}) {
$$man .= "$macro->{brief}\n";
$$man .= ".PP\n";
}
if ($macro->{description}) {
my $macro_description = $macro->{description};
$macro_description =~ s/\n\n/\n.PP\n/g;
$$man .= "$macro_description\n";
}
if (!($macro->{brief}) and !($macro->{description})) {
$$man .= "This macro requires documentation.\n";
}
for my $param (@{$macro->{parameters}}) {
$$man .= ".TP\n";
if ($param->{key}) {
$$man .= ".RI \"$param->{key} \"";
}
else {
$$man .= ".IR";
}
if ($param->{name}) {
if ($param->{type} =~ /$list_pattern/) {
$$man .= " \"$param->{name}1 $param->{name}2 \"...\n";
}
elsif ($param->{type} =~ /$option_pattern/) {
$$man .= " $param->{name}\n";
}
else {
$$man .= " \"$param->{name}\"\n";
}
}
else {
$$man .= "\n";
}
if ($param->{description}) {
my $param_description = $param->{description};
$param_description =~ s/\n\n/\n.PP\n/g;
$$man .= "$param_description\n";
}
else {
$$man .= "This parameter requires documentation.\n";
}
}
$$man .= ".RE\n";
}
$$man .= ".SH AUTHOR\n";
$$man .= "Written by $project_authors.\n";
$$man .= ".SH REPORTING BUGS\n";
$$man .= "Report bugs to <$project_contact>.\n";
$$man .= ".SH COPYRIGHT\n";
$$man .= "$project_name is published under the $project_license.\n";
for my $reference_key (keys %$references) {
$$man =~ s/$reference_key/$$references{$reference_key}/g;
}
$$man =~ s/\s*$man_reference_pattern\s*/\n.BR \1 \2\n/g;
if (%$references) {
my $see_also = join(" ", values(%$references));
$see_also =~ s/\s*$man_reference_pattern\s*/.BR \1 \2\n/g;
$$man .= ".SH SEE ALSO\n";
$$man .= $see_also;
}
$$man .= ".SH COLOPHON\n";
$$man .= "This page is part of version $project_version, ".
"release $project_release of the $project_name project.\n";
$$man .= ".PP\n";
$$man .= "A description of the project, and information about ".
"reporting bugs, can be found at ".$project_home.".\n";
}
sub find_source {
my %module;
my @variables;
my @macros;
my %references;
my $source_name = $File::Find::name;
return unless -f $source_name;
return unless basename($source_name) =~ /$find_pattern/;
print_stdout "$generator: Parsing ".basename($source_name)."\n";
read_source($source_name, \%module, \@variables, \@macros, \%references);
print_stdout "$generator: - $module{name}: ".@macros." macro(s), ".
keys(%references)." reference(s)\n";
my $man_name = lc($project_name);
if ($module{name} =~ /$name_pattern/) {
$man_name .= "_".lc($1);
}
foreach $reference_key (keys %references) {
if ($reference_key =~ /$name_pattern/) {
$references{$reference_key} = lc($project_name)."_".lc($1).
"($man_extension)";
}
}
my $man;
print_stdout "$generator: - $module{name}: Generating ".
"$man_name($man_extension)\n";
generate_man($man_name, \%module, \@variables, \@macros, \%references, \$man);
if ($doc_type =~ /man/) {
my $doc_name = "man${man_extension}/$man_name.$man_extension.gz";
print_stdout "Writing $doc_name\n";
mkpath("${doc_output}/man${man_extension}");
my $z = new IO::Compress::Gzip "$doc_output/$doc_name" or
die("Error: Failed to compress $doc_name!\n");
print $z $man;
close $z;
}
else {
my $doc_name = "$man_name.".lc($doc_type);
print_stdout "Writing $doc_name\n";
mkpath(${doc_output});
my $pid = open(file, "| $groff_executable -t -e -man -T${doc_type} - >".
"$doc_output/$doc_name") or
die("Error: Failed to execute groff!\n");
print file $man;
}
}
foreach $glob (@ARGV) {
find(\&find_source, $glob);
}
| NIFTi-Fraunhofer/nifti_arm | remake/doc/cdoc.pl | Perl | bsd-3-clause | 10,509 |
###########################################################################
#
# This file is partially auto-generated by the DateTime::Locale generator
# tools (v0.10). This code generator comes with the DateTime::Locale
# distribution in the tools/ directory, and is called generate-modules.
#
# This file was generated from the CLDR JSON locale data. See the LICENSE.cldr
# file included in this distribution for license details.
#
# Do not edit this file directly unless you are sure the part you are editing
# is not created by the generator.
#
###########################################################################
=pod
=encoding UTF-8
=head1 NAME
DateTime::Locale::hy - Locale data examples for the hy locale.
=head1 DESCRIPTION
This pod file contains examples of the locale data available for the
Armenian locale.
=head2 Days
=head3 Wide (format)
երկուշաբթի
երեքշաբթի
չորեքշաբթի
հինգշաբթի
ուրբաթ
շաբաթ
կիրակի
=head3 Abbreviated (format)
երկ
երք
չրք
հնգ
ուր
շբթ
կիր
=head3 Narrow (format)
Ե
Ե
Չ
Հ
Ու
Շ
Կ
=head3 Wide (stand-alone)
երկուշաբթի
երեքշաբթի
չորեքշաբթի
հինգշաբթի
ուրբաթ
շաբաթ
կիրակի
=head3 Abbreviated (stand-alone)
երկ
երք
չրք
հնգ
ուր
շբթ
կիր
=head3 Narrow (stand-alone)
Եկ
Եր
Չր
Հգ
Ու
Շբ
Կր
=head2 Months
=head3 Wide (format)
հունվարի
փետրվարի
մարտի
ապրիլի
մայիսի
հունիսի
հուլիսի
օգոստոսի
սեպտեմբերի
հոկտեմբերի
նոյեմբերի
դեկտեմբերի
=head3 Abbreviated (format)
հնվ
փտվ
մրտ
ապր
մյս
հնս
հլս
օգս
սեպ
հոկ
նոյ
դեկ
=head3 Narrow (format)
Հ
Փ
Մ
Ա
Մ
Հ
Հ
Օ
Ս
Հ
Ն
Դ
=head3 Wide (stand-alone)
հունվար
փետրվար
մարտ
ապրիլ
մայիս
հունիս
հուլիս
օգոստոս
սեպտեմբեր
հոկտեմբեր
նոյեմբեր
դեկտեմբեր
=head3 Abbreviated (stand-alone)
հնվ
փտվ
մրտ
ապր
մյս
հնս
հլս
օգս
սեպ
հոկ
նոյ
դեկ
=head3 Narrow (stand-alone)
Հ
Փ
Մ
Ա
Մ
Հ
Հ
Օ
Ս
Հ
Ն
Դ
=head2 Quarters
=head3 Wide (format)
1-ին եռամսյակ
2-րդ եռամսյակ
3-րդ եռամսյակ
4-րդ եռամսյակ
=head3 Abbreviated (format)
1-ին եռմս.
2-րդ եռմս.
3-րդ եռմս.
4-րդ եռմս.
=head3 Narrow (format)
1
2
3
4
=head3 Wide (stand-alone)
1-ին եռամսյակ
2-րդ եռամսյակ
3-րդ եռամսյակ
4-րդ եռամսյակ
=head3 Abbreviated (stand-alone)
1-ին եռմս.
2-րդ եռմս.
3-րդ եռմս.
4-րդ եռմս.
=head3 Narrow (stand-alone)
1
2
3
4
=head2 Eras
=head3 Wide (format)
մ.թ.ա.
մ.թ.
=head3 Abbreviated (format)
մ.թ.ա.
մ.թ.
=head3 Narrow (format)
մ.թ.ա.
մ.թ.
=head2 Date Formats
=head3 Full
2008-02-05T18:30:30 = 2008թ. փետրվարի 5, երեքշաբթի
1995-12-22T09:05:02 = 1995թ. դեկտեմբերի 22, ուրբաթ
-0010-09-15T04:44:23 = -10թ. սեպտեմբերի 15, շաբաթ
=head3 Long
2008-02-05T18:30:30 = 05 փետրվարի, 2008թ.
1995-12-22T09:05:02 = 22 դեկտեմբերի, 1995թ.
-0010-09-15T04:44:23 = 15 սեպտեմբերի, -10թ.
=head3 Medium
2008-02-05T18:30:30 = 05 փտվ, 2008թ.
1995-12-22T09:05:02 = 22 դեկ, 1995թ.
-0010-09-15T04:44:23 = 15 սեպ, -10թ.
=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
=head2 Time Formats
=head3 Full
2008-02-05T18:30:30 = 18:30:30, UTC
1995-12-22T09:05:02 = 9:05:02, UTC
-0010-09-15T04:44:23 = 4:44:23, UTC
=head3 Long
2008-02-05T18:30:30 = 18:30:30, UTC
1995-12-22T09:05:02 = 9:05:02, UTC
-0010-09-15T04:44:23 = 4:44:23, UTC
=head3 Medium
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 Short
2008-02-05T18:30:30 = 18:30
1995-12-22T09:05:02 = 9:05
-0010-09-15T04:44:23 = 4:44
=head2 Datetime Formats
=head3 Full
2008-02-05T18:30:30 = 2008թ. փետրվարի 5, երեքշաբթի, 18:30:30, UTC
1995-12-22T09:05:02 = 1995թ. դեկտեմբերի 22, ուրբաթ, 9:05:02, UTC
-0010-09-15T04:44:23 = -10թ. սեպտեմբերի 15, շաբաթ, 4:44:23, UTC
=head3 Long
2008-02-05T18:30:30 = 05 փետրվարի, 2008թ., 18:30:30, UTC
1995-12-22T09:05:02 = 22 դեկտեմբերի, 1995թ., 9:05:02, UTC
-0010-09-15T04:44:23 = 15 սեպտեմբերի, -10թ., 4:44:23, UTC
=head3 Medium
2008-02-05T18:30:30 = 05 փտվ, 2008թ., 18:30:30
1995-12-22T09:05:02 = 22 դեկ, 1995թ., 9:05:02
-0010-09-15T04:44:23 = 15 սեպ, -10թ., 4:44:23
=head3 Short
2008-02-05T18:30:30 = 05.02.08, 18:30
1995-12-22T09:05:02 = 22.12.95, 9:05
-0010-09-15T04:44:23 = 15.09.-10, 4:44
=head2 Available Formats
=head3 E (ccc)
2008-02-05T18:30:30 = երք
1995-12-22T09:05:02 = ուր
-0010-09-15T04:44:23 = շբթ
=head3 EHm (E, HH:mm)
2008-02-05T18:30:30 = երք, 18:30
1995-12-22T09:05:02 = ուր, 09:05
-0010-09-15T04:44:23 = շբթ, 04:44
=head3 EHms (E, 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 Ed (d, ccc)
2008-02-05T18:30:30 = 5, երք
1995-12-22T09:05:02 = 22, ուր
-0010-09-15T04:44:23 = 15, շբթ
=head3 Ehm (E, h:mm a)
2008-02-05T18:30:30 = երք, 6:30 PM
1995-12-22T09:05:02 = ուր, 9:05 AM
-0010-09-15T04:44:23 = շբթ, 4:44 AM
=head3 Ehms (E, h:mm:ss a)
2008-02-05T18:30:30 = երք, 6:30:30 PM
1995-12-22T09:05:02 = ուր, 9:05:02 AM
-0010-09-15T04:44:23 = շբթ, 4:44:23 AM
=head3 Gy (G yթ.)
2008-02-05T18:30:30 = մ.թ. 2008թ.
1995-12-22T09:05:02 = մ.թ. 1995թ.
-0010-09-15T04:44:23 = մ.թ.ա. -10թ.
=head3 GyMMM (G yթ. LLL)
2008-02-05T18:30:30 = մ.թ. 2008թ. փտվ
1995-12-22T09:05:02 = մ.թ. 1995թ. դեկ
-0010-09-15T04:44:23 = մ.թ.ա. -10թ. սեպ
=head3 GyMMMEd (G yթ. MMM d, E)
2008-02-05T18:30:30 = մ.թ. 2008թ. փտվ 5, երք
1995-12-22T09:05:02 = մ.թ. 1995թ. դեկ 22, ուր
-0010-09-15T04:44:23 = մ.թ.ա. -10թ. սեպ 15, շբթ
=head3 GyMMMd (d MMM, yթ.,)
2008-02-05T18:30:30 = 5 փտվ, 2008թ.,
1995-12-22T09:05:02 = 22 դեկ, 1995թ.,
-0010-09-15T04:44:23 = 15 սեպ, -10թ.,
=head3 H (H)
2008-02-05T18:30:30 = 18
1995-12-22T09:05:02 = 9
-0010-09-15T04:44:23 = 4
=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 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 Hmsv (HH:mm:ss v)
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 Hmv (HH:mm v)
2008-02-05T18:30:30 = 18:30 UTC
1995-12-22T09:05:02 = 09:05 UTC
-0010-09-15T04:44:23 = 04:44 UTC
=head3 M (L)
2008-02-05T18:30:30 = 2
1995-12-22T09:05:02 = 12
-0010-09-15T04:44:23 = 9
=head3 MEd (dd.MM, E)
2008-02-05T18:30:30 = 05.02, երք
1995-12-22T09:05:02 = 22.12, ուր
-0010-09-15T04:44:23 = 15.09, շբթ
=head3 MMM (LLL)
2008-02-05T18:30:30 = փտվ
1995-12-22T09:05:02 = դեկ
-0010-09-15T04:44:23 = սեպ
=head3 MMMEd (d MMM, E)
2008-02-05T18:30:30 = 5 փտվ, երք
1995-12-22T09:05:02 = 22 դեկ, ուր
-0010-09-15T04:44:23 = 15 սեպ, շբթ
=head3 MMMMd (MMMM d)
2008-02-05T18:30:30 = փետրվարի 5
1995-12-22T09:05:02 = դեկտեմբերի 22
-0010-09-15T04:44:23 = սեպտեմբերի 15
=head3 MMMd (d MMM)
2008-02-05T18:30:30 = 5 փտվ
1995-12-22T09:05:02 = 22 դեկ
-0010-09-15T04:44:23 = 15 սեպ
=head3 Md (dd.MM)
2008-02-05T18:30:30 = 05.02
1995-12-22T09:05:02 = 22.12
-0010-09-15T04:44:23 = 15.09
=head3 d (d)
2008-02-05T18:30:30 = 5
1995-12-22T09:05:02 = 22
-0010-09-15T04:44:23 = 15
=head3 h (h a)
2008-02-05T18:30:30 = 6 PM
1995-12-22T09:05:02 = 9 AM
-0010-09-15T04:44:23 = 4 AM
=head3 hm (h:mm a)
2008-02-05T18:30:30 = 6:30 PM
1995-12-22T09:05:02 = 9:05 AM
-0010-09-15T04:44:23 = 4:44 AM
=head3 hms (h:mm:ss a)
2008-02-05T18:30:30 = 6:30:30 PM
1995-12-22T09:05:02 = 9:05:02 AM
-0010-09-15T04:44:23 = 4:44:23 AM
=head3 hmsv (h:mm:ss a v)
2008-02-05T18:30:30 = 6:30:30 PM UTC
1995-12-22T09:05:02 = 9:05:02 AM UTC
-0010-09-15T04:44:23 = 4:44:23 AM UTC
=head3 hmv (h:mm a v)
2008-02-05T18:30:30 = 6:30 PM UTC
1995-12-22T09:05:02 = 9:05 AM UTC
-0010-09-15T04:44:23 = 4:44 AM UTC
=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 (MM.y)
2008-02-05T18:30:30 = 02.2008
1995-12-22T09:05:02 = 12.1995
-0010-09-15T04:44:23 = 09.-10
=head3 yMEd (d.MM.yթ., E)
2008-02-05T18:30:30 = 5.02.2008թ., երք
1995-12-22T09:05:02 = 22.12.1995թ., ուր
-0010-09-15T04:44:23 = 15.09.-10թ., շբթ
=head3 yMMM (yթ. LLL)
2008-02-05T18:30:30 = 2008թ. փտվ
1995-12-22T09:05:02 = 1995թ. դեկ
-0010-09-15T04:44:23 = -10թ. սեպ
=head3 yMMMEd (yթ. MMM d, E)
2008-02-05T18:30:30 = 2008թ. փտվ 5, երք
1995-12-22T09:05:02 = 1995թ. դեկ 22, ուր
-0010-09-15T04:44:23 = -10թ. սեպ 15, շբթ
=head3 yMMMM (yթ․ MMMM)
2008-02-05T18:30:30 = 2008թ․ փետրվարի
1995-12-22T09:05:02 = 1995թ․ դեկտեմբերի
-0010-09-15T04:44:23 = -10թ․ սեպտեմբերի
=head3 yMMMd (d MMM, yթ.)
2008-02-05T18:30:30 = 5 փտվ, 2008թ.
1995-12-22T09:05:02 = 22 դեկ, 1995թ.
-0010-09-15T04:44:23 = 15 սեպ, -10թ.
=head3 yMd (dd.MM.y)
2008-02-05T18:30:30 = 05.02.2008
1995-12-22T09:05:02 = 22.12.1995
-0010-09-15T04:44:23 = 15.09.-10
=head3 yQQQ (y թ, QQQ)
2008-02-05T18:30:30 = 2008 թ, 1-ին եռմս.
1995-12-22T09:05:02 = 1995 թ, 4-րդ եռմս.
-0010-09-15T04:44:23 = -10 թ, 3-րդ եռմս.
=head3 yQQQQ (y թ, QQQQ)
2008-02-05T18:30:30 = 2008 թ, 1-ին եռամսյակ
1995-12-22T09:05:02 = 1995 թ, 4-րդ եռամսյակ
-0010-09-15T04:44:23 = -10 թ, 3-րդ եռամսյակ
=head2 Miscellaneous
=head3 Prefers 24 hour time?
Yes
=head3 Local first day of the week
1 (երկուշաբթի)
=head1 SUPPORT
See L<DateTime::Locale>.
=cut
| jkb78/extrajnm | local/lib/perl5/DateTime/Locale/hy.pod | Perl | mit | 10,871 |
package Paws::SES::DeleteConfigurationSetResponse;
use Moose;
has _request_id => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::SES::DeleteConfigurationSetResponse
=head1 ATTRIBUTES
=head2 _request_id => Str
=cut
| ioanrogers/aws-sdk-perl | auto-lib/Paws/SES/DeleteConfigurationSetResponse.pm | Perl | apache-2.0 | 267 |
#!/usr/bin/env perl
# Time-stamp: <2011-01-16 21:15:53 barre>
#
# Convert VTK headers to doxygen format
#
# roeim : Vetle Roeim <vetler@ifi.uio.no>
# barre : Sebastien Barre <sebastien@barre.nom.fr>
#
# 0.9 (barre) :
# - add --conds : add \cond...\endcond around public:, private:, protected:
#
# 0.83 (barre) :
# - add --stdout : print converted file to standard output
#
# 0.82 (barre) :
# - add --relativeto path : each file/directory to document is considered
# relative to 'path', where --to and --relativeto should be absolute
#
# 0.81 (barre) :
# - fix pb if both --to and path to the file to document were absolute
# - remove warning when date or revision not found
#
# 0.8 (barre) :
# - update to match the new VTK 4.0 tree
# - change default --dirs so that it can be launched from Utilities/Doxygen
# - change default --to so that it can be launched from Utilities/Doxygen
# - handle more .SECTION syntax
# - add group support (at last)
#
# 0.76 (barre) :
# - add 'parallel' to the default set of directories
#
# 0.75 (barre) :
# - change default --to to '../vtk-doxygen' to comply with Kitware's doxyfile
#
# 0.74 (barre) :
# - as doxygen now handles RCS/CVS tags of the form $word:text$, use them
#
# 0.73 (barre) :
# - change doxygen command style from \ to @ to match javadoc, autodoc, etc.
#
# 0.72 (barre) :
# - change default --to to '../vtk-dox'
#
# 0.71 (barre) :
# - fix O_TEXT flag problem
# - switch to Unix CR/LF format
#
# 0.7 (barre) :
# - change name
# - remove -c option
#
# 0.6 (barre) :
# - change (warning) default --to to '../vtk2' because I ruined my own
# VTK distrib too many times :(
# - add automatic creation of missing directory trees
# - add check for current OS (if Windows, do not perform tests based
# on stat()/idev/ino features)
#
# 0.5 (barre) :
# - better .SECTION handling
# - add support for empty lines in documentation block
# - fix problem with headers not corresponding to classes
# - change name to doc_header2doxygen (removed vtk_)
# - change '-s' (silent) to '-v' (verbose)
# - add function description reformatting
#
# 0.4 (barre) :
# - change /*! ... */ position upon request
# - add 'Date:' support as @date
# - add 'Version:' support as @version
# - add 'Thanks:' support as @par Thanks
#
# 0.3 (barre) :
# - fix various " // Description" spelling problems :)
#
# 0.2 (barre) :
# - fix problem with classes with no brief documentation
#
# 0.1 (barre) :
# - add Perl syntactic sugar, options...
# - add standard output (filter) mode (-c)
# - add silent mode (-s)
# - add update mode, convert only if newer (-u)
# - add conversion to another directory (--to)
# - add '.SECTION Caveats' support as @warning
# - add/fix '.SECTION whatever' support as @par
# - add default directories to process
#
# 0.0 (roeim)
# - first release (thanks to V. Roeim !)
use Carp;
use Cwd 'abs_path';
use Getopt::Long;
use Fcntl;
use File::Basename;
use File::Find;
use File::Path;
use Text::Wrap;
use strict;
my ($VERSION, $PROGNAME, $AUTHOR) = (0.9, $0, "Sebastien Barre et al.");
$PROGNAME =~ s/^.*[\\\/]//;
# -------------------------------------------------------------------------
# Defaults (add options as you want: "verbose" => 1 for default verbose mode)
my %default =
(
dirs => ["../../Charts",
"../../Common",
"../../Filtering",
"../../GenericFiltering",
"../../GenericFiltering/Testing/Cxx",
"../../Geovis",
"../../Graphics",
"../../GUISupport/MFC",
"../../GUISupport/Qt",
"../../Hybrid",
"../../Imaging",
"../../Infovis",
"../../IO",
"../../Parallel",
"../../Rendering",
"../../TextAnalysis",
"../../Views",
"../../VolumeRendering",
"../../Widgets"],
relativeto => "",
temp => "doc_header2doxygen.tmp",
to => "../../../VTK-doxygen"
);
# -------------------------------------------------------------------------
# Parse options
my %args;
Getopt::Long::Configure("bundling");
GetOptions (\%args, "help", "verbose|v", "update|u", "conds|c", "force|f", "temp=s", "to=s", "stdout", "relativeto=s");
print "$PROGNAME $VERSION, by $AUTHOR\n" if ! exists $args{"stdout"};
if (exists $args{"help"}) {
print <<"EOT";
Usage : $PROGNAME [--help] [--verbose|-v] [--update|-u] [--conds|-c] [--force|-f] [--temp file] [--to path] [--relativeto path] [files|directories...]
--help : this message
--verbose|-v : verbose (display filenames while processing)
--update|-u : update (convert only if newer, requires --to)
--force|-f : force conversion for all files (overrides --update)
--stdout : print converted file to standard output
--temp file : use 'file' as temporary file (default: $default{temp})
--to path : use 'path' as destination directory (default: $default{to})
--relativeto path : each file/directory to document is considered relative to 'path', where --to and --relativeto should be absolute (default: $default{relativeto})
--conds|-c : use \cond sections around public, protected, private
Example:
$PROGNAME --to ../vtk-doxygen
$PROGNAME contrib
EOT
exit;
}
$args{"verbose"} = 1 if exists $default{"verbose"};
$args{"update"} = 1 if exists $default{"update"};
$args{"conds"} = 1 if exists $default{"conds"};
$args{"force"} = 1 if exists $default{"force"};
$args{"temp"} = $default{temp} if ! exists $args{"temp"};
$args{"to"} = $default{"to"} if ! exists $args{"to"};
$args{"to"} =~ s/[\\\/]*$// if exists $args{"to"};
$args{"relativeto"} = $default{"relativeto"} if ! exists $args{"relativeto"};
$args{"relativeto"} =~ s/[\\\/]*$// if exists $args{"relativeto"};
croak "$PROGNAME: --update requires --to\n"
if exists $args{"update"} && ! exists $args{"to"};
my $os_is_win = ($^O =~ m/(MSWin32|Cygwin)/i);
my $open_file_as_text = $os_is_win ? O_TEXT : 0;
my $start_time = time();
# -------------------------------------------------------------------------
# Collect all files and directories
push @ARGV, @{$default{dirs}} if !@ARGV;
print "Collecting...\n" if ! exists $args{"stdout"};
my @files;
foreach my $file (@ARGV) {
if (-f $file) {
push @files, $file;
} elsif (-d $file) {
find sub { push @files, $File::Find::name; }, $file;
}
}
# -------------------------------------------------------------------------
# Process files corresponding to headers
print "Converting...\n" if ! exists $args{"stdout"};
my $intermediate_time = time();
my $nb_file = 0;
foreach my $source (@files) {
next if $source !~ /vtk[^\\\/]*\.h\Z/;
# Figure out destination file now
my $dest;
if (! exists $args{"to"}) {
$dest = $args{"temp"};
} else {
# if source has absolute path, just use the basename, unless a
# relativeto path has been set
if ($source =~ m/^(\/|[a-zA-W]\:[\/\\])/) {
if ($args{"relativeto"}) {
my ($dir, $absrel) = (abs_path(dirname($source)),
abs_path($args{"relativeto"}));
$dir =~ s/$absrel//;
$dest = $args{"to"} . $dir . '/' . basename($source);
} else {
$dest = $args{"to"} . '/' . basename($source);
}
} else {
my $source2 = $source;
# let's remove the ../ component before the source filename, so
# that it might be appended to the "to" directory
$source2 =~ s/^(\.\.[\/\\])*//;
$dest = $args{"to"} . '/' . $source2;
}
# Ensure both source and target are different
if (!$os_is_win) {
my ($i_dev, $i_ino) = stat $source;
my ($o_dev, $o_ino) = stat $dest;
croak "$PROGNAME: sorry, $source and $dest are the same file\n"
if ($i_dev == $o_dev && $i_ino == $o_ino);
}
}
# Update mode : skip the file if it is not newer than the
# previously converted target
if (exists $args{"update"} && ! exists $args{"force"}) {
next if -e $dest && (stat $source)[9] < (stat $dest)[9];
}
++$nb_file;
print " $source\n" if exists $args{"verbose"};
# Open file, feed it entirely to an array
sysopen(HEADERFILE, $source, O_RDONLY|$open_file_as_text)
or croak "$PROGNAME: unable to open $source\n";
my @headerfile = <HEADERFILE>;
close(HEADERFILE);
my ($date, $revision) = ("", "");
my @converted = ();
my @thanks = ();
# Parse the file until the beginning of the documentation block
# is found. The copyright and disclaimer sections are parsed to
# extract the 'Date', 'Version' and 'Thanks' values.
my $line;
while ($line = shift @headerfile) {
# Quit if the beginning of the documentation block has been reached.
# It is supposed to start with:
# // .NAME vtkFooBar - foo bar class
last if $line =~ /\/\/ \.NAME/;
# Date. Example:
# Date: $Date$
if ($line =~ /^\s*Date:\s*(.*)$/) {
$date = $1;
# Version. Example:
# Version: $Revision$
} elsif ($line =~ /^\s*Version:\s*(.*)$/) {
$revision = $1;
# Thanks (maybe multi-lines). Example:
# Thanks: Thanks to Sebastien Barre who developed this class.
} elsif ($line =~ /^\s*Thanks:\s*(.*)$/) {
push @thanks, " ", $1, "\n";
# Handle multi-line thanks
while ($line = shift @headerfile) {
last if $line =~ /^\s*$/;
$line =~ s/^(\s*)//;
push @thanks, " ", $line;
}
push @converted, $line;
# Everything else goes to the converted file
} else {
push @converted, $line;
}
}
# Process the documentation block
# Extract the name of the class and its short description
# // .NAME vtkFooBar - foo bar class
if (defined($line) && $line =~ /\/\/ \.NAME (\w*)( \- (.*))?/) {
my ($class_name, $class_short_description) = ($1, $3);
$class_name =~ s/\.h//;
# Insert class description, date, revision, thanks
push @converted, "/*! \@class $class_name\n";
push @converted, " \@brief $class_short_description\n"
if $class_short_description;
if ($date) {
push @converted, "\n $date\n";
}
# WARNING : need a blank line between RCS tags and previous dox tag
if ($revision) {
push @converted, "\n" if (!$date);
push @converted, " $revision\n";
}
# Do not add thanks anymore. Will be done externally.
# push @converted, " \@par Thanks:\n", @thanks if @thanks;
# Read until the end of the documentation block is reached
# Translate 'See Also', 'Caveats' and whatever .SECTION
# As of 24 sep 2001, there are:
# 137 // .SECTION Caveats
# 1 // .SECTION Credits
# 702 // .SECTION Description
# 3 // .SECTION Note
# 1 // .SECTION note
# 329 // .SECTION See Also
# 4 // .SECTION See also
# 70 // .SECTION see also
# 1 // .SECTION Warning
# find . -name vtk\*.h -exec grep "\.SECTION" {} \; | sort | uniq -c
# Let's provide support for bugs too:
# // .SECTION Bug
# // .SECTION Bugs
# // .SECTION Todo
my ($tag, $inblock) = ("", 0);
while ($line = shift @headerfile) {
# Quit if the end of the documentation block has been reached.
# Let'say that it is supposed to end as soon as the usual
# inclusion directives are found, for example:
# #ifndef __vtkAbstractTransform_h
# #define __vtkAbstractTransform_h
last if $line =~ /^\#/;
# Process and recognize a .SECTION command and convert it to
# the corresponding doxygen tag ($tag)
if ($line =~ /^\/\/\s+\.SECTION\s+(.+)\s*$/i) {
my $type = $1;
# Bugs (@bugs). Starts with:
# // .SECTION Bug
# // .SECTION Bugs
if ($type =~ /Bugs?/i) {
$tag = "\@bug";
}
# Caveats or Warnings (@warning). Starts with:
# // .SECTION Caveats
# // .SECTION Warning
# // .SECTION Warnings
elsif ($type =~ /(Caveats|Warnings?)/i) {
$tag = "\@warning";
}
# Description. Starts with:
# // .SECTION Description
elsif ($type =~ /Description/i) {
$tag = "";
push @converted, "\n";
}
# Note (@attention). Starts with:
# // .SECTION Note
elsif ($type =~ /Note/i) {
$tag = "\@attention";
}
# See also (@sa). Starts with:
# // .SECTION See Also
elsif ($type =~ /See Also/i) {
$tag = "\@sa";
}
# Todo (@todo). Starts with:
# // .SECTION Todo
elsif ($type =~ /Todo/i) {
$tag = "\@todo";
}
# Any other .SECTION (@par). Starts with:
# // .SECTION whatever
else {
$tag = "\@par " . $type . ":";
}
$inblock = 0;
}
# If the line starts with '//', we are still within the tag block.
# Remove '//' for non empty lines, eventually put or duplicate
# the tag name if an empty comment is found (meaning that a new
# 'paragraph' is requested but with the same tag type)
# Example:
# // .SECTION Caveats
# // blabla1q
# // blabla1b
# //
# // blabla2
# Gets translated into:
# @warning
# blabla1q
# blabla1b
#
# @warning
# blabla2
elsif ($line =~ /^\/\/(.*)/) {
my $remaining = $1;
if ($remaining =~ /\S/) {
push @converted, " $tag\n"
if $tag ne "" && ! $inblock;
push @converted, $remaining, "\n";
$inblock = 1;
} else {
push @converted, "\n";
$inblock = 0;
}
} else {
# Does not starts with // but still within block or just
# before the end (#). Probably an empty line.
# Hack : let's have a look at the next line... if it begins
# with // then the current line is included (was a space).
if (my $next_line = shift @headerfile) {
push @converted, $line if $next_line =~ /^\/\//;
unshift @headerfile, $next_line;
}
}
}
# Close the doxygen documentation block describing the class
push @converted, "*/\n\n", $line;
}
# Read until the end of the header and translate the description of
# each function provided that it is located in a C++ comment
# containing the 'Description:' keyword.
# Example:
# // Description:
# // Construct with automatic computation of divisions, averaging
# // 25 points per bucket.
# static vtkPointLocator2D *New();
my $in_section = "";
while ($line = shift @headerfile) {
# Track the public:, protected: and private: sections and put them
# between \cond... \endcond so that they can be removed from the
# documentation conditionally. Add them to ENABLED_SECTION
# to show them.
# IMPORTANT: *no* spaces are allowed between the beginning of the
# line and the qualifier. This is mandatory to solve issues
# with nested class definitions, since it is non-trivial to
# track the fact that we are leaving a class definition to
# re-enter the parent class definition, etc.
if (exists $args{"conds"}) {
if ($line =~ /^(public|protected|private):/) {
if ($in_section ne "") {
push @converted, "// \@endcond\n";
}
$in_section = $1;
push @converted, "// \@cond section_$in_section\n";
}
}
if ($line =~ /^(\s*)\/\/\s*De(s|c)(s|c)?ription/) {
my $indent = $1;
$Text::Wrap::columns = 76;
# While there are still lines beginning with '//' append them to
# the function's description and trim spaces.
my @description = ();
while ($line = shift @headerfile) {
last if $line !~ /^\s*\/\//;
chop $line;
$line =~ s/^\s*\/\/\s*//;
$line =~ s/\s*$//;
push @description, $line;
}
# While there are non-empty lines or a new Descrption line add
# these lines to the list of declarations
# (and/or inline definitions) pertaining to the same description.
my @declarations = ();
while ($line && $line =~ /\s*\S/) {
push @declarations, $line;
# terminate if we encounter another Description line
# that doesn't have a leading empty line
if ($headerfile[0] !~ /^(\s*)\/\/\s*De(s|c)(s|c)?ription/ ) {
$line = shift @headerfile;
}else{
$line = "";
}
}
# If there is more than one declaration or at least a macro,
# enclose in a group (actually a single multiline declaration will
# be enclosed too, but who cares :)...
my $enclose =
(scalar @declarations > 1 || $declarations[0] =~ /vtk.+Macro/);
push @converted, "$indent//@\{\n" if $enclose;
push @converted,
wrap("$indent/*! ", "$indent ", @description), " */\n"
if @description;
push @converted, @declarations;
push @converted, "$indent//@\}\n" if $enclose;
}
push @converted, $line;
}
if (exists $args{"conds"}) {
if ($in_section ne "") {
push @converted, "// \@endcond";
}
}
# Write the converted header to its destination
# or to standard output.
if (exists $args{"stdout"}) {
print @converted;
} else {
# Open the target and create the missing directory if any
if (!sysopen(DEST_FILE,
$dest,
O_WRONLY|O_TRUNC|O_CREAT|$open_file_as_text)) {
my $dir = dirname($dest);
mkpath($dir);
sysopen(DEST_FILE,
$dest,
O_WRONLY|O_TRUNC|O_CREAT|$open_file_as_text)
or croak "$PROGNAME: unable to open destination file $dest\n";
}
print DEST_FILE @converted;
close(DEST_FILE);
# If in-place conversion was requested, remove source and rename target
# (or temp file) to source
if (! exists $args{"to"}) {
unlink($source)
or carp "$PROGNAME: unable to delete original file $source\n";
rename($args{"temp"}, $source)
or carp "$PROGNAME: unable to rename ", $args{"temp"}, " to $source\n";
}
}
}
if (! exists $args{"stdout"}) {
print " => $nb_file files converted in ", time() - $intermediate_time, " s. \n";
print "Finished in ", time() - $start_time, " s.\n";
}
| cjh1/vtkmodular | Utilities/Doxygen/doc_header2doxygen.pl | Perl | bsd-3-clause | 20,567 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.