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
package Mojolicious::Plugin::HeaderCondition; use Mojo::Base 'Mojolicious::Plugin'; sub register { my ($self, $app) = @_; $app->routes->add_condition(headers => \&_headers); $app->routes->add_condition( agent => sub { _headers(@_[0 .. 2], {'User-Agent' => $_[3]}) }); $app->routes->add_condition( host => sub { _check($_[1]->req->url->to_abs->host, $_[3]) }); } sub _check { my ($value, $pattern) = @_; return 1 if $value && $pattern && ref $pattern eq 'Regexp' && $value =~ $pattern; return $value && defined $pattern && $pattern eq $value; } sub _headers { my ($route, $c, $captures, $patterns) = @_; return undef unless $patterns && ref $patterns eq 'HASH' && keys %$patterns; # All headers need to match my $headers = $c->req->headers; _check($headers->header($_), $patterns->{$_}) || return undef for keys %$patterns; return 1; } 1; =encoding utf8 =head1 NAME Mojolicious::Plugin::HeaderCondition - Header condition plugin =head1 SYNOPSIS # Mojolicious $app->plugin('HeaderCondition'); $app->routes->get('/:controller/:action') ->over(headers => {Referer => qr/example\.com/}); # Mojolicious::Lite plugin 'HeaderCondition'; get '/' => (headers => {Referer => qr/example\.com/}) => sub {...}; # All headers need to match $app->routes->get('/:controller/:action')->over(headers => { 'X-Secret-Header' => 'Foo', Referer => qr/example\.com/ }); # The "agent" condition is a shortcut for the "User-Agent" header get '/' => (agent => qr/Firefox/) => sub {...}; # The "host" condition is a shortcut for the detected host get '/' => (host => qr/mojolicious\.org/) => sub {...}; =head1 DESCRIPTION L<Mojolicious::Plugin::HeaderCondition> is a route condition for header-based routes. This is a core plugin, that means it is always enabled and its code a good example for learning to build new plugins, you're welcome to fork it. See L<Mojolicious::Plugins/"PLUGINS"> for a list of plugins that are available by default. =head1 METHODS L<Mojolicious::Plugin::HeaderCondition> inherits all methods from L<Mojolicious::Plugin> and implements the following new ones. =head2 register $plugin->register(Mojolicious->new); Register conditions in L<Mojolicious> application. =head1 SEE ALSO L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>. =cut
ashkanx/binary-mt
scripts/local/lib/perl5/Mojolicious/Plugin/HeaderCondition.pm
Perl
apache-2.0
2,360
# openbsd-lib.pl # Quota functions for openbsd # quotas_init() sub quotas_init { return undef; } # quotas_supported() # Returns 1 for user quotas, 2 for group quotas or 3 for both sub quotas_supported { return 3; } # free_space(filesystem) # Returns an array containing btotal, bfree, ftotal, ffree sub free_space { local(@out, @rv); my $oldsize = $ENV{'BLOCKSIZE'}; $ENV{'BLOCKSIZE'} = 512; my $out = &backquote_command("df -i ".quotemeta($_[0])); $ENV{'BLOCKSIZE'} = $oldsize; if ($out =~ /Mounted on\n\S+\s+(\d+)\s+\d+\s+(\d+)\s+\S+\s+(\d+)\s+(\d+)/) { return ($1, $2, $3+$4, $4); } return ( ); } # quota_can(&mnttab, &fstab) # Can this filesystem type support quotas? # 0 = No quota support (or not turned on in /etc/fstab) # 1 = User quotas only # 2 = Group quotas only # 3 = User and group quotas sub quota_can { return ($_[1]->[3] =~ /userquota/ ? 1 : 0) + ($_[1]->[3] =~ /groupquota/ ? 2 : 0); } # quota_now(&mnttab, &fstab) # Are quotas currently active? # 0 = Not active # 1 = User quotas active # 2 = Group quotas active # 3 = Both active sub quota_now { return $_[0]->[3] =~ /quota/ ? 3 : 0; } # quotaon(filesystem, mode) # Activate quotas and create quota files for some filesystem. The mode can # be 1 for user only, 2 for group only or 3 for user and group sub quotaon { return if (&is_readonly_mode()); local($out, $qf, @qfile, $flags); if ($_[1]%2 == 1) { # turn on user quotas $qf = "$_[0]/quota.user"; if (!(-r $qf)) { &open_tempfile(QUOTAFILE, ">$qf", 0, 1); &close_tempfile(QUOTAFILE); &set_ownership_permissions(undef, undef, 0600, $qf); &system_logged("$config{'quotacheck_command'} $_[0]"); } $out = &backquote_logged("$config{'user_quotaon_command'} $_[0] 2>&1"); if ($?) { return $out; } } if ($_[1] > 1) { # turn on group quotas $qf = "$_[0]/quota.group"; if (!(-r $qf)) { &open_tempfile(QUOTAFILE, ">$qf", 0, 1); &close_tempfile(QUOTAFILE); &set_ownership_permissions(undef, undef, 0600, $qf); &system_logged("$config{'quotacheck_command'} $_[0]"); } $out = &backquote_logged("$config{'group_quotaon_command'} $_[0] 2>&1"); if ($?) { return $out; } } return undef; } # quotaoff(filesystem, mode) # Turn off quotas for some filesystem sub quotaoff { return if (&is_readonly_mode()); local($out); if ($_[1]%2 == 1) { $out = &backquote_logged("$config{'user_quotaoff_command'} $_[0] 2>&1"); if ($?) { return $out; } } if ($_[1] > 1) { $out = &backquote_logged("$config{'group_quotaoff_command'} $_[0] 2>&1"); if ($?) { return $out; } } return undef; } # user_filesystems(user) # Fills the array %filesys with details of all filesystem some user has # quotas on sub user_filesystems { local($n, $_, %mtab); open(QUOTA, "$config{'user_quota_command'} ".quotemeta($_[0])." |"); $n=0; while(<QUOTA>) { chop; if (/^(Disk|\s+Filesystem)/) { next; } if (/^(\S+)$/) { # Bogus wrapped line $filesys{$n,'filesys'} = $1; local $nl = <QUOTA>; $nl =~ /^\s+(\S+)\s+(\S+)\s+(\S+)(.{8}\s+)(\S+)\s+(\S+)\s+(\S+)(.*)/ || $nl =~ /^.{15}(.{8}).(.{7})(.{8}).{8}(.{8}).(.{7})(.{8})/; $filesys{$n,'ublocks'} = int($1); $filesys{$n,'sblocks'} = int($2); $filesys{$n,'hblocks'} = int($3); $filesys{$n,'ufiles'} = int($4); $filesys{$n,'sfiles'} = int($5); $filesys{$n,'hfiles'} = int($6); $n++; } elsif (/^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(.{8}\s+)(\S+)\s+(\S+)\s+(\S+)(.*)/ || /^(.{15})(.{8}).(.{7})(.{8}).{8}(.{8}).(.{7})(.{8})/) { $filesys{$n,'ublocks'} = int($2); $filesys{$n,'sblocks'} = int($3); $filesys{$n,'hblocks'} = int($4); $filesys{$n,'ufiles'} = int($5); $filesys{$n,'sfiles'} = int($6); $filesys{$n,'hfiles'} = int($7); $filesys{$n,'filesys'} = $1; $filesys{$n,'filesys'} =~ s/^\s+//g; $n++; } } close(QUOTA); return $n; } # group_filesystems(group) # Fills the array %filesys with details of all filesystem some group has # quotas on sub group_filesystems { local($n, $_, %mtab); open(QUOTA, "$config{'group_quota_command'} ".quotemeta($_[0])." |"); $n=0; while(<QUOTA>) { chop; if (/^(Disk|\s+Filesystem)/) { next; } if (/^(\S+)$/) { # Bogus wrapped line $filesys{$n,'filesys'} = $1; local $nl = <QUOTA>; $nl =~ /^\s+(\S+)\s+(\S+)\s+(\S+)(.{8}\s+)(\S+)\s+(\S+)\s+(\S+)(.*)/ || $nl =~ /^.{15}(.{8}).(.{7})(.{8}).{8}(.{8}).(.{7})(.{8})/; $filesys{$n,'ublocks'} = int($1); $filesys{$n,'sblocks'} = int($2); $filesys{$n,'hblocks'} = int($3); $filesys{$n,'ufiles'} = int($4); $filesys{$n,'sfiles'} = int($5); $filesys{$n,'hfiles'} = int($6); $n++; } elsif (/^\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(.{8}\s+)(\S+)\s+(\S+)\s+(\S+)(.*)/ || /^(.{15})(.{8}).(.{7})(.{8}).{8}(.{8}).(.{7})(.{8})/) { $filesys{$n,'ublocks'} = int($2); $filesys{$n,'sblocks'} = int($3); $filesys{$n,'hblocks'} = int($4); $filesys{$n,'ufiles'} = int($5); $filesys{$n,'sfiles'} = int($6); $filesys{$n,'hfiles'} = int($7); $filesys{$n,'filesys'} = $1; $filesys{$n,'filesys'} =~ s/^\s+//g; $n++; } } close(QUOTA); return $n; } # filesystem_users(filesystem) # Fills the array %user with information about all users with quotas # on this filesystem. This may not be all users on the system.. sub filesystem_users { local($rep, @rep, $n, $what); $rep = `$config{'user_repquota_command'} $_[0] 2>&1`; if ($?) { return -1; } @rep = split(/\n/, $rep); @rep = grep { !/^root\s/ } @rep[3..$#rep]; for($n=0; $n<@rep; $n++) { if ($rep[$n] =~ /(\S+)\s*[\-\+]{2}\s+(\d+)\s+(\d+)\s+(\d+)\s(.{0,15})\s(\d+)\s+(\d+)\s+(\d+)(.*)/ || $rep[$n] =~ /(\S+)\s+..(.{8})(.{8})(.{8})(.{7})(.{8})(.{8})(.{8})(.*)/) { $user{$n,'user'} = $1; $user{$n,'ublocks'} = int($2); $user{$n,'sblocks'} = int($3); $user{$n,'hblocks'} = int($4); $user{$n,'gblocks'} = $5; $user{$n,'ufiles'} = int($6); $user{$n,'sfiles'} = int($7); $user{$n,'hfiles'} = int($8); $user{$n,'gfiles'} = $9; $user{$n,'gblocks'} = &trunc_space($user{$n,'gblocks'}); $user{$n,'gfiles'} = &trunc_space($user{$n,'gfiles'}); } } return $n; } # filesystem_groups(filesystem) # Fills the array %group with information about all groups with quotas # on this filesystem. This may not be all groups on the system.. sub filesystem_groups { local($rep, @rep, $n, $what); $rep = `$config{'group_repquota_command'} $_[0] 2>&1`; if ($?) { return -1; } @rep = split(/\n/, $rep); @rep = @rep[3..$#rep]; for($n=0; $n<@rep; $n++) { if ($rep[$n] =~ /(\S+)\s*[\-\+]{2}\s+(\d+)\s+(\d+)\s+(\d+)\s(.{0,15})\s(\d+)\s+(\d+)\s+(\d+)(.*)/ || $rep[$n] =~ /(\S+)\s+..(.{8})(.{8})(.{8})(.{7})(.{8})(.{8})(.{8})/) { $group{$n,'group'} = $1; $group{$n,'ublocks'} = int($2); $group{$n,'sblocks'} = int($3); $group{$n,'hblocks'} = int($4); $group{$n,'gblocks'} = $5; $group{$n,'ufiles'} = int($6); $group{$n,'sfiles'} = int($7); $group{$n,'hfiles'} = int($8); $group{$n,'gfiles'} = $9; $group{$n,'gblocks'} = &trunc_space($group{$n,'gblocks'}); $group{$n,'gfiles'} = &trunc_space($group{$n,'gfiles'}); } } return $n; } # edit_quota_file(data, filesys, sblocks, hblocks, sfiles, hfiles) sub edit_quota_file { local($rv, $line, %mtab, @m); @line = split(/\n/, $_[0]); for($i=0; $i<@line; $i++) { if ($line[$i] =~ /^(\S+): (blocks|kbytes) in use: (\d+), limits \(soft = (\d+), hard = (\d+)\)$/ && $1 eq $_[1]) { # found lines to change, old style $rv .= "$1: $2 in use: $3, limits (soft = $_[2], hard = $_[3])\n"; $line[++$i] =~ /^\s*inodes in use: (\d+), limits \(soft = (\d+), hard = (\d+)\)$/; $rv .= "\tinodes in use: $1, limits (soft = $_[4], hard = $_[5])\n"; } elsif ($line[$i] =~ /^(\S+): in use: (\d+)k, limits \(soft = (\d+)k, hard = (\d+)k\)$/ && $1 eq $_[1]) { # found lines to change, new style $rv .= "$1: in use: ${2}k, limits (soft = $_[2]k, hard = $_[3]k)\n"; $line[++$i] =~ /^\s*inodes in use: (\d+), limits \(soft = (\d+), hard = (\d+)\)$/; $rv .= "\tinodes in use: $1, limits (soft = $_[4], hard = $_[5])\n"; } else { $rv .= "$line[$i]\n"; } } return $rv; } # quotacheck(filesystem, mode) # Runs quotacheck on some filesystem sub quotacheck { $out = &backquote_logged("$config{'quotacheck_command'} $_[0] 2>&1"); if ($?) { return $out; } return undef; } # copy_user_quota(user, [user]+) # Copy the quotas for some user to many others sub copy_user_quota { for($i=1; $i<@_; $i++) { $out = &backquote_logged("$config{'user_copy_command'} ". quotemeta($_[0])." ".quotemeta($_[$i])." 2>&1"); if ($?) { return $out; } } return undef; } # copy_group_quota(group, [group]+) # Copy the quotas for some group to many others sub copy_group_quota { for($i=1; $i<@_; $i++) { $out = &backquote_logged("$config{'group_copy_command'} ". quotemeta($_[0])." ".quotemeta($_[$i])." 2>&1"); if ($?) { return $out; } } return undef; } # default_grace() # Returns 0 if grace time can be 0, 1 if zero grace means default sub default_grace { return 0; } # get_user_grace(filesystem) # Returns an array containing btime, bunits, ftime, funits # The units can be 0=sec, 1=min, 2=hour, 3=day sub get_user_grace { local(@rv, %mtab, @m); $ENV{'EDITOR'} = $ENV{'VISUAL'} = "cat"; open(GRACE, "$config{'user_grace_command'} $_[0] |"); while(<GRACE>) { if (/^(\S+): block grace period: (\d+) (\S+), file grace period: (\d+) (\S+)/ && $1 eq $_[0]) { @rv = ($2, $name_to_unit{$3}, $4, $name_to_unit{$5}); } } close(GRACE); return @rv; } # get_group_grace(filesystem) # Returns an array containing btime, bunits, ftime, funits # The units can be 0=sec, 1=min, 2=hour, 3=day sub get_group_grace { local(@rv, %mtab, @m); $ENV{'EDITOR'} = $ENV{'VISUAL'} = "cat"; open(GRACE, "$config{'group_grace_command'} $_[0] |"); while(<GRACE>) { if (/^(\S+): block grace period: (\d+) (\S+), file grace period: (\d+) (\S+)/ && $1 eq $_[0]) { @rv = ($2, $name_to_unit{$3}, $4, $name_to_unit{$5}); } } close(GRACE); return @rv; } # edit_grace_file(data, filesystem, btime, bunits, ftime, funits) sub edit_grace_file { local($rv, $line, @m, %mtab); foreach $line (split(/\n/, $_[0])) { if ($line =~ /^(\S+): block grace period: (\d+) (\S+), file grace period: (\d+) (\S+)/ && $1 eq $_[1]) { # replace this line $line = "$1: block grace period: $_[2] $unit_to_name{$_[3]}, file grace period: $_[4] $unit_to_name{$_[5]}"; } $rv .= "$line\n"; } return $rv; } # grace_units() # Returns an array of possible units for grace periods sub grace_units { return ($text{'grace_seconds'}, $text{'grace_minutes'}, $text{'grace_hours'}, $text{'grace_days'}); } # fs_block_size(dir, device, filesystem) # Returns the size of blocks on some filesystem, or undef if unknown. # Always 512 because the ENV setting above forces this. sub fs_block_size { return 512; } # quota_block_size(dir, device, filesystem) # Always returns 1024, as that's the block size BSD appears to use sub quota_block_size { return 1024; } %name_to_unit = ( "second", 0, "seconds", 0, "minute", 1, "minutes", 1, "hour", 2, "hours", 2, "day", 3, "days", 3, ); foreach $k (keys %name_to_unit) { $unit_to_name{$name_to_unit{$k}} = $k; } 1;
HasClass0/webmin
quota/freebsd-lib.pl
Perl
bsd-3-clause
10,971
# iscsi-tgtd-lib.pl # Common functions for managing and configuring the iSCSI TGTD server BEGIN { push(@INC, ".."); }; use strict; use warnings; use WebminCore; &init_config(); &foreign_require("raid"); &foreign_require("fdisk"); &foreign_require("lvm"); &foreign_require("mount"); our (%text, %config, %gconfig, $module_config_file); our ($list_disks_partitions_cache, $get_raidtab_cache, $list_logical_volumes_cache, $get_tgtd_config_cache); # check_config() # Returns undef if the iSCSI server is installed, or an error message if # missing sub check_config { return $text{'check_econfigset'} if (!$config{'config_file'}); return &text('check_econfig', "<tt>$config{'config_file'}</tt>") if (!-r $config{'config_file'}); return &text('check_etgtadm', "<tt>$config{'tgtadm'}</tt>") if (!&has_command($config{'tgtadm'})); #&foreign_require("init"); #return &text('check_einit', "<tt>$config{'init_name'}</tt>") # if (&init::action_status($config{'init_name'}) == 0); return undef; } # get_tgtd_config() # Parses the iSCSI server config file in an array ref of objects sub get_tgtd_config { if (!$get_tgtd_config_cache) { $get_tgtd_config_cache = &read_tgtd_config_file($config{'config_file'}); } return $get_tgtd_config_cache; } # read_tgtd_config_file(file) # Parses a single config file into an array ref sub read_tgtd_config_file { my ($file) = @_; my @rv; my $lnum = 0; my $parent; my $lref = &read_file_lines($file, 1); my @pstack; foreach my $ol (@$lref) { my $l = $ol; $l =~ s/#.*$//; if ($l =~ /^\s*include\s(\S+)/) { # Include some other files my $ifile = $1; foreach my $iglob (glob($ifile)) { next if (!-r $iglob); my $inc = &read_tgtd_config_file($iglob); push(@rv, @$inc); } } elsif ($l =~ /^\s*<(\S+)\s+(.*)>/) { # Start of a block my $dir = { 'name' => $1, 'value' => $2, 'values' => [ split(/\s+/, $2) ], 'type' => 1, 'members' => [ ], 'file' => $file, 'line' => $lnum, 'eline' => $lnum }; if ($parent) { push(@{$parent->{'members'}}, $dir); } else { push(@rv, $dir); } push(@pstack, $parent); $parent = $dir; } elsif ($l =~ /^\s*<\/(\S+)>/) { # End of a block $parent->{'eline'} = $lnum; $parent = pop(@pstack); } elsif ($l =~ /^\s*(\S+)\s+(\S.*)/) { # Some directive in a block my $dir = { 'name' => $1, 'value' => $2, 'values' => [ split(/\s+/, $2) ], 'type' => 0, 'file' => $file, 'line' => $lnum, 'eline' => $lnum }; if ($parent) { push(@{$parent->{'members'}}, $dir); } else { push(@rv, $dir); } } $lnum++; } return \@rv; } # save_directive(&config, [&old|old-name], [&new], [&parent], [add-file-file]) # Replaces, creates or deletes some directive sub save_directive { my ($conf, $olddir, $newdir, $parent, $addfile) = @_; my $file; if ($olddir && !ref($olddir)) { # Lookup the old directive by name $olddir = &find($parent ? $parent->{'members'} : $conf, $olddir); } if ($olddir) { # Modifying old directive's file $file = $olddir->{'file'}; } elsif ($addfile) { # Adding to a specific file $file = $addfile; } elsif ($parent) { # Adding to parent's file $file = $parent->{'file'}; } else { # Adding to the default config file $file = $config{'config_file'}; } my $lref = $file ? &read_file_lines($file) : undef; my @lines = $newdir ? &directive_lines($newdir) : ( ); my $oldlen = $olddir ? $olddir->{'eline'} - $olddir->{'line'} + 1 : undef; my $oldidx = $olddir && $parent ? &indexof($olddir, @{$parent->{'members'}}) : $olddir ? &indexof($olddir, @$conf) : undef; my ($renumline, $renumoffset); if ($olddir && $newdir) { # Replace some directive if ($lref) { splice(@$lref, $olddir->{'line'}, $oldlen, @lines); $newdir->{'file'} = $olddir->{'file'}; $newdir->{'line'} = $olddir->{'line'}; $newdir->{'eline'} = $newdir->{'line'} + scalar(@lines) - 1; if ($parent) { $parent->{'eline'} += scalar(@lines) - $oldlen; } } if ($parent) { $parent->{'members'}->[$oldidx] = $newdir; } else { $conf->[$oldidx] = $newdir; } $renumline = $newdir->{'eline'}; $renumoffset = scalar(@lines) - $oldlen; } elsif ($olddir) { # Remove some directive if ($lref) { splice(@$lref, $olddir->{'line'}, $oldlen); } if ($parent) { # From inside parent splice(@{$parent->{'members'}}, $oldidx, 1); if ($lref) { $parent->{'eline'} -= $oldlen; } } else { # From top-level splice(@$conf, $oldidx, 1); } $renumline = $olddir->{'line'}; $renumoffset = $oldlen; } elsif ($newdir) { # Add some directive if ($lref) { $newdir->{'file'} = $file; } if ($parent) { # Inside parent if ($lref) { $newdir->{'line'} = $parent->{'eline'}; $newdir->{'eline'} = $newdir->{'line'} + scalar(@lines) - 1; $parent->{'eline'} += scalar(@lines); splice(@$lref, $newdir->{'line'}, 0, @lines); } $parent->{'members'} ||= [ ]; $parent->{'type'} ||= 1; push(@{$parent->{'members'}}, $newdir); } else { # At end of file if ($lref) { $newdir->{'line'} = scalar(@lines); $newdir->{'eline'} = $newdir->{'line'} + scalar(@lines) - 1; push(@$lref, @lines); } push(@$conf, $newdir); } $renumline = $newdir->{'eline'}; $renumoffset = scalar(@lines); } # Apply any renumbering to the config (recursively) if ($renumoffset && $lref) { &recursive_renumber($conf, $file, $renumline, $renumoffset, [ $newdir, $parent ? ( $parent ) : ( ) ]); } } # save_multiple_directives(&config, name, &directives, &parent) # Update all existing directives with some name sub save_multiple_directives { my ($conf, $name, $newdirs, $parent) = @_; my $olddirs = [ &find($parent ? $parent->{'members'} : $conf, $name) ]; for(my $i=0; $i<@$olddirs || $i<@$newdirs; $i++) { &save_directive($conf, $i<@$olddirs ? $olddirs->[$i] : undef, $i<@$newdirs ? $newdirs->[$i] : undef, $parent); } } # delete_if_empty(file) # Remove some file if after modification it contains no non-whitespace lines sub delete_if_empty { my ($file) = @_; my $lref = &read_file_lines($file, 1); foreach my $l (@$lref) { return 0 if ($l =~ /\S/); } &unlink_file($file); &unflush_file_lines($file); return 1; } # recursive_renumber(&directives, file, after-line, offset, &ignore-list) sub recursive_renumber { my ($conf, $file, $renumline, $renumoffset, $ignore) = @_; foreach my $c (@$conf) { if ($c->{'file'} eq $file && &indexof($c, @$ignore) < 0) { $c->{'line'} += $renumoffset if ($c->{'line'} > $renumline); $c->{'eline'} += $renumoffset if ($c->{'eline'} > $renumline); } if ($c->{'type'}) { &recursive_renumber($c->{'members'}, $file, $renumline, $renumoffset, $ignore); } } } # directive_lines(&dir, [indent]) # Returns the lines of text for some directive sub directive_lines { my ($dir, $indent) = @_; $indent ||= 0; my $istr = " " x $indent; my @rv; if ($dir->{'type'}) { # Has sub-directives push(@rv, $istr."<".$dir->{'name'}. ($dir->{'value'} ? " ".$dir->{'value'} : "").">"); foreach my $s (@{$dir->{'members'}}) { push(@rv, &directive_lines($s, $indent+1)); } push(@rv, $istr."</".$dir->{'name'}.">"); } else { # Just a name/value push(@rv, $istr.$dir->{'name'}. ($dir->{'value'} ? " ".$dir->{'value'} : "")); } return @rv; } # find(&config|&object, name) # Returns all config objects with the given name sub find { my ($conf, $name) = @_; $conf = $conf->{'members'} if (ref($conf) eq 'HASH'); my @rv = grep { lc($_->{'name'}) eq lc($name) } @$conf; return wantarray ? @rv : $rv[0]; } # find_value(&config|&object, name) # Returns config values with the given name sub find_value { my ($conf, $name) = @_; $conf = $conf->{'members'} if (ref($conf) eq 'HASH'); my @rv = map { $_->{'value'} } &find($conf, $name); return wantarray ? @rv : $rv[0]; } # is_tgtd_running() # Returns the PID if the server process is running, or 0 if not sub is_tgtd_running { my $pid = &find_byname("tgtd"); return $pid; } # setup_tgtd_init() # If no init script exists, create one sub setup_tgtd_init { &foreign_require("init"); return 0 if (&init::action_status($config{'init_name'})); &init::enable_at_boot($config{'init_name'}, "Start TGTd iSCSI server", &has_command($config{'tgtd'}). " && sleep 2 && ". &has_command($config{'tgtadmin'})." -e", "killall -9 tgtd", undef, { 'fork' => 1 }, ); } # start_iscsi_tgtd() # Run the init script to start the server sub start_iscsi_tgtd { if ($config{'start_cmd'}) { my $out = &backquote_command("$config{'start_cmd'} 2>&1 </dev/null"); return $? ? $out : undef; } else { &setup_tgtd_init(); &foreign_require("init"); my ($ok, $out) = &init::start_action($config{'init_name'}); return $ok ? undef : $out; } } # stop_iscsi_tgtd() # Run the init script to stop the server sub stop_iscsi_tgtd { if ($config{'stop_cmd'}) { my $out = &backquote_command("$config{'stop_cmd'} 2>&1 </dev/null"); return $? ? $out : undef; } else { &setup_tgtd_init(); &foreign_require("init"); my ($ok, $out) = &init::stop_action($config{'init_name'}); return $ok ? undef : $out; } } # restart_iscsi_tgtd() # Sends a HUP signal to re-read the configuration sub restart_iscsi_tgtd { if ($config{'restart_cmd'}) { my $out = &backquote_command("$config{'restart_cmd'} 2>&1 </dev/null"); return $? ? $out : undef; } else { &stop_iscsi_tgtd(); # Wait for process to exit for(my $i=0; $i<20; $i++) { last if (!&is_tgtd_running()); sleep(1); } return &start_iscsi_tgtd(); } } # get_device_size(device, "part"|"raid"|"lvm"|"other") # Returns the size in bytes of some device, which can be a partition, RAID # device, logical volume or regular file. sub get_device_size { my ($dev, $type) = @_; if (!$type) { $type = $dev =~ /^\/dev\/md\d+$/ ? "raid" : $dev =~ /^\/dev\/([^\/]+)\/([^\/]+)$/ ? "lvm" : $dev =~ /^\/dev\/(s|h|v|xv)d[a-z]+\d*$/ ? "part" : "other"; } if ($type eq "part") { # A partition or whole disk foreach my $d (&list_disks_partitions_cached()) { if ($d->{'device'} eq $dev) { # Whole disk return $d->{'cylinders'} * $d->{'cylsize'}; } foreach my $p (@{$d->{'parts'}}) { if ($p->{'device'} eq $dev) { return ($p->{'end'} - $p->{'start'} + 1) * $d->{'cylsize'}; } } } return undef; } elsif ($type eq "raid") { # A RAID device my $conf = &get_raidtab_cached(); foreach my $c (@$conf) { if ($c->{'value'} eq $dev) { return $c->{'size'} * 1024; } } return undef; } elsif ($type eq "lvm") { # LVM volume group foreach my $l (&list_logical_volumes_cached()) { if ($l->{'device'} eq $dev) { return $l->{'size'} * 1024; } } } else { # A regular file my @st = stat($dev); return @st ? $st[7] : undef; } } sub list_disks_partitions_cached { $list_disks_partitions_cache ||= [ &fdisk::list_disks_partitions() ]; return @$list_disks_partitions_cache; } sub get_raidtab_cached { $get_raidtab_cache ||= &raid::get_raidtab(); return $get_raidtab_cache; } sub list_logical_volumes_cached { if (!$list_logical_volumes_cache) { $list_logical_volumes_cache = [ ]; foreach my $v (&lvm::list_volume_groups()) { push(@$list_logical_volumes_cache, &lvm::list_logical_volumes($v->{'name'})); } } return @$list_logical_volumes_cache; } # find_host_name(&config) # Returns the first host name part of the first target sub find_host_name { my ($conf) = @_; my %hcount; foreach my $t (&find_value($conf, "target")) { my ($host) = split(/:/, $t); $hcount{$host}++; } my @hosts = sort { $hcount{$b} <=> $hcount{$a} } (keys %hcount); return $hosts[0]; } # generate_host_name() # Returns the first part of a target name, in the standard format sub generate_host_name { my @tm = localtime(time()); return sprintf("iqn.%.4d-%.2d.%s", $tm[5]+1900, $tm[4]+1, join(".", reverse(split(/\./, &get_system_hostname())))); } 1;
rcuvgd/Webmin22.01.2016
iscsi-tgtd/iscsi-tgtd-lib.pl
Perl
bsd-3-clause
11,888
#!/usr/bin/perl -w use strict; use File::Basename; use lib '/home/shichen.wang/perl5/lib/perl5'; use JSON::Parse 'json_file_to_perl'; use XML::Simple; use Data::Dumper; use Cwd; use FindBin; my $star_bar = '*' x 80; my $usage = qq ($star_bar Usage: $0 <pacbio_sequence_folder, i.e, /data4/pacbio/r54092_20160921_211039> <cell_1> <cell_2> ...\n Examples: * To generate report for all cells of the run: $0 /data4/pacbio/r54092_20160921_211039 This will generate report for all cells in the folder r54092_20160921_211039; * To generate report for certain cell(s) of the run: $0 /data4/pacbio/r54092_20160921_211039 1_A01 2_B02 * To run BLAST RUNBLAST=1 $0 /data4/pacbio/r54092_20160921_211039 1_A01 2_B02 The output will be gereated in the working directory while the perl script is running, with the folder named as RUN_NAME-Cell1-Cell2, i.e., r54092_20160921_211039-1_A01-2_B02. This folder may be copyed to the PI's downloadable folder. shichen\@tamu 01/05/2017 first draft $star_bar ); my $dir = shift or die $usage; $dir =~ s/\/$//; #$dir = Cwd::abs_path($dir); my @selected_cells = @ARGV; print STDERR "Selected cells: ", @selected_cells >0?join(" ", @selected_cells):"None, will take all detected.", "\n"; my $pacbio_data_root = "/data4/pacbio"; my $second_analysis_dir = $pacbio_data_root . "/000"; my %analysis_dir_properties = get_properties($second_analysis_dir); my @sub_dirs = <$dir/*>; my @cells = grep {-d $_} @sub_dirs; print STDERR "Detected cells: ", join(" ", map{basename($_)}@cells), "\n"; my %selected = map{$_, 1}@selected_cells; @cells = grep{exists $selected{basename($_)} }@cells if @selected_cells > 0; my $output_dir = join("-", basename($dir), map{basename($_)}@cells); mkdir($output_dir) unless -d $output_dir; # generate zipped file my $zip = basename($dir) . "_" . join("-", (map{basename($_)}@cells)) . ".tar"; my $zip_dir = $output_dir . "/" . random_str(); mkdir ($zip_dir) unless -d $zip_dir; #my $zip_cmd = "tar --exclude=\".*\" --exclude=\"*scraps.*\" -cvf $zip_dir/$zip -C $dir " . join(" ", (map{basename($_)}@cells));# print STDERR $zip_cmd, "\n"; my $zip_cmd = "tar -cvf $zip_dir/$zip -C $dir " . join(" ", (map{basename($_)}@cells));# print STDERR $zip_cmd, "\n"; print STDERR $zip_cmd, "\n"; die if system($zip_cmd); $zip = basename($zip_dir) . "/" . $zip; # run blast if (exists $ENV{RUNBLAST}){ foreach my $cell (@cells){ my @bams = <$cell/*subreads.bam>; foreach my $bam (@bams){ my $blast_output = $output_dir . "/" . basename($cell) . ".blast.out"; my $blast_sum = $output_dir . "/" . basename($cell) . ".blast.sum.txt"; my $cmd = "bamToFastq -i $bam -fq /dev/stdout | head -n 10000 |seqtk seq -A |blastn -db nt -num_threds 10 -outfmt \'6 qseqid stitle qcovs \' >$blast_output"; system($cmd); `sh $FindBin::Bin/../lib/summarize_blast.sh $blast_output >$blast_sum`; } } } my $output_html = $output_dir . "/index.html"; open (my $HTML, ">$output_html") or die "$output_html error!"; my $header_printed = 0; foreach my $cell (@cells) { print STDERR "Processing $cell ...\n"; my @files = <$cell/*xml>; next unless @files; my $subread_bam = (<$cell/*subread*bam>)[0]; my $metadata_xml; map{$metadata_xml = $_ if /run.metadata/}@files; #my $r = `cat $metadata_xml`; #my ($run_start, $stamp_name, $run_id) = $r=~/pbdm:Run Status=.*WhenStarted="(\S+)".*TimeStampedName="(\S+)".*Name="(\S+)"/; #unless($header_printed){print_header($HTML, $run_start, $stamp_name, $run_id); $header_printed = 1} my $subset_xml; map{$subset_xml = $_ if /subreadset/}@files; my $analysis_dir; map{print STDERR "\t", $_, "\n"; $analysis_dir = $_ if $analysis_dir_properties{$_}->[1] eq $subset_xml}keys %analysis_dir_properties; my $pbscala_stdout = $analysis_dir . "/pbscala-job.stdout"; ## #my $r = `cat $pbscala_stdout`; #my $info_str = $1 if $r =~/Successfully entered SubreadSet SubreadServiceDataSet\((.*)\)/; #my @info_arr = split /,/, $info_str; my $xml = new XML::Simple; my $data = $xml->XMLin($subset_xml); my $r = $data->{"pbds:DataSetMetadata"}->{"Collections"}->{"CollectionMetadata"}->{"RunDetails"}; my ($run_start, $stamp_name, $run_id) = ($r->{"WhenCreated"}, $r->{"TimeStampedName"}, $r->{"Name"}); my $subset_str = `cat $subset_xml`; my $lib_cell = $1 if $subset_str=~/pbds\:SubreadSet.*?Name="(.*?)"/; $lib_cell =~ s/\s+/_/g; my ($lib_name, $cell_name) = ($1, $2) if $lib_cell=~/^(.*)\-(Cell\d+)$/; print STDERR join("\t", "Test", $lib_cell, $lib_name, $cell_name), "\n"; ## unless($header_printed){print_header($HTML, $run_start, $stamp_name, $lib_name, $run_id); $header_printed = 1} my $polymerase_plot = $analysis_dir . "/dataset-reports/filter_stats_xml/readLenDist0.png"; my $insert_plot = $analysis_dir . "/dataset-reports/filter_stats_xml/insertLenDist0.png"; mkdir( "$output_dir/" . basename($cell)) unless -d "$output_dir/" . basename($cell); system("cp $polymerase_plot $insert_plot $output_dir/" . basename($cell)); $polymerase_plot = basename($cell) . "/". basename($polymerase_plot); $insert_plot = basename($cell). "/". basename($insert_plot); my ($poly_read_total, $poly_read_count, $poly_read_mean, $poly_read_N50) = get_polymerase_count($analysis_dir . "/dataset-reports/filter_stats_xml/filter_stats_xml.json"); my ($sub_read_total, $sub_read_N50, $sub_read_mean, $sub_read_count) = get_stats_from_bam($subread_bam); # my ($sub_read_total, $sub_read_N50, $sub_read_mean, $sub_read_count) = (21123456, 2345, 3421, 9900); print $HTML "<li> <div class=\"lane\">", basename($cell), "</div></li>"; print $HTML qq( <h4>Sequencing summary:</h4> <table class="table table-bordered table-condensed"> <thead> <tr> <th></th> <th>Polymerase read</th> <th>Subread</th> </tr> </thead> <tbody> <tr> <td>Number reads</td> <td>$poly_read_count</td> <td>$sub_read_count</td> </tr> <tr> <td>Total bases</td> <td>$poly_read_total</td> <td>$sub_read_total</td> </tr> <tr> <td>Mean length, bp</td> <td>$poly_read_mean</td> <td>$sub_read_mean</td> </tr> <tr> <td>N50, bp</td> <td>$poly_read_N50</td> <td>$sub_read_N50</td> </tr> </tbody> </table> <p> ); #add plot print $HTML qq( <table class="table table-condensed"> <tr> <td>Polymerase read length<br><img src="$polymerase_plot" class="img-rounded" alt="" width="304" height="236"></td> <td>Insert length<br><img src="$insert_plot" class="img-rounded" alt="" width="304" height="236"></td> </tr> </table> ); }; ## add downlod link print $HTML qq( <li><div class="documentation">Retrieve data</div> You may click <a href="$zip"> this link </a> or use the wget command. <pre> <script type="text/javascript">document.write(dl_cmd(\"$zip\"));</script> </pre> </li> <li><div class="documentation">Documentation</div> <ul> <li><a href="http://www.pacb.com/wp-content/uploads/2015/09/Pacific-Biosciences-Glossary-of-Terms.pdf">PacBio Terminology</a></li> <li><a href="https://github.com/PacificBiosciences/Bioinformatics-Training/wiki">Bioinformatics Tutorial for PacBio data</a></li> <img src="/media/image/pacbio.png", width=500> </ul> </li> ); print $HTML "<hr>", "<div id=\"footer\">Texas A&M AgriLife Genomcis and Bioinformatics Service. &copy 2017</div>"; print $HTML "</div></body></html>"; close $HTML; ## generate a file in the directory when the report is done. my $time = localtime(time); print STDERR "\n\n$time Done!\nReport is in $output_dir !\n\n"; open (DONE, ">$output_dir/report.done.txt") or die $!; print DONE $time, " Done\n\n"; close DONE; ## subroutines sub get_stats_from_bam { my $bam = shift or die; print STDERR "Bam file: $bam \n"; my $samtools = `which samtools` || '/home/shichen.wang/Tools/bin/samtools'; chomp $samtools; print STDERR "$samtools view $bam\n"; open (my $IN, "$samtools view $bam |" ) or die $!; my @regions; my $total_length = 0; my $read_mean = 0; my $read_count = 0; while(<$IN>){ my $id = $1 if /^(\S+)/; # m54092_161220_211206/4194368/0_11 my @p = split /\//, $id; my @arr = split /_/, $p[-1]; my $region_len = $arr[1] - $arr[0]; $read_count ++; $total_length += $region_len; push @regions, $region_len; } $read_mean = int($total_length / $read_count); @regions = sort {$a <=> $b} @regions; my $N50 = $regions[int((scalar @regions)/2)]; return($total_length, $N50, $read_mean, $read_count); } sub all_exist { } sub get_properties { my $root = shift; my %return; my @dirs = <$root/*>; foreach my $d (@dirs){ my $datastore = $d."/datastore.json"; next unless -e $datastore; my $p = json_file_to_perl($datastore); #print STDERR Data::Dumper->Dump([$p], "datastore"); my $xml = $p->{files}->[0]->{path}; my $proj_name = $p->{files}->[0]->{name}; $return{$d} = [$proj_name, $xml]; print STDERR join("\t", $d, $proj_name, $xml),"\n"; } return %return; } sub print_header { my $fh = shift; my ($run_start, $stamp_name, $lib_name, $run_id) = @_; print {$fh} qq( <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>$stamp_name</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="/media/css/delivery.css" rel="stylesheet"/> <script type="text/javascript"> function basename(path) { return path.replace(/\\\\/g,'/').replace( /.*\\//, '' ); } function dirname(path) { return path.replace(/\\\\/g,'/').replace(/\\/[^\\/]*\$/, '');; } function dl_cmd(file) { dir = dirname(document.URL); return 'wget ' + dir + '/' + file; } </script> </head> <body> <div class="container"> <div id="logo"> <a href="http://txgen.tamu.edu/"><img src="/media/image/logo.png" alt="Texas A&amp;M AgriLife Research" /></a><br /> <div id="department"><a href="http://www.txgen.tamu.edu/">Genomics and Bioinformatics Services</a></div> </div> <ul id="properties"> <li>Run number: $run_id</li> <li>Library: $lib_name</li> <li>TimeStampName: $stamp_name</li> <li>Date: $run_start</li> <li>Sequencer ID: 54092</li> </ul> ); print STDERR "\tHeadaer printed!\n"; } sub get_polymerase_count { my $file = shift; die $file unless -e $file; my $p = json_file_to_perl($file); return ($p->{attributes}->[0]->{"value"}, $p->{attributes}->[1]->{"value"},$p->{attributes}->[2]->{"value"},$p->{attributes}->[3]->{"value"}) } sub random_str { my @arr=('a'..'z', "-"); my $n = shift || 10; my $str=""; while($n--){$str .= $arr[int(rand(scalar @arr))]} return $str; }
swang8/Perl_scripts_misc
generate_pacbio_report.pl
Perl
mit
11,113
:- module( hash_ext, [ hash_algorithm/1, % ?Name hash_directory/2, % +Hash, -Directory hash_directory/3, % +Root, +Hash, -Directory hash_file/3, % +Hash, +Local, -File hash_file/4, % +Root, +Hash, +Local, -File md5/2, % +Term, -Hash md5/3, % +Term, -Hash, +Options md5_text/2, % +Text, -Hash md5_text/3, % +Text, -Hash, +Options sha/2, % +Term, -Hash sha/3, % +Term, -Hash, +Options sha_text/2, % +Text, -Hash sha_text/3 % +Text, -Hash, +Options ] ). /** <module> Extended support for hashes */ :- use_module(library(lists)). :- reexport(library(md5), [ md5_hash/3 as md5_text ]). :- reexport(library(sha), [ sha_hash/3 as sha_text ]). :- use_module(library(dict)). :- use_module(library(file_ext)). %! hash_algorithm(+Name:atom) is semidet. %! hash_algorithm(-Name:atom) is multi. % % The hash types that are supported by this module. hash_algorithm(md5). hash_algorithm(sha1). hash_algorithm(sha224). hash_algorithm(sha256). hash_algorithm(sha384). hash_algorithm(sha512). %! hash_directory(+Hash:atom, -Directory:atom) is det. %! hash_directory(+Root:atom, +Hash:atom, -Directory:atom) is det. hash_directory(Hash, Dir2) :- working_directory(Root), hash_directory(Root, Hash, Dir2). hash_directory(Root, Hash, Dir2) :- sub_atom(Hash, 0, 2, _, Subdir1), directory_file_path(Root, Subdir1, Dir1), sub_atom(Hash, 2, _, 0, Subdir2), directory_file_path(Dir1, Subdir2, Dir2). %! hash_file(+Hash:atom, +Local:atom, -File:atom) is det. %! hash_file(+Root:atom, +Hash:atom, +Local:atom, -File:atom) is det. hash_file(Hash, Local, File) :- working_directory(Root), hash_file(Root, Hash, Local, File). hash_file(Root, Hash, Local, File) :- hash_directory(Root, Hash, Dir), create_directory(Dir), directory_file_path(Dir, Local, File). %! md5(+Term, -Hash:atom) is det. %! md5(+Term, -Hash:atom, +Options:options) is det. md5(Term, Hash) :- md5(Term, Hash, options{}). md5(Term, Hash, Options1) :- term_to_atom(Term, Atom), dict_terms(Options1, Options2), md5_hash(Atom, Hash, Options2). %! md5_text(+Text:text, -Hash:atom) is det. %! md5_text(+Text:text, -Hash:atom, +Options:options) is det. md5_text(Text, Hash) :- md5_text(Text, Hash, []). %! sha(+Term, -Hash:atom) is det. %! sha(+Term, -Hash:atom, +Options:options) is det. sha(Data, Hash) :- sha(Data, Hash, options{}). sha(Term, Hash, Options1) :- term_to_atom(Term, Atom), dict_terms(Options1, Options2), sha_hash(Atom, Hash, Options2). %! sha_text(+Text:text, -Hash:atom) is det. %! sha_text(+Text:text, -Hash:atom, +Options:options) is det. sha_text(Text, Hash) :- sha_text(Text, Hash, []).
wouterbeek/Prolog_Library_Collection
prolog/hash_ext.pl
Perl
mit
2,781
package HTTP::Session2::Base; use strict; use warnings; use utf8; use 5.008_001; use Digest::SHA; use Carp (); use Mouse; has env => ( is => 'ro', required => 1, ); has session_cookie => ( is => 'ro', lazy => 1, default => sub { +{ httponly => 1, secure => 0, name => 'hss_session', path => '/', }, }, # Need shallow copy trigger => sub { my $self = shift; $self->{session_cookie} = +{%{$self->{session_cookie}}}; }, ); has xsrf_cookie => ( is => 'ro', lazy => 1, default => sub { # httponly must be false. AngularJS need to read this value. +{ httponly => 0, secure => 0, name => 'XSRF-TOKEN', path => '/', }, }, # Need shallow copy trigger => sub { my $self = shift; $self->{xsrf_cookie} = +{%{$self->{xsrf_cookie}}}; }, ); has hmac_function => ( is => 'ro', default => sub { \&Digest::SHA::sha1_hex }, ); has is_dirty => ( is => 'rw', default => sub { 0 }, ); has is_fresh => ( is => 'rw', default => sub { 0 }, ); has necessary_to_send => ( is => 'rw', default => sub { 0 }, ); has secret => ( is => 'ro', required => 1, trigger => sub { my ($self, $secret) = @_; if (length($secret) < 20) { Carp::cluck("Secret string too short"); } }, ); no Mouse; sub _data { my $self = shift; unless ($self->{_data}) { $self->load_or_create(); } $self->{_data}; } sub id { my $self = shift; unless ($self->{id}) { $self->load_or_create(); } $self->{id}; } sub load_or_create { my $self = shift; $self->load_session() || $self->create_session(); } sub load_session { die "Abstract method" } sub create_session { die "Abstract method" } sub set { my ($self, $key, $value) = @_; $self->_data->{$key} = $value; $self->is_dirty(1); } sub get { my ($self, $key) = @_; $self->_data->{$key}; } sub remove { my ($self, $key) = @_; $self->is_dirty(1); delete $self->_data->{$key}; } sub validate_xsrf_token { my ($self, $token) = @_; # If user does not have any session data, user don't need a XSRF protection. return 1 unless %{$self->_data}; return 0 unless defined $token; return 1 if $token eq $self->xsrf_token; return 0; } sub finalize_plack_response { my ($self, $res) = @_; my @cookies = $self->finalize(); while (my ($name, $cookie) = splice @cookies, 0, 2) { my $baked = Cookie::Baker::bake_cookie( $name, $cookie ); $res->headers->push_header('Set-Cookie' => $baked); } } sub finalize_psgi_response { my ($self, $res) = @_; my @cookies = $self->finalize(); while (my ($name, $cookie) = splice @cookies, 0, 2) { my $baked = Cookie::Baker::bake_cookie( $name, $cookie ); push @{$res->[1]}, ( 'Set-Cookie' => $baked, ); } } sub finalize { die "Abstract method" } 1; __END__ =head1 NAME HTTP::Session2 - Abstract base class for HTTP::Session2 =head1 DESCRIPTION This is an abstract base class for HTTP::Session2. =head1 Common Methods =over 4 =item C<< my $session = HTTP::Session2::*->new(%args) >> Create new instance. =over 4 =item hmac_function: CodeRef This module uses HMAC to sign the session data. You can choice HMAC function for security enhancements and performance tuning. Default: C<< \&Digest::SHA::sha1_hex >> =item session_cookie: HashRef Options for session cookie. For more details, please look L<Cookie::Baker>. Default: +{ httponly => 1, secure => 0, name => 'hss_session', path => '/', }, =item xsrf_cookie: HashRef HTTP::Session2 generates 2 cookies. One is for session, other is for XSRF token. This parameter configures parameters for XSRF token cookie. For more details, please look L<Cookie::Baker>. Default: +{ httponly => 0, secure => 0, name => 'XSRF-TOKEN', path => '/', }, Note: C<httponly> flag should be false. Because this parameter should be readable from JavaScript. And it does not decrease security. =back =item C<< $session->get($key: Str) >> Get a value from session. =item C<< $session->set($key: Str, $value:Any) >> Set a value to session. This means you can set any Serializable data to the storage. =item C<< $session->remove($key: Str) >> Remove the value from session. =item C<< $session->validate_xsrf_token($token: Str) >> my $token = $req->header('X-XSRF-TOKEN') || $req->param('XSRF-TOKEN'); unless ($session->validate_xsrf_token($token)) { return Plack::Response->new( 403, [], 'Missing XSRF token' ); } Validate XSRF token. If the XSRF token is valid, return true. False otherwise. =item C<< $session->xsrf_token() >> Get a XSRF token in string. =item C<< $session->finalize_plack_response($res: Plack::Response) >> Finalize cookie headers and inject it to L<Plack::Response> instance. =back
rosiro/wasarabi
local/lib/perl5/HTTP/Session2/Base.pm
Perl
mit
5,239
#!/usr/bin/env perl package QDT; use strict; use warnings; use constant SEG_TEXT => 1; use constant SEG_LOGIC => 2; use constant SEG_OUTPUT => 3; use constant SEG_COMMENT => 4; use constant TAG_NONE => 1; use constant TAG_CODE => 2; use constant TAG_EMIT => 3; use constant TAG_COMMENT => 4; use constant MSG_WARNING => 1; use constant MSG_ERROR => 1; use Exporter; our @ISA = qw/Exporter/; our @EXPORT = qw/checkErrors evaluateCode generateCode parseDoc removeExtraWhiteSpace/; our $verbose = 0; # Use this function in templates: sub get_p { my $name = shift; my $default = shift; if (!defined $ENV{$name}) { return $default if (defined $default); die "Undefined environment variable: $name"; } return $ENV{$name}; } sub quoteEscape { my $s = shift; $s =~ s/\\/\\\\/g; $s =~ s/'/'\\/g; $s; } sub getLocn { my ($allText, $textPos) = @_; my $text = substr($allText, 0, $textPos); my $lastNL = rindex($text, "\n"); my ($init, $rest); if ($text =~ m{\A(.*\n)([^\n]*)\z}sx) { $init = $1; $rest = $2; } else { $init = ""; $rest = $text; } return sprintf("Line %d, column %d", 1 + ($init =~ tr/\n//), length($rest)); } # The QDT templating language: # <%...%>: logic # <%# ... %>: comment - pulled out # <%= ... -?%>: eval and emit -- trailing - squelches a newline # <<%#%>% : emits a literal "<%" # <<%#%># : emits a literal "<#" # %> that isn't preceded by a <% is emitted as is # Everything else is emitted as is. # Returns a tagged array of pieces of text sub parseDoc { my $text = shift; return [] if !$text; my @pieces = split(/(<%[=\#]?|-?%>)/, $text); my @segments = (); my $textPos = 0; my $t; my @errors = (); my $tagType = TAG_NONE; my $lastCode = ""; my $lastTagStartPos; while (0+@pieces) { # First piece will always be text, could be empty $t = shift @pieces; if ($t =~ m{\A(-?)\%>\z}) { if ($tagType == TAG_NONE) { push @segments, [SEG_TEXT, $t]; push @errors, [MSG_WARNING, "Unmatched %> treated verbatim at " . getLocn]; } elsif (substr($t, 1, 0) eq '-' && 0+@pieces) { $pieces[0] =~ s{\A(\s*\n)}{}; $textPos += length($1); } $tagType = TAG_NONE; } elsif ($t =~ m{\A<\%(.?)\z}) { my $tagTypeChar = $1; $lastTagStartPos = $textPos; if (!$tagTypeChar) { $tagType = TAG_CODE; } elsif ($tagTypeChar eq "#") { $tagType = TAG_COMMENT; } elsif ($tagTypeChar eq "=") { $tagType = TAG_EMIT; } else { die "Unexpected tag type char: $tagTypeChar"; } } else { if ($tagType == TAG_COMMENT) { push @segments, [SEG_COMMENT, $t]; } elsif ($tagType == TAG_CODE) { push @segments, [SEG_LOGIC, $t]; } elsif ($tagType == TAG_EMIT) { $t =~ s{\A\s+}{}; $t =~ s{\s+\z}{}; push @segments, [SEG_OUTPUT, $t]; } elsif ($t) { push @segments, [SEG_TEXT, $t]; } } $textPos += length($t); } if ($tagType != TAG_NONE) { push @errors, [MSG_ERROR, "Unmatched <% at pos " . getLocn($text, $lastTagStartPos)]; } return [\@segments, \@errors]; } sub xp { map{sprintf("%s: %d", $_, ord $_) }split(//, shift); } =begin removeExtraWhiteSpace - basically we want to remove the whitespace surrounding a <% ... %> tag, including the trailing newline, if there's no other non-whitespace text next to it. Because the parser isn't line-oriented, it's easier to walk through the array of segments and use context to figure out what to do. See tests like t/check-white-space.t to see examples of how this works. =cut sub removeExtraWhiteSpace { my $segments = shift; my $leadingWS = 0; my ($tagType, $text, $seg, $res); my $i = 0; my $lim = 0+@$segments; while ($i < $lim) { $seg = $segments->[$i]; if (($tagType = $seg->[0]) == SEG_TEXT) { # Take the trailing whitespace and determine if we should squelch it $text = stripTextBeforeLogic($seg->[1]); if (defined $text) { $res = shouldStripLogicalWhiteSpace($segments, $i + 1, $lim); if ($res) { $seg->[1] = $text; my $j = $res->[0]; my $replaceText = $res->[1]; $segments->[$j][1] = $replaceText; $i = $j - 1; # Skip ahead to the string we just adjusted } } } elsif ($tagType == SEG_LOGIC || $tagType == SEG_COMMENT ) { # We aren't following leading white-space, but does the sequence of code blocks end # with squelchable trailing white-space or a newline? $res = shouldStripLogicalWhiteSpace($segments, $i + 1, $lim); if ($res) { my $j = $res->[0]; my $replaceText = $res->[1]; $segments->[$j][1] = $replaceText; $i = $j - 1; # Skip ahead to the string we just adjusted } } $i += 1; } return $segments; } sub stripTextBeforeLogic { my $text = shift; if ($text =~ m{ \A ([ \t]+) \z}x ) { return ""; } elsif ($text =~ m{ \A (.* \n) [ \t]* \z}sx) { return $1; } undef; } sub stripTextAfterLogic { my $text = shift; if ($text =~ m{ \A [ \t]+ \z }x) { return ""; } elsif ($text =~ m{ \A [ \t]* \n (.*) }sx) { return $1; } undef; } sub shouldStripLogicalWhiteSpace { my ($segments, $i, $lim) = @_; my ($tagType, $text, $seg, $res); while ($i < $lim) { $seg = $segments->[$i]; if (($tagType = $seg->[0]) == SEG_OUTPUT) { return; } elsif ($tagType == SEG_TEXT) { $res = stripTextAfterLogic(($text = $seg->[1])); if (defined $res) { return [$i, $res]; } elsif ($text =~ /[^ \t]/) { return; } # Otherwise if it contains only tabs and spaces keep going } # Otherwise if it's SEG_LOGIC or SEG_COMMENT just keep looking for the next thing. $i += 1; } undef; } sub checkErrors { my $e = shift; my @errors = @$e; if (0+@errors) { my $sawError = 0; for (@errors) { my $eType = $_->[0]; my $eStr = $_->[1]; my $eCode; if ($eType == MSG_ERROR) { $eCode = "Error"; $sawError = 1; } else { $eCode = "Warning"; } print STDERR "$eCode: $eStr\n"; } exit 1 if $sawError; } } sub generateCode { my $res = shift; my @segments = @{$res}; #print join("\n", map {">> @$_"} @segments) . "\n"; my @codeSegments = map { my $segment = $_; #print "@$segment\n"; my $segType = $segment->[0]; my $segText = $segment->[1]; if ($segType == SEG_LOGIC) { $segText; } elsif ($segType == SEG_TEXT) { $segText =~ s{\\}{\\\\}g; $segText =~ s{'}{\\'}g; "\n" . "push(\@__collector, '$segText');" } elsif ($segType == SEG_COMMENT) { # Do nothing } else { die "Unexpected segType of $segType" if $segType != SEG_OUTPUT; "\n" . "push(\@__collector, $segText);" } } @segments; print join("\n", map {"*>> $_"} @codeSegments) . "\n" if $verbose; my $code = join("", @codeSegments); dump_code($code) if $verbose; return $code; } =begin The emitted code is a mixture of Perl logic and updates to an array of strings called "@__collector". This var should probably be put in a package to make it harder for templates to collide with it, but it's an unlikely enough name. Returns a Go-like array, of either [nil, error-message] or [the contents of the @__collector array, followed by nil. =cut sub evaluateCode { my $__code = shift; my @__collector; { no strict; eval($__code); } return $@ ? [undef, $@] : [\@__collector, undef]; } sub dump_code { my $code = shift . "\n"; my $i = 0; print "**************** CODE: \n"; while ($code =~ m{([^\n]*?)\n}gx) { $i += 1; printf("%4d %s\n", $i, $1); } print "**************** \n"; } 1;
ericpromislow/qdt
lib/QDT.pm
Perl
mit
7,598
/* $Id$ Part of CLP(Q) (Constraint Logic Programming over Rationals) Author: Leslie De Koninck E-mail: Leslie.DeKoninck@cs.kuleuven.be WWW: http://www.swi-prolog.org http://www.ai.univie.ac.at/cgi-bin/tr-online?number+95-09 Copyright (C): 2006, K.U. Leuven and 1992-1995, Austrian Research Institute for Artificial Intelligence (OFAI), Vienna, Austria This software is based on CLP(Q,R) by Christian Holzbaur for SICStus Prolog and distributed under the license details below with permission from all mentioned authors. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, if you link this library with other files, compiled with a Free Software compiler, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ :- module(store_q, [ add_linear_11/3, add_linear_f1/4, add_linear_ff/5, normalize_scalar/2, delete_factor/4, mult_linear_factor/3, nf_rhs_x/4, indep/2, isolate/3, nf_substitute/4, mult_hom/3, nf2sum/3, nf_coeff_of/3, renormalize/2 ]). % normalize_scalar(S,[N,Z]) % % Transforms a scalar S into a linear expression [S,0] normalize_scalar(S,[S,0]). % renormalize(List,Lin) % % Renormalizes the not normalized linear expression in List into % a normalized one. It does so to take care of unifications. % (e.g. when a variable X is bound to a constant, the constant is added to % the constant part of the linear expression; when a variable X is bound to % another variable Y, the scalars of both are added) renormalize([I,R|Hom],Lin) :- length(Hom,Len), renormalize_log(Len,Hom,[],Lin0), add_linear_11([I,R],Lin0,Lin). % renormalize_log(Len,Hom,HomTail,Lin) % % Logarithmically renormalizes the homogene part of a not normalized % linear expression. See also renormalize/2. renormalize_log(1,[Term|Xs],Xs,Lin) :- !, Term = l(X*_,_), renormalize_log_one(X,Term,Lin). renormalize_log(2,[A,B|Xs],Xs,Lin) :- !, A = l(X*_,_), B = l(Y*_,_), renormalize_log_one(X,A,LinA), renormalize_log_one(Y,B,LinB), add_linear_11(LinA,LinB,Lin). renormalize_log(N,L0,L2,Lin) :- P is N>>1, Q is N-P, renormalize_log(P,L0,L1,Lp), renormalize_log(Q,L1,L2,Lq), add_linear_11(Lp,Lq,Lin). % renormalize_log_one(X,Term,Res) % % Renormalizes a term in X: if X is a nonvar, the term becomes a scalar. renormalize_log_one(X,Term,Res) :- var(X), Term = l(X*K,_), get_attr(X,itf,Att), arg(5,Att,order(OrdX)), % Order might have changed Res = [0,0,l(X*K,OrdX)]. renormalize_log_one(X,Term,Res) :- nonvar(X), Term = l(X*K,_), Xk is X*K, normalize_scalar(Xk,Res). % ----------------------------- sparse vector stuff ---------------------------- % % add_linear_ff(LinA,Ka,LinB,Kb,LinC) % % Linear expression LinC is the result of the addition of the 2 linear expressions % LinA and LinB, each one multiplied by a scalar (Ka for LinA and Kb for LinB). add_linear_ff(LinA,Ka,LinB,Kb,LinC) :- LinA = [Ia,Ra|Ha], LinB = [Ib,Rb|Hb], LinC = [Ic,Rc|Hc], Ic is Ia*Ka+Ib*Kb, Rc is Ra*Ka+Rb*Kb, add_linear_ffh(Ha,Ka,Hb,Kb,Hc). % add_linear_ffh(Ha,Ka,Hb,Kb,Hc) % % Homogene part Hc is the result of the addition of the 2 homogene parts Ha and Hb, % each one multiplied by a scalar (Ka for Ha and Kb for Hb) add_linear_ffh([],_,Ys,Kb,Zs) :- mult_hom(Ys,Kb,Zs). add_linear_ffh([l(X*Kx,OrdX)|Xs],Ka,Ys,Kb,Zs) :- add_linear_ffh(Ys,X,Kx,OrdX,Xs,Zs,Ka,Kb). % add_linear_ffh(Ys,X,Kx,OrdX,Xs,Zs,Ka,Kb) % % Homogene part Zs is the result of the addition of the 2 homogene parts Ys and % [l(X*Kx,OrdX)|Xs], each one multiplied by a scalar (Ka for [l(X*Kx,OrdX)|Xs] and Kb for Ys) add_linear_ffh([],X,Kx,OrdX,Xs,Zs,Ka,_) :- mult_hom([l(X*Kx,OrdX)|Xs],Ka,Zs). add_linear_ffh([l(Y*Ky,OrdY)|Ys],X,Kx,OrdX,Xs,Zs,Ka,Kb) :- compare(Rel,OrdX,OrdY), ( Rel = (=) -> Kz is Kx*Ka+Ky*Kb, ( Kz =:= 0 -> add_linear_ffh(Xs,Ka,Ys,Kb,Zs) ; Zs = [l(X*Kz,OrdX)|Ztail], add_linear_ffh(Xs,Ka,Ys,Kb,Ztail) ) ; Rel = (<) -> Zs = [l(X*Kz,OrdX)|Ztail], Kz is Kx*Ka, add_linear_ffh(Xs,Y,Ky,OrdY,Ys,Ztail,Kb,Ka) ; Rel = (>) -> Zs = [l(Y*Kz,OrdY)|Ztail], Kz is Ky*Kb, add_linear_ffh(Ys,X,Kx,OrdX,Xs,Ztail,Ka,Kb) ). % add_linear_f1(LinA,Ka,LinB,LinC) % % special case of add_linear_ff with Kb = 1 add_linear_f1(LinA,Ka,LinB,LinC) :- LinA = [Ia,Ra|Ha], LinB = [Ib,Rb|Hb], LinC = [Ic,Rc|Hc], Ic is Ia*Ka+Ib, Rc is Ra*Ka+Rb, add_linear_f1h(Ha,Ka,Hb,Hc). % add_linear_f1h(Ha,Ka,Hb,Hc) % % special case of add_linear_ffh/5 with Kb = 1 add_linear_f1h([],_,Ys,Ys). add_linear_f1h([l(X*Kx,OrdX)|Xs],Ka,Ys,Zs) :- add_linear_f1h(Ys,X,Kx,OrdX,Xs,Zs,Ka). % add_linear_f1h(Ys,X,Kx,OrdX,Xs,Zs,Ka) % % special case of add_linear_ffh/8 with Kb = 1 add_linear_f1h([],X,Kx,OrdX,Xs,Zs,Ka) :- mult_hom([l(X*Kx,OrdX)|Xs],Ka,Zs). add_linear_f1h([l(Y*Ky,OrdY)|Ys],X,Kx,OrdX,Xs,Zs,Ka) :- compare(Rel,OrdX,OrdY), ( Rel = (=) -> Kz is Kx*Ka+Ky, ( Kz =:= 0 -> add_linear_f1h(Xs,Ka,Ys,Zs) ; Zs = [l(X*Kz,OrdX)|Ztail], add_linear_f1h(Xs,Ka,Ys,Ztail) ) ; Rel = (<) -> Zs = [l(X*Kz,OrdX)|Ztail], Kz is Kx*Ka, add_linear_f1h(Xs,Ka,[l(Y*Ky,OrdY)|Ys],Ztail) ; Rel = (>) -> Zs = [l(Y*Ky,OrdY)|Ztail], add_linear_f1h(Ys,X,Kx,OrdX,Xs,Ztail,Ka) ). % add_linear_11(LinA,LinB,LinC) % % special case of add_linear_ff with Ka = 1 and Kb = 1 add_linear_11(LinA,LinB,LinC) :- LinA = [Ia,Ra|Ha], LinB = [Ib,Rb|Hb], LinC = [Ic,Rc|Hc], Ic is Ia+Ib, Rc is Ra+Rb, add_linear_11h(Ha,Hb,Hc). % add_linear_11h(Ha,Hb,Hc) % % special case of add_linear_ffh/5 with Ka = 1 and Kb = 1 add_linear_11h([],Ys,Ys). add_linear_11h([l(X*Kx,OrdX)|Xs],Ys,Zs) :- add_linear_11h(Ys,X,Kx,OrdX,Xs,Zs). % add_linear_11h(Ys,X,Kx,OrdX,Xs,Zs) % % special case of add_linear_ffh/8 with Ka = 1 and Kb = 1 add_linear_11h([],X,Kx,OrdX,Xs,[l(X*Kx,OrdX)|Xs]). add_linear_11h([l(Y*Ky,OrdY)|Ys],X,Kx,OrdX,Xs,Zs) :- compare(Rel,OrdX,OrdY), ( Rel = (=) -> Kz is Kx+Ky, ( Kz =:= 0 -> add_linear_11h(Xs,Ys,Zs) ; Zs = [l(X*Kz,OrdX)|Ztail], add_linear_11h(Xs,Ys,Ztail) ) ; Rel = (<) -> Zs = [l(X*Kx,OrdX)|Ztail], add_linear_11h(Xs,Y,Ky,OrdY,Ys,Ztail) ; Rel = (>) -> Zs = [l(Y*Ky,OrdY)|Ztail], add_linear_11h(Ys,X,Kx,OrdX,Xs,Ztail) ). % mult_linear_factor(Lin,K,Res) % % Linear expression Res is the result of multiplication of linear % expression Lin by scalar K mult_linear_factor(Lin,K,Mult) :- K =:= 1, !, Mult = Lin. mult_linear_factor(Lin,K,Res) :- Lin = [I,R|Hom], Res = [Ik,Rk|Mult], Ik is I*K, Rk is R*K, mult_hom(Hom,K,Mult). % mult_hom(Hom,K,Res) % % Homogene part Res is the result of multiplication of homogene part % Hom by scalar K mult_hom([],_,[]). mult_hom([l(A*Fa,OrdA)|As],F,[l(A*Fan,OrdA)|Afs]) :- Fan is F*Fa, mult_hom(As,F,Afs). % nf_substitute(Ord,Def,Lin,Res) % % Linear expression Res is the result of substitution of Var in % linear expression Lin, by its definition in the form of linear % expression Def nf_substitute(OrdV,LinV,LinX,LinX1) :- delete_factor(OrdV,LinX,LinW,K), add_linear_f1(LinV,K,LinW,LinX1). % delete_factor(Ord,Lin,Res,Coeff) % % Linear expression Res is the result of the deletion of the term % Var*Coeff where Var has ordering Ord from linear expression Lin delete_factor(OrdV,Lin,Res,Coeff) :- Lin = [I,R|Hom], Res = [I,R|Hdel], delete_factor_hom(OrdV,Hom,Hdel,Coeff). % delete_factor_hom(Ord,Hom,Res,Coeff) % % Homogene part Res is the result of the deletion of the term % Var*Coeff from homogene part Hom delete_factor_hom(VOrd,[Car|Cdr],RCdr,RKoeff) :- Car = l(_*Koeff,Ord), compare(Rel,VOrd,Ord), ( Rel= (=) -> RCdr = Cdr, RKoeff=Koeff ; Rel= (>) -> RCdr = [Car|RCdr1], delete_factor_hom(VOrd,Cdr,RCdr1,RKoeff) ). % nf_coeff_of(Lin,OrdX,Coeff) % % Linear expression Lin contains the term l(X*Coeff,OrdX) nf_coeff_of([_,_|Hom],VOrd,Coeff) :- nf_coeff_hom(Hom,VOrd,Coeff). % nf_coeff_hom(Lin,OrdX,Coeff) % % Linear expression Lin contains the term l(X*Coeff,OrdX) where the % order attribute of X = OrdX nf_coeff_hom([l(_*K,OVar)|Vs],OVid,Coeff) :- compare(Rel,OVid,OVar), ( Rel = (=) -> Coeff = K ; Rel = (>) -> nf_coeff_hom(Vs,OVid,Coeff) ). % nf_rhs_x(Lin,OrdX,Rhs,K) % % Rhs = R + I where Lin = [I,R|Hom] and l(X*K,OrdX) is a term of Hom nf_rhs_x(Lin,OrdX,Rhs,K) :- Lin = [I,R|Tail], nf_coeff_hom(Tail,OrdX,K), Rhs is R+I. % late because X may not occur in H % isolate(OrdN,Lin,Lin1) % % Linear expression Lin1 is the result of the transformation of linear expression % Lin = 0 which contains the term l(New*K,OrdN) into an equivalent expression Lin1 = New. isolate(OrdN,Lin,Lin1) :- delete_factor(OrdN,Lin,Lin0,Coeff), K is -1 rdiv Coeff, mult_linear_factor(Lin0,K,Lin1). % indep(Lin,OrdX) % % succeeds if Lin = [0,_|[l(X*1,OrdX)]] indep(Lin,OrdX) :- Lin = [I,_|[l(_*K,OrdY)]], OrdX == OrdY, K =:= 1, I =:= 0. % nf2sum(Lin,Sofar,Term) % % Transforms a linear expression into a sum % (e.g. the expression [5,_,[l(X*2,OrdX),l(Y*-1,OrdY)]] gets transformed into 5 + 2*X - Y) nf2sum([],I,I). nf2sum([X|Xs],I,Sum) :- ( I =:= 0 -> X = l(Var*K,_), ( K =:= 1 -> hom2sum(Xs,Var,Sum) ; K =:= -1 -> hom2sum(Xs,-Var,Sum) ; hom2sum(Xs,K*Var,Sum) ) ; hom2sum([X|Xs],I,Sum) ). % hom2sum(Hom,Sofar,Term) % % Transforms a linear expression into a sum % this predicate handles all but the first term % (the first term does not need a concatenation symbol + or -) % see also nf2sum/3 hom2sum([],Term,Term). hom2sum([l(Var*K,_)|Cs],Sofar,Term) :- ( K =:= 1 -> Next = Sofar + Var ; K =:= -1 -> Next = Sofar - Var ; K < 0 -> Ka is -K, Next = Sofar - Ka*Var ; Next = Sofar + K*Var ), hom2sum(Cs,Next,Term).
TeamSPoon/logicmoo_workspace
docker/rootfs/usr/local/lib/swipl/library/clp/clpq/store_q.pl
Perl
mit
10,711
use MooseX::Declare; use strict; use warnings; #### USE LIB FOR INHERITANCE use FindBin qw($Bin); use lib "$Bin/../"; class Test::Virtual { sub new { my $class = shift; my $type = shift; $type = uc(substr($type, 0, 1)) . substr($type, 1); #print "Virtual::new type: $type\n"; my $location = "Test/Virtual/$type.pm"; $class = "Test::Virtual::$type"; #print "Virtual::new DOING require $location\n"; require $location; return $class->new(@_); } Test::Virtual->meta->make_immutable(inline_constructor => 0); } #### END 1;
aguadev/aguadev
t/unit/lib/Test/Virtual.pm
Perl
mit
605
# This file is auto-generated by the Perl DateTime Suite time zone # code generator (0.07) This code generator comes with the # DateTime::TimeZone module distribution in the tools/ directory # # Generated from debian/tzdata/southamerica. Olson data version 2008c # # Do not edit this file directly. # package DateTime::TimeZone::America::Recife; use strict; use Class::Singleton; use DateTime::TimeZone; use DateTime::TimeZone::OlsonDB; @DateTime::TimeZone::America::Recife::ISA = ( 'Class::Singleton', 'DateTime::TimeZone' ); my $spans = [ [ DateTime::TimeZone::NEG_INFINITY, 60368465976, DateTime::TimeZone::NEG_INFINITY, 60368457600, -8376, 0, 'LMT' ], [ 60368465976, 60928725600, 60368455176, 60928714800, -10800, 0, 'BRT' ], [ 60928725600, 60944320800, 60928718400, 60944313600, -7200, 1, 'BRST' ], [ 60944320800, 60960308400, 60944310000, 60960297600, -10800, 0, 'BRT' ], [ 60960308400, 60975856800, 60960301200, 60975849600, -7200, 1, 'BRST' ], [ 60975856800, 61501863600, 60975846000, 61501852800, -10800, 0, 'BRT' ], [ 61501863600, 61513614000, 61501856400, 61513606800, -7200, 1, 'BRST' ], [ 61513614000, 61533399600, 61513603200, 61533388800, -10800, 0, 'BRT' ], [ 61533399600, 61543850400, 61533392400, 61543843200, -7200, 1, 'BRST' ], [ 61543850400, 61564935600, 61543839600, 61564924800, -10800, 0, 'BRT' ], [ 61564935600, 61575472800, 61564928400, 61575465600, -7200, 1, 'BRST' ], [ 61575472800, 61596558000, 61575462000, 61596547200, -10800, 0, 'BRT' ], [ 61596558000, 61604330400, 61596550800, 61604323200, -7200, 1, 'BRST' ], [ 61604330400, 61944318000, 61604319600, 61944307200, -10800, 0, 'BRT' ], [ 61944318000, 61951485600, 61944310800, 61951478400, -7200, 1, 'BRST' ], [ 61951485600, 61980519600, 61951474800, 61980508800, -10800, 0, 'BRT' ], [ 61980519600, 61985613600, 61980512400, 61985606400, -7200, 1, 'BRST' ], [ 61985613600, 62006785200, 61985602800, 62006774400, -10800, 0, 'BRT' ], [ 62006785200, 62014557600, 62006778000, 62014550400, -7200, 1, 'BRST' ], [ 62014557600, 62035729200, 62014546800, 62035718400, -10800, 0, 'BRT' ], [ 62035729200, 62046093600, 62035722000, 62046086400, -7200, 1, 'BRST' ], [ 62046093600, 62067265200, 62046082800, 62067254400, -10800, 0, 'BRT' ], [ 62067265200, 62077716000, 62067258000, 62077708800, -7200, 1, 'BRST' ], [ 62077716000, 62635431600, 62077705200, 62635420800, -10800, 0, 'BRT' ], [ 62635431600, 62646919200, 62635424400, 62646912000, -7200, 1, 'BRST' ], [ 62646919200, 62666276400, 62646908400, 62666265600, -10800, 0, 'BRT' ], [ 62666276400, 62675949600, 62666269200, 62675942400, -7200, 1, 'BRST' ], [ 62675949600, 62697812400, 62675938800, 62697801600, -10800, 0, 'BRT' ], [ 62697812400, 62706880800, 62697805200, 62706873600, -7200, 1, 'BRST' ], [ 62706880800, 62728657200, 62706870000, 62728646400, -10800, 0, 'BRT' ], [ 62728657200, 62737725600, 62728650000, 62737718400, -7200, 1, 'BRST' ], [ 62737725600, 62760106800, 62737714800, 62760096000, -10800, 0, 'BRT' ], [ 62760106800, 62770384800, 62760099600, 62770377600, -7200, 1, 'BRST' ], [ 62770384800, 62789223600, 62770374000, 62789212800, -10800, 0, 'BRT' ], [ 62789223600, 63074343600, 62789212800, 63074332800, -10800, 0, 'BRT' ], [ 63074343600, 63074602800, 63074332800, 63074592000, -10800, 0, 'BRT' ], [ 63074602800, 63087300000, 63074595600, 63087292800, -7200, 1, 'BRST' ], [ 63087300000, 63106657200, 63087289200, 63106646400, -10800, 0, 'BRT' ], [ 63106657200, 63107258400, 63106650000, 63107251200, -7200, 1, 'BRST' ], [ 63107258400, 63136033200, 63107247600, 63136022400, -10800, 0, 'BRT' ], [ 63136033200, 63138711600, 63136022400, 63138700800, -10800, 0, 'BRT' ], [ 63138711600, 63149594400, 63138704400, 63149587200, -7200, 1, 'BRST' ], [ 63149594400, 63169124400, 63149583600, 63169113600, -10800, 0, 'BRT' ], [ 63169124400, DateTime::TimeZone::INFINITY, 63169113600, DateTime::TimeZone::INFINITY, -10800, 0, 'BRT' ], ]; sub olson_version { '2008c' } sub has_dst_changes { 19 } sub _max_year { 2018 } sub _new_instance { return shift->_init( @_, spans => $spans ); } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/DateTime/TimeZone/America/Recife.pm
Perl
mit
4,394
:- module(rdf_test, [load_manifest/0,run_rdf_tests/0]). /** <module> Run W3C tests for RDF @author Wouter Beek @version 2015/08 */ :- use_module(library(apply)). :- use_module(library(io_ext)). :- use_module(library(rdf/rdf_convert)). :- use_module(library(rdf/rdf_list)). :- use_module(library(rdf/rdf_read)). :- use_module(library(rdfs/rdfs_read)). :- use_module(library(semweb/rdf_db)). :- use_module(library(semweb/rdf_http_plugin)). :- use_module(library(semweb/turtle)). :- dynamic(current_manifest/1). :- rdf_register_prefix(mf, 'http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#'). :- rdf_register_prefix(rdft, 'http://www.w3.org/ns/rdftest#'). manifest_uri('http://www.w3.org/2013/TurtleTests/manifest.ttl'). load_manifest:- clean_current_manifest, manifest_uri(Uri), rdf_load(Uri, [base_uri(Uri),format(turtle),graph(manifest)]), assert(current_manifest(Uri)). clean_current_manifest:- rdf_retractall(_, _, _, manifest), retractall(current_manifest(_)). mf_test(Test):- rdf_instance(MF, mf:'Manifest', manifest), rdf(MF, mf:entries, Entries, manifest), rdf_list_member_raw(Test, Entries, manifest). run_rdf_tests:- forall(mf_test(Test), run_rdf_test(Test)). run_rdf_test(Test):- announce_test(Test), !, rdf(Test, mf:action, Uri, manifest), print_input(Uri, [indent(2)]), rdf_convert(Uri, To, []), print_input(To, [indent(2)]). announce_test(Test):- rdf_literal(Test, mf:name, xsd:string, Name, manifest), rdfs_comment(Test, Comment), format('Test ~a:~nComment: ~a~n', [Name,Comment]).
Anniepoo/plRdf
prolog/rdf/rdf_test.pl
Perl
mit
1,551
/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: J.Wielemaker@vu.nl WWW: http://www.swi-prolog.org Copyright (c) 2009-2014, VU University, Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(http_server_files, [ serve_files_in_directory/2 % +Alias, +HTTPRequest ]). :- use_module(library(http/http_path)). :- use_module(library(http/http_dispatch)). /** <module> Serve files needed by modules from the server This module provides an infrastructure for serving resource-files such as icons, JavaScript, CSS files, etc. The default configuration serves the HTTP locations =icons=, =css= and =js= (see http_absolute_location/3) The location for these services can be changed by adding rules for http:location/3. Directories providing additional or alternative resources can be achieved by adding rules for user:file_search_path/2. */ :- multifile http:location/3. % Alias, Expansion, Options :- dynamic http:location/3. % Alias, Expansion, Options http:location(icons, root(icons), [ priority(-100) ]). http:location(css, root(css), [ priority(-100) ]). http:location(js, root(js), [ priority(-100) ]). :- multifile user:file_search_path/2. :- dynamic user:file_search_path/2. user:file_search_path(icons, library('http/web/icons')). user:file_search_path(css, library('http/web/css')). user:file_search_path(js, library('http/web/js')). :- http_handler(icons(.), serve_files_in_directory(icons), [prefix, priority(-100)]). :- http_handler(css(.), serve_files_in_directory(css), [prefix, priority(-100)]). :- http_handler(js(.), serve_files_in_directory(js), [prefix, priority(-100)]). %! serve_files_in_directory(+Alias, +Request) % % Serve files from the directory Alias from the path-info from % Request. This predicate is used together with % file_search_path/2. Note that multiple clauses for the same % file_search_path alias can be used to merge files from different % physical locations onto the same HTTP directory. Note that the % handler must be declared as =prefix=. Below is an example % serving images from http://<host>/img/... from the directory % =http/web/icons=. % % == % http:location(img, root(img), []). % user:file_search_path(icons, library('http/web/icons')). % % :- http_handler(img(.), serve_files_in_directory(icons), [prefix]). % == % % This predicate calls http_404/2 if the physical file cannot be % located. If the requested path-name is unsafe (i.e., points % outside the hierarchy defines by the file_search_path/2 % declaration), this handlers returns a _403 Forbidden_ page. % % @see http_reply_file/3 serve_files_in_directory(Alias, Request) :- memberchk(path_info(PathInfo), Request), !, Term =.. [Alias,PathInfo], ( catch(http_safe_file(Term, []), error(permission_error(read, file, _), _), fail) -> ( absolute_file_name(Term, Path, [ access(read), file_errors(fail) ]) -> http_reply_file(Path, [ unsafe(true), static_gzip(true) ], Request) ; http_404([], Request) ) ; memberchk(path(Path), Request), throw(http_reply(forbidden(Path))) ). serve_files_in_directory(_Alias, Request) :- memberchk(path(Path), Request), throw(http_reply(forbidden(Path))).
TeamSPoon/logicmoo_workspace
docker/rootfs/usr/local/lib/swipl/library/http/http_server_files.pl
Perl
mit
5,054
=head1 NAME Attean::API::ResultSerializer - Role for serializers of L<Attean::API::Result> objects =head1 VERSION This document describes Attean::API::ResultSerializer version 0.002 =head1 DESCRIPTION The Attean::API::ResultSerializer role defines serializers of L<Attean::API::Result> objects. =head1 ROLES This role consumes the L<Attean::API::Serializer> roles which provide the following methods: =over 4 =item C<< serialize_list_to_io( $fh, @elements ) >> =item C<< serialize_list_to_bytes( @elements ) >> =back =head1 METHODS This role provides default implementations of the following methods: =over 4 =item C<< handled_type >> Returns a L<Type::Tiny> object for objects which consume the L<Attean::API::Result> role. =back =head1 BUGS Please report any bugs or feature requests to through the GitHub web interface at L<https://github.com/kasei/attean/issues>. =head1 SEE ALSO L<http://www.perlrdf.org/> =head1 AUTHOR Gregory Todd Williams C<< <gwilliams@cpan.org> >> =head1 COPYRIGHT Copyright (c) 2014 Gregory Todd Williams. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
gitpan/Attean
lib/Attean/API/ResultSerializer.pod
Perl
mit
1,175
%query: count(i,o). /* from Giesl, 1995 */ flatten(atom(X),[X]). flatten(cons(atom(X),U),[X|Y]) :- flatten(U,Y). flatten(cons(cons(U,V),W),X) :- flatten(cons(U,cons(V,W)),X). count(atom(X),s(0)). count(cons(atom(X),Y),s(Z)) :- count(Y,Z). count(cons(cons(U,V),W),Z) :- flatten(cons(cons(U,V),W),X), count(X,Z).
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Logic_Programming/SGST06/flatten_phd.pl
Perl
mit
314
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package storage::netapp::ontap::oncommandapi::custom::api; use strict; use warnings; use centreon::plugins::http; use JSON::XS; sub new { my ($class, %options) = @_; my $self = {}; bless $self, $class; if (!defined($options{output})) { print "Class Custom: Need to specify 'output' argument.\n"; exit 3; } if (!defined($options{options})) { $options{output}->add_option_msg(short_msg => "Class Custom: Need to specify 'options' argument."); $options{output}->option_exit(); } if (!defined($options{noptions})) { $options{options}->add_options(arguments => { 'hostname:s' => { name => 'hostname' }, 'url-path:s' => { name => 'url_path' }, 'port:s' => { name => 'port' }, 'proto:s' => { name => 'proto' }, 'username:s' => { name => 'username' }, 'password:s' => { name => 'password' }, 'timeout:s' => { name => 'timeout' } }); } $options{options}->add_help(package => __PACKAGE__, sections => 'OnCommand API OPTIONS', once => 1); $self->{output} = $options{output}; $self->{http} = centreon::plugins::http->new(%options); return $self; } sub set_options { my ($self, %options) = @_; $self->{option_results} = $options{option_results}; } sub set_defaults {} sub check_options { my ($self, %options) = @_; $self->{hostname} = (defined($self->{option_results}->{hostname})) ? $self->{option_results}->{hostname} : ''; $self->{url_path} = (defined($self->{option_results}->{url_path})) ? $self->{option_results}->{url_path} : '/api/4.0/ontap'; $self->{port} = (defined($self->{option_results}->{port})) ? $self->{option_results}->{port} : 8443; $self->{proto} = (defined($self->{option_results}->{proto})) ? $self->{option_results}->{proto} : 'https'; $self->{username} = (defined($self->{option_results}->{username})) ? $self->{option_results}->{username} : ''; $self->{password} = (defined($self->{option_results}->{password})) ? $self->{option_results}->{password} : ''; $self->{timeout} = (defined($self->{option_results}->{timeout})) ? $self->{option_results}->{timeout} : 10; if ($self->{hostname} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify hostname option."); $self->{output}->option_exit(); } return 0; } sub build_options_for_httplib { my ($self, %options) = @_; $self->{option_results}->{hostname} = $self->{hostname}; $self->{option_results}->{timeout} = $self->{timeout}; $self->{option_results}->{port} = $self->{port}; $self->{option_results}->{proto} = $self->{proto}; $self->{option_results}->{credentials} = 1; $self->{option_results}->{basic} = 1; $self->{option_results}->{username} = $self->{username}; $self->{option_results}->{password} = $self->{password}; $self->{option_results}->{warning_status} = ''; $self->{option_results}->{critical_status} = ''; } sub settings { my ($self, %options) = @_; $self->build_options_for_httplib(); $self->{http}->set_options(%{$self->{option_results}}); } sub get_connection_info { my ($self, %options) = @_; return $self->{hostname} . ":" . $self->{port}; } sub get_objects { my ($self, %options) = @_; my %objects; my $objects = $self->get(%options); foreach my $object (@{$objects}) { $objects{ $object->{ $options{key} } } = $object->{ $options{name} }; } return \%objects; } sub get_next { my ($self, %options) = @_; my $get_param = []; $get_param = $options{get_param} if (defined($options{get_param})); push @$get_param, 'nextTag=' . $options{nextTag} if (defined($options{nextTag})); my $response = $self->{http}->request( url_path => $self->{url_path} . $options{path}, get_param => $get_param ); my $content; eval { $content = JSON::XS->new->utf8->decode($response); }; if ($@) { $self->{output}->add_option_msg(short_msg => "Cannot decode json response: $@"); $self->{output}->option_exit(); } if (defined($content->{errmsg})) { $self->{output}->add_option_msg(short_msg => "Cannot get data: " . $content->{errmsg}); $self->{output}->option_exit(); } return $content; } sub get { my ($self, %options) = @_; $self->settings(); my @result; while (my $content = $self->get_next(%options)) { push @result, @{$content->{result}->{records}}; last if (!defined($content->{result}->{nextTag})); $options{nextTag} = $content->{result}->{nextTag}; } return \@result; } sub get_record_attr { my ($self, %options) = @_; foreach (@{$options{records}}) { if ($_->{ $options{key} } eq $options{value}) { return $_->{ $options{attr} }; } } } 1; __END__ =head1 NAME NetApp OnCommand API =head1 SYNOPSIS NetApp OnCommand API custom mode =head1 OnCommand API OPTIONS =over 8 =item B<--hostname> NetApp hostname. =item B<--url-path> OnCommand API url path (Default: '/api/4.0/ontap') =item B<--port> OnCommand API port (Default: 8443) =item B<--proto> Specify https if needed (Default: 'https') =item B<--username> OnCommand API username. =item B<--password> OnCommand API password. =item B<--timeout> Set HTTP timeout =back =head1 DESCRIPTION B<custom>. =cut
centreon/centreon-plugins
storage/netapp/ontap/oncommandapi/custom/api.pm
Perl
apache-2.0
6,219
package API::Cdn; # # # 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 UI::Utils; use Mojo::Base 'Mojolicious::Controller'; use Data::Dumper; use Carp qw(cluck confess); use JSON; use MIME::Base64; use UI::DeliveryService; use MojoPlugins::Response; use Common::ReturnCodes qw(SUCCESS ERROR); use strict; sub index { my $self = shift; my @data; my $orderby = $self->param('orderby') || "name"; my $rs_data = $self->db->resultset("Cdn")->search( undef, { order_by => $orderby } ); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "name" => $row->name, "domainName" => $row->domain_name, "dnssecEnabled" => \$row->dnssec_enabled, "lastUpdated" => $row->last_updated, } ); } $self->success( \@data ); } sub show { my $self = shift; my $id = $self->param('id'); my $rs_data = $self->db->resultset("Cdn")->search( { id => $id } ); my @data = (); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "name" => $row->name, "domainName" => $row->domain_name, "dnssecEnabled" => \$row->dnssec_enabled, "lastUpdated" => $row->last_updated, } ); } $self->success( \@data ); } sub name { my $self = shift; my $cdn = $self->param('name'); my $rs_data = $self->db->resultset("Cdn")->search( { name => $cdn } ); my @data = (); while ( my $row = $rs_data->next ) { push( @data, { "id" => $row->id, "name" => $row->name, "domainName" => $row->domain_name, "dnssecEnabled" => \$row->dnssec_enabled, "lastUpdated" => $row->last_updated, } ); } $self->success( \@data ); } sub create { my $self = shift; my $params = $self->req->json; if ( !&is_oper($self) ) { return $self->forbidden(); } if ( !defined($params) ) { return $self->alert("parameters must be in JSON format."); } if ( !defined( $params->{name} ) ) { return $self->alert("CDN 'name' is required."); } if ( !defined( $params->{dnssecEnabled} ) ) { return $self->alert("dnssecEnabled is required."); } if ( !defined( $params->{domainName} ) ) { return $self->alert("Domain Name is required."); } my $existing = $self->db->resultset('Cdn')->search( { name => $params->{name} } )->single(); if ($existing) { $self->app->log->error( "a cdn with name '" . $params->{name} . "' already exists." ); return $self->alert( "a cdn with name " . $params->{name} . " already exists." ); } $existing = $self->db->resultset('Cdn')->search( { domain_name => $params->{domainName} } )->single(); if ($existing) { $self->app->log->error( "a cdn with domain name '" . $params->{domainName} . "' already exists." ); return $self->alert( "a cdn with domain " . $params->{domainName} . " already exists." ); } my $values = { name => $params->{name}, dnssec_enabled => $params->{dnssecEnabled}, domain_name => $params->{domainName}, }; my $insert = $self->db->resultset('Cdn')->create($values); $insert->insert(); my $rs = $self->db->resultset('Cdn')->find( { id => $insert->id } ); if ( defined($rs) ) { my $response; $response->{id} = $rs->id; $response->{name} = $rs->name; $response->{domainName} = $rs->domain_name; $response->{dnssecEnabled} = \$rs->dnssec_enabled; &log( $self, "Created CDN with id: " . $rs->id . " and name: " . $rs->name, "APICHANGE" ); return $self->success( $response, "cdn was created." ); } return $self->alert("create cdn failed."); } sub update { my $self = shift; my $id = $self->param('id'); my $params = $self->req->json; if ( !&is_oper($self) ) { return $self->forbidden(); } my $cdn = $self->db->resultset('Cdn')->find( { id => $id } ); if ( !defined($cdn) ) { return $self->not_found(); } if ( !defined( $params->{name} ) ) { return $self->alert("Name is required."); } if ( !defined( $params->{dnssecEnabled} ) ) { return $self->alert("dnssecEnabled is required."); } if ( !defined( $params->{domainName} ) ) { return $self->alert("Domain Name is required."); } my $existing = $self->db->resultset('Cdn')->search( { name => $params->{name} } )->single(); if ( $existing && $existing->id != $cdn->id ) { return $self->alert( "a cdn with name " . $params->{name} . " already exists." ); } $existing = $self->db->resultset('Cdn')->search( { domain_name => $params->{domainName} } )->single(); if ( $existing && $existing->id != $cdn->id ) { return $self->alert( "a cdn with domain name " . $params->{domainName} . " already exists." ); } my $values = { name => $params->{name}, dnssec_enabled => $params->{dnssecEnabled}, domain_name => $params->{domainName}, }; my $rs = $cdn->update($values); if ( $rs ) { my $response; $response->{id} = $rs->id; $response->{name} = $rs->name; $response->{domainName} = $rs->domain_name; $response->{dnssecEnabled} = \$rs->dnssec_enabled; &log( $self, "Updated CDN name '" . $rs->name . "' for id: " . $rs->id, "APICHANGE" ); return $self->success( $response, "CDN update was successful." ); } return $self->alert("CDN update failed."); } sub delete { my $self = shift; my $id = $self->param('id'); if ( !&is_oper($self) ) { return $self->forbidden(); } my $cdn = $self->db->resultset('Cdn')->search( { id => $id } ); if ( !defined($cdn) ) { return $self->not_found(); } my $rs = $self->db->resultset('Server')->search( { cdn_id => $id } ); if ( $rs->count() > 0 ) { $self->app->log->error("Failed to delete cdn id = $id has servers"); return $self->alert("Failed to delete cdn id = $id has servers"); } $rs = $self->db->resultset('Deliveryservice')->search( { cdn_id => $id } ); if ( $rs->count() > 0 ) { $self->app->log->error("Failed to delete cdn id = $id has delivery services"); return $self->alert("Failed to delete cdn id = $id has delivery services"); } my $name = $cdn->get_column('name')->single(); $cdn->delete(); &log( $self, "Delete cdn " . $name, "APICHANGE" ); return $self->success_message("cdn was deleted."); } sub delete_by_name { my $self = shift; my $cdn_name = $self->param('name'); if ( !&is_oper($self) ) { return $self->forbidden(); } my $cdn = $self->db->resultset('Cdn')->find( { name => $cdn_name } ); if ( !defined($cdn) ) { return $self->not_found(); } my $id = $cdn->id; my $rs = $self->db->resultset('Server')->search( { cdn_id => $id } ); if ( $rs->count() > 0 ) { $self->app->log->error("Failed to delete cdn id = $id has servers"); return $self->alert("Failed to delete cdn id = $id has servers"); } $rs = $self->db->resultset('Deliveryservice')->search( { cdn_id => $id } ); if ( $rs->count() > 0 ) { $self->app->log->error("Failed to delete cdn id = $id has delivery services"); return $self->alert("Failed to delete cdn id = $id has delivery services"); } $cdn->delete(); &log( $self, "Delete cdn " . $cdn_name, "APICHANGE" ); return $self->success_message("cdn was deleted."); } sub queue_updates { my $self = shift; my $params = $self->req->json; my $cdn_id = $self->param('id'); if ( !&is_oper($self) ) { return $self->forbidden("Forbidden. You must have the operations role to perform this operation."); } my $cdn = $self->db->resultset('Cdn')->find( { id => $cdn_id } ); if ( !defined($cdn) ) { return $self->not_found(); } my $cdn_servers = $self->db->resultset('Server')->search( { cdn_id => $cdn_id } ); if ( $cdn_servers->count() < 1 ) { return $self->alert("No servers found for cdn_id = $cdn_id"); } my $setqueue = $params->{action}; if ( $setqueue eq "queue" ) { $setqueue = 1; } elsif ( $setqueue eq "dequeue" ) { $setqueue = 0; } else { return $self->alert("Action required, Should be queue or dequeue."); } $cdn_servers->update( { upd_pending => $setqueue } ); my $msg = "Server updates " . $params->{action} . "d for " . $cdn->name; &log( $self, $msg, "APICHANGE" ); my $response; $response->{cdnId} = $cdn_id; $response->{action} = $params->{action}; return $self->success($response, $msg); } sub configs_monitoring { my $self = shift; my $cdn_name = $self->param('name'); my $extension = $self->param('extension'); my $data_obj = $self->get_traffic_monitor_config($cdn_name); $self->success($data_obj); } sub get_traffic_monitor_config { my $self = shift; my $cdn_name = shift || confess("Please supply a CDN name"); my $rascal_profile; my @cache_profiles; my @ccr_profiles; my $ccr_profile_id; my $data_obj; my $profile_to_type; my $rs_pp = $self->db->resultset('Server')->search( { 'cdn.name' => $cdn_name }, { prefetch => ['cdn', 'profile', 'type'], select => 'me.profile', distinct => 1, group_by => [qw/cdn.id profile.id me.profile type.id/], } ); while ( my $row = $rs_pp->next ) { if ( $row->type->name =~ m/^RASCAL/ ) { $rascal_profile = $row->profile->name; } elsif ( $row->type->name =~ m/^CCR/ ) { push( @ccr_profiles, $row->profile->name ); # TODO MAT: support multiple CCR profiles $ccr_profile_id = $row->profile->id; } elsif ( $row->type->name =~ m/^EDGE/ || $row->type->name =~ m/^MID/ ) { push( @cache_profiles, $row->profile->name ); $profile_to_type->{$row->profile->name}->{$row->type->name} = $row->type->name; } } my %condition = ( 'parameter.config_file' => 'rascal-config.txt', 'profile.name' => $rascal_profile ); $rs_pp = $self->db->resultset('ProfileParameter')->search( \%condition, { prefetch => [ { 'parameter' => undef }, { 'profile' => undef } ] } ); while ( my $row = $rs_pp->next ) { my $parameter; if ( $row->parameter->name =~ m/location/ ) { next; } if ( $row->parameter->value =~ m/^\d+$/ ) { $data_obj->{'config'}->{ $row->parameter->name } = int( $row->parameter->value ); } else { $data_obj->{'config'}->{ $row->parameter->name } = $row->parameter->value; } } %condition = ( 'parameter.config_file' => 'rascal.properties', 'profile.name' => { -in => \@cache_profiles } ); $rs_pp = $self->db->resultset('ProfileParameter')->search( \%condition, { prefetch => [ { 'parameter' => undef }, { 'profile' => undef } ] } ); if ( !exists( $data_obj->{'profiles'} ) ) { $data_obj->{'profiles'} = undef; } my $profile_tracker; while ( my $row = $rs_pp->next ) { if ( exists($profile_to_type->{$row->profile->name}) ) { for my $profile_type ( keys(%{$profile_to_type->{$row->profile->name}}) ) { $profile_tracker->{ $profile_type }->{ $row->profile->name }->{'type'} = $profile_type; $profile_tracker->{ $profile_type }->{ $row->profile->name }->{'name'} = $row->profile->name; if ( $row->parameter->value =~ m/^\d+$/ ) { $profile_tracker->{ $profile_type }->{ $row->profile->name }->{'parameters'}->{ $row->parameter->name } = int( $row->parameter->value ); } else { $profile_tracker->{ $profile_type }->{ $row->profile->name }->{'parameters'}->{ $row->parameter->name } = $row->parameter->value; } } } } foreach my $type ( keys %{$profile_tracker} ) { foreach my $profile ( keys %{$profile_tracker->{$type}} ) { push( @{ $data_obj->{'profiles'} }, $profile_tracker->{$type}->{$profile} ); } } foreach my $ccr_profile (@ccr_profiles) { my $profile; $profile->{'name'} = $ccr_profile; $profile->{'type'} = "CCR"; $profile->{'parameters'} = undef; push( @{ $data_obj->{'profiles'} }, $profile ); } my $rs_ds = $self->db->resultset('Deliveryservice')->search( { 'me.profile' => $ccr_profile_id, 'active' => 1 }, {} ); while ( my $row = $rs_ds->next ) { my $delivery_service; # MAT: Do we move this to the DB? Rascal needs to know if it should monitor a DS or not, and the status=REPORTED is what we do for caches. $delivery_service->{'xmlId'} = $row->xml_id; $delivery_service->{'status'} = "REPORTED"; $delivery_service->{'totalKbpsThreshold'} = ( defined( $row->global_max_mbps ) && $row->global_max_mbps > 0 ) ? ( $row->global_max_mbps * 1000 ) : 0; $delivery_service->{'totalTpsThreshold'} = int( $row->global_max_tps || 0 ); push( @{ $data_obj->{'deliveryServices'} }, $delivery_service ); } my $caches_query = 'SELECT me.host_name as hostName, CONCAT(me.host_name, \'.\', me.domain_name) as fqdn, status.name as status, cachegroup.name as cachegroup, me.tcp_port as port, me.ip_address as ip, me.ip6_address as ip6, profile.name as profile, me.interface_name as interfaceName, type.name as type, me.xmpp_id as hashId FROM server me JOIN type type ON type.id = me.type JOIN status status ON status.id = me.status JOIN cachegroup cachegroup ON cachegroup.id = me.cachegroup JOIN profile profile ON profile.id = me.profile JOIN cdn cdn ON cdn.id = me.cdn_id WHERE cdn.name = ?;'; my $dbh = $self->db->storage->dbh; my $caches_servers = $dbh->selectall_arrayref( $caches_query, {Columns=>{}}, ($cdn_name) ); foreach (@{ $caches_servers }) { if ( $_->{'type'} eq "RASCAL" ) { push( @{ $data_obj->{'trafficMonitors'} }, $_ ); } elsif ( $_->{'type'} =~ m/^EDGE/ || $_->{'type'} =~ m/^MID/ ) { push( @{ $data_obj->{'trafficServers'} }, $_ ); } } my $rs_loc = $self->db->resultset('Server')->search( { 'cdn.name' => $cdn_name }, { join => [ 'cdn', 'cachegroup' ], select => [ 'cachegroup.name', 'cachegroup.latitude', 'cachegroup.longitude' ], distinct => 1 } ); while ( my $row = $rs_loc->next ) { my $cache_group; my $latitude = $row->cachegroup->latitude + 0; my $longitude = $row->cachegroup->longitude + 0; $cache_group->{'coordinates'}->{'latitude'} = $latitude; $cache_group->{'coordinates'}->{'longitude'} = $longitude; $cache_group->{'name'} = $row->cachegroup->name; push( @{ $data_obj->{'cacheGroups'} }, $cache_group ); } return ($data_obj); } sub capacity { my $self = shift; return $self->get_cache_capacity(); } sub health { my $self = shift; my $args = {}; my $cdn_name = $self->param('name'); if (defined($cdn_name)) { $args->{'cdn_name'} = $cdn_name; } return $self->get_cache_health($args); } sub routing { my $self = shift; my $args = shift; if ( !exists( $args->{status} ) ) { $args->{status} = "ONLINE"; } $args->{type} = "CCR"; my $ccr_map = $self->get_host_map($args); my $data = {}; my $stats = { totalCount => 0, raw => {}, }; for my $cdn_name ( keys( %{$ccr_map} ) ) { for my $ccr ( keys( %{ $ccr_map->{$cdn_name} } ) ) { my $ccr_host = $ccr_map->{$cdn_name}->{$ccr}->{host_name} . "." . $ccr_map->{$cdn_name}->{$ccr}->{domain_name}; # TODO: what happens when the request to CCR times out? -jse my $c = $self->get_traffic_router_connection( { hostname => $ccr_host } ); my $s = $c->get_crs_stats(); if ( !defined($s) ) { return $self->internal_server_error( { "Internal Server" => "Error" } ); } else { if ( exists( $s->{stats} ) ) { for my $type ( "httpMap", "dnsMap" ) { next if ( exists( $args->{stat_key} ) && $args->{stat_key} ne $type ); if ( exists( $s->{stats}->{$type} ) ) { for my $fqdn ( keys( %{ $s->{stats}->{$type} } ) ) { my $count = 1; if ( exists( $args->{patterns} ) && ref( $args->{patterns} ) eq "ARRAY" ) { $count = 0; for my $pattern ( @{ $args->{patterns} } ) { if ( $fqdn =~ /$pattern/ ) { $count = 1; last; } } } if ($count) { for my $counter ( keys( %{ $s->{stats}->{$type}->{$fqdn} } ) ) { if ( !exists( $stats->{raw}->{$counter} ) ) { $stats->{raw}->{$counter} = 0; } $stats->{raw}->{$counter} += $s->{stats}->{$type}->{$fqdn}->{$counter}; $stats->{totalCount} += $s->{stats}->{$type}->{$fqdn}->{$counter}; } } if ($count) { for my $counter ( keys( %{ $s->{stats}->{$type}->{$fqdn} } ) ) { if ( !exists( $stats->{raw}->{$counter} ) ) { $stats->{raw}->{$counter} = 0; } $stats->{raw}->{$counter} += $s->{stats}->{$type}->{$fqdn}->{$counter}; $stats->{totalCount} += $s->{stats}->{$type}->{$fqdn}->{$counter}; } } } } } } } } } for my $counter ( keys( %{ $stats->{raw} } ) ) { my $p = $counter; $p =~ s/Count//gi; if ( $stats->{totalCount} > 0 ) { $data->{$p} = ( $stats->{raw}->{$counter} / $stats->{totalCount} ) * 100; } else { $data->{$p} = 0; } } $self->success($data); } sub configs_routing { my $self = shift; my $cdn_name = $self->param('name'); my $data_obj; my $json = $self->gen_traffic_router_config($cdn_name); $self->success($json); } sub gen_traffic_router_config { my $self = shift; my $cdn_name = shift; my $data_obj; my $ccr_profile_id; my $ccr_domain_name = ""; my $cdn_soa_minimum = 30; my $cdn_soa_expire = 604800; my $cdn_soa_retry = 7200; my $cdn_soa_refresh = 28800; my $cdn_soa_admin = "traffic_ops"; my $tld_ttls_soa = 86400; my $tld_ttls_ns = 3600; $SIG{__WARN__} = sub { warn $_[0] unless $_[0] =~ m/Prefetching multiple has_many rels deliveryservice_servers/; }; $data_obj->{'stats'}->{'cdnName'} = $cdn_name; $data_obj->{'stats'}->{'date'} = time(); $data_obj->{'stats'}->{'trafficOpsVersion'} = &tm_version(); $data_obj->{'stats'}->{'trafficOpsPath'} = $self->req->url->path->{'path'}; $data_obj->{'stats'}->{'trafficOpsHost'} = $self->req->headers->host; $data_obj->{'stats'}->{'trafficOpsUser'} = $self->current_user()->{username}; my @cdn_profiles = $self->db->resultset('Server')->search( { 'cdn.name' => $cdn_name }, { prefetch => ['cdn'] } )->get_column('profile')->all(); if ( scalar(@cdn_profiles) ) { $ccr_profile_id = $self->db->resultset('Profile')->search( { id => { -in => \@cdn_profiles }, name => { -like => 'CCR%' } } )->get_column('id')->single(); if ( !defined($ccr_profile_id) ) { my $e = Mojo::Exception->throw("No CCR profile found in profile IDs: @cdn_profiles "); } } else { my $e = Mojo::Exception->throw( "No profiles found for CDN_name: " . $cdn_name ); } my %condition = ( 'profile_parameters.profile' => $ccr_profile_id, 'config_file' => 'CRConfig.json' ); $ccr_domain_name = $self->db->resultset('Cdn')->search({ 'name' => $cdn_name})->get_column('domain_name')->single(); my $rs_config = $self->db->resultset('Parameter')->search( \%condition, { join => 'profile_parameters' } ); while ( my $row = $rs_config->next ) { if ( $row->name eq 'tld.soa.admin' ) { $cdn_soa_admin = $row->value; } if ( $row->name eq 'tld.soa.expire' ) { $cdn_soa_expire = $row->value; } if ( $row->name eq 'tld.soa.minimum' ) { $cdn_soa_minimum = $row->value; } if ( $row->name eq 'tld.soa.refresh' ) { $cdn_soa_refresh = $row->value; } if ( $row->name eq 'tld.soa.retry' ) { $cdn_soa_retry = $row->value; } if ( $row->name eq 'tld.ttls.SOA' ) { $tld_ttls_soa = $row->value; } if ( $row->name eq 'tld.ttls.NS' ) { $tld_ttls_ns = $row->value; } my $parameter->{'type'} = "parameter"; if ( $row->value =~ m/^\d+$/ ) { $data_obj->{'config'}->{ $row->name } = int( $row->value ); } else { $data_obj->{'config'}->{ $row->name } = $row->value; } } my $rs_loc = $self->db->resultset('Server')->search( { 'cdn.name' => $cdn_name }, { join => [ 'cdn', 'cachegroup' ], select => [ 'cachegroup.name', 'cachegroup.latitude', 'cachegroup.longitude' ], distinct => 1 } ); while ( my $row = $rs_loc->next ) { my $cache_group; my $latitude = $row->cachegroup->latitude + 0; my $longitude = $row->cachegroup->longitude + 0; $cache_group->{'coordinates'}->{'latitude'} = $latitude; $cache_group->{'coordinates'}->{'longitude'} = $longitude; $cache_group->{'name'} = $row->cachegroup->name; push( @{ $data_obj->{'cacheGroups'} }, $cache_group ); } my $regex_tracker; my $rs_regexes = $self->db->resultset('Regex')->search( {}, { 'prefetch' => 'type' } ); while ( my $row = $rs_regexes->next ) { $regex_tracker->{ $row->id }->{'type'} = $row->type->name; $regex_tracker->{ $row->id }->{'pattern'} = $row->pattern; } my %cache_tracker; my $rs_caches = $self->db->resultset('Server')->search( { 'profile' => { -in => \@cdn_profiles } }, { prefetch => [ 'type', 'status', 'cachegroup', 'profile' ], columns => [ 'host_name', 'domain_name', 'tcp_port', 'interface_name', 'ip_address', 'ip6_address', 'id', 'xmpp_id' ] } ); while ( my $row = $rs_caches->next ) { if ( $row->type->name eq "RASCAL" ) { my $traffic_monitor; $traffic_monitor->{'hostName'} = $row->host_name; $traffic_monitor->{'fqdn'} = $row->host_name . "." . $row->domain_name; $traffic_monitor->{'status'} = $row->status->name; $traffic_monitor->{'location'} = $row->cachegroup->name; $traffic_monitor->{'port'} = int( $row->tcp_port ); $traffic_monitor->{'ip'} = $row->ip_address; $traffic_monitor->{'ip6'} = $row->ip6_address; $traffic_monitor->{'profile'} = $row->profile->name; push( @{ $data_obj->{'trafficMonitors'} }, $traffic_monitor ); } elsif ( $row->type->name eq "CCR" ) { my $rs_param = $self->db->resultset('Parameter')->search( { 'profile_parameters.profile' => $row->profile->id, 'name' => 'api.port' }, { join => 'profile_parameters' } ); my $r = $rs_param->single; my $api_port = ( defined($r) && defined( $r->value ) ) ? $r->value : 3333; my $traffic_router; $traffic_router->{'hostName'} = $row->host_name; $traffic_router->{'fqdn'} = $row->host_name . "." . $row->domain_name; $traffic_router->{'status'} = $row->status->name; $traffic_router->{'location'} = $row->cachegroup->name; $traffic_router->{'port'} = int( $row->tcp_port ); $traffic_router->{'apiPort'} = int($api_port); $traffic_router->{'ip'} = $row->ip_address; $traffic_router->{'ip6'} = $row->ip6_address; $traffic_router->{'profile'} = $row->profile->name; push( @{ $data_obj->{'trafficRouters'} }, $traffic_router ); } elsif ( $row->type->name =~ m/^EDGE/ || $row->type->name =~ m/^MID/ ) { if ( !exists $cache_tracker{ $row->id } ) { $cache_tracker{ $row->id } = $row->host_name; } my $traffic_server; $traffic_server->{'cacheGroup'} = $row->cachegroup->name; $traffic_server->{'hostName'} = $row->host_name; $traffic_server->{'fqdn'} = $row->host_name . "." . $row->domain_name; $traffic_server->{'port'} = int( $row->tcp_port ); $traffic_server->{'interfaceName'} = $row->interface_name; $traffic_server->{'status'} = $row->status->name; $traffic_server->{'ip'} = $row->ip_address; $traffic_server->{'ip6'} = ( $row->ip6_address || "" ); $traffic_server->{'profile'} = $row->profile->name; $traffic_server->{'type'} = $row->type->name; $traffic_server->{'hashId'} = $row->xmpp_id; push( @{ $data_obj->{'trafficServers'} }, $traffic_server ); } } my $ds_regex_tracker; my $regexps; my $rs_ds = $self->db->resultset('Deliveryservice') ->search( { 'me.profile' => $ccr_profile_id, 'active' => 1 }, { prefetch => [ 'deliveryservice_servers', 'deliveryservice_regexes', 'type' ] } ); while ( my $row = $rs_ds->next ) { my $delivery_service; $delivery_service->{'xmlId'} = $row->xml_id; my $protocol; if ( $row->type->name =~ m/DNS/ ) { $protocol = 'DNS'; } else { $protocol = 'HTTP'; } my @server_subrows = $row->deliveryservice_servers->all; my @regex_subrows = $row->deliveryservice_regexes->all; my $regex_to_props; my %ds_to_remap; if ( scalar(@regex_subrows) ) { foreach my $subrow (@regex_subrows) { $delivery_service->{'matchSets'}->[ $subrow->set_number ]->{'protocol'} = $protocol; $regex_to_props->{ $subrow->{'_column_data'}->{'regex'} }->{'pattern'} = $regex_tracker->{ $subrow->{'_column_data'}->{'regex'} }->{'pattern'}; $regex_to_props->{ $subrow->{'_column_data'}->{'regex'} }->{'setNumber'} = $subrow->set_number; $regex_to_props->{ $subrow->{'_column_data'}->{'regex'} }->{'type'} = $regex_tracker->{ $subrow->{'_column_data'}->{'regex'} }->{'type'}; if ( $regex_to_props->{ $subrow->{'_column_data'}->{'regex'} }->{'type'} eq 'HOST_REGEXP' ) { $ds_to_remap{ $row->xml_id }->[ $subrow->set_number ] = $regex_to_props->{ $subrow->{'_column_data'}->{'regex'} }->{'pattern'}; } } } my $domains; foreach my $regex ( sort keys %{$regex_to_props} ) { my $set_number = $regex_to_props->{$regex}->{'setNumber'}; my $pattern = $regex_to_props->{$regex}->{'pattern'}; my $type = $regex_to_props->{$regex}->{'type'}; if ( $type eq 'HOST_REGEXP' ) { push( @{ $delivery_service->{'matchSets'}->[$set_number]->{'matchList'} }, { 'matchType' => 'HOST', 'regex' => $pattern } ); my $host = $pattern; $host =~ s/\\//g; $host =~ s/\.\*//g; $host =~ s/\.//g; push @$domains, "$host.$ccr_domain_name"; } elsif ( $type eq 'PATH_REGEXP' ) { push( @{ $delivery_service->{'matchSets'}->[$set_number]->{'matchList'} }, { 'matchType' => 'PATH', 'regex' => $pattern } ); } elsif ( $type eq 'HEADER_REGEXP' ) { push( @{ $delivery_service->{'matchSets'}->[$set_number]->{'matchList'} }, { 'matchType' => 'HEADER', 'regex' => $pattern } ); } } $delivery_service->{'domains'} = $domains; if ( scalar(@server_subrows) ) { #my $host_regex = qr/(^(\.)+\*\\\.)(.*)(\\\.(\.)+\*$)/; my $host_regex1 = qr/\\|\.\*/; #MAT: Have to do this dedup because @server_subrows contains duplicates (* the # of host regexes) my %server_subrow_dedup; foreach my $subrow (@server_subrows) { $server_subrow_dedup{ $subrow->{'_column_data'}->{'server'} } = $subrow->{'_column_data'}->{'deliveryservice'}; } my $ds_regex->{'xmlId'} = $row->xml_id; foreach my $server ( keys %server_subrow_dedup ) { my @remaps; foreach my $host ( @{ $ds_to_remap{ $row->xml_id } } ) { my $remap; if ( $host =~ m/\.\*$/ ) { my $host_copy = $host; $host_copy =~ s/$host_regex1//g; if ( $protocol eq 'DNS' ) { $remap = 'edge' . $host_copy . $ccr_domain_name; } else { my $cache_tracker_server = $cache_tracker{$server} || ""; my $host_copy = $host_copy || ""; my $ccr_domain_name = $ccr_domain_name || ""; $remap = $cache_tracker_server . $host_copy . $ccr_domain_name; } } else { $remap = $host; } push( @remaps, $remap ); } my $cache_tracker_server = $cache_tracker{$server} || ""; push( @{ $ds_regex_tracker->{$cache_tracker_server}->{ $row->xml_id }->{'remaps'} }, @remaps ); } } $delivery_service->{'ttl'} = int( $row->ccr_dns_ttl ); my $geo_limit = $row->geo_limit; if ( $geo_limit == 1 ) { # Ref to 0 or 1 makes JSON bool value $delivery_service->{'coverageZoneOnly'} = \1; $delivery_service->{'geoEnabled'} = []; } elsif ( $geo_limit == 2 ) { # Ref to 0 or 1 makes JSON bool value $delivery_service->{'coverageZoneOnly'} = \0; $delivery_service->{'geoEnabled'} = [ { 'countryCode' => 'US' } ]; } elsif ( $geo_limit == 3 ) { # Ref to 0 or 1 makes JSON bool value $delivery_service->{'coverageZoneOnly'} = \0; $delivery_service->{'geoEnabled'} = [ { 'countryCode' => 'CA' } ]; } else { # Ref to 0 or 1 makes JSON bool value $delivery_service->{'coverageZoneOnly'} = \0; $delivery_service->{'geoEnabled'} = []; } my $bypass_destination; if ( $protocol =~ m/DNS/ ) { $bypass_destination->{'type'} = 'DNS'; if ( defined( $row->dns_bypass_ip ) && $row->dns_bypass_ip ne "" ) { $bypass_destination->{'ip'} = $row->dns_bypass_ip; } if ( defined( $row->dns_bypass_ip6 ) && $row->dns_bypass_ip6 ne "" ) { $bypass_destination->{'ip6'} = $row->dns_bypass_ip6; } if ( defined( $row->dns_bypass_cname ) && $row->dns_bypass_cname ne "" ) { $bypass_destination->{'cname'} = $row->dns_bypass_cname; } if ( defined( $row->dns_bypass_ttl ) && $row->dns_bypass_ttl ne "" ) { $bypass_destination->{'ttl'} = int( $row->dns_bypass_ttl ); } if ( defined( $row->max_dns_answers ) && $row->max_dns_answers ne "" ) { $bypass_destination->{'maxDnsIpsForLocation'} = int( $row->max_dns_answers ); } } elsif ( $protocol =~ m/HTTP/ ) { $bypass_destination->{'type'} = 'HTTP'; if ( defined( $row->http_bypass_fqdn ) && $row->http_bypass_fqdn ne "" ) { my $full = $row->http_bypass_fqdn; my $fqdn; if ( $full =~ m/\:/ ) { my $port; ( $fqdn, $port ) = split( /\:/, $full ); # Specify port number only if explicitly set by the DS 'Bypass FQDN' field - issue 1493 $bypass_destination->{'port'} = int($port); } else { $fqdn = $full; } $bypass_destination->{'fqdn'} = $fqdn; } } $delivery_service->{'bypassDestination'} = $bypass_destination; if ( defined( $row->miss_lat ) && $row->miss_lat ne "" ) { $delivery_service->{'missCoordinates'}->{'latitude'} = $row->miss_lat + 0; } if ( defined( $row->miss_long ) && $row->miss_long ne "" ) { $delivery_service->{'missCoordinates'}->{'longitude'} = $row->miss_long + 0; } $delivery_service->{'ttls'} = { 'A' => int( $row->ccr_dns_ttl ), 'AAAA' => int( $row->ccr_dns_ttl ), 'NS' => int($tld_ttls_ns), 'SOA' => int($tld_ttls_soa) }; $delivery_service->{'soa'}->{'minimum'} = int($cdn_soa_minimum); $delivery_service->{'soa'}->{'expire'} = int($cdn_soa_expire); $delivery_service->{'soa'}->{'retry'} = int($cdn_soa_retry); $delivery_service->{'soa'}->{'refresh'} = int($cdn_soa_retry); $delivery_service->{'soa'}->{'admin'} = $cdn_soa_admin; my $rs_dns = $self->db->resultset('Staticdnsentry')->search( { 'deliveryservice.active' => 1, 'deliveryservice.profile' => $ccr_profile_id }, { prefetch => [ 'deliveryservice', 'type' ], columns => [ 'host', 'type', 'ttl', 'address' ] } ); while ( my $dns_row = $rs_dns->next ) { my $dns_obj; $dns_obj->{'name'} = $dns_row->host; $dns_obj->{'ttl'} = int( $dns_row->ttl ); $dns_obj->{'value'} = $dns_row->address; my $type = $dns_row->type->name; $type =~ s/\_RECORD//g; $dns_obj->{'type'} = $type; push( @{ $delivery_service->{'staticDnsEntries'} }, $dns_obj ); } push( @{ $data_obj->{'deliveryServices'} }, $delivery_service ); } foreach my $cache_hostname ( sort keys %{$ds_regex_tracker} ) { my $i = 0; my $server_ref; foreach my $traffic_server ( @{ $data_obj->{'trafficServers'} } ) { $i++; my $traffic_server_hostname = $traffic_server->{'hostName'} || ""; next if ( $traffic_server_hostname ne $cache_hostname ); $server_ref = $data_obj->{'trafficServers'}->[ $i - 1 ]; } foreach my $xml_id ( sort keys %{ $ds_regex_tracker->{$cache_hostname} } ) { my $ds; $ds->{'xmlId'} = $xml_id; $ds->{'remaps'} = $ds_regex_tracker->{$cache_hostname}->{$xml_id}->{'remaps'}; push( @{ $server_ref->{'deliveryServices'} }, $ds ); $data_obj->{'trafficServers'}->[$i] = $server_ref; } } my @empty_array; foreach my $traffic_server ( @{ $data_obj->{'trafficServers'} } ) { if ( !defined( $traffic_server->{'deliveryServices'} ) ) { push( @{ $traffic_server->{'deliveryServices'} }, @empty_array ); } } return ($data_obj); } # Produces a list of Cdns for traversing child links sub get_cdns { my $self = shift; my $rs_data = $self->db->resultset("Cdn")->search( {}, { order_by => "name" } ); my $json_response = $self->build_cdns_json( $rs_data, "id,name" ); #push( @{$json_response}, { "links" => [ { "rel" => "configs", "href" => "child" } ] } ); $self->success($json_response); } sub build_cdns_json { my $self = shift; my $rs_data = shift; my $default_columns = shift; my $columns; if ( defined $self->param('columns') ) { $columns = $self->param('columns'); } else { $columns = $default_columns; } my (@columns) = split( /,/, $columns ); my %columns; foreach my $col (@columns) { $columns{$col} = defined; } my @data; my @cols = grep { exists $columns{$_} } $rs_data->result_source->columns; while ( my $row = $rs_data->next ) { my %parameter; foreach my $col (@cols) { $parameter{$col} = $row->$col; } push( @data, \%parameter ); } return \@data; } sub domains { my $self = shift; my @data; my $rs = $self->db->resultset('Profile')->search( { 'me.name' => { -like => 'CCR%' } }, { prefetch => ['cdn'] } ); while ( my $row = $rs->next ) { push( @data, { "domainName" => $row->cdn->domain_name, "parameterId" => -1, # it's not a parameter anymore "profileId" => $row->id, "profileName" => $row->name, "profileDescription" => $row->description, } ); } $self->success( \@data ); } sub dnssec_keys { my $self = shift; my $is_updated = 0; if ( &is_admin($self) ) { my $cdn_name = $self->param('name'); my $keys; my $response_container = $self->riak_get( "dnssec", $cdn_name ); my $get_keys = $response_container->{'response'}; if ( $get_keys->is_success() ) { $keys = decode_json( $get_keys->content ); return $self->success($keys); } else { return $self->success({}, " - Dnssec keys for $cdn_name could not be found. "); } } return $self->alert( { Error => " - You must be an ADMIN to perform this operation!" } ); } #checks if keys are expired and re-generates them if they are. sub dnssec_keys_refresh { my $self = shift; # fork and daemonize so we can avoid blocking my $rc = $self->fork_and_daemonize(); if ( $rc < 0 ) { my $error = "Unable to fork_and_daemonize to check DNSSEC keys for refresh in the background"; $self->app->log->fatal($error); return $self->alert( { Error => $error } ); } elsif ( $rc > 0 ) { # This is the parent, report success and return return $self->success("Checking DNSSEC keys for refresh in the background"); } # we're in the fork()ed process now, do the work and exit $self->refresh_keys(); exit(0); } sub refresh_keys { my $self = shift; my $is_updated = 0; my $error_message; $self->app->log->debug("Starting refresh of DNSSEC keys"); my $rs_data = $self->db->resultset("Cdn")->search( {}, { order_by => "name" } ); while ( my $row = $rs_data->next ) { if ( $row->dnssec_enabled == 1 ) { my $cdn_name = $row->name; my $cdn_domain_name = $row->domain_name; my $keys; my $response_container = $self->riak_get( "dnssec", $cdn_name ); my $get_keys = $response_container->{'response'}; if ( !$get_keys->is_success() ) { $error_message = "Can't update dnssec keys for $cdn_name! Response was: " . $get_keys->content; $self->app->log->warn($error_message); next; } $keys = decode_json( $get_keys->content ); #get DNSKEY ttl, generation multiplier, and effective mutiplier for CDN TLD my $profile_id = $self->get_profile_id_by_cdn($cdn_name); my $dnskey_gen_multiplier; my $dnskey_ttl; my $dnskey_effective_multiplier; my %condition = ( 'parameter.name' => 'tld.ttls.DNSKEY', 'profile.name' => $profile_id ); my $rs_pp = $self->db->resultset('ProfileParameter')->search( \%condition, { prefetch => [ { 'parameter' => undef }, { 'profile' => undef } ] } ) ->single; $rs_pp ? $dnskey_ttl = $rs_pp->parameter->value : $dnskey_ttl = '60'; %condition = ( 'parameter.name' => 'DNSKEY.generation.multiplier', 'profile.name' => $profile_id ); $rs_pp = $self->db->resultset('ProfileParameter')->search( \%condition, { prefetch => [ { 'parameter' => undef }, { 'profile' => undef } ] } ) ->single; $rs_pp ? $dnskey_gen_multiplier = $rs_pp->parameter->value : $dnskey_gen_multiplier = '10'; %condition = ( 'parameter.name' => 'DNSKEY.effective.multiplier', 'profile.name' => $profile_id ); $rs_pp = $self->db->resultset('ProfileParameter')->search( \%condition, { prefetch => [ { 'parameter' => undef }, { 'profile' => undef } ] } ) ->single; $rs_pp ? $dnskey_effective_multiplier = $rs_pp->parameter->value : $dnskey_effective_multiplier = '10'; my $key_expiration = time() + ( $dnskey_ttl * $dnskey_gen_multiplier ); #get default expiration days and ttl for DSs from CDN record my $default_k_exp_days = "365"; my $default_z_exp_days = "30"; my $cdn_ksk = $keys->{$cdn_name}->{ksk}; foreach my $cdn_krecord (@$cdn_ksk) { my $cdn_kstatus = $cdn_krecord->{status}; if ( $cdn_kstatus eq 'new' ) { #ignore anything other than the 'new' record my $cdn_k_exp = $cdn_krecord->{expirationDate}; my $cdn_k_incep = $cdn_krecord->{inceptionDate}; $default_k_exp_days = ( $cdn_k_exp - $cdn_k_incep ) / 86400; } } my $cdn_zsk = $keys->{$cdn_name}->{zsk}; foreach my $cdn_zrecord (@$cdn_zsk) { my $cdn_zstatus = $cdn_zrecord->{status}; if ( $cdn_zstatus eq 'new' ) { #ignore anything other than the 'new' record my $cdn_z_exp = $cdn_zrecord->{expirationDate}; my $cdn_z_incep = $cdn_zrecord->{inceptionDate}; $default_z_exp_days = ( $cdn_z_exp - $cdn_z_incep ) / 86400; #check if zsk is expired, if so re-generate if ( $cdn_z_exp < $key_expiration ) { #if expired create new keys $self->app->log->info("The ZSK keys for $cdn_name are expired!"); my $effective_date = $cdn_z_exp - ( $dnskey_ttl * $dnskey_effective_multiplier ); my $new_dnssec_keys = $self->regen_expired_keys( "zsk", $cdn_name, $keys, $effective_date ); $keys->{$cdn_name} = $new_dnssec_keys; } } } #get DeliveryServices for CDN my %search = ( cdn_id => $row->id ); my @ds_rs = $self->db->resultset('Deliveryservice')->search( \%search ); foreach my $ds (@ds_rs) { if ( $ds->type->name !~ m/^HTTP/ && $ds->type->name !~ m/^CLIENT_STEERING$/ && $ds->type->name !~ m/^STEERING$/ && $ds->type->name !~ m/^DNS/ ) { next; } #check if keys exist for ds my $xml_id = $ds->xml_id; my $ds_keys = $keys->{$xml_id}; if ( !$ds_keys ) { #create keys $self->app->log->info("Keys do not exist for ds $xml_id"); my $ds_id = $ds->id; #create the ds domain name for dnssec keys my $ds_name = UI::DeliveryService::get_ds_domain_name($self, $ds_id, $xml_id, $cdn_domain_name); my $inception = time(); my $z_expiration = $inception + ( 86400 * $default_z_exp_days ); my $k_expiration = $inception + ( 86400 * $default_k_exp_days ); my $zsk = $self->get_dnssec_keys( "zsk", $ds_name, $dnskey_ttl, $inception, $z_expiration, "new", $inception ); my $ksk = $self->get_dnssec_keys( "ksk", $ds_name, $dnskey_ttl, $inception, $k_expiration, "new", $inception ); #add to keys hash $keys->{$xml_id} = { zsk => [$zsk], ksk => [$ksk] }; #update is_updated param $is_updated = 1; } #if keys do exist, check expiration else { my $ksk = $ds_keys->{ksk}; foreach my $krecord (@$ksk) { my $kstatus = $krecord->{status}; if ( $kstatus eq 'new' ) { if ( $krecord->{expirationDate} < $key_expiration ) { #if expired create new keys $self->app->log->info("The KSK keys for $xml_id are expired!"); my $effective_date = $krecord->{expirationDate} - ( $dnskey_ttl * $dnskey_effective_multiplier ); my $new_dnssec_keys = $self->regen_expired_keys( "ksk", $xml_id, $keys, $effective_date ); $keys->{$xml_id} = $new_dnssec_keys; #update is_updated param $is_updated = 1; } } } my $zsk = $ds_keys->{zsk}; foreach my $zrecord (@$zsk) { my $zstatus = $zrecord->{status}; if ( $zstatus eq 'new' ) { if ( $zrecord->{expirationDate} < $key_expiration ) { #if expired create new keys $self->app->log->info("The ZSK keys for $xml_id are expired!"); my $effective_date = $zrecord->{expirationDate} - ( $dnskey_ttl * $dnskey_effective_multiplier ); my $new_dnssec_keys = $self->regen_expired_keys( "zsk", $xml_id, $keys, $effective_date ); $keys->{$xml_id} = $new_dnssec_keys; #update is_updated param $is_updated = 1; } } } } } if ( $is_updated == 1 ) { # #convert hash to json and store in Riak my $json_data = encode_json($keys); $response_container = $self->riak_put( "dnssec", $cdn_name, $json_data ); } my $response = $response_container->{"response"}; if ( !$response->is_success() ) { $error_message = "DNSSEC keys could not be stored for $cdn_name! Response was: " . $response->content; $self->app->log->warn($error_message); next; } } } $self->app->log->debug("Done refreshing DNSSEC keys"); } sub regen_expired_keys { my $self = shift; my $type = shift; my $key = shift; my $existing_keys = shift; my $effective_date = shift; my $tld = shift; my $reset_exp = shift; my $regen_keys = {}; my $old_key; my $existing = $existing_keys->{$key}->{$type}; foreach my $record (@$existing) { if ( $record->{status} eq 'new' ) { $old_key = $record; } } my $name = $old_key->{name}; my $ttl = $old_key->{ttl}; my $expiration = $old_key->{expirationDate}; my $inception = $old_key->{inceptionDate}; my $expiration_days = ( $expiration - $inception ) / 86400; #create new expiration and inception time my $new_inception = time(); my $new_expiration = $new_inception + ( 86400 * $expiration_days ); #generate new keys my $new_key = $self->get_dnssec_keys( $type, $name, $ttl, $new_inception, $new_expiration, "new", $effective_date, $tld ); if ( $type eq "ksk" ) { #get existing zsk my @zsk = $existing_keys->{$key}->{zsk}; #set existing ksk status to "expired" $old_key->{status} = "expired"; if ($reset_exp) { $old_key->{expirationDate} = $effective_date; } $regen_keys = { zsk => @zsk, ksk => [ $new_key, $old_key ] }; } elsif ( $type eq "zsk" ) { #get existing ksk my @ksk = $existing_keys->{$key}->{ksk}; #set existing ksk status to "expired" $old_key->{status} = "expired"; if ($reset_exp) { $old_key->{expirationDate} = $effective_date; } $regen_keys = { zsk => [ $new_key, $old_key ], ksk => @ksk }; } return $regen_keys; } sub dnssec_keys_generate { my $self = shift; if ( !&is_admin($self) ) { $self->alert( { Error => " - You must be an ADMIN to perform this operation!" } ); } else { my $key_type = "dnssec"; my $key = $self->req->json->{key}; my $name = $self->req->json->{name}; my $ttl = $self->req->json->{ttl}; my $k_exp_days = $self->req->json->{kskExpirationDays}; my $z_exp_days = $self->req->json->{zskExpirationDays}; my $effectiveDate = $self->req->json->{effectiveDate}; if ( !defined($effectiveDate) ) { $effectiveDate = time(); } my $res = $self->generate_store_dnssec_keys( $key, $name, $ttl, $k_exp_days, $z_exp_days, $effectiveDate ); my $response = $res->{response}; my $rc = $response->{_rc}; if ( $rc eq "204" ) { &log( $self, "Generated DNSSEC keys for CDN $key", "APICHANGE" ); $self->success_message("Successfully created $key_type keys for $key"); } else { $self->alert( { Error => " - DNSSEC keys for $key could not be created. Response was" . $response->content } ); } } } sub delete_dnssec_keys { my $self = shift; my $key = $self->param('name'); my $key_type = "dnssec"; my $response; if ( !&is_admin($self) ) { $self->alert( { Error => " - You must be an ADMIN to perform this operation!" } ); } else { $self->app->log->info("deleting key_type = $key_type, key = $key"); my $response_container = $self->riak_delete( $key_type, $key ); $response = $response_container->{"response"}; if ( $response->is_success() ) { &log( $self, "Deleted DNSSEC keys for CDN $key", "UICHANGE" ); $self->success("Successfully deleted $key_type keys for $key"); } else { $self->alert( { Error => " - SSL keys for key type $key_type and key $key could not be deleted. Response was" . $response->content } ); } } } sub ssl_keys { my $self = shift; if ( !&is_admin($self) ) { return $self->alert( { Error => " - You must be an ADMIN to perform this operation!" } ); } my $cdn_name = $self->param('name'); my $keys; #get "latest" ssl records for all DSs in the CDN my $response_container = $self->riak_search( "sslkeys", "q=cdn:$cdn_name&fq=_yz_rk:*latest&start=0&rows=1000" ); my $response = $response_container->{'response'}; if ( $response->is_success() ) { my $content = decode_json( $response->content )->{response}->{docs}; unless ( scalar(@$content) > 0 ) { return $self->render( json => { "message" => "No SSL certificates found for $cdn_name" }, status => 404 ); } foreach my $record (@$content) { push( @$keys, { deliveryservice => $record->{deliveryservice}, certificate => { crt => $record->{'certificate.crt'}, key => $record->{'certificate.key'}, }, hostname => $record->{hostname} } ); } return $self->success($keys); } return $self->alert( { Error => " - Could not retrieve SSL records for $cdn_name! Response was: " . $response->content } ); } sub tool_logout { my $self = shift; $self->logout(); $self->success_message("You are logged out."); } sub catch_all { my $self = shift; my $mimetype = $self->req->headers->content_type; if ( defined( $self->current_user() ) ) { if ( &UI::Utils::is_ldap( $self ) ) { my $config = $self->app->config; return $self->forbidden( $config->{'to'}{'no_account_found_msg'} ); } else { return $self->not_found(); } } else { return $self->unauthorized(); } } 1;
mdb/incubator-trafficcontrol
traffic_ops/app/lib/API/Cdn.pm
Perl
apache-2.0
47,221
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2020] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Translation - A class representing the translation of a transcript =head1 SYNOPSIS my $translation = Bio::EnsEMBL::Translation->new( -START_EXON => $exon1, -END_EXON => $exon2, -SEQ_START => 98, -SEQ_END => 39 ); # stable ID setter $translation->stable_id('ENSP00053458'); # get start and end position in start/end exons my $start = $translation->start; my $end = $translation->end; =head1 DESCRIPTION A Translation object defines the CDS and UTR regions of a Transcript through the use of start_Exon/end_Exon, and start/end attributes. =cut package Bio::EnsEMBL::Translation; use vars qw($AUTOLOAD @ISA); use strict; use Bio::EnsEMBL::Utils::Exception qw(throw warning ); use Bio::EnsEMBL::Utils::Argument qw( rearrange ); use Bio::EnsEMBL::Utils::Scalar qw( assert_ref wrap_array ); use Scalar::Util qw(weaken); use Bio::EnsEMBL::Storable; @ISA = qw(Bio::EnsEMBL::Storable); =head2 new Arg [-START_EXON] : The Exon object in which the translation (CDS) starts Arg [-END_EXON] : The Exon object in which the translation (CDS) ends Arg [-SEQ_START] : The offset in the start_Exon indicating the start position of the CDS. Arg [-SEQ_END] : The offset in the end_Exon indicating the end position of the CDS. Arg [-STABLE_ID] : The stable identifier for this Translation Arg [-VERSION] : The version of the stable identifier Arg [-DBID] : The internal identifier of this Translation Arg [-ADAPTOR] : The TranslationAdaptor for this Translation Arg [-SEQ] : Manually sets the peptide sequence of this translation. May be useful if this translation is not stored in a database. Arg [-CREATED_DATE]: the date the translation was created Arg [-MODIFIED_DATE]: the date the translation was modified Example : my $tl = Bio::EnsEMBL::Translation->new (-START_EXON => $ex1, -END_EXON => $ex2, -SEQ_START => 98, -SEQ_END => 39); Description: Constructor. Creates a new Translation object Returntype : Bio::EnsEMBL::Translation Exceptions : none Caller : general Status : Stable =cut sub new { my $caller = shift; my $class = ref($caller) || $caller; my ( $start_exon, $end_exon, $seq_start, $seq_end, $stable_id, $version, $dbID, $adaptor, $seq, $created_date, $modified_date ) = rearrange( [ "START_EXON", "END_EXON", "SEQ_START", "SEQ_END", "STABLE_ID", "VERSION", "DBID", "ADAPTOR", "SEQ", "CREATED_DATE", "MODIFIED_DATE" ], @_ ); # Default version if ( !defined($version) ) { $version = 1 } my $self = bless { 'start_exon' => $start_exon, 'end_exon' => $end_exon, 'dbID' => $dbID, 'start' => $seq_start, 'end' => $seq_end, 'stable_id' => $stable_id, 'version' => $version, 'created_date' => $created_date, 'modified_date' => $modified_date, 'seq' => $seq }, $class; $self->adaptor($adaptor); return $self; } =head2 transcript Arg [1] : Transcript object (optional) Description : Sets or retrieves the transcript object associated with this translation object. Exceptions : Throws if there is no adaptor or no dbID defined for the translation object. Returntype : Bio::EnsEMBL::Transcript =cut sub transcript { my ( $self, $transcript ) = @_; if ( defined($transcript) ) { assert_ref( $transcript, 'Bio::EnsEMBL::Transcript' ); $self->{'transcript'} = $transcript; weaken( $self->{'transcript'} ); # Avoid circular references. } elsif ( @_ > 1 ) { # Break connection to transcript. delete( $self->{'transcript'} ); } elsif ( !defined( $self->{'transcript'} ) ) { my $adaptor = $self->adaptor; if ( !defined($adaptor) ) { throw( "Adaptor is not set for translation, " . "can not fetch its transcript." ); } my $dbID = $self->{'dbID'}; if ( !defined($dbID) ) { throw( "dbID is not set for translation, " . " can not fetch its transcript." ); } $self->{'transcript'} = $adaptor->db()->get_TranscriptAdaptor() ->fetch_by_translation_id($dbID); # Do not weaken the reference if we had to get the transcript from the # database. The user is probably working on translations directly, # not going through transcripts. #weaken( $self->{'transcript'} ); # Avoid circular references. } return $self->{'transcript'}; } ## end sub transcript =head2 start Arg [1] : (optional) int $start - start position to set Example : $translation->start(17); Description: Getter/setter for the value of start, which is a position within the exon given by start_Exon. If you need genomic coordinates, use the genomic_start() method. Returntype : int Exceptions : none Caller : general Status : Stable =cut sub start{ my $obj = shift; if( @_ ) { my $value = shift; $obj->{'start'} = $value; } return $obj->{'start'}; } =head2 end Arg [1] : (optional) int $end - end position to set Example : $translation->end(8); Description: Getter/setter for the value of end, which is a position within the exon given by end_Exon. If you need genomic coordinates, use the genomic_end() method. Returntype : int Exceptions : none Caller : general Status : Stable =cut sub end { my $self = shift; if( @_ ) { my $value = shift; $self->{'end'} = $value; } return $self->{'end'}; } =head2 start_Exon Arg [1] : (optional) Bio::EnsEMBL::Exon - start exon to assign Example : $translation->start_Exon($exon1); Description: Getter/setter for the value of start_Exon, which denotes the exon at which translation starts (and within this exon, at the position indicated by start, see above). Returntype : Bio::EnsEMBL::Exon Exceptions : thrown on wrong argument type Caller : general Status : Stable =cut sub start_Exon { my $self = shift; if( @_ ) { my $value = shift; if( !ref $value || !$value->isa('Bio::EnsEMBL::Exon') ) { throw("Got to have an Exon object, not a $value"); } $self->{'start_exon'} = $value; } return $self->{'start_exon'}; } =head2 end_Exon Arg [1] : (optional) Bio::EnsEMBL::Exon - start exon to assign Example : $translation->start_Exon($exon1); Description: Getter/setter for the value of end_Exon, which denotes the exon at which translation ends (and within this exon, at the position indicated by end, see above). Returntype : Bio::EnsEMBL::Exon Exceptions : thrown on wrong argument type Caller : general Status : Stable =cut sub end_Exon { my $self = shift; if( @_ ) { my $value = shift; if( !ref $value || !$value->isa('Bio::EnsEMBL::Exon') ) { throw("Got to have an Exon object, not a $value"); } $self->{'end_exon'} = $value; } return $self->{'end_exon'}; } =head2 cdna_start Arg [1] : (optional) Bio::EnsEMBL::Transcript $transcript The transcript which this is a translation of. Example : $translation_cdna_start = $translation->cdna_start(); Description : Returns the start position of the translation in cDNA coordinates. If no transcript is given, the method will use TranscriptAdaptor->fetch_by_translation_id() to locate the correct transcript. Return type : Integer Exceptions : Throws if the given (optional) argument is not a transcript. Caller : General Status : At Risk (Under Development) =cut sub cdna_start { my ( $self, $transcript ) = @_; if ( defined($transcript) && ( !ref($transcript) || !$transcript->isa('Bio::EnsEMBL::Transcript') ) ) { throw("Argument is not a transcript"); } if ( !exists( $self->{'cdna_start'} ) ) { if ( !defined($transcript) ) { # We were not given a transcript, get the transcript out of # the database. $transcript = $self->transcript(); } $self->{'cdna_start'} = $self->start_Exon()->cdna_coding_start($transcript); } return $self->{'cdna_start'}; } =head2 cdna_end Arg [1] : (optional) Bio::EnsEMBL::Transcript $transcript The transcript which this is a translation of. Example : $translation_cdna_end = $translation->cdna_end(); Description : Returns the end position of the translation in cDNA coordinates. If no transcript is given, the method will use TranscriptAdaptor->fetch_by_translation_id() to locate the correct transcript. Return type : Integer Exceptions : Throws if the given (optional) argument is not a transcript. Caller : General Status : At Risk (Under Development) =cut sub cdna_end { my ( $self, $transcript ) = @_; if ( defined($transcript) && ( !ref($transcript) || !$transcript->isa('Bio::EnsEMBL::Transcript') ) ) { throw("Argument is not a transcript"); } if ( !exists( $self->{'cdna_end'} ) ) { if ( !defined($transcript) ) { # We were not given a transcript, get the transcript out of # the database. $transcript = $self->transcript(); } $self->{'cdna_end'} = $self->end_Exon()->cdna_coding_end($transcript); } return $self->{'cdna_end'}; } =head2 genomic_start Args : None Example : $translation_genomic_start = $translation->genomic_start(); Description : Returns the start position of the translation in genomic coordinates on the forward strand. Return type : Integer Exceptions : None Caller : General Status : At Risk (Under Development) =cut sub genomic_start { my $self = shift; if ( !exists $self->{'genomic_start'} ) { if ( $self->start_Exon()->strand() >= 0 ) { $self->{'genomic_start'} = $self->start_Exon()->start() + ( $self->start() - 1 ); } else { $self->{'genomic_start'} = $self->end_Exon()->end() - ( $self->end() - 1 ); } } return $self->{'genomic_start'}; } =head2 genomic_end Args : None Example : $translation_genomic_end = $translation->genomic_end(); Description : Returns the end position of the translation in genomic coordinates on the forward strand. Return type : Integer Exceptions : None Caller : General Status : At Risk (Under Development) =cut sub genomic_end { my $self = shift; if ( !exists $self->{'genomic_end'} ) { if ( $self->end_Exon()->strand() >= 0 ) { $self->{'genomic_end'} = $self->end_Exon()->start() + ( $self->end() - 1 ); } else { $self->{'genomic_end'} = $self->start_Exon()->end() - ( $self->start() - 1 ); } } return $self->{'genomic_end'}; } =head2 version Arg [1] : (optional) string $version - version to set Example : $translation->version(2); Description: Getter/setter for attribute version Returntype : string Exceptions : none Caller : general Status : Stable =cut sub version { my $self = shift; $self->{'version'} = shift if( @_ ); return $self->{'version'}; } =head2 stable_id Arg [1] : (optional) string $stable_id - stable ID to set Example : $translation->stable_id('ENSP0059890'); Description: Getter/setter for attribute stable_id Returntype : string Exceptions : none Caller : general Status : Stable =cut sub stable_id { my $self = shift; $self->{'stable_id'} = shift if( @_ ); return $self->{'stable_id'}; } =head2 stable_id_version Arg [1] : (optional) String - the stable ID with version to set Example : $translation->stable_id("ENSP0059890.3"); Description: Getter/setter for stable id with version for this translation. Returntype : String Exceptions : none Caller : general Status : Stable =cut sub stable_id_version { my $self = shift; if(my $stable_id = shift) { # See if there's an embedded period, assume that's a # version, might not work for some species but you # should use ->stable_id() and version() if you're worried # about ambiguity my $vindex = rindex($stable_id, '.'); # Set the stable_id and version pair depending on if # we found a version delimiter in the stable_id ($self->{stable_id}, $self->{version}) = ($vindex > 0 ? (substr($stable_id,0,$vindex), substr($stable_id,$vindex+1)) : $stable_id, undef); } return $self->{stable_id} . ($self->{version} ? ".$self->{version}" : ''); } =head2 created_date Arg [1] : (optional) string $created_date - created date to set Example : $translation->created_date('2007-01-10 20:52:00'); Description: Getter/setter for attribute created date Returntype : string Exceptions : none Caller : general Status : Stable =cut sub created_date { my $self = shift; $self->{'created_date'} = shift if ( @_ ); return $self->{'created_date'}; } =head2 modified_date Arg [1] : (optional) string $modified_date - modification date to set Example : $translation->modified_date('2007-01-10 20:52:00'); Description: Getter/setter for attribute modified date Returntype : string Exceptions : none Caller : general Status : Stable =cut sub modified_date { my $self = shift; $self->{'modified_date'} = shift if ( @_ ); return $self->{'modified_date'}; } =head2 transform Arg [1] : hashref $old_new_exon_map a hash that maps old to new exons for a whole gene Description: maps start end end exon according to mapping table. If an exon is not mapped, just keep the old one. Returntype : none Exceptions : none Caller : Transcript->transform() Status : Stable =cut sub transform { my $self = shift; my $href_exons = shift; my $start_exon = $self->start_Exon(); my $end_exon = $self->end_Exon(); if ( exists $href_exons->{$start_exon} ) { $self->start_Exon($href_exons->{$start_exon}); } else { # do nothing, the start exon wasnt mapped } if ( exists $href_exons->{$end_exon} ) { $self->end_Exon($href_exons->{$end_exon}); } else { # do nothing, the end exon wasnt mapped } } =head2 get_all_DBEntries Arg [1] : (optional) String, external database name, SQL wildcard characters (_ and %) can be used to specify patterns. Arg [2] : (optional) String, external_db type, ('ARRAY','ALT_TRANS','ALT_GENE','MISC','LIT','PRIMARY_DB_SYNONYM','ENSEMBL'), SQL wildcard characters (_ and %) can be used to specify patterns. Example : my @dbentries = @{ $translation->get_all_DBEntries() }; @dbentries = @{ $translation->get_all_DBEntries('Uniprot%') }; @dbentries = @{ $translation->get_all_DBEntries('%', 'ENSEMBL') }; Description: Retrieves DBEntries (xrefs) for this translation. This method will attempt to lazy-load DBEntries from a database if an adaptor is available and no DBEntries are present on the translation (i.e. they have not already been added or loaded). Returntype : Listref to Bio::EnsEMBL::DBEntry objects Exceptions : none Caller : TranslationAdaptor::store Status : Stable =cut sub get_all_DBEntries { my ( $self, $ex_db_exp, $ex_db_type ) = @_; my $cache_name = 'dbentries'; if ( defined($ex_db_exp) ) { $cache_name .= $ex_db_exp; } if ( defined($ex_db_type) ) { $cache_name .= $ex_db_type; } # if not cached, retrieve all of the xrefs for this translation if ( !defined( $self->{$cache_name} ) && defined( $self->adaptor() ) ) { $self->{$cache_name} = $self->adaptor()->db()->get_DBEntryAdaptor() ->fetch_all_by_Translation( $self, $ex_db_exp, $ex_db_type ); } $self->{$cache_name} ||= []; return $self->{$cache_name}; } ## end sub get_all_DBEntries =head2 get_all_object_xrefs Arg [1] : (optional) String, external database name Arg [2] : (optional) String, external_db type Example : @oxrefs = @{ $translation->get_all_object_xrefs() }; Description: Retrieves xrefs for this translation. This method will attempt to lazy-load xrefs from a database if an adaptor is available and no xrefs are present on the translation (i.e. they have not already been added or loaded). NB: This method is an alias for the get_all_DBentries() method. Return type: Listref of Bio::EnsEMBL::DBEntry objects Status : Stable =cut sub get_all_object_xrefs { my $self = shift; return $self->get_all_DBEntries(@_); } =head2 add_DBEntry Arg [1] : Bio::EnsEMBL::DBEntry $dbe The dbEntry to be added Example : $translation->add_DBEntry($xref); Description: Associates a DBEntry with this translation. Note that adding DBEntries will prevent future lazy-loading of DBEntries for this translation (see get_all_DBEntries). Returntype : none Exceptions : thrown on incorrect argument type Caller : general Status : Stable =cut sub add_DBEntry { my $self = shift; my $dbe = shift; unless($dbe && ref($dbe) && $dbe->isa('Bio::EnsEMBL::DBEntry')) { throw('Expected DBEntry argument'); } $self->{'dbentries'} ||= []; push @{$self->{'dbentries'}}, $dbe; } =head2 get_all_DBLinks Arg [1] : String database name (optional) SQL wildcard characters (_ and %) can be used to specify patterns. Arg [2] : (optional) String, external database type, can be one of ('ARRAY','ALT_TRANS','ALT_GENE','MISC','LIT','PRIMARY_DB_SYNONYM','ENSEMBL'), SQL wildcard characters (_ and %) can be used to specify patterns. Example : my @dblinks = @{ $translation->get_all_DBLinks() }; @dblinks = @{ $translation->get_all_DBLinks('Uniprot%') }; @dblinks = @{ $translation->get_all_DBLinks('%', 'ENSEMBL') }; Description: This is here for consistancy with the Transcript and Gene classes. It is a synonym for the get_all_DBEntries() method. Return type: Listref to Bio::EnsEMBL::DBEntry objects Exceptions : none Caller : general Status : Stable =cut sub get_all_DBLinks { my $self = shift; return $self->get_all_DBEntries(@_); } =head2 get_all_xrefs Arg [1] : String database name (optional) SQL wildcard characters (_ and %) can be used to specify patterns. Example : @xrefs = @{ $translation->get_all_xrefs() }; @xrefs = @{ $translation->get_all_xrefs('Uniprot%') }; Description: This method is here for consistancy with the Gene and Transcript classes. It is an alias for the get_all_DBLinks() method, which in turn directly calls get_all_DBEntries(). Return type: Listref of Bio::EnsEMBL::DBEntry objects Status : Stable =cut sub get_all_xrefs { my $self = shift; return $self->get_all_DBLinks(@_); } =head2 get_all_ProteinFeatures Arg [1] : (optional) string $logic_name The analysis logic_name of the features to retrieve. If not specified, all features are retrieved instead. If no logic_name is found, looking for analysis db name instead. Example : $features = $self->get_all_ProteinFeatures('PFam'); Description: Retrieves all ProteinFeatures associated with this Translation. If a logic_name is specified, only features with that logic_name are returned. If no logic_name is provided all associated protein_features are returned. ProteinFeatures are lazy-loaded from the database unless they added manually to the Translation or had already been loaded. Returntype : Listref of Bio::EnsEMBL::ProteinFeature Exceptions : none Caller : general Status : Stable =cut sub get_all_ProteinFeatures { my $self = shift; my $logic_name = shift; my (%hash, %db_hash); my $no_pf = 0; if(!$self->{'protein_features'}) { $no_pf = 1; my $adaptor = $self->adaptor(); my $dbID = $self->dbID(); return [] if (!$adaptor || !$dbID); $self->{'protein_features'} = \%hash; my $pfa = $adaptor->db()->get_ProteinFeatureAdaptor(); my ($name, $ana_db); foreach my $f (@{$pfa->fetch_all_by_translation_id($dbID)}) { my $analysis = $f->analysis(); if($analysis) { $name = lc($f->analysis->logic_name()); $ana_db = lc($f->analysis->db()); $db_hash{$ana_db} = $name; } else { warning("ProteinFeature has no attached analysis\n"); $name = ''; } $hash{$name} ||= []; push @{$hash{$name}}, $f; } } # a specific type of protein feature was requested if(defined($logic_name)) { $logic_name = lc($logic_name); if (!$hash{$logic_name} && $no_pf) { $logic_name = $db_hash{$logic_name}; } return $self->{'protein_features'}->{$logic_name} || []; } my @features = (); # all protein features were requested foreach my $type (keys %{$self->{'protein_features'}}) { push @features, @{$self->{'protein_features'}->{$type}}; } return \@features; } =head2 get_all_DomainFeatures Example : @domain_feats = @{$translation->get_all_DomainFeatures}; Description: A convenience method which retrieves all protein features that are considered to be 'Domain' features. Features which are 'domain' features are those with analysis logic names: 'pfscan', 'scanprosite', 'superfamily', 'pfam', 'prints', 'smart', 'pirsf', 'tigrfam'. Returntype : listref of Bio::EnsEMBL::ProteinFeature Exceptions : none Caller : webcode (protview) Status : Stable =cut sub get_all_DomainFeatures{ my ($self) = @_; my @features; my @types = ('pfscan', #profile (prosite or pfam motifs) 'scanprosite', #prosite 'superfamily', 'pfam', 'smart', 'tigrfam', 'pirsf', 'prints'); foreach my $type (@types) { push @features, @{$self->get_all_ProteinFeatures($type)}; } return \@features; } =head2 add_ProteinFeature Arg [1] : Bio::EnsEMBL::ProteinFeature $pf The ProteinFeature to be added Example : $translation->add_ProteinFeature($pf); Description: Associates a ProteinFeature with this translation. Note that adding ProteinFeatures will prevent future lazy-loading of ProteinFeatures for this translation (see get_all_ProteinFeatures). Returntype : none Exceptions : thrown on incorrect argument type Caller : general Status : Stable =cut sub add_ProteinFeature { my $self = shift; my $pf = shift; unless ($pf && ref($pf) && $pf->isa('Bio::EnsEMBL::ProteinFeature')) { throw('Expected ProteinFeature argument'); } my $analysis = $pf->analysis; throw("ProteinFeature has no attached Analysis.") unless $analysis; push @{ $self->{'protein_features'}->{$analysis->logic_name} }, $pf; } =head2 display_id Example : print $translation->display_id(); Description: This method returns a string that is considered to be the 'display' identifier. For translations this is (depending on availability and in this order) the stable Id, the dbID or an empty string. Returntype : string Exceptions : none Caller : web drawing code Status : Stable =cut sub display_id { my $self = shift; return $self->{'stable_id'} || $self->dbID || ''; } =head2 length Example : print "Peptide length =", $translation->length(); Description: Retrieves the length of the peptide sequence (i.e. number of amino acids) represented by this Translation object. Returntype : int Exceptions : none Caller : webcode (protview etc.) Status : Stable =cut sub length { my $self = shift; my $seq = $self->seq(); return ($seq) ? CORE::length($seq) : 0; } =head2 seq Example : print $translation->seq(); Description: Retrieves a string representation of the peptide sequence of this Translation. This retrieves the transcript from the database and gets its sequence, or retrieves the sequence which was set via the constructor. Returntype : string Exceptions : warning if the sequence is not set and cannot be retrieved from the database. Caller : webcode (protview etc.) Status : Stable =cut sub seq { my ( $self, $sequence ) = @_; if ( defined($sequence) ) { $self->{'seq'} = $sequence; } elsif ( !defined( $self->{'seq'} ) ) { my $transcript = $self->transcript(); my $canonical_translation = $transcript->translation(); my $is_alternative; if(!$canonical_translation) { throw "Transcript does not have a canonical translation"; } if ( defined( $canonical_translation->stable_id() ) && defined( $self->stable_id() ) ) { # Try stable ID. $is_alternative = ( $canonical_translation->stable_id() ne $self->stable_id() ); } elsif ( defined( $canonical_translation->dbID() ) && defined( $self->dbID() ) ) { # Try dbID. $is_alternative = ( $canonical_translation->dbID() != $self->dbID() ); } else { # Resort to using geomic start/end coordinates. $is_alternative = ( ($canonical_translation->genomic_start() != $self->genomic_start() ) || ( $canonical_translation->genomic_end() != $self->genomic_end() ) ); } if ($is_alternative) { # To deal with non-canonical (alternative) translations, subsitute # the canonical translation in the transcript with $self for a # while. $transcript->translation($self); } my $seq = $transcript->translate(); if ( defined($seq) ) { $self->{'seq'} = $seq->seq(); } if ($is_alternative) { # Reinstate the real canonical translation. $transcript->translation($canonical_translation); } } ## end elsif ( !defined( $self->...)) if ( !defined( $self->{'seq'} ) ) { return ''; # Empty string } return $self->{'seq'}; } ## end sub seq =head2 get_all_Attributes Arg [1] : optional string $attrib_code The code of the attribute type to retrieve values for. Example : ($sc_attr) = @{$tl->get_all_Attributes('_selenocysteine')}; @tl_attributes = @{$translation->get_all_Attributes()}; Description: Gets a list of Attributes of this translation. Optionally just get Attrubutes for given code. Recognized attribute "_selenocysteine" Returntype : listref Bio::EnsEMBL::Attribute Exceptions : warning if translation does not have attached adaptor and attempts lazy load. Caller : general, modify_translation Status : Stable =cut sub get_all_Attributes { my $self = shift; my $attrib_code = shift; if( ! exists $self->{'attributes' } ) { if(!$self->adaptor() ) { # warning('Cannot get attributes without an adaptor.'); return []; } my $aa = $self->adaptor->db->get_AttributeAdaptor(); $self->{'attributes'} = $aa->fetch_all_by_Translation( $self ); } if( defined $attrib_code ) { my @results = grep { uc($_->code()) eq uc($attrib_code) } @{$self->{'attributes'}}; return \@results; } else { return $self->{'attributes'}; } } =head2 add_Attributes Arg [1..N] : Bio::EnsEMBL::Attribute $attribute Attributes to add. Example : $translation->add_Attributes($selenocysteine_attribute); Description: Adds an Attribute to the Translation. Usefull to do _selenocysteine. If you add an attribute before you retrieve any from database, lazy load will be disabled. Returntype : none Exceptions : throw on incorrect arguments Caller : general Status : Stable =cut sub add_Attributes { my $self = shift; my @attribs = @_; if( ! exists $self->{'attributes'} ) { $self->{'attributes'} = []; } for my $attrib ( @attribs ) { if( ! $attrib->isa( "Bio::EnsEMBL::Attribute" )) { throw( "Argument to add_Attribute must be a Bio::EnsEMBL::Attribute" ); } push( @{$self->{'attributes'}}, $attrib ); $self->{seq}=undef; } } =head2 get_all_SeqEdits Arg [1] : ArrayRef $edits. Specify the name of the edits to fetch Example : my @seqeds = @{$translation->get_all_SeqEdits()}; my @seqeds = @{$translation->get_all_SeqEdits('_selenocysteine')}; Description: Retrieves all post transcriptional sequence modifications for this translation. Returntype : Bio::EnsEMBL::SeqEdit Exceptions : none Caller : spliced_seq() Status : Stable =cut sub get_all_SeqEdits { my $self = shift; my $edits = shift; my @seqeds; my $attribs; $edits ||= ['initial_met', '_selenocysteine', 'amino_acid_sub', '_stop_codon_rt']; foreach my $edit(@{wrap_array($edits)}){ $attribs = $self->get_all_Attributes($edit); # convert attributes to SeqEdit objects foreach my $a (@$attribs) { push @seqeds, Bio::EnsEMBL::SeqEdit->new(-ATTRIB => $a); } } return \@seqeds; } =head2 get_all_selenocysteine_SeqEdits Example : my @edits = @{$translation->get_all_selenocysteine_SeqEdits()}; Description: Retrieves all post transcriptional sequence modifications related to selenocysteine PTMs Returntype : Bio::EnsEMBL::SeqEdit Exceptions : none =cut sub get_all_selenocysteine_SeqEdits { my ($self) = @_; return $self->get_all_SeqEdits(['_selenocysteine']); } =head2 get_all_stop_codon_SeqEdits Example : my @edits = @{$translation->get_all_stop_codon_SeqEdits()}; Description: Retrieves all post transcriptional sequence modifications related to stop codon readthrough Returntype : Bio::EnsEMBL::SeqEdit Exceptions : none =cut sub get_all_stop_codon_SeqEdits { my ($self) = @_; return $self->get_all_SeqEdits(['_stop_codon_rt']); } =head2 modify_translation Arg [1] : Bio::Seq $peptide Example : my $seq = Bio::Seq->new(-SEQ => $dna)->translate(); $translation->modify_translation($seq); Description: Applies sequence edits such as selenocysteines to the Bio::Seq peptide thats passed in Returntype : Bio::Seq Exceptions : none Caller : Bio::EnsEMBL::Transcript->translate Status : Stable =cut sub modify_translation { my ( $self, $seq ) = @_; my @seqeds = @{ $self->get_all_SeqEdits() }; # Sort in reverse order to avoid complication of adjusting # downstream edits. # HACK: The translation ENSP00000420939 somehow makes the next line # bomb out ($a or $b becomes undef) if the start() method # is used. I haven't been able to find out why. It has 10 # Selenocysteine seqedits that looks correct. # /Andreas (release 59) @seqeds = sort { $b->{'start'} <=> $a->{'start'} } @seqeds; # Apply all edits. my $peptide = $seq->seq(); foreach my $se (@seqeds) { $se->apply_edit( \$peptide ); } $seq->seq($peptide); return $seq; } =head2 load Arg [1] : Boolean $load_xrefs Load (or don't load) xrefs. Default is to load xrefs. Example : $translation->load(); Description : The Ensembl API makes extensive use of lazy-loading. Under some circumstances (e.g., when copying genes between databases), all data of an object needs to be fully loaded. This method loads the parts of the object that are usually lazy-loaded. Returns : none =cut sub load { my ( $self, $load_xrefs ) = @_; if ( !defined($load_xrefs) ) { $load_xrefs = 1 } $self->seq(); $self->stable_id(); $self->get_all_Attributes(); $self->get_all_ProteinFeatures(); if ($load_xrefs) { $self->get_all_DBEntries(); } } =head2 get_all_DASFactories Function : Retrieves a listref of registered DAS objects Returntype: Listref of DAS Objects Exceptions: none Caller : webcode Example : $dasref = $prot->get_all_DASFactories; Status : Stable =cut sub get_all_DASFactories { my $self = shift; return [ $self->adaptor()->db()->_each_DASFeatureFactory ]; } =head2 get_all_DAS_Features Example : $features = $prot->get_all_DAS_Features; Description: Retrieves a hash reference to a hash of DAS feature sets, keyed by the DNS, NOTE the values of this hash are an anonymous array containing: (1) a pointer to an array of features; (2) a pointer to the DAS stylesheet Returntype : hashref of Bio::SeqFeatures Exceptions : none Caller : webcode Status : Stable =cut sub get_all_DAS_Features{ my $self = shift; my $db = $self->adaptor->db; my $GeneAdaptor = $db->get_GeneAdaptor; my $Gene = $GeneAdaptor->fetch_by_translation_stable_id($self->stable_id) || return; my $slice = $Gene->feature_Slice; return $self->SUPER::get_all_DAS_Features($slice); } =head2 summary_as_hash Example : $translation_summary = $translation->summary_as_hash(); Description : Retrieves a textual summary of this Translation. Not inherited from Feature. Returns : hashref of arrays of descriptive strings Status : Intended for internal use =cut sub summary_as_hash { my $self = shift; my %summary; my $id = $self->display_id; if ($self->version) { $id .= "." . $self->version; } $summary{'id'} = $id; $summary{'protein_id'} = $id; $summary{'genomic_start'} = $self->genomic_start; $summary{'genomic_end'} = $self->genomic_end; $summary{'length'} = $self->length; my $transcript = $self->transcript; $summary{'Parent'} = $transcript->display_id; return \%summary; } 1;
james-monkeyshines/ensembl
modules/Bio/EnsEMBL/Translation.pm
Perl
apache-2.0
36,116
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2021] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Web::Ticket::Postgap; use strict; use warnings; use List::Util qw(first); use EnsEMBL::Web::Exceptions; use EnsEMBL::Web::Job::Postgap; use parent qw(EnsEMBL::Web::Ticket); sub init_from_user_input { ## Abstract method implementation my $self = shift; my $hub = $self->hub; my $species = $hub->param('species'); my $method = first { $hub->param($_) } qw(file url text); my $output_format = 'tsv'; #hardcoded for now until we have this optional on the form (can be either tsv or json) # if no data entered throw exception('InputError', 'No input file has been entered') unless $hub->param('file'); my ($file_content, $file_name) = $self->get_input_file_content($method); $self->add_job(EnsEMBL::Web::Job::Postgap->new($self, { 'job_desc' => $hub->param('name') ? $hub->param('name') : "Post-GWAS job", 'species' => $species, 'assembly' => $hub->species_defs->get_config($species, 'ASSEMBLY_VERSION'), 'job_data' => { 'job_desc' => $hub->param('name') ? $hub->param('name') : "Post-GWAS job", 'input_file' => $file_name, 'population' => $hub->param('population') || 'AFR', 'output_file' => 'postgap_output', 'output2_file' => 'output2.tsv', # this is used by the html report generation script 'output_format' => $output_format, 'report_file' => 'colocalization_report.html' } }, { $file_name => {'content' => $file_content} })); } 1;
Ensembl/public-plugins
tools/modules/EnsEMBL/Web/Ticket/Postgap.pm
Perl
apache-2.0
2,235
package Moose::Exception::PackageDoesNotUseMooseExporter; our $VERSION = '2.1404'; use Moose; extends 'Moose::Exception'; has 'package' => ( is => 'ro', isa => 'Str', required => 1 ); has 'is_loaded' => ( is => 'ro', isa => 'Bool', required => 1 ); sub _build_message { my $self = shift; my $package = $self->package; return "Package in also ($package) does not seem to " . "use Moose::Exporter" . ( $self->is_loaded ? "" : " (is it loaded?)" ); } 1;
ray66rus/vndrv
local/lib/perl5/x86_64-linux-thread-multi/Moose/Exception/PackageDoesNotUseMooseExporter.pm
Perl
apache-2.0
536
package Google::Ads::AdWords::v201809::MutateMembersOperation; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/rm/v201809' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201809::Operation); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %operator_of :ATTR(:get<operator>); my %Operation__Type_of :ATTR(:get<Operation__Type>); my %operand_of :ATTR(:get<operand>); __PACKAGE__->_factory( [ qw( operator Operation__Type operand ) ], { 'operator' => \%operator_of, 'Operation__Type' => \%Operation__Type_of, 'operand' => \%operand_of, }, { 'operator' => 'Google::Ads::AdWords::v201809::Operator', 'Operation__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'operand' => 'Google::Ads::AdWords::v201809::MutateMembersOperand', }, { 'operator' => 'operator', 'Operation__Type' => 'Operation.Type', 'operand' => 'operand', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201809::MutateMembersOperation =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType MutateMembersOperation from the namespace https://adwords.google.com/api/adwords/rm/v201809. Operation representing a request to add or remove members from a user list. The following {@link Operator}s are supported: ADD and REMOVE. The SET operator is not supported. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * operand =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/MutateMembersOperation.pm
Perl
apache-2.0
1,999
=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::DBSQL::MethodLinkSpeciesSetAdaptor - Object to access data in the method_link_species_set and method_link tables =head1 SYNOPSIS =head2 Retrieve data from the database my $method_link_species_sets = $mlssa->fetch_all; my $method_link_species_set = $mlssa->fetch_by_dbID(1); my $method_link_species_set = $mlssa->fetch_by_method_link_type_registry_aliases( "BLASTZ_NET", ["human", "Mus musculus"]); my $method_link_species_set = $mlssa->fetch_by_method_link_type_species_set_name( "EPO", "mammals") my $method_link_species_sets = $mlssa->fetch_all_by_method_link_type("BLASTZ_NET"); my $method_link_species_sets = $mlssa->fetch_all_by_GenomeDB($genome_db); my $method_link_species_sets = $mlssa->fetch_all_by_method_link_type_GenomeDB( "PECAN", $gdb1); my $method_link_species_set = $mlssa->fetch_by_method_link_type_GenomeDBs( "TRANSLATED_BLAT", [$gdb1, $gdb2]); =head2 Store/Delete data from the database $mlssa->store($method_link_species_set); =head1 DESCRIPTION This object is intended for accessing data in the method_link and method_link_species_set tables. =head1 INHERITANCE This class inherits all the methods and attributes from Bio::EnsEMBL::DBSQL::BaseAdaptor =head1 SEE ALSO - Bio::EnsEMBL::Registry - Bio::EnsEMBL::DBSQL::BaseAdaptor - Bio::EnsEMBL::BaseAdaptor - Bio::EnsEMBL::Compara::MethodLinkSpeciesSet - Bio::EnsEMBL::Compara::GenomeDB - Bio::EnsEMBL::Compara::DBSQL::GenomeDBAdaptor =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _ =cut package Bio::EnsEMBL::Compara::DBSQL::MethodLinkSpeciesSetAdaptor; use strict; use warnings; use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::Compara::Method; use Bio::EnsEMBL::Compara::MethodLinkSpeciesSet; use Bio::EnsEMBL::Utils::Exception; use Bio::EnsEMBL::Utils::SqlHelper; use Bio::EnsEMBL::Utils::Scalar qw(:assert); use base ('Bio::EnsEMBL::Compara::DBSQL::BaseFullCacheAdaptor', 'Bio::EnsEMBL::Compara::DBSQL::TagAdaptor'); ############################################################# # Implements Bio::EnsEMBL::Compara::RunnableDB::ObjectStore # ############################################################# sub object_class { return 'Bio::EnsEMBL::Compara::MethodLinkSpeciesSet'; } ################## # store* methods # ################## =head2 store Arg 1 : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Example : $mlssa->store($method_link_species_set) Description: Stores a Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object into the database if it does not exist yet. It also stores or updates accordingly the meta table if this object has a max_alignment_length attribute. Returntype : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Exception : Thrown if the argument is not a Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Exception : Thrown if the corresponding method_link is not in the database Caller : =cut sub store { my ($self, $mlss, $store_components_first) = @_; assert_ref($mlss, 'Bio::EnsEMBL::Compara::MethodLinkSpeciesSet'); #FIXME: $store_components_first should be used for the method as well my $method = $mlss->method() or die "No Method defined, cannot store\n"; $self->db->get_MethodAdaptor->store( $method ); # will only store if the object needs storing (type is missing) and reload the dbID otherwise my $species_set_obj = $mlss->species_set_obj() or die "No SpeciesSet defined, cannot store\n"; $self->db->get_SpeciesSetAdaptor->store( $species_set_obj, $store_components_first ); my $dbID; if(my $already_stored_method_link_species_set = $self->fetch_by_method_link_id_species_set_id($method->dbID, $species_set_obj->dbID, 1) ) { $dbID = $already_stored_method_link_species_set->dbID; } if (!$dbID) { my $columns = '(method_link_species_set_id, method_link_id, species_set_id, name, source, url)'; my $mlss_placeholders = '?, ?, ?, ?, ?'; my @mlss_data = ($method->dbID, $species_set_obj->dbID, $mlss->name || '', $mlss->source || '', $mlss->url || ''); $dbID = $mlss->dbID(); if (!$dbID) { ## Use conversion rule for getting a new dbID. At the moment, we use the following ranges: ## ## dna-dna alignments: method_link_id E [1-100], method_link_species_set_id E [1-10000] ## synteny: method_link_id E [101-100], method_link_species_set_id E [10001-20000] ## homology: method_link_id E [201-300], method_link_species_set_id E [20001-30000] ## families: method_link_id E [301-400], method_link_species_set_id E [30001-40000] ## ## => the method_link_species_set_id must be between 10000 times the hundreds in the ## method_link_id and the next hundred. my $mlss_id_factor = int($method->dbID / 100); my $min_mlss_id = 10000 * $mlss_id_factor + 1; my $max_mlss_id = 10000 * ($mlss_id_factor + 1); my $helper = Bio::EnsEMBL::Utils::SqlHelper->new( -DB_CONNECTION => $self->dbc ); my $val = $helper->transaction( -RETRY => 3, -CALLBACK => sub { my $sth2 = $self->prepare("INSERT INTO method_link_species_set $columns SELECT IF( MAX(method_link_species_set_id) = $max_mlss_id, NULL, IFNULL( MAX(method_link_species_set_id) + 1, $min_mlss_id ) ), $mlss_placeholders FROM method_link_species_set WHERE method_link_species_set_id BETWEEN $min_mlss_id AND $max_mlss_id "); my $r = $sth2->execute(@mlss_data); $dbID = $self->dbc->db_handle->last_insert_id(undef, undef, 'method_link_species_set', 'method_link_species_set_id'); $sth2->finish(); return $r; } ); } else { my $method_link_species_set_sql = qq{INSERT INTO method_link_species_set $columns VALUES (?, $mlss_placeholders)}; my $sth3 = $self->prepare($method_link_species_set_sql); $sth3->execute($dbID, @mlss_data); $sth3->finish(); } $self->_id_cache->put($dbID, $mlss); } $self->attach( $mlss, $dbID); $self->sync_tags_to_database( $mlss ); return $mlss; } =head2 delete Arg 1 : integer $method_link_species_set_id Example : $mlssa->delete(23) Description: Deletes a Bio::EnsEMBL::Compara::MethodLinkSpeciesSet entry from the database. Returntype : none Exception : Caller : =cut sub delete { my ($self, $method_link_species_set_id) = @_; my $method_link_species_set_sql = 'DELETE mlsst, mlss FROM method_link_species_set mlss LEFT JOIN method_link_species_set_tag mlsst USING (method_link_species_set_id) WHERE method_link_species_set_id = ?'; my $sth = $self->prepare($method_link_species_set_sql); $sth->execute($method_link_species_set_id); $sth->finish(); $self->_id_cache->remove($method_link_species_set_id); } ######################################################## # Implements Bio::EnsEMBL::Compara::DBSQL::BaseAdaptor # ######################################################## sub _objs_from_sth { my ($self, $sth) = @_; my @mlss_list = (); my $method_adaptor = $self->db->get_MethodAdaptor; my $species_set_adaptor = $self->db->get_SpeciesSetAdaptor; my $method_hash = $self->db->get_MethodAdaptor()->_id_cache; my $species_set_hash = $self->db->get_SpeciesSetAdaptor()->_id_cache; my ($dbID, $method_link_id, $species_set_id, $name, $source, $url); $sth->bind_columns(\$dbID, \$method_link_id, \$species_set_id, \$name, \$source, \$url); while ($sth->fetch()) { my $method = $method_hash->get($method_link_id) or warning "Could not fetch Method with dbID=$method_link_id for MLSS with dbID=$dbID"; my $species_set_obj = $species_set_hash->get($species_set_id) or warning "Could not fetch SpeciesSet with dbID=$species_set_id for MLSS with dbID=$dbID"; if($method and $species_set_obj) { my $mlss = Bio::EnsEMBL::Compara::MethodLinkSpeciesSet->new( -adaptor => $self, -dbID => $dbID, -method => $method, -species_set_obj => $species_set_obj, -name => $name, -source => $source, -url => $url, ); push @mlss_list, $mlss; } } $sth->finish(); $self->_load_tagvalues_multiple(\@mlss_list, 1); return \@mlss_list; } sub _tables { return (['method_link_species_set', 'm']) } sub _columns { return qw( m.method_link_species_set_id m.method_link_id m.species_set_id m.name m.source m.url ) } sub _unique_attributes { return qw( method_link_id species_set_id ) } ################### # fetch_* methods # ################### =head2 fetch_all_by_species_set_id Arg 1 : int $species_set_id Example : my $method_link_species_set = $mlss_adaptor->fetch_all_by_species_set_id($ss->dbID) Description : Retrieve the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet objects corresponding to the given species_set_id Returntype : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet Exceptions : none =cut sub fetch_all_by_species_set_id { my ($self, $species_set_id, $no_warning) = @_; my $mlss = $self->_id_cache->get_all_by_additional_lookup('species_set_id', $species_set_id); if (not $mlss and not $no_warning) { warning("Unable to find method_link_species_set with species_set='$species_set_id'"); } return $mlss; } =head2 fetch_by_method_link_id_species_set_id Arg 1 : int $method_link_id Arg 2 : int $species_set_id Example : my $method_link_species_set = $mlssa->fetch_by_method_link_id_species_set_id(1, 1234) Description: Retrieve the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object corresponding to the given method_link_id and species_set_id Returntype : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Exceptions : Returns undef if no Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object is found Caller : =cut sub fetch_by_method_link_id_species_set_id { my ($self, $method_link_id, $species_set_id, $no_warning) = @_; my $mlss = $self->_id_cache->get_by_additional_lookup('method_species_set', sprintf('%d_%d', $method_link_id, $species_set_id)); if (not $mlss and not $no_warning) { warning("Unable to find method_link_species_set with method_link_id='$method_link_id' and species_set_id='$species_set_id'"); } return $mlss; } =head2 fetch_all_by_method_link_type Arg 1 : string method_link_type Example : my $method_link_species_sets = $mlssa->fetch_all_by_method_link_type("BLASTZ_NET") Description: Retrieve all the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet objects corresponding to the given method_link_type Returntype : listref of Bio::EnsEMBL::Compara::MethodLinkSpeciesSet objects Exceptions : none Caller : =cut sub fetch_all_by_method_link_type { my ($self, $method_link_type, $no_warning) = @_; my $method = $self->db->get_MethodAdaptor->fetch_by_type($method_link_type); unless ($method) { warning("Unable to find any method_link_species_sets with method_link_type='$method_link_type, returning an empty list'") unless ($no_warning); my $empty_mlsss = []; return $empty_mlsss; } return $self->_id_cache->get_all_by_additional_lookup('method', $method->dbID); } =head2 fetch_all_by_GenomeDB Arg 1 : Bio::EnsEMBL::Compara::GenomeDB $genome_db Example : my $method_link_species_sets = $mlssa->fetch_all_by_genome_db($genome_db) Description: Retrieve all the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet objects which includes the genome defined by the Bio::EnsEMBL::Compara::GenomeDB object or the genome_db_id in the species_set Returntype : listref of Bio::EnsEMBL::Compara::MethodLinkSpeciesSet objects Exceptions : wrong argument throws Caller : =cut sub fetch_all_by_GenomeDB { my ($self, $genome_db) = @_; assert_ref($genome_db, 'Bio::EnsEMBL::Compara::GenomeDB'); my $genome_db_id = $genome_db->dbID or throw "[$genome_db] must have a dbID"; return $self->_id_cache->get_all_by_additional_lookup(sprintf('genome_db_%d', $genome_db_id), 1); } =head2 fetch_all_by_method_link_type_GenomeDB Arg 1 : string method_link_type Arg 2 : Bio::EnsEMBL::Compara::GenomeDB $genome_db Example : my $method_link_species_sets = $mlssa->fetch_all_by_method_link_type_GenomeDB("BLASTZ_NET", $rat_genome_db) Description: Retrieve all the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet objects corresponding to the given method_link_type and which include the given Bio::EnsEBML::Compara::GenomeDB Returntype : listref of Bio::EnsEMBL::Compara::MethodLinkSpeciesSet objects Exceptions : none Caller : =cut sub fetch_all_by_method_link_type_GenomeDB { my ($self, $method_link_type, $genome_db) = @_; assert_ref($genome_db, 'Bio::EnsEMBL::Compara::GenomeDB'); my $genome_db_id = $genome_db->dbID; throw "[$genome_db] must have a dbID" if (!$genome_db_id); return $self->_id_cache->get_all_by_additional_lookup(sprintf('genome_db_%d_method_%s', $genome_db_id, uc $method_link_type), 1); } =head2 fetch_by_method_link_type_GenomeDBs Arg 1 : string $method_link_type Arg 2 : listref of Bio::EnsEMBL::Compara::GenomeDB objects [$gdb1, $gdb2, $gdb3] Arg 3 : (optional) bool $no_warning Example : my $method_link_species_set = $mlssa->fetch_by_method_link_type_GenomeDBs('MULTIZ', [$human_genome_db, $rat_genome_db, $mouse_genome_db]) Description: Retrieve the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object corresponding to the given method_link and the given set of Bio::EnsEMBL::Compara::GenomeDB objects Returntype : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Exceptions : Returns undef if no Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object is found. It also send a warning message unless the $no_warning option is on Caller : =cut sub fetch_by_method_link_type_GenomeDBs { my ($self, $method_link_type, $genome_dbs, $no_warning) = @_; my $method = $self->db->get_MethodAdaptor->fetch_by_type($method_link_type); if (not defined $method) { # Do not complain if ENSEMBL_HOMOEOLOGUES does not exist return undef if $method_link_type eq 'ENSEMBL_HOMOEOLOGUES'; die "Could not fetch Method with type='$method_link_type'"; } my $method_link_id = $method->dbID; my $species_set = $self->db->get_SpeciesSetAdaptor->fetch_by_GenomeDBs( $genome_dbs ); unless ($species_set) { warning("No Bio::EnsEMBL::Compara::SpeciesSet found for: ".join(", ", map {$_->name."(".$_->assembly.")"} @$genome_dbs)) unless $no_warning; return undef; } my $method_link_species_set = $self->fetch_by_method_link_id_species_set_id($method_link_id, $species_set->dbID, $no_warning); if (not $method_link_species_set and not $no_warning) { my $warning = "No Bio::EnsEMBL::Compara::MethodLinkSpeciesSet found for\n". " <$method_link_type> and ". join(", ", map {$_->name."(".$_->assembly.")"} @$genome_dbs); warning($warning); } return $method_link_species_set; } =head2 fetch_by_method_link_type_genome_db_ids Arg 1 : string $method_link_type Arg 2 : listref of int [$gdbid1, $gdbid2, $gdbid3] Example : my $method_link_species_set = $mlssa->fetch_by_method_link_type_genome_db_id('MULTIZ', [$human_genome_db->dbID, $rat_genome_db->dbID, $mouse_genome_db->dbID]) Description: Retrieve the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object corresponding to the given method_link and the given set of Bio::EnsEMBL::Compara::GenomeDB objects defined by the set of $genome_db_ids Returntype : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Exceptions : Returns undef if no Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object is found Caller : =cut sub fetch_by_method_link_type_genome_db_ids { my ($self, $method_link_type, $genome_db_ids) = @_; my $method = $self->db->get_MethodAdaptor->fetch_by_type($method_link_type); if (not defined $method) { # Do not complain if ENSEMBL_HOMOEOLOGUES does not exist return undef if $method_link_type eq 'ENSEMBL_HOMOEOLOGUES'; die "Could not fetch Method with type='$method_link_type'"; } my $method_link_id = $method->dbID; my $species_set = $self->db->get_SpeciesSetAdaptor->fetch_by_GenomeDBs( $genome_db_ids ); return undef unless $species_set; return $self->fetch_by_method_link_id_species_set_id($method_link_id, $species_set->dbID); } =head2 fetch_by_method_link_type_registry_aliases Arg 1 : string $method_link_type Arg 2 : listref of core database aliases [$human, $mouse, $rat] Example : my $method_link_species_set = $mlssa->fetch_by_method_link_type_registry_aliases("MULTIZ", ["human","mouse","rat"]) Description: Retrieve the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object corresponding to the given method_link and the given set of core database aliases defined in the Bio::EnsEMBL::Registry Returntype : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Exceptions : Returns undef if no Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object is found Caller : =cut sub fetch_by_method_link_type_registry_aliases { my ($self,$method_link_type, $registry_aliases) = @_; my $gdba = $self->db->get_GenomeDBAdaptor; my @genome_dbs; foreach my $alias (@{$registry_aliases}) { if (Bio::EnsEMBL::Registry->alias_exists($alias)) { my $binomial = Bio::EnsEMBL::Registry->get_alias($alias); my $gdb = $gdba->fetch_by_name_assembly($binomial); if (!$gdb) { my $meta_c = Bio::EnsEMBL::Registry->get_adaptor($alias, 'core', 'MetaContainer'); $gdb = $gdba->fetch_by_name_assembly($meta_c->get_production_name()); }; push @genome_dbs, $gdb; } else { throw("Database alias $alias is not known\n"); } } return $self->fetch_by_method_link_type_GenomeDBs($method_link_type,\@genome_dbs); } =head2 fetch_by_method_link_type_species_set_name Arg 1 : string method_link_type Arg 2 : string species_set_name Example : my $method_link_species_set = $mlssa->fetch_by_method_link_type_species_set_name("EPO", "mammals") Description: Retrieve the Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object corresponding to the given method_link_type and and species_set_tag value Returntype : Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object Exceptions : Returns undef if no Bio::EnsEMBL::Compara::MethodLinkSpeciesSet object is found Caller : =cut sub fetch_by_method_link_type_species_set_name { my ($self, $method_link_type, $species_set_name) = @_; my $species_set_adaptor = $self->db->get_SpeciesSetAdaptor; my $all_species_sets = $species_set_adaptor->fetch_all_by_tag_value('name', $species_set_name); my $method = $self->db->get_MethodAdaptor->fetch_by_type($method_link_type); if ($method) { foreach my $this_species_set (@$all_species_sets) { my $mlss = $self->fetch_by_method_link_id_species_set_id($method->dbID, $this_species_set->dbID, 1); # final 1, before we don't want a warning here if any is missing return $mlss if $mlss; } } warning("Unable to find method_link_species_set with method_link_type of $method_link_type and species_set_tag value of $species_set_name\n"); return undef } ################################### # # tagging # ################################### sub _tag_capabilities { return ("method_link_species_set_tag", undef, "method_link_species_set_id", "dbID"); } ############################################################ # Implements Bio::EnsEMBL::Compara::DBSQL::BaseFullAdaptor # ############################################################ sub _build_id_cache { my $self = shift; return Bio::EnsEMBL::DBSQL::Cache::MethodLinkSpeciesSet->new($self); } package Bio::EnsEMBL::DBSQL::Cache::MethodLinkSpeciesSet; use base qw/Bio::EnsEMBL::DBSQL::Support::FullIdCache/; use strict; use warnings; sub support_additional_lookups { return 1; } sub compute_keys { my ($self, $mlss) = @_; return { method => sprintf('%d', $mlss->method->dbID), method_species_set => sprintf('%d_%d', $mlss->method->dbID, $mlss->species_set_obj->dbID), (map {sprintf('genome_db_%d', $_->dbID) => 1} @{$mlss->species_set_obj->genome_dbs()}), (map {sprintf('genome_db_%d_method_%s', $_->dbID, uc $mlss->method->type) => 1} @{$mlss->species_set_obj->genome_dbs()}), } } 1;
ckongEbi/ensembl-compara
modules/Bio/EnsEMBL/Compara/DBSQL/MethodLinkSpeciesSetAdaptor.pm
Perl
apache-2.0
22,887
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::alcatel::pss::1830::snmp::mode::listsap; use base qw(centreon::plugins::mode); use strict; use warnings; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } my $oid_tnSapDescription = '.1.3.6.1.4.1.7483.6.1.2.4.3.2.1.5'; my $oid_tnSvcName = '.1.3.6.1.4.1.7483.6.1.2.4.2.2.1.28'; sub manage_selection { my ($self, %options) = @_; $self->{sap} = {}; my $snmp_result = $self->{snmp}->get_multiple_table(oids => [ { oid => $oid_tnSapDescription }, { oid => $oid_tnSvcName } ], nothing_quit => 1); foreach my $oid (keys %{$snmp_result->{$oid_tnSapDescription}}) { next if ($oid !~ /^$oid_tnSapDescription\.(.*?)\.(.*?)\.(.*?)\.(.*?)$/); my ($SysSwitchId, $SvcId, $SapPortId, $SapEncapValue) = ($1, $2, $3, $4); $self->{sap}->{$SysSwitchId . '.' . $SvcId . '.' . $SapPortId . '.' . $SapEncapValue} = { SysSwitchId => $SysSwitchId, SvcId => $SvcId, SapPortId => $SapPortId, SapEncapValue => $SapEncapValue, SapDescription => $snmp_result->{$oid_tnSapDescription}->{$oid}, SvcName => defined($snmp_result->{$oid_tnSvcName}->{$oid_tnSvcName . '.' . $SysSwitchId . '.' . $SvcId}) ? $snmp_result->{$oid_tnSvcName}->{$oid_tnSvcName . '.' . $SysSwitchId . '.' . $SvcId} : '' }; } } sub run { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->manage_selection(); foreach my $instance (sort keys %{$self->{sap}}) { my $msg = ''; $self->{output}->output_add(long_msg => "[SysSwitchId = " . $self->{sap}->{$instance}->{SysSwitchId} . "]" . "[SvcId = " . $self->{sap}->{$instance}->{SvcId} . "]" . "[SapPortId = " . $self->{sap}->{$instance}->{SapPortId} . "]" . "[SapEncapValue = " . $self->{sap}->{$instance}->{SapEncapValue} . "]" . "[SapDescription = " . $self->{sap}->{$instance}->{SapDescription} . "]" . "[SvcName = " . $self->{sap}->{$instance}->{SvcName} . "]" ); } $self->{output}->output_add(severity => 'OK', short_msg => 'List SAP:'); $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 => ['SysSwitchId', 'SvcId', 'SapPortId', 'SapEncapValue', 'SapDescription', 'SvcName']); } sub disco_show { my ($self, %options) = @_; $self->{snmp} = $options{snmp}; $self->manage_selection(disco => 1); foreach my $instance (sort keys %{$self->{sap}}) { $self->{output}->add_disco_entry(%{$self->{sap}->{$instance}}); } } 1; __END__ =head1 MODE List SAP. =over 8 =back =cut
Tpo76/centreon-plugins
network/alcatel/pss/1830/snmp/mode/listsap.pm
Perl
apache-2.0
3,968
package Task::Mock::Person; # Pragmas. use strict; use warnings; # Version. our $VERSION = 0.04; 1; __END__ =pod =encoding utf8 =head1 NAME Task::Mock::Person - Install the Mock::Person modules. =head1 SYNOPSIS cpanm Task::Mock::Person =head1 SEE ALSO L<Mock::Person>, L<Mock::Person::CZ>, L<Mock::Person::DE>, L<Mock::Person::EN>, L<Mock::Person::JP::Person>, L<Mock::Person::SK>, L<Mock::Person::SK::ROM>, L<Mock::Person::SV>. =head1 REPOSITORY L<https://github.com/tupinek/Task-Mock-Person> =head1 AUTHOR Michal Špaček L<mailto:skim@cpan.org> L<http://skim.cz> =head1 LICENSE AND COPYRIGHT © 2015 Michal Špaček Artistic License BSD 2-Clause License =head1 VERSION 0.04 =cut
tupinek/Task-Mock-Person
Person.pm
Perl
bsd-2-clause
708
use utf8; package App::Netdisco::DB::Result::Subnet; # Created by DBIx::Class::Schema::Loader # DO NOT MODIFY THE FIRST PART OF THIS FILE use strict; use warnings; use base 'DBIx::Class::Core'; __PACKAGE__->table("subnets"); __PACKAGE__->add_columns( "net", { data_type => "cidr", is_nullable => 0 }, "creation", { data_type => "timestamp", default_value => \"current_timestamp", is_nullable => 1, original => { default_value => \"now()" }, }, "last_discover", { data_type => "timestamp", default_value => \"current_timestamp", is_nullable => 1, original => { default_value => \"now()" }, }, ); __PACKAGE__->set_primary_key("net"); # Created by DBIx::Class::Schema::Loader v0.07015 @ 2012-01-07 14:20:02 # DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:1EHOfYx8PYOHoTkViZR6OA # You can replace this text with custom code or comments, and it will be preserved on regeneration 1;
gitpan/App-Netdisco
lib/App/Netdisco/DB/Result/Subnet.pm
Perl
bsd-3-clause
953
<?php $PASS_WRONG_EMAIL_FOR_REGISTER = 'Próbujesz zarejestrować użytkownika na niepoprawny email.'; $CORRECT_PASSED_EMAIL = 'Email <b>%s</b> przekazany do rejestracji nie wygląda jak adres email, powinieneś wcześniej sprawdzać jego poprawność.'; $HERE_ERROR_OCCUR = 'Tutaj przekazujesz błędny email.'; $PASS_WRONG_EMAIL_FOR_LOGIN = 'Próbujesz zalogować użytkownika podając niepoprawny email.'; $CORRECT_EMAIL_FOR_LOGIN = 'Email <b>%s</b> przekazany przy logowaniu nie wygląda jak adres email, powinieneś wcześniej sprawdzać jego poprawność.'; $WANT_ACCESS_FOR_WRONG_EMAIL = 'Próbujesz uzyskać dostęp podając nieprawidłowy email.'; $CORRECT_ACCESS_EMAIL = 'Email dla którego chcesz sprawdzić dostęp <b>%s</b> nie wygląda jak adres email.'; $LOOKING_FOR_ACCOUT_BY_WRONG_EMAIL = 'Próbujesz szukać niepotwierdzone konta dla nieprawidłowego adresu email.'; $CORRECT_EMAIL_FOR_SEARCH = 'Popraw email <b>%s</b> przekazywany przy szukaniu.';
charJKL/deArcane
src/User28/_Exception/Input/WrongEmail.lang.pl
Perl
mit
969
#!/usr/bin/perl -w use strict; use Bio::SearchIO; die "perl $0 <blast_file>\n" unless @ARGV; parse_blastx_results(shift); sub parse_blastx_results { my $file = shift; my %return_hash; my $searchio = Bio::SearchIO->new(-format => 'blast', file => "$file" ); while (my $result = $searchio->next_result()) { last unless defined $result; my $query_name = $result->query_name; #print $query_name; my $flag = 0; while(my $hit = $result->next_hit()) { $flag = 1; my $hsp = $hit->next_hsp(); next unless defined $hsp; print $query_name, "\t",$hit->name,"\t",$hit->description,"\t", $hit->significance,"\t", $result->query_length, "\t", $hsp->length('hit'), "\t", $hsp->percent_identity , "%\n"; #last if $flag; } # print "\n"; } return %return_hash; }
swang8/Perl_scripts_misc
parse_blast_output_for_acquried_exon.pl
Perl
mit
784
########################################################################### # # 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::mk - Locale data examples for the mk locale. =head1 DESCRIPTION This pod file contains examples of the locale data available for the Macedonian 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) прво тромесечје второ тромесечје трето тромесечје четврто тромесечје =head3 Abbreviated (format) јан-мар апр-јун јул-сеп окт-дек =head3 Narrow (format) 1 2 3 4 =head3 Wide (stand-alone) прво тромесечје второ тромесечје трето тромесечје четврто тромесечје =head3 Abbreviated (stand-alone) јан-мар апр-јун јул-сеп окт-дек =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 = вторник, 05 февруари 2008 1995-12-22T09:05:02 = петок, 22 декември 1995 -0010-09-15T04:44:23 = сабота, 15 септември -10 =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.2.2008 1995-12-22T09:05:02 = 22.12.1995 -0010-09-15T04:44:23 = 15.9.-10 =head3 Short 2008-02-05T18:30:30 = 05.2.08 1995-12-22T09:05:02 = 22.12.95 -0010-09-15T04:44:23 = 15.9.-10 =head2 Time Formats =head3 Full 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 09:05:02 UTC -0010-09-15T04:44:23 = 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 18:30:30 1995-12-22T09:05:02 = 09:05:02 -0010-09-15T04:44:23 = 04:44:23 =head3 Short 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head2 Datetime Formats =head3 Full 2008-02-05T18:30:30 = вторник, 05 февруари 2008 18:30:30 UTC 1995-12-22T09:05:02 = петок, 22 декември 1995 09:05:02 UTC -0010-09-15T04:44:23 = сабота, 15 септември -10 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 05 февруари 2008 18:30:30 UTC 1995-12-22T09:05:02 = 22 декември 1995 09:05:02 UTC -0010-09-15T04:44:23 = 15 септември -10 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 05.2.2008 18:30:30 1995-12-22T09:05:02 = 22.12.1995 09:05:02 -0010-09-15T04:44:23 = 15.9.-10 04:44:23 =head3 Short 2008-02-05T18:30:30 = 05.2.08 18:30 1995-12-22T09:05:02 = 22.12.95 09:05 -0010-09-15T04:44:23 = 15.9.-10 04: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 E) 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 попладне 1995-12-22T09:05:02 = пет. 9:05 претпладне -0010-09-15T04:44:23 = саб. 4:44 претпладне =head3 Ehms (E h:mm:ss a) 2008-02-05T18:30:30 = вт. 6:30:30 попладне 1995-12-22T09:05:02 = пет. 9:05:02 претпладне -0010-09-15T04:44:23 = саб. 4:44:23 претпладне =head3 Gy (y G) 2008-02-05T18:30:30 = 2008 н.е. 1995-12-22T09:05:02 = 1995 н.е. -0010-09-15T04:44:23 = -10 пр.н.е. =head3 GyMMM (MMM y G) 2008-02-05T18:30:30 = фев. 2008 н.е. 1995-12-22T09:05:02 = дек. 1995 н.е. -0010-09-15T04:44:23 = септ. -10 пр.н.е. =head3 GyMMMEd (E, dd MMM y G) 2008-02-05T18:30:30 = вт., 05 фев. 2008 н.е. 1995-12-22T09:05:02 = пет., 22 дек. 1995 н.е. -0010-09-15T04:44:23 = саб., 15 септ. -10 пр.н.е. =head3 GyMMMd (dd MMM y G) 2008-02-05T18:30:30 = 05 фев. 2008 н.е. 1995-12-22T09:05:02 = 22 дек. 1995 н.е. -0010-09-15T04:44:23 = 15 септ. -10 пр.н.е. =head3 H (HH) 2008-02-05T18:30:30 = 18 1995-12-22T09:05:02 = 09 -0010-09-15T04:44:23 = 04 =head3 Hm (HH:mm) 2008-02-05T18:30:30 = 18:30 1995-12-22T09:05:02 = 09:05 -0010-09-15T04:44:23 = 04:44 =head3 Hms (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 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 (E, d.M) 2008-02-05T18:30:30 = вт., 5.2 1995-12-22T09:05:02 = пет., 22.12 -0010-09-15T04:44:23 = саб., 15.9 =head3 MMM (LLL) 2008-02-05T18:30:30 = фев. 1995-12-22T09:05:02 = дек. -0010-09-15T04:44:23 = септ. =head3 MMMEd (E d MMM) 2008-02-05T18:30:30 = вт. 5 фев. 1995-12-22T09:05:02 = пет. 22 дек. -0010-09-15T04:44:23 = саб. 15 септ. =head3 MMMMEd (E d MMMM) 2008-02-05T18:30:30 = вт. 5 февруари 1995-12-22T09:05:02 = пет. 22 декември -0010-09-15T04:44:23 = саб. 15 септември =head3 MMMMd (d MMMM) 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 (d.M) 2008-02-05T18:30:30 = 5.2 1995-12-22T09:05:02 = 22.12 -0010-09-15T04:44:23 = 15.9 =head3 Mdd (dd.M) 2008-02-05T18:30:30 = 05.2 1995-12-22T09:05:02 = 22.12 -0010-09-15T04:44:23 = 15.9 =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 попладне 1995-12-22T09:05:02 = 9 претпладне -0010-09-15T04:44:23 = 4 претпладне =head3 hm (h:mm a) 2008-02-05T18:30:30 = 6:30 попладне 1995-12-22T09:05:02 = 9:05 претпладне -0010-09-15T04:44:23 = 4:44 претпладне =head3 hms (h:mm:ss a) 2008-02-05T18:30:30 = 6:30:30 попладне 1995-12-22T09:05:02 = 9:05:02 претпладне -0010-09-15T04:44:23 = 4:44:23 претпладне =head3 hmsv (h:mm:ss a v) 2008-02-05T18:30:30 = 6:30:30 попладне UTC 1995-12-22T09:05:02 = 9:05:02 претпладне UTC -0010-09-15T04:44:23 = 4:44:23 претпладне UTC =head3 hmv (h:mm a v) 2008-02-05T18:30:30 = 6:30 попладне UTC 1995-12-22T09:05:02 = 9:05 претпладне UTC -0010-09-15T04:44:23 = 4:44 претпладне 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 (M.y) 2008-02-05T18:30:30 = 2.2008 1995-12-22T09:05:02 = 12.1995 -0010-09-15T04:44:23 = 9.-10 =head3 yMEd (E, d.M.y) 2008-02-05T18:30:30 = вт., 5.2.2008 1995-12-22T09:05:02 = пет., 22.12.1995 -0010-09-15T04:44:23 = саб., 15.9.-10 =head3 yMMM (MMM y 'г'.) 2008-02-05T18:30:30 = фев. 2008 г. 1995-12-22T09:05:02 = дек. 1995 г. -0010-09-15T04:44:23 = септ. -10 г. =head3 yMMMEd (E, 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 yMMMM (MMMM y 'г'.) 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 (d.M.y) 2008-02-05T18:30:30 = 5.2.2008 1995-12-22T09:05:02 = 22.12.1995 -0010-09-15T04:44:23 = 15.9.-10 =head3 yQQQ (QQQ y 'г'.) 2008-02-05T18:30:30 = јан-мар 2008 г. 1995-12-22T09:05:02 = окт-дек 1995 г. -0010-09-15T04:44:23 = јул-сеп -10 г. =head3 yQQQQ (QQQQ y 'г'.) 2008-02-05T18:30:30 = прво тромесечје 2008 г. 1995-12-22T09:05:02 = четврто тромесечје 1995 г. -0010-09-15T04:44:23 = трето тромесечје -10 г. =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/mk.pod
Perl
mit
11,409
package AsposeImagingCloud::ImagingApi; require 5.6.0; use strict; use warnings; use utf8; use Exporter; use Carp qw( croak ); use Log::Any qw($log); use File::Slurp; use AsposeImagingCloud::ApiClient; use AsposeImagingCloud::Configuration; my $VERSION = '1.03'; sub new { my $class = shift; my $default_api_client = $AsposeImagingCloud::Configuration::api_client ? $AsposeImagingCloud::Configuration::api_client : AsposeImagingCloud::ApiClient->new; my (%self) = ( 'api_client' => $default_api_client, @_ ); #my $self = { # #api_client => $options->{api_client} # api_client => $default_api_client #}; bless \%self, $class; } # # PostImageBmp # # Update parameters of bmp image. # # @param String $bitsPerPixel Color depth. (required) # @param String $horizontalResolution New horizontal resolution. (required) # @param String $verticalResolution New vertical resolution. (required) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImageBmp { my ($self, %args) = @_; # verify the required parameter 'bitsPerPixel' is set unless (exists $args{'bitsPerPixel'}) { croak("Missing the required parameter 'bitsPerPixel' when calling PostImageBmp"); } # verify the required parameter 'horizontalResolution' is set unless (exists $args{'horizontalResolution'}) { croak("Missing the required parameter 'horizontalResolution' when calling PostImageBmp"); } # verify the required parameter 'verticalResolution' is set unless (exists $args{'verticalResolution'}) { croak("Missing the required parameter 'verticalResolution' when calling PostImageBmp"); } # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImageBmp"); } # parse inputs my $_resource_path = '/imaging/bmp/?appSid={appSid}&amp;bitsPerPixel={bitsPerPixel}&amp;horizontalResolution={horizontalResolution}&amp;verticalResolution={verticalResolution}&amp;fromScratch={fromScratch}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'bitsPerPixel'}) { $_resource_path =~ s/\Q{bitsPerPixel}\E/$args{'bitsPerPixel'}/g; }else{ $_resource_path =~ s/[?&]bitsPerPixel.*?(?=&|\?|$)//g; }# query params if ( exists $args{'horizontalResolution'}) { $_resource_path =~ s/\Q{horizontalResolution}\E/$args{'horizontalResolution'}/g; }else{ $_resource_path =~ s/[?&]horizontalResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'verticalResolution'}) { $_resource_path =~ s/\Q{verticalResolution}\E/$args{'verticalResolution'}/g; }else{ $_resource_path =~ s/[?&]verticalResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostCropImage # # Crop image from body # # @param String $format Output file format. Valid Formats: Bmp, png, jpg, tiff, psd, gif. (required) # @param String $x X position of start point for cropping rectangle (required) # @param String $y Y position of start point for cropping rectangle (required) # @param String $width Width of cropping rectangle (required) # @param String $height Height of cropping rectangle (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostCropImage { my ($self, %args) = @_; # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling PostCropImage"); } # verify the required parameter 'x' is set unless (exists $args{'x'}) { croak("Missing the required parameter 'x' when calling PostCropImage"); } # verify the required parameter 'y' is set unless (exists $args{'y'}) { croak("Missing the required parameter 'y' when calling PostCropImage"); } # verify the required parameter 'width' is set unless (exists $args{'width'}) { croak("Missing the required parameter 'width' when calling PostCropImage"); } # verify the required parameter 'height' is set unless (exists $args{'height'}) { croak("Missing the required parameter 'height' when calling PostCropImage"); } # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostCropImage"); } # parse inputs my $_resource_path = '/imaging/crop/?appSid={appSid}&amp;toFormat={toFormat}&amp;x={x}&amp;y={y}&amp;width={width}&amp;height={height}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'x'}) { $_resource_path =~ s/\Q{x}\E/$args{'x'}/g; }else{ $_resource_path =~ s/[?&]x.*?(?=&|\?|$)//g; }# query params if ( exists $args{'y'}) { $_resource_path =~ s/\Q{y}\E/$args{'y'}/g; }else{ $_resource_path =~ s/[?&]y.*?(?=&|\?|$)//g; }# query params if ( exists $args{'width'}) { $_resource_path =~ s/\Q{width}\E/$args{'width'}/g; }else{ $_resource_path =~ s/[?&]width.*?(?=&|\?|$)//g; }# query params if ( exists $args{'height'}) { $_resource_path =~ s/\Q{height}\E/$args{'height'}/g; }else{ $_resource_path =~ s/[?&]height.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostImageGif # # Update parameters of gif image. # # @param String $backgroundColorIndex Index of the background color. (optional) # @param array $colorResolution Color resolution. (optional) # @param array $hasTrailer Specifies if image has trailer. (optional) # @param Integer $interlaced Specifies if image is interlaced. (optional) # @param Boolean $isPaletteSorted Specifies if palette is sorted. (optional) # @param String $pixelAspectRatio Pixel aspect ratio. (optional) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImageGif { my ($self, %args) = @_; # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImageBmp"); } # parse inputs my $_resource_path = '/imaging/gif/?appSid={appSid}&amp;backgroundColorIndex={backgroundColorIndex}&amp;colorResolution={colorResolution}&amp;hasTrailer={hasTrailer}&amp;interlaced={interlaced}&amp;isPaletteSorted={isPaletteSorted}&amp;pixelAspectRatio={pixelAspectRatio}&amp;fromScratch={fromScratch}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'backgroundColorIndex'}) { $_resource_path =~ s/\Q{backgroundColorIndex}\E/$args{'backgroundColorIndex'}/g; }else{ $_resource_path =~ s/[?&]backgroundColorIndex.*?(?=&|\?|$)//g; }# query params if ( exists $args{'colorResolution'}) { $_resource_path =~ s/\Q{colorResolution}\E/$args{'colorResolution'}/g; }else{ $_resource_path =~ s/[?&]colorResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'hasTrailer'}) { $_resource_path =~ s/\Q{hasTrailer}\E/$args{'hasTrailer'}/g; }else{ $_resource_path =~ s/[?&]hasTrailer.*?(?=&|\?|$)//g; }# query params if ( exists $args{'interlaced'}) { $_resource_path =~ s/\Q{interlaced}\E/$args{'interlaced'}/g; }else{ $_resource_path =~ s/[?&]interlaced.*?(?=&|\?|$)//g; }# query params if ( exists $args{'isPaletteSorted'}) { $_resource_path =~ s/\Q{isPaletteSorted}\E/$args{'isPaletteSorted'}/g; }else{ $_resource_path =~ s/[?&]isPaletteSorted.*?(?=&|\?|$)//g; }# query params if ( exists $args{'pixelAspectRatio'}) { $_resource_path =~ s/\Q{pixelAspectRatio}\E/$args{'pixelAspectRatio'}/g; }else{ $_resource_path =~ s/[?&]pixelAspectRatio.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostImageJpg # # Update parameters of jpg image. # # @param String $quality Quality of image. From 0 to 100. Default is 75 (optional) # @param String $compressionType Compression type. (optional) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImageJpg { my ($self, %args) = @_; # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImageJpg"); } # parse inputs my $_resource_path = '/imaging/jpg/?appSid={appSid}&amp;quality={quality}&amp;compressionType={compressionType}&amp;fromScratch={fromScratch}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'quality'}) { $_resource_path =~ s/\Q{quality}\E/$args{'quality'}/g; }else{ $_resource_path =~ s/[?&]quality.*?(?=&|\?|$)//g; }# query params if ( exists $args{'compressionType'}) { $_resource_path =~ s/\Q{compressionType}\E/$args{'compressionType'}/g; }else{ $_resource_path =~ s/[?&]compressionType.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostImagePng # # Update parameters of png image. # # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImagePng { my ($self, %args) = @_; # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImagePng"); } # parse inputs my $_resource_path = '/imaging/png/?appSid={appSid}&amp;fromScratch={fromScratch}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostImagePsd # # Update parameters of psd image. # # @param Integer $channelsCount Count of channels. (optional) # @param String $compressionMethod Compression method. (optional) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImagePsd { my ($self, %args) = @_; # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImagePsd"); } # parse inputs my $_resource_path = '/imaging/psd/?appSid={appSid}&amp;channelsCount={channelsCount}&amp;compressionMethod={compressionMethod}&amp;fromScratch={fromScratch}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'channelsCount'}) { $_resource_path =~ s/\Q{channelsCount}\E/$args{'channelsCount'}/g; }else{ $_resource_path =~ s/[?&]channelsCount.*?(?=&|\?|$)//g; }# query params if ( exists $args{'compressionMethod'}) { $_resource_path =~ s/\Q{compressionMethod}\E/$args{'compressionMethod'}/g; }else{ $_resource_path =~ s/[?&]compressionMethod.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostChangeImageScale # # Change scale of an image from body # # @param String $format Output file format. Valid Formats: Bmp, png, jpg, tiff, psd, gif. (required) # @param String $newWidth New width of the scaled image. (required) # @param String $newHeight New height of the scaled image. (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostChangeImageScale { my ($self, %args) = @_; # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling PostChangeImageScale"); } # verify the required parameter 'newWidth' is set unless (exists $args{'newWidth'}) { croak("Missing the required parameter 'newWidth' when calling PostChangeImageScale"); } # verify the required parameter 'newHeight' is set unless (exists $args{'newHeight'}) { croak("Missing the required parameter 'newHeight' when calling PostChangeImageScale"); } # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostChangeImageScale"); } # parse inputs my $_resource_path = '/imaging/resize/?appSid={appSid}&amp;toFormat={toFormat}&amp;newWidth={newWidth}&amp;newHeight={newHeight}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newWidth'}) { $_resource_path =~ s/\Q{newWidth}\E/$args{'newWidth'}/g; }else{ $_resource_path =~ s/[?&]newWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newHeight'}) { $_resource_path =~ s/\Q{newHeight}\E/$args{'newHeight'}/g; }else{ $_resource_path =~ s/[?&]newHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostImageRotateFlip # # Rotate and flip existing image and get it from response. # # @param String $format Number of frame. (Bmp, png, jpg, tiff, psd, gif.) (required) # @param String $method New width of the scaled image. (Rotate180FlipNone, Rotate180FlipX, Rotate180FlipXY, Rotate180FlipY, Rotate270FlipNone, Rotate270FlipX, Rotate270FlipXY, Rotate270FlipY, Rotate90FlipNone, Rotate90FlipX, Rotate90FlipXY, Rotate90FlipY, RotateNoneFlipNone, RotateNoneFlipX, RotateNoneFlipXY, RotateNoneFlipY) (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImageRotateFlip { my ($self, %args) = @_; # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling PostImageRotateFlip"); } # verify the required parameter 'method' is set unless (exists $args{'method'}) { croak("Missing the required parameter 'method' when calling PostImageRotateFlip"); } # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImageRotateFlip"); } # parse inputs my $_resource_path = '/imaging/rotateflip/?toFormat={toFormat}&amp;appSid={appSid}&amp;method={method}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'method'}) { $_resource_path =~ s/\Q{method}\E/$args{'method'}/g; }else{ $_resource_path =~ s/[?&]method.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostImageSaveAs # # Export existing image to another format. Image is passed as request body. # # @param String $format Output file format. (Bmp, png, jpg, tiff, psd, gif.) (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImageSaveAs { my ($self, %args) = @_; # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling PostImageSaveAs"); } # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImageSaveAs"); } # parse inputs my $_resource_path = '/imaging/saveAs/?appSid={appSid}&amp;toFormat={toFormat}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostProcessTiff # # Update tiff image. # # @param String $compression New compression. (optional) # @param String $resolutionUnit New resolution unit. (optional) # @param String $bitDepth New bit depth. (optional) # @param Boolean $fromScratch (optional) # @param String $horizontalResolution New horizontal resolution. (optional) # @param String $verticalResolution New verstical resolution. (optional) # @param String $outPath Path to save result (optional) # @param File $file (required) # @return ResponseMessage # sub PostProcessTiff { my ($self, %args) = @_; # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostProcessTiff"); } # parse inputs my $_resource_path = '/imaging/tiff/?appSid={appSid}&amp;compression={compression}&amp;resolutionUnit={resolutionUnit}&amp;bitDepth={bitDepth}&amp;fromScratch={fromScratch}&amp;horizontalResolution={horizontalResolution}&amp;verticalResolution={verticalResolution}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'compression'}) { $_resource_path =~ s/\Q{compression}\E/$args{'compression'}/g; }else{ $_resource_path =~ s/[?&]compression.*?(?=&|\?|$)//g; }# query params if ( exists $args{'resolutionUnit'}) { $_resource_path =~ s/\Q{resolutionUnit}\E/$args{'resolutionUnit'}/g; }else{ $_resource_path =~ s/[?&]resolutionUnit.*?(?=&|\?|$)//g; }# query params if ( exists $args{'bitDepth'}) { $_resource_path =~ s/\Q{bitDepth}\E/$args{'bitDepth'}/g; }else{ $_resource_path =~ s/[?&]bitDepth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'horizontalResolution'}) { $_resource_path =~ s/\Q{horizontalResolution}\E/$args{'horizontalResolution'}/g; }else{ $_resource_path =~ s/[?&]horizontalResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'verticalResolution'}) { $_resource_path =~ s/\Q{verticalResolution}\E/$args{'verticalResolution'}/g; }else{ $_resource_path =~ s/[?&]verticalResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostTiffAppend # # Append tiff image. # # @param String $name Original image name. (required) # @param String $appendFile Second image file name. (optional) # @param String $storage The images storage. (optional) # @param String $folder The images folder. (optional) # @return SaaSposeResponse # sub PostTiffAppend { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling PostTiffAppend"); } # parse inputs my $_resource_path = '/imaging/tiff/{name}/appendTiff/?appSid={appSid}&amp;appendFile={appendFile}&amp;storage={storage}&amp;folder={folder}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/json'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'appendFile'}) { $_resource_path =~ s/\Q{appendFile}\E/$args{'appendFile'}/g; }else{ $_resource_path =~ s/[?&]appendFile.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'SaaSposeResponse', $response->header('content-type')); return $_response_object; } # # GetTiffToFax # # Get tiff image for fax. # # @param String $name The image file name. (required) # @param String $storage The image file storage. (optional) # @param String $folder The image file folder. (optional) # @param String $outPath Path to save result (optional) # @return ResponseMessage # sub GetTiffToFax { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetTiffToFax"); } # parse inputs my $_resource_path = '/imaging/tiff/{name}/toFax/?appSid={appSid}&amp;storage={storage}&amp;folder={folder}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # PostImageOperationsSaveAs # # Perform scaling, cropping and flipping of an image in single request. Image is passed as request body. # # @param String $format Save image in another format. By default format remains the same (required) # @param String $newWidth New Width of the scaled image. (required) # @param String $newHeight New height of the scaled image. (required) # @param String $x X position of start point for cropping rectangle (required) # @param String $y Y position of start point for cropping rectangle (required) # @param String $rectWidth Width of cropping rectangle (required) # @param String $rectHeight Height of cropping rectangle (required) # @param String $rotateFlipMethod RotateFlip method. Default is RotateNoneFlipNone. (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param File $file (required) # @return ResponseMessage # sub PostImageOperationsSaveAs { my ($self, %args) = @_; # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling PostImageSaveAs"); } # verify the required parameter 'newWidth' is set unless (exists $args{'newWidth'}) { croak("Missing the required parameter 'newWidth' when calling PostImageSaveAs"); } # verify the required parameter 'newHeight' is set unless (exists $args{'newHeight'}) { croak("Missing the required parameter 'newHeight' when calling PostImageSaveAs"); } # verify the required parameter 'x' is set unless (exists $args{'x'}) { croak("Missing the required parameter 'x' when calling PostImageSaveAs"); } # verify the required parameter 'y' is set unless (exists $args{'y'}) { croak("Missing the required parameter 'y' when calling PostImageSaveAs"); } # verify the required parameter 'rectWidth' is set unless (exists $args{'rectWidth'}) { croak("Missing the required parameter 'rectWidth' when calling PostImageSaveAs"); } # verify the required parameter 'rectHeight' is set unless (exists $args{'rectHeight'}) { croak("Missing the required parameter 'rectHeight' when calling PostImageSaveAs"); } # verify the required parameter 'rotateFlipMethod' is set unless (exists $args{'rotateFlipMethod'}) { croak("Missing the required parameter 'rotateFlipMethod' when calling PostImageSaveAs"); } # verify the required parameter 'file' is set unless (exists $args{'file'}) { croak("Missing the required parameter 'file' when calling PostImageSaveAs"); } # parse inputs my $_resource_path = '/imaging/updateImage/?appSid={appSid}&amp;toFormat={toFormat}&amp;newWidth={newWidth}&amp;newHeight={newHeight}&amp;x={x}&amp;y={y}&amp;rectWidth={rectWidth}&amp;rectHeight={rectHeight}&amp;rotateFlipMethod={rotateFlipMethod}&amp;outPath={outPath}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); # query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newWidth'}) { $_resource_path =~ s/\Q{newWidth}\E/$args{'newWidth'}/g; }else{ $_resource_path =~ s/[?&]newWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newHeight'}) { $_resource_path =~ s/\Q{newHeight}\E/$args{'newHeight'}/g; }else{ $_resource_path =~ s/[?&]newHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'x'}) { $_resource_path =~ s/\Q{x}\E/$args{'x'}/g; }else{ $_resource_path =~ s/[?&]x.*?(?=&|\?|$)//g; }# query params if ( exists $args{'y'}) { $_resource_path =~ s/\Q{y}\E/$args{'y'}/g; }else{ $_resource_path =~ s/[?&]y.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rectWidth'}) { $_resource_path =~ s/\Q{rectWidth}\E/$args{'rectWidth'}/g; }else{ $_resource_path =~ s/[?&]rectWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rectHeight'}) { $_resource_path =~ s/\Q{rectHeight}\E/$args{'rectHeight'}/g; }else{ $_resource_path =~ s/[?&]rectHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rotateFlipMethod'}) { $_resource_path =~ s/\Q{rotateFlipMethod}\E/$args{'rotateFlipMethod'}/g; }else{ $_resource_path =~ s/[?&]rotateFlipMethod.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; } my $_body_data; # form params if ( exists $args{'file'} ) { $_body_data = read_file( $args{'file'} , binmode => ':raw' ); } # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImageBmp # # Update parameters of bmp image. # # @param String $name Filename of image. (required) # @param String $bitsPerPixel Color depth. (required) # @param String $horizontalResolution New horizontal resolution. (required) # @param String $verticalResolution New vertical resolution. (required) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImageBmp { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageBmp"); } # verify the required parameter 'bitsPerPixel' is set unless (exists $args{'bitsPerPixel'}) { croak("Missing the required parameter 'bitsPerPixel' when calling GetImageBmp"); } # verify the required parameter 'horizontalResolution' is set unless (exists $args{'horizontalResolution'}) { croak("Missing the required parameter 'horizontalResolution' when calling GetImageBmp"); } # verify the required parameter 'verticalResolution' is set unless (exists $args{'verticalResolution'}) { croak("Missing the required parameter 'verticalResolution' when calling GetImageBmp"); } # parse inputs my $_resource_path = '/imaging/{name}/bmp/?appSid={appSid}&amp;bitsPerPixel={bitsPerPixel}&amp;horizontalResolution={horizontalResolution}&amp;verticalResolution={verticalResolution}&amp;fromScratch={fromScratch}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'bitsPerPixel'}) { $_resource_path =~ s/\Q{bitsPerPixel}\E/$args{'bitsPerPixel'}/g; }else{ $_resource_path =~ s/[?&]bitsPerPixel.*?(?=&|\?|$)//g; }# query params if ( exists $args{'horizontalResolution'}) { $_resource_path =~ s/\Q{horizontalResolution}\E/$args{'horizontalResolution'}/g; }else{ $_resource_path =~ s/[?&]horizontalResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'verticalResolution'}) { $_resource_path =~ s/\Q{verticalResolution}\E/$args{'verticalResolution'}/g; }else{ $_resource_path =~ s/[?&]verticalResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetCropImage # # Crop existing image # # @param String $name The image name. (required) # @param String $format Output file format. Valid Formats: Bmp, png, jpg, tiff, psd, gif. (required) # @param String $x X position of start point for cropping rectangle (required) # @param String $y Y position of start point for cropping rectangle (required) # @param String $width Width of cropping rectangle (required) # @param String $height Height of cropping rectangle (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetCropImage { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetCropImage"); } # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling GetCropImage"); } # verify the required parameter 'x' is set unless (exists $args{'x'}) { croak("Missing the required parameter 'x' when calling GetCropImage"); } # verify the required parameter 'y' is set unless (exists $args{'y'}) { croak("Missing the required parameter 'y' when calling GetCropImage"); } # verify the required parameter 'width' is set unless (exists $args{'width'}) { croak("Missing the required parameter 'width' when calling GetCropImage"); } # verify the required parameter 'height' is set unless (exists $args{'height'}) { croak("Missing the required parameter 'height' when calling GetCropImage"); } # parse inputs my $_resource_path = '/imaging/{name}/crop/?appSid={appSid}&amp;toFormat={toFormat}&amp;x={x}&amp;y={y}&amp;width={width}&amp;height={height}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'x'}) { $_resource_path =~ s/\Q{x}\E/$args{'x'}/g; }else{ $_resource_path =~ s/[?&]x.*?(?=&|\?|$)//g; }# query params if ( exists $args{'y'}) { $_resource_path =~ s/\Q{y}\E/$args{'y'}/g; }else{ $_resource_path =~ s/[?&]y.*?(?=&|\?|$)//g; }# query params if ( exists $args{'width'}) { $_resource_path =~ s/\Q{width}\E/$args{'width'}/g; }else{ $_resource_path =~ s/[?&]width.*?(?=&|\?|$)//g; }# query params if ( exists $args{'height'}) { $_resource_path =~ s/\Q{height}\E/$args{'height'}/g; }else{ $_resource_path =~ s/[?&]height.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImageFrame # # Get separate frame of tiff image # # @param String $name Filename of image. (required) # @param String $frameId Number of frame. (required) # @param String $newWidth New width of the scaled image. (optional) # @param String $newHeight New height of the scaled image. (optional) # @param String $x X position of start point for cropping rectangle (optional) # @param String $y Y position of start point for cropping rectangle (optional) # @param String $rectWidth Width of cropping rectangle (optional) # @param String $rectHeight Height of cropping rectangle (optional) # @param String $rotateFlipMethod RotateFlip method.(Rotate180FlipNone, Rotate180FlipX, Rotate180FlipXY, Rotate180FlipY, Rotate270FlipNone, Rotate270FlipX, Rotate270FlipXY, Rotate270FlipY, Rotate90FlipNone, Rotate90FlipX, Rotate90FlipXY, Rotate90FlipY, RotateNoneFlipNone, RotateNoneFlipX, RotateNoneFlipXY, RotateNoneFlipY. Default is RotateNoneFlipNone.) (optional) # @param Boolean $saveOtherFrames Include all other frames or just specified frame in response. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImageFrame { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageFrame"); } # verify the required parameter 'frameId' is set unless (exists $args{'frameId'}) { croak("Missing the required parameter 'frameId' when calling GetImageFrame"); } # parse inputs my $_resource_path = '/imaging/{name}/frames/{frameId}/?appSid={appSid}&amp;newWidth={newWidth}&amp;newHeight={newHeight}&amp;x={x}&amp;y={y}&amp;rectWidth={rectWidth}&amp;rectHeight={rectHeight}&amp;rotateFlipMethod={rotateFlipMethod}&amp;saveOtherFrames={saveOtherFrames}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'frameId'}) { $_resource_path =~ s/\Q{frameId}\E/$args{'frameId'}/g; }else{ $_resource_path =~ s/[?&]frameId.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newWidth'}) { $_resource_path =~ s/\Q{newWidth}\E/$args{'newWidth'}/g; }else{ $_resource_path =~ s/[?&]newWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newHeight'}) { $_resource_path =~ s/\Q{newHeight}\E/$args{'newHeight'}/g; }else{ $_resource_path =~ s/[?&]newHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'x'}) { $_resource_path =~ s/\Q{x}\E/$args{'x'}/g; }else{ $_resource_path =~ s/[?&]x.*?(?=&|\?|$)//g; }# query params if ( exists $args{'y'}) { $_resource_path =~ s/\Q{y}\E/$args{'y'}/g; }else{ $_resource_path =~ s/[?&]y.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rectWidth'}) { $_resource_path =~ s/\Q{rectWidth}\E/$args{'rectWidth'}/g; }else{ $_resource_path =~ s/[?&]rectWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rectHeight'}) { $_resource_path =~ s/\Q{rectHeight}\E/$args{'rectHeight'}/g; }else{ $_resource_path =~ s/[?&]rectHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rotateFlipMethod'}) { $_resource_path =~ s/\Q{rotateFlipMethod}\E/$args{'rotateFlipMethod'}/g; }else{ $_resource_path =~ s/[?&]rotateFlipMethod.*?(?=&|\?|$)//g; }# query params if ( exists $args{'saveOtherFrames'}) { $_resource_path =~ s/\Q{saveOtherFrames}\E/$args{'saveOtherFrames'}/g; }else{ $_resource_path =~ s/[?&]saveOtherFrames.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImageFrameProperties # # Get properties of a tiff frame. # # @param String $name Filename with image. (required) # @param String $frameId Number of frame. (required) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ImagingResponse # sub GetImageFrameProperties { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageFrameProperties"); } # verify the required parameter 'frameId' is set unless (exists $args{'frameId'}) { croak("Missing the required parameter 'frameId' when calling GetImageFrameProperties"); } # parse inputs my $_resource_path = '/imaging/{name}/frames/{frameId}/properties/?appSid={appSid}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/json'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'frameId'}) { $_resource_path =~ s/\Q{frameId}\E/$args{'frameId'}/g; }else{ $_resource_path =~ s/[?&]frameId.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ImagingResponse', $response->header('content-type')); return $_response_object; } # # GetImageGif # # Update parameters of bmp image. # # @param String $name Filename of image. (required) # @param String $backgroundColorIndex Index of the background color. (optional) # @param String $colorResolution Color resolution. (optional) # @param Boolean $hasTrailer Specifies if image has trailer. (optional) # @param Boolean $interlaced Specifies if image is interlaced. (optional) # @param Boolean $isPaletteSorted Specifies if palette is sorted. (optional) # @param String $pixelAspectRatio Pixel aspect ratio. (optional) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImageGif { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageGif"); } # parse inputs my $_resource_path = '/imaging/{name}/gif/?appSid={appSid}&amp;backgroundColorIndex={backgroundColorIndex}&amp;colorResolution={colorResolution}&amp;hasTrailer={hasTrailer}&amp;interlaced={interlaced}&amp;isPaletteSorted={isPaletteSorted}&amp;pixelAspectRatio={pixelAspectRatio}&amp;fromScratch={fromScratch}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'backgroundColorIndex'}) { $_resource_path =~ s/\Q{backgroundColorIndex}\E/$args{'backgroundColorIndex'}/g; }else{ $_resource_path =~ s/[?&]backgroundColorIndex.*?(?=&|\?|$)//g; }# query params if ( exists $args{'colorResolution'}) { $_resource_path =~ s/\Q{colorResolution}\E/$args{'colorResolution'}/g; }else{ $_resource_path =~ s/[?&]colorResolution.*?(?=&|\?|$)//g; }# query params if ( exists $args{'hasTrailer'}) { $_resource_path =~ s/\Q{hasTrailer}\E/$args{'hasTrailer'}/g; }else{ $_resource_path =~ s/[?&]hasTrailer.*?(?=&|\?|$)//g; }# query params if ( exists $args{'interlaced'}) { $_resource_path =~ s/\Q{interlaced}\E/$args{'interlaced'}/g; }else{ $_resource_path =~ s/[?&]interlaced.*?(?=&|\?|$)//g; }# query params if ( exists $args{'isPaletteSorted'}) { $_resource_path =~ s/\Q{isPaletteSorted}\E/$args{'isPaletteSorted'}/g; }else{ $_resource_path =~ s/[?&]isPaletteSorted.*?(?=&|\?|$)//g; }# query params if ( exists $args{'pixelAspectRatio'}) { $_resource_path =~ s/\Q{pixelAspectRatio}\E/$args{'pixelAspectRatio'}/g; }else{ $_resource_path =~ s/[?&]pixelAspectRatio.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImageJpg # # Update parameters of jpg image. # # @param String $name Filename of image. (required) # @param String $quality Quality of image. From 0 to 100. Default is 75 (optional) # @param String $compressionType Compression type. (optional) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImageJpg { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageJpg"); } # parse inputs my $_resource_path = '/imaging/{name}/jpg/?appSid={appSid}&amp;quality={quality}&amp;compressionType={compressionType}&amp;fromScratch={fromScratch}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'quality'}) { $_resource_path =~ s/\Q{quality}\E/$args{'quality'}/g; }else{ $_resource_path =~ s/[?&]quality.*?(?=&|\?|$)//g; }# query params if ( exists $args{'compressionType'}) { $_resource_path =~ s/\Q{compressionType}\E/$args{'compressionType'}/g; }else{ $_resource_path =~ s/[?&]compressionType.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImagePng # # Update parameters of png image. # # @param String $name Filename of image. (required) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImagePng { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImagePng"); } # parse inputs my $_resource_path = '/imaging/{name}/png/?appSid={appSid}&amp;fromScratch={fromScratch}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImageProperties # # Get properties of an image. # # @param String $name The image name. (required) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ImagingResponse # sub GetImageProperties { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageProperties"); } # parse inputs my $_resource_path = '/imaging/{name}/properties/?appSid={appSid}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/json'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ImagingResponse', $response->header('content-type')); return $_response_object; } # # GetImagePsd # # Update parameters of psd image. # # @param String $name Filename of image. (required) # @param Integer $channelsCount Count of channels. (optional) # @param String $compressionMethod Compression method. (optional) # @param Boolean $fromScratch Specifies where additional parameters we do not support should be taken from. If this is true – they will be taken from default values for standard image, if it is false – they will be saved from current image. Default is false. (optional) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImagePsd { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImagePsd"); } # parse inputs my $_resource_path = '/imaging/{name}/psd/?appSid={appSid}&amp;channelsCount={channelsCount}&amp;compressionMethod={compressionMethod}&amp;fromScratch={fromScratch}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'channelsCount'}) { $_resource_path =~ s/\Q{channelsCount}\E/$args{'channelsCount'}/g; }else{ $_resource_path =~ s/[?&]channelsCount.*?(?=&|\?|$)//g; }# query params if ( exists $args{'compressionMethod'}) { $_resource_path =~ s/\Q{compressionMethod}\E/$args{'compressionMethod'}/g; }else{ $_resource_path =~ s/[?&]compressionMethod.*?(?=&|\?|$)//g; }# query params if ( exists $args{'fromScratch'}) { $_resource_path =~ s/\Q{fromScratch}\E/$args{'fromScratch'}/g; }else{ $_resource_path =~ s/[?&]fromScratch.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetChangeImageScale # # Change scale of an existing image # # @param String $name The image name. (required) # @param String $format Output file format. Valid Formats: Bmp, png, jpg, tiff, psd, gif. (required) # @param String $newWidth New width of the scaled image. (required) # @param String $newHeight New height of the scaled image. (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetChangeImageScale { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetChangeImageScale"); } # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling GetChangeImageScale"); } # verify the required parameter 'newWidth' is set unless (exists $args{'newWidth'}) { croak("Missing the required parameter 'newWidth' when calling GetChangeImageScale"); } # verify the required parameter 'newHeight' is set unless (exists $args{'newHeight'}) { croak("Missing the required parameter 'newHeight' when calling GetChangeImageScale"); } # parse inputs my $_resource_path = '/imaging/{name}/resize/?appSid={appSid}&amp;toFormat={toFormat}&amp;newWidth={newWidth}&amp;newHeight={newHeight}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newWidth'}) { $_resource_path =~ s/\Q{newWidth}\E/$args{'newWidth'}/g; }else{ $_resource_path =~ s/[?&]newWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newHeight'}) { $_resource_path =~ s/\Q{newHeight}\E/$args{'newHeight'}/g; }else{ $_resource_path =~ s/[?&]newHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImageRotateFlip # # Rotate and flip existing image # # @param String $name Filename of image. (required) # @param String $format Number of frame. (Bmp, png, jpg, tiff, psd, gif.) (required) # @param String $method New width of the scaled image. (Rotate180FlipNone, Rotate180FlipX, Rotate180FlipXY, Rotate180FlipY, Rotate270FlipNone, Rotate270FlipX, Rotate270FlipXY, Rotate270FlipY, Rotate90FlipNone, Rotate90FlipX, Rotate90FlipXY, Rotate90FlipY, RotateNoneFlipNone, RotateNoneFlipX, RotateNoneFlipXY, RotateNoneFlipY) (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImageRotateFlip { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageRotateFlip"); } # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling GetImageRotateFlip"); } # verify the required parameter 'method' is set unless (exists $args{'method'}) { croak("Missing the required parameter 'method' when calling GetImageRotateFlip"); } # parse inputs my $_resource_path = '/imaging/{name}/rotateflip/?toFormat={toFormat}&amp;appSid={appSid}&amp;method={method}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'method'}) { $_resource_path =~ s/\Q{method}\E/$args{'method'}/g; }else{ $_resource_path =~ s/[?&]method.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetImageSaveAs # # Export existing image to another format # # @param String $name Filename of image. (required) # @param String $format Output file format. (Bmp, png, jpg, tiff, psd, gif.) (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetImageSaveAs { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetImageSaveAs"); } # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling GetImageSaveAs"); } # parse inputs my $_resource_path = '/imaging/{name}/saveAs/?appSid={appSid}&amp;toFormat={toFormat}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } # # GetUpdatedImage # # Perform scaling, cropping and flipping of an image in single request. # # @param String $name Filename of image. (required) # @param String $format Save image in another format. By default format remains the same (required) # @param String $newWidth New Width of the scaled image. (required) # @param String $newHeight New height of the scaled image. (required) # @param String $x X position of start point for cropping rectangle (required) # @param String $y Y position of start point for cropping rectangle (required) # @param String $rectWidth Width of cropping rectangle (required) # @param String $rectHeight Height of cropping rectangle (required) # @param String $rotateFlipMethod RotateFlip method. Default is RotateNoneFlipNone. (required) # @param String $outPath Path to updated file, if this is empty, response contains streamed image. (optional) # @param String $folder Folder with image to process. (optional) # @param String $storage (optional) # @return ResponseMessage # sub GetUpdatedImage { my ($self, %args) = @_; # verify the required parameter 'name' is set unless (exists $args{'name'}) { croak("Missing the required parameter 'name' when calling GetUpdatedImage"); } # verify the required parameter 'format' is set unless (exists $args{'format'}) { croak("Missing the required parameter 'format' when calling GetUpdatedImage"); } # verify the required parameter 'newWidth' is set unless (exists $args{'newWidth'}) { croak("Missing the required parameter 'newWidth' when calling GetUpdatedImage"); } # verify the required parameter 'newHeight' is set unless (exists $args{'newHeight'}) { croak("Missing the required parameter 'newHeight' when calling GetUpdatedImage"); } # verify the required parameter 'x' is set unless (exists $args{'x'}) { croak("Missing the required parameter 'x' when calling GetUpdatedImage"); } # verify the required parameter 'y' is set unless (exists $args{'y'}) { croak("Missing the required parameter 'y' when calling GetUpdatedImage"); } # verify the required parameter 'rectWidth' is set unless (exists $args{'rectWidth'}) { croak("Missing the required parameter 'rectWidth' when calling GetUpdatedImage"); } # verify the required parameter 'rectHeight' is set unless (exists $args{'rectHeight'}) { croak("Missing the required parameter 'rectHeight' when calling GetUpdatedImage"); } # verify the required parameter 'rotateFlipMethod' is set unless (exists $args{'rotateFlipMethod'}) { croak("Missing the required parameter 'rotateFlipMethod' when calling GetUpdatedImage"); } # parse inputs my $_resource_path = '/imaging/{name}/updateImage/?appSid={appSid}&amp;toFormat={toFormat}&amp;newWidth={newWidth}&amp;newHeight={newHeight}&amp;x={x}&amp;y={y}&amp;rectWidth={rectWidth}&amp;rectHeight={rectHeight}&amp;rotateFlipMethod={rotateFlipMethod}&amp;outPath={outPath}&amp;folder={folder}&amp;storage={storage}'; $_resource_path =~ s/\Q&amp;\E/&/g; $_resource_path =~ s/\Q\/?\E/?/g; $_resource_path =~ s/\QtoFormat={toFormat}\E/format={format}/g; $_resource_path =~ s/\Q{path}\E/{Path}/g; 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/xml', 'application/octet-stream'); if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; } $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); # query params if ( exists $args{'name'}) { $_resource_path =~ s/\Q{name}\E/$args{'name'}/g; }else{ $_resource_path =~ s/[?&]name.*?(?=&|\?|$)//g; }# query params if ( exists $args{'format'}) { $_resource_path =~ s/\Q{format}\E/$args{'format'}/g; }else{ $_resource_path =~ s/[?&]format.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newWidth'}) { $_resource_path =~ s/\Q{newWidth}\E/$args{'newWidth'}/g; }else{ $_resource_path =~ s/[?&]newWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'newHeight'}) { $_resource_path =~ s/\Q{newHeight}\E/$args{'newHeight'}/g; }else{ $_resource_path =~ s/[?&]newHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'x'}) { $_resource_path =~ s/\Q{x}\E/$args{'x'}/g; }else{ $_resource_path =~ s/[?&]x.*?(?=&|\?|$)//g; }# query params if ( exists $args{'y'}) { $_resource_path =~ s/\Q{y}\E/$args{'y'}/g; }else{ $_resource_path =~ s/[?&]y.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rectWidth'}) { $_resource_path =~ s/\Q{rectWidth}\E/$args{'rectWidth'}/g; }else{ $_resource_path =~ s/[?&]rectWidth.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rectHeight'}) { $_resource_path =~ s/\Q{rectHeight}\E/$args{'rectHeight'}/g; }else{ $_resource_path =~ s/[?&]rectHeight.*?(?=&|\?|$)//g; }# query params if ( exists $args{'rotateFlipMethod'}) { $_resource_path =~ s/\Q{rotateFlipMethod}\E/$args{'rotateFlipMethod'}/g; }else{ $_resource_path =~ s/[?&]rotateFlipMethod.*?(?=&|\?|$)//g; }# query params if ( exists $args{'outPath'}) { $_resource_path =~ s/\Q{outPath}\E/$args{'outPath'}/g; }else{ $_resource_path =~ s/[?&]outPath.*?(?=&|\?|$)//g; }# query params if ( exists $args{'folder'}) { $_resource_path =~ s/\Q{folder}\E/$args{'folder'}/g; }else{ $_resource_path =~ s/[?&]folder.*?(?=&|\?|$)//g; }# query params if ( exists $args{'storage'}) { $_resource_path =~ s/\Q{storage}\E/$args{'storage'}/g; }else{ $_resource_path =~ s/[?&]storage.*?(?=&|\?|$)//g; } my $_body_data; # authentication setting, if any my $auth_settings = []; # 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; } if($AsposeImagingCloud::Configuration::debug){ print "\nResponse Content: ".$response->content; } my $_response_object = $self->{api_client}->pre_deserialize($response->content, 'ResponseMessage', $response->header('content-type')); return $_response_object; } 1;
aspose-imaging/Aspose.Imaging-for-Cloud
SDKs/Aspose.Imaging-Cloud-SDK-for-Perl/lib/AsposeImagingCloud/ImagingApi.pm
Perl
mit
108,851
package Google::Ads::AdWords::v201409::CriterionAttribute; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/o/v201409' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201409::Attribute); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %Attribute__Type_of :ATTR(:get<Attribute__Type>); my %value_of :ATTR(:get<value>); __PACKAGE__->_factory( [ qw( Attribute__Type value ) ], { 'Attribute__Type' => \%Attribute__Type_of, 'value' => \%value_of, }, { 'Attribute__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'value' => 'Google::Ads::AdWords::v201409::Criterion', }, { 'Attribute__Type' => 'Attribute.Type', 'value' => 'value', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201409::CriterionAttribute =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType CriterionAttribute from the namespace https://adwords.google.com/api/adwords/o/v201409. {@link Attribute} type that contains a {@link Criterion} value. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * value =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/CriterionAttribute.pm
Perl
apache-2.0
1,654
# # 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::sensors::sensormetrix::em01::web::mode::humidity; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::http; sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; $options{options}->add_options(arguments => { "hostname:s" => { name => 'hostname' }, "port:s" => { name => 'port', }, "proto:s" => { name => 'proto' }, "urlpath:s" => { name => 'url_path', default => "/index.htm?em" }, "credentials" => { name => 'credentials' }, "username:s" => { name => 'username' }, "password:s" => { name => 'password' }, "proxyurl:s" => { name => 'proxyurl' }, "warning:s" => { name => 'warning' }, "critical:s" => { name => 'critical' }, "timeout:s" => { name => 'timeout' }, }); $self->{http} = centreon::plugins::http->new(output => $self->{output}); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); $self->{output}->option_exit(); } $self->{http}->set_options(%{$self->{option_results}}); } sub run { my ($self, %options) = @_; my $webcontent = $self->{http}->request(); my $humidity; if ($webcontent !~ /<body>(.*)<\/body>/msi || $1 !~ /HU:\s*([0-9\.]+)/i) { $self->{output}->add_option_msg(short_msg => "Could not find humidity information."); $self->{output}->option_exit(); } $humidity = $1; $humidity = '0' . $humidity if ($humidity =~ /^\./); my $exit = $self->{perfdata}->threshold_check(value => $humidity, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => sprintf("Humidity: %.2f %%", $humidity)); $self->{output}->perfdata_add(label => "humidity", unit => '%', value => sprintf("%.2f", $humidity), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), ); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check sensor Humidity. =over 8 =item B<--hostname> IP Addr/FQDN of the webserver host =item B<--port> Port used by Apache =item B<--proxyurl> Proxy URL if any =item B<--proto> Specify https if needed =item B<--urlpath> Set path to get server-status page in auto mode (Default: '/index.htm?em') =item B<--credentials> Specify this option if you access server-status page over basic authentification =item B<--username> Specify username for basic authentification (Mandatory if --credentials is specidied) =item B<--password> Specify password for basic authentification (Mandatory if --credentials is specidied) =item B<--timeout> Threshold for HTTP timeout =item B<--warning> Warning Threshold for Humidity =item B<--critical> Critical Threshold for Humidity =back =cut
bcournaud/centreon-plugins
hardware/sensors/sensormetrix/em01/web/mode/humidity.pm
Perl
apache-2.0
4,714
package VMOMI::HistoryCollector; use parent 'VMOMI::ManagedObject'; use strict; use warnings; our @class_ancestors = ( 'ManagedObject', ); our @class_members = ( ['filter', 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/HistoryCollector.pm
Perl
apache-2.0
417
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 8.0.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V1124 65 91 97 123 170 171 181 182 186 187 192 215 216 247 248 706 710 722 736 741 748 749 750 751 880 885 886 888 891 894 895 896 902 903 904 907 908 909 910 930 931 1014 1015 1154 1162 1328 1329 1367 1369 1370 1377 1416 1488 1515 1520 1523 1568 1611 1646 1648 1649 1748 1749 1750 1765 1767 1774 1776 1786 1789 1791 1792 1808 1809 1810 1840 1869 1958 1969 1970 1994 2027 2036 2038 2042 2043 2048 2070 2074 2075 2084 2085 2088 2089 2112 2137 2208 2229 2308 2362 2365 2366 2384 2385 2392 2402 2417 2433 2437 2445 2447 2449 2451 2473 2474 2481 2482 2483 2486 2490 2493 2494 2510 2511 2524 2526 2527 2530 2544 2546 2565 2571 2575 2577 2579 2601 2602 2609 2610 2612 2613 2615 2616 2618 2649 2653 2654 2655 2674 2677 2693 2702 2703 2706 2707 2729 2730 2737 2738 2740 2741 2746 2749 2750 2768 2769 2784 2786 2809 2810 2821 2829 2831 2833 2835 2857 2858 2865 2866 2868 2869 2874 2877 2878 2908 2910 2911 2914 2929 2930 2947 2948 2949 2955 2958 2961 2962 2966 2969 2971 2972 2973 2974 2976 2979 2981 2984 2987 2990 3002 3024 3025 3077 3085 3086 3089 3090 3113 3114 3130 3133 3134 3160 3163 3168 3170 3205 3213 3214 3217 3218 3241 3242 3252 3253 3258 3261 3262 3294 3295 3296 3298 3313 3315 3333 3341 3342 3345 3346 3387 3389 3390 3406 3407 3423 3426 3450 3456 3461 3479 3482 3506 3507 3516 3517 3518 3520 3527 3585 3633 3634 3635 3648 3655 3713 3715 3716 3717 3719 3721 3722 3723 3725 3726 3732 3736 3737 3744 3745 3748 3749 3750 3751 3752 3754 3756 3757 3761 3762 3763 3773 3774 3776 3781 3782 3783 3804 3808 3840 3841 3904 3912 3913 3949 3976 3981 4096 4139 4159 4160 4176 4182 4186 4190 4193 4194 4197 4199 4206 4209 4213 4226 4238 4239 4256 4294 4295 4296 4301 4302 4304 4347 4348 4681 4682 4686 4688 4695 4696 4697 4698 4702 4704 4745 4746 4750 4752 4785 4786 4790 4792 4799 4800 4801 4802 4806 4808 4823 4824 4881 4882 4886 4888 4955 4992 5008 5024 5110 5112 5118 5121 5741 5743 5760 5761 5787 5792 5867 5870 5881 5888 5901 5902 5906 5920 5938 5952 5970 5984 5997 5998 6001 6016 6068 6103 6104 6108 6109 6176 6264 6272 6313 6314 6315 6320 6390 6400 6431 6480 6510 6512 6517 6528 6572 6576 6602 6656 6679 6688 6741 6823 6824 6917 6964 6981 6988 7043 7073 7086 7088 7098 7142 7168 7204 7245 7248 7258 7294 7401 7405 7406 7410 7413 7415 7424 7616 7680 7958 7960 7966 7968 8006 8008 8014 8016 8024 8025 8026 8027 8028 8029 8030 8031 8062 8064 8117 8118 8125 8126 8127 8130 8133 8134 8141 8144 8148 8150 8156 8160 8173 8178 8181 8182 8189 8305 8306 8319 8320 8336 8349 8450 8451 8455 8456 8458 8468 8469 8470 8472 8478 8484 8485 8486 8487 8488 8489 8490 8506 8508 8512 8517 8522 8526 8527 8544 8585 11264 11311 11312 11359 11360 11493 11499 11503 11506 11508 11520 11558 11559 11560 11565 11566 11568 11624 11631 11632 11648 11671 11680 11687 11688 11695 11696 11703 11704 11711 11712 11719 11720 11727 11728 11735 11736 11743 12293 12296 12321 12330 12337 12342 12344 12349 12353 12439 12445 12448 12449 12539 12540 12544 12549 12590 12593 12687 12704 12731 12784 12800 13312 19894 19968 40918 40960 42125 42192 42238 42240 42509 42512 42528 42538 42540 42560 42607 42623 42654 42656 42736 42775 42784 42786 42889 42891 42926 42928 42936 42999 43010 43011 43014 43015 43019 43020 43043 43072 43124 43138 43188 43250 43256 43259 43260 43261 43262 43274 43302 43312 43335 43360 43389 43396 43443 43471 43472 43488 43493 43494 43504 43514 43519 43520 43561 43584 43587 43588 43596 43616 43639 43642 43643 43646 43696 43697 43698 43701 43703 43705 43710 43712 43713 43714 43715 43739 43742 43744 43755 43762 43765 43777 43783 43785 43791 43793 43799 43808 43815 43816 43823 43824 43867 43868 43878 43888 44003 44032 55204 55216 55239 55243 55292 63744 64110 64112 64218 64256 64263 64275 64280 64285 64286 64287 64297 64298 64311 64312 64317 64318 64319 64320 64322 64323 64325 64326 64434 64467 64606 64612 64830 64848 64912 64914 64968 65008 65018 65137 65138 65139 65140 65143 65144 65145 65146 65147 65148 65149 65150 65151 65277 65313 65339 65345 65371 65382 65438 65440 65471 65474 65480 65482 65488 65490 65496 65498 65501 65536 65548 65549 65575 65576 65595 65596 65598 65599 65614 65616 65630 65664 65787 65856 65909 66176 66205 66208 66257 66304 66336 66352 66379 66384 66422 66432 66462 66464 66500 66504 66512 66513 66518 66560 66718 66816 66856 66864 66916 67072 67383 67392 67414 67424 67432 67584 67590 67592 67593 67594 67638 67639 67641 67644 67645 67647 67670 67680 67703 67712 67743 67808 67827 67828 67830 67840 67862 67872 67898 67968 68024 68030 68032 68096 68097 68112 68116 68117 68120 68121 68148 68192 68221 68224 68253 68288 68296 68297 68325 68352 68406 68416 68438 68448 68467 68480 68498 68608 68681 68736 68787 68800 68851 69635 69688 69763 69808 69840 69865 69891 69927 69968 70003 70006 70007 70019 70067 70081 70085 70106 70107 70108 70109 70144 70162 70163 70188 70272 70279 70280 70281 70282 70286 70287 70302 70303 70313 70320 70367 70405 70413 70415 70417 70419 70441 70442 70449 70450 70452 70453 70458 70461 70462 70480 70481 70493 70498 70784 70832 70852 70854 70855 70856 71040 71087 71128 71132 71168 71216 71236 71237 71296 71339 71424 71450 71840 71904 71935 71936 72384 72441 73728 74650 74752 74863 74880 75076 77824 78895 82944 83527 92160 92729 92736 92767 92880 92910 92928 92976 92992 92996 93027 93048 93053 93072 93952 94021 94032 94033 94099 94112 110592 110594 113664 113771 113776 113789 113792 113801 113808 113818 119808 119893 119894 119965 119966 119968 119970 119971 119973 119975 119977 119981 119982 119994 119995 119996 119997 120004 120005 120070 120071 120075 120077 120085 120086 120093 120094 120122 120123 120127 120128 120133 120134 120135 120138 120145 120146 120486 120488 120513 120514 120539 120540 120571 120572 120597 120598 120629 120630 120655 120656 120687 120688 120713 120714 120745 120746 120771 120772 120780 124928 125125 126464 126468 126469 126496 126497 126499 126500 126501 126503 126504 126505 126515 126516 126520 126521 126522 126523 126524 126530 126531 126535 126536 126537 126538 126539 126540 126541 126544 126545 126547 126548 126549 126551 126552 126553 126554 126555 126556 126557 126558 126559 126560 126561 126563 126564 126565 126567 126571 126572 126579 126580 126584 126585 126589 126590 126591 126592 126602 126603 126620 126625 126628 126629 126634 126635 126652 131072 173783 173824 177973 177984 178206 178208 183970 194560 195102 END
operepo/ope
bin/usr/share/perl5/core_perl/unicore/lib/XIDS/Y.pl
Perl
mit
6,814
=pod =head1 NAME EVP_PKEY_is_a, EVP_PKEY_can_sign, EVP_PKEY_type_names_do_all, EVP_PKEY_get0_type_name, EVP_PKEY_get0_description, EVP_PKEY_get0_provider - key type and capabilities functions =head1 SYNOPSIS #include <openssl/evp.h> int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name); int EVP_PKEY_can_sign(const EVP_PKEY *pkey); int EVP_PKEY_type_names_do_all(const EVP_PKEY *pkey, void (*fn)(const char *name, void *data), void *data); const char *EVP_PKEY_get0_type_name(const EVP_PKEY *key); const char *EVP_PKEY_get0_description(const EVP_PKEY *key); const OSSL_PROVIDER *EVP_PKEY_get0_provider(const EVP_PKEY *key); =head1 DESCRIPTION EVP_PKEY_is_a() checks if the key type of I<pkey> is I<name>. EVP_PKEY_can_sign() checks if the functionality for the key type of I<pkey> supports signing. No other check is done, such as whether I<pkey> contains a private key. EVP_PKEY_type_names_do_all() traverses all names for I<pkey>'s key type, and calls I<fn> with each name and I<data>. For example, an RSA B<EVP_PKEY> may be named both C<RSA> and C<rsaEncryption>. The order of the names depends on the provider implementation that holds the key. EVP_PKEY_get0_type_name() returns the first key type name that is found for the given I<pkey>. Note that the I<pkey> may have multiple synonyms associated with it. In this case it depends on the provider implementation that holds the key which one will be returned. Ownership of the returned string is retained by the I<pkey> object and should not be freed by the caller. EVP_PKEY_get0_description() returns a description of the type of B<EVP_PKEY>, meant for display and human consumption. The description is at the discretion of the key type implementation. EVP_PKEY_get0_provider() returns the provider of the B<EVP_PKEY>'s L<EVP_KEYMGMT(3)>. =head1 RETURN VALUES EVP_PKEY_is_a() returns 1 if I<pkey> has the key type I<name>, otherwise 0. EVP_PKEY_can_sign() returns 1 if the I<pkey> key type functionality supports signing, otherwise 0. EVP_PKEY_get0_type_name() returns the name that is found or NULL on error. EVP_PKEY_get0_description() returns the description if found or NULL if not. EVP_PKEY_get0_provider() returns the provider if found or NULL if not. EVP_PKEY_type_names_do_all() returns 1 if the callback was called for all names. A return value of 0 means that the callback was not called for any names. =head1 EXAMPLES =head2 EVP_PKEY_is_a() The loaded providers and what key types they support will ultimately determine what I<name> is possible to use with EVP_PKEY_is_a(). We do know that the default provider supports RSA, DH, DSA and EC keys, so we can use this as an crude example: #include <openssl/evp.h> ... /* |pkey| is an EVP_PKEY* */ if (EVP_PKEY_is_a(pkey, "RSA")) { BIGNUM *modulus = NULL; if (EVP_PKEY_get_bn_param(pkey, "n", &modulus)) /* do whatever with the modulus */ BN_free(modulus); } =head2 EVP_PKEY_can_sign() #include <openssl/evp.h> ... /* |pkey| is an EVP_PKEY* */ if (!EVP_PKEY_can_sign(pkey)) { fprintf(stderr, "Not a signing key!"); exit(1); } /* Sign something... */ =head1 HISTORY The functions described here were added in OpenSSL 3.0. =head1 COPYRIGHT Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
jens-maus/amissl
openssl/doc/man3/EVP_PKEY_is_a.pod
Perl
bsd-3-clause
3,681
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 0000 021F 0222 0233 0250 02AD 02B0 02EE 0300 034E 0360 0362 0374 0375 037A 037E 0384 038A 038C 038E 03A1 03A3 03CE 03D0 03D7 03DA 03F5 0400 0486 0488 0489 048C 04C4 04C7 04C8 04CB 04CC 04D0 04F5 04F8 04F9 0531 0556 0559 055F 0561 0587 0589 058A 0591 05A1 05A3 05B9 05BB 05C4 05D0 05EA 05F0 05F4 060C 061B 061F 0621 063A 0640 0655 0660 066D 0670 06ED 06F0 06FE 0700 070D 070F 072C 0730 074A 0780 07B0 0901 0903 0905 0939 093C 094D 0950 0954 0958 0970 0981 0983 0985 098C 098F 0990 0993 09A8 09AA 09B0 09B2 09B6 09B9 09BC 09BE 09C4 09C7 09C8 09CB 09CD 09D7 09DC 09DD 09DF 09E3 09E6 09FA 0A02 0A05 0A0A 0A0F 0A10 0A13 0A28 0A2A 0A30 0A32 0A33 0A35 0A36 0A38 0A39 0A3C 0A3E 0A42 0A47 0A48 0A4B 0A4D 0A59 0A5C 0A5E 0A66 0A74 0A81 0A83 0A85 0A8B 0A8D 0A8F 0A91 0A93 0AA8 0AAA 0AB0 0AB2 0AB3 0AB5 0AB9 0ABC 0AC5 0AC7 0AC9 0ACB 0ACD 0AD0 0AE0 0AE6 0AEF 0B01 0B03 0B05 0B0C 0B0F 0B10 0B13 0B28 0B2A 0B30 0B32 0B33 0B36 0B39 0B3C 0B43 0B47 0B48 0B4B 0B4D 0B56 0B57 0B5C 0B5D 0B5F 0B61 0B66 0B70 0B82 0B83 0B85 0B8A 0B8E 0B90 0B92 0B95 0B99 0B9A 0B9C 0B9E 0B9F 0BA3 0BA4 0BA8 0BAA 0BAE 0BB5 0BB7 0BB9 0BBE 0BC2 0BC6 0BC8 0BCA 0BCD 0BD7 0BE7 0BF2 0C01 0C03 0C05 0C0C 0C0E 0C10 0C12 0C28 0C2A 0C33 0C35 0C39 0C3E 0C44 0C46 0C48 0C4A 0C4D 0C55 0C56 0C60 0C61 0C66 0C6F 0C82 0C83 0C85 0C8C 0C8E 0C90 0C92 0CA8 0CAA 0CB3 0CB5 0CB9 0CBE 0CC4 0CC6 0CC8 0CCA 0CCD 0CD5 0CD6 0CDE 0CE0 0CE1 0CE6 0CEF 0D02 0D03 0D05 0D0C 0D0E 0D10 0D12 0D28 0D2A 0D39 0D3E 0D43 0D46 0D48 0D4A 0D4D 0D57 0D60 0D61 0D66 0D6F 0D82 0D83 0D85 0D96 0D9A 0DB1 0DB3 0DBB 0DBD 0DC0 0DC6 0DCA 0DCF 0DD4 0DD6 0DD8 0DDF 0DF2 0DF4 0E01 0E3A 0E3F 0E5B 0E81 0E82 0E84 0E87 0E88 0E8A 0E8D 0E94 0E97 0E99 0E9F 0EA1 0EA3 0EA5 0EA7 0EAA 0EAB 0EAD 0EB9 0EBB 0EBD 0EC0 0EC4 0EC6 0EC8 0ECD 0ED0 0ED9 0EDC 0EDD 0F00 0F47 0F49 0F6A 0F71 0F8B 0F90 0F97 0F99 0FBC 0FBE 0FCC 0FCF 1000 1021 1023 1027 1029 102A 102C 1032 1036 1039 1040 1059 10A0 10C5 10D0 10F6 10FB 1100 1159 115F 11A2 11A8 11F9 1200 1206 1208 1246 1248 124A 124D 1250 1256 1258 125A 125D 1260 1286 1288 128A 128D 1290 12AE 12B0 12B2 12B5 12B8 12BE 12C0 12C2 12C5 12C8 12CE 12D0 12D6 12D8 12EE 12F0 130E 1310 1312 1315 1318 131E 1320 1346 1348 135A 1361 137C 13A0 13F4 1401 1676 1680 169C 16A0 16F0 1780 17DC 17E0 17E9 1800 180E 1810 1819 1820 1877 1880 18A9 1E00 1E9B 1EA0 1EF9 1F00 1F15 1F18 1F1D 1F20 1F45 1F48 1F4D 1F50 1F57 1F59 1F5B 1F5D 1F5F 1F7D 1F80 1FB4 1FB6 1FC4 1FC6 1FD3 1FD6 1FDB 1FDD 1FEF 1FF2 1FF4 1FF6 1FFE 2000 2046 2048 204D 206A 2070 2074 208E 20A0 20AF 20D0 20E3 2100 213A 2153 2183 2190 21F3 2200 22F1 2300 237B 237D 239A 2400 2426 2440 244A 2460 24EA 2500 2595 25A0 25F7 2600 2613 2619 2671 2701 2704 2706 2709 270C 2727 2729 274B 274D 274F 2752 2756 2758 275E 2761 2767 2776 2794 2798 27AF 27B1 27BE 2800 28FF 2E80 2E99 2E9B 2EF3 2F00 2FD5 2FF0 2FFB 3000 303A 303E 303F 3041 3094 3099 309E 30A1 30FE 3105 312C 3131 318E 3190 31B7 3200 321C 3220 3243 3260 327B 327F 32B0 32C0 32CB 32D0 32FE 3300 3376 337B 33DD 33E0 33FE 3400 4DB5 4E00 9FA5 A000 A48C A490 A4A1 A4A4 A4B3 A4B5 A4C0 A4C2 A4C4 A4C6 AC00 D7A3 D800 FA2D FB00 FB06 FB13 FB17 FB1D FB36 FB38 FB3C FB3E FB40 FB41 FB43 FB44 FB46 FBB1 FBD3 FD3F FD50 FD8F FD92 FDC7 FDD0 FDFB FE20 FE23 FE30 FE44 FE49 FE52 FE54 FE66 FE68 FE6B FE70 FE72 FE74 FE76 FEFC FEFF FF01 FF5E FF61 FFBE FFC2 FFC7 FFCA FFCF FFD2 FFD7 FFDA FFDC FFE0 FFE6 FFE8 FFEE FFF9 FFFF 10300 1031E 10320 10323 10330 1034A 10400 10425 10428 1044D 1D000 1D0F5 1D100 1D126 1D12A 1D1DD 1D400 1D454 1D456 1D49C 1D49E 1D49F 1D4A2 1D4A5 1D4A6 1D4A9 1D4AC 1D4AE 1D4B9 1D4BB 1D4BD 1D4C0 1D4C2 1D4C3 1D4C5 1D505 1D507 1D50A 1D50D 1D514 1D516 1D51C 1D51E 1D539 1D53B 1D53E 1D540 1D544 1D546 1D54A 1D550 1D552 1D6A3 1D6A8 1D7C9 1D7CE 1D7FF 1FFFE 2A6D6 2F800 2FA1D 2FFFE 2FFFF 3FFFE 3FFFF 4FFFE 4FFFF 5FFFE 5FFFF 6FFFE 6FFFF 7FFFE 7FFFF 8FFFE 8FFFF 9FFFE 9FFFF AFFFE AFFFF BFFFE BFFFF CFFFE CFFFF DFFFE DFFFF E0001 E0020 E007F EFFFE 10FFFF END
efortuna/AndroidSDKClone
ndk_experimental/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/In/3_1.pl
Perl
apache-2.0
4,387
#!/usr/bin/perl # # poll-mirrors.pl # # This script is designed to poll download sites after posting a release # and print out notice as each becomes available. The RM can use this # script to delay the release announcement until the release can be # downloaded. # # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # use strict; use warnings; use Getopt::Long; use POSIX qw/strftime/; use LWP::UserAgent; my $version; my $interval = 300; my $quiet = 0; my $result = GetOptions ("version=s" => \$version, "interval=i" => \$interval); my $usage = "$0 -v version [ -i interval (seconds; default: 300) ]"; unless ($result) { print STDERR $usage; exit(1); } unless (defined($version) && $version =~ /\d+(?:\.\d+)+/) { print STDERR "You must specify the release version.\n$usage"; exit(1); } my $previously_selected = select STDOUT; $| = 1; # turn off buffering of STDOUT, so status is printed immediately select $previously_selected; my $apache_url_suffix = "lucene/java/$version/lucene-$version.zip.asc"; my $apache_mirrors_list_url = "http://www.apache.org/mirrors/"; my $maven_url = "http://repo1.maven.org/maven2/org/apache/lucene/lucene-core/$version/lucene-core-$version.pom.asc"; my $agent = LWP::UserAgent->new(); $agent->timeout(2); my $maven_available = 0; my @apache_mirrors = (); my $apache_mirrors_list_page = $agent->get($apache_mirrors_list_url)->decoded_content; if (defined($apache_mirrors_list_page)) { #<TR> # <TD ALIGN=RIGHT><A HREF="http://apache.dattatec.com/">apache.dattatec.com</A>&nbsp;&nbsp;<A HREF="http://apache.dattatec.com/">@</A></TD> # # <TD>http</TD> # <TD ALIGN=RIGHT>8 hours<BR><IMG BORDER=1 SRC="icons/mms14.gif" ALT=""></TD> # <TD ALIGN=RIGHT>5 hours<BR><IMG BORDER=1 SRC="icons/mms14.gif" ALT=""></TD> # <TD>ok</TD> #</TR> while ($apache_mirrors_list_page =~ m~<TR>(.*?)</TR>~gis) { my $mirror_entry = $1; next unless ($mirror_entry =~ m~<TD>\s*ok\s*</TD>\s*$~i); # skip mirrors with problems if ($mirror_entry =~ m~<A\s+HREF\s*=\s*"([^"]+)"\s*>~i) { my $mirror_url = $1; push @apache_mirrors, "$mirror_url/$apache_url_suffix"; } } } else { print STDERR "Error fetching Apache mirrors list $apache_mirrors_list_url"; exit(1); } my $num_apache_mirrors = $#apache_mirrors; my $sleep_interval = 0; while (1) { print "\n", strftime('%d-%b-%Y %H:%M:%S', localtime); print "\nPolling $#apache_mirrors Apache Mirrors"; print " and Maven Central" unless ($maven_available); print "...\n"; my $start = time(); $maven_available = (200 == $agent->get($maven_url)->code) unless ($maven_available); @apache_mirrors = &check_mirrors; my $stop = time(); $sleep_interval = $interval - ($stop - $start); my $num_downloadable_apache_mirrors = $num_apache_mirrors - $#apache_mirrors; print "$version is ", ($maven_available ? "" : "not "), "downloadable from Maven Central.\n"; printf "$version is downloadable from %d/%d Apache Mirrors (%0.1f%%)\n", $num_downloadable_apache_mirrors, $num_apache_mirrors, ($num_downloadable_apache_mirrors*100/$num_apache_mirrors); last if ($maven_available && 0 == $#apache_mirrors); if ($sleep_interval > 0) { print "Sleeping for $sleep_interval seconds...\n"; sleep($sleep_interval) } } sub check_mirrors { my @not_yet_downloadable_apache_mirrors; for my $mirror (@apache_mirrors) { push @not_yet_downloadable_apache_mirrors, $mirror unless (200 == $agent->get($mirror)->code); print "."; } print "\n"; return @not_yet_downloadable_apache_mirrors; }
pkarmstr/NYBC
solr-4.2.1/dev-tools/scripts/poll-mirrors.pl
Perl
apache-2.0
4,297
package DDG::Goodie::IsAwesome::mjgardner; # ABSTRACT: mjgardner's first Goodie use DDG::Goodie; use strict; zci answer_type => "is_awesome_mjgardner"; zci is_cached => 1; triggers start => "duckduckhack mjgardner"; handle remainder => sub { return if $_; return "mjgardner is awesome and has successfully completed the DuckDuckHack Goodie tutorial!"; }; 1;
roxxup/zeroclickinfo-goodies
lib/DDG/Goodie/IsAwesome/mjgardner.pm
Perl
apache-2.0
373
package DDG::Goodie::IsAwesome::Black616Angel; # ABSTRACT: Black616Angels first Goodie use DDG::Goodie; use strict; zci answer_type => "is_awesome_black616angel"; zci is_cached => 1; triggers start => "duckduckhack black616angel"; handle remainder => sub { return if $_; return "Black616Angel is awesome and has successfully completed the DuckDuckHack Goodie tutorial!"; }; 1;
aleksandar-todorovic/zeroclickinfo-goodies
lib/DDG/Goodie/IsAwesome/Black616Angel.pm
Perl
apache-2.0
392
#----------------------------------------------------------- # shellbags_xp.pl # RR plugin to parse (Vista, Win7/Win2008R2) shell bags # # History: # 20130515 - created from shellbags.pl; many differences between XP and Win7 # 20130102 - updated to include type 0x35 # 20120824 - updated parseFolderEntry() for XP (extver == 3) # 20120810 - added support for parsing Network types; added handling of # offsets for Folder types (ie, transition to long name offset), # based on OS version (Vista, Win7); tested against one Win2008R2 # system (successfully); added parsing of URI types. # 20120809 - added parsing of file szie values for type 0x32 items # 20120808 - Updated # 20120720 - created # # References # Andrew's Python code for Registry Decoder # http://code.google.com/p/registrydecoder/source/browse/trunk/templates/template_files/ShellBagMRU.py # Joachim Metz's shell item format specification # http://download.polytechnic.edu.na/pub4/download.sourceforge.net/pub/ # sourceforge/l/project/li/liblnk/Documentation/Windows%20Shell%20Item%20format/ # Windows%20Shell%20Item%20format.pdf # Converting DOS Date format # http://msdn.microsoft.com/en-us/library/windows/desktop/ms724274(v=VS.85).aspx # # Thanks to Willi Ballenthin and Joachim Metz for the documentation they # provided, Andrew Case for posting the Registry Decoder code, and Kevin # Moore for writing the shell bag parser for Registry Decoder, as well as # assistance with some parsing. # # License: GPL v3 # copyright 2012 Quantum Analytics Research, LLC # Author: H. Carvey, keydet89@yahoo.com #----------------------------------------------------------- package shellbags_xp; use strict; use Time::Local; my %config = (hive => "NTUSER\.DAT", hivemask => 32, output => "report", category => "User Activity", osmask => 20, #Vista, Win7/Win2008R2 hasShortDescr => 1, hasDescr => 0, hasRefs => 0, version => 20130102); sub getConfig{return %config} sub getShortDescr { return "Shell/BagMRU traversal in XP NTUSER.DAT hives"; } sub getDescr{} sub getRefs {} sub getHive {return $config{hive};} sub getVersion {return $config{version};} my $VERSION = getVersion(); my %cp_guids = ("{bb64f8a7-bee7-4e1a-ab8d-7d8273f7fdb6}" => "Action Center", "{7a979262-40ce-46ff-aeee-7884ac3b6136}" => "Add Hardware", "{d20ea4e1-3957-11d2-a40b-0c5020524153}" => "Administrative Tools", "{9c60de1e-e5fc-40f4-a487-460851a8d915}" => "AutoPlay", "{b98a2bea-7d42-4558-8bd1-832f41bac6fd}" => "Backup and Restore Center", "{0142e4d0-fb7a-11dc-ba4a-000ffe7ab428}" => "Biometric Devices", "{d9ef8727-cac2-4e60-809e-86f80a666c91}" => "BitLocker Drive Encryption", "{b2c761c6-29bc-4f19-9251-e6195265baf1}" => "Color Management", "{1206f5f1-0569-412c-8fec-3204630dfb70}" => "Credential Manager", "{e2e7934b-dce5-43c4-9576-7fe4f75e7480}" => "Date and Time", "{00c6d95f-329c-409a-81d7-c46c66ea7f33}" => "Default Location", "{17cd9488-1228-4b2f-88ce-4298e93e0966}" => "Default Programs", "{37efd44d-ef8d-41b1-940d-96973a50e9e0}" => "Desktop Gadgets", "{74246bfc-4c96-11d0-abef-0020af6b0b7a}" => "Device Manager", "{a8a91a66-3a7d-4424-8d24-04e180695c7a}" => "Devices and Printers", "{c555438b-3c23-4769-a71f-b6d3d9b6053a}" => "Display", "{d555645e-d4f8-4c29-a827-d93c859c4f2a}" => "Ease of Access Center", "{6dfd7c5c-2451-11d3-a299-00c04f8ef6af}" => "Folder Options", "{93412589-74d4-4e4e-ad0e-e0cb621440fd}" => "Fonts", "{259ef4b1-e6c9-4176-b574-481532c9bce8}" => "Game Controllers", "{15eae92e-f17a-4431-9f28-805e482dafd4}" => "Get Programs", "{cb1b7f8c-c50a-4176-b604-9e24dee8d4d1}" => "Getting Started", "{67ca7650-96e6-4fdd-bb43-a8e774f73a57}" => "HomeGroup", "{87d66a43-7b11-4a28-9811-c86ee395acf7}" => "Indexing Options", "{a0275511-0e86-4eca-97c2-ecd8f1221d08}" => "Infrared", "{a3dd4f92-658a-410f-84fd-6fbbbef2fffe}" => "Internet Options", "{a304259d-52b8-4526-8b1a-a1d6cecc8243}" => "iSCSI Initiator", "{725be8f7-668e-4c7b-8f90-46bdb0936430}" => "Keyboard", "{e9950154-c418-419e-a90a-20c5287ae24b}" => "Location and Other Sensors", "{1fa9085f-25a2-489b-85d4-86326eedcd87}" => "Manage Wireless Networks", "{6c8eec18-8d75-41b2-a177-8831d59d2d50}" => "Mouse", "{7007acc7-3202-11d1-aad2-00805fc1270e}" => "Network Connections", "{8e908fc9-becc-40f6-915b-f4ca0e70d03d}" => "Network and Sharing Center", "{05d7b0f4-2121-4eff-bf6b-ed3f69b894d9}" => "Notification Area Icons", "{d24f75aa-4f2b-4d07-a3c4-469b3d9030c4}" => "Offline Files", "{96ae8d84-a250-4520-95a5-a47a7e3c548b}" => "Parental Controls", "{f82df8f7-8b9f-442e-a48c-818ea735ff9b}" => "Pen and Input Devices", "{5224f545-a443-4859-ba23-7b5a95bdc8ef}" => "People Near Me", "{78f3955e-3b90-4184-bd14-5397c15f1efc}" => "Performance Information and Tools", "{ed834ed6-4b5a-4bfe-8f11-a626dcb6a921}" => "Personalization", "{40419485-c444-4567-851a-2dd7bfa1684d}" => "Phone and Modem", "{025a5937-a6be-4686-a844-36fe4bec8b6d}" => "Power Options", "{2227a280-3aea-1069-a2de-08002b30309d}" => "Printers", "{fcfeecae-ee1b-4849-ae50-685dcf7717ec}" => "Problem Reports and Solutions", "{7b81be6a-ce2b-4676-a29e-eb907a5126c5}" => "Programs and Features", "{9fe63afd-59cf-4419-9775-abcc3849f861}" => "Recovery", "{62d8ed13-c9d0-4ce8-a914-47dd628fb1b0}" => "Regional and Language Options", "{241d7c96-f8bf-4f85-b01f-e2b043341a4b}" => "RemoteApp and Desktop Connections", "{00f2886f-cd64-4fc9-8ec5-30ef6cdbe8c3}" => "Scanners and Cameras", "{e211b736-43fd-11d1-9efb-0000f8757fcd}" => "Scanners and Cameras", "{d6277990-4c6a-11cf-8d87-00aa0060f5bf}" => "Scheduled Tasks", "{f2ddfc82-8f12-4cdd-b7dc-d4fe1425aa4d}" => "Sound", "{58e3c745-d971-4081-9034-86e34b30836a}" => "Speech Recognition Options", "{9c73f5e5-7ae7-4e32-a8e8-8d23b85255bf}" => "Sync Center", "{bb06c0e4-d293-4f75-8a90-cb05b6477eee}" => "System", "{80f3f1d5-feca-45f3-bc32-752c152e456e}" => "Tablet PC Settings", "{0df44eaa-ff21-4412-828e-260a8728e7f1}" => "Taskbar and Start Menu", "{d17d1d6d-cc3f-4815-8fe3-607e7d5d10b3}" => "Text to Speech", "{c58c4893-3be0-4b45-abb5-a63e4b8c8651}" => "Troubleshooting", "{60632754-c523-4b62-b45c-4172da012619}" => "User Accounts", "{be122a0e-4503-11da-8bde-f66bad1e3f3a}" => "Windows Anytime Upgrade", "{78cb147a-98ea-4aa6-b0df-c8681f69341c}" => "Windows CardSpace", "{d8559eb9-20c0-410e-beda-7ed416aecc2a}" => "Windows Defender", "{4026492f-2f69-46b8-b9bf-5654fc07e423}" => "Windows Firewall", "{3e7efb4c-faf1-453d-89eb-56026875ef90}" => "Windows Marketplace", "{5ea4f148-308c-46d7-98a9-49041b1dd468}" => "Windows Mobility Center", "{087da31b-0dd3-4537-8e23-64a18591f88b}" => "Windows Security Center", "{e95a4861-d57a-4be1-ad0f-35267e261739}" => "Windows SideShow", "{36eef7db-88ad-4e81-ad49-0e313f0c35f8}" => "Windows Update"); my %folder_types = ("{724ef170-a42d-4fef-9f26-b60e846fba4f}" => "Administrative Tools", "{d0384e7d-bac3-4797-8f14-cba229b392b5}" => "Common Administrative Tools", "{de974d24-d9c6-4d3e-bf91-f4455120b917}" => "Common Files", "{c1bae2d0-10df-4334-bedd-7aa20b227a9d}" => "Common OEM Links", "{5399e694-6ce5-4d6c-8fce-1d8870fdcba0}" => "Control Panel", "{21ec2020-3aea-1069-a2dd-08002b30309d}" => "Control Panel", "{1ac14e77-02e7-4e5d-b744-2eb1ae5198b7}" => "CSIDL_SYSTEM", "{b4bfcc3a-db2c-424c-b029-7fe99a87c641}" => "Desktop", "{7b0db17d-9cd2-4a93-9733-46cc89022e7c}" => "Documents Library", "{fdd39ad0-238f-46af-adb4-6c85480369c7}" => "Documents", "{374de290-123f-4565-9164-39c4925e467b}" => "Downloads", "{de61d971-5ebc-4f02-a3a9-6c82895e5c04}" => "Get Programs", "{a305ce99-f527-492b-8b1a-7e76fa98d6e4}" => "Installed Updates", "{871c5380-42a0-1069-a2ea-08002b30309d}" => "Internet Explorer (Homepage)", "{031e4825-7b94-4dc3-b131-e946b44c8dd5}" => "Libraries", "{49bf5420-fa7f-11cf-8011-00a0c90a8f78}" => "Mobile Device", #MS KB836152 "{4bd8d571-6d19-48d3-be97-422220080e43}" => "Music", "{20d04fe0-3aea-1069-a2d8-08002b30309d}" => "My Computer", "{450d8fba-ad25-11d0-98a8-0800361b1103}" => "My Documents", "{fc9fb64a-1eb2-4ccf-af5e-1a497a9b5c2d}" => "My Shared Folders", # "{5e591a74-df96-48d3-8d67-1733bcee28ba}" => "My Documents", "{ed228fdf-9ea8-4870-83b1-96b02cfe0d52}" => "My Games", "{208d2c60-3aea-1069-a2d7-08002b30309d}" => "My Network Places", "{f02c1a0d-be21-4350-88b0-7367fc96ef3c}" => "Network", "{33e28130-4e1e-4676-835a-98395c3bc3bb}" => "Pictures", "{a990ae9f-a03b-4e80-94bc-9912d7504104}" => "Pictures", "{7c5a40ef-a0fb-4bfc-874a-c0f2e0b9fa8e}" => "Program Files (x86)", "{905e63b6-c1bf-494e-b29c-65b732d3d21a}" => "Program Files", "{df7266ac-9274-4867-8d55-3bd661de872d}" => "Programs and Features", "{3214fab5-9757-4298-bb61-92a9deaa44ff}" => "Public Music", "{b6ebfb86-6907-413c-9af7-4fc2abf07cc5}" => "Public Pictures", "{2400183a-6185-49fb-a2d8-4a392a602ba3}" => "Public Videos", "{4336a54d-38b-4685-ab02-99bb52d3fb8b}" => "Public", "{491e922f-5643-4af4-a7eb-4e7a138d8174}" => "Public", "{dfdf76a2-c82a-4d63-906a-5644ac457385}" => "Public", "{645ff040-5081-101b-9f08-00aa002f954e}" => "Recycle Bin", "{d65231b0-b2f1-4857-a4ce-a8e7c6ea7d27}" => "System32 (x86)", "{9e52ab10-f80d-49df-acb8-4330f5687855}" => "Temporary Burn Folder", "{f3ce0f7c-4901-4acc-8648-d5d44b04ef8f}" => "Users Files", "{59031a47-3f72-44a7-89c5-5595fe6b30ee}" => "User Files", "{59031a47-3f72-44a7-89c5-5595fe6b30ee}" => "Users", "{f38bf404-1d43-42f2-9305-67de0b28fc23}" => "Windows"); sub pluginmain { my $class = shift; my $hive = shift; ::logMsg("Launching shellbags_xp v.".$VERSION); ::rptMsg("shellbags_xp v.".$VERSION); # banner ::rptMsg("(".getHive().") ".getShortDescr()."\n"); # banner my %item = (); my $reg = Parse::Win32Registry->new($hive); my $root_key = $reg->get_root_key; my $key_path = "Software\\Microsoft\\Windows\\ShellNoRoam\\BagMRU"; my $key; if ($key = $root_key->get_subkey($key_path)) { $item{path} = "Desktop\\"; $item{name} = ""; # Print header info ::rptMsg(sprintf "%-20s |%-20s | %-20s | %-20s | %-20s |Resource","MRU Time","Modified","Accessed","Created","Zip_Subfolder"); ::rptMsg(sprintf "%-20s |%-20s | %-20s | %-20s | %-20s |"."-" x 12,"-" x 12,"-" x 12,"-" x 12,"-" x 12,"-" x 12); traverse($key,\%item); } else { ::rptMsg($key_path." not found."); } } sub traverse { my $key = shift; my $parent = shift; my %item = (); my @vals = $key->get_list_of_values(); my %values; foreach my $v (@vals) { my $name = $v->get_name(); $values{$name} = $v->get_data(); } delete $values{NodeSlot}; my $mru; if (exists $values{MRUListEx}) { $mru = unpack("V",substr($values{MRUListEx},0,4)); } delete $values{MRUListEx}; foreach my $v (sort {$a <=> $b} keys %values) { next unless ($v =~ m/^\d/); my $type = unpack("C",substr($values{$v},2,1)); # Need to first check to see if the parent of the item was a zip folder # and if the 'zipsubfolder' value is set to 1 if (exists ${$parent}{zipsubfolder} && ${$parent}{zipsubfolder} == 1) { # These data items are different on Win7; need to reparse for XP # my @d = printData($values{$v}); # ::rptMsg(""); # foreach (0..(scalar(@d) - 1)) { # ::rptMsg($d[$_]); # } # ::rptMsg(""); # %item = parseZipSubFolderItem($values{$v}); # $item{zipsubfolder} = 1; } elsif ($type == 0x00) { # Variable/Property Sheet %item = parseVariableEntry($values{$v}); } elsif ($type == 0x01) { # %item = parse01ShellItem($values{$v}); } elsif ($type == 0x1F) { # System Folder %item = parseSystemFolderEntry($values{$v}); } elsif ($type == 0x2e) { # Device %item = parseDeviceEntry($values{$v}); my @d = printData($values{$v}); ::rptMsg(""); foreach (0..(scalar(@d) - 1)) { ::rptMsg($d[$_]); } ::rptMsg(""); } elsif ($type == 0x2F) { # Volume (Drive Letter) %item = parseDriveEntry($values{$v}); } elsif ($type == 0xc3 || $type == 0x41 || $type == 0x42 || $type == 0x46 || $type == 0x47) { # Network stuff my $id = unpack("C",substr($values{$v},3,1)); if ($type == 0xc3 && $id != 0x01) { %item = parseNetworkEntry($values{$v}); } else { %item = parseNetworkEntry($values{$v}); } } elsif ($type == 0x31 || $type == 0x32 || $type == 0xb1 || $type == 0x74) { # Folder or Zip File %item = parseFolderEntry($values{$v}); } elsif ($type == 0x35) { %item = parseFolderEntry2($values{$v}); } elsif ($type == 0x71) { # Control Panel %item = parseControlPanelEntry($values{$v}); } elsif ($type == 0x61) { # URI type %item = parseURIEntry($values{$v}); } elsif ($type == 0xd7 || $type == 0x9 || $type == 0xe3 || $type == 0x45) { %item = parseXPShellDeviceItem($values{$v}); } else { # Unknown type $item{name} = sprintf "Unknown Type (0x%x)",$type; my @d = printData($values{$v}); ::rptMsg(""); foreach (0..(scalar(@d) - 1)) { ::rptMsg($d[$_]); } ::rptMsg(""); } if ($item{name} =~ m/\.zip$/ && $type == 0x32) { $item{zipsubfolder} = 1; } # for debug purposes # $item{name} = $item{name}."[".$v."]"; # ::rptMsg(${$parent}{path}.$item{name}); if ($mru != 4294967295 && ($v == $mru)) { $item{mrutime} = $key->get_timestamp(); $item{mrutime_str} = $key->get_timestamp_as_string(); $item{mrutime_str} =~ s/T/ /; $item{mrutime_str} =~ s/Z/ /; } my ($m,$a,$c,$o); (exists $item{mtime_str} && $item{mtime_str} ne "0") ? ($m = $item{mtime_str}) : ($m = ""); (exists $item{atime_str} && $item{atime_str} ne "0") ? ($a = $item{atime_str}) : ($a = ""); (exists $item{ctime_str} && $item{ctime_str} ne "0") ? ($c = $item{ctime_str}) : ($c = ""); (exists $item{datetime} && $item{datetime} ne "N/A") ? ($o = $item{datetime}) : ($o = ""); my $resource = ${$parent}{path}.$item{name}; if (exists $item{filesize}) { $resource .= " [".$item{filesize}."]"; } if (exists $item{timestamp} && $item{timestamp} > 0) { $resource .= " [".gmtime($item{timestamp})." Z]"; } my $str = sprintf "%-20s |%-20s | %-20s | %-20s | %-20s |".$resource,$item{mrutime_str},$m,$a,$c,$o; ::rptMsg($str); if ($item{name} eq "" || $item{name} =~ m/\\$/) { } else { $item{name} = $item{name}."\\"; } $item{path} = ${$parent}{path}.$item{name}; traverse($key->get_subkey($v),\%item); } } #------------------------------------------------------------------------------- ## Functions #------------------------------------------------------------------------------- #----------------------------------------------------------- # parseVariableEntry() # #----------------------------------------------------------- sub parseVariableEntry { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1)); my $tag = unpack("C",substr($data,0x0A,1)); if (unpack("v",substr($data,4,2)) == 0x1A) { my $guid = parseGUID(substr($data,14,16)); if (exists $folder_types{$guid}) { $item{name} = $folder_types{$guid}; } else { $item{name} = $guid; } } elsif (grep(/1SPS/,$data)) { my @seg = split(/1SPS/,$data); my %segs = (); foreach my $s (0..(scalar(@seg) - 1)) { my $guid = parseGUID(substr($seg[$s],0,16)); $segs{$guid} = $seg[$s]; } if (exists $segs{"{b725f130-47ef-101a-a5f1-02608c9eebac}"}) { # Ref: http://msdn.microsoft.com/en-us/library/aa965725(v=vs.85).aspx my $stuff = $segs{"{b725f130-47ef-101a-a5f1-02608c9eebac}"}; my $tag = 1; my $cnt = 0x10; while($tag) { my $sz = unpack("V",substr($stuff,$cnt,4)); my $id = unpack("V",substr($stuff,$cnt + 4,4)); #-------------------------------------------------------------- # sub-segment types # 0x0a - file name # 0x14 - short name # 0x0e, 0x0f, 0x10 - mod date, create date, access date(?) # 0x0c - size #-------------------------------------------------------------- return %item unless (defined $sz); if ($sz == 0x00) { $tag = 0; next; } elsif ($id == 0x0a) { my $num = unpack("V",substr($stuff,$cnt + 13,4)); my $str = substr($stuff,$cnt + 13 + 4,($num * 2)); $str =~ s/\x00//g; $item{name} = $str; } $cnt += $sz; } } # if (exists $segs{"{5cbf2787-48cf-4208-b90e-ee5e5d420294}"}) { # my $stuff = $segs{"{5cbf2787-48cf-4208-b90e-ee5e5d420294}"}; # my $tag = 1; # my $cnt = 0x10; # while($tag) { # my $sz = unpack("V",substr($stuff,$cnt,4)); # my $id = unpack("V",substr($stuff,$cnt + 4,4)); # return %item unless (defined $sz); # if ($sz == 0x00) { # $tag = 0; # next; # } # elsif ($id == 0x19) { # # my $num = unpack("V",substr($stuff,$cnt + 13,4)); # my $str = substr($stuff,$cnt + 13 + 4,($num * 2)); # $str =~ s/\x00//g; # $item{name} = $str; # } # $cnt += $sz; # } # } } elsif (substr($data,4,4) eq "AugM") { %item = parseFolderEntry($data); } # Following two entries are for Device Property data elsif ($tag == 0x7b || $tag == 0xbb || $tag == 0xfb) { my ($sz1,$sz2,$sz3) = unpack("VVV",substr($data,0x3e,12)); $item{name} = substr($data,0x4a,$sz1 * 2); $item{name} =~ s/\x00//g; } elsif ($tag == 0x02 || $tag == 0x03) { my ($sz1,$sz2,$sz3,$sz4) = unpack("VVVV",substr($data,0x26,16)); $item{name} = substr($data,0x36,$sz1 * 2); $item{name} =~ s/\x00//g; } else { $item{name} = "Unknown Type"; } return %item; } #----------------------------------------------------------- # parseNetworkEntry() # #----------------------------------------------------------- sub parseNetworkEntry { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1)); my @n = split(/\x00/,substr($data,4,length($data) - 4)); $item{name} = $n[0]; return %item; } #----------------------------------------------------------- # parseZipSubFolderItem() # parses what appears to be Zip file subfolders; this type # appears to contain the date and time of when the subfolder # was accessed/opened, in string format. #----------------------------------------------------------- sub parseZipSubFolderItem { my $data = shift; my %item = (); # Get the opened/accessed date/time $item{datetime} = substr($data,0x24,6); $item{datetime} =~ s/\x00//g; if ($item{datetime} eq "N/A") { } else { $item{datetime} = substr($data,0x24,40); $item{datetime} =~ s/\x00//g; my ($date,$time) = split(/\s+/,$item{datetime},2); my ($mon,$day,$yr) = split(/\//,$date,3); my ($hr,$min,$sec) = split(/:/,$time,3); my $gmtime = timegm($sec,$min,$hr,$day,($mon - 1),$yr); $item{datetime} = "$yr-$mon-$day $hr:$min:$sec"; # ::rptMsg("[Access_Time]: ".gmtime($gmtime)); } my $sz = unpack("V",substr($data,0x54,4)); my $sz2 = unpack("V",substr($data,0x58,4)); my $str1 = substr($data,0x5C,$sz *2) if ($sz > 0); $str1 =~ s/\x00//g; my $str2 = substr($data,0x5C + ($sz * 2),$sz2 *2) if ($sz2 > 0); $str2 =~ s/\x00//g; if ($sz2 > 0) { $item{name} = $str1."\\".$str2; } else { $item{name} = $str1; } return %item; } #----------------------------------------------------------- # parse01ShellItem() # I honestly have no idea what to do with this data; there's really # no reference for or description of the format of this data. For # now, this is just a place holder #----------------------------------------------------------- sub parse01ShellItem { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1));; $item{name} = ""; # ($item{val0},$item{val1}) = unpack("VV",substr($data,2,length($data) - 2)); return %item; } #----------------------------------------------------------- # parseXPShellDeviceItem() # #----------------------------------------------------------- sub parseXPShellDeviceItem { my $data = shift; my %item = (); my ($t0,$t1) = unpack("VV",substr($data,0x04,8)); $item{timestamp} = ::getTime($t0,$t1); # starting at offset 0x18, read the null-term. string as the name value my $str = substr($data,0x18,length($data) - 0x18); $item{name} = (split(/\x00/,$str))[0]; return %item; } #----------------------------------------------------------- # #----------------------------------------------------------- sub parseURIEntry { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1)); my ($lo,$hi) = unpack("VV",substr($data,0x0e,8)); $item{uritime} = ::getTime($lo,$hi); my $sz = unpack("V",substr($data,0x2a,4)); my $uri = substr($data,0x2e,$sz); $uri =~ s/\x00//g; my $proto = substr($data,length($data) - 6, 6); $proto =~ s/\x00//g; $item{name} = $proto."://".$uri." [".gmtime($item{uritime})."]"; return %item; } #----------------------------------------------------------- # #----------------------------------------------------------- sub parseSystemFolderEntry { my $data = shift; my %item = (); my %vals = (0x00 => "Explorer", 0x42 => "Libraries", 0x44 => "Users", 0x4c => "Public", 0x48 => "My Documents", 0x50 => "My Computer", 0x58 => "My Network Places", 0x60 => "Recycle Bin", 0x68 => "Explorer", 0x70 => "Control Panel", 0x78 => "Recycle Bin", 0x80 => "My Games"); $item{type} = unpack("C",substr($data,2,1)); $item{id} = unpack("C",substr($data,3,1)); if (exists $vals{$item{id}}) { $item{name} = $vals{$item{id}}; } else { $item{name} = parseGUID(substr($data,4,16)); } return %item; } #----------------------------------------------------------- # parseGUID() # Takes 16 bytes of binary data, returns a string formatted # as an MS GUID. #----------------------------------------------------------- sub parseGUID { my $data = shift; my $d1 = unpack("V",substr($data,0,4)); my $d2 = unpack("v",substr($data,4,2)); my $d3 = unpack("v",substr($data,6,2)); my $d4 = unpack("H*",substr($data,8,2)); my $d5 = unpack("H*",substr($data,10,6)); my $guid = sprintf "{%08x-%x-%x-$d4-$d5}",$d1,$d2,$d3; if (exists $cp_guids{$guid}) { return $cp_guids{$guid}; } elsif (exists $folder_types{$guid}) { return $folder_types{$guid}; } else { return $guid; } } #----------------------------------------------------------- # #----------------------------------------------------------- sub parseDeviceEntry { my $data = shift; my %item = (); # my $userlen = unpack("V",substr($data,30,4)); # my $devlen = unpack("V",substr($data,34,4)); # # my $user = substr($data,0x28,$userlen * 2); # $user =~ s/\x00//g; # # my $dev = substr($data,0x28 + ($userlen * 2),$devlen * 2); # $dev =~ s/\x00//g; # # $item{name} = $user; my $len = unpack("v",substr($data,0,2)); if ($len == 0x14) { $item{name} = parseGUID(substr($data,4,16)); } else { my $len = unpack("v",substr($data,4,2)); my $guid1 = parseGUID(substr($data,$len + 6,16)); my $guid2 = parseGUID(substr($data,$len + 6 + 16,16)); $item{name} = $guid1."\\".$guid2 } return %item; } #----------------------------------------------------------- # #----------------------------------------------------------- sub parseDriveEntry { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1));; $item{name} = substr($data,3,3); return %item; } #----------------------------------------------------------- # #----------------------------------------------------------- sub parseControlPanelEntry { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1)); my $guid = parseGUID(substr($data,14,16)); if (exists $cp_guids{$guid}) { $item{name} = $cp_guids{$guid}; } else { $item{name} = $guid; } return %item; } #----------------------------------------------------------- # #----------------------------------------------------------- sub parseFolderEntry { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1)); # Type 0x74 folders have a slightly different format my $ofs_mdate; my $ofs_shortname; if ($item{type} == 0x74) { $ofs_mdate = 0x12; } elsif (substr($data,4,4) eq "AugM") { $ofs_mdate = 0x1c; } else { $ofs_mdate = 0x08; } # some type 0x32 items will include a file size if ($item{type} == 0x32) { my $size = unpack("V",substr($data,4,4)); if ($size != 0) { $item{filesize} = $size; } } my @m = unpack("vv",substr($data,$ofs_mdate,4)); ($item{mtime_str},$item{mtime}) = convertDOSDate($m[0],$m[1]); # Need to read in short name; nul-term ASCII # $item{shortname} = (split(/\x00/,substr($data,12,length($data) - 12),2))[0]; $ofs_shortname = $ofs_mdate + 6; my $tag = 1; my $cnt = 0; my $str = ""; while($tag) { my $s = substr($data,$ofs_shortname + $cnt,1); return %item unless (defined $s); if ($s =~ m/\x00/ && ((($cnt + 1) % 2) == 0)) { $tag = 0; } else { $str .= $s; $cnt++; } } # $str =~ s/\x00//g; my $shortname = $str; my $ofs = $ofs_shortname + $cnt + 1; # Read progressively, 1 byte at a time, looking for 0xbeef $tag = 1; $cnt = 0; while ($tag) { my $s = substr($data,$ofs + $cnt,2); return %item unless (defined $s); if (unpack("v",$s) == 0xbeef) { $tag = 0; } else { $cnt++; } } $item{extver} = unpack("v",substr($data,$ofs + $cnt - 4,2)); $ofs = $ofs + $cnt + 2; @m = unpack("vv",substr($data,$ofs,4)); ($item{ctime_str},$item{ctime}) = convertDOSDate($m[0],$m[1]); $ofs += 4; @m = unpack("vv",substr($data,$ofs,4)); ($item{atime_str},$item{atime}) = convertDOSDate($m[0],$m[1]); my $jmp; if ($item{extver} == 0x03) { $jmp = 8; } elsif ($item{extver} == 0x07) { $jmp = 26; } elsif ($item{extver} == 0x08) { $jmp = 30; } else {} $ofs += $jmp; $str = substr($data,$ofs,length($data) - 30); my $longname = (split(/\x00\x00/,$str,2))[0]; $longname =~ s/\x00//g; if ($longname ne "") { $item{name} = $longname; } else { $item{name} = $shortname; } return %item; } #----------------------------------------------------------- # convertDOSDate() # subroutine to convert 4 bytes of binary data into a human- # readable format. Returns both a string and a Unix-epoch # time. #----------------------------------------------------------- sub convertDOSDate { my $date = shift; my $time = shift; if ($date == 0x00 || $time == 0x00){ return (0,0); } else { my $sec = ($time & 0x1f) * 2; $sec = "0".$sec if (length($sec) == 1); if ($sec == 60) {$sec = 59}; my $min = ($time & 0x7e0) >> 5; $min = "0".$min if (length($min) == 1); my $hr = ($time & 0xF800) >> 11; $hr = "0".$hr if (length($hr) == 1); my $day = ($date & 0x1f); $day = "0".$day if (length($day) == 1); my $mon = ($date & 0x1e0) >> 5; $mon = "0".$mon if (length($mon) == 1); my $yr = (($date & 0xfe00) >> 9) + 1980; my $gmtime = timegm($sec,$min,$hr,$day,($mon - 1),$yr); return ("$yr-$mon-$day $hr:$min:$sec",$gmtime); # return gmtime(timegm($sec,$min,$hr,$day,($mon - 1),$yr)); } } #----------------------------------------------------------- # parseFolderEntry2() # # Initial code for parsing type 0x35 #----------------------------------------------------------- sub parseFolderEntry2 { my $data = shift; my %item = (); my $ofs = 0; my $tag = 1; while ($tag) { my $s = substr($data,$ofs,2); return %item unless (defined $s); if (unpack("v",$s) == 0xbeef) { $tag = 0; } else { $ofs++; } } $item{extver} = unpack("v",substr($data,$ofs - 4,2)); # Move offset over to end of where the ctime value would be $ofs += 4; my $jmp; if ($item{extver} == 0x03) { $jmp = 8; } elsif ($item{extver} == 0x07) { $jmp = 26; } elsif ($item{extver} == 0x08) { $jmp = 30; } else {} $ofs += $jmp; my $str = substr($data,$ofs,length($data) - 30); ::rptMsg(" --- parseFolderEntry2 --- "); my @d = printData($str); foreach (0..(scalar(@d) - 1)) { ::rptMsg($d[$_]); } ::rptMsg(""); $item{name} = (split(/\x00\x00/,$str,2))[0]; $item{name} =~ s/\x13\x20/\x2D\x00/; $item{name} =~ s/\x00//g; return %item; } #----------------------------------------------------------- # #----------------------------------------------------------- sub parseNetworkEntry { my $data = shift; my %item = (); $item{type} = unpack("C",substr($data,2,1)); my @names = split(/\x00/,substr($data,5,length($data) - 5)); $item{name} = $names[0]; return %item; } #----------------------------------------------------------- # printData() # subroutine used primarily for debugging; takes an arbitrary # length of binary data, prints it out in hex editor-style # format for easy debugging #----------------------------------------------------------- sub printData { my $data = shift; my $len = length($data); my $tag = 1; my @display = (); my $loop = $len/16; $loop++ if ($len%16); foreach my $cnt (0..($loop - 1)) { # while ($tag) { my $left = $len - ($cnt * 16); my $n; ($left < 16) ? ($n = $left) : ($n = 16); my $seg = substr($data,$cnt * 16,$n); my @str1 = split(//,unpack("H*",$seg)); my @s3; my $str = ""; foreach my $i (0..($n - 1)) { $s3[$i] = $str1[$i * 2].$str1[($i * 2) + 1]; if (hex($s3[$i]) > 0x1f && hex($s3[$i]) < 0x7f) { $str .= chr(hex($s3[$i])); } else { $str .= "\."; } } my $h = join(' ',@s3); # ::rptMsg(sprintf "0x%08x: %-47s ".$str,($cnt * 16),$h); $display[$cnt] = sprintf "0x%08x: %-47s ".$str,($cnt * 16),$h; } return @display; } 1;
millmanorama/autopsy
thirdparty/rr-full/plugins/shellbags_xp.pl
Perl
apache-2.0
30,031
package DDG::Goodie::IsAwesome::ashleyglidden; # ABSTRACT: ashleyglidden's first Goodie use DDG::Goodie; use strict; zci answer_type => "is_awesome_ashleyglidden"; zci is_cached => 1; name "IsAwesome ashleyglidden"; description "My first Goodie, it let's the world know that ashleyglidden is awesome"; primary_example_queries "duckduckhack ashleyglidden"; category "special"; topics "special_interest", "geek"; code_url "https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/IsAwesome/ashleyglidden.pm"; attribution github => ["https://github.com/ashleyglidden", "ashleyglidden"], web => ['http://ashleyglidden.com', 'Ashley Glidden'], twitter => "aishleyng"; triggers start => "duckduckhack ashleyglidden"; handle remainder => sub { return if $_; return "ashleyglidden is awesome and has successfully completed the DuckDuckHack Goodie tutorial!"; }; 1;
kavithaRajagopalan/zeroclickinfo-goodies
lib/DDG/Goodie/IsAwesome/ashleyglidden.pm
Perl
apache-2.0
923
use c_rt_lib; use hash; use ptd; use tct; use boolean_t; use nast; use singleton; use compiler_lib; sub tc_types_priv::op_def; sub tc_types::get_bin_op_def; sub tc_types_priv::get_binary_ops; sub tc_types::errors_t; sub tc_types::bin_op_type; sub tc_types::defs_funs_t; sub tc_types::return_t; sub tc_types::modules_t; sub tc_types::deref_type; sub tc_types::deref_types; sub tc_types::env; sub tc_types::var_t; sub tc_types::fun_arg_t; sub tc_types::def_fun_t; sub tc_types::vars_t; sub tc_types::type; sub tc_types::value_src; sub tc_types::lval_path; sub tc_types::walk_arg; sub tc_types::ref_t; sub tc_types::stack_info_type; sub tc_types::check_info; sub tc_types::special_functions; sub tc_types::get_default_type; return 1; sub tc_types_priv::op_def($$$$$) { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;$memory_0 = $_[0];Scalar::Util::weaken($_[0]) if ref($_[0]);$memory_1 = $_[1];$memory_2 = $_[2];$memory_3 = $_[3];$memory_4 = $_[4]; #line 16 $memory_5 = {arg1 => $memory_2,arg2 => $memory_3,ret => $memory_4,}; #line 16 hash::set_value($memory_0, $memory_1, $memory_5); #line 16 undef($memory_5); #line 16 undef($memory_1); #line 16 undef($memory_2); #line 16 undef($memory_3); #line 16 undef($memory_4); #line 16 $_[0] = $memory_0;return; $_[0] = $memory_0;} sub tc_types::get_bin_op_def($) { my $memory_0;my $memory_1;my $memory_2;$memory_0 = $_[0]; #line 20 $memory_2 = tc_types_priv::get_binary_ops(); #line 20 $memory_1 = hash::get_value($memory_2, $memory_0); #line 20 undef($memory_2); #line 20 undef($memory_0); #line 20 return $memory_1; #line 20 undef($memory_1); #line 20 undef($memory_0); #line 20 return; } sub tc_types_priv::__get_binary_ops() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 24 $memory_0 = {}; #line 25 $memory_1 = "*"; #line 25 $memory_2 = tct::sim(); #line 25 $memory_3 = tct::sim(); #line 25 $memory_4 = tct::sim(); #line 25 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 25 undef($memory_4); #line 25 undef($memory_3); #line 25 undef($memory_2); #line 25 undef($memory_1); #line 26 $memory_1 = "/"; #line 26 $memory_2 = tct::sim(); #line 26 $memory_3 = tct::sim(); #line 26 $memory_4 = tct::sim(); #line 26 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 26 undef($memory_4); #line 26 undef($memory_3); #line 26 undef($memory_2); #line 26 undef($memory_1); #line 27 $memory_1 = "%"; #line 27 $memory_2 = tct::sim(); #line 27 $memory_3 = tct::sim(); #line 27 $memory_4 = tct::sim(); #line 27 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 27 undef($memory_4); #line 27 undef($memory_3); #line 27 undef($memory_2); #line 27 undef($memory_1); #line 28 $memory_1 = "+"; #line 28 $memory_2 = tct::sim(); #line 28 $memory_3 = tct::sim(); #line 28 $memory_4 = tct::sim(); #line 28 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 28 undef($memory_4); #line 28 undef($memory_3); #line 28 undef($memory_2); #line 28 undef($memory_1); #line 29 $memory_1 = "-"; #line 29 $memory_2 = tct::sim(); #line 29 $memory_3 = tct::sim(); #line 29 $memory_4 = tct::sim(); #line 29 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 29 undef($memory_4); #line 29 undef($memory_3); #line 29 undef($memory_2); #line 29 undef($memory_1); #line 30 $memory_1 = "."; #line 30 $memory_2 = tct::sim(); #line 30 $memory_3 = tct::sim(); #line 30 $memory_4 = tct::sim(); #line 30 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 30 undef($memory_4); #line 30 undef($memory_3); #line 30 undef($memory_2); #line 30 undef($memory_1); #line 31 $memory_1 = ">="; #line 31 $memory_2 = tct::sim(); #line 31 $memory_3 = tct::sim(); #line 31 $memory_4 = tct::bool(); #line 31 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 31 undef($memory_4); #line 31 undef($memory_3); #line 31 undef($memory_2); #line 31 undef($memory_1); #line 32 $memory_1 = "<="; #line 32 $memory_2 = tct::sim(); #line 32 $memory_3 = tct::sim(); #line 32 $memory_4 = tct::bool(); #line 32 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 32 undef($memory_4); #line 32 undef($memory_3); #line 32 undef($memory_2); #line 32 undef($memory_1); #line 33 $memory_1 = "<"; #line 33 $memory_2 = tct::sim(); #line 33 $memory_3 = tct::sim(); #line 33 $memory_4 = tct::bool(); #line 33 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 33 undef($memory_4); #line 33 undef($memory_3); #line 33 undef($memory_2); #line 33 undef($memory_1); #line 34 $memory_1 = ">"; #line 34 $memory_2 = tct::sim(); #line 34 $memory_3 = tct::sim(); #line 34 $memory_4 = tct::bool(); #line 34 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 34 undef($memory_4); #line 34 undef($memory_3); #line 34 undef($memory_2); #line 34 undef($memory_1); #line 35 $memory_1 = "=="; #line 35 $memory_2 = tct::sim(); #line 35 $memory_3 = tct::sim(); #line 35 $memory_4 = tct::bool(); #line 35 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 35 undef($memory_4); #line 35 undef($memory_3); #line 35 undef($memory_2); #line 35 undef($memory_1); #line 36 $memory_1 = "!="; #line 36 $memory_2 = tct::sim(); #line 36 $memory_3 = tct::sim(); #line 36 $memory_4 = tct::bool(); #line 36 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 36 undef($memory_4); #line 36 undef($memory_3); #line 36 undef($memory_2); #line 36 undef($memory_1); #line 37 $memory_1 = "eq"; #line 37 $memory_2 = tct::sim(); #line 37 $memory_3 = tct::sim(); #line 37 $memory_4 = tct::bool(); #line 37 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 37 undef($memory_4); #line 37 undef($memory_3); #line 37 undef($memory_2); #line 37 undef($memory_1); #line 38 $memory_1 = "ne"; #line 38 $memory_2 = tct::sim(); #line 38 $memory_3 = tct::sim(); #line 38 $memory_4 = tct::bool(); #line 38 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 38 undef($memory_4); #line 38 undef($memory_3); #line 38 undef($memory_2); #line 38 undef($memory_1); #line 39 $memory_1 = "&&"; #line 39 $memory_2 = tct::bool(); #line 39 $memory_3 = tct::bool(); #line 39 $memory_4 = tct::bool(); #line 39 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 39 undef($memory_4); #line 39 undef($memory_3); #line 39 undef($memory_2); #line 39 undef($memory_1); #line 40 $memory_1 = "||"; #line 40 $memory_2 = tct::bool(); #line 40 $memory_3 = tct::bool(); #line 40 $memory_4 = tct::bool(); #line 40 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 40 undef($memory_4); #line 40 undef($memory_3); #line 40 undef($memory_2); #line 40 undef($memory_1); #line 41 $memory_1 = "+="; #line 41 $memory_2 = tct::sim(); #line 41 $memory_3 = tct::sim(); #line 41 $memory_4 = tct::sim(); #line 41 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 41 undef($memory_4); #line 41 undef($memory_3); #line 41 undef($memory_2); #line 41 undef($memory_1); #line 42 $memory_1 = "/="; #line 42 $memory_2 = tct::sim(); #line 42 $memory_3 = tct::sim(); #line 42 $memory_4 = tct::sim(); #line 42 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 42 undef($memory_4); #line 42 undef($memory_3); #line 42 undef($memory_2); #line 42 undef($memory_1); #line 43 $memory_1 = "*="; #line 43 $memory_2 = tct::sim(); #line 43 $memory_3 = tct::sim(); #line 43 $memory_4 = tct::sim(); #line 43 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 43 undef($memory_4); #line 43 undef($memory_3); #line 43 undef($memory_2); #line 43 undef($memory_1); #line 44 $memory_1 = ".="; #line 44 $memory_2 = tct::sim(); #line 44 $memory_3 = tct::sim(); #line 44 $memory_4 = tct::sim(); #line 44 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 44 undef($memory_4); #line 44 undef($memory_3); #line 44 undef($memory_2); #line 44 undef($memory_1); #line 45 $memory_1 = "-="; #line 45 $memory_2 = tct::sim(); #line 45 $memory_3 = tct::sim(); #line 45 $memory_4 = tct::sim(); #line 45 tc_types_priv::op_def($memory_0, $memory_1, $memory_2, $memory_3, $memory_4); #line 45 undef($memory_4); #line 45 undef($memory_3); #line 45 undef($memory_2); #line 45 undef($memory_1); #line 46 $memory_1 = singleton::sigleton_do_not_use_without_approval($memory_0); #line 46 undef($memory_0); #line 46 return $memory_1; #line 46 undef($memory_1); #line 46 undef($memory_0); #line 46 return; } my $_get_binary_ops; sub tc_types_priv::get_binary_ops() { $_get_binary_ops = tc_types_priv::__get_binary_ops() unless defined $_get_binary_ops; return $_get_binary_ops; } sub tc_types::__errors_t() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5; #line 51 $memory_2 = ptd::sim(); #line 52 $memory_3 = ptd::sim(); #line 53 $memory_4 = { module => "compiler_lib", name => "errors_t", }; #line 53 $memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4); #line 54 $memory_5 = { module => "compiler_lib", name => "errors_t", }; #line 54 $memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5); #line 54 $memory_1 = {current_line => $memory_2,module => $memory_3,warnings => $memory_4,errors => $memory_5,}; #line 54 undef($memory_2); #line 54 undef($memory_3); #line 54 undef($memory_4); #line 54 undef($memory_5); #line 54 $memory_0 = ptd::rec($memory_1); #line 54 undef($memory_1); #line 54 return $memory_0; #line 54 undef($memory_0); #line 54 return; } my $_errors_t; sub tc_types::errors_t() { $_errors_t = tc_types::__errors_t() unless defined $_errors_t; return $_errors_t; } sub tc_types::__bin_op_type() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 59 $memory_2 = { module => "tct", name => "meta_type", }; #line 59 $memory_2 = c_rt_lib::ov_mk_arg('ref', $memory_2); #line 59 $memory_3 = { module => "tct", name => "meta_type", }; #line 59 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 59 $memory_4 = { module => "tct", name => "meta_type", }; #line 59 $memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4); #line 59 $memory_1 = {arg1 => $memory_2,arg2 => $memory_3,ret => $memory_4,}; #line 59 undef($memory_2); #line 59 undef($memory_3); #line 59 undef($memory_4); #line 59 $memory_0 = ptd::rec($memory_1); #line 59 undef($memory_1); #line 59 return $memory_0; #line 59 undef($memory_0); #line 59 return; } my $_bin_op_type; sub tc_types::bin_op_type() { $_bin_op_type = tc_types::__bin_op_type() unless defined $_bin_op_type; return $_bin_op_type; } sub tc_types::__defs_funs_t() { my $memory_0;my $memory_1;my $memory_2; #line 63 $memory_2 = { module => "tc_types", name => "def_fun_t", }; #line 63 $memory_2 = c_rt_lib::ov_mk_arg('ref', $memory_2); #line 63 $memory_1 = ptd::hash($memory_2); #line 63 undef($memory_2); #line 63 $memory_0 = ptd::hash($memory_1); #line 63 undef($memory_1); #line 63 return $memory_0; #line 63 undef($memory_0); #line 63 return; } my $_defs_funs_t; sub tc_types::defs_funs_t() { $_defs_funs_t = tc_types::__defs_funs_t() unless defined $_defs_funs_t; return $_defs_funs_t; } sub tc_types::__return_t() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 68 $memory_2 = { module => "compiler_lib", name => "errors_t", }; #line 68 $memory_2 = c_rt_lib::ov_mk_arg('ref', $memory_2); #line 69 $memory_3 = { module => "compiler_lib", name => "errors_t", }; #line 69 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 70 $memory_4 = { module => "tc_types", name => "deref_types", }; #line 70 $memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4); #line 70 $memory_1 = {errors => $memory_2,warnings => $memory_3,deref => $memory_4,}; #line 70 undef($memory_2); #line 70 undef($memory_3); #line 70 undef($memory_4); #line 70 $memory_0 = ptd::rec($memory_1); #line 70 undef($memory_1); #line 70 return $memory_0; #line 70 undef($memory_0); #line 70 return; } my $_return_t; sub tc_types::return_t() { $_return_t = tc_types::__return_t() unless defined $_return_t; return $_return_t; } sub tc_types::__modules_t() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 75 $memory_3 = { module => "boolean_t", name => "type", }; #line 75 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 75 $memory_2 = ptd::hash($memory_3); #line 75 undef($memory_3); #line 75 $memory_3 = { module => "tc_types", name => "env", }; #line 75 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 75 $memory_4 = { module => "tc_types", name => "defs_funs_t", }; #line 75 $memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4); #line 75 $memory_1 = {imports => $memory_2,env => $memory_3,funs => $memory_4,}; #line 75 undef($memory_2); #line 75 undef($memory_3); #line 75 undef($memory_4); #line 75 $memory_0 = ptd::rec($memory_1); #line 75 undef($memory_1); #line 75 return $memory_0; #line 75 undef($memory_0); #line 75 return; } my $_modules_t; sub tc_types::modules_t() { $_modules_t = tc_types::__modules_t() unless defined $_modules_t; return $_modules_t; } sub tc_types::__deref_type() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 79 $memory_2 = ptd::sim(); #line 79 $memory_3 = ptd::sim(); #line 79 $memory_4 = ptd::sim(); #line 79 $memory_1 = {line => $memory_2,module => $memory_3,type_name => $memory_4,}; #line 79 undef($memory_2); #line 79 undef($memory_3); #line 79 undef($memory_4); #line 79 $memory_0 = ptd::rec($memory_1); #line 79 undef($memory_1); #line 79 return $memory_0; #line 79 undef($memory_0); #line 79 return; } my $_deref_type; sub tc_types::deref_type() { $_deref_type = tc_types::__deref_type() unless defined $_deref_type; return $_deref_type; } sub tc_types::__deref_types() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 83 $memory_3 = { module => "tc_types", name => "deref_type", }; #line 83 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 83 $memory_2 = ptd::arr($memory_3); #line 83 undef($memory_3); #line 83 $memory_4 = { module => "tc_types", name => "deref_type", }; #line 83 $memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4); #line 83 $memory_3 = ptd::arr($memory_4); #line 83 undef($memory_4); #line 83 $memory_1 = {delete => $memory_2,create => $memory_3,}; #line 83 undef($memory_2); #line 83 undef($memory_3); #line 83 $memory_0 = ptd::rec($memory_1); #line 83 undef($memory_1); #line 83 return $memory_0; #line 83 undef($memory_0); #line 83 return; } my $_deref_types; sub tc_types::deref_types() { $_deref_types = tc_types::__deref_types() unless defined $_deref_types; return $_deref_types; } sub tc_types::__env() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6; #line 88 $memory_2 = ptd::sim(); #line 89 $memory_5 = { module => "tc_types", name => "vars_t", }; #line 89 $memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5); #line 89 $memory_6 = { module => "boolean_t", name => "type", }; #line 89 $memory_6 = c_rt_lib::ov_mk_arg('ref', $memory_6); #line 89 $memory_4 = {vars => $memory_5,is => $memory_6,}; #line 89 undef($memory_5); #line 89 undef($memory_6); #line 89 $memory_3 = ptd::rec($memory_4); #line 89 undef($memory_4); #line 90 $memory_4 = { module => "tct", name => "meta_type", }; #line 90 $memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4); #line 91 $memory_5 = { module => "tc_types", name => "deref_types", }; #line 91 $memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5); #line 91 $memory_1 = {current_module => $memory_2,breaks => $memory_3,ret_type => $memory_4,deref => $memory_5,}; #line 91 undef($memory_2); #line 91 undef($memory_3); #line 91 undef($memory_4); #line 91 undef($memory_5); #line 91 $memory_0 = ptd::rec($memory_1); #line 91 undef($memory_1); #line 91 return $memory_0; #line 91 undef($memory_0); #line 91 return; } my $_env; sub tc_types::env() { $_env = tc_types::__env() unless defined $_env; return $_env; } sub tc_types::__var_t() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5; #line 96 $memory_4 = ptd::none(); #line 96 $memory_5 = ptd::none(); #line 96 $memory_3 = {yes => $memory_4,no => $memory_5,}; #line 96 undef($memory_4); #line 96 undef($memory_5); #line 96 $memory_2 = ptd::var($memory_3); #line 96 undef($memory_3); #line 96 $memory_3 = { module => "tct", name => "meta_type", }; #line 96 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 96 $memory_1 = {overwrited => $memory_2,type => $memory_3,}; #line 96 undef($memory_2); #line 96 undef($memory_3); #line 96 $memory_0 = ptd::rec($memory_1); #line 96 undef($memory_1); #line 96 return $memory_0; #line 96 undef($memory_0); #line 96 return; } my $_var_t; sub tc_types::var_t() { $_var_t = tc_types::__var_t() unless defined $_var_t; return $_var_t; } sub tc_types::__fun_arg_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; #line 101 $memory_2 = ptd::sim(); #line 102 $memory_3 = { module => "tct", name => "meta_type", }; #line 102 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 103 $memory_6 = ptd::none(); #line 103 $memory_7 = ptd::none(); #line 103 $memory_5 = {none => $memory_6,ref => $memory_7,}; #line 103 undef($memory_6); #line 103 undef($memory_7); #line 103 $memory_4 = ptd::var($memory_5); #line 103 undef($memory_5); #line 103 $memory_1 = {name => $memory_2,type => $memory_3,mod => $memory_4,}; #line 103 undef($memory_2); #line 103 undef($memory_3); #line 103 undef($memory_4); #line 103 $memory_0 = ptd::rec($memory_1); #line 103 undef($memory_1); #line 103 return $memory_0; #line 103 undef($memory_0); #line 103 return; } my $_fun_arg_t; sub tc_types::fun_arg_t() { $_fun_arg_t = tc_types::__fun_arg_t() unless defined $_fun_arg_t; return $_fun_arg_t; } sub tc_types::__def_fun_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 109 $memory_2 = { module => "nast", name => "cmd_t", }; #line 109 $memory_2 = c_rt_lib::ov_mk_arg('ref', $memory_2); #line 110 $memory_5 = ptd::none(); #line 110 $memory_6 = { module => "tct", name => "meta_type", }; #line 110 $memory_6 = c_rt_lib::ov_mk_arg('ref', $memory_6); #line 110 $memory_4 = {no => $memory_5,yes => $memory_6,}; #line 110 undef($memory_5); #line 110 undef($memory_6); #line 110 $memory_3 = ptd::var($memory_4); #line 110 undef($memory_4); #line 111 $memory_6 = ptd::none(); #line 111 $memory_8 = ptd::sim(); #line 111 $memory_7 = ptd::arr($memory_8); #line 111 undef($memory_8); #line 111 $memory_5 = {no => $memory_6,yes => $memory_7,}; #line 111 undef($memory_6); #line 111 undef($memory_7); #line 111 $memory_4 = ptd::var($memory_5); #line 111 undef($memory_5); #line 112 $memory_5 = ptd::sim(); #line 113 $memory_6 = ptd::sim(); #line 114 $memory_9 = ptd::none(); #line 114 $memory_10 = ptd::none(); #line 114 $memory_8 = {priv => $memory_9,pub => $memory_10,}; #line 114 undef($memory_9); #line 114 undef($memory_10); #line 114 $memory_7 = ptd::var($memory_8); #line 114 undef($memory_8); #line 115 $memory_9 = { module => "tc_types", name => "fun_arg_t", }; #line 115 $memory_9 = c_rt_lib::ov_mk_arg('ref', $memory_9); #line 115 $memory_8 = ptd::arr($memory_9); #line 115 undef($memory_9); #line 116 $memory_9 = { module => "tct", name => "meta_type", }; #line 116 $memory_9 = c_rt_lib::ov_mk_arg('ref', $memory_9); #line 116 $memory_1 = {cmd => $memory_2,is_type => $memory_3,ref_types => $memory_4,name => $memory_5,module => $memory_6,access => $memory_7,args => $memory_8,ret_type => $memory_9,}; #line 116 undef($memory_2); #line 116 undef($memory_3); #line 116 undef($memory_4); #line 116 undef($memory_5); #line 116 undef($memory_6); #line 116 undef($memory_7); #line 116 undef($memory_8); #line 116 undef($memory_9); #line 116 $memory_0 = ptd::rec($memory_1); #line 116 undef($memory_1); #line 116 return $memory_0; #line 116 undef($memory_0); #line 116 return; } my $_def_fun_t; sub tc_types::def_fun_t() { $_def_fun_t = tc_types::__def_fun_t() unless defined $_def_fun_t; return $_def_fun_t; } sub tc_types::__vars_t() { my $memory_0;my $memory_1; #line 121 $memory_1 = { module => "tc_types", name => "var_t", }; #line 121 $memory_1 = c_rt_lib::ov_mk_arg('ref', $memory_1); #line 121 $memory_0 = ptd::hash($memory_1); #line 121 undef($memory_1); #line 121 return $memory_0; #line 121 undef($memory_0); #line 121 return; } my $_vars_t; sub tc_types::vars_t() { $_vars_t = tc_types::__vars_t() unless defined $_vars_t; return $_vars_t; } sub tc_types::__type() { my $memory_0;my $memory_1;my $memory_2;my $memory_3; #line 125 $memory_2 = { module => "tc_types", name => "value_src", }; #line 125 $memory_2 = c_rt_lib::ov_mk_arg('ref', $memory_2); #line 125 $memory_3 = { module => "tct", name => "meta_type", }; #line 125 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 125 $memory_1 = {src => $memory_2,type => $memory_3,}; #line 125 undef($memory_2); #line 125 undef($memory_3); #line 125 $memory_0 = ptd::rec($memory_1); #line 125 undef($memory_1); #line 125 return $memory_0; #line 125 undef($memory_0); #line 125 return; } my $_type; sub tc_types::type() { $_type = tc_types::__type() unless defined $_type; return $_type; } sub tc_types::__value_src() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 129 $memory_2 = ptd::none(); #line 129 $memory_3 = ptd::none(); #line 129 $memory_4 = ptd::none(); #line 129 $memory_1 = {known => $memory_2,knownhash => $memory_3,speculation => $memory_4,}; #line 129 undef($memory_2); #line 129 undef($memory_3); #line 129 undef($memory_4); #line 129 $memory_0 = ptd::var($memory_1); #line 129 undef($memory_1); #line 129 return $memory_0; #line 129 undef($memory_0); #line 129 return; } my $_value_src; sub tc_types::value_src() { $_value_src = tc_types::__value_src() unless defined $_value_src; return $_value_src; } sub tc_types::__lval_path() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6; #line 133 $memory_3 = ptd::sim(); #line 133 $memory_4 = ptd::none(); #line 133 $memory_5 = ptd::sim(); #line 133 $memory_6 = ptd::none(); #line 133 $memory_2 = {var => $memory_3,arr => $memory_4,rec => $memory_5,hashkey => $memory_6,}; #line 133 undef($memory_3); #line 133 undef($memory_4); #line 133 undef($memory_5); #line 133 undef($memory_6); #line 133 $memory_1 = ptd::var($memory_2); #line 133 undef($memory_2); #line 133 $memory_0 = ptd::arr($memory_1); #line 133 undef($memory_1); #line 133 return $memory_0; #line 133 undef($memory_0); #line 133 return; } my $_lval_path; sub tc_types::lval_path() { $_lval_path = tc_types::__lval_path() unless defined $_lval_path; return $_lval_path; } sub tc_types::__walk_arg() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4; #line 138 $memory_4 = ptd::sim(); #line 138 $memory_3 = ptd::arr($memory_4); #line 138 undef($memory_4); #line 138 $memory_2 = ptd::hash($memory_3); #line 138 undef($memory_3); #line 139 $memory_3 = { module => "tc_types", name => "errors_t", }; #line 139 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 140 $memory_4 = { module => "tc_types", name => "modules_t", }; #line 140 $memory_4 = c_rt_lib::ov_mk_arg('ref', $memory_4); #line 140 $memory_1 = {ref_inf => $memory_2,errors => $memory_3,modules => $memory_4,}; #line 140 undef($memory_2); #line 140 undef($memory_3); #line 140 undef($memory_4); #line 140 $memory_0 = ptd::rec($memory_1); #line 140 undef($memory_1); #line 140 return $memory_0; #line 140 undef($memory_0); #line 140 return; } my $_walk_arg; sub tc_types::walk_arg() { $_walk_arg = tc_types::__walk_arg() unless defined $_walk_arg; return $_walk_arg; } sub tc_types::__ref_t() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5;my $memory_6; #line 146 $memory_2 = ptd::sim(); #line 147 $memory_5 = ptd::sim(); #line 147 $memory_4 = ptd::arr($memory_5); #line 147 undef($memory_5); #line 147 $memory_3 = ptd::hash($memory_4); #line 147 undef($memory_4); #line 148 $memory_6 = ptd::sim(); #line 148 $memory_5 = ptd::arr($memory_6); #line 148 undef($memory_6); #line 148 $memory_4 = ptd::hash($memory_5); #line 148 undef($memory_5); #line 149 $memory_5 = { module => "boolean_t", name => "type", }; #line 149 $memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5); #line 150 $memory_6 = { module => "boolean_t", name => "type", }; #line 150 $memory_6 = c_rt_lib::ov_mk_arg('ref', $memory_6); #line 150 $memory_1 = {level => $memory_2,from => $memory_3,to => $memory_4,check => $memory_5,cast => $memory_6,}; #line 150 undef($memory_2); #line 150 undef($memory_3); #line 150 undef($memory_4); #line 150 undef($memory_5); #line 150 undef($memory_6); #line 150 $memory_0 = ptd::rec($memory_1); #line 150 undef($memory_1); #line 150 return $memory_0; #line 150 undef($memory_0); #line 150 return; } my $_ref_t; sub tc_types::ref_t() { $_ref_t = tc_types::__ref_t() unless defined $_ref_t; return $_ref_t; } sub tc_types::__stack_info_type() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5; #line 155 $memory_2 = ptd::none(); #line 155 $memory_3 = ptd::none(); #line 155 $memory_4 = ptd::sim(); #line 155 $memory_5 = ptd::sim(); #line 155 $memory_1 = {ptd_hash => $memory_2,ptd_arr => $memory_3,ptd_rec => $memory_4,ptd_var => $memory_5,}; #line 155 undef($memory_2); #line 155 undef($memory_3); #line 155 undef($memory_4); #line 155 undef($memory_5); #line 155 $memory_0 = ptd::var($memory_1); #line 155 undef($memory_1); #line 155 return $memory_0; #line 155 undef($memory_0); #line 155 return; } my $_stack_info_type; sub tc_types::stack_info_type() { $_stack_info_type = tc_types::__stack_info_type() unless defined $_stack_info_type; return $_stack_info_type; } sub tc_types::__check_info() { 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; #line 160 $memory_2 = ptd::none(); #line 162 $memory_5 = { module => "tct", name => "meta_type", }; #line 162 $memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5); #line 163 $memory_6 = { module => "tct", name => "meta_type", }; #line 163 $memory_6 = c_rt_lib::ov_mk_arg('ref', $memory_6); #line 164 $memory_8 = { module => "tc_types", name => "stack_info_type", }; #line 164 $memory_8 = c_rt_lib::ov_mk_arg('ref', $memory_8); #line 164 $memory_7 = ptd::arr($memory_8); #line 164 undef($memory_8); #line 164 $memory_4 = {from => $memory_5,to => $memory_6,stack => $memory_7,}; #line 164 undef($memory_5); #line 164 undef($memory_6); #line 164 undef($memory_7); #line 164 $memory_3 = ptd::rec($memory_4); #line 164 undef($memory_4); #line 164 $memory_1 = {ok => $memory_2,err => $memory_3,}; #line 164 undef($memory_2); #line 164 undef($memory_3); #line 164 $memory_0 = ptd::var($memory_1); #line 164 undef($memory_1); #line 164 return $memory_0; #line 164 undef($memory_0); #line 164 return; } my $_check_info; sub tc_types::check_info() { $_check_info = tc_types::__check_info() unless defined $_check_info; return $_check_info; } sub tc_types::__special_functions() { my $memory_0;my $memory_1;my $memory_2;my $memory_3;my $memory_4;my $memory_5; #line 170 $memory_3 = { module => "tct", name => "meta_type", }; #line 170 $memory_3 = c_rt_lib::ov_mk_arg('ref', $memory_3); #line 170 $memory_5 = { module => "tc_types", name => "fun_arg_t", }; #line 170 $memory_5 = c_rt_lib::ov_mk_arg('ref', $memory_5); #line 170 $memory_4 = ptd::arr($memory_5); #line 170 undef($memory_5); #line 170 $memory_2 = {r => $memory_3,a => $memory_4,}; #line 170 undef($memory_3); #line 170 undef($memory_4); #line 170 $memory_1 = ptd::rec($memory_2); #line 170 undef($memory_2); #line 170 $memory_0 = ptd::hash($memory_1); #line 170 undef($memory_1); #line 170 return $memory_0; #line 170 undef($memory_0); #line 170 return; } my $_special_functions; sub tc_types::special_functions() { $_special_functions = tc_types::__special_functions() unless defined $_special_functions; return $_special_functions; } sub tc_types::__get_default_type() { my $memory_0;my $memory_1;my $memory_2; #line 174 $memory_1 = tct::tct_im(); #line 174 $memory_2 = c_rt_lib::ov_mk_none('speculation'); #line 174 $memory_0 = {type => $memory_1,src => $memory_2,}; #line 174 undef($memory_1); #line 174 undef($memory_2); #line 174 return $memory_0; #line 174 undef($memory_0); #line 174 return; } my $_get_default_type; sub tc_types::get_default_type() { $_get_default_type = tc_types::__get_default_type() unless defined $_get_default_type; return $_get_default_type; }
nianiolang/nl
bin/nianio_lang_pm/tc_types.pm
Perl
mit
28,827
/**************************************************** % pronto_morph_spelling_rules.pl % Author: Jason Schlachter (ai@uga.edu)(www.arches.uga.edu/~ai) % Released: May 8th, 2003 % Artificial Intelligence Center (www.ai.uga.edu) % ***see pronto_morph.pdf for documentation % Morphological Analyzer to be used with % ProNTo (Prolog Natural Language Toolkit), % created at the Artificial Intelligence Center % of The University of Georgia ****************************************************/ % ******************************************************* % COMMENT OUT SPELLING RULES THAT YOU DO NOT WANT TO USE! % ******************************************************* % split_suffix(+Characters,-Root,-Suffix) % % Splits a word into root and suffix. % Must line up with the end of the word % (that's the job of find_suffix, which calls it). % Fails if there is no suffix. % Instantiates Category to the syntactic category % to which this suffix attaches. % ******************************************************* split_suffix( X , [] , S ):- suffix( X , S ). % Suffixes with doubled consonants in root split_suffix([z,z,e,s],[z],-s). % "quizzes", "whizzes" split_suffix([s,s,e,s],[s],-s). % "gasses" (verb), "crosses" % TOO VAGUE???? split_suffix([V,C,C,V2|Rest],[V,C],Suffix) :- vowel(V), \+ vowel(C), vowel(V2), suffix([V2|Rest],Suffix). % y changing to i and -s changing to -es simultaneously split_suffix([C,i,e,s],[C,y],-s) :- \+ vowel(C). % y changes to i after consonant, before suffix beg. w vowel split_suffix([C,i,X|Rest],[C,y],Suffix) :- \+ vowel(C), \+ (X = i), suffix([_|Rest],Suffix). % -es = -s after s (etc.) split_suffix([s,h,e,s],[s,h],-s). split_suffix([c,h,e,s],[c,h],-s). split_suffix([s,e,s],[s],-s). split_suffix([z,e,s],[z],-s). split_suffix([x,e,s],[x],-s). % verb spelling rules split_suffix([e,n],[e],-en). % (ex. forgiven --> forgive) % -est = superlative inflection split_suffix( [ e , s , t ] , [ e ] , -est ). % example is "finest" split_suffix( [ C , C , e , s , t ] , [ C ] , -est ) :- % example is "reddest" \+ vowel( C ). % should this be here?? split_suffix( [ i , e , s , t ] , [ y ] , -est ). % example is "craziest" % -er = comparative inflection split_suffix( [ C , C , e , r ] , [ C ] , -er ) :- % example is "redder" \+ vowel( C ). split_suffix( [i , e , r ] , [ y ] , -er ). % example is "crazier" % Final e drops out before a suffix beg. with a vowel split_suffix([C,V|Rest],[C,e],Suffix) :- \+ vowel(C), vowel(V), suffix([V|Rest],Suffix). % spelling rules for English words % that have foriegn or scientific origins % split_suffix([l,v,e,s],[l,f],-pl). split_suffix([e,a,u,x],[e,a,u],-pl). split_suffix([i],[u,s],-pl). split_suffix([i,a],[i,u,m],-pl). split_suffix([a],[u,m],-pl). % (ex. antra --> antrum) split_suffix([a,e],[a],-pl). % (ex. amoebae --> amoeba) split_suffix([s,e,s],[s,i,s],-pl). % (ex. amniocenteses --> amniocenteses) split_suffix([x,e,s],[x,i,s],-pl). % (ex. apomixes apomixis) split_suffix([i,c,e,s],[e,x],-pl). % (ex. apices apex) split_suffix([i,c,e,s],[i,x],-pl). % (ex. appendices appendix) split_suffix([i,m],[i],-pl). % (ex. ashkenazim ashkenazi) split_suffix([e,s],[],-pl). % (ex. banjoes --> banjo) split_suffix([i,n,a],[e,n],-pl). % (ex. praenomina --> praenomen) split_suffix([i,a],[e],-pl). % (ex. qualia --> quale) split_suffix([a,t,a],[a],-pl). % (ex. trymata --> tryma) split_suffix([i,a],[i,o,n],-pl). % (ex. acromia --> acromion) split_suffix([a],[o,n],-pl). % (ex. entera --> enteron) split_suffix([v,e,s],[f,e],-pl). % (ex. knives --> knife) split_suffix([i],[o], -pl). % (ex. maestri --> maestro) split_suffix([f,e,e,t],[f,o,o,t],-pl). % (ex. blackfeet --> blackfoot) split_suffix([a,e],[e],-pl). % (ex. phylae --> phyle) split_suffix([i],[],-pl). % (ex. pirogi --> pirog) split_suffix([e,s],[i,s],-pl). % (ex. vermes --> vermis)
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/ProNTo/Schlachter/pronto_morph_spelling_rules.pl
Perl
mit
3,978
# bulk BAC End Raw download script for SGN database # Lukas Mueller, August 12, 2003 # This bulk download option handles the query # Of BAC Ends of type Raw. # Many of its methods are in the Bulk object. # Modified July 15, 2005 # Modified more August 11, 2005 # Summer Intern Caroline N. Nyenke # Modified July 7, 2006 # Summer Intern Emily Hart # Modified July 3rd, 2007 # Alexander Naydich and Matthew Crumb =head1 NAME /CXGN/Bulk/BACEndRaw.pm (A subclass of Bulk) =head1 DESCRIPTION This perl script is used on the bulk download page. The script collects identifiers submitted by the user and returns information based on the BAC End Raw Ids entered. It then determines the information the user is searching for (Bac Id, Clone Type, Orgonism Name, Accession Name, Library Name, Estimated Length, Genbank Accession, Bac End Sequence, and Qual Value Sequence) and preforms the appropriate querying of the database. The results of the database query are formated and presented to the user on a separate page. Options of viewing or downloading in text or fasta are available. =cut use strict; use warnings; use CXGN::Bulk; use CXGN::DB::DBICFactory; use CXGN::Genomic::CloneNameParser; use CXGN::Genomic::Chromat; use CXGN::Genomic::GSS; package CXGN::Bulk::BACEndRaw; use base "CXGN::Bulk"; sub new { my $class = shift; my $self = $class->SUPER::new(@_); return $self; } =head2 process_parameters Desc: Args: none Ret : 1 if the parameters were OK, 0 if not Modifies some of the parameters received set in get_parameters. Preparing data for the database query. =cut sub process_parameters { my $self = shift; # @output_list defines the identity on order of all fields that can be output my @output_list = ('bac_id', 'clone_type', 'org_name', 'accession_name', 'library_name', 'estimated_length', 'genbank_accession', 'overgo_matches', 'bac_end_sequence', 'qual_value_seq'); my @output_fields = (); $self->debug("Type of identifier: ".($self->{idType}).""); # @output_fields is the sub-set of fields that will actually be output. for my $o (@output_list) { if (my $value = $self->{$o}) { if ($value eq "on") { push @output_fields, $o; } } } $self->{output_list} = \@output_list; $self->{output_fields} = \@output_fields; my @ids = $self->check_ids(); if (@ids == ()) {return 0;} $self->debug("IDs to be processed:"); foreach my $i (@ids) { $self->debug($i); } my $has_valid_id = 0; foreach my $i(@ids) { if ($i ne "") { $has_valid_id = 1; } } if(!$has_valid_id) { return 0; } $self->{ids} = \@ids; return 1; #params were OK if we got here } =head2 process_ids Desc: sub process_ids Args: default; Ret : data from database printed to a file; Queries database using Persistent (see perldoc Persistent) and object oriented perl to obtain data on Bulk Objects using formatted IDs. =cut sub process_ids { my $self = shift; $self->{query_start_time} = time(); my $dbh = $self->{db}; my $chado = CXGN::DB::DBICFactory->open_schema('Bio::Chado::Schema'); my @output_fields = @{$self->{output_fields}}; my @notfound = (); my @return_data = (); my ($dump_fh, $notfound_fh) = $self->create_dumpfile(); my @bac_output; # time counting my $current_time= time() - $self->{query_start_time}; my $foundcount=0; my $notfoundcount=0; my $count=0; # iterate through identifiers foreach my $id (@{$self->{ids}}) { $count++; my $bac_end_parser = CXGN::Genomic::CloneNameParser->new(); # parse name my $parsed_bac_end = $bac_end_parser->BAC_end_external_id ($id); # parsed clone returns undef if parsing did not succeed unless ($parsed_bac_end) { print $notfound_fh (">$id\n"); next; } #look up the chromat my $chromat = CXGN::Genomic::Chromat->retrieve($parsed_bac_end->{chromat_id}); unless ($chromat) { print $notfound_fh (">$id\n"); next; } my $clone = $chromat->clone_object; my $lib = $clone->library_object; my ($gss) = CXGN::Genomic::GSS->search(chromat_id => $chromat->chromat_id, version => $parsed_bac_end->{version}, ); unless($gss) { print $notfound_fh ">$id\n"; next; } # get organism name and accession my (undef, $oname, $cname) = $lib->accession_name(); # raw seq and qual value my $bacseq = $gss->seq; my $qualvalue = $gss->qual; print STDERR "GENBANK ACCESSION:". ref($clone->genbank_accession($chado)) ."\n"; # # check which parameters were selected # my @use_flags = @{$self}{qw/ bac_id # clone_type # org_name # accession_name # library_name # estimated_length # genbank_accession # overgo_matches # bac_end_sequence # qual_value_seq # /}; # will be added soon my $bac_id = $chromat->clone_read_external_identifier(); my $clone_type = $parsed_bac_end->{clonetype}; my $library_name = $lib->name(); my $estimated_length = $clone->estimated_length(); my $genbank_accession = $clone->genbank_accession($chado); my $overgo = "overgo"; my %field_vals = ( "bac_id" => $bac_id, "clone_type" => $clone_type, "org_name" => $oname, "accession_name" => $cname, "library_name" => $library_name, "estimated_length" => $estimated_length, "genbank_accession" => $genbank_accession , "overgo_matches" => $overgo, "bac_end_sequence" => $bacseq, "qual_value_seq" => $qualvalue, ); #warn 'made field vals ',join(', ',@field_vals); my @data_array = (); print STDERR "OUTPUT FIELDS: ". (join "\t", @output_fields)."\n\n"; foreach my $selected_field (@output_fields) { print STDERR "PUSHING $selected_field = $field_vals{$selected_field}\n"; push @data_array, $field_vals{$selected_field}; } # my @field_vals = map { $_ || '' } ($chromat->clone_read_external_identifier, # $parsed_bac_end->{clonetype}, # $oname, # $cname, # $lib->name, # $clone->estimated_length, # $clone->genbank_accession, # $overgo, # $bacseq, # $qualvalue, # ); # #warn 'made field vals ',join(', ',@field_vals); # my @data_array = map { my $val = shift @field_vals; # $_ ? ($val) : () # } @output_fields; # warn "information from query: $oname, $cname,\n"; # print query results to dumpfile my $linecolumns = join("\t", @data_array)."\n"; print $dump_fh $linecolumns ; print STDERR "LINE: ". $linecolumns; } $current_time = time() - $self->{query_start_time}; close($dump_fh); close($notfound_fh); $self->{foundcount}= $foundcount; $self->{notfoundcount}= $notfoundcount; $current_time = time() - $self->{query_start_time}; $self->{query_time} = time() - $self->{query_start_time}; } 1;
solgenomics/sgn
lib/CXGN/Bulk/BACEndRaw.pm
Perl
mit
7,209
#------------------------------------------------------------------------------ # File: Charset.pm # # Description: ExifTool character encoding routines # # Revisions: 2009/08/28 - P. Harvey created # 2010/01/20 - P. Harvey complete re-write # 2010/07/16 - P. Harvey added UTF-16 support # # Notes: Charset lookups are generated using my convertCharset script #------------------------------------------------------------------------------ package Image::ExifTool::Charset; use strict; use vars qw($VERSION %csType); use Image::ExifTool qw(:DataAccess :Utils); $VERSION = '1.11'; my %charsetTable; # character set tables we've loaded # lookup for converting Unicode to 1-byte character sets my %unicode2byte = ( Latin => { # pre-load Latin (cp1252) for speed 0x20ac => 0x80, 0x0160 => 0x8a, 0x2013 => 0x96, 0x201a => 0x82, 0x2039 => 0x8b, 0x2014 => 0x97, 0x0192 => 0x83, 0x0152 => 0x8c, 0x02dc => 0x98, 0x201e => 0x84, 0x017d => 0x8e, 0x2122 => 0x99, 0x2026 => 0x85, 0x2018 => 0x91, 0x0161 => 0x9a, 0x2020 => 0x86, 0x2019 => 0x92, 0x203a => 0x9b, 0x2021 => 0x87, 0x201c => 0x93, 0x0153 => 0x9c, 0x02c6 => 0x88, 0x201d => 0x94, 0x017e => 0x9e, 0x2030 => 0x89, 0x2022 => 0x95, 0x0178 => 0x9f, }, ); # bit flags for all supported character sets # (this number must be correct because it dictates the decoding algorithm!) # 0x001 = character set requires a translation module # 0x002 = inverse conversion not yet supported by Recompose() # 0x080 = some characters with codepoints in the range 0x00-0x7f are remapped # 0x100 = 1-byte fixed-width characters # 0x200 = 2-byte fixed-width characters # 0x400 = 4-byte fixed-width characters # 0x800 = 1- and 2-byte variable-width characters, or 1-byte # fixed-width characters that map into multiple codepoints # Note: In its public interface, ExifTool can currently only support type 0x101 # and lower character sets because strings are only converted if they # contain characters above 0x7f and there is no provision for specifying # the byte order for input/output values %csType = ( UTF8 => 0x100, ASCII => 0x100, # (treated like UTF8) Arabic => 0x101, Baltic => 0x101, Cyrillic => 0x101, Greek => 0x101, Hebrew => 0x101, Latin => 0x101, Latin2 => 0x101, DOSLatinUS => 0x101, DOSLatin1 => 0x101, DOSCyrillic => 0x101, MacCroatian => 0x101, MacCyrillic => 0x101, MacGreek => 0x101, MacIceland => 0x101, MacLatin2 => 0x101, MacRoman => 0x101, MacRomanian => 0x101, MacTurkish => 0x101, Thai => 0x101, Turkish => 0x101, Vietnam => 0x101, MacArabic => 0x103, # (directional characters not supported) PDFDoc => 0x181, Unicode => 0x200, # (UCS2) UCS2 => 0x200, UTF16 => 0x200, Symbol => 0x201, JIS => 0x201, UCS4 => 0x400, MacChineseCN => 0x803, MacChineseTW => 0x803, MacHebrew => 0x803, # (directional characters not supported) MacKorean => 0x803, MacRSymbol => 0x803, MacThai => 0x803, MacJapanese => 0x883, ShiftJIS => 0x883, ); #------------------------------------------------------------------------------ # Load character set module # Inputs: 0) Module name # Returns: Reference to lookup hash, or undef on error sub LoadCharset($) { my $charset = shift; my $conv = $charsetTable{$charset}; unless ($conv) { # load translation module my $module = "Image::ExifTool::Charset::$charset"; no strict 'refs'; if (%$module or eval "require $module") { $conv = $charsetTable{$charset} = \%$module; } } return $conv; } #------------------------------------------------------------------------------ # Does an array contain valid UTF-16 characters? # Inputs: 0) array reference to list of UCS-2 values # Returns: 0=invalid UTF-16, 1=valid UTF-16 with no surrogates, 2=valid UTF-16 with surrogates sub IsUTF16($) { local $_; my $uni = shift; my $surrogate; foreach (@$uni) { my $hiBits = ($_ & 0xfc00); if ($hiBits == 0xfc00) { # check for invalid values in UTF-16 return 0 if $_ == 0xffff or $_ == 0xfffe or ($_ >= 0xfdd0 and $_ <= 0xfdef); } elsif ($surrogate) { return 0 if $hiBits != 0xdc00; $surrogate = 0; } else { return 0 if $hiBits == 0xdc00; $surrogate = 1 if $hiBits == 0xd800; } } return 1 if not defined $surrogate; return 2 unless $surrogate; return 0; } #------------------------------------------------------------------------------ # Decompose string with specified encoding into an array of integer code points # Inputs: 0) ExifTool object ref (or undef), 1) string, 2) character set name, # 3) optional byte order ('II','MM','Unknown' or undef to use ExifTool ordering) # Returns: Reference to array of Unicode values # Notes: Accepts any type of character set # - byte order only used for fixed-width 2-byte and 4-byte character sets # - byte order mark observed and then removed with UCS2 and UCS4 # - no warnings are issued if ExifTool object is not provided # - sets ExifTool WrongByteOrder flag if byte order is Unknown and current order is wrong sub Decompose($$$;$) { local $_; my ($et, $val, $charset) = @_; # ($byteOrder assigned later if required) my $type = $csType{$charset}; my (@uni, $conv); if ($type & 0x001) { $conv = LoadCharset($charset); unless ($conv) { # (shouldn't happen) $et->Warn("Invalid character set $charset") if $et; return \@uni; # error! } } elsif ($type == 0x100) { # convert ASCII and UTF8 (treat ASCII as UTF8) if ($] < 5.006001) { # do it ourself @uni = Image::ExifTool::UnpackUTF8($val); } else { # handle warnings from malformed UTF-8 undef $Image::ExifTool::evalWarning; local $SIG{'__WARN__'} = \&Image::ExifTool::SetWarning; # (somehow the meaning of "U0" was reversed in Perl 5.10.0!) @uni = unpack($] < 5.010000 ? 'U0U*' : 'C0U*', $val); # issue warning if we had errors if ($Image::ExifTool::evalWarning and $et and not $$et{WarnBadUTF8}) { $et->Warn('Malformed UTF-8 character(s)'); $$et{WarnBadUTF8} = 1; } } return \@uni; # all done! } if ($type & 0x100) { # 1-byte fixed-width characters @uni = unpack('C*', $val); foreach (@uni) { $_ = $$conv{$_} if defined $$conv{$_}; } } elsif ($type & 0x600) { # 2-byte or 4-byte fixed-width characters my $unknown; my $byteOrder = $_[3]; if (not $byteOrder) { $byteOrder = GetByteOrder(); } elsif ($byteOrder eq 'Unknown') { $byteOrder = GetByteOrder(); $unknown = 1; } my $fmt = $byteOrder eq 'MM' ? 'n*' : 'v*'; if ($type & 0x400) { # 4-byte $fmt = uc $fmt; # unpack as 'N*' or 'V*' # honour BOM if it exists $val =~ s/^(\0\0\xfe\xff|\xff\xfe\0\0)// and $fmt = $1 eq "\0\0\xfe\xff" ? 'N*' : 'V*'; undef $unknown; # (byte order logic applies to 2-byte only) } elsif ($val =~ s/^(\xfe\xff|\xff\xfe)//) { $fmt = $1 eq "\xfe\xff" ? 'n*' : 'v*'; undef $unknown; } # convert from UCS2 or UCS4 @uni = unpack($fmt, $val); if (not $conv) { # no translation necessary if ($unknown) { # check the byte order my (%bh, %bl); my ($zh, $zl) = (0, 0); foreach (@uni) { $bh{$_ >> 8} = 1; $bl{$_ & 0xff} = 1; ++$zh unless $_ & 0xff00; ++$zl unless $_ & 0x00ff; } # count the number of unique values in the hi and lo bytes my ($bh, $bl) = (scalar(keys %bh), scalar(keys %bl)); # the byte with the greater number of unique values should be # the low-order byte, otherwise the byte which is zero more # often is likely the high-order byte if ($bh > $bl or ($bh == $bl and $zl > $zh)) { # we guessed wrong, so decode using the other byte order $fmt =~ tr/nvNV/vnVN/; @uni = unpack($fmt, $val); $$et{WrongByteOrder} = 1; } } # handle surrogate pairs of UTF-16 if ($charset eq 'UTF16') { my $i; for ($i=0; $i<$#uni; ++$i) { next unless ($uni[$i] & 0xfc00) == 0xd800 and ($uni[$i+1] & 0xfc00) == 0xdc00; my $cp = 0x10000 + (($uni[$i] & 0x3ff) << 10) + ($uni[$i+1] & 0x3ff); splice(@uni, $i, 2, $cp); } } } elsif ($unknown) { # count encoding errors as we do the translation my $e1 = 0; foreach (@uni) { defined $$conv{$_} and $_ = $$conv{$_}, next; ++$e1; } # try the other byte order if we had any errors if ($e1) { $fmt = $byteOrder eq 'MM' ? 'v*' : 'n*'; #(reversed) my @try = unpack($fmt, $val); my $e2 = 0; foreach (@try) { defined $$conv{$_} and $_ = $$conv{$_}, next; ++$e2; } # use this byte order if there are fewer errors if ($e2 < $e1) { $$et{WrongByteOrder} = 1; return \@try; } } } else { # translate any characters found in the lookup foreach (@uni) { $_ = $$conv{$_} if defined $$conv{$_}; } } } else { # variable-width characters # unpack into bytes my @bytes = unpack('C*', $val); while (@bytes) { my $ch = shift @bytes; my $cv = $$conv{$ch}; # pass straight through if no translation $cv or push(@uni, $ch), next; # byte translates into single Unicode character ref $cv or push(@uni, $cv), next; # byte maps into multiple Unicode characters ref $cv eq 'ARRAY' and push(@uni, @$cv), next; # handle 2-byte character codes $ch = shift @bytes; if (defined $ch) { if ($$cv{$ch}) { $cv = $$cv{$ch}; ref $cv or push(@uni, $cv), next; push @uni, @$cv; # multiple Unicode characters } else { push @uni, ord('?'); # encoding error unshift @bytes, $ch; } } else { push @uni, ord('?'); # encoding error } } } return \@uni; } #------------------------------------------------------------------------------ # Convert array of code point integers into a string with specified encoding # Inputs: 0) ExifTool ref (or undef), 1) unicode character array ref, # 2) character set (note: not all types are supported) # 3) byte order ('MM' or 'II', multi-byte sets only, defaults to current byte order) # Returns: converted string (truncated at null character if it exists), empty on error # Notes: converts elements of input character array to new code points # - ExifTool ref may be undef provided $charset is defined sub Recompose($$;$$) { local $_; my ($et, $uni, $charset) = @_; # ($byteOrder assigned later if required) my ($outVal, $conv, $inv); $charset or $charset = $$et{OPTIONS}{Charset}; my $csType = $csType{$charset}; if ($csType == 0x100) { # UTF8 (also treat ASCII as UTF8) if ($] >= 5.006001) { # let Perl do it $outVal = pack('C0U*', @$uni); } else { # do it ourself $outVal = Image::ExifTool::PackUTF8(@$uni); } $outVal =~ s/\0.*//s; # truncate at null terminator return $outVal; } # get references to forward and inverse lookup tables if ($csType & 0x801) { $conv = LoadCharset($charset); unless ($conv) { $et->Warn("Missing charset $charset") if $et; return ''; } $inv = $unicode2byte{$charset}; # generate inverse lookup if necessary unless ($inv) { if (not $csType or $csType & 0x802) { $et->Warn("Invalid destination charset $charset") if $et; return ''; } # prepare table to convert from Unicode to 1-byte characters my ($char, %inv); foreach $char (keys %$conv) { $inv{$$conv{$char}} = $char; } $inv = $unicode2byte{$charset} = \%inv; } } if ($csType & 0x100) { # 1-byte fixed-width # convert to specified character set foreach (@$uni) { next if $_ < 0x80; $$inv{$_} and $_ = $$inv{$_}, next; # our tables omit 1-byte characters with the same values as Unicode, # so pass them straight through after making sure there isn't a # different character with this byte value next if $_ < 0x100 and not $$conv{$_}; $_ = ord('?'); # set invalid characters to '?' if ($et and not $$et{EncodingError}) { $et->Warn("Some character(s) could not be encoded in $charset"); $$et{EncodingError} = 1; } } # repack as an 8-bit string and truncate at null $outVal = pack('C*', @$uni); $outVal =~ s/\0.*//s; } else { # 2-byte and 4-byte fixed-width # convert if required if ($inv) { $$inv{$_} and $_ = $$inv{$_} foreach @$uni; } # generate surrogate pairs of UTF-16 if ($charset eq 'UTF16') { my $i; for ($i=0; $i<@$uni; ++$i) { next unless $$uni[$i] >= 0x10000 and $$uni[$i] < 0x10ffff; my $t = $$uni[$i] - 0x10000; my $w1 = 0xd800 + (($t >> 10) & 0x3ff); my $w2 = 0xdc00 + ($t & 0x3ff); splice(@$uni, $i, 1, $w1, $w2); ++$i; # skip surrogate pair } } # pack as 2- or 4-byte integer in specified byte order my $byteOrder = $_[3] || GetByteOrder(); my $fmt = $byteOrder eq 'MM' ? 'n*' : 'v*'; $fmt = uc($fmt) if $csType & 0x400; $outVal = pack($fmt, @$uni); } return $outVal; } 1; # end __END__ =head1 NAME Image::ExifTool::Charset - ExifTool character encoding routines =head1 SYNOPSIS This module is required by Image::ExifTool. =head1 DESCRIPTION This module contains routines used by ExifTool to translate special character sets. Currently, the following character sets are supported: UTF8, UTF16, UCS2, UCS4, Arabic, Baltic, Cyrillic, Greek, Hebrew, JIS, Latin, Latin2, DOSLatinUS, DOSLatin1, DOSCyrillic, MacArabic, MacChineseCN, MacChineseTW, MacCroatian, MacCyrillic, MacGreek, MacHebrew, MacIceland, MacJapanese, MacKorean, MacLatin2, MacRSymbol, MacRoman, MacRomanian, MacThai, MacTurkish, PDFDoc, RSymbol, ShiftJIS, Symbol, Thai, Turkish, Vietnam However, only some of these character sets are available to the user via ExifTool options -- the multi-byte character sets are used only internally when decoding certain types of information. =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 SEE ALSO L<Image::ExifTool(3pm)|Image::ExifTool> =cut
mceachen/exiftool_vendored
bin/lib/Image/ExifTool/Charset.pm
Perl
mit
16,397
#!/usr/bin/perl use strict; use warnings; use lib '../'; # This script uses full DBIx::Class object inflation. It takes about # 2.6 hours to process 4 million features. use GAL::Schema; my $schema = GAL::Schema->connect('DBI:mysql:database=pg_chinese_snp'); my $feature_rs = $schema->resultset('Feature'); while (my $feature = $feature_rs->next) { my $id = $feature->id; my $ref_allele = $feature->attributes->find({key => 'reference_allele'})->value; print "$id\t$ref_allele\n"; }
4ureliek/TEanalysis
Lib/GAL/t/devel_scripts/schema_object.pl
Perl
mit
503
########################################################################### # # This file is auto-generated by the Perl DateTime Suite time locale # generator (0.04). This code generator comes with the # DateTime::Locale distribution in the tools/ directory, and is called # generate_from_cldr. # # This file as generated from the CLDR XML locale data. See the # LICENSE.cldr file included in this distribution for license details. # # This file was generated from the source file ar.xml. # The source file version number was 1.84, generated on # 2007/07/24 23:39:15. # # Do not edit this file directly. # ########################################################################### package DateTime::Locale::ar; use strict; BEGIN { if ( $] >= 5.006 ) { require utf8; utf8->import; } } use DateTime::Locale::root; @DateTime::Locale::ar::ISA = qw(DateTime::Locale::root); my @day_names = ( "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد", ); my @day_abbreviations = ( "اثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت", "أحد", ); my @day_narrows = ( "ن", "ث", "ر", "خ", "ج", "س", "ح", ); my @month_names = ( "يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر", ); my @month_abbreviations = ( "يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر", ); my @month_narrows = ( "ي", "ف", "م", "أ", "و", "ن", "ل", "غ", "س", "ك", "ب", "د", ); my @quarter_names = ( "الربع\ الأول", "الربع\ الثاني", "الربع\ الثالث", "الربع\ الرابع", ); my @quarter_abbreviations = ( "الربع\ الأول", "الربع\ الثاني", "الربع\ الثالث", "الربع\ الرابع", ); my @am_pms = ( "ص", "م", ); my @era_names = ( "قبل\ الميلاد", "ميلادي", ); my @era_abbreviations = ( "ق\.م", "م", ); my $date_before_time = "1"; my $date_parts_order = "dmy"; sub day_names { \@day_names } sub day_abbreviations { \@day_abbreviations } sub day_narrows { \@day_narrows } sub month_names { \@month_names } sub month_abbreviations { \@month_abbreviations } sub month_narrows { \@month_narrows } sub quarter_names { \@quarter_names } sub quarter_abbreviations { \@quarter_abbreviations } sub am_pms { \@am_pms } sub era_names { \@era_names } sub era_abbreviations { \@era_abbreviations } sub full_date_format { "\%A\,\ \%\{day\}\ \%B\,\ \%\{ce_year\}" } sub long_date_format { "\%\{day\}\ \%B\,\ \%\{ce_year\}" } sub medium_date_format { "\%d‏\/\%m‏\/\%\{ce_year\}" } sub short_date_format { "\%\{day\}‏\/\%\{month\}‏\/\%\{ce_year\}" } sub full_time_format { "v\ \%\{hour_12\}\:\%M\:\%S\ \%p" } sub long_time_format { "\%\{time_zone_long_name\}\ \%\{hour_12\}\:\%M\:\%S\ \%p" } sub medium_time_format { "\%\{hour_12\}\:\%M\:\%S\ \%p" } sub short_time_format { "\%\{hour_12\}\:\%M\ \%p" } sub date_before_time { $date_before_time } sub date_parts_order { $date_parts_order } 1;
carlgao/lenga
images/lenny64-peon/usr/share/perl5/DateTime/Locale/ar.pm
Perl
mit
3,550
#!/usr/bin/env perl use strict; use warnings; use Getopt::Long; use YAML::XS qw (LoadFile DumpFile); use File::Basename; use Assembly::Utils; my $options = {}; my @colheaders = ("Species", "Strain", "Sample_ID", "Trim_Raw", "Reference_Strain", "Reference_Metafile", "Output_Release_Dir", "Output_Release_Prefix"); sub set_default_opts { my %defaults = qw( rna_assembly_table input_data/RnaAssemblyTable.tab genome_lengths_table input_data/GenomeLengths.tab wiki_table_file output_files/wiki_transcript_table.txt yaml_in yaml_files/15_rna_setup.yml yaml_out yaml_files/16_rna_release.yml create_release 0 ); for my $key (keys %defaults) { $options->{$key} = $defaults{$key} unless $options->{$key}; } } sub check_options { unless ($options->{rna_assembly_table} and $options->{yaml_in} ) { die "Usage: $0 -a <RNA assembly table> -i <yaml input file> -o <yaml output file> Optional: --genome_lengths_table <filename> --wiki_table_file <filename> --testing --verbose --create_release "; } } sub gather_options { GetOptions($options, 'rna_assembly_table|a=s', 'genome_lengths_table|g=s', 'wiki_table_file|w=s', 'testing|t', 'verbose|v', 'create_release|r', 'yaml_in|i=s', 'yaml_out|o=s', ); set_default_opts; check_options; } sub print_verbose { if ($options->{verbose}) { print (@_); } } # Parse the input table sub parse_assembly_table { my $table_recs = {}; my $fname = ($options->{rna_assembly_table} ? $options->{rna_assembly_table} : ''); if ($fname and -s $fname) { open (FRNA, '<', $fname) or die "Error: couldn't open file $fname\n"; while (my $line = <FRNA>) { chomp $line; my @fields = split (/\t/, $line); if (scalar (@fields) == scalar (@colheaders)) { my $line_record = {}; foreach my $i (0..$#colheaders) { # Add hash entry key=column header, value=parsed field value $line_record->{$colheaders[$i]} = $fields[$i]; } my $species_key = Assembly::Utils::format_species_key($line_record->{Species}); $line_record->{Species} = $species_key; # Reset value to standard access format. my $strain_key = Assembly::Utils::format_strain_key($line_record->{Strain}); $line_record->{Strain} = $strain_key; # Reset value to standard access format. my $reference_strain_key = Assembly::Utils::format_strain_key($line_record->{Reference_Strain}); $line_record->{Reference_Strain} = $reference_strain_key; my $sample = $line_record->{"Sample_ID"}; $table_recs->{$sample} = $line_record; } else { print_verbose ("Error on line $. of rna assembly table file - incorrect number of cols.\n"); } } close (FRNA); } return $table_recs; } # Parse the species, kingdom from the genome lengths table sub parse_genome_lengths_table { my $s2k = {}; my $fname = ($options->{genome_lengths_table} ? $options->{genome_lengths_table} : ''); if ($fname and -s $fname) { open (FGL, '<', $fname) or die "Error: couldn't open file $fname\n"; <FGL>; <FGL>; # skip top two (col headers) rows. while (my $line = <FGL>) { chomp $line; my @fields = split (/\t/, $line); if (scalar @fields > 1) { my $species = Assembly::Utils::format_species_key ($fields[0]); my $kingdom = $fields[1]; $s2k->{$species} = $kingdom; } } close (FGL); } return $s2k; } sub get_key { my ($species, $strain, $release) = @_; return join(":", ($species, $strain, $release)); } sub get_release_recs { my $table_records = shift; # Get each unique combo of reference species, reference strain, release. my $release_recs = {}; for my $sample (keys %$table_records) { my $species = $table_records->{$sample}->{"Species"}; my $strain = $table_records->{$sample}->{"Reference_Strain"}; my $release = $table_records->{$sample}->{"Output_Release_Prefix"}; my $release_dir = $table_records->{$sample}->{"Output_Release_Dir"}; print "Got release dir $release_dir\n"; my $key = get_key ($species, $strain, $release); unless ($release_recs->{$key}) { $release_recs->{$key} = [$species, $strain, $release, $release_dir]; } } return $release_recs; } sub get_release_link { my $release_dir = shift; my $link_prefix = "http://biocluster/project_data/CRTI-09S-462RD/specimen"; $release_dir =~ s/processing_test2\///; $release_dir =~ s/.*\/specimen\///; my $link_dir = $link_prefix . "/" . $release_dir; my $link = "[[" . $link_dir . "][Release]]"; return $link; } sub create_wiki_table { my $yaml_records = shift; my $table_records = shift; my $spec_to_king = shift; my $release_recs = get_release_recs ($table_records); my $fname = ($options->{wiki_table_file} ? $options->{wiki_table_file} : ''); if ($fname) { my @wiki_line_list = (); foreach my $rkey (keys %$release_recs) { my $rec = $release_recs->{$rkey}; my ($species, $strain, $release, $release_dir) = @$rec; my $kingdom = $spec_to_king->{$species}; my $link = get_release_link ($release_dir); $release =~ s/^.*\_//; $species =~ s/\_/ /g; $strain =~ s/\_/ /g; my $type = "Transcript Assembly"; my $wiki_line = "|" . join ("|", ($kingdom, $species, $strain, $release, $type, $link)) . "|"; #print FWIKI $wiki_line . "\n"; push (@wiki_line_list, $wiki_line); } open (FWIKI, '>', $fname) or die "Error: couldn't open file for output: $fname\n"; print FWIKI "|" . join ("|", (qw(Kingdom Species Strain Release Type Link))) . "|\n"; @wiki_line_list = sort (@wiki_line_list); print FWIKI join ("\n", @wiki_line_list) . "\n"; close (FWIKI); } } gather_options; my $yaml_records = LoadFile ($options->{yaml_in}); my $table_records = parse_assembly_table; my $spec_to_king = parse_genome_lengths_table; create_wiki_table ($yaml_records, $table_records, $spec_to_king); #DumpFile ($options->{yaml_out});
AAFC-MBB/crti-assembly-pipeline
RnaAssemblyReleaseWiki.pl
Perl
mit
6,924
package SanrioCharacterRanking::DB::Row; use strict; use warnings; use utf8; use parent qw(Teng::Row); 1;
mono0x/ranking.sucretown.net
lib/SanrioCharacterRanking/DB/Row.pm
Perl
mit
107
package Pod::AsciiDoctor; use 5.006; use strict; use warnings FATAL => 'all'; use base 'Pod::Parser'; =head1 NAME Pod::AsciiDoctor - Convert from POD to AsciiDoc =head1 VERSION Version 0.01 =cut our $VERSION = '0.01'; =head1 SYNOPSIS Converts the POD of a Perl module to AsciiDoc format. use Pod::AsciiDoctor; my $adoc = Pod::AsciiDoctor->new(); $adoc->parse_from_filehandle($fh); print $adoc->adoc(); =head1 SUBROUTINES/METHODS =head2 initialize =cut sub initalize { my $self = shift; $self->SUPER::initialize(@_); $self->_prop; return $self; } =head2 adoc =cut sub adoc { my $self = shift; my $data = $self->_prop; return join "\n", @{$data->{text}}; } =head2 _prop =cut sub _prop { my $self = shift; $self->{prop} //= { 'text' => [], 'headers' => "", 'topheaders' => {}, 'command' => '', 'indent' => 0 }; } =head2 sanitise =cut sub _sanitise { my $self = shift; my $p = shift; chomp($p); return $p; } =head2 append =cut sub append { my ($self, $doc) = @_; my $data = $self->_prop; push @{$data->{text}}, $doc; } =head2 command Overrides Pod::Parser::command =cut sub command { my ($self, $command, $paragraph, $lineno) = @_; my $data = $self->_prop; $data->{command} = $command; # _sanitise: Escape AsciiDoctor syntax chars that appear in the paragraph. $paragraph = $self->_sanitise($paragraph); if ($command =~ /head(\d)/) { my $level = $1; $level //= 2; $data->{command} = 'head'; $data->{topheaders}{$1} = defined($data->{topheaders}{$1}) ? $data->{topheaders}{$1}++ : 1; $paragraph = $self->set_formatting($paragraph); # print "PARA:: $paragraph\n"; $self->append($self->make_header($command, $level, $paragraph)); } if ($command =~ /over/) { $data->{indent}++; } if ($command =~ /back/) { $data->{indent}--; } if ($command =~ /item/) { $self->append($self->make_text($paragraph, 1)); } return; } =head2 verbatim Overrides Pod::Parser::verbatim =cut sub verbatim { my $self = shift; my $paragraph = shift; chomp($paragraph); $self->append($paragraph); return; } =head2 textblock Overrides Pod::Parser::textblock =cut sub textblock { my $self = shift; my ($paragraph, $lineno) = @_; chomp($paragraph); $self->append($paragraph); } =head2 make_header =cut sub make_header { my ($self, $command, $level, $paragraph) = @_; if ($command =~ /head/) { my $h = sprintf("%s %s", "=" x ($level+1), $paragraph); return $h; } elsif ($command =~ /item/) { return "* $paragraph"; } } =head2 make_text =cut sub make_text { my ($self, $paragraph, $list) = @_; my @lines = split "\n", $paragraph; my $data = $self->_prop; my @i_paragraph; my $pnt = $list ? "*" : ""; for my $line (@lines) { # print "MKTXT::$line\n"; push @i_paragraph, $pnt x $data->{indent} . " " . $line . "\n"; } return join "\n", @i_paragraph; } =head2 set_formatting =cut sub set_formatting { my $self = shift; my $paragraph = shift; $paragraph =~ s/I<(.*)>/_$1_/; $paragraph =~ s/B<(.*)>/*$1*/; $paragraph =~ s/B<(.*)>/*$1*/; $paragraph =~ s/C<(.*)>/\`$1\`/xms; return $paragraph; } =head1 AUTHOR Balachandran Sivakumar, C<< <balachandran at balachandran.org> >> =head1 BUGS Please report any bugs or feature requests to C<bug-pod-asciidoctor at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Pod-AsciiDoctor>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Pod::AsciiDoctor You can also look for information at: =over 4 =item * RT: CPAN's request tracker (report bugs here) L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Pod-AsciiDoctor> =item * AnnoCPAN: Annotated CPAN documentation L<http://annocpan.org/dist/Pod-AsciiDoctor> =item * CPAN Ratings L<http://cpanratings.perl.org/d/Pod-AsciiDoctor> =item * Search CPAN L<http://search.cpan.org/dist/Pod-AsciiDoctor/> =back =head1 ACKNOWLEDGEMENTS =head1 LICENSE AND COPYRIGHT Copyright 2015 Balachandran Sivakumar. This program is free software; you can redistribute it and/or modify it under the terms of the the Apache License (2.0). You can get 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 1;
syohex/pod-asciidoctor
lib/Pod/AsciiDoctor.pm
Perl
apache-2.0
4,989
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package hardware::ups::apc::snmp::mode::batterystatus; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::templates::catalog_functions; sub custom_status_output { my ($self, %options) = @_; my $msg = sprintf("Battery status is '%s' [battery needs replace: %s]", $self->{result_values}->{status}, $self->{result_values}->{replace}); return $msg; } sub custom_status_calc { my ($self, %options) = @_; $self->{result_values}->{status} = $options{new_datas}->{$self->{instance} . '_upsBasicBatteryStatus'}; $self->{result_values}->{replace} = $options{new_datas}->{$self->{instance} . '_upsAdvBatteryReplaceIndicator'}; return 0; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0 }, ]; $self->{maps_counters}->{global} = [ { label => 'status', threshold => 0, set => { key_values => [ { name => 'upsBasicBatteryStatus' }, { name => 'upsAdvBatteryReplaceIndicator' } ], closure_custom_calc => $self->can('custom_status_calc'), closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => \&centreon::plugins::templates::catalog_functions::catalog_status_threshold, } }, { label => 'load', set => { key_values => [ { name => 'upsAdvBatteryCapacity' } ], output_template => 'Remaining capacity : %s %%', perfdatas => [ { label => 'load', value => 'upsAdvBatteryCapacity_absolute', template => '%s', min => 0, max => 100, unit => '%' }, ], } }, { label => 'time', set => { key_values => [ { name => 'upsAdvBatteryRunTimeRemaining' } ], output_template => 'Remaining time : %.2f minutes', perfdatas => [ { label => 'load_time', value => 'upsAdvBatteryRunTimeRemaining_absolute', template => '%.2f', min => 0, unit => 'm' }, ], } }, { label => 'current', set => { key_values => [ { name => 'upsAdvBatteryCurrent' } ], output_template => 'Current : %s A', perfdatas => [ { label => 'current', value => 'upsAdvBatteryCurrent_absolute', template => '%s', min => 0, unit => 'A' }, ], } }, { label => 'voltage', set => { key_values => [ { name => 'upsAdvBatteryActualVoltage' } ], output_template => 'Voltage : %s V', perfdatas => [ { label => 'voltage', value => 'upsAdvBatteryActualVoltage_absolute', template => '%s', unit => 'V' }, ], } }, { label => 'temperature', set => { key_values => [ { name => 'upsAdvBatteryTemperature' } ], output_template => 'Temperature : %s C', perfdatas => [ { label => 'temperature', value => 'upsAdvBatteryTemperature_absolute', template => '%s', unit => 'C'}, ], } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { "unknown-status:s" => { name => 'unknown_status', default => '%{status} =~ /unknown/i' }, "warning-status:s" => { name => 'warning_status', default => '%{status} =~ /batteryLow/i' }, "critical-status:s" => { name => 'critical_status', default => '%{replace} =~ /yes/i' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->change_macros(macros => ['warning_status', 'critical_status', 'unknown_status']); } my %map_battery_status = ( 1 => 'unknown', 2 => 'batteryNormal', 3 => 'batteryLow', ); my %map_replace_status = ( 1 => 'no', 2 => 'yes', ); my $mapping = { upsBasicBatteryStatus => { oid => '.1.3.6.1.4.1.318.1.1.1.2.1.1', map => \%map_battery_status }, upsBasicBatteryTimeOnBattery => { oid => '.1.3.6.1.4.1.318.1.1.1.2.1.2' }, }; my $mapping2 = { upsAdvBatteryCapacity => { oid => '.1.3.6.1.4.1.318.1.1.1.2.2.1' }, upsAdvBatteryTemperature => { oid => '.1.3.6.1.4.1.318.1.1.1.2.2.2' }, upsAdvBatteryRunTimeRemaining => { oid => '.1.3.6.1.4.1.318.1.1.1.2.2.3' }, upsAdvBatteryReplaceIndicator => { oid => '.1.3.6.1.4.1.318.1.1.1.2.2.4', map => \%map_replace_status }, upsAdvBatteryActualVoltage => { oid => '.1.3.6.1.4.1.318.1.1.1.2.2.8' }, upsAdvBatteryCurrent => { oid => '.1.3.6.1.4.1.318.1.1.1.2.2.9' }, }; my $oid_upsBasicBattery = '.1.3.6.1.4.1.318.1.1.1.2.1'; my $oid_upsAdvBattery = '.1.3.6.1.4.1.318.1.1.1.2.2'; sub manage_selection { my ($self, %options) = @_; $self->{global} = {}; $self->{results} = $options{snmp}->get_multiple_table(oids => [ { oid => $oid_upsBasicBattery }, { oid => $oid_upsAdvBattery }, ], nothing_quit => 1); my $result = $options{snmp}->map_instance(mapping => $mapping, results => $self->{results}->{$oid_upsBasicBattery}, instance => '0'); my $result2 = $options{snmp}->map_instance(mapping => $mapping2, results => $self->{results}->{$oid_upsAdvBattery}, instance => '0'); $result2->{upsAdvBatteryRunTimeRemaining} = sprintf("%.0f", $result2->{upsAdvBatteryRunTimeRemaining} / 100 / 60) if (defined($result2->{upsAdvBatteryRunTimeRemaining})); foreach my $name (keys %{$mapping}) { $self->{global}->{$name} = $result->{$name}; } foreach my $name (keys %{$mapping2}) { $self->{global}->{$name} = $result2->{$name}; } } 1; __END__ =head1 MODE Check Battery Status and battery charge remaining. =over 8 =item B<--filter-counters> Only display some counters (regexp can be used). Example: --filter-counters='^status|load$' =item B<--unknown-status> Set warning threshold for status (Default: '%{status} =~ /unknown/i'). Can used special variables like: %{status}, %{replace} =item B<--warning-status> Set warning threshold for status (Default: '%{status} =~ /batteryLow/i'). Can used special variables like: %{status}, %{replace} =item B<--critical-status> Set critical threshold for status (Default: '%{replace} =~ /yes/i'). Can used special variables like: %{status}, %{replace} =item B<--warning-*> Threshold warning. Can be: 'load', 'voltage', 'current', 'temperature', 'time'. =item B<--critical-*> Threshold critical. Can be: 'load', 'voltage', 'current', 'temperature', 'time'. =back =cut
Sims24/centreon-plugins
hardware/ups/apc/snmp/mode/batterystatus.pm
Perl
apache-2.0
8,142
#!/usr/bin/env perl use strict; use warnings; # use diagnostics; use autodie; use feature qw(say); use Data::Printer; use Cwd 'abs_path'; # use JSON qw(decode_json); # use Path::Tiny; use JSON::Parse 'json_file_to_perl'; main(); sub main { if ( !$ARGV[0] ) { usage(); exit 1; } my $json_dir = abs_path( $ARGV[0] ); my $data = get_data_from_jsons($json_dir); while ( my ( $json_file, $json_data ) = each %{$data} ) { check_mandatory_fields( $json_file, $json_data ); } print_csv($data); say 'success'; } sub print_csv { my ( $data, $output ) = @_; for my $j ( values %{$data} ) { print $j->{accession} . "," . $j->{replicate}->{experiment}->{biosample_term_name} . "," . $j->{replicate}->{experiment}->{target}->{label} . "," . $j->{replicate}->{biological_replicate_number} . "," . $j->{replicate}->{technical_replicate_number} . "," . $j->{md5sum} . "," . $j->{funcgen}->{local_url} . "," . $j->{funcgen}->{is_control} . "," . $j->{replicate}->{experiment}->{assay_title} . "," . $j->{funcgen}->{experimental_group} . ","; print join( ',', @{ $j->{replicate}->{experiment}->{biosample_term_id} } ); print ","; if ( $j->{funcgen}->{is_control} == 0 ) { print join( ',', @{ $j->{controlled_by} } ); print ","; } print join( ',', @{ $j->{replicate}->{experiment}->{biosample_synonyms} } ); print "\n"; } } sub get_data_from_jsons { my ($json_dir) = @_; my %data; opendir( my $dir_h, $json_dir ); my @json_files = grep {/.json/} readdir $dir_h; if ( scalar @json_files == 0 ) { say STDERR "ERROR: No json files found in $json_dir"; exit 1; } for my $json_file (@json_files) { $data{$json_file} = json_file_to_perl( $json_dir . '/' . $json_file ); } return \%data; } sub check_mandatory_fields { my ( $json_file, $json_data ) = @_; my $multi_error_flag = 0; my @mandatory_fields = ( "accession", "md5sum", "funcgen.experimental_group", "funcgen.local_url", "funcgen.is_control", "replicate.biological_replicate_number", "replicate.experiment.assay_title", "replicate.experiment.biosample_term_name", "replicate.experiment.biosample_term_id", "replicate.experiment.target.label", "replicate.technical_replicate_number", ); for my $man_field (@mandatory_fields) { my $error_flag = 0; my @tiers = split /\./, $man_field; my $field = $json_data; for ( my $i = 0; $i <= $#tiers; $i++ ) { $field = $field->{ $tiers[$i] }; if ( !defined $field || length($field) == 0 ) { $error_flag = 1; $multi_error_flag = 1; } } say STDERR "ERROR: In file '$json_file' mandatory json attribute '$man_field' is not defined!" if $error_flag == 1; } if ($multi_error_flag) { say STDERR "Exiting... Please check this file: $json_file"; exit 1; } } sub usage { say STDERR "Usage: perl json2csv.pl <json_dir>"; say STDERR "Please set the directory which contains the json files"; }
Ensembl/ensembl-funcgen
scripts/tracking/json2csv.pl
Perl
apache-2.0
3,418
# # Copyright 2018 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::citrix::netscaler::snmp::mode::connections; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 0, message_separator => ' - ' } ]; $self->{maps_counters}->{global} = [ { label => 'active', set => { key_values => [ { name => 'active' } ], output_template => 'Active Server TCP connections : %s', perfdatas => [ { label => 'active_server', value => 'active_absolute', template => '%s', unit => 'con', min => 0 }, ], } }, { label => 'server', set => { key_values => [ { name => 'server' } ], output_template => 'Server TCP connections : %s', perfdatas => [ { label => 'server', value => 'server_absolute', template => '%s', unit => 'con', min => 0 }, ], } }, { label => 'client', set => { key_values => [ { name => 'client' } ], output_template => 'Client TCP connections : %s', perfdatas => [ { label => 'client', value => 'client_absolute', template => '%s', unit => 'con', min => 0 }, ], } }, ]; } 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 => { }); return $self; } sub manage_selection { my ($self, %options) = @_; $self->{global} = { client => 0, server => 0, active => 0 }; my $oid_tcpCurServerConn = '.1.3.6.1.4.1.5951.4.1.1.46.1.0'; my $oid_tcpCurClientConn = '.1.3.6.1.4.1.5951.4.1.1.46.2.0'; my $oid_tcpActiveServerConn = '.1.3.6.1.4.1.5951.4.1.1.46.8.0'; my $result = $options{snmp}->get_leef(oids => [$oid_tcpCurServerConn, $oid_tcpCurClientConn, $oid_tcpActiveServerConn ], nothing_quit => 1); $self->{global}->{client} = $result->{$oid_tcpCurClientConn}; $self->{global}->{server} = $result->{$oid_tcpCurServerConn}; $self->{global}->{active} = $result->{$oid_tcpActiveServerConn}; } 1; __END__ =head1 MODE Check connections usage (Client, Server, ActiveServer) (NS-ROOT-MIBv2). =over 8 =item B<--warning-*> Threshold warning. Can be: 'server', 'active', 'client'. =item B<--critical-*> Threshold critical. Can be: 'server', 'active', 'client'. =back =cut
wilfriedcomte/centreon-plugins
network/citrix/netscaler/snmp/mode/connections.pm
Perl
apache-2.0
3,521
# # 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 storage::oracle::zs::restapi::mode::components::cpu; use strict; use warnings; sub check { my ($self) = @_; $self->{output}->output_add(long_msg => 'checking cpu'); $self->{components}->{cpu} = { name => 'cpu', total => 0, skip => 0 }; return if ($self->check_filter(section => 'cpu')); foreach my $chassis (values %{$self->{results}}) { foreach (@{$chassis->{cpu}}) { my $instance = $chassis->{name} . ':' . $_->{label}; next if ($self->check_filter(section => 'cpu', instance => $instance)); $self->{components}->{cpu}->{total}++; my $status = $_->{faulted} ? 'faulted' : 'ok'; $self->{output}->output_add( long_msg => sprintf( "cpu '%s' status is '%s' [instance = %s]", $instance, $status, $instance, ) ); my $exit = $self->get_severity(label => 'default', section => 'cpu', value => $status); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf("Cpu '%s' status is '%s'", $instance, $status) ); } } } } 1;
Tpo76/centreon-plugins
storage/oracle/zs/restapi/mode/components/cpu.pm
Perl
apache-2.0
2,091
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package storage::netapp::ontap::restapi::mode::components::shelf; use strict; use warnings; sub load {} sub check { my ($self) = @_; $self->{output}->output_add(long_msg => 'checking shelfs'); $self->{components}->{shelf} = { name => 'shelfs', total => 0, skip => 0 }; return if ($self->check_filter(section => 'shelf')); return if (!defined($self->{json_results}->{records})); foreach my $shelf (@{$self->{json_results}->{records}}) { my $shelf_instance = $shelf->{serial_number}; my $shelf_name = $shelf->{name}; next if ($self->check_filter(section => 'shelf', instance => $shelf_instance)); $self->{components}->{shelf}->{total}++; $self->{output}->output_add( long_msg => sprintf( "shelf '%s' state is '%s' [instance: %s]", $shelf_name, $shelf->{state}, $shelf_instance ) ); my $exit = $self->get_severity(label => 'state', section => 'shelf', value => $shelf->{state}); if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { $self->{output}->output_add( severity => $exit, short_msg => sprintf( "Shelf '%s' state is '%s'", $shelf_name, $shelf->{state} ) ); } } } 1;
centreon/centreon-plugins
storage/netapp/ontap/restapi/mode/components/shelf.pm
Perl
apache-2.0
2,198
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package cloud::azure::network::cdn::mode::latency; use base qw(cloud::azure::custom::mode); use strict; use warnings; sub get_metrics_mapping { my ($self, %options) = @_; my $metrics_mapping = { 'totallatency' => { 'output' => 'Total Latency', 'label' => 'total-latency', 'nlabel' => 'cdn.latency.total.milliseconds', 'unit' => 'ms', 'min' => '0', 'max' => '' } }; return $metrics_mapping; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { 'filter-metric:s' => { name => 'filter_metric' }, 'resource:s' => { name => 'resource' }, 'resource-group:s' => { name => 'resource_group' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{resource}) || $self->{option_results}->{resource} eq '') { $self->{output}->add_option_msg(short_msg => 'Need to specify either --resource <name> with --resource-group option or --resource <id>.'); $self->{output}->option_exit(); } my $resource = $self->{option_results}->{resource}; my $resource_group = defined($self->{option_results}->{resource_group}) ? $self->{option_results}->{resource_group} : ''; if ($resource =~ /^\/subscriptions\/.*\/resourceGroups\/(.*)\/providers\/Microsoft\.Cdn\/profiles\/(.*)$/) { $resource_group = $1; $resource = $2; } $self->{az_resource} = $resource; $self->{az_resource_group} = $resource_group; $self->{az_resource_type} = 'profiles'; $self->{az_resource_namespace} = 'Microsoft.Cdn'; $self->{az_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 900; $self->{az_interval} = defined($self->{option_results}->{interval}) ? $self->{option_results}->{interval} : 'PT5M'; $self->{az_aggregations} = ['Average']; if (defined($self->{option_results}->{aggregation})) { $self->{az_aggregations} = []; foreach my $stat (@{$self->{option_results}->{aggregation}}) { if ($stat ne '') { push @{$self->{az_aggregations}}, ucfirst(lc($stat)); } } } foreach my $metric (keys %{$self->{metrics_mapping}}) { next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne '' && $metric !~ /$self->{option_results}->{filter_metric}/); push @{$self->{az_metrics}}, $metric; } } 1; __END__ =head1 MODE Check Azure CDN latency. Example: Using resource name : perl centreon_plugins.pl --plugin=cloud::azure::network::cdn::plugin --mode=latency --custommode=api --resource=<cdn_id> --resource-group=<resourcegroup_id> --aggregation='average' --warning-total-latency='50' --critical-total-latency='100' Using resource id : perl centreon_plugins.pl --plugin=cloud::azure::network::cdn::plugin --mode=latency --custommode=api --resource='/subscriptions/<subscription_id>/resourceGroups/<resourcegroup_id>/providers/Microsoft.Cdn/profiles/<cdn_id>' --aggregation='average' --warning-total-latency='50' --critical-total-latency='100' Default aggregation: 'average' / 'minimum', 'maximum' and 'total' are valid. =over 8 =item B<--resource> Set resource name or id (Required). =item B<--resource-group> Set resource group (Required if resource's name is used). =item B<--warning-total-latency> Warning threshold. =item B<--critical-total-latency> Critical threshold. =back =cut
Tpo76/centreon-plugins
cloud/azure/network/cdn/mode/latency.pm
Perl
apache-2.0
4,514
#!/usr/local/bin/perl use strict; use Bio::EnsEMBL::Registry; Bio::EnsEMBL::Registry->load_registry_from_db (-host=>"ensembldb.ensembl.org", -user=>"anonymous", -db_version=>'58'); my $human_gene_adaptor = Bio::EnsEMBL::Registry->get_adaptor ("Homo sapiens", "core", "Gene"); my $member_adaptor = Bio::EnsEMBL::Registry->get_adaptor ("Compara", "compara", "Member"); my $homology_adaptor = Bio::EnsEMBL::Registry->get_adaptor ("Compara", "compara", "Homology"); my $proteintree_adaptor = Bio::EnsEMBL::Registry->get_adaptor ("Compara", "compara", "ProteinTree"); my $mlss_adaptor = Bio::EnsEMBL::Registry->get_adaptor ("Compara", "compara", "MethodLinkSpeciesSet"); my $genes = $human_gene_adaptor-> fetch_all_by_external_name('BRCA2'); my $verbose = 0; foreach my $gene (@$genes) { my $member = $member_adaptor-> fetch_by_source_stable_id("ENSEMBLGENE",$gene->stable_id); die "no members" unless (defined $member); my $all_homologies = $homology_adaptor->fetch_by_Member($member); foreach my $homology (@$all_homologies) { my @two_ids = map { $_->get_canonical_peptide_Member->member_id } @{$homology->gene_list}; my $leaf_node_id = $homology->node_id; my $tree = $proteintree_adaptor->fetch_node_by_node_id($leaf_node_id); my $node_a = $proteintree_adaptor->fetch_AlignedMember_by_member_id_root_id($two_ids[0],1); my $node_b = $proteintree_adaptor->fetch_AlignedMember_by_member_id_root_id($two_ids[1],1); my $root = $node_a->subroot; $root->merge_node_via_shared_ancestor($node_b); my $ancestor = $node_a->find_first_shared_ancestor($node_b); $ancestor->print_tree(20) if ($verbose); my $distance_a = $node_a->distance_to_ancestor($ancestor); my $distance_b = $node_b->distance_to_ancestor($ancestor); print $node_a->stable_id, ",", $node_b->stable_id, ",", $ancestor->get_tagvalue("taxon_name"), ",", $ancestor->get_tagvalue("taxon_alias_mya"), ",", $distance_a, ",", $distance_b, "\n"; } }
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-compara/scripts/examples/homology12.pl
Perl
apache-2.0
2,053
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::ruckus::scg::snmp::mode::listssids; 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 => { "filter-name:s" => { name => 'filter_name' }, }); $self->{ssid} = {}; return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } my $mapping = { ruckusSCGWLANSSID => { oid => '.1.3.6.1.4.1.25053.1.3.2.1.1.1.2.1.1' }, ruckusSCGWLANZone => { oid => '.1.3.6.1.4.1.25053.1.3.2.1.1.1.2.1.2' }, ruckusSCGWLANDomain => { oid => '.1.3.6.1.4.1.25053.1.3.2.1.1.1.2.1.3' }, ruckusSCGWLANAuthType => { oid => '.1.3.6.1.4.1.25053.1.3.2.1.1.1.2.1.17' }, }; sub manage_selection { my ($self, %options) = @_; my $snmp_result = $options{snmp}->get_multiple_table(oids => [ { oid => $mapping->{ruckusSCGWLANSSID}->{oid} }, { oid => $mapping->{ruckusSCGWLANZone}->{oid} }, { oid => $mapping->{ruckusSCGWLANDomain}->{oid} }, { oid => $mapping->{ruckusSCGWLANAuthType}->{oid} }, ], return_type => 1, nothing_quit => 1); foreach my $oid (keys %$snmp_result) { next if ($oid !~ /^$mapping->{ruckusSCGWLANSSID}->{oid}\.(.*)$/); my $instance = $1; my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $instance); if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $result->{ruckusSCGWLANSSID} !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping '" . $result->{ruckusSCGWLANSSID} . "': no matching filter.", debug => 1); next; } $self->{ssid}->{$instance} = { name => $result->{ruckusSCGWLANSSID}, zone => $result->{ruckusSCGWLANZone}, domain => $result->{ruckusSCGWLANDomain}, authentication => $result->{ruckusSCGWLANAuthType} }; } } sub run { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $instance (sort keys %{$self->{ssid}}) { $self->{output}->output_add(long_msg => '[name = ' . $self->{ssid}->{$instance}->{name} . "] [zone = " . $self->{ssid}->{$instance}->{zone} . "] [domain = " . $self->{ssid}->{$instance}->{domain} . "] [authentication = " . $self->{ssid}->{$instance}->{authentication} . "]" ); } $self->{output}->output_add(severity => 'OK', short_msg => 'List SSIDs:'); $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', 'zone', 'domain', 'authentication']); } sub disco_show { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $instance (sort keys %{$self->{ssid}}) { $self->{output}->add_disco_entry( name => $self->{ssid}->{$instance}->{name}, zone => $self->{ssid}->{$instance}->{zone}, domain => $self->{ssid}->{$instance}->{domain}, authentication => $self->{ssid}->{$instance}->{authentication}); } } 1; __END__ =head1 MODE List SSIDs. =over 8 =item B<--filter-name> Filter by SSID name (can be a regexp). =back =cut
centreon/centreon-plugins
network/ruckus/scg/snmp/mode/listssids.pm
Perl
apache-2.0
4,763
package Paws::ECS::ListContainerInstances; use Moose; has Cluster => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'cluster' ); has Filter => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'filter' ); has MaxResults => (is => 'ro', isa => 'Int', traits => ['NameInRequest'], request_name => 'maxResults' ); has NextToken => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'nextToken' ); has Status => (is => 'ro', isa => 'Str', traits => ['NameInRequest'], request_name => 'status' ); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'ListContainerInstances'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::ECS::ListContainerInstancesResponse'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::ECS::ListContainerInstances - Arguments for method ListContainerInstances on Paws::ECS =head1 DESCRIPTION This class represents the parameters used for calling the method ListContainerInstances on the Amazon EC2 Container Service service. Use the attributes of this class as arguments to method ListContainerInstances. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ListContainerInstances. As an example: $service_obj->ListContainerInstances(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 Cluster => Str The short name or full Amazon Resource Name (ARN) of the cluster that hosts the container instances to list. If you do not specify a cluster, the default cluster is assumed. =head2 Filter => Str You can filter the results of a C<ListContainerInstances> operation with cluster query language statements. For more information, see Cluster Query Language in the I<Amazon EC2 Container Service Developer Guide>. =head2 MaxResults => Int The maximum number of container instance results returned by C<ListContainerInstances> in paginated output. When this parameter is used, C<ListContainerInstances> only returns C<maxResults> results in a single page along with a C<nextToken> response element. The remaining results of the initial request can be seen by sending another C<ListContainerInstances> request with the returned C<nextToken> value. This value can be between 1 and 100. If this parameter is not used, then C<ListContainerInstances> returns up to 100 results and a C<nextToken> value if applicable. =head2 NextToken => Str The C<nextToken> value returned from a previous paginated C<ListContainerInstances> request where C<maxResults> was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the C<nextToken> value. This value is C<null> when there are no more results to return. This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes. =head2 Status => Str Filters the container instances by status. For example, if you specify the C<DRAINING> status, the results include only container instances that have been set to C<DRAINING> using UpdateContainerInstancesState. If you do not specify this parameter, the default is to include container instances set to C<ACTIVE> and C<DRAINING>. Valid values are: C<"ACTIVE">, C<"DRAINING"> =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method ListContainerInstances in L<Paws::ECS> =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/ECS/ListContainerInstances.pm
Perl
apache-2.0
3,994
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2021] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; =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 warnings; use DBI; use Getopt::Long; my $host; my $port = 3306; my $user; my $pass; my $pattern; my $attrib_file; my $dry_run; my $help; GetOptions( "host=s" => \$host, "port=i" => \$port, "user=s" => \$user, "pass=s" => \$pass, "pattern=s" => \$pattern, "attrib_file=s" => \$attrib_file, "dry_run" => \$dry_run, "help|h" => \$help, ); unless ($host && $user && $pattern && $attrib_file) { print "Missing required parameter...\n" unless $help; $help = 1; } if ($help) { print "Usage: $0 --host <host> --port <port> --user <user> --pass <pass> --pattern <pattern> --attrib_file <attrib_sql_file> --dry_run --help\n"; exit(0); } unless (-e $attrib_file) { die "Can't see file: '$attrib_file'\n"; } my $dbh = DBI->connect( "DBI:mysql:host=$host;port=$port", $user, $pass, ); my $sth = $dbh->prepare("SHOW DATABASES LIKE '$pattern'"); $sth->execute; while (my ($db) = $sth->fetchrow_array) { my $cmd = "mysql --host=$host --port=$port --user=$user --pass=$pass --database=$db < $attrib_file"; print "CMD: $cmd\n"; unless ($dry_run) { my $rc = system($cmd); if ($rc != 0) { die "command failed..."; } } }
Ensembl/ensembl-variation
scripts/misc/add_attrib_entries.pl
Perl
apache-2.0
2,258
# # Copyright 2021 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package cloud::prometheus::direct::kubernetes::plugin; use strict; use warnings; use base qw(centreon::plugins::script_custom); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '0.1'; %{$self->{modes}} = ( 'container-status' => 'cloud::prometheus::direct::kubernetes::mode::containerstatus', 'daemonset-status' => 'cloud::prometheus::direct::kubernetes::mode::daemonsetstatus', 'deployment-status' => 'cloud::prometheus::direct::kubernetes::mode::deploymentstatus', 'list-containers' => 'cloud::prometheus::direct::kubernetes::mode::listcontainers', 'list-daemonsets' => 'cloud::prometheus::direct::kubernetes::mode::listdaemonsets', 'list-deployments' => 'cloud::prometheus::direct::kubernetes::mode::listdeployments', 'list-namespaces' => 'cloud::prometheus::direct::kubernetes::mode::listnamespaces', 'list-nodes' => 'cloud::prometheus::direct::kubernetes::mode::listnodes', 'list-services' => 'cloud::prometheus::direct::kubernetes::mode::listservices', 'namespace-status' => 'cloud::prometheus::direct::kubernetes::mode::namespacestatus', 'node-status' => 'cloud::prometheus::direct::kubernetes::mode::nodestatus', ); $self->{custom_modes}{api} = 'cloud::prometheus::restapi::custom::api'; return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Kubernetes metrics through Prometheus server using the Kubernetes kube-state-metrics add-on agent. =cut
Tpo76/centreon-plugins
cloud/prometheus/direct/kubernetes/plugin.pm
Perl
apache-2.0
2,456
package DocSet::RunTime; # META: this class acts as Singleton, consider to actually use # Class::Singleton use strict; use warnings; use File::Spec::Functions qw(catdir catfile splitdir); use File::Find; use DocSet::Util; use Carp; use vars qw(@ISA @EXPORT %opts); @ISA = qw(Exporter); @EXPORT = qw(get_opts find_src_doc set_render_obj get_render_obj unset_render_obj); my %registers = (); my @search_paths = (); my %src_docs = (); my %exts = (); my $render_obj; sub registers_reset { %registers = (); } sub register { my ($register, $key, $val) = @_; push @{$registers{$register}{$key}}, $val; return @{ $registers{$register}{$key} || []}; } sub set_opt { my (%args) = (); if (@_ == 1) { my $arg = shift; my $ref = ref $arg; if ($ref) { %args = $ref eq 'HASH' ? %$arg : @$arg; } else { die "must be a ref to or an array/hash"; } } else { %args = @_; } @opts{keys %args} = values %args; } sub get_opts { my $opt = shift; exists $opts{$opt} ? $opts{$opt} : ''; } # check whether we have a Storable avalable use constant HAS_STORABLE => eval { require Storable; }; sub has_storable_module { return HAS_STORABLE; } # check for existence of html2ps and ps2pdf my $html2ps_exec = which('html2ps'); sub can_create_ps { # ps2html is bundled, so we can always create PS return $html2ps_exec if $html2ps_exec; print 'It seems that you do not have html2ps installed! You have', 'to install it if you want to generate the PDF file'; return 0; # if you unbundle it make sure you write here a code similar to # can_create_pdf() } my $ps2pdf_exec = which('ps2pdf'); sub can_create_pdf { # check whether ps2pdf exists return $ps2pdf_exec if $ps2pdf_exec; print 'It seems that you do not have ps2pdf installed! You have', 'to install it if you want to generate the PDF file'; return 0; } sub scan_src_docs { my ($base, $ra_search_paths, $ra_search_exts) = @_; @search_paths = @{$ra_search_paths || []}; # .cfg is for matching config.cfg to become index.html %exts = map {$_ => 1} @{$ra_search_exts || []}, 'cfg'; my @ext_accept_pattern = map {quotemeta($_)."\$"} keys %exts; my $rsub_keep_ext = build_matchmany_sub(\@ext_accept_pattern); my %seen; for my $rel_path (@search_paths) { my $full_base_path = catdir $base, $rel_path; die "'search_paths' attr: $full_base_path is not a dir" unless -d $full_base_path; my @seen_pattern = map {"^".quotemeta($_)} keys %seen; my $rsub_skip_seen = build_matchmany_sub(\@seen_pattern); my $rel_uri = path2uri($rel_path); $src_docs{$rel_uri} = { # autogenerated index.html map { s/config\.cfg$/index.html/; ($_ => 1) } # full path => relative uri map path2uri( DocSet::Util::abs2rel($_, $full_base_path) ), grep $rsub_keep_ext->($_), # get files with wanted exts grep !$rsub_skip_seen->($_), # skip seen base dirs @{ expand_dir($full_base_path) } }; note "Scanning for src files: $full_base_path"; $seen{$full_base_path}++; } # dumper \%src_docs; } # this function returns a URI, so its separators are always / sub find_src_doc { my ($resource_rel_path) = @_; # push the html extension, because of autogenerated index.html, # which should be found automatically $exts{html} = 1 unless exists $exts{html}; for my $path (keys %src_docs) { if (my $found_path = match_in_doc_src_subset($path, $resource_rel_path)) { return path2uri($found_path); } } # if we didn't find anything so far, it's possible that the path was # specified with a longer prefix, that was needed (the above # searches only the end leaves), so try locate the segments of the # search path and search within maching sub-sets for my $path (@search_paths) { if ($resource_rel_path =~ m|^$path/(.*)|) { if (my $found_path = match_in_doc_src_subset($path, $1)) { return path2uri($found_path); } } } #dumper $src_docs{"docs/1.0"}; return; } # accepts the base_path (from the @search_paths) and the rel_path as # args, then it tries to find the match by applying known extensions. # # if matched, returns the whole path relative to the root, otherwise # returns undef sub match_in_doc_src_subset { my ($base_path, $rel_path) = @_; for my $ext (keys %exts) { #print qq{Try: $base_path :: $rel_path.$ext\n}; if (exists $src_docs{$base_path}{"$rel_path.$ext"}) { #print qq{Found $base_path/$rel_path.$ext\n}; return catdir $base_path, "$rel_path.$ext"; } } return; } # set render object: sort of Singleton, it'll complain aloud if the # object is set over the existing object, without first unsetting it sub set_render_obj { Carp::croak("usage: set_render_obj(\$obj) ") unless @_; Carp::croak("unset render_obj before setting a new one") if $render_obj; Carp::croak("undefined render_obj passed") unless defined $_[0]; $render_obj = shift; } sub get_render_obj { Carp::croak("render_obj is not available") unless $render_obj; return $render_obj; } sub unset_render_obj { Carp::croak("render_obj is not set") unless $render_obj; undef $render_obj; } 1; __END__ =head1 NAME C<DocSet::RunTime> - RunTime Configuration =head1 SYNOPSIS use DocSet::RunTime; # run time options DocSet::RunTime::set_opt(\%args); if (get_opts('verbose') { print "verbose mode"; } # hosting system capabilities testing DocSet::RunTime::has_storable_module(); DocSet::RunTime::can_create_ps(); DocSet::RunTime::can_create_pdf(); # source documents lookup DocSet::RunTime::scan_src_docs($base_path, \@search_paths, \@search_exts); my $full_src_path = find_src_doc($resource_rel_path); # rendering object singleton set_render_obj($obj); unset_render_obj(); $obj = get_render_obj(); =head1 DESCRIPTION This module is a part of the docset application, and it stores the run time arguments, caches results of expensive calls and provide Singleton-like service to the whole system. =head1 FUNCTIONS META: To be completed, see SYNOPSIS =head2 Run Time Options Only get_opts() method is exported by default. =over =item * registers_reset() This function resets various run-time registers, used for validations. If the runtime is run more than once remember to always run first this function and even better always run it before using the runtime. e.g.: DocSet::RunTime::registers_reset(); my $docset = DocSet::DocSet::HTML->new($config_file); $docset->set_dir(abs_root => "."); $docset->scan; $docset->render; =item * register my @entries = register($register_name, $key, $val); Push into the register for a given key the supplied value. Return an array of the given register's key. For example used to track duplicated docset ids with: my @entries = DocSet::RunTime::register('unique_docset_id', $id, $self->{config_file}); die if @entries > 1; because if the register returns two value for the same key, someone has already registered that key before. The values in C<@entries> include the config files in this example. =item * set_opt(\%args) =item * get_opts() =back =head2 Hosting System Capabilities Testing These methods test the capability of the system and are a part of the runtime system to perform the checking only once. =over =item * has_storable_module =item * can_create_ps =item * can_create_pdf =back =head2 Source Documents Lookup A system for mapping L<> escapes to the located of the rendered files. This system scans once the C<@search_paths> for files with C<@search_exts> starting from C<$base_path> using scan_src_docs(). The C<@search_paths> and C<@search_exts> are configured in the I<config.cfg> file. For example: dir => { # search path for pods, etc. must put more specific paths first! search_paths => [qw( foo/bar foo . )], # what extensions to search for search_exts => [qw(pod pm html)], }, So for example if the base path is I<~/myproject/src>, the files with extensions I<.pod>, I<.pm> and I<.html> will be searched in I<~/myproject/src/foo/bar>, I<~/myproject/src/foo> and I<~/myproject/src>. Notice that you must specify more specific paths first, since for optimization the seen paths are skipped. Therefore in our example the more explicit path I<foo/bar> was listed before the more general I<foo>. When the POD parser finds a L<> sequence it indentifies the resource part and passes it to the find_src_doc() which looks up for this file in the cache and returns its original (src) location, which can be then easily converted to the final location and optionally adjusting the extension, e.g. when the POD file is converted to HTML. As a special extension this function automatically assumes that C<index.html> will be generated in each directory containing items of an interest. Therefore in find_src_doc() it'll automatically find things like: L<the guide|guide::index>, even though there was no source I<index.pod> or I<index.html> in first place. Only the find_src_doc() function is exported by default. =over =item * scan_src_docs($base_path, \@search_paths, \@search_exts); =item * find_src_doc($resource_rel_path); returns C<undef> if nothing was found. See the description above. =back =head2 Rendering Object Singleton Since the rendering process may happen by a third party system, into which we provide hooks or overload some of its methods, it's quite possible that we won't be able to access the current document (or better rendering) object. One solution would be to have a global package variable, but that's very error-prone. Therefore the used solution is to provide a hook into a RunTime environment setting the current rendering object when the rendering of a single page starts via C<set_render_obj($obj)> and unsetting it when it's finished via unset_render_obj(). Between these two moments the current rendering object can be retrieved with get_render_obj() method. Notice that this is all possible in the program which is not threaded, or/and only one rendering process exists at any given time from its start to its end. All three methods are exported by default. =over =item * set_render_obj($obj) Sets the current rendering object. You cannot set a new rendering object before the previous one is unset. This is in order to make sure that one document won't use by mistake a rendering object of another document. So when the rendering is done remember to call the unset_render_obj() function. =item * unset_render_obj() Unsets the currently set rendering object. =item * get_render_obj() Retrieves the currently set rendering object or complains aloud if it cannot find one. =back =head1 AUTHORS Stas Bekman E<lt>stas (at) stason.orgE<gt> =cut
Distrotech/mod_perl
docs/lib/DocSet/RunTime.pm
Perl
apache-2.0
11,335
#! /usr/bin/env perl use strict; use warnings; use FindBin qw($Bin); die "Please specify path to xml files" unless $ARGV[0]; my $files = qx{ find $ARGV[0] -name \\*_Phenotype.xml -or -name \\*_Gene.xml -and -not -name \\*_otherfeatures_\\* }; my %doc; foreach my $file (split("\n",$files)) { chomp $file; print STDERR "Examining $file\n"; unless(open(FILE,$file)) { print STDERR "No such file '$file'\n"; next; } while(<FILE>) { if(/<doc/) { %doc = (); } elsif(/<field name="feature_type">(.*?)<\/field>/) { $doc{'type'} = $1; } elsif(/<field name="species_name">(.*?)<\/field>/) { $doc{'species'} = $1; } elsif(/<field name="name">(.*?)<\/field>/) { $doc{'name'} = $1; } elsif(/<field name="id">(.*?)<\/field>/) { $doc{'id'} = $1; } elsif(/<field name="domain_url">(.*?)<\/field>/) { $doc{'url'} = $1; } elsif(/<\/doc/) { next unless $doc{'type'} eq 'Gene' or $doc{'type'} eq 'Phenotype'; next unless $doc{'name'} and $doc{'species'} and $doc{'url'}; $doc{'species'} = lc($doc{'species'}); $doc{'lcname'} = lc($doc{'name'}); if($doc{'type'} eq 'Gene') { $doc{'url'} =~ s/^.*&amp;db=/db=/; $doc{'rest'} = $doc{'url'}; } else { $doc{'rest'} = ''; } my @out = map { $doc{$_} } qw(species lcname type id name rest); print join('__',map { s/_/_+/g; s/\s+/_-/g; $_; } @out)."\n"; } } close FILE; } 1;
Ensembl/ensembl-webcode
utils/indexing/autocomplete/build_direct.pl
Perl
apache-2.0
1,435
#!/usr/bin/perl use strict; use encoding 'utf8'; use Data::Dumper; use Errno; use IO::Handle; =head1 NAME Vaam - An interface to the (V)ariant-(a)ware (a)pproximate (m)atcher =head1 SYNOPSIS my $vaam = new Vaam( distance => 1, dicFile => 'some_dict.mdic', patternFile => 'some_patterns.txt' ) my $answer = $vaam->lookup( "theyl" ); =head1 DESCRIPTION This module uses the binary 'vaamFilter' (originally written in c++) to provide a perl interface for Vaam. Comments, bug reports etc. are appreciated, write to: uli@cis.uni-muenchen.de =cut package Vaam; use IPC::Open2; =pod =head1 CONSTRUCTOR The new() constructor uses 'key => value' syntax for its arguments, where the keys 'dicFile' and 'patternFile' are obligatory. All allowed keys are: =over 3 =item B<dicFile> => 'some_dict.mdic' path to a .mdic dictionary file =item B<patternFile> => 'some_patterns.txt' path to a plaintext file defining a set of patterns with each line simply giving left and right side separated by a SPACE =item B<distance> => N to allow up to N standard-levenshtein edit operations (apart from the variant patterns). Defaults to 0. =item B<vaamBinary> => '/some/where/binary' to choose a binary path other than the one on the CIS installation =item B<minNrOfPatterns> => N Allow only interpretations with N or more pattern applications. Defaults to 0. =item B<maxNrOfPatterns> => N Allow only interpretations with at most N pattern applications. Defaults to infinite. =back =cut sub new { my $self = {}; ( my $class, %$self ) = @_; $self->{distance} = $self->{distance} || 0; if( ! $self->{vaamBinary} ) { my $defaultBinary = "/mounts/data/proj/impact/software/uli/x86_64/bin/vaamFilter"; if( $ENV{CPU} ne "x86_64" || !-f $defaultBinary ) { warn "Vaam.pm: default path to vaam executable seems not to fit here. Please specify 'vaamBinary' as option in the constructor"; return undef; } $self->{vaamBinary} = $defaultBinary; #print $self->{vaamBinary}, "\n"; exit; } if( !$self->{dicFile} || !$self->{patternFile} ) { warn "Perl::Vaam: provide arguments 'dicFile' and 'patternFile' as arguments for the constructor.\n"; return undef; } my $options =' --machineReadable=1'; if( defined ( $self->{maxNrOfPatterns} ) ) { $options .= " --maxNrOfPatterns=". $self->{maxNrOfPatterns}; } if( defined( $self->{minNrOfPatterns} ) ) { $options .= " --minNrOfPatterns=". $self->{minNrOfPatterns}; } my $binary = "$$self{vaamBinary} $options $self->{distance} $self->{dicFile} $self->{patternFile}"; print "$binary\n"; open2( $self->{BINARY_OUT}, $self->{BINARY_IN}, $binary ) or die "Perl::Vaam: $!"; if( defined $self->{encoding} ) { if( $self->{encoding} eq 'iso' ) { $self->{encoding} = 'bytes'; } } else { # if nothing is specified, use utf8 $self->{encoding} = 'utf8'; } binmode( $self->{BINARY_OUT}, ':'.$self->{encoding} ); binmode( $self->{BINARY_IN}, ':'.$self->{encoding} ); $self->{BINARY_OUT}->autoflush( 1 ); $self->{BINARY_IN}->autoflush( 1 ); my $statusMessage = readline( $self->{BINARY_OUT} ); chomp $statusMessage; if( $statusMessage !~ m/csl::Vaam.+READY/ ) { warn "Vaam.pm: Did not receive proper statusMessage from vaam executable"; return undef; } if( $statusMessage !~ m/machineReadable=true/ ) { warn "Vaam.pm: vaam executable seems not to be initialised in machine-readable mode"; return undef; } bless( $self, $class ); return $self; } =pod =head1 METHODS =over 1 =item setSlimMode( $bool ) set slimMode to true or false. In slimMode Vaam does not create an answer-object but just returns the string as it gets it from the binary. =cut sub setSlimMode { my( $self, $bool ) = @_; $self->{slimMode} = $bool; } =item lookup( $oldWord ) Returns a data-structure containing all found interpretations of $oldWord as a historical variant. =cut sub lookup { my($self, $word) = @_; print { $self->{BINARY_IN} } ( "$word\n" ); my $output = readline( $self->{BINARY_OUT} ); chomp $output; my @ints; my $answer = { query => $word, vaamString => $output }; $answer->{foundInLex} = 0; # this might be changed! $answer->{interpretations} = \@ints unless( $self->{slimMode} ); if( $output =~ m/\:NONE$/ ) { return $answer; } unless( $self->{slimMode} ) { for my $intString ( split( /\|/, $output ) ) { # for all interpretations my %int; my $instruction; if( ( $int{candidate}, $int{modernWord}, $instruction, $int{distance} ) = ( $intString =~ m/(.+?):(.+?)\+\[(.*?)\],dist=(.+?)/ ) ) { @{$int{instruction}} = (); # see that instruction is defined even if it remains empty while( $instruction =~ m/\((.*?):(.*?),(\d+)\)/g ) { # for all posPatterns of the instruction push( @{$int{instruction}}, { left => $1, right => $2, pos => $3 } ); } if( ! @{$int{instruction}} ) { $answer->{foundInLex} = 1; } push( @ints, \%int ); } else { # error?! } } } return( $answer ); } =item close() Close pipe to binary =cut sub close { close(BINARY_IN); close(BINARY_OUT); } =pod =back =head1 AUTHOR Ulrich Reffle<uli@cis.uni-muenchen.de>, 2008 =cut 1; __END__
ulir/FSDict
PERLLIB/CSL/Vaam.pm
Perl
apache-2.0
5,332
# # Copyright 2022 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package cloud::aws::elb::classic::mode::queues; use base qw(centreon::plugins::templates::counter); use strict; use warnings; my %metrics_mapping = ( 'SpilloverCount' => { # Average, Minimum, and Maximum are reported per load balancer node and are not typically useful. 'output' => 'Spillover Count', 'label' => 'spillovercount', 'nlabel' => 'elb.spillovercount.count', }, 'SurgeQueueLength' => { # Sum is not useful. 'output' => 'Surge Queue Length', 'label' => 'surgequeuelength', 'nlabel' => 'elb.surgequeuelength.count', }, ); my %map_type = ( "loadbalancer" => "LoadBalancerName", "availabilityzone" => "AvailabilityZone", ); sub prefix_metric_output { my ($self, %options) = @_; my $availability_zone = ""; if (defined($options{instance_value}->{availability_zone}) && $options{instance_value}->{availability_zone} ne '') { $availability_zone = "[$options{instance_value}->{availability_zone}] "; } return ucfirst($self->{option_results}->{type}) . " '" . $options{instance_value}->{display} . "' " . $availability_zone; } sub prefix_statistics_output { my ($self, %options) = @_; return "Statistic '" . $options{instance_value}->{display} . "' Metrics "; } sub long_output { my ($self, %options) = @_; my $availability_zone = ""; if (defined($options{instance_value}->{availability_zone}) && $options{instance_value}->{availability_zone} ne '') { $availability_zone = "[$options{instance_value}->{availability_zone}] "; } return "Checking " . ucfirst($self->{option_results}->{type}) . " '" . $options{instance_value}->{display} . "' " . $availability_zone; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'metrics', type => 3, cb_prefix_output => 'prefix_metric_output', cb_long_output => 'long_output', message_multiple => 'All elb metrics are ok', indent_long_output => ' ', group => [ { name => 'statistics', display_long => 1, cb_prefix_output => 'prefix_statistics_output', message_multiple => 'All metrics are ok', type => 1, skipped_code => { -10 => 1 } }, ] } ]; foreach my $metric (keys %metrics_mapping) { my $entry = { label => $metrics_mapping{$metric}->{label}, nlabel => $metrics_mapping{$metric}->{nlabel}, set => { key_values => [ { name => $metric }, { name => 'display' } ], output_template => $metrics_mapping{$metric}->{output} . ': %.2f', perfdatas => [ { value => $metric , template => '%.2f', label_extra_instance => 1 } ], } }; push @{$self->{maps_counters}->{statistics}}, $entry; } } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { "type:s" => { name => 'type' }, "name:s@" => { name => 'name' }, "availability-zone:s" => { name => 'availability_zone' }, "filter-metric:s" => { name => 'filter_metric' }, "statistic:s@" => { name => 'statistic' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{type}) || $self->{option_results}->{type} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --type option."); $self->{output}->option_exit(); } if ($self->{option_results}->{type} ne 'loadbalancer' && $self->{option_results}->{type} ne 'availabilityzone') { $self->{output}->add_option_msg(short_msg => "Instance type '" . $self->{option_results}->{type} . "' is not handled for this mode"); $self->{output}->option_exit(); } if ($self->{option_results}->{type} eq 'availabilityzone' && defined($self->{option_results}->{availability_zone})) { $self->{output}->add_option_msg(short_msg => "Can't specify --availability-zone option with availabilityzone instance's type"); $self->{output}->option_exit(); } if (!defined($self->{option_results}->{name}) || $self->{option_results}->{name} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --name option."); $self->{output}->option_exit(); } foreach my $instance (@{$self->{option_results}->{name}}) { if ($instance ne '') { push @{$self->{aws_instance}}, $instance; } } $self->{aws_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 600; $self->{aws_period} = defined($self->{option_results}->{period}) ? $self->{option_results}->{period} : 60; $self->{aws_statistics} = ['Sum', 'Maximum']; if (defined($self->{option_results}->{statistic})) { $self->{aws_statistics} = []; foreach my $stat (@{$self->{option_results}->{statistic}}) { if ($stat ne '') { push @{$self->{aws_statistics}}, ucfirst(lc($stat)); } } } foreach my $metric (keys %metrics_mapping) { next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne '' && $metric !~ /$self->{option_results}->{filter_metric}/); push @{$self->{aws_metrics}}, $metric; } } sub manage_selection { my ($self, %options) = @_; my %metric_results; foreach my $instance (@{$self->{aws_instance}}) { push @{$self->{aws_dimensions}}, { Name => $map_type{$self->{option_results}->{type}}, Value => $instance }; if (defined($self->{option_results}->{availability_zone}) && $self->{option_results}->{availability_zone} ne '') { push @{$self->{aws_dimensions}}, { Name => 'AvailabilityZone', Value => $self->{option_results}->{availability_zone} }; } $metric_results{$instance} = $options{custom}->cloudwatch_get_metrics( namespace => 'AWS/ELB', dimensions => $self->{aws_dimensions}, metrics => $self->{aws_metrics}, statistics => $self->{aws_statistics}, timeframe => $self->{aws_timeframe}, period => $self->{aws_period}, ); foreach my $metric (@{$self->{aws_metrics}}) { foreach my $statistic (@{$self->{aws_statistics}}) { next if (!defined($metric_results{$instance}->{$metric}->{lc($statistic)}) && !defined($self->{option_results}->{zeroed})); $self->{metrics}->{$instance}->{display} = $instance; $self->{metrics}->{$instance}->{availability_zone} = $self->{option_results}->{availability_zone}; $self->{metrics}->{$instance}->{statistics}->{lc($statistic)}->{display} = $statistic; $self->{metrics}->{$instance}->{statistics}->{lc($statistic)}->{$metric} = defined($metric_results{$instance}->{$metric}->{lc($statistic)}) ? $metric_results{$instance}->{$metric}->{lc($statistic)} : 0; } } } if (scalar(keys %{$self->{metrics}}) <= 0) { $self->{output}->add_option_msg(short_msg => 'No metrics. Check your options or use --zeroed option to set 0 on undefined values'); $self->{output}->option_exit(); } } 1; __END__ =head1 MODE Check Classic ELB surge queue. Example: perl centreon_plugins.pl --plugin=cloud::aws::elb::classic::plugin --custommode=paws --mode=queues --region='eu-west-1' --type='loadbalancer' --name='elb-www-fr' --critical-spillovercount-sum='10' --verbose See 'https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-cloudwatch-metrics.html' for more informations. Default statistic: 'sum', 'maximum' / Most usefull statistics: SpilloverCount: 'sum', SurgeQueueLength: 'maximum'. =over 8 =item B<--type> Set the instance type (Required) (Can be: 'loadbalancer', 'availabilityzone'). =item B<--name> Set the instance name (Required) (Can be multiple). =item B<--availability-zone> Add Availability Zone dimension (only with --type='loadbalancer'). =item B<--filter-metric> Filter metrics (Can be: 'SpilloverCount', 'SurgeQueueLength') (Can be a regexp). =item B<--warning-*> B<--critical-*> Thresholds warning (Can be: 'spillovercount', 'surgequeuelength'). =back =cut
centreon/centreon-plugins
cloud/aws/elb/classic/mode/queues.pm
Perl
apache-2.0
9,353
use 5.008001; use strict; use warnings; package Metabase::Backend::MongoDB; our $VERSION = '1.000'; # VERSION use MongoDB; use Moose::Role; use namespace::autoclean; requires '_build_collection_name', '_ensure_index' ; # XXX eventually, do some validation on this -- dagolden, 2011-06-30 has 'host' => ( is => 'ro', isa => 'Str', default => 'mongodb://localhost:27017', required => 1, ); # XXX eventually, do some validation on this -- dagolden, 2011-06-30 has 'db_name' => ( is => 'ro', isa => 'Str', default => 'metabase', required => 1, ); # XXX eventually, do some validation on this -- dagolden, 2011-07-07 has 'collection_name' => ( is => 'ro', isa => 'Str', lazy => 1, builder => '_build_collection_name', ); # XXX eventually, do some validation on this -- dagolden, 2011-06-30 # e.g. if password,then also need non-empty username has ['username', 'password'] => ( is => 'ro', isa => 'Str', default => '', ); has 'connection' => ( is => 'ro', isa => 'MongoDB::Connection', lazy => 1, builder => '_build_connection', ); sub _build_connection { my $self = shift; return MongoDB::Connection->new( host => $self->host, $self->password ? ( db_name => $self->db_name, username => $self->username, password => $self->password, ) : (), ); } has 'coll' => ( is => 'ro', isa => 'MongoDB::Collection', lazy => 1, builder => '_build_coll', ); sub _build_coll { my $self = shift; my $coll = $self->connection ->get_database( $self->db_name ) ->get_collection( $self->collection_name ); $self->_ensure_index($coll); return $coll; } #--------------------------------------------------------------------------# sub _munge_keys { my ($self, $data, $from, $to) = @_; $from ||= '.'; $to ||= '|'; if ( ref $data eq 'HASH' ) { for my $key (keys %$data) { (my $new_key = $key) =~ s/\Q$from\E/$to/; $data->{$new_key} = delete $data->{$key}; } } else { $data =~ s/\Q$from\E/$to/; } return $data; } 1; # ABSTRACT: Metabase backend implemented using MongoDB # # This file is part of Metabase-Backend-MongoDB # # This software is Copyright (c) 2011 by David Golden. # # This is free software, licensed under: # # The Apache License, Version 2.0, January 2004 # __END__ =pod =head1 NAME Metabase::Backend::MongoDB - Metabase backend implemented using MongoDB =head1 VERSION version 1.000 =head1 SYNOPSIS use Metabase::Index::MongoDB; Metabase::Index::MongoDB->new( host => 'mongodb://localhost:27017', db_name => 'my_metabase', ); use Metabase::Archive::MongoDB; Metabase::Archive::MongoDB->new( host => 'mongodb://localhost:27017', db_name => 'my_metabase', ); =head1 DESCRIPTION This distribution provides a backend for L<Metabase> using MongoDB. There are two modules included, L<Metabase::Index::MongoDB> and L<Metabase::Archive::MongoDB>. They can be used separately or together (see L<Metabase::Librarian> for details). The L<Metabase::Backend::MongoDB> module is a L<Moose::Role> that provides common attributes and private helpers and is not intended to be used directly. Common attributes are described further below. =head1 ATTRIBUTES =head2 host A MongoDB connection string. Defaults to 'mongodb://localhost:27017'. =head2 db_name A database name. Defaults to 'metabase'. To avoid collision with other Metabase data on the same MongoDB server, users should always explicitly set this to a unique name for a given Metabase installation. =head2 collection_name A collection name for the archive or table. Defaults to 'metabase_index' or 'metabase_archive'. As long as the C<db_name> is unique, these defaults should be safe to use for most purposes. =head2 username A username for MongoDB authentication. By default, no username is used. =head2 password A password for MongoDB authentication. By default, no password is used. =head1 METHODS =head2 connection This returns the L<MongoDB::Connection> object that is created when the object is instantiated. =head2 coll This returns the L<MongoDB::Collection> object containing the index or archive data. =for Pod::Coverage method_names_here =for :stopwords cpan testmatrix url annocpan anno bugtracker rt cpants kwalitee diff irc mailto metadata placeholders metacpan =head1 SUPPORT =head2 Bugs / Feature Requests Please report any bugs or feature requests through the issue tracker at L<http://rt.cpan.org/Public/Dist/Display.html?Name=Metabase-Backend-MongoDB>. You will be notified automatically of any progress on your issue. =head2 Source Code This is open source software. The code repository is available for public review and contribution under the terms of the license. L<https://github.com/dagolden/metabase-backend-mongodb> git clone https://github.com/dagolden/metabase-backend-mongodb.git =head1 AUTHOR David Golden <dagolden@cpan.org> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2011 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut
gitpan/Metabase-Backend-MongoDB
lib/Metabase/Backend/MongoDB.pm
Perl
apache-2.0
5,199
package Google::Ads::AdWords::v201809::AudioError; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201809' }; our $XML_ATTRIBUTE_CLASS; undef $XML_ATTRIBUTE_CLASS; sub __get_attr_class { return $XML_ATTRIBUTE_CLASS; } use base qw(Google::Ads::AdWords::v201809::ApiError); # Variety: sequence use Class::Std::Fast::Storable constructor => 'none'; use base qw(Google::Ads::SOAP::Typelib::ComplexType); { # BLOCK to scope variables my %fieldPath_of :ATTR(:get<fieldPath>); my %fieldPathElements_of :ATTR(:get<fieldPathElements>); my %trigger_of :ATTR(:get<trigger>); my %errorString_of :ATTR(:get<errorString>); my %ApiError__Type_of :ATTR(:get<ApiError__Type>); my %reason_of :ATTR(:get<reason>); __PACKAGE__->_factory( [ qw( fieldPath fieldPathElements trigger errorString ApiError__Type reason ) ], { 'fieldPath' => \%fieldPath_of, 'fieldPathElements' => \%fieldPathElements_of, 'trigger' => \%trigger_of, 'errorString' => \%errorString_of, 'ApiError__Type' => \%ApiError__Type_of, 'reason' => \%reason_of, }, { 'fieldPath' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'fieldPathElements' => 'Google::Ads::AdWords::v201809::FieldPathElement', 'trigger' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'errorString' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'ApiError__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'reason' => 'Google::Ads::AdWords::v201809::AudioError::Reason', }, { 'fieldPath' => 'fieldPath', 'fieldPathElements' => 'fieldPathElements', 'trigger' => 'trigger', 'errorString' => 'errorString', 'ApiError__Type' => 'ApiError.Type', 'reason' => 'reason', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201809::AudioError =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType AudioError from the namespace https://adwords.google.com/api/adwords/cm/v201809. Error class for errors associated with parsing audio data. =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * reason =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
googleads/googleads-perl-lib
lib/Google/Ads/AdWords/v201809/AudioError.pm
Perl
apache-2.0
2,514
package Google::Ads::AdWords::v201402::Ad; use strict; use warnings; __PACKAGE__->_set_element_form_qualified(1); sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201402' }; 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 %id_of :ATTR(:get<id>); my %url_of :ATTR(:get<url>); my %displayUrl_of :ATTR(:get<displayUrl>); my %devicePreference_of :ATTR(:get<devicePreference>); my %Ad__Type_of :ATTR(:get<Ad__Type>); __PACKAGE__->_factory( [ qw( id url displayUrl devicePreference Ad__Type ) ], { 'id' => \%id_of, 'url' => \%url_of, 'displayUrl' => \%displayUrl_of, 'devicePreference' => \%devicePreference_of, 'Ad__Type' => \%Ad__Type_of, }, { 'id' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'url' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'displayUrl' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', 'devicePreference' => 'SOAP::WSDL::XSD::Typelib::Builtin::long', 'Ad__Type' => 'SOAP::WSDL::XSD::Typelib::Builtin::string', }, { 'id' => 'id', 'url' => 'url', 'displayUrl' => 'displayUrl', 'devicePreference' => 'devicePreference', 'Ad__Type' => 'Ad.Type', } ); } # end BLOCK 1; =pod =head1 NAME Google::Ads::AdWords::v201402::Ad =head1 DESCRIPTION Perl data type class for the XML Schema defined complexType Ad from the namespace https://adwords.google.com/api/adwords/cm/v201402. The base class of all ad types. To update basic ad fields, you can construct an {@code Ad} object (instead of the ad's concrete type) with the appropriate fields set. <span class="constraint AdxEnabled">This is enabled for AdX.</span> =head2 PROPERTIES The following properties may be accessed using get_PROPERTY / set_PROPERTY methods: =over =item * id =item * url =item * displayUrl =item * devicePreference =item * Ad__Type Note: The name of this property has been altered, because it didn't match perl's notion of variable/subroutine names. The altered name is used in perl code only, XML output uses the original name: Ad.Type =back =head1 METHODS =head2 new Constructor. The following data structure may be passed to new(): =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201402/Ad.pm
Perl
apache-2.0
2,528
:- module(compiler, [make_po/1, ensure_loaded/1, ensure_loaded/2, use_module/1, use_module/2, use_module/3, unload/1, set_debug_mode/1, set_nodebug_mode/1, set_debug_module/1, set_nodebug_module/1, set_debug_module_source/1, mode_of_module/2, module_of/2 ], [assertions]). :- use_module(library(system), [cd/1, working_directory/2]). :- use_module(library('compiler/c_itf_internal')). make_po([]) :- !. make_po([File|Files]) :- !, make_po_prot(File), make_po(Files). make_po(File) :- make_po_prot(File). %% make_po_prot is to avoid that when an exception is raised, %% the working directory be changed (EFM) make_po_prot(File) :- working_directory(W,W), catch(make_po1(File), Error, (cd(W), handle_exc(Error))). :- meta_predicate use_module(addmodule). use_module(Mod,This) :- use_module(Mod,all,This). :- meta_predicate use_module(+,addmodule). use_module(File, Imports, ByThisModule) :- cleanup_c_itf_data, use_mod(File, Imports, ByThisModule), check_static_module(File). :- meta_predicate ensure_loaded(addmodule). %JF[] ensure_loaded(File) :- ensure_loaded(File, ByThisModule) :- cleanup_c_itf_data, %JF[] use_mod_user(File), use_mod_user(File, ByThisModule), check_static_module(File). check_static_module(File) :- base_name(File, Base), defines_module(Base, Module), static_module(Module), !, message(note, ['module ',Module, ' already in executable, just made visible']). check_static_module(_). unload(File) :- unload_mod(File). set_debug_mode(File) :- absolute_file_name(File, Source), (interpret_file(Source), ! ; assertz_fact(interpret_file(Source))). set_nodebug_mode(File) :- absolute_file_name(File, Source), retractall_fact(interpret_file(Source)). set_debug_module(Mod) :- module_pattern(Mod, MPat), retractall_fact(interpret_srcdbg(MPat)), ( current_fact(interpret_module(MPat)), ! ; assertz_fact(interpret_module(MPat)) ). set_nodebug_module(Mod) :- module_pattern(Mod, MPat), retract_fact(interpret_module(MPat)), retractall_fact(interpret_srcdbg(MPat)). set_debug_module_source(Mod) :- module_pattern(Mod, MPat), assertz_fact(interpret_module(MPat)), ( current_fact(interpret_srcdbg(MPat)), ! ; assertz_fact(interpret_srcdbg(MPat)) ). module_pattern(user, user(_)) :- !. module_pattern(Module, Module) :- atom(Module). module_of(H, M) :- pred_module(H, M). mode_of_module(Module, Mode) :- module_loaded(Module, _, _, Mode).
leuschel/ecce
www/CiaoDE/ciao/lib/compiler/compiler.pl
Perl
apache-2.0
2,698
/*get_slots,get_class_instances,get_class_subclasses,get_class_superclasses,get_instance_types,get_slot_domain,get_slot_facets,get_slot_type,get_slot_value,get_slot_values,get_slot_values_in_detail,individual_p,instance_of_p,get_frame_details,member_slot_value_p,member_facet_value_p,get_facet_value,get_facet_values*/ /* Implementacion de las primitivas OKBC en Prolog de Edimburgo */ /* Version: 0.5 */ /* Author: Juan Pablo Perez Aldea */ /* Date: 12/3/2001 */ /* Comments: Faltan todavia unas tres operaciones.*/ /****************************************************************/ /* Primitivas OKBC */ /****************************************************************/ get_slots(Frame, L) :- find_slots(Frame, [], L). get_class_instances(C, L) :- class(C), find_instances(C, [], L). get_class_subclasses(C, direct, L) :- class(C), find_subclasses(C, [], L). get_class_subclasses(C, taxonomic, L) :- class(C), get_class_subclasses(C, direct, X), get_list_subclasses(X, X, L), !. get_class_superclasses(C, direct, L) :- class(C), find_superclasses(C, [], L). get_class_superclasses(C, taxonomic, L) :- class(C), get_class_superclasses(C, direct, X), get_list_superclasses(X, X, L), !. get_instance_types(Instance, L) :- find_instance_types(Instance, [], L). get_slot_domain(Slot,L) :- find_slot_domains(Slot, [], S), recorre2(S, S, L). get_slot_facets(Slot, L) :- find_facets(Slot, [], L). get_slot_type(Frame, Slot, own):- own_slot_of(Slot, Frame). get_slot_type(Frame, Slot, template):- template_slot_of(Slot, Frame). get_slot_value(Frame, Slot, X) :- slot_of(Slot, Frame), find_values(valor, Slot, [], [X|Xs]), unique([X|Xs]). get_slot_value(Frame, Slot, cardinality_violation) :- slot_of(Slot, Frame), find_values(valor, Slot, [], L), not(unique(L)), not(empty(L)). get_slot_values(Frame, Slot, L) :- slot_of(Slot, Frame), find_values(valor, Slot, [], L). get_slot_values_in_detail(Frame, Slot, L) :- get_facet_values(Frame, Slot, valor, L1), convierte_d(L1, [], L2), find_values_of_slot(Slot, L2, L3), convierte_nd(L3, [], L). individual_p(X) :- not(class(X)). instance_of_p(X, C) :- instance_of(X, C). get_frame_details(Frame, L) :- class(Frame), get_class_superclasses(Frame, Sup, taxonomic), get_class_subclasses(Frame, Sub, taxonomic), get_slots(Frame, Sl), introduce(Sl, [], X), introduce(Sub, X, Y), introduce(Sup, Y, Z), introduce([clase], Z, L). get_frame_details(Frame, L) :- instance_of(Frame, Y), get_slots(Frame, Sl), introduce(Sl, [], X), introduce([instancia], X, L). member_slot_value_p(Frame, Slot, Value) :- slot_of(Slot, Frame), find_values(valor, Slot, [], L), member(Value, L). member_facet_value_p(Frame, Slot, Facet, Value) :- slot_of(Slot, Frame), find_values(Facet, Slot, [], L), member(Value, L). get_facet_value(Frame, Slot, Facet, X) :- slot_of(Slot, Frame), find_values(Facet, Slot, [], [X|Xs]), unique([X|Xs]). get_facet_value(Frame, Slot, Facet, cardinality_violation) :- slot_of(Slot, Frame), find_values(Facet, Slot, [], L), not(unique(L)), not(empty(L)). get_facet_values(Frame, Slot, Facet, L) :- slot_of(Slot, Frame), find_values(Facet, Slot, [], L). /******************************************************************/ /* Predicados 'find_' */ /******************************************************************/ find_instances(C, I, L) :- instance_of(X, C), not(member(X, I)), find_instances(C, [X|I], L), !. find_instances(_, I, I). find_instance_types(C, I, L) :- type_of(X, C), not(member(X, I)), find_instances(C, [X|I], L), !. find_instance_types(_, I, I). find_subclasses(C, I, L) :- subclass_of(X, C), not(member(X, I)), find_subclasses(C, [X|I], L), !. find_subclasses(_, I, I). find_superclasses(C, I, L) :- superclass_of(X, C), not(member(X, I)), find_superclasses(C, [X|I], L), !. find_superclasses(_, I, I). find_values(F, S, I, L) :- value_of_facet_of(X, F, S), not(member(X, I)), find_values(F, S, [X|I], L), !. find_values(_, _, I, I). find_facets(S, I, L) :- facet_of(X, S), not(member(X, I)), find_facets(S, [X|I], L), !. find_facets(_, I, I). find_slots(F, I, L) :- slot_of(X, F), not(member(X, I)), find_slots(F, [X|I], L), !. find_slots(_, I, I). find_slot_domains(S, I, L) :- slot_of(S, X), not(member(X, I)), find_slot_domains(S, [X|I], L), !. find_slot_domains(_, I, I). find_values_of_slot(S, I, L) :- value_of_facet_of(X, valor, S), not(member(X, I)), find_subclasses(S, [X|I], L), !. find_values_of_slot(_, I, I). /******************************************************************/ /* Predicados 'get_list' */ /******************************************************************/ get_list_subclasses([], Y, Y). get_list_subclasses([X|Xs], Lista_Inicial, L) :- get_class_subclasses(X, taxonomic, Y), aplana(Y, Lista_Inicial, Z), get_list_subclasses(Xs, Z, L). get_list_superclasses([], Y, Y). get_list_superclasses([X|Xs], Lista_Inicial, L) :- get_class_superclasses(X, taxonomic, Y), aplana(Y, Lista_Inicial, Z), get_list_superclasses(Xs, Z, L). /********************************************************************/ /* OSCAR::: slot_of(X,Y) :- own_slot_of(X,Y). */ /* slot_of(X,Y) :- template_slot_of(X,Y). */ slot_of(X,Y) :- own_slot_of(X,Y). slot_of(X,Y) :- template_slot_of(X,Y). /******************************************************************/ /* Predicados auxiliares */ /******************************************************************/ not(Goal) :- call(Goal), !, fail. not(_). member(X, [X|_]). member(X, [_|Ys]) :- member(X, Ys). member_super(X, L) :- get_class_superclasses(X, taxonomic, S), recorre(S, L). recorre([X|_], L) :- member(X,L). recorre([_|Xs], L) :- recorre(Xs, L). recorre2([], S, S). recorre2([X|Xs], S, L) :- not(member_super(X, S)), recorre2(Xs, S, L). recorre2([X|Xs], S, L) :- member_super(X, S), quitar(X, S, R), recorre2(Xs, R, L). quitar(X, L, R) :- quitar(X, L, [], R). quitar(X, [X|Xs], L, R) :- reverse(L, L2), append(L2, Xs, R). quitar(X, [Y|Ys], L, R) :- quitar(X, Ys, [Y|L], R). aplana([], Ys, Ys). aplana([X|Xs], Ys, [X|Zs]) :- aplana(Xs, Ys, Zs). introduce(X, L, [X|L]). convierte_d([], L, L). convierte_nd([], L, L). /*convierte_d([X|Xs], Ys, L) :- convierte_d(Xs, [tupla(X,true,true)|Ys], L).*/ append([], Ys, Ys) :- list(Ys). append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs). list([]). list([_|Y]) :- list(Y). reverse(Xs, Ys) :- reverse(Xs, [], Ys). reverse([], Ys, Ys). reverse([X|Xs], Acc, Ys) :- reverse(Xs, [X|Acc], Ys). unique([_]). empty([]).
leuschel/ecce
www/CiaoDE/ciao/library/ontologies/iengine.pl
Perl
apache-2.0
7,401
# ************************************************************************* # Copyright (c) 2014-2017, SUSE LLC # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of SUSE LLC nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ************************************************************************* # # share/config/WWW_Config.pm # # Main configuration file # # MFILE_APPNAME # the name of this web front-end (no colons; must match the directory # name where application-specific JavaScript files are stored - e.g. # share/js/mfile-www) set( 'MFILE_APPNAME', 'mfile-www' ); # MFILE_WWW_DEBUG_MODE # turn debug-level log messages on and off set( 'MFILE_WWW_DEBUG_MODE', 1 ); # MFILE_WWW_HOST # hostname/IP address where WWW server will listen set( 'MFILE_WWW_HOST', 'localhost' ); # MFILE_WWW_PORT # port number where WWW server will listen set( 'MFILE_WWW_PORT', 5001 ); # MFILE_WWW_LOG_FILE # full path of logfile set( 'MFILE_WWW_LOG_FILE', $ENV{'HOME'} . "/.mfile-www.log" ); # MFILE_WWW_LOG_FILE_RESET # should the logfile be deleted/wiped/unlinked/reset before each use set( 'MFILE_WWW_LOG_FILE_RESET', 1 ); # MFILE_URI_MAX_LENGTH # see lib/App/MFILE/WWW/Resource.pm set( 'MFILE_URI_MAX_LENGTH', 1000 ); # MFILE_WWW_BYPASS_LOGIN_DIALOG # bypass the login dialog and use default login credentials (see next # param) set( 'MFILE_WWW_BYPASS_LOGIN_DIALOG', 1 ); # MFILE_WWW_DEFAULT_LOGIN_CREDENTIALS # when bypassing login dialog, use these credentials set( 'MFILE_WWW_DEFAULT_LOGIN_CREDENTIALS', { 'nam' => 'root', 'pwd' => 'root' } ); # MFILE_WWW_STANDALONE_CREDENTIALS_DATABASE set( 'MFILE_WWW_STANDALONE_CREDENTIALS_DATABASE', [ { 'nam' => 'root', 'pwd' => 'root', 'eid' => 1, 'priv' => 'admin', }, { 'nam' => 'demo', 'pwd' => 'demo', 'eid' => 2, 'priv' => 'passerby', }, ] ); # MFILE_WWW_LOGIN_DIALOG_CHALLENGE_TEXT # text displayed in the login dialog set( 'MFILE_WWW_LOGIN_DIALOG_CHALLENGE_TEXT', 'Enter your Innerweb credentials, or demo/demo' ); # MFILE_WWW_LOGIN_DIALOG_MAXLENGTH_USERNAME # see share/comp/auth.mi set( 'MFILE_WWW_LOGIN_DIALOG_MAXLENGTH_USERNAME', 20 ); # MFILE_WWW_LOGIN_DIALOG_MAXLENGTH_PASSWORD # see share/comp/auth.mi set( 'MFILE_WWW_LOGIN_DIALOG_MAXLENGTH_PASSWORD', 40 ); # MFILE_WWW_SESSION_EXPIRATION_TIME # number of seconds after which a session will be considered stale set( 'MFILE_WWW_SESSION_EXPIRATION_TIME', 3600 ); # MFILE_WWW_LOGOUT_MESSAGE # message that will be displayed for 1 second upon logout set( 'MFILE_WWW_LOGOUT_MESSAGE', '<br><br><br><br>App::MFILE::WWW over and out.<br><br>Have a lot of fun.<br><br><br><br>' ); # MFILE_WWW_DISPLAY_SESSION_DATA # controls whether session data will be displayed on all screens set( 'MFILE_WWW_DISPLAY_SESSION_DATA', 0 ); # JAVASCRIPT (REQUIREJS) # we use RequireJS to bring in dependencies - the following configuration # parameters are required to bring in RequireJS set( 'MFILE_WWW_JS_REQUIREJS', '/js/core/require.js' ); set( 'MFILE_WWW_REQUIREJS_BASEURL', '/js/core' ); # ----------------------------------- # DO NOT EDIT ANYTHING BELOW THIS LINE # ----------------------------------- use strict; use warnings; 1;
smithfarm/mfile-www
share/config/WWW_Config.pm
Perl
bsd-3-clause
4,685
package Persist::Tabular; use 5.008; use strict; use warnings; use Carp; use Getargs::Mixed; our $AUTOLOAD; our ( $VERSION ) = '$Revision: 1.11 $' =~ /\$Revision:\s+([^\s]+)/; =head1 NAME Persist::Tabular - Abstract base class for Persist::Table and Persist::Join =head1 SYNOPSIS See L<Persist::Tabular> and L<Persist::Join> for a synopsis of the functionality provided by Persist::Tabular. =head1 DESCRIPTION Provides functionality common to Persist::Table and Persist::Join. Specifically, the iterator functionality. =over =cut # =item $tabular = new Persist::Tabular($driver) # # Creates a new object using the given driver. # sub new { my ($class, $driver) = @_; my $self = bless {}, ref $class || $class; $self->{-driver} = $driver; $self; } # =item $self-E<gt>_open($reset) # # Tells the driver to open the appropriate object. # sub _open { die "Must be implemented by subclass."; } # =item $self-E<gt>_sync($reset) # # Saves any changes made since the last C<_sync>. # sub _sync { my ($self, $reset) = @_; $self->_open($reset); } =item $tabular-E<gt>first Moves the iterator position to the first row of the data set. This method should be used to reset the data position to the beginning. Either this method or C<next> must be called before data is accessed. If there are changes pending in the current row, then those changes are saved before moving the iterator position. This method should be avoided when possible as it may entail a greater performance cost associated with resetting cursors and such in the underlying driver. =cut sub first { my ($self, %args) = parameters('self', [qw(;bytable)], @_); $self->_sync; $self->{-data} = $self->{-driver}->first( -handle => $self->{-handle}, -bytable => $args{bytable}); $self->{-data} ? $self : undef; } =item $tabular-E<gt>next( [ $bytable ] ) Moves the iterator position to the next row of the data set. Either this method or C<first> must be called before data is accessed. This is the preferred method as it doesn't result in restarting calls which may involve resetting cursors, etc. in the driver's store. If there are changes pending in the current row, then those changes are saved before moving the iterator position. If the C<$bytable> option is set to true and this is a join, then this will not return a hash of all column-names pointing to values. Instead, this will return an array of hashes. Each element of the array will be the data corresponding to the respective table defined in during the call to C<join>. =cut sub next { my ($self, %args) = parameters('self', [qw(;bytable)], @_); $self->_sync; $self->{-data} = $self->{-driver}->next( -handle => $self->{-handle}, -bytable => $args{bytable}); $self->{-data} ? $self : undef; } =item $tabular-E<gt>filter($filter) Changes the filter or filters used to filter the data set and resets the driver handle. Either C<first> or C<next> must be called to access the data after this call is made. For information on the format of filters see L<Persist::Filter>. =cut sub filter { my ($self, %args) = parameters('self', [qw(filter)], @_); $self->{-filter} = $args{filter}; $self->_sync(1); $self; } =item $tabular-E<gt>order(\@order) Sets or changes the order columns are to be sorted and resets the driver handle. Either C<first> or C<next> must be called to access the data after this call is made. =cut sub order { my ($self, %args) = parameters('self', [qw(order)], @_); $self->{-order} = $args{order}; $self->_sync(1); $self; } =item $tabular-E<gt>offset($offset) Sets or changes the offset that the table uses and resets the driver handle. Either C<first> or C<next> must be called to access the data after this call is made. =cut sub offset { my ($self, %args) = parameters('self', [qw(offset)], @_); $self->{-offset} = $args{offset}; $self->_sync(1); $self; } =item $tabular-E<gt>limit($limit) Sets or changes the limit that the table uses and resets the driver handle. Either C<first> or C<next> must be called to access the data after this call is made. =cut sub limit { my ($self, %args) = parameters('self', [qw(limit)], @_); $self->{-limit} = $args{limit}; $self->_sync(1); $self; } =item $tabular-E<gt>options([ $filter, \@order, $offset, $limit ]) This allows a number of options on the table to be set at once and then resets the driver handle. Either C<first> or C<next> must be called to access the data after this call is made. =cut sub options { my ($self, %args) = parameters('self', [qw(;filter order offset limit)], @_); # Use exists to make sure we undef when they want us to! $self->{-filter} = $args{filter} if exists $args{filter}; $self->{-order} = $args{order} if exists $args{order}; $self->{-offset} = $args{offset} if exists $args{offset}; $self->{-limit} = $args{limit} if exists $args{limit}; $self->_sync(1); $self; } =item $tabular-E<gt>value($column) Reads the data found in the given column. Either C<first> or C<next> must have been called prior to the this. =cut sub value { my ($self, %args) = parameters('self', [qw(column)], @_); my $key = $args{column}; return $self->{-data}{$key}; } =item $tabular-E<gt>I<E<lt>columnE<gt>> Shortcut for of C<value> that returns the data found in the given column. =cut sub AUTOLOAD { my ($self) = @_; my ($key) = $AUTOLOAD =~ /::([^:]+)$/; $self->value($key); } sub DESTROY { # prevent AUTOLOAD from hooking } =back =head1 SEE ALSO L<Persist>, L<Persist::Join>, L<Persist::Table> =head1 AUTHOR Andrew Sterling Hanenkamp, E<lt>hanenkamp@users.sourceforge.netE<gt> =head1 COPYRIGHT AND LICENSE Copyright (c) 2003, Andrew Sterling Hanenkamp 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 Contentment 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. =cut 1
gitpan/persist
Persist/Tabular/Tabular.pm
Perl
bsd-3-clause
7,228
/* Part of XPCE --- The SWI-Prolog GUI toolkit Author: Jan Wielemaker and Anjo Anjewierden E-mail: jan@swi.psy.uva.nl WWW: http://www.swi.psy.uva.nl/projects/xpce/ Copyright (c) 1985-2002, University of Amsterdam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(emacs_cpp_mode, []). :- use_module(library(pce)). :- require([ forall/2 , ignore/1 ]). :- emacs_begin_mode(cpp, c, "Mode for (XPCE) C++ programs", [ pce_insert_include_files = button(pce), pce_collect_selectors = button(pce), pce_replace_selectors = button(pce), pce_unreplace_selectors = button(pce) ], []). from_pce('Arg', 'Pce'). from_pce('Object', 'Pce'). from_pce('Global', 'Pce'). from_pce('Status', 'Pce'). from_pce('Funcall', 'Call'). from_pce('Variable', 'Class'). from_pce('Receiver', 'Class'). from_pce('Cell', 'Chain'). from_pce('Pointer', 'Pointer'). canonicalise(Headers) :- forall(from_pce(F, T), ignore(send(Headers, replace, F, T))), send(Headers, sort), send(Headers, unique), ignore(send(Headers, move_after, 'Pce')). pce_insert_include_files(M) :-> "Collect the used Pce classes and insert includes":: get(M, collect, regex('#\\s*include\\s+<pce/([A-Za-z]+).h>'), 1, CE), canonicalise(CE), get(M, collect, regex('\\yPce([A-Z][a-zA-Z]*)'), 1, Ch), canonicalise(Ch), ( send(CE, equal, Ch) -> send(M, report, status, 'No changes necessary') ; send(Ch, for_all, message(M, insert, create(string, '#include <pce/%s.h>\n', @arg1))) ). pce_collect_selectors(M) :-> "Collect selectors and generate PcN... lines":: get(M, collect, regex('\\y(send|get)\\("(\\w+)"'), 2, Used), get(M, collect, regex('^PceArg\\s+\\yPcN(\\w+)\\y'), 1, Defined), ( send(Used, equal, Defined) -> send(M, report, status, 'No changes necessary') ; send(Used, for_all, message(M, insert, create(string, 'static PceArg PcN%s("%s");\n', @arg1, @arg1))) ). pce_replace_selectors(M) :-> "Replace all ""bla"" by PcN...":: get(M, collect, regex('^(static\\s+)?PceArg\\s+\\yPcN(\\w+)\\y'), 2, Defined), send(Defined, for_all, message(M, pce_replace_selector, @arg1)). pce_replace_selector(M, Name:char_array) :-> "Replace all occurrences after the caret of ""name"" by PcNname":: get(M, text_buffer, TB), send(regex(string('"%s"', Name)), for_all, TB, message(@arg1, replace, @arg2, string('PcN%s', Name)), M?caret). pce_unreplace_selectors(M) :-> "Replace all PcNbla by ""bla""":: get(M, text_buffer, TB), send(regex('PcN(\\w+)'), for_all, TB, message(@arg1, replace, @arg2, '"\\1"'), M?caret). collect(M, Re:regex, Reg:[int], Result) :<- "Collect specified register of regex matches":: get(M, text_buffer, TB), new(Result, chain), send(Re, for_all, TB, message(Result, append, ?(@arg1, register_value, @arg2, Reg, name))), send(Result, sort), send(Result, unique). :- emacs_end_mode.
TeamSPoon/logicmoo_workspace
docker/rootfs/usr/local/lib/swipl/xpce/prolog/lib/emacs/cpp_mode.pl
Perl
mit
4,742
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package XrefParser::ncRNA_DBParser; use strict; use warnings; use Carp; use File::Basename; use base qw( XrefParser::BaseParser ); use strict; use Bio::EnsEMBL::DBSQL::DBAdaptor; use XrefParser::Database; sub run_script { my ($self, $ref_arg) = @_; my $source_id = $ref_arg->{source_id}; my $species_id = $ref_arg->{species_id}; my $file = $ref_arg->{file}; my $verbose = $ref_arg->{verbose}; if((!defined $source_id) or (!defined $species_id) or (!defined $file) ){ croak "Need to pass source_id, species_id and files as pairs"; } $verbose |=0; my ($type, $my_args) = split(/:/,$file); my $user ="ensro"; my $host; my $port; my $dbname; my $pass; if($my_args =~ /host[=][>](\S+?)[,]/){ $host = $1; } if($my_args =~ /port[=][>](\S+?)[,]/){ $port = $1; } if($my_args =~ /dbname[=][>](\S+?)[,]/){ $dbname = $1; } if($my_args =~ /pass[=][>](\S+?)[,]/){ $pass = $1; } if($my_args =~ /user[=][>](\S+?)[,]/){ $user = $1; } my %source; $source{"RFAM"} = $self->get_source_id_for_source_name('RFAM') || die "Could not get source_id for RFAM"; $source{"miRBase"} = $self->get_source_id_for_source_name('miRBase') || die "Could not get source_id for miRBase"; my $ccds_db = XrefParser::Database->new({ host => $host, port => $port, user => $user, dbname => $dbname, pass => $pass}); my $dbi2 = $ccds_db->dbi(); if(!defined($dbi2)){ return 1; } my $sql=(<<SQL); SELECT transcript_stable_id, transcript_dbid, source, xref_name, xref_primary_id, xref_description FROM ncRNA_Xref WHERE taxonomy_id = $species_id SQL my ($stable_id, $dbid, $source_name, $label, $acc, $desc); my $sth = $dbi2->prepare($sql); $sth->execute() or croak( $dbi2->errstr() ); $sth->bind_columns(\$stable_id, \$dbid, \$source_name, \$label, \$acc, \$desc); my $added = 0; while ( $sth->fetch() ) { my ($description,$junk) = split("[[]Source:",$desc); if(!defined($source{$source_name})){ print STDERR "Could not find source_id for source $source_name for xref $acc\n"; next; } my $xref_id = $self->get_xref($acc,$source{$source_name}, $species_id); if(!defined($xref_id)){ $xref_id = $self->add_xref({ acc => $acc, label => $label, desc => $description, source_id => $source{$source_name}, species_id => $species_id, info_type => "DIRECT"} ); $added++; } my $transcript_id = $dbid; if(defined($stable_id) and $stable_id ne ""){ $transcript_id = $stable_id; } $self->add_direct_xref($xref_id, $transcript_id, "Transcript", "") if (defined($transcript_id)); } $sth->finish; print "Added $added Xrefs for ncRNAs\n" if($verbose); if ($added > 0) { return 0; } else { return 1; } } 1;
at7/ensembl
misc-scripts/xref_mapping/XrefParser/ncRNA_DBParser.pm
Perl
apache-2.0
3,564
package Paws::WAF::CreateIPSetResponse; use Moose; has ChangeToken => (is => 'ro', isa => 'Str'); has IPSet => (is => 'ro', isa => 'Paws::WAF::IPSet'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::WAF::CreateIPSetResponse =head1 ATTRIBUTES =head2 ChangeToken => Str The C<ChangeToken> that you used to submit the C<CreateIPSet> request. You can also use this value to query the status of the request. For more information, see GetChangeTokenStatus. =head2 IPSet => L<Paws::WAF::IPSet> The IPSet returned in the C<CreateIPSet> response. =head2 _request_id => Str =cut 1;
ioanrogers/aws-sdk-perl
auto-lib/Paws/WAF/CreateIPSetResponse.pm
Perl
apache-2.0
651
#!/usr/bin/perl -w # # Copyright 2012, Google Inc. All Rights Reserved. # # 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. # # This example gets location criteria by name. # # Tags: LocationCriterionSerivce.get # Author: David Torres <api.davidtorres@gmail.com> use strict; use lib "../../../lib"; use utf8; use Google::Ads::AdWords::Client; use Google::Ads::AdWords::Logging; use Google::Ads::AdWords::v201409::OrderBy; use Google::Ads::AdWords::v201409::Predicate; use Google::Ads::AdWords::v201409::Selector; use Cwd qw(abs_path); # Example main subroutine. sub lookup_location { my $client = shift; # Create selector. my $selector = Google::Ads::AdWords::v201409::Selector->new({ fields => ["Id", "LocationName", "CanonicalName", "DisplayType", "ParentLocations", "Reach", "TargetingStatus"], predicates => [Google::Ads::AdWords::v201409::Predicate->new({ field => "LocationName", operator => "IN", values => ["Paris", "Quebec", "Spain", "Deutschland"] }), Google::Ads::AdWords::v201409::Predicate->new({ field => "Locale", operator => "EQUALS", values => "en" })], ordering => [Google::Ads::AdWords::v201409::OrderBy->new({ field => "LocationName", sortOrder => "ASCENDING" })] }); # Get all campaigns. my $location_criteria = $client->LocationCriterionService()->get({ selector => $selector }); # Display campaigns. foreach my $location_criterion (@{$location_criteria}) { my @parent_locations = (); if ($location_criterion->get_location()->get_parentLocations()) { foreach my $parent_location (@{$location_criterion->get_location()->get_parentLocations()}) { push @parent_locations, sprintf("%s (%s)", $parent_location->get_locationName(), $parent_location->get_displayType()); } } my $location = $location_criterion->get_location(); printf "The search term '%s' returned the location '%s' of type '%s' " . "with parent locations '%s', reach '%d' and targeting status '%s'.\n", $location_criterion->get_searchTerm, $location->get_locationName(), $location->get_displayType(), scalar(@parent_locations) ? join(", ", @parent_locations) : "N/A", $location_criterion->get_reach(), $location->get_targetingStatus(); } return 1; } # Don't run the example if the file is being included. if (abs_path($0) ne abs_path(__FILE__)) { return 1; } # Log SOAP XML request, response and API errors. Google::Ads::AdWords::Logging::enable_all_logging(); # Get AdWords Client, credentials will be read from ~/adwords.properties. my $client = Google::Ads::AdWords::Client->new({version => "v201409"}); # By default examples are set to die on any server returned fault. $client->set_die_on_faults(1); # Call the example lookup_location($client);
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
examples/v201409/targeting/lookup_location.pl
Perl
apache-2.0
3,565
#! /usr/bin/perl -w use strict; use Net::LDAP 0.33; use Authen::SASL 2.10; # -------- Adjust to your environment -------- my $adhost = 'a.wcmc-ad.net'; my $ldap_base = 'dc=a,dc=wcmc-ad,dc=net'; my $ldap_filter = '(&(sAMAccountName=oli2002))'; my $sasl = Authen::SASL->new(mechanism => 'GSSAPI'); my $ldap; eval { $ldap = Net::LDAP->new($adhost, onerror => 'die') or die "Cannot connect to LDAP host '$adhost': '$@'"; $ldap->bind(sasl => $sasl); }; if ($@) { chomp $@; die "\nBind error : $@", "\nDetailed SASL error: ", $sasl->error, "\nTerminated"; } print "\nLDAP bind() succeeded, working in authenticated state"; my $mesg = $ldap->search(base => $ldap_base, filter => $ldap_filter); # -------- evaluate $mesg
victorbrodsky/order-lab
orderflex/ldap_sasl.pl
Perl
apache-2.0
835
package NTPPool::API; use strict; use base qw(Combust::API); __PACKAGE__->setup_api( 'staff' => 'Staff', 'notes' => 'Notes', ); 1;
punitvara/ntppool
lib/NTPPool/API.pm
Perl
apache-2.0
141
=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>. =head1 NAME Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::TreeBest =head1 DESCRIPTION This Runnable offers some methods to run Treebest. Notes: - Apart from the multiple alignments, all the data are exchanged as Perl strings. - The parameter treebest_exe must be set. - An alignment filtering method can be defined via the parameter filt_cmdline PS: Until e75, RunnableDB/GeneTrees/ReconcileTree.pm was able to reconcile a tree *in place* =head1 AUTHORSHIP Ensembl Team. Individual contributions can be found in the GIT log. =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with an underscore (_) =cut package Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::TreeBest; use strict; use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable'); # First of all, we need a tree of node_ids, since our foreign keys are based on that sub _load_species_tree_string_from_db { my ($self) = @_; my $species_tree = $self->param('gene_tree')->species_tree(); $species_tree->attach_to_genome_dbs(); $self->param('species_tree_string', $species_tree->root->newick_format('ryo', '%{o}%{-E"*"}')) } # # Methods that will build a tree on an alignment ################################################## =head2 run_treebest_best - IN: $input_aln: filename: the multiple alignment - OUT: string: the "best" tree computed on the alignment - PARAM: intermediate_prefix: how to prefix the files with the intermediate trees - PARAM: extra_args: extra arguments to give to treebest =cut sub run_treebest_best { my ($self, $input_aln, $lk_scale) = @_; my $species_tree_file = $self->get_species_tree_file(); my $max_diff_lk; my $filtering_cutoff; while (1) { # Main arguments my $args = sprintf('best -f %s', $species_tree_file); # Optional arguments $args .= sprintf(' -p %s', $self->param('intermediate_prefix')) if $self->param('intermediate_prefix'); $args .= sprintf(' %s', $self->param('extra_args')) if $self->param('extra_args'); $args .= sprintf(' -Z %f', $max_diff_lk) if $max_diff_lk; $args .= sprintf(' -X %f', $lk_scale) if $lk_scale; $args .= ' -D'; $args .= sprintf(' -F %d', $filtering_cutoff) if $filtering_cutoff; my $cmd = $self->_get_alignment_filtering_cmd($args, $input_aln); my $run_cmd = $self->run_command($cmd); $self->param('treebest_stderr', $run_cmd->err); return $run_cmd->out unless ($run_cmd->exit_code); my $full_cmd = $run_cmd->cmd; $self->throw("'$full_cmd' resulted in a segfault") if ($run_cmd->exit_code == 11); print STDERR "$full_cmd\n"; my $logfile = $run_cmd->err; $logfile =~ s/^Large distance.*$//mg; $logfile =~ s/\n\n*/\n/g; if (($logfile =~ /NNI/) || ($logfile =~ /Optimize_Br_Len_Serie/) || ($logfile =~ /Optimisation failed/) || ($logfile =~ /Brent failed/)) { # Increase the tolerance max_diff_lk in the computation $max_diff_lk = 1e-5 unless $max_diff_lk; $max_diff_lk *= 10; $self->warning("Lowering max_diff_lk to $max_diff_lk"); } elsif ($logfile =~ /The filtered alignment has 0 columns. Cannot build a tree/ and not ($self->param('extra_args') and $self->param('extra_args') =~ /-F /)) { # Decrease the cutoff to remove columns (only in auto mode, i.e. when the user hasn't given a -F option) # Although the default value in treebest is 11, we start directly at 6, and reduce by 1 at each iteration $filtering_cutoff = 7 unless $filtering_cutoff; $filtering_cutoff--; $self->warning("Lowering filtering_cutoff to $filtering_cutoff"); } else { $self->throw(sprintf("error running treebest [%s]: %d\n%s", $run_cmd->cmd, $run_cmd->exit_code, $logfile)); } } } =head2 run_treebest_nj -IN: $input_aln: filename: the multiple alignment -OUT: string: the tree built on that alignment =cut sub run_treebest_nj { my ($self, $input_aln) = @_; my $args = sprintf('nj -s %s ', $self->get_species_tree_file()); return $self->_run_and_return_output($self->_get_alignment_filtering_cmd($args, $input_aln)); } =head2 run_treebest_phyml -IN: $input_aln: filename: the multiple alignment -OUT: string: the tree built on that alignment =cut sub run_treebest_phyml { my ($self, $input_aln) = @_; my $args = sprintf('phyml -Snf %s', $self->get_species_tree_file()); return $self->_run_and_return_output($self->_get_alignment_filtering_cmd($args, $input_aln)); } =head2 run_treebest_branchlength_nj -IN: $input_aln: filename: the multiple alignment -IN: $input_tree: string: the tree -OUT: string: the same tree with branch lengths =cut sub run_treebest_branchlength_nj { my ($self, $input_aln, $input_tree) = @_; my $args = sprintf( 'nj -I -c %s -s %s', $self->_write_temp_tree_file('input_tree', $input_tree), $self->get_species_tree_file()); return $self->_run_and_return_output($self->_get_alignment_filtering_cmd($args, $input_aln)); } # # Alignment-free methods ######################### =head2 run_treebest_mmerge -IN: $input_forest: arrayref of strings: the trees to merge -OUT: string: the merged tree =cut sub run_treebest_mmerge { my ($self, $input_forest) = @_; my $args = sprintf( 'mmerge -s %s %s', $self->get_species_tree_file(), $self->_write_temp_tree_file('input_forest', join("\n", @$input_forest)), ); return $self->_run_and_return_output($self->_get_treebest_cmd($args)); } =head2 run_treebest_sdi_genepair - IN: $gene1: string: name of the first gene - IN: $gene2: string: name of the second gene - OUT: string: reconciled tree with the two genes =cut sub run_treebest_sdi_genepair { my ($self, $gene1, $gene2) = @_; return $self->run_treebest_sdi(sprintf('(%s,%s);', $gene1, $gene2), 0); } =head2 run_treebest_sdi - IN: $unreconciled_tree: string: the unreconciled tree - OUT: string: the reconciled tree =cut sub run_treebest_sdi { my ($self, $unreconciled_tree, $root_tree) = @_; my $args = sprintf( 'sdi -%s %s %s', $root_tree ? 'rs' : 's', $self->get_species_tree_file, $self->_write_temp_tree_file('unrooted.nhx', $unreconciled_tree), ); return $self->_run_and_return_output($self->_get_treebest_cmd($args)); } # # Common methods to call treebest ################################## =head2 _get_alignment_filtering_cmd Returns the command line needed to run treebest with a filtered alignment =cut sub _get_alignment_filtering_cmd { my ($self, $args, $input_aln) = @_; my $cmd = $self->_get_treebest_cmd($args).' '; # External alignment filtering ? if (defined $self->param('filt_cmdline')) { my $tmp_align = $self->worker_temp_directory.'prog-filtalign.fa'; $cmd .= $tmp_align; $cmd = sprintf($self->param('filt_cmdline'), $input_aln, $tmp_align).' ; '.$cmd; } else { $cmd .= $input_aln } return sprintf('cd %s; %s', $self->worker_temp_directory, $cmd); } =head2 _get_treebest_cmd Returns the command line needed to run treebest with the given arguments =cut sub _get_treebest_cmd { my ($self, $args) = @_; return sprintf('%s %s', $self->require_executable('treebest_exe'), $args); } =head2 _run_and_return_output Runs the command and checks for failure. Returns the output of treebest if success. =cut sub _run_and_return_output { my ($self, $cmd) = @_; my $cmd_out = $self->run_command($cmd); return $cmd_out->out unless $cmd_out->exit_code; $self->throw(sprintf("error running treebest [%s]: %d\n%s", $cmd_out->cmd, $cmd_out->exit_code, $cmd_out->err)); } =head2 _write_temp_tree_file Creates a temporary file in the worker temp directory, with the given content =cut sub _write_temp_tree_file { my ($self, $tree_name, $tree_content) = @_; my $filename = $self->worker_temp_directory . $tree_name; open my $fh, ">", $filename or die $!; print $fh $tree_content; close $fh; return $filename; } 1;
ckongEbi/ensembl-compara
modules/Bio/EnsEMBL/Compara/RunnableDB/GeneTrees/TreeBest.pm
Perl
apache-2.0
9,212
# 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 ModPerl::RegistryBB; use strict; use warnings FATAL => 'all'; # we try to develop so we reload ourselves without die'ing on the warning no warnings qw(redefine); # XXX, this should go away in production! our $VERSION = '1.99'; use base qw(ModPerl::RegistryCooker); sub handler : method { my $class = (@_ >= 2) ? shift : __PACKAGE__; my $r = shift; return $class->new($r)->default_handler(); } # currently all the methods are inherited through the normal ISA # search may 1; __END__
gitpan/mod_perl
ModPerl-Registry/lib/ModPerl/RegistryBB.pm
Perl
apache-2.0
1,293
=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>. =head1 NAME NewickParser - DESCRIPTION of Object =head1 DESCRIPTION Module which implements a newick string parser as a finite state machine which enables it to parse the full Newick specification. Module does not need to be instantiated, the method can be called directly. =head1 AUTHORSHIP Ensembl Team. Individual contributions can be found in the GIT log. =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with an underscore (_) =cut package Bio::EnsEMBL::Compara::Graph::NewickParser; use strict; use warnings; use Bio::EnsEMBL::Compara::NestedSet; use Bio::EnsEMBL::Utils::Exception qw(throw warning); =head2 parse_newick_into_tree Arg 1 : string $newick_tree Arg 2 : string $class (optional) Example : $tree = Bio::EnsEMBL::Compara::Graph::NewickParser::parse_newick_into_tree($newick_tree); Description: Read the newick string and returns (the root of) a tree. Tree nodes are instances of $class, or Bio::EnsEMBL::Compara::NestedSet by default. Returntype : Bio::EnsEMBL::Compara::NestedSet or $class Exceptions : none Caller : general =cut sub parse_newick_into_tree { my $newick = shift; my $class = shift; my $count=1; my $debug = 0; print STDERR "NEWICK:$newick\n" if($debug); my $token = next_token(\$newick, "(;"); my $lastset = undef; my $node = undef; my $root = undef; my $state=1; my $bracket_level = 0; while(defined($token)) { if($debug) { printf("state %d : '%s'\n", $state, $token); }; if ($state == 1) { #new node $node = new Bio::EnsEMBL::Compara::NestedSet; if (defined $class) { # Make sure that the class is loaded eval "require $class"; bless $node, $class; } $node->node_id($count++); $lastset->add_child($node) if($lastset); $root=$node unless($root); if($token eq '(') { #create new set printf(" create set\n") if($debug); $token = next_token(\$newick, "[(:,)"); $state = 1; $bracket_level++; $lastset = $node; } else { $state = 2; } } elsif ($state == 2) { #naming a node if(!($token =~ /[\[\:\,\)\;]/)) { $node->name($token); if($debug) { print(" naming leaf"); $node->print_node; } $token = next_token(\$newick, "[:,);"); } $state = 3; } elsif ($state == 3) { # optional : and distance if($token eq ':') { $token = next_token(\$newick, "[,);"); $node->distance_to_parent($token); if($debug) { print("set distance: $token"); $node->print_node; } $token = next_token(\$newick, ",);"); #move to , or ) } elsif ($token eq '[') { # NHX tag without previous blength $token .= next_token(\$newick, ",);"); } $state = 4; } elsif ($state == 4) { # optional NHX tags if($token =~ /\[\&\&NHX/) { # careful: this regexp gets rid of all NHX wrapping in one step $token =~ /\[\&\&NHX\:(\S+)\]/; if ($1) { # NHX may be empty, presumably at end of file, just before ";" my @attributes = split ':', $1; foreach my $attribute (@attributes) { $attribute =~ s/\s+//; my($key,$value) = split '=', $attribute; # we assume only one value per key # shortcut duplication mapping if ($key eq 'D') { $key = "Duplication"; # this is a small hack that will work for # treefam nhx trees $value =~ s/Y/1/; $value =~ s/N/0/; } if ($key eq 'DD') { # this is a small hack that will work for # treefam nhx trees $value =~ s/Y/1/; $value =~ s/N/0/; } $node->add_tag("$key","$value"); } } # $token = next_token(\$newick, ",);"); #$node->distance_to_parent($token); # Force a duplication = 0 for some strange treefam internal nodes unless ($node->is_leaf) { if (not $node->has_tag("Duplication")) { $node->add_tag("Duplication",0); } } if($debug) { print("NHX tags: $token"); $node->print_node; } $token = next_token(\$newick, ",);"); #move to , or ) } $state = 5; } elsif ($state == 5) { # end node if($token eq ')') { if($debug) { print("end set : "); $lastset->print_node; } $node = $lastset; $lastset = $lastset->parent; $token = next_token(\$newick, "[:,);"); # it is possible to have anonymous internal nodes no name # no blength but with NHX tags if ($token eq '[') { $state=1; } else { $state=2; } $bracket_level--; } elsif($token eq ',') { $token = next_token(\$newick, "[(:,)"); #can be un_blengthed nhx nodes $state=1; } elsif($token eq ';') { #done with tree throw("parse error: unbalanced ()\n") if($bracket_level ne 0); $state=13; $token = next_token(\$newick, "("); } else { throw("parse error: expected ; or ) or ,\n"); } } elsif ($state == 13) { throw("parse error: nothing expected after ;"); } } # Tags of the root node are lost otherwise $root->{_tags} = $node->{_tags} unless $root eq $node; return $root; } sub next_token { my $string = shift; my $delim = shift; $$string =~ s/^(\s)+//; return undef unless(length($$string)); #print("input =>$$string\n"); #print("delim =>$delim\n"); my $index=undef; my @delims = split(/ */, $delim); foreach my $dl (@delims) { my $pos = index($$string, $dl); if($pos>=0) { $index = $pos unless(defined($index)); $index = $pos if($pos<$index); } } unless(defined($index)) { throw("couldn't find delimiter $delim\n"); } my $token =''; if($index==0) { $token = substr($$string,0,1); $$string = substr($$string, 1); } else { $token = substr($$string, 0, $index); $$string = substr($$string, $index); } #print(" token =>$token\n"); #print(" outstring =>$$string\n\n"); return $token; } 1;
ckongEbi/ensembl-compara
modules/Bio/EnsEMBL/Compara/Graph/NewickParser.pm
Perl
apache-2.0
7,573
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.1.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 0030 0039 0660 0669 066B 066C 06F0 06F9 07C0 07C9 0966 096F 09E6 09EF 0A66 0A6F 0AE6 0AEF 0B66 0B6F 0BE6 0BEF 0C66 0C6F 0CE6 0CEF 0D66 0D6F 0E50 0E59 0ED0 0ED9 0F20 0F29 1040 1049 1090 1099 17E0 17E9 1810 1819 1946 194F 19D0 19D9 1A80 1A89 1A90 1A99 1B50 1B59 1BB0 1BB9 1C40 1C49 1C50 1C59 A620 A629 A8D0 A8D9 A900 A909 A9D0 A9D9 AA50 AA59 ABF0 ABF9 104A0 104A9 11066 1106F 110F0 110F9 11136 1113F 111D0 111D9 116C0 116C9 1D7CE 1D7FF END
efortuna/AndroidSDKClone
ndk_experimental/prebuilt/linux-x86_64/lib/perl5/5.16.2/unicore/lib/Lb/NU.pl
Perl
apache-2.0
857
#!/usr/bin/perl -w use strict; die "Usage: $0 file.conll\n\n Converts a CoNLL formatted labeled sequence into cdec's format.\n\n" unless scalar @ARGV == 1; open F, "<$ARGV[0]" or die "Can't read $ARGV[0]: $!\n"; my @xx; my @yy; my @os; my $sec = undef; my $i = 0; while(<F>) { chomp; if (/^\s*$/) { print "<seg id=\"$i\""; $i++; for (my $j = 0; $j < $sec; $j++) { my @oo = (); for (my $k = 0; $k < scalar @xx; $k++) { my $sym = $os[$k]->[$j]; $sym =~ s/"/'/g; push @oo, $sym; } my $zz = $j + 1; print " feat$zz=\"@oo\""; } print "> @xx ||| @yy </seg>\n"; @xx = (); @yy = (); @os = (); } else { my ($x, @fs) = split /\s+/; my $y = pop @fs; if (!defined $sec) { $sec = scalar @fs; } die unless $sec == scalar @fs; push @xx, $x; push @yy, $y; push @os, \@fs; } }
carhaas/cdec-semparse
corpus/conll2cdec.pl
Perl
apache-2.0
887
#!perl -w use warnings; use strict; my $n = 1; my $j; while ($n < 27) { open J, ">frege/rt/Product$n.java" or die "can't open $!"; my @targs = map { "T$_" } (1..$n); # T1, T2, T3 my @nargs = map {"final Lazy<T$_> arg$_" } (1..$n); # final Lazy<T1> arg1, ... my $cnargs = join (",", @nargs); # "final ... arg1, ...." my @args = map { "arg$_" } (1..$n); # arg1, arg2 my $crargs = join(",", reverse @args); # "arg2, arg1" my $rt = $targs[$n]; # Tn my $ctargs = join (",", @targs); # "T1, T2, T3" my $cargs = join (",", @args); # "arg1, arg2" my $p = $n-1; my @ptargs = @targs; shift @ptargs; my $cptargs = join(",", @ptargs); my @pargs = map { "final Lazy<T$_> arg$_" } (2..$n); my @rpargs = reverse @pargs; my $crpargs = join(",", @rpargs); print J <<'LIZENZ'; /* «•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•» Copyright © 2011, Ingo Wechsung 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. «•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•»«•» */ LIZENZ print J "package frege.rt;\r\n"; print J <<'TEXT'; // $Author$ // $Date$ // $Rev$ // $Id$ TEXT print J <<"TEXT"; /** * <p> Base class for values constructed with $n-ary constructors. </p> * * <p> This will be extended by constructors of sum types and by product types. * Subclasses must implement the {\@link Value#_c} method and the * {\@link Lazy} interface. * </p> * * <p> Note that Product<sub><em>$n</em></sub> is not a subclass of Product<sub><em>$p</em></sub>! </p> */ public abstract class Product$n<$ctargs> implements Value { /** <p> Must be implemented by subclasses to return their constructor number. </p> */ public abstract int _c(); /** <p> Default implementation of the {\@link Lazy#_u} method. </p> * \@return false */ final public boolean _u() { return false; } TEXT for ($j = 1; $j <= $n; $j++) { print J <<"TEXT"; /** <p>Field $j </p> */ public final Lazy<T$j> m$j; /** <p> Frege function to get field $j lazily. </p> */ public final static class Get$j<$ctargs, T extends Product$n<$ctargs>> extends Fun1<T, T$j> { public final Lazy<T$j> r(final Lazy<T> arg1) { return arg1._e().m$j; } private final static Get$j single = new Get$j(); \@SuppressWarnings("unchecked") public final static <$ctargs, T extends Product$n<$ctargs>> Get$j<$ctargs,T> n() { return (Get$j<$ctargs,T>) single; } } TEXT } print J <<"TEXT"; /** <p> Constructor. </p> */ protected Product$n($cnargs) { TEXT for ($j = 1; $j <= $n; $j++) { print J <<"TEXT"; m$j = arg$j; TEXT } print J <<"TEXT"; } } TEXT close J; $n++; }
vsts/frege
scripts/genP.pl
Perl
bsd-3-clause
4,706
#============================================================= -*-Perl-*- # # Template::Parser # # DESCRIPTION # This module implements a LALR(1) parser and assocated support # methods to parse template documents into the appropriate "compiled" # format. Much of the parser DFA code (see _parse() method) is based # on Francois Desarmenien's Parse::Yapp module. Kudos to him. # # AUTHOR # Andy Wardley <abw@wardley.org> # # COPYRIGHT # Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved. # # This module is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. # # The following copyright notice appears in the Parse::Yapp # documentation. # # The Parse::Yapp module and its related modules and shell # scripts are copyright (c) 1998 Francois Desarmenien, # France. All rights reserved. # # You may use and distribute them under the terms of either # the GNU General Public License or the Artistic License, as # specified in the Perl README file. # #============================================================================ package Template::Parser; use strict; use warnings; use base 'Template::Base'; use Template::Constants qw( :status :chomp ); use Template::Directive; use Template::Grammar; # parser state constants use constant CONTINUE => 0; use constant ACCEPT => 1; use constant ERROR => 2; use constant ABORT => 3; our $VERSION = 2.89; our $DEBUG = 0 unless defined $DEBUG; our $ERROR = ''; #======================================================================== # -- COMMON TAG STYLES -- #======================================================================== our $TAG_STYLE = { 'default' => [ '\[%', '%\]' ], 'template1' => [ '[\[%]%', '%[\]%]' ], 'metatext' => [ '%%', '%%' ], 'html' => [ '<!--', '-->' ], 'mason' => [ '<%', '>' ], 'asp' => [ '<%', '%>' ], 'php' => [ '<\?', '\?>' ], 'star' => [ '\[\*', '\*\]' ], }; $TAG_STYLE->{ template } = $TAG_STYLE->{ tt2 } = $TAG_STYLE->{ default }; our $DEFAULT_STYLE = { START_TAG => $TAG_STYLE->{ default }->[0], END_TAG => $TAG_STYLE->{ default }->[1], # TAG_STYLE => 'default', ANYCASE => 0, INTERPOLATE => 0, PRE_CHOMP => 0, POST_CHOMP => 0, V1DOLLAR => 0, EVAL_PERL => 0, }; our $QUOTED_ESCAPES = { n => "\n", r => "\r", t => "\t", }; # note that '-' must come first so Perl doesn't think it denotes a range our $CHOMP_FLAGS = qr/[-=~+]/; #======================================================================== # ----- PUBLIC METHODS ----- #======================================================================== #------------------------------------------------------------------------ # new(\%config) # # Constructor method. #------------------------------------------------------------------------ sub new { my $class = shift; my $config = $_[0] && ref($_[0]) eq 'HASH' ? shift(@_) : { @_ }; my ($tagstyle, $debug, $start, $end, $defaults, $grammar, $hash, $key, $udef); my $self = bless { START_TAG => undef, END_TAG => undef, TAG_STYLE => 'default', ANYCASE => 0, INTERPOLATE => 0, PRE_CHOMP => 0, POST_CHOMP => 0, V1DOLLAR => 0, EVAL_PERL => 0, FILE_INFO => 1, GRAMMAR => undef, _ERROR => '', IN_BLOCK => [ ], TRACE_VARS => $config->{ TRACE_VARS }, FACTORY => $config->{ FACTORY } || 'Template::Directive', }, $class; # update self with any relevant keys in config foreach $key (keys %$self) { $self->{ $key } = $config->{ $key } if defined $config->{ $key }; } $self->{ FILEINFO } = [ ]; # DEBUG config item can be a bitmask if (defined ($debug = $config->{ DEBUG })) { $self->{ DEBUG } = $debug & ( Template::Constants::DEBUG_PARSER | Template::Constants::DEBUG_FLAGS ); $self->{ DEBUG_DIRS } = $debug & Template::Constants::DEBUG_DIRS; } # package variable can be set to 1 to support previous behaviour elsif ($DEBUG == 1) { $self->{ DEBUG } = Template::Constants::DEBUG_PARSER; $self->{ DEBUG_DIRS } = 0; } # otherwise let $DEBUG be a bitmask else { $self->{ DEBUG } = $DEBUG & ( Template::Constants::DEBUG_PARSER | Template::Constants::DEBUG_FLAGS ); $self->{ DEBUG_DIRS } = $DEBUG & Template::Constants::DEBUG_DIRS; } $grammar = $self->{ GRAMMAR } ||= do { require Template::Grammar; Template::Grammar->new(); }; # instantiate a FACTORY object unless (ref $self->{ FACTORY }) { my $fclass = $self->{ FACTORY }; $self->{ FACTORY } = $self->{ FACTORY }->new( NAMESPACE => $config->{ NAMESPACE } ) || return $class->error($self->{ FACTORY }->error()); } # load grammar rules, states and lex table @$self{ qw( LEXTABLE STATES RULES ) } = @$grammar{ qw( LEXTABLE STATES RULES ) }; $self->new_style($config) || return $class->error($self->error()); return $self; } #----------------------------------------------------------------------- # These methods are used to track nested IF and WHILE blocks. Each # generated if/while block is given a label indicating the directive # type and nesting depth, e.g. FOR0, WHILE1, FOR2, WHILE3, etc. The # NEXT and LAST directives use the innermost label, e.g. last WHILE3; #----------------------------------------------------------------------- sub enter_block { my ($self, $name) = @_; my $blocks = $self->{ IN_BLOCK }; push(@{ $self->{ IN_BLOCK } }, $name); } sub leave_block { my $self = shift; my $label = $self->block_label; pop(@{ $self->{ IN_BLOCK } }); return $label; } sub in_block { my ($self, $name) = @_; my $blocks = $self->{ IN_BLOCK }; return @$blocks && $blocks->[-1] eq $name; } sub block_label { my ($self, $prefix, $suffix) = @_; my $blocks = $self->{ IN_BLOCK }; my $name = @$blocks ? $blocks->[-1] . scalar @$blocks : undef; return join('', grep { defined $_ } $prefix, $name, $suffix); } #------------------------------------------------------------------------ # new_style(\%config) # # Install a new (stacked) parser style. This feature is currently # experimental but should mimic the previous behaviour with regard to # TAG_STYLE, START_TAG, END_TAG, etc. #------------------------------------------------------------------------ sub new_style { my ($self, $config) = @_; my $styles = $self->{ STYLE } ||= [ ]; my ($tagstyle, $tags, $start, $end, $key); # clone new style from previous or default style my $style = { %{ $styles->[-1] || $DEFAULT_STYLE } }; # expand START_TAG and END_TAG from specified TAG_STYLE if ($tagstyle = $config->{ TAG_STYLE }) { return $self->error("Invalid tag style: $tagstyle") unless defined ($tags = $TAG_STYLE->{ $tagstyle }); ($start, $end) = @$tags; $config->{ START_TAG } ||= $start; $config->{ END_TAG } ||= $end; } foreach $key (keys %$DEFAULT_STYLE) { $style->{ $key } = $config->{ $key } if defined $config->{ $key }; } push(@$styles, $style); return $style; } #------------------------------------------------------------------------ # old_style() # # Pop the current parser style and revert to the previous one. See # new_style(). ** experimental ** #------------------------------------------------------------------------ sub old_style { my $self = shift; my $styles = $self->{ STYLE }; return $self->error('only 1 parser style remaining') unless (@$styles > 1); pop @$styles; return $styles->[-1]; } #------------------------------------------------------------------------ # parse($text, $data) # # Parses the text string, $text and returns a hash array representing # the compiled template block(s) as Perl code, in the format expected # by Template::Document. #------------------------------------------------------------------------ sub parse { my ($self, $text, $info) = @_; my ($tokens, $block); $info->{ DEBUG } = $self->{ DEBUG_DIRS } unless defined $info->{ DEBUG }; # print "info: { ", join(', ', map { "$_ => $info->{ $_ }" } keys %$info), " }\n"; # store for blocks defined in the template (see define_block()) my $defblock = $self->{ DEFBLOCK } = { }; my $metadata = $self->{ METADATA } = [ ]; my $variables = $self->{ VARIABLES } = { }; $self->{ DEFBLOCKS } = [ ]; $self->{ _ERROR } = ''; # split file into TEXT/DIRECTIVE chunks $tokens = $self->split_text($text) || return undef; ## RETURN ## push(@{ $self->{ FILEINFO } }, $info); # parse chunks $block = $self->_parse($tokens, $info); pop(@{ $self->{ FILEINFO } }); return undef unless $block; ## RETURN ## $self->debug("compiled main template document block:\n$block") if $self->{ DEBUG } & Template::Constants::DEBUG_PARSER; return { BLOCK => $block, DEFBLOCKS => $defblock, VARIABLES => $variables, METADATA => { @$metadata }, }; } #------------------------------------------------------------------------ # split_text($text) # # Split input template text into directives and raw text chunks. #------------------------------------------------------------------------ sub split_text { my ($self, $text) = @_; my ($pre, $dir, $prelines, $dirlines, $postlines, $chomp, $tags, @tags); my $style = $self->{ STYLE }->[-1]; my ($start, $end, $prechomp, $postchomp, $interp ) = @$style{ qw( START_TAG END_TAG PRE_CHOMP POST_CHOMP INTERPOLATE ) }; my $tags_dir = $self->{ANYCASE} ? qr<TAGS>i : qr<TAGS>; my @tokens = (); my $line = 1; return \@tokens ## RETURN ## unless defined $text && length $text; # extract all directives from the text while ($text =~ s/ ^(.*?) # $1 - start of line up to directive (?: $start # start of tag (.*?) # $2 - tag contents $end # end of tag ) //sx) { ($pre, $dir) = ($1, $2); $pre = '' unless defined $pre; $dir = '' unless defined $dir; $prelines = ($pre =~ tr/\n//); # newlines in preceeding text $dirlines = ($dir =~ tr/\n//); # newlines in directive tag $postlines = 0; # newlines chomped after tag for ($dir) { if (/^\#/) { # comment out entire directive except for any end chomp flag $dir = ($dir =~ /($CHOMP_FLAGS)$/o) ? $1 : ''; } else { s/^($CHOMP_FLAGS)?\s*//so; # PRE_CHOMP: process whitespace before tag $chomp = $1 ? $1 : $prechomp; $chomp =~ tr/-=~+/1230/; if ($chomp && $pre) { # chomp off whitespace and newline preceding directive if ($chomp == CHOMP_ALL) { $pre =~ s{ (\r?\n|^) [^\S\n]* \z }{}mx; } elsif ($chomp == CHOMP_COLLAPSE) { $pre =~ s{ (\s+) \z }{ }x; } elsif ($chomp == CHOMP_GREEDY) { $pre =~ s{ (\s+) \z }{}x; } } } # POST_CHOMP: process whitespace after tag s/\s*($CHOMP_FLAGS)?\s*$//so; $chomp = $1 ? $1 : $postchomp; $chomp =~ tr/-=~+/1230/; if ($chomp) { if ($chomp == CHOMP_ALL) { $text =~ s{ ^ ([^\S\n]* \n) }{}x && $postlines++; } elsif ($chomp == CHOMP_COLLAPSE) { $text =~ s{ ^ (\s+) }{ }x && ($postlines += $1=~y/\n//); } # any trailing whitespace elsif ($chomp == CHOMP_GREEDY) { $text =~ s{ ^ (\s+) }{}x && ($postlines += $1=~y/\n//); } } } # any text preceding the directive can now be added if (length $pre) { push(@tokens, $interp ? [ $pre, $line, 'ITEXT' ] : ('TEXT', $pre) ); } $line += $prelines; # and now the directive, along with line number information if (length $dir) { # the TAGS directive is a compile-time switch if ($dir =~ /^$tags_dir\s+(.*)/) { my @tags = split(/\s+/, $1); if (scalar @tags > 1) { ($start, $end) = map { quotemeta($_) } @tags; } elsif ($tags = $TAG_STYLE->{ $tags[0] }) { ($start, $end) = @$tags; } else { warn "invalid TAGS style: $tags[0]\n"; } } else { # DIRECTIVE is pushed as: # [ $dirtext, $line_no(s), \@tokens ] push(@tokens, [ $dir, ($dirlines ? sprintf("%d-%d", $line, $line + $dirlines) : $line), $self->tokenise_directive($dir) ]); } } # update line counter to include directive lines and any extra # newline chomped off the start of the following text $line += $dirlines + $postlines; } # anything remaining in the string is plain text push(@tokens, $interp ? [ $text, $line, 'ITEXT' ] : ( 'TEXT', $text) ) if length $text; return \@tokens; ## RETURN ## } #------------------------------------------------------------------------ # interpolate_text($text, $line) # # Examines $text looking for any variable references embedded like # $this or like ${ this }. #------------------------------------------------------------------------ sub interpolate_text { my ($self, $text, $line) = @_; my @tokens = (); my ($pre, $var, $dir); while ($text =~ / ( (?: \\. | [^\$] ){1,3000} ) # escaped or non-'$' character [$1] | ( \$ (?: # embedded variable [$2] (?: \{ ([^\}]*) \} ) # ${ ... } [$3] | ([\w\.]+) # $word [$4] ) ) /gx) { ($pre, $var, $dir) = ($1, $3 || $4, $2); # preceding text if (defined($pre) && length($pre)) { $line += $pre =~ tr/\n//; $pre =~ s/\\\$/\$/g; push(@tokens, 'TEXT', $pre); } # $variable reference if ($var) { $line += $dir =~ tr/\n/ /; push(@tokens, [ $dir, $line, $self->tokenise_directive($var) ]); } # other '$' reference - treated as text elsif ($dir) { $line += $dir =~ tr/\n//; push(@tokens, 'TEXT', $dir); } } return \@tokens; } #------------------------------------------------------------------------ # tokenise_directive($text) # # Called by the private _parse() method when it encounters a DIRECTIVE # token in the list provided by the split_text() or interpolate_text() # methods. The directive text is passed by parameter. # # The method splits the directive into individual tokens as recognised # by the parser grammar (see Template::Grammar for details). It # constructs a list of tokens each represented by 2 elements, as per # split_text() et al. The first element contains the token type, the # second the token itself. # # The method tokenises the string using a complex (but fast) regex. # For a deeper understanding of the regex magic at work here, see # Jeffrey Friedl's excellent book "Mastering Regular Expressions", # from O'Reilly, ISBN 1-56592-257-3 # # Returns a reference to the list of chunks (each one being 2 elements) # identified in the directive text. On error, the internal _ERROR string # is set and undef is returned. #------------------------------------------------------------------------ sub tokenise_directive { my ($self, $text, $line) = @_; my ($token, $uctoken, $type, $lookup); my $lextable = $self->{ LEXTABLE }; my $style = $self->{ STYLE }->[-1]; my ($anycase, $start, $end) = @$style{ qw( ANYCASE START_TAG END_TAG ) }; my @tokens = ( ); while ($text =~ / # strip out any comments (\#[^\n]*) | # a quoted phrase matches in $3 (["']) # $2 - opening quote, ' or " ( # $3 - quoted text buffer (?: # repeat group (no backreference) \\\\ # an escaped backslash \\ | # ...or... \\\2 # an escaped quote \" or \' (match $1) | # ...or... . # any other character | \n )*? # non-greedy repeat ) # end of $3 \2 # match opening quote | # an unquoted number matches in $4 (-?\d+(?:\.\d+)?) # numbers | # filename matches in $5 ( \/?\w+(?:(?:\/|::?)\w*)+ | \/\w+) | # an identifier matches in $6 (\w+) # variable identifier | # an unquoted word or symbol matches in $7 ( [(){}\[\]:;,\/\\] # misc parenthesis and symbols # | \-> # arrow operator (for future?) | [+\-*] # math operations | \$\{? # dollar with option left brace | => # like '=' | [=!<>]?= | [!<>] # eqality tests | &&? | \|\|? # boolean ops | \.\.? # n..n sequence | \S+ # something unquoted ) # end of $7 /gmxo) { # ignore comments to EOL next if $1; # quoted string if (defined ($token = $3)) { # double-quoted string may include $variable references if ($2 eq '"') { if ($token =~ /[\$\\]/) { $type = 'QUOTED'; # unescape " and \ but leave \$ escaped so that # interpolate_text() doesn't incorrectly treat it # as a variable reference # $token =~ s/\\([\\"])/$1/g; for ($token) { s/\\([^\$nrt])/$1/g; s/\\([nrt])/$QUOTED_ESCAPES->{ $1 }/ge; } push(@tokens, ('"') x 2, @{ $self->interpolate_text($token) }, ('"') x 2); next; } else { $type = 'LITERAL'; $token =~ s['][\\']g; $token = "'$token'"; } } else { $type = 'LITERAL'; $token = "'$token'"; } } # number elsif (defined ($token = $4)) { $type = 'NUMBER'; } elsif (defined($token = $5)) { $type = 'FILENAME'; } elsif (defined($token = $6)) { # Fold potential keywords to UPPER CASE if the ANYCASE option is # set, unless (we've got some preceeding tokens and) the previous # token is a DOT op. This prevents the 'last' in 'data.last' # from being interpreted as the LAST keyword. $uctoken = ($anycase && (! @tokens || $tokens[-2] ne 'DOT')) ? uc $token : $token; if (defined ($type = $lextable->{ $uctoken })) { $token = $uctoken; } else { $type = 'IDENT'; } } elsif (defined ($token = $7)) { # reserved words may be in lower case unless case sensitive $uctoken = $anycase ? uc $token : $token; unless (defined ($type = $lextable->{ $uctoken })) { $type = 'UNQUOTED'; } } push(@tokens, $type, $token); # print(STDERR " +[ $type, $token ]\n") # if $DEBUG; } # print STDERR "tokenise directive() returning:\n [ @tokens ]\n" # if $DEBUG; return \@tokens; ## RETURN ## } #------------------------------------------------------------------------ # define_block($name, $block) # # Called by the parser 'defblock' rule when a BLOCK definition is # encountered in the template. The name of the block is passed in the # first parameter and a reference to the compiled block is passed in # the second. This method stores the block in the $self->{ DEFBLOCK } # hash which has been initialised by parse() and will later be used # by the same method to call the store() method on the calling cache # to define the block "externally". #------------------------------------------------------------------------ sub define_block { my ($self, $name, $block) = @_; my $defblock = $self->{ DEFBLOCK } || return undef; $self->debug("compiled block '$name':\n$block") if $self->{ DEBUG } & Template::Constants::DEBUG_PARSER; $defblock->{ $name } = $block; return undef; } sub push_defblock { my $self = shift; my $stack = $self->{ DEFBLOCK_STACK } ||= []; push(@$stack, $self->{ DEFBLOCK } ); $self->{ DEFBLOCK } = { }; } sub pop_defblock { my $self = shift; my $defs = $self->{ DEFBLOCK }; my $stack = $self->{ DEFBLOCK_STACK } || return $defs; return $defs unless @$stack; $self->{ DEFBLOCK } = pop @$stack; return $defs; } #------------------------------------------------------------------------ # add_metadata(\@setlist) #------------------------------------------------------------------------ sub add_metadata { my ($self, $setlist) = @_; my $metadata = $self->{ METADATA } || return undef; push(@$metadata, @$setlist); return undef; } #------------------------------------------------------------------------ # location() # # Return Perl comment indicating current parser file and line #------------------------------------------------------------------------ sub location { my $self = shift; return "\n" unless $self->{ FILE_INFO }; my $line = ${ $self->{ LINE } }; my $info = $self->{ FILEINFO }->[-1]; my $file = $info->{ path } || $info->{ name } || '(unknown template)'; $line =~ s/\-.*$//; # might be 'n-n' $line ||= 1; return "#line $line \"$file\"\n"; } #======================================================================== # ----- PRIVATE METHODS ----- #======================================================================== #------------------------------------------------------------------------ # _parse(\@tokens, \@info) # # Parses the list of input tokens passed by reference and returns a # Template::Directive::Block object which contains the compiled # representation of the template. # # This is the main parser DFA loop. See embedded comments for # further details. # # On error, undef is returned and the internal _ERROR field is set to # indicate the error. This can be retrieved by calling the error() # method. #------------------------------------------------------------------------ sub _parse { my ($self, $tokens, $info) = @_; my ($token, $value, $text, $line, $inperl); my ($state, $stateno, $status, $action, $lookup, $coderet, @codevars); my ($lhs, $len, $code); # rule contents my $stack = [ [ 0, undef ] ]; # DFA stack # DEBUG # local $" = ', '; # retrieve internal rule and state tables my ($states, $rules) = @$self{ qw( STATES RULES ) }; # If we're tracing variable usage then we need to give the factory a # reference to our $self->{ VARIABLES } for it to fill in. This is a # bit of a hack to back-patch this functionality into TT2. $self->{ FACTORY }->trace_vars($self->{ VARIABLES }) if $self->{ TRACE_VARS }; # call the grammar set_factory method to install emitter factory $self->{ GRAMMAR }->install_factory($self->{ FACTORY }); $line = $inperl = 0; $self->{ LINE } = \$line; $self->{ FILE } = $info->{ name }; $self->{ INPERL } = \$inperl; $status = CONTINUE; my $in_string = 0; while(1) { # get state number and state $stateno = $stack->[-1]->[0]; $state = $states->[$stateno]; # see if any lookaheads exist for the current state if (exists $state->{'ACTIONS'}) { # get next token and expand any directives (i.e. token is an # array ref) onto the front of the token list while (! defined $token && @$tokens) { $token = shift(@$tokens); if (ref $token) { ($text, $line, $token) = @$token; if (ref $token) { if ($info->{ DEBUG } && ! $in_string) { # - - - - - - - - - - - - - - - - - - - - - - - - - # This is gnarly. Look away now if you're easily # frightened. We're pushing parse tokens onto the # pending list to simulate a DEBUG directive like so: # [% DEBUG msg line='20' text='INCLUDE foo' %] # - - - - - - - - - - - - - - - - - - - - - - - - - my $dtext = $text; $dtext =~ s[(['\\])][\\$1]g; unshift(@$tokens, DEBUG => 'DEBUG', IDENT => 'msg', IDENT => 'line', ASSIGN => '=', LITERAL => "'$line'", IDENT => 'text', ASSIGN => '=', LITERAL => "'$dtext'", IDENT => 'file', ASSIGN => '=', LITERAL => "'$info->{ name }'", (';') x 2, @$token, (';') x 2); } else { unshift(@$tokens, @$token, (';') x 2); } $token = undef; # force redo } elsif ($token eq 'ITEXT') { if ($inperl) { # don't perform interpolation in PERL blocks $token = 'TEXT'; $value = $text; } else { unshift(@$tokens, @{ $self->interpolate_text($text, $line) }); $token = undef; # force redo } } } else { # toggle string flag to indicate if we're crossing # a string boundary $in_string = ! $in_string if $token eq '"'; $value = shift(@$tokens); } }; # clear undefined token to avoid 'undefined variable blah blah' # warnings and let the parser logic pick it up in a minute $token = '' unless defined $token; # get the next state for the current lookahead token $action = defined ($lookup = $state->{'ACTIONS'}->{ $token }) ? $lookup : defined ($lookup = $state->{'DEFAULT'}) ? $lookup : undef; } else { # no lookahead actions $action = $state->{'DEFAULT'}; } # ERROR: no ACTION last unless defined $action; # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # shift (+ive ACTION) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - if ($action > 0) { push(@$stack, [ $action, $value ]); $token = $value = undef; redo; }; # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # reduce (-ive ACTION) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - ($lhs, $len, $code) = @{ $rules->[ -$action ] }; # no action imples ACCEPTance $action or $status = ACCEPT; # use dummy sub if code ref doesn't exist $code = sub { $_[1] } unless $code; @codevars = $len ? map { $_->[1] } @$stack[ -$len .. -1 ] : (); eval { $coderet = &$code( $self, @codevars ); }; if ($@) { my $err = $@; chomp $err; return $self->_parse_error($err); } # reduce stack by $len splice(@$stack, -$len, $len); # ACCEPT return $coderet ## RETURN ## if $status == ACCEPT; # ABORT return undef ## RETURN ## if $status == ABORT; # ERROR last if $status == ERROR; } continue { push(@$stack, [ $states->[ $stack->[-1][0] ]->{'GOTOS'}->{ $lhs }, $coderet ]), } # ERROR ## RETURN ## return $self->_parse_error('unexpected end of input') unless defined $value; # munge text of last directive to make it readable # $text =~ s/\n/\\n/g; return $self->_parse_error("unexpected end of directive", $text) if $value eq ';'; # end of directive SEPARATOR return $self->_parse_error("unexpected token ($value)", $text); } #------------------------------------------------------------------------ # _parse_error($msg, $dirtext) # # Method used to handle errors encountered during the parse process # in the _parse() method. #------------------------------------------------------------------------ sub _parse_error { my ($self, $msg, $text) = @_; my $line = $self->{ LINE }; $line = ref($line) ? $$line : $line; $line = 'unknown' unless $line; $msg .= "\n [% $text %]" if defined $text; return $self->error("line $line: $msg"); } #------------------------------------------------------------------------ # _dump() # # Debug method returns a string representing the internal state of the # object. #------------------------------------------------------------------------ sub _dump { my $self = shift; my $output = "[Template::Parser] {\n"; my $format = " %-16s => %s\n"; my $key; foreach $key (qw( START_TAG END_TAG TAG_STYLE ANYCASE INTERPOLATE PRE_CHOMP POST_CHOMP V1DOLLAR )) { my $val = $self->{ $key }; $val = '<undef>' unless defined $val; $output .= sprintf($format, $key, $val); } $output .= '}'; return $output; } 1; __END__ =head1 NAME Template::Parser - LALR(1) parser for compiling template documents =head1 SYNOPSIS use Template::Parser; $parser = Template::Parser->new(\%config); $template = $parser->parse($text) || die $parser->error(), "\n"; =head1 DESCRIPTION The C<Template::Parser> module implements a LALR(1) parser and associated methods for parsing template documents into Perl code. =head1 PUBLIC METHODS =head2 new(\%params) The C<new()> constructor creates and returns a reference to a new C<Template::Parser> object. A reference to a hash may be supplied as a parameter to provide configuration values. See L<CONFIGURATION OPTIONS> below for a summary of these options and L<Template::Manual::Config> for full details. my $parser = Template::Parser->new({ START_TAG => quotemeta('<+'), END_TAG => quotemeta('+>'), }); =head2 parse($text) The C<parse()> method parses the text passed in the first parameter and returns a reference to a hash array of data defining the compiled representation of the template text, suitable for passing to the L<Template::Document> L<new()|Template::Document#new()> constructor method. On error, undef is returned. $data = $parser->parse($text) || die $parser->error(); The C<$data> hash reference returned contains a C<BLOCK> item containing the compiled Perl code for the template, a C<DEFBLOCKS> item containing a reference to a hash array of sub-template C<BLOCK>s defined within in the template, and a C<METADATA> item containing a reference to a hash array of metadata values defined in C<META> tags. =head1 CONFIGURATION OPTIONS The C<Template::Parser> module accepts the following configuration options. Please see L<Template::Manual::Config> for futher details on each option. =head2 START_TAG, END_TAG The L<START_TAG|Template::Manual::Config#START_TAG_END_TAG> and L<END_TAG|Template::Manual::Config#START_TAG_END_TAG> options are used to specify character sequences or regular expressions that mark the start and end of a template directive. my $parser = Template::Parser->new({ START_TAG => quotemeta('<+'), END_TAG => quotemeta('+>'), }); =head2 TAG_STYLE The L<TAG_STYLE|Template::Manual::Config#TAG_STYLE> option can be used to set both L<START_TAG> and L<END_TAG> according to pre-defined tag styles. my $parser = Template::Parser->new({ TAG_STYLE => 'star', # [* ... *] }); =head2 PRE_CHOMP, POST_CHOMP The L<PRE_CHOMP|Template::Manual::Config#PRE_CHOMP_POST_CHOMP> and L<POST_CHOMP|Template::Manual::Config#PRE_CHOMP_POST_CHOMP> can be set to remove any whitespace before or after a directive tag, respectively. my $parser = Template::Parser-E<gt>new({ PRE_CHOMP => 1, POST_CHOMP => 1, }); =head2 INTERPOLATE The L<INTERPOLATE|Template::Manual::Config#INTERPOLATE> flag can be set to allow variables to be embedded in plain text blocks. my $parser = Template::Parser->new({ INTERPOLATE => 1, }); Variables should be prefixed by a C<$> to identify them, using curly braces to explicitly scope the variable name where necessary. Hello ${name}, The day today is ${day.today}. =head2 ANYCASE The L<ANYCASE|Template::Manual::Config#ANYCASE> option can be set to allow directive keywords to be specified in any case. # with ANYCASE set to 1 [% INCLUDE foobar %] # OK [% include foobar %] # OK [% include = 10 %] # ERROR, 'include' is a reserved word =head2 GRAMMAR The L<GRAMMAR|Template::Manual::Config#GRAMMAR> configuration item can be used to specify an alternate grammar for the parser. This allows a modified or entirely new template language to be constructed and used by the Template Toolkit. use MyOrg::Template::Grammar; my $parser = Template::Parser->new({ GRAMMAR = MyOrg::Template::Grammar->new(); }); By default, an instance of the default L<Template::Grammar> will be created and used automatically if a C<GRAMMAR> item isn't specified. =head2 DEBUG The L<DEBUG|Template::Manual::Config#DEBUG> option can be used to enable various debugging features of the C<Template::Parser> module. use Template::Constants qw( :debug ); my $template = Template->new({ DEBUG => DEBUG_PARSER | DEBUG_DIRS, }); =head1 AUTHOR Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/> =head1 COPYRIGHT Copyright (C) 1996-2007 Andy Wardley. All Rights Reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The main parsing loop of the C<Template::Parser> module was derived from a standalone parser generated by version 0.16 of the C<Parse::Yapp> module. The following copyright notice appears in the C<Parse::Yapp> documentation. The Parse::Yapp module and its related modules and shell scripts are copyright (c) 1998 Francois Desarmenien, France. All rights reserved. You may use and distribute them under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file. =head1 SEE ALSO L<Template>, L<Template::Grammar>, L<Template::Directive>
Dokaponteam/ITF_Project
xampp/perl/vendor/lib/Template/Parser.pm
Perl
mit
38,163
=pod =head1 NAME X509_NAME_get_index_by_NID, X509_NAME_get_index_by_OBJ, X509_NAME_get_entry, X509_NAME_entry_count, X509_NAME_get_text_by_NID, X509_NAME_get_text_by_OBJ - X509_NAME lookup and enumeration functions =head1 SYNOPSIS #include <openssl/x509.h> int X509_NAME_get_index_by_NID(X509_NAME *name,int nid,int lastpos); int X509_NAME_get_index_by_OBJ(X509_NAME *name,ASN1_OBJECT *obj, int lastpos); int X509_NAME_entry_count(X509_NAME *name); X509_NAME_ENTRY *X509_NAME_get_entry(X509_NAME *name, int loc); int X509_NAME_get_text_by_NID(X509_NAME *name, int nid, char *buf,int len); int X509_NAME_get_text_by_OBJ(X509_NAME *name, ASN1_OBJECT *obj, char *buf,int len); =head1 DESCRIPTION These functions allow an B<X509_NAME> structure to be examined. The B<X509_NAME> structure is the same as the B<Name> type defined in RFC2459 (and elsewhere) and used for example in certificate subject and issuer names. X509_NAME_get_index_by_NID() and X509_NAME_get_index_by_OBJ() retrieve the next index matching B<nid> or B<obj> after B<lastpos>. B<lastpos> should initially be set to -1. If there are no more entries -1 is returned. X509_NAME_entry_count() returns the total number of entries in B<name>. X509_NAME_get_entry() retrieves the B<X509_NAME_ENTRY> from B<name> corresponding to index B<loc>. Acceptable values for B<loc> run from 0 to (X509_NAME_entry_count(name) - 1). The value returned is an internal pointer which must not be freed. X509_NAME_get_text_by_NID(), X509_NAME_get_text_by_OBJ() retrieve the "text" from the first entry in B<name> which matches B<nid> or B<obj>, if no such entry exists -1 is returned. At most B<len> bytes will be written and the text written to B<buf> will be null terminated. The length of the output string written is returned excluding the terminating null. If B<buf> is <NULL> then the amount of space needed in B<buf> (excluding the final null) is returned. =head1 NOTES X509_NAME_get_text_by_NID() and X509_NAME_get_text_by_OBJ() are legacy functions which have various limitations which make them of minimal use in practice. They can only find the first matching entry and will copy the contents of the field verbatim: this can be highly confusing if the target is a muticharacter string type like a BMPString or a UTF8String. For a more general solution X509_NAME_get_index_by_NID() or X509_NAME_get_index_by_OBJ() should be used followed by X509_NAME_get_entry() on any matching indices and then the various B<X509_NAME_ENTRY> utility functions on the result. The list of all relevant B<NID_*> and B<OBJ_* codes> can be found in the source code header files E<lt>openssl/obj_mac.hE<gt> and/or E<lt>openssl/objects.hE<gt>. =head1 EXAMPLES Process all entries: int i; X509_NAME_ENTRY *e; for (i = 0; i < X509_NAME_entry_count(nm); i++) { e = X509_NAME_get_entry(nm, i); /* Do something with e */ } Process all commonName entries: int loc; X509_NAME_ENTRY *e; loc = -1; for (;;) { lastpos = X509_NAME_get_index_by_NID(nm, NID_commonName, lastpos); if (lastpos == -1) break; e = X509_NAME_get_entry(nm, lastpos); /* Do something with e */ } =head1 RETURN VALUES X509_NAME_get_index_by_NID() and X509_NAME_get_index_by_OBJ() return the index of the next matching entry or -1 if not found. X509_NAME_entry_count() returns the total number of entries. X509_NAME_get_entry() returns an B<X509_NAME> pointer to the requested entry or B<NULL> if the index is invalid. =head1 SEE ALSO L<ERR_get_error(3)|ERR_get_error(3)>, L<d2i_X509_NAME(3)|d2i_X509_NAME(3)> =head1 HISTORY TBA =cut
domenicosolazzo/philocademy
venv/src/node-v0.10.36/deps/openssl/openssl/doc/crypto/X509_NAME_get_index_by_NID.pod
Perl
mit
3,585
#!/usr/bin/env perl # Copyright 2009 The Go Authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. # This program reads a file containing function prototypes # (like syscall_darwin.go) and generates system call bodies. # The prototypes are marked by lines beginning with "//sys" # and read like func declarations if //sys is replaced by func, but: # * The parameter lists must give a name for each argument. # This includes return parameters. # * The parameter lists must give a type for each argument: # the (x, y, z int) shorthand is not allowed. # * If the return parameter is an error number, it must be named errno. # A line beginning with //sysnb is like //sys, except that the # goroutine will not be suspended during the execution of the system # call. This must only be used for system calls which can never # block, as otherwise the system call could cause all goroutines to # hang. use strict; my $cmdline = "mksyscall.pl " . join(' ', @ARGV); my $errors = 0; my $_32bit = ""; my $plan9 = 0; my $openbsd = 0; my $netbsd = 0; my $dragonfly = 0; my $nacl = 0; my $arm = 0; # 64-bit value should use (even, odd)-pair if($ARGV[0] eq "-b32") { $_32bit = "big-endian"; shift; } elsif($ARGV[0] eq "-l32") { $_32bit = "little-endian"; shift; } if($ARGV[0] eq "-plan9") { $plan9 = 1; shift; } if($ARGV[0] eq "-openbsd") { $openbsd = 1; shift; } if($ARGV[0] eq "-netbsd") { $netbsd = 1; shift; } if($ARGV[0] eq "-dragonfly") { $dragonfly = 1; shift; } if($ARGV[0] eq "-nacl") { $nacl = 1; shift; } if($ARGV[0] eq "-arm") { $arm = 1; shift; } if($ARGV[0] =~ /^-/) { print STDERR "usage: mksyscall.pl [-b32 | -l32] [file ...]\n"; exit 1; } sub parseparamlist($) { my ($list) = @_; $list =~ s/^\s*//; $list =~ s/\s*$//; if($list eq "") { return (); } return split(/\s*,\s*/, $list); } sub parseparam($) { my ($p) = @_; if($p !~ /^(\S*) (\S*)$/) { print STDERR "$ARGV:$.: malformed parameter: $p\n"; $errors = 1; return ("xx", "int"); } return ($1, $2); } my $text = ""; while(<>) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, errno error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # Try in vain to keep people from editing this file. # The theory is that they jump into the middle of the file # without reading the header. $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; # Go function header. my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my @uses = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass dummy pointer in that case. # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). $text .= "\tvar _p$n unsafe.Pointer\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; $text .= "\n"; push @args, "uintptr(_p$n)", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && ($openbsd || $netbsd)) { push @args, "0"; if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $dragonfly) { if ($func !~ /^extp(read|write)/i) { push @args, "0"; } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $_32bit ne "") { if(@args % 2 && $arm) { # arm abi specifies 64-bit argument uses # (even, odd) pair push @args, "0" } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name>>32)"; } } else { push @args, "uintptr($name)"; } } # Determine which form to use; pad args with zeros. my $asm = "Syscall"; if ($nonblock) { $asm = "RawSyscall"; } if(@args <= 3) { while(@args < 3) { push @args, "0"; } } elsif(@args <= 6) { $asm .= "6"; while(@args < 6) { push @args, "0"; } } elsif(@args <= 9) { $asm .= "9"; while(@args < 9) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # System call number. if($sysname eq "") { $sysname = "SYS_$func"; $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar $sysname =~ y/a-z/A-Z/; if($nacl) { $sysname =~ y/A-Z/a-z/; } } # Actual call. my $args = join(', ', @args); my $call = "$asm($sysname, $args)"; # Assign return values. my $body = ""; my @ret = ("_", "_", "_"); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err" && !$plan9) { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } elsif($name eq "err" && $plan9) { $ret[0] = "r0"; $ret[2] = "e1"; next; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1" || $plan9) { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } foreach my $use (@uses) { $text .= "\t$use\n"; } $text .= $body; if ($plan9 && $ret[2] eq "e1") { $text .= "\tif int32(r0) == -1 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } elsif ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n\n"; } chomp $text; chomp $text; if($errors) { exit 1; } print <<EOF; // $cmdline // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package syscall import "unsafe" $text EOF exit 0;
sagivo/go
src/syscall/mksyscall.pl
Perl
bsd-3-clause
8,024
#!/usr/bin/perl sub fibonacci { my $n = shift; $n < 3 ? 1: fibonacci($n - 1) + fibonacci($n - 2) } sub factorial { my $m = shift; if ($m==0) { return 1; } else { return $m*factorial($m-1); }} print "factorial:", factorial ($ARGV[0]),"\n" ; print "fibonacci:"; foreach (1..$ARGV[0]) { print fibonacci($_), " "; }
dimir2/hse12pi2-scripts
MartirosyanA/fibo.pl
Perl
mit
317
use strict; use Data::Dumper; use Carp; # # This is a SAS Component # =head1 NAME query_entity_Biomass =head1 SYNOPSIS query_entity_Biomass [--is field,value] [--like field,value] [--op operator,field,value] =head1 DESCRIPTION Query the entity Biomass. Results are limited using one or more of the query flags: =over 4 =item the C<--is> flag to match for exact values; =item the C<--like> flag for SQL LIKE searches, or =item the C<--op> flag for making other comparisons. =back A biomass is a collection of compounds in a specific ratio and in specific compartments that are necessary for a cell to function properly. The prediction of biomasses is key to the functioning of the model. Each biomass belongs to a specific model. Example: query_entity_Biomass -is id,exact-match-value -a > records =head2 Related entities The Biomass entity has the following relationship links: =over 4 =item IsComprisedOf CompoundInstance =item IsManagedBy Model =back =head1 COMMAND-LINE OPTIONS query_entity_Biomass [arguments] > records =over 4 =item --is field,value Limit the results to entities where the given field has the given value. =item --like field,value Limit the results to entities where the given field is LIKE (in the sql sense) the given value. =item --op operator,field,value Limit the results to entities where the given field is related to the given value based on the given operator. The operators supported are as follows. We provide text based alternatives to the comparison operators so that extra quoting is not required to keep the command-line shell from confusing them with shell I/O redirection operators. =over 4 =item < or lt =item > or gt =item <= or le =item >= or ge =item = =item LIKE =back =item --a Return all fields. =item --show-fields Display a list of the fields available for use. =item --fields field-list Choose a set of fields to return. Field-list is a comma-separated list of strings. The following fields are available: =over 4 =item mod_date =item name =item dna =item protein =item cell_wall =item lipid =item cofactor =item energy =back =back =head1 AUTHORS L<The SEED Project|http://www.theseed.org> =cut use Bio::KBase::CDMI::CDMIClient; use Getopt::Long; #Default fields my @all_fields = ( 'mod_date', 'name', 'dna', 'protein', 'cell_wall', 'lipid', 'cofactor', 'energy' ); my %all_fields = map { $_ => 1 } @all_fields, 'id'; our $usage = <<'END'; query_entity_Biomass [arguments] > records --is field,value Limit the results to entities where the given field has the given value. --like field,value Limit the results to entities where the given field is LIKE (in the sql sense) the given value. --op operator,field,value Limit the results to entities where the given field is related to the given value based on the given operator. The operators supported are as follows. We provide text based alternatives to the comparison operators so that extra quoting is not required to keep the command-line shell from confusing them with shell I/O redirection operators. < or lt > or gt <= or le >= or ge = LIKE -a Return all fields. --show-fields Display a list of the fields available for use. --fields field-list Choose a set of fields to return. Field-list is a comma-separated list of strings. The following fields are available: mod_date name dna protein cell_wall lipid cofactor energy END my $a; my $f; my @fields; my $help; my $show_fields; my @query_is; my @query_like; my @query_op; my %op_map = ('>', '>', 'gt', '>', '<', '<', 'lt', '<', '>=', '>=', 'ge', '>=', '<=', '<=', 'le', '<=', 'like', 'LIKE', ); my $geO = Bio::KBase::CDMI::CDMIClient->new_get_entity_for_script("all-fields|a" => \$a, "show-fields" => \$show_fields, "help|h" => \$help, "is=s" => \@query_is, "like=s" => \@query_like, "op=s" => \@query_op, "fields=s" => \$f); if ($help) { print $usage; exit 0; } elsif ($show_fields) { print STDERR "Available fields:\n"; print STDERR "\t$_\n" foreach @all_fields; exit 0; } if (@ARGV != 0 || ($a && $f)) { print STDERR $usage, "\n"; exit 1; } if ($a) { @fields = @all_fields; } elsif ($f) { my @err; for my $field (split(",", $f)) { if (!$all_fields{$field}) { push(@err, $field); } else { push(@fields, $field); } } if (@err) { print STDERR "all_entities_Biomass: unknown fields @err. Valid fields are: @all_fields\n"; exit 1; } } my @qry; for my $ent (@query_is) { my($field,$value) = split(/,/, $ent, 2); if (!$all_fields{$field}) { die "$field is not a valid field\n"; } push(@qry, [$field, '=', $value]); } for my $ent (@query_like) { my($field,$value) = split(/,/, $ent, 2); if (!$all_fields{$field}) { die "$field is not a valid field\n"; } push(@qry, [$field, 'LIKE', $value]); } for my $ent (@query_op) { my($op,$field,$value) = split(/,/, $ent, 3); if (!$all_fields{$field}) { die "$field is not a valid field\n"; } my $mapped_op = $op_map{lc($op)}; if (!$mapped_op) { die "$op is not a valid operator\n"; } push(@qry, [$field, $mapped_op, $value]); } my $h = $geO->query_entity_Biomass(\@qry, \@fields ); while (my($k, $v) = each %$h) { print join("\t", $k, map { ref($_) eq 'ARRAY' ? join(",", @$_) : $_ } @$v{@fields}), "\n"; }
kbase/kb_seed
scripts/query_entity_Biomass.pl
Perl
mit
5,674
package Reply::Plugin::Colors; BEGIN { $Reply::Plugin::Colors::AUTHORITY = 'cpan:DOY'; } $Reply::Plugin::Colors::VERSION = '0.37'; use strict; use warnings; # ABSTRACT: colorize output use base 'Reply::Plugin'; use Term::ANSIColor; BEGIN { if ($^O eq 'MSWin32') { require Win32::Console::ANSI; Win32::Console::ANSI->import; } } sub new { my $class = shift; my %opts = @_; my $self = $class->SUPER::new(@_); $self->{error} = $opts{error} || 'red'; $self->{warning} = $opts{warning} || 'yellow'; $self->{result} = $opts{result} || 'green'; return $self; } sub compile { my $self = shift; my ($next, @args) = @_; local $SIG{__WARN__} = sub { $self->print_warn(@_) }; $next->(@args); } sub execute { my $self = shift; my ($next, @args) = @_; local $SIG{__WARN__} = sub { $self->print_warn(@_) }; $next->(@args); } sub print_error { my $self = shift; my ($next, $error) = @_; print color($self->{error}); $next->($error); local $| = 1; print color('reset'); } sub print_result { my $self = shift; my ($next, @result) = @_; print color($self->{result}); $next->(@result); local $| = 1; print color('reset'); } sub print_warn { my $self = shift; my ($warning) = @_; print color($self->{warning}); print $warning; local $| = 1; print color('reset'); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Reply::Plugin::Colors - colorize output =head1 VERSION version 0.37 =head1 SYNOPSIS ; .replyrc [Colors] error = bright red warning = bright yellow result = bright green =head1 DESCRIPTION This plugin adds coloring to the results when they are printed to the screen. By default, errors are C<red>, warnings are C<yellow>, and normal results are C<green>, although this can be overridden through configuration as shown in the synopsis. L<Term::ANSIColor> is used to generate the colors, so any value that is accepted by that module is a valid value for the C<error>, C<warning>, and C<result> options. =for Pod::Coverage print_warn =head1 AUTHOR Jesse Luehrs <doy@tozt.net> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2014 by Jesse Luehrs. This is free software, licensed under: The MIT (X11) License =cut
gitpan/Reply
lib/Reply/Plugin/Colors.pm
Perl
mit
2,318
#!/usr/bin/perl -w use strict; my $sUsage = qq( perl $0 <pasa transcript isoform gff> <ctg fasta file> <flanking lenght, 30> <output file> ); die $sUsage unless @ARGV >= 3; my ($gff, $fasta, $fl, $outfile) = @ARGV; my ($strand, $contigs, $gene_pos)= read_gff($gff); my %fasta_seq = read_fasta($fasta); open (OUT ,">$outfile") or die $!; foreach my $gene(keys %$gene_pos) { foreach my $asmbl (keys %{$gene_pos->{$gene}}) { my @introns; my @ctg_pos; next unless @{$gene_pos->{$gene}{$asmbl}} >1; my $arrref = $gene_pos->{$gene}{$asmbl}; foreach my $index ( 0..(scalar @$arrref -2)) { my @pos = ($arrref->[$index]->[2], $arrref->[$index]->[3], $arrref->[$index+1]->[2], $arrref->[$index+1]->[3]); @pos = sort{$a<=>$b} @pos; push @ctg_pos, [$pos[1]+1, $pos[2]-1]; push @introns, join("_",($arrref->[$index]->[0], $arrref->[$index]->[1], $arrref->[$index+1]->[0], $arrref->[$index+1]->[1])); print STDERR $introns[$index],"\n" if $asmbl eq 'asmbl_7587'; print STDERR join("\t",($arrref->[$index]->[0], $arrref->[$index]->[1])),"\n" if $asmbl eq 'asmbl_7587'; print STDERR $gene_pos->{$gene}{$asmbl}->[$index]->[0],"\t", $gene_pos->{$gene}{$asmbl}->[$index]->[1],"\n" if $asmbl eq 'asmbl_7587'; } foreach my $ind (0..$#ctg_pos) { my ($start, $end) = @{$ctg_pos[$ind]}; ($start, $end) = ($end, $start) if $start > $end; my $seq = substr($fasta_seq{$contigs->{$asmbl}}, $start-1-$fl, ($end-$start+1+$fl*2)); print OUT '>', join("_",($gene, $asmbl, $introns[$ind])),"\n", $seq, "\n"; # print STDERR $introns[$ind],"\n" if $asmbl eq 'asmbl_7587'; } } } close OUT; sub read_gff { my $file = shift; open (IN, $gff) or die; my %strand; my %contigs; my %return; while (<IN>) { next if /^\s+$/; # ID=S10-asmbl_10; Target=asmbl_10 1 399 + my ($gene, $asmbl, $start, $end) = $_ =~ /ID=(S\d+)\-(asmbl_\d+).*Target\S+\s(\d+)\s(\d+)/; my @t=split /\t/,$_; $strand{$asmbl} = $t[6]; $contigs{$asmbl} = $t[0]; print STDERR join("\t", ($start, $end)),"\n" if $asmbl eq 'asmbl_7587'; push @{$return{$gene}{$asmbl}}, [$start, $end, @t[3, 4]]; } close IN; return (\%strand, \%contigs, \%return) } sub read_fasta { my $file = shift; open (IN, "$file") or die "$! $file\n"; my %return_hash; my $id; my $debug = 1; while (<IN>) { next if /^\s+$/; chomp; if (/^>(\S+)/) { $id = $1; print 'fasta id: ', $id ,"\n" if $debug; $debug = 0; $return_hash{$id} = ''; next; } $return_hash{$id} .= $_; } close IN; return %return_hash; }
swang8/Perl_scripts_misc
extract_intron_and_flanking_pasa.pl
Perl
mit
2,520
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use XML::Simple; my ($fin, $fout) = (\*STDIN, \*STDOUT); if (my $ifname = shift) { open $fin, '<', $ifname or die $!; if (my $ofname = shift) { open $fout, '>', $ofname or die $!; } } my $xml = new XML::Simple; my $data = $xml->XMLin($fin); print $fout <<END; #include "foreigns.hh" #include <string> #include <vector> using namespace std; const vector<ForeignCategory> ForeignInfo::categories = { END for my $catname (keys $data->{'category'}) { my $catcname = $data->{'category'}{$catname}{'cname'}; my $fs = $data->{'category'}{$catname}{'foreign'}; print $fout "\tForeignCategory(\"$catname\", \"$catcname\", {\n"; for my $fname (keys %$fs) { my $fcname = $fs->{$fname}{cname}; my $desc = $fs->{$fname}{description}; $desc = "" if ref($desc); $desc =~ s/\n/ /msg; $desc =~ s/^\s+//; $desc =~ s/\s+$//; $desc =~ s/\s+/ /msg; $desc =~ s/"/\\"/msg; # TODO escape better print $fout "\t\tForeignFunc(\"$fname\", \"$fcname\", \"\", BlockType({}, {}, {})),\n"; } print $fout "\t}),\n"; } print $fout <<END; }; END close $fin; close $fout;
bytbox/EVAN
tools/gen-foreigns-cc.pl
Perl
mit
1,139
#!/usr/bin/perl =pod Hello World server Binds REP socket to tcp://*:5555 Expects "Hello" from client, replies with "World" Author: Daisuke Maki (lestrrat) Original version Author: Alexander D'Archangel (darksuji) <darksuji(at)gmail(dot)com> =cut use strict; use warnings; use 5.10.0; use ZMQ::LibZMQ3; use ZMQ::Constants qw(ZMQ_REP); my $MAX_MSGLEN = 255; my $context = zmq_init(); # Socket to talk to clients my $responder = zmq_socket($context, ZMQ_REP); zmq_bind($responder, 'tcp://*:5555'); while (1) { # Wait for the next request from client my $message; my $size = zmq_recv($responder, $message, $MAX_MSGLEN); my $request = substr($message, 0, $size); say 'Received request: ['. $request .']'; # Do some 'work' sleep (1); # Send reply back to client zmq_send($responder, 'World'); }
soscpd/bee
root/tests/zguide/examples/Perl/hwserver.pl
Perl
mit
838
package Text::Xslate::Parser; use Mouse; use Scalar::Util (); use Text::Xslate::Symbol; use Text::Xslate::Util qw( $DEBUG $STRING $NUMBER is_int any_in neat literal_to_value make_error p ); use constant _DUMP_PROTO => scalar($DEBUG =~ /\b dump=proto \b/xmsi); use constant _DUMP_TOKEN => scalar($DEBUG =~ /\b dump=token \b/xmsi); our @CARP_NOT = qw(Text::Xslate::Compiler Text::Xslate::Symbol); my $CODE = qr/ (?: $STRING | [^'"] ) /xms; my $COMMENT = qr/\# [^\n;]* (?= [;\n] | \z)/xms; # Operator tokens that the parser recognizes. # All the single characters are tokenized as an operator. my $OPERATOR_TOKEN = sprintf '(?:%s|[^ \t\r\n])', join('|', map{ quotemeta } qw( ... .. == != <=> <= >= << >> += -= *= /= %= ~= &&= ||= //= ~~ =~ && || // -> => :: ++ -- +| +& +^ +< +> +~ ), ','); my %shortcut_table = ( '=' => 'print', ); my $CHOMP_FLAGS = qr/-/xms; has identity_pattern => ( is => 'ro', isa => 'RegexpRef', builder => '_build_identity_pattern', init_arg => undef, ); sub _build_identity_pattern { return qr/(?: (?:[A-Za-z_]|\$\~?) [A-Za-z0-9_]* )/xms; } has [qw(compiler engine)] => ( is => 'rw', required => 0, weak_ref => 1, ); has symbol_table => ( # the global symbol table is => 'ro', isa => 'HashRef', default => sub{ {} }, init_arg => undef, ); has iterator_element => ( is => 'ro', isa => 'HashRef', lazy => 1, builder => '_build_iterator_element', init_arg => undef, ); has scope => ( is => 'rw', isa => 'ArrayRef[HashRef]', clearer => 'init_scope', lazy => 1, default => sub{ [ {} ] }, init_arg => undef, ); has token => ( is => 'rw', isa => 'Maybe[Object]', init_arg => undef, ); has next_token => ( # to peek the next token is => 'rw', isa => 'Maybe[ArrayRef]', init_arg => undef, ); has statement_is_finished => ( is => 'rw', isa => 'Bool', init_arg => undef, ); has following_newline => ( is => 'rw', isa => 'Int', default => 0, init_arg => undef, ); has input => ( is => 'rw', isa => 'Str', init_arg => undef, ); has line_start => ( is => 'ro', isa => 'Maybe[Str]', builder => '_build_line_start', ); sub _build_line_start { ':' } has tag_start => ( is => 'ro', isa => 'Str', builder => '_build_tag_start', ); sub _build_tag_start { '<:' } has tag_end => ( is => 'ro', isa => 'Str', builder => '_build_tag_end', ); sub _build_tag_end { ':>' } has comment_pattern => ( is => 'ro', isa => 'RegexpRef', builder => '_build_comment_pattern', ); sub _build_comment_pattern { $COMMENT } has shortcut_table => ( is => 'ro', isa => 'HashRef[Str]', builder => '_build_shortcut_table', ); sub _build_shortcut_table { \%shortcut_table } has in_given => ( is => 'rw', isa => 'Bool', init_arg => undef, ); # attributes for error messages has near_token => ( is => 'rw', init_arg => undef, ); has file => ( is => 'rw', required => 0, ); has line => ( is => 'rw', required => 0, ); has input_layer => ( is => 'ro', default => ':utf8', ); sub symbol_class() { 'Text::Xslate::Symbol' } # the entry point sub parse { my($parser, $input, %args) = @_; local $parser->{file} = $args{file} || \$input; local $parser->{line} = $args{line} || 1; local $parser->{in_given} = 0; local $parser->{scope} = [ map { +{ %{$_} } } @{ $parser->scope } ]; local $parser->{symbol_table} = { %{ $parser->symbol_table } }; local $parser->{near_token}; local $parser->{next_token}; local $parser->{token}; local $parser->{input}; $parser->input( $parser->preprocess($input) ); $parser->next_token( $parser->tokenize() ); $parser->advance(); my $ast = $parser->statements(); if(my $input_pos = pos $parser->{input}) { if($input_pos != length($parser->{input})) { $parser->_error("Syntax error", $parser->token); } } return $ast; } sub trim_code { my($parser, $s) = @_; $s =~ s/\A [ \t]+ //xms; $s =~ s/ [ \t]+ \n?\z//xms; return $s; } sub auto_chomp { my($parser, $tokens_ref, $i, $s_ref) = @_; my $p; my $nl = 0; # postchomp if($i >= 1 and ($p = $tokens_ref->[$i-1])->[0] eq 'postchomp') { # [ CODE ][*][ TEXT ] # <: ... -:> \nfoobar # ^^^^ ${$s_ref} =~ s/\A [ \t]* (\n)//xms; if($1) { $nl++; } } # prechomp if(($i+1) < @{$tokens_ref} and ($p = $tokens_ref->[$i+1])->[0] eq 'prechomp') { if(${$s_ref} !~ / [^ \t] /xms) { # HERE # [ TEXT ][*][ CODE ] # <:- ... :> # ^^^^^^^^ ${$s_ref} = ''; } else { # HERE # [ TEXT ][*][ CODE ] # \n<:- ... :> # ^^ $nl += chomp ${$s_ref}; } } elsif(($i+2) < @{$tokens_ref} and ($p = $tokens_ref->[$i+2])->[0] eq 'prechomp' and ($p = $tokens_ref->[$i+1])->[0] eq 'text' and $p->[1] !~ / [^ \t] /xms) { # HERE # [ TEXT ][ TEXT ][*][ CODE ] # \n <:- ... :> # ^^^^^^^^^^ $p->[1] = ''; $nl += (${$s_ref} =~ s/\n\z//xms); } return $nl; } # split templates by tags before tokenizing sub split :method { my $parser = shift; local($_) = @_; my @tokens; my $line_start = $parser->line_start; my $tag_start = $parser->tag_start; my $tag_end = $parser->tag_end; my $lex_line_code = defined($line_start) && qr/\A ^ [ \t]* \Q$line_start\E ([^\n]* \n?) /xms; my $lex_tag_start = qr/\A \Q$tag_start\E ($CHOMP_FLAGS?)/xms; # 'text' is a something without newlines # following a newline, $tag_start, or end of the input my $lex_text = qr/\A ( [^\n]*? (?: \n | (?= \Q$tag_start\E ) | \z ) ) /xms; my $lex_comment = $parser->comment_pattern; my $lex_code = qr/(?: $lex_comment | $CODE )/xms; my $in_tag = 0; while($_ ne '') { if($in_tag) { my $start = 0; my $pos; while( ($pos = index $_, $tag_end, $start) >= 0 ) { my $code = substr $_, 0, $pos; $code =~ s/$lex_code//xmsg; if(length($code) == 0) { last; } $start = $pos + 1; } if($pos >= 0) { my $code = substr $_, 0, $pos, ''; $code =~ s/($CHOMP_FLAGS?) \z//xmso; my $chomp = $1; s/\A \Q$tag_end\E //xms or die "Oops!"; push @tokens, [ code => $code ]; if($chomp) { push @tokens, [ postchomp => $chomp ]; } $in_tag = 0; } else { last; # the end tag is not found } } # not $in_tag elsif($lex_line_code && (@tokens == 0 || $tokens[-1][1] =~ /\n\z/xms) && s/$lex_line_code//xms) { push @tokens, [ code => $1 ]; } elsif(s/$lex_tag_start//xms) { $in_tag = 1; my $chomp = $1; if($chomp) { push @tokens, [ prechomp => $chomp ]; } } elsif(s/$lex_text//xms) { push @tokens, [ text => $1 ]; } else { confess "Oops: Unreached code, near" . p($_); } } if($in_tag) { # calculate line number my $orig_src = $_[0]; substr $orig_src, -length($_), length($_), ''; my $line = ($orig_src =~ tr/\n/\n/); $parser->_error("Malformed templates detected", neat((split /\n/, $_)[0]), ++$line, ); } #p(\@tokens); return \@tokens; } sub preprocess { my($parser, $input) = @_; # tokenization my $tokens_ref = $parser->split($input); my $code = ''; my $shortcut_table = $parser->shortcut_table; my $shortcut = join('|', map{ quotemeta } keys %shortcut_table); my $shortcut_rx = qr/\A ($shortcut)/xms; for(my $i = 0; $i < @{$tokens_ref}; $i++) { my($type, $s) = @{ $tokens_ref->[$i] }; if($type eq 'text') { my $nl = $parser->auto_chomp($tokens_ref, $i, \$s); $s =~ s/(["\\])/\\$1/gxms; # " for poor editors # $s may have single new line $nl += ($s =~ s/\n/\\n/xms); $code .= qq{print_raw "$s";}; # must set even if $s is empty $code .= qq{\n} if $nl > 0; } elsif($type eq 'code') { # shortcut commands $s =~ s/$shortcut_rx/$shortcut_table->{$1}/xms if $shortcut; $s = $parser->trim_code($s); if($s =~ /\A \s* [}] \s* \z/xms){ $code .= $s; } elsif($s =~ s/\n\z//xms) { $code .= qq{$s\n}; } else { $code .= qq{$s;}; # auto semicolon insertion } } elsif($type eq 'prechomp') { # noop, just a marker } elsif($type eq 'postchomp') { # noop, just a marker } else { $parser->_error("Oops: Unknown token: $s ($type)"); } } print STDOUT $code, "\n" if _DUMP_PROTO; return $code; } sub BUILD { my($parser) = @_; $parser->_init_basic_symbols(); $parser->init_symbols(); return; } # The grammer sub _init_basic_symbols { my($parser) = @_; $parser->symbol('(end)')->is_block_end(1); # EOF # prototypes of value symbols foreach my $type (qw(name variable literal)) { my $s = $parser->symbol("($type)"); $s->arity($type); $s->set_nud( $parser->can("nud_$type") ); } # common separators $parser->symbol(';')->set_nud(\&nud_separator); $parser->define_pair('(' => ')'); $parser->define_pair('{' => '}'); $parser->define_pair('[' => ']'); $parser->symbol(',') ->is_comma(1); $parser->symbol('=>') ->is_comma(1); # common commands $parser->symbol('print') ->set_std(\&std_print); $parser->symbol('print_raw')->set_std(\&std_print); # special literals $parser->define_literal(nil => undef); $parser->define_literal(true => 1); $parser->define_literal(false => 0); # special tokens $parser->symbol('__FILE__')->set_nud(\&nud_current_file); $parser->symbol('__LINE__')->set_nud(\&nud_current_line); $parser->symbol('__ROOT__')->set_nud(\&nud_current_vars); return; } sub init_basic_operators { my($parser) = @_; # define operator precedence $parser->prefix('{', 256, \&nud_brace); $parser->prefix('[', 256, \&nud_brace); $parser->infix('(', 256, \&led_call); $parser->infix('.', 256, \&led_dot); $parser->infix('[', 256, \&led_fetch); $parser->prefix('(', 256, \&nud_paren); $parser->prefix('!', 200)->is_logical(1); $parser->prefix('+', 200); $parser->prefix('-', 200); $parser->prefix('+^', 200); # numeric bitwise negate $parser->infix('*', 190); $parser->infix('/', 190); $parser->infix('%', 190); $parser->infix('x', 190); $parser->infix('+&', 190); # numeric bitwise and $parser->infix('+', 180); $parser->infix('-', 180); $parser->infix('~', 180); # connect $parser->infix('+|', 180); # numeric bitwise or $parser->infix('+^', 180); # numeric bitwise xor $parser->prefix('defined', 170, \&nud_defined); # named unary operator $parser->infix('<', 160)->is_logical(1); $parser->infix('<=', 160)->is_logical(1); $parser->infix('>', 160)->is_logical(1); $parser->infix('>=', 160)->is_logical(1); $parser->infix('==', 150)->is_logical(1); $parser->infix('!=', 150)->is_logical(1); $parser->infix('<=>', 150); $parser->infix('cmp', 150); $parser->infix('~~', 150); $parser->infix('|', 140, \&led_pipe); $parser->infix('&&', 130)->is_logical(1); $parser->infix('||', 120)->is_logical(1); $parser->infix('//', 120)->is_logical(1); $parser->infix('min', 120); $parser->infix('max', 120); $parser->infix('..', 110, \&led_range); $parser->symbol(':'); $parser->infixr('?', 100, \&led_ternary); $parser->assignment('=', 90); $parser->assignment('+=', 90); $parser->assignment('-=', 90); $parser->assignment('*=', 90); $parser->assignment('/=', 90); $parser->assignment('%=', 90); $parser->assignment('~=', 90); $parser->assignment('&&=', 90); $parser->assignment('||=', 90); $parser->assignment('//=', 90); $parser->make_alias('!' => 'not')->ubp(70); $parser->make_alias('&&' => 'and')->lbp(60); $parser->make_alias('||' => 'or') ->lbp(50); return; } sub init_symbols { my($parser) = @_; my $s; # syntax specific separators $parser->symbol('{'); $parser->symbol('}')->is_block_end(1); # block end $parser->symbol('->'); $parser->symbol('else'); $parser->symbol('with'); $parser->symbol('::'); # operators $parser->init_basic_operators(); # statements $s = $parser->symbol('if'); $s->set_std(\&std_if); $s->can_be_modifier(1); $parser->symbol('for') ->set_std(\&std_for); $parser->symbol('while' ) ->set_std(\&std_while); $parser->symbol('given') ->set_std(\&std_given); $parser->symbol('when') ->set_std(\&std_when); $parser->symbol('default') ->set_std(\&std_when); $parser->symbol('include') ->set_std(\&std_include); $parser->symbol('last') ->set_std(\&std_last); $parser->symbol('next') ->set_std(\&std_next); # macros $parser->symbol('cascade') ->set_std(\&std_cascade); $parser->symbol('macro') ->set_std(\&std_proc); $parser->symbol('around') ->set_std(\&std_proc); $parser->symbol('before') ->set_std(\&std_proc); $parser->symbol('after') ->set_std(\&std_proc); $parser->symbol('block') ->set_std(\&std_macro_block); $parser->symbol('super') ->set_std(\&std_super); $parser->symbol('override') ->set_std(\&std_override); $parser->symbol('->') ->set_nud(\&nud_lambda); # lexical variables/constants stuff $parser->symbol('constant')->set_nud(\&nud_constant); $parser->symbol('my' )->set_nud(\&nud_constant); return; } sub _build_iterator_element { return { index => \&iterator_index, count => \&iterator_count, is_first => \&iterator_is_first, is_last => \&iterator_is_last, body => \&iterator_body, size => \&iterator_size, max_index => \&iterator_max_index, peek_next => \&iterator_peek_next, peek_prev => \&iterator_peek_prev, cycle => \&iterator_cycle, }; } sub symbol { my($parser, $id, $lbp) = @_; my $stash = $parser->symbol_table; my $s = $stash->{$id}; if(defined $s) { if(defined $lbp) { $s->lbp($lbp); } } else { # create a new symbol $s = $parser->symbol_class->new(id => $id, lbp => $lbp || 0); $stash->{$id} = $s; } return $s; } sub define_pair { my($parser, $left, $right) = @_; $parser->symbol($left) ->counterpart($right); $parser->symbol($right)->counterpart($left); return; } # the low-level tokenizer. Don't use it directly, use advance() instead. sub tokenize { my($parser) = @_; local *_ = \$parser->{input}; my $comment_rx = $parser->comment_pattern; my $id_rx = $parser->identity_pattern; my $count = 0; TRY: { /\G (\s*) /xmsgc; $count += ( $1 =~ tr/\n/\n/); $parser->following_newline( $count ); if(/\G $comment_rx /xmsgc) { redo TRY; # retry } elsif(/\G ($id_rx)/xmsgc){ return [ name => $1 ]; } elsif(/\G ($NUMBER | $STRING)/xmsogc){ return [ literal => $1 ]; } elsif(/\G ($OPERATOR_TOKEN)/xmsogc){ return [ operator => $1 ]; } elsif(/\G (\S+)/xmsgc) { Carp::confess("Oops: Unexpected token '$1'"); } else { # empty return [ special => '(end)' ]; } } } sub next_token_is { my($parser, $token) = @_; return $parser->next_token->[1] eq $token; } # the high-level tokenizer sub advance { my($parser, $expect) = @_; my $t = $parser->token; if(defined($expect) && $t->id ne $expect) { $parser->_unexpected(neat($expect), $t); } $parser->near_token($t); my $stash = $parser->symbol_table; $t = $parser->next_token; if($t->[0] eq 'special') { return $parser->token( $stash->{ $t->[1] } ); } $parser->statement_is_finished( $parser->following_newline != 0 ); my $line = $parser->line( $parser->line + $parser->following_newline ); $parser->next_token( $parser->tokenize() ); my($arity, $id) = @{$t}; if( $arity eq "name" && $parser->next_token_is("=>") ) { $arity = "literal"; } print STDOUT "[$arity => $id] #$line\n" if _DUMP_TOKEN; my $symbol; if($arity eq "literal") { $symbol = $parser->symbol('(literal)')->clone( id => $id, value => $parser->parse_literal($id) ); } elsif($arity eq "operator") { $symbol = $stash->{$id}; if(not defined $symbol) { $parser->_error("Unknown operator '$id'"); } $symbol = $symbol->clone( arity => $arity, # to make error messages clearer ); } else { # name # find_or_create() returns a cloned symbol, # so there's not need to clone() here $symbol = $parser->find_or_create($id); } $symbol->line($line); return $parser->token($symbol); } sub parse_literal { my($parser, $literal) = @_; return literal_to_value($literal); } sub nud_name { my($parser, $symbol) = @_; return $symbol->clone( arity => 'name', ); } sub nud_variable { my($parser, $symbol) = @_; return $symbol->clone( arity => 'variable', ); } sub nud_literal { my($parser, $symbol) = @_; return $symbol->clone( arity => 'literal', ); } sub default_nud { my($parser, $symbol) = @_; return $symbol->clone(); # as is } sub default_led { my($parser, $symbol) = @_; $parser->near_token($parser->token); $parser->_error( sprintf 'Missing operator (%s): %s', $symbol->arity, $symbol->id); } sub default_std { my($parser, $symbol) = @_; $parser->near_token($parser->token); $parser->_error( sprintf 'Not a statement (%s): %s', $symbol->arity, $symbol->id); } sub expression { my($parser, $rbp) = @_; my $t = $parser->token; $parser->advance(); my $left = $t->nud($parser); while($rbp < $parser->token->lbp) { $t = $parser->token; $parser->advance(); $left = $t->led($parser, $left); } return $left; } sub expression_list { my($parser) = @_; my @list; while(1) { if($parser->token->is_value) { push @list, $parser->expression(0); } if(!$parser->token->is_comma) { last; } $parser->advance(); # comma } return \@list; } # for left associative infix operators sub led_infix { my($parser, $symbol, $left) = @_; return $parser->binary( $symbol, $left, $parser->expression($symbol->lbp) ); } sub infix { my($parser, $id, $bp, $led) = @_; my $symbol = $parser->symbol($id, $bp); $symbol->set_led($led || \&led_infix); return $symbol; } # for right associative infix operators sub led_infixr { my($parser, $symbol, $left) = @_; return $parser->binary( $symbol, $left, $parser->expression($symbol->lbp - 1) ); } sub infixr { my($parser, $id, $bp, $led) = @_; my $symbol = $parser->symbol($id, $bp); $symbol->set_led($led || \&led_infixr); return $symbol; } # for prefix operators sub prefix { my($parser, $id, $bp, $nud) = @_; my $symbol = $parser->symbol($id); $symbol->ubp($bp); $symbol->set_nud($nud || \&nud_prefix); return $symbol; } sub nud_prefix { my($parser, $symbol) = @_; my $un = $symbol->clone(arity => 'unary'); $parser->reserve($un); $un->first($parser->expression($symbol->ubp)); return $un; } sub led_assignment { my($parser, $symbol, $left) = @_; $parser->_error("Assignment ($symbol) is forbidden", $left); } sub assignment { my($parser, $id, $bp) = @_; $parser->symbol($id, $bp)->set_led(\&led_assignment); return; } # the ternary is a right associative operator sub led_ternary { my($parser, $symbol, $left) = @_; my $if = $symbol->clone(arity => 'if'); $if->first($left); $if->second([$parser->expression( $symbol->lbp - 1 )]); $parser->advance(":"); $if->third([$parser->expression( $symbol->lbp - 1 )]); return $if; } sub is_valid_field { my($parser, $token) = @_; my $arity = $token->arity; if($arity eq "name") { return 1; } elsif($arity eq "literal") { return is_int($token->id); } return 0; } sub led_dot { my($parser, $symbol, $left) = @_; my $t = $parser->token; if(!$parser->is_valid_field($t)) { $parser->_unexpected("a field name", $t); } my $dot = $symbol->clone( arity => "field", first => $left, second => $t->clone(arity => 'literal'), ); $t = $parser->advance(); if($t->id eq "(") { $parser->advance(); # "(" $dot->third( $parser->expression_list() ); $parser->advance(")"); $dot->arity("methodcall"); } return $dot; } sub led_fetch { # $h[$field] my($parser, $symbol, $left) = @_; my $fetch = $symbol->clone( arity => "field", first => $left, second => $parser->expression(0), ); $parser->advance("]"); return $fetch; } sub call { my($parser, $function, @args) = @_; if(not ref $function) { $function = $parser->symbol('(name)')->clone( arity => 'name', id => $function, line => $parser->line, ); } return $parser->symbol('(call)')->clone( arity => 'call', first => $function, second => \@args, ); } sub led_call { my($parser, $symbol, $left) = @_; my $call = $symbol->clone(arity => 'call'); $call->first($left); $call->second( $parser->expression_list() ); $parser->advance(")"); return $call; } sub led_pipe { # filter my($parser, $symbol, $left) = @_; # a | b -> b(a) return $parser->call($parser->expression($symbol->lbp), $left); } sub led_range { # x .. y my($parser, $symbol, $left) = @_; return $symbol->clone( arity => 'range', first => $left, second => $parser->expression(0), ); } sub nil { my($parser) = @_; return $parser->symbol('nil')->nud($parser); } sub nud_defined { my($parser, $symbol) = @_; $parser->reserve( $symbol->clone() ); # prefix:<defined> is a syntactic sugar to $a != nil return $parser->binary( '!=', $parser->expression($symbol->ubp), $parser->nil, ); } # for special literals (e.g. nil, true, false) sub nud_special { my($parser, $symbol) = @_; return $symbol->first; } sub define_literal { # special literals my($parser, $id, $value) = @_; my $symbol = $parser->symbol($id); $symbol->first( $symbol->clone( arity => defined($value) ? 'literal' : 'nil', value => $value, ) ); $symbol->set_nud(\&nud_special); $symbol->is_defined(1); return $symbol; } sub new_scope { my($parser) = @_; push @{ $parser->scope }, {}; return; } sub pop_scope { my($parser) = @_; pop @{ $parser->scope }; return; } sub undefined_name { my($parser, $name) = @_; if($name =~ /\A \$/xms) { return $parser->symbol_table->{'(variable)'}->clone( id => $name, ); } else { return $parser->symbol_table->{'(name)'}->clone( id => $name, ); } } sub find_or_create { # find a name from all the scopes my($parser, $name) = @_; my $s; foreach my $scope(reverse @{$parser->scope}){ $s = $scope->{$name}; if(defined $s) { return $s->clone(); } } $s = $parser->symbol_table->{$name}; return defined($s) ? $s : $parser->undefined_name($name); } sub reserve { # reserve a name to the scope my($parser, $symbol) = @_; if($symbol->arity ne 'name' or $symbol->is_reserved) { return $symbol; } my $top = $parser->scope->[-1]; my $t = $top->{$symbol->id}; if($t) { if($t->is_reserved) { return $symbol; } if($t->arity eq "name") { $parser->_error("Already defined: $symbol"); } } $top->{$symbol->id} = $symbol; $symbol->is_reserved(1); #$symbol->scope($top); return $symbol; } sub define { # define a name to the scope my($parser, $symbol) = @_; my $top = $parser->scope->[-1]; my $t = $top->{$symbol->id}; if(defined $t) { $parser->_error($t->is_reserved ? "Already is_reserved: $t" : "Already defined: $t"); } $top->{$symbol->id} = $symbol; $symbol->is_defined(1); $symbol->is_reserved(0); $symbol->remove_nud(); $symbol->remove_led(); $symbol->remove_std(); $symbol->lbp(0); #$symbol->scope($top); return $symbol; } sub print { my($parser, @args) = @_; return $parser->symbol('print')->clone( arity => 'print', first => \@args, line => $parser->line, ); } sub binary { my($parser, $symbol, $lhs, $rhs) = @_; if(!ref $symbol) { # operator $symbol = $parser->symbol($symbol); } if(!ref $lhs) { # literal $lhs = $parser->symbol('(literal)')->clone( id => $lhs, ); } if(!ref $rhs) { # literal $rhs = $parser->symbol('(literal)')->clone( id => $rhs, ); } return $symbol->clone( arity => 'binary', first => $lhs, second => $rhs, ); } sub define_function { my($parser, @names) = @_; foreach my $name(@names) { my $s = $parser->symbol($name); $s->set_nud(\&nud_name); $s->is_defined(1); } return; } sub finish_statement { my($parser, $expr) = @_; my $t = $parser->token; if($t->can_be_modifier) { $parser->advance(); $expr = $t->std($parser, $expr); $t = $parser->token; } if($t->is_block_end or $parser->statement_is_finished) { # noop } elsif($t->id eq ";") { $parser->advance(); } else { $parser->_unexpected("a semicolon or block end", $t); } return $expr; } sub statement { # process one or more statements my($parser) = @_; my $t = $parser->token; if($t->id eq ";"){ $parser->advance(); # ";" return; } if($t->has_std) { # is $t a statement? $parser->reserve($t); $parser->advance(); # std() can return a list of nodes return $t->std($parser); } my $expr = $parser->auto_command( $parser->expression(0) ); return $parser->finish_statement($expr); } sub auto_command { my($parser, $expr) = @_; if($expr->is_statement) { # expressions can produce pure statements (e.g. assignment ) return $expr; } else { return $parser->print($expr); } } sub statements { # process statements my($parser) = @_; my @a; for(my $t = $parser->token; !$t->is_block_end; $t = $parser->token) { push @a, $parser->statement(); } return \@a; } sub block { my($parser) = @_; $parser->new_scope(); $parser->advance("{"); my $a = $parser->statements(); $parser->advance("}"); $parser->pop_scope(); return $a; } sub nud_paren { my($parser, $symbol) = @_; my $expr = $parser->expression(0); $parser->advance( $symbol->counterpart ); return $expr; } # for object literals sub nud_brace { my($parser, $symbol) = @_; my $list = $parser->expression_list(); $parser->advance($symbol->counterpart); return $symbol->clone( arity => 'composer', first => $list, ); } # iterator variables ($~iterator) # $~iterator . NAME | NAME() sub nud_iterator { my($parser, $symbol) = @_; my $iterator = $symbol->clone(); if($parser->token->id eq ".") { $parser->advance(); my $t = $parser->token; if(!any_in($t->arity, qw(variable name))) { $parser->_unexpected("a field name", $t); } my $generator = $parser->iterator_element->{$t->value}; if(!$generator) { $parser->_error("Undefined iterator element: $t"); } $parser->advance(); # element name my $args; if($parser->token->id eq "(") { $parser->advance(); $args = $parser->expression_list(); $parser->advance(")"); } $iterator->second($t); return $generator->($parser, $iterator, @{$args}); } return $iterator; } sub nud_constant { my($parser, $symbol) = @_; my $t = $parser->token; my $expect = $symbol->id eq 'constant' ? 'name' : $symbol->id eq 'my' ? 'variable' : die "Oops: $symbol"; if($t->arity ne $expect) { $parser->_unexpected("a $expect", $t); } $parser->define($t)->arity("name"); $parser->advance(); $parser->advance("="); return $symbol->clone( arity => 'constant', first => $t, second => $parser->expression(0), is_statement => 1, ); } my $lambda_id = 0; sub lambda { my($parser, $proto) = @_; my $name = $parser->symbol('(name)')->clone( id => sprintf('lambda@%s:%d', $parser->file, $lambda_id++), ); return $parser->symbol('(name)')->clone( arity => 'proc', id => 'macro', first => $name, line => $proto->line, ); } # -> $x { ... } sub nud_lambda { my($parser, $symbol) = @_; my $pointy = $parser->lambda($symbol); $parser->new_scope(); my @params; if($parser->token->id ne "{") { # has params my $paren = ($parser->token->id eq "("); $parser->advance("(") if $paren; # optional my $t = $parser->token; while($t->arity eq "variable") { push @params, $t; $parser->define($t); $t = $parser->advance(); if($t->id eq ",") { $t = $parser->advance(); # "," } else { last; } } $parser->advance(")") if $paren; } $pointy->second( \@params ); $parser->advance("{"); $pointy->third($parser->statements()); $parser->advance("}"); $parser->pop_scope(); return $symbol->clone( arity => 'lambda', first => $pointy, ); } sub nud_current_file { my($self, $symbol) = @_; my $file = $self->file; return $symbol->clone( arity => 'literal', value => ref($file) ? '<string>' : $file, ); } sub nud_current_line { my($self, $symbol) = @_; return $symbol->clone( arity => 'literal', value => $symbol->line, ); } sub nud_current_vars { my($self, $symbol) = @_; return $symbol->clone( arity => 'vars', ); } sub nud_separator { my($self, $symbol) = @_; $self->_error("Invalid expression found", $symbol); } # -> VARS { STATEMENTS } # -> { STATEMENTS } # { STATEMENTS } sub pointy { my($parser, $pointy, $in_for) = @_; my @params; $parser->new_scope(); if($parser->token->id eq "->") { $parser->advance(); if($parser->token->id ne "{") { my $paren = ($parser->token->id eq "("); $parser->advance("(") if $paren; my $t = $parser->token; while($t->arity eq "variable") { push @params, $t; $parser->define($t); if($in_for) { $parser->define_iterator($t); } $t = $parser->advance(); if($t->id eq ",") { $t = $parser->advance(); # "," } else { last; } } $parser->advance(")") if $paren; } } $pointy->second( \@params ); $parser->advance("{"); $pointy->third($parser->statements()); $parser->advance("}"); $parser->pop_scope(); return; } sub iterator_name { my($parser, $var) = @_; # $foo -> $~foo (my $it_name = $var->id) =~ s/\A (\$?) /${1}~/xms; return $it_name; } sub define_iterator { my($parser, $var) = @_; my $it = $parser->symbol( $parser->iterator_name($var) )->clone( arity => 'iterator', first => $var, ); $parser->define($it); $it->set_nud(\&nud_iterator); return $it; } sub std_for { my($parser, $symbol) = @_; my $proc = $symbol->clone(arity => 'for'); $proc->first( $parser->expression(0) ); $parser->pointy($proc, 1); # for-else support if($parser->token eq 'else') { $parser->advance(); my $else = $parser->block(); $proc = $symbol->clone( arity => 'for_else', first => $proc, second => $else, ) } return $proc; } sub std_while { my($parser, $symbol) = @_; my $proc = $symbol->clone(arity => 'while'); $proc->first( $parser->expression(0) ); $parser->pointy($proc); return $proc; } # macro name -> { ... } sub std_proc { my($parser, $symbol) = @_; my $macro = $symbol->clone(arity => "proc"); my $name = $parser->token; if($name->arity ne "name") { $parser->_unexpected("a name", $name); } $parser->define_function($name->id); $macro->first($name); $parser->advance(); $parser->pointy($macro); return $macro; } # block name -> { ... } # block name | filter -> { ... } sub std_macro_block { my($parser, $symbol) = @_; my $macro = $symbol->clone(arity => "proc"); my $name = $parser->token; if($name->arity ne "name") { $parser->_unexpected("a name", $name); } # auto filters my @filters; my $t = $parser->advance(); while($t->id eq "|") { $t = $parser->advance(); if($t->arity ne "name") { $parser->_unexpected("a name", $name); } my $filter = $t->clone(); $t = $parser->advance(); my $args; if($t->id eq "(") { $parser->advance(); $args = $parser->expression_list(); $t = $parser->advance(")"); } push @filters, $args ? $parser->call($filter, @{$args}) : $filter; } $parser->define_function($name->id); $macro->first($name); $parser->pointy($macro); my $call = $parser->call($macro->first); if(@filters) { foreach my $filter(@filters) { # apply filters $call = $parser->call($filter, $call); } } # std() can return a list return( $macro, $parser->print($call) ); } sub std_override { # synonym to 'around' my($parser, $symbol) = @_; return $parser->std_proc($symbol->clone(id => 'around')); } sub std_if { my($parser, $symbol, $expr) = @_; my $if = $symbol->clone(arity => "if"); $if->first( $parser->expression(0) ); if(defined $expr) { # statement modifier $if->second([$expr]); return $if; } $if->second( $parser->block() ); my $top_if = $if; my $t = $parser->token; while($t->id eq "elsif") { $parser->reserve($t); $parser->advance(); # "elsif" my $elsif = $t->clone(arity => "if"); $elsif->first( $parser->expression(0) ); $elsif->second( $parser->block() ); $if->third([$elsif]); $if = $elsif; $t = $parser->token; } if($t->id eq "else") { $parser->reserve($t); $t = $parser->advance(); # "else" $if->third( $t->id eq "if" ? [$parser->statement()] : $parser->block()); } return $top_if; } sub std_given { my($parser, $symbol) = @_; my $given = $symbol->clone(arity => 'given'); $given->first( $parser->expression(0) ); local $parser->{in_given} = 1; $parser->pointy($given); if(!(defined $given->second && @{$given->second})) { # if no topic vars $given->second([ $parser->symbol('($_)')->clone(arity => 'variable' ) ]); } $parser->build_given_body($given, "when"); return $given; } # when/default sub std_when { my($parser, $symbol) = @_; if(!$parser->in_given) { $parser->_error("You cannot use $symbol blocks outside given blocks"); } my $proc = $symbol->clone(arity => 'when'); if($symbol->id eq "when") { $proc->first( $parser->expression(0) ); } $proc->second( $parser->block() ); return $proc; } sub _only_white_spaces { my($s) = @_; return $s->arity eq "literal" && $s->value =~ m{\A [ \t\r\n]* \z}xms } sub build_given_body { my($parser, $given, $expect) = @_; my($topic) = @{$given->second}; # make if-elsif-else chain from given-when my $if; my $elsif; my $else; foreach my $when(@{$given->third}) { if($when->arity ne $expect) { # ignore white space if($when->id eq "print_raw" && !grep { !_only_white_spaces($_) } @{$when->first}) { next; } $parser->_unexpected("$expect blocks", $when); } $when->arity("if"); # change the arity if(defined(my $test = $when->first)) { # when if(!$test->is_logical) { $when->first( $parser->binary('~~', $topic, $test) ); } } else { # default $when->first( $parser->symbol('true')->nud($parser) ); $else = $when; next; } if(!defined $if) { $if = $when; $elsif = $when; } else { $elsif->third([$when]); $elsif = $when; } } if(defined $else) { # default if(defined $elsif) { $elsif->third([$else]); } else { $if = $else; # only default } } $given->third(defined $if ? [$if] : undef); return; } sub std_include { my($parser, $symbol) = @_; my $arg = $parser->barename(); my $vars = $parser->localize_vars(); my $stmt = $symbol->clone( first => $arg, second => $vars, arity => 'include', ); return $parser->finish_statement($stmt); } sub std_print { my($parser, $symbol) = @_; my $args; if($parser->token->id ne ";") { $args = $parser->expression_list(); } my $stmt = $symbol->clone( arity => 'print', first => $args, ); return $parser->finish_statement($stmt); } # for cascade() and include() sub barename { my($parser) = @_; my $t = $parser->token; if($t->arity ne 'name' or $t->is_defined) { # string literal for 'cascade', or any expression for 'include' return $parser->expression(0); } # path::to::name my @parts; push @parts, $t; $parser->advance(); while(1) { my $t = $parser->token; if($t->id eq "::") { $t = $parser->advance(); # "::" if($t->arity ne "name") { $parser->_unexpected("a name", $t); } push @parts, $t; $parser->advance(); } else { last; } } return \@parts; } # NOTHING | { expression-list } sub localize_vars { my($parser) = @_; if($parser->token->id eq "{") { $parser->advance(); $parser->new_scope(); my $vars = $parser->expression_list(); $parser->pop_scope(); $parser->advance("}"); return $vars; } return undef; } sub std_cascade { my($parser, $symbol) = @_; my $base; if($parser->token->id ne "with") { $base = $parser->barename(); } my $components; if($parser->token->id eq "with") { $parser->advance(); # "with" my @c = $parser->barename(); while($parser->token->id eq ",") { $parser->advance(); # "," push @c, $parser->barename(); } $components = \@c; } my $vars = $parser->localize_vars(); my $stmt = $symbol->clone( arity => 'cascade', first => $base, second => $components, third => $vars, ); return $parser->finish_statement($stmt); } sub std_super { my($parser, $symbol) = @_; my $stmt = $symbol->clone(arity => 'super'); return $parser->finish_statement($stmt); } sub std_next { my($parser, $symbol) = @_; my $stmt = $symbol->clone(arity => 'loop_control', id => 'next'); return $parser->finish_statement($stmt); } sub std_last { my($parser, $symbol) = @_; my $stmt = $symbol->clone(arity => 'loop_control', id => 'last'); return $parser->finish_statement($stmt); } # iterator elements sub bad_iterator_args { my($parser, $iterator) = @_; $parser->_error("Wrong number of arguments for $iterator." . $iterator->second); } sub iterator_index { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator return $iterator; } sub iterator_count { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator + 1 return $parser->binary('+', $iterator, 1); } sub iterator_is_first { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator == 0 return $parser->binary('==', $iterator, 0); } sub iterator_is_last { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator == $~iterator.max_index return $parser->binary('==', $iterator, $parser->iterator_max_index($iterator)); } sub iterator_body { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator.body return $iterator->clone( arity => 'iterator_body', ); } sub iterator_size { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator.max_index + 1 return $parser->binary('+', $parser->iterator_max_index($iterator), 1); } sub iterator_max_index { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # __builtin_max_index($~iterator.body) return $parser->symbol('max_index')->clone( arity => 'unary', first => $parser->iterator_body($iterator), ); } sub _iterator_peek { my($parser, $iterator, $pos) = @_; # $~iterator.body[ $~iterator.index + $pos ] return $parser->binary('[', $parser->iterator_body($iterator), $parser->binary('+', $parser->iterator_index($iterator), $pos), ); } sub iterator_peek_next { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; return $parser->_iterator_peek($iterator, +1); } sub iterator_peek_prev { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args != 0; # $~iterator.is_first ? nil : <prev> return $parser->symbol('?')->clone( arity => 'if', first => $parser->iterator_is_first($iterator), second => [$parser->nil], third => [$parser->_iterator_peek($iterator, -1)], ); } sub iterator_cycle { my($parser, $iterator, @args) = @_; $parser->bad_iterator_args($iterator) if @args < 2; # $iterator.cycle("foo", "bar", "baz") makes: # ($tmp = $~iterator % n) == 0 ? "foo" # : $tmp == 1 ? "bar" # : "baz" $parser->new_scope(); my $mod = $parser->binary('%', $iterator, scalar @args); # for the second time my $tmp = $parser->symbol('($cycle)')->clone(arity => 'name'); # for the first time my $cond = $iterator->clone( arity => 'constant', first => $tmp, second => $mod, ); my $parent = $iterator->clone( arity => 'if', first => $parser->binary('==', $cond, 0), second => [ $args[0] ], ); my $child = $parent; my $last = pop @args; for(my $i = 1; $i < @args; $i++) { my $nth = $iterator->clone( arity => 'if', id => "$iterator.cycle: $i", first => $parser->binary('==', $tmp, $i), second => [$args[$i]], ); $child->third([$nth]); $child = $nth; } $child->third([$last]); $parser->pop_scope(); return $parent; } # utils sub make_alias { # alas(from => to) my($parser, $from, $to) = @_; my $stash = $parser->symbol_table; if(exists $parser->symbol_table->{$to}) { Carp::confess( "Cannot make an alias to an existing symbol ($from => $to / " . p($parser->symbol_table->{$to}) .")"); } # make a snapshot return $stash->{$to} = $parser->symbol($from)->clone( value => $to, # real id ); } sub not_supported { my($parser, $symbol) = @_; $parser->_error("'$symbol' is not supported"); } sub _unexpected { my($parser, $expected, $got) = @_; if(defined($got) && $got ne ";") { if($got eq '(end)') { $parser->_error("Expected $expected, but reached EOF"); } else { $parser->_error("Expected $expected, but got " . neat("$got")); } } else { $parser->_error("Expected $expected"); } } sub _error { my($parser, $message, $near, $line) = @_; $near ||= $parser->near_token || ";"; if($near ne ";" && $message !~ /\b \Q$near\E \b/xms) { $message .= ", near $near"; } die $parser->make_error($message . ", while parsing templates", $parser->file, $line || $parser->line); } no Mouse; __PACKAGE__->meta->make_immutable; __END__ =head1 NAME Text::Xslate::Parser - The base class of template parsers =head1 DESCRIPTION This is a parser to build the abstract syntax tree from templates. The basis of the parser is Top Down Operator Precedence. =head1 SEE ALSO L<http://javascript.crockford.com/tdop/tdop.html> - Top Down Operator Precedence (Douglas Crockford) L<Text::Xslate> L<Text::Xslate::Compiler> L<Text::Xslate::Symbol> =cut
rosiro/wasarabi
local/lib/perl5/x86_64-linux-thread-multi/Text/Xslate/Parser.pm
Perl
mit
47,617
package Kvasir::Writer::XML; use strict; use warnings; use Carp qw(croak); use Scalar::Util qw(blessed); use XML::LibXML; use Kvasir::Engine; use Kvasir::Util qw(is_existing_package); our $VERSION = "0.02"; sub _new { my ($pkg) = @_; my $self = bless { }, $pkg; return $self; } sub to_file { my ($self, $engine, $path) = @_; my $xml = $self->_engine_to_doc($engine); $xml->toFile($path); } our $XML_FORMAT = 1; sub as_xml { my ($self, $engine) = @_; my $doc = $self->_engine_to_doc($engine); return $doc->serialize($XML_FORMAT); } sub _engine_to_doc { my ($self, $engine) = @_; croak "Engine is undefined" if !defined $engine; croak "Not a Kvasir::Engine instance" if !(blessed $engine && $engine->isa("Kvasir::Engine")); my $doc = XML::LibXML::Document->new(); my $root = $doc->createElement("engine"); $doc->setDocumentElement($root); # Defaults for my $defaults_name (sort $engine->defaults) { my $values = $engine->get_defaults($defaults_name); my $defaults = $doc->createElement("defaults"); $defaults->setAttribute(name => $defaults_name); while (my ($key, $value) = each %$values) { $defaults->appendTextChild($key, $value); } $root->addChild($defaults) } # Actions for my $action (sort $engine->actions) { my $decl = $engine->_get_action($action); my $entity = _decl_to_element("action", $action, $doc, $decl); $root->addChild($entity); } # Inputs for my $input (sort $engine->inputs) { my $decl = $engine->_get_input($input); my $entity = _decl_to_element("input", $input, $doc, $decl); $root->addChild($entity); } # Prehooks for my $hook (@{$engine->_pre_hooks}) { my $decl = $engine->_get_hook($hook); my $entity = _decl_to_element("prehook", $hook, $doc, $decl); $root->addChild($entity); } my %actionmap; # Rule comes here for my $rule (@{$engine->_rule_order}) { my $decl = $engine->_get_rule($rule); my $entity = _decl_to_element("rule", $rule, $doc, $decl); $root->addChild($entity); for my $action (@{$engine->_get_rule_actions($rule)}) { push @{$actionmap{$action}}, $rule; } } # Rule -> Action mapping for my $action (sort keys %actionmap) { my $run = $doc->createElement("run"); $run->setAttribute("action" => $action); for my $rule (@{$actionmap{$action}}) { my $rule_elem = $doc->createElement("rule"); $rule_elem->appendText($rule); $run->addChild($rule_elem); } $root->addChild($run); } # Posthooks for my $hook (@{$engine->_post_hooks}) { my $decl = $engine->_get_hook($hook); my $entity = _decl_to_element("posthook", $hook, $doc, $decl); $root->addChild($entity); } # Outputs for my $output (sort $engine->outputs) { my $decl = $engine->_get_output($output); my $entity = _decl_to_element("output", $output, $doc, $decl); $root->addChild($entity); } return $doc; } sub _decl_to_element { my ($type, $name, $doc, $decl) = @_; my $entity = $doc->createElement($type); $entity->setAttribute("name" => $name); $entity->setAttribute("instanceOf" => $decl->_pkg); my $defaults = $decl->_defaults; if ($defaults && @$defaults) { $entity->setAttribute("defaults" => join(", ", @$defaults)); } _args_to_element($doc, $entity, $decl->_pkg, $decl->_args); return $entity; } sub _args_to_element { my ($doc, $parent, $pkg, $args) = @_; if (!is_existing_package($pkg)) { eval "require ${pkg};"; croak $@ if $@; } if ($pkg->can("process_xml_writer_args")) { $pkg->process_xml_writer_args($doc, $parent, @$args); return; } if (!(@$args & 1)) { my %args = @$args; for my $key (sort keys %args) { $parent->appendTextChild($key, $args{$key}); } } } 1; __END__ =head1 NAME Kvasir::Writer::XML - Store Kvasir engine declarations as XML =head1 SYNOPSIS use Kvasir::Writer::XML; my $xml = Kvasir::Writer::XML->as_xml($engine); Kvasir::Loader::XML->to_file($engine, "my_engine.xml"); =head1 DESCRIPTION This module provides a mean to write Kvasir engine declarations to XML. =head1 INTERFACE =head2 CLASS METHODS =over 4 =item as_xml ( ENGINE ) Returns a XML-representation of I<ENGINE> =item to_file ( ENGINE, PATH ) Creates a XML-representation of I<ENGINE> and saves it at I<PATH>. =back =head1 XML Document structure The structure of the XML created by this writer is described in L<Kvasir::Loader::XML/XML Document structure>. Arguments to entities (actions, inputs, hooks, outputs and rules) will be tested to see if it's a single hash reference and if so be written as such using the key as element name and the value as the elements text content. However, if the implementing class of the entitiy implements the method C<process_xml_writers_args> this will be called as a class method and is responsible for adding children to the element. The arguments to the method are the document as a C<XML::LibXML::Document>-instance, the entity-element as C<XML::LibXML::Element>-instance which to add children to and a list of the arguments encapsulated by C<Kvasir::TypeDecl>-instance that represents the entity. =head1 SEE ALSO L<Kvasir> L<Kvasir::Loader::XML> =head1 BUGS AND LIMITATIONS Please report any bugs or feature requests to C<bug-kvasir-writer-xml@rt.cpan.org>, or through the web interface at L<http://rt.cpan.org>. =head1 AUTHOR Claes Jakobsson C<< <claesjac@cpan.org> >> =head1 LICENCE AND COPYRIGHT Copyright (c) 2007, Versed Solutions C<< <info@versed.se> >>. All rights reserved. This software is released under the MIT license cited below. =head2 The "MIT" License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =cut
gitpan/Kvasir-Writer-XML
lib/Kvasir/Writer/XML.pm
Perl
mit
7,115
#!/usr/bin/perl -w use strict; use Getopt::Long; use File::Basename; use Bio::SeqIO; &GetOptions( 'in=s' => \my$backbone, # 'query=s' => \my$query, # 'q' => \my$quiet, 'h' => \my$h, 'genomes=s' => \my$genomes, 'out=s' => \my$out); # ($backbone and $query and $genomes and $out) or &HELP_MESSAGE; if($h){ &HELP_MESSAGE }; my$inname= basename($backbone, ".xmfa.backbone"); my@ids = split("-",$inname); my$genomeA = &getgrep( $ids[0], $genomes); my$genomeB = &getgrep( $ids[1], $genomes); my$clean=0; open BB, "$backbone"; open OUT, ">$out"; while(my$block = <BB>){ if($block =~ /seq/){ print OUT $block; }else{ chomp$block; my@sblock = split("\t",$block); if( &gapcheck(\@sblock,$query,$genomeA,$genomeB) == 1){ print OUT $block ."\n"; }else{ $clean++ }; } } close BB; close OUT; unless($quiet){ print "\nRemoved ".$clean." gaps from '".basename($backbone)."' based on matches to '".basename($query)."'.\n\n"; } #clean-up any temporary fasta files created for blasting foreach my$g ($genomeA,$genomeB){ if($g =~ /tmp.fasta$/){ system( "rm $g" ); } } ############################## sub gapcheck { my@coords = @{$_[0]}; my%coordhash = map { $_ => 1 } @coords; if(exists($coordhash{ 0 })){ my$r=0; if($coords[0] == 0){ #blast genomeB $r = &doblast($_[1],$_[3],$coords[2],$coords[3]); }elsif($coords[2] == 0){ #blast genomeA $r = &doblast($_[1],$_[2],$coords[0],$coords[1]); } return($r); }else{ return(1) }; } sub doblast { my($q, $sub, $c1, $c2) = @_; my$blast = qx( blastn -query $q -subject $sub -subject_loc $c1\-$c2 -outfmt \'6 sstart send\' -qcov_hsp_perc 50 -perc_identity 90 ); chomp$blast; $blast =~ s/\n/\t/g; my@hits = sort{$a <=> $b}(split("\t",$blast)); if( scalar(@hits) < 2){ #make sure there are hits return(1); }elsif((($hits[0] - $c1) >= 100) || (($c2 - $hits[-1]) >= 100)){ #matches cannot be >100bp inside gap return(1); }elsif( scalar(@hits) > 2){ my$r=0; for(my$h = 2; $h < scalar(@hits); $h+=2){ if(( $hits[$h] - $hits[$h-1] ) >= 50 ){ #max allowable 50bp between $r=1; last; } } return($r); }else{ return(0) }; } sub getgrep { my($pdl) = $_[0] =~ /([A-Z][0-9]{3})/; my$match = qx( grep $pdl $_[1] ); chomp$match; return( &checkfasta($match) ); } sub checkfasta { if($_[0] =~ /fasta/){ return ($_[0]); }else{ #convert genbank to temp fasta for blasting my$gbk = Bio::SeqIO->new(-file => "$_[0]", -format => 'genbank'); my$tempfasta = basename($_[0],".gbk"). ".tmp.fasta"; my$out = Bio::SeqIO->new(-file => ">$tempfasta", -format => 'fasta'); while(my$seq = $gbk->next_seq){ $out->write_seq($seq); } return($tempfasta); } } sub HELP_MESSAGE { die " .Description: Checks a pairwise mauve alignment backbone file and removes gaps that correspond to BLASTn alignment with a given query (eg. IS481). Removes gaps if [1] query alignment coordinates are < 100bp within gap coordinates, and [2] multiple query matches are spaced < 50bp apart, where applicable. .Usage: $0 -in -gap -out [mandatory] -in <in.backbone> Backbone file output from progressiveMauve. (Assumes format: \"GenomeA-GenomeB.xmfa.backbone\") -query <query.fasta> Fasta sequence for BLASTn. -genomes <list.txt> List of file paths to genome sequences in alignment. (Assumes basename consistency: GenomeA.gbk, GenomeB.fasta) -out <out.txt> New backbone file with matched gaps removed. [optional] -q Run quietly. -h This help message. [dependencies] BioPerl (Bio::SeqIO) blastn (Must be in your \$PATH) " }
mikeyweigand/Pertussis_n257
Current/mauve.backbone-clean.pl
Perl
mit
3,562
our $lock_fh; our $meshchat_path = "/tmp/meshchat"; our $max_messages_db_size = 500; our $max_file_storage = 512 * 1024; our $lock_file = $meshchat_path . '/lock'; our $messages_db_file = $meshchat_path . '/messages'; our $messages_db_file_orig = $meshchat_path . '/messages'; our $sync_status_file = $meshchat_path . '/sync_status'; our $local_users_status_file = $meshchat_path . '/users_local'; our $remote_users_status_file = $meshchat_path . '/users_remote'; our $remote_files_file = $meshchat_path . '/files_remote'; our $messages_version_file = $meshchat_path . '/messages_version'; our $local_files_dir = $meshchat_path . '/files'; our $pi_nodes_file = $meshchat_path . '/pi'; our $tmp_upload_dir = '/tmp/web/upload'; our $poll_interval = 10; our $non_meshchat_poll_interval = 600; our $connect_timeout = 5; our $platform = 'node'; our $debug = 0; our $extra_nodes = []; 1;
tpaskett/meshchat
src/node/data/www/cgi-bin/meshchatconfig.pm
Perl
mit
1,087
#!/usr/local/bin/perl #$ -S /usr/local/bin/perl #$ -cwd #Title: Make relative exp. data #Auther: Naoto Imamachi #ver: 1.0.0 #Date: 2014-08-29 =pod =cut use warnings; use strict; my $input = $ARGV[0]; my $cutoff = 0.1; my @list=( "mRNA", "ncRNA" ); ################################## foreach my $filename(@list){ open(IN,"$input\_$filename\.fpkm_table") || die; open(OUT,">$input\_$filename\_rel.fpkm_table") || die; while(my $line = <IN>){ chomp $line; my @data = split/\t/,$line; if($data[0] eq "gr_id"){ print OUT "$line\n"; next; } my @infor = @data[0..3]; print OUT join("\t",@infor); my $num_col = @data; my $num_sample = $num_col - 4; my $first; for(my $i=0; $i<$num_sample; $i++){ if($i == 0){ $first = $data[4+$i]; unless($first > $cutoff){ #Default: 0.001rpkm print OUT "\t0"; next; } print OUT "\t1"; }else{ unless($first > $cutoff){ #Default: 0.001rpkm print OUT "\t0"; next; } my $dat = $data[4+$i]/$first; print OUT "\t$dat"; } } print OUT "\n"; } close(IN); close(OUT); }
Naoto-Imamachi/NGS_data_analysis_pipeline
cuffnorm_BRIC-seq/A_make_relative_exp_data.pl
Perl
mit
1,054
#!/usr/bin/perl -w # use strict; use warnings; # my $binpath = undef; # BEGIN { use File::Basename; # $binpath = dirname($0); $binpath = "." if ($binpath eq ""); } # # use CPAN to download Digest::CRC if it is not available. # # use Digest::CRC qw(crc64 crc32 crc16 crcccitt crc crc8); # use lib "$binpath"; use lib "$binpath/myutils"; # use myconstants; use mylogger; use myutils; # my $use_join = FALSE; # if ((scalar(@ARGV) < 1) || (($ARGV[0] eq "-j") && (scalar(@ARGV) == 1))) { printf "usage: $0 [-j] string1 [string2 [...]]\n"; exit 2; } elsif ($ARGV[0] eq "-j") { $use_join = TRUE; shift @ARGV; } # my $plog = mylogger->new(); die "Unable to create logger: $!" unless (defined($plog)); # my $putils = myutils->new($plog); die "Unable to create utils: $!" unless (defined($putils)); # if ($use_join == TRUE) { my $crc = undef; my $args = join("", @ARGV); # $crc = $putils->my_crc_32($args); printf "\nMy CRC32 (string) = %s\n", $crc; # $crc = $putils->crc_16($args); printf "CRC16 (string) = %s\n", $crc; # $crc = $putils->crc_32($args); printf "CRC32 (string) = %s\n", $crc; # $crc = $putils->crc_64($args); printf "CRC64 (string) = %s\n", $crc; # $crc = $putils->crc_ccitt($args); printf "CRCCCITT (string) = %s\n", $crc; } else { foreach my $arg (@ARGV) { my $crc = undef; # $crc = $putils->my_crc_32($arg); printf "\nMy CRC32 (string) = %s\n", $crc; # $crc = $putils->crc_16($arg); printf "CRC16 (string) = %s\n", $crc; # $crc = $putils->crc_32($arg); printf "CRC32 (string) = %s\n", $crc; # $crc = $putils->crc_64($arg); printf "CRC64 (string) = %s\n", $crc; # $crc = $putils->crc_ccitt($arg); printf "CRCCCITT (string) = %s\n", $crc; } } # exit 0;
ombt/analytics
apex/bin/crcs.pl
Perl
mit
1,904
#!/usr/bin/perl use strict; use Switch; #use warnings; use List::MoreUtils qw/ uniq /; use Date::Manip; use File::Find; use POSIX qw( strftime ); my $resultFolder = $ARGV[0]; my $autoType=$ARGV[1]; #my $domain="";#$ARGV[1]; my $cpuDataJson; my ($content, $contentR); my ($cycleName, $cycleMode, $device_manu, $device_name, $device_model, $device_OS, $device_ver, $resolution, $cpu_arch, $device_size, $DisplaName, $StartTime, $EndTime, $session_dur_minutes, $session_dur_secs, $session_dur_hours); my ($sc, @flv); my (@total_sc); my (@cpu_array, @mem_array, @devConsumption_array, @appConsumption_array, @appPercentageConsump_array); my $timeStamp=""; my @deviceTimeStamp; my $incompletedFile; my $imgDir; my $statFile; my $NewDate=""; my $beginDate=""; my $deviceORdevices=""; my $icStatus = 0; my $total_exeTime = 0; my $sum = 0; my $cpuData=0; my $cpuFile=""; #ios declaration my $interval=2; my (@cpu_array, @mem_array, @screenShot); my (@total_no, @cpu, @memory, @wifircvd, @wifisent, @ios_cpu_date_time, @ios_mem_date_time, @ios_wifi_date_time); #ios declaration ends here #files related Declaration my ($cpuFile, $memFile, $netFile, $batFile, $frameFile); #CPU releated Declaration my (@cpu_date_time, @user_cpu, @system_cpu, @app_cpu, @step); my (@tot_date_time_cpu, @tot_user_cpu, @tot_system_cpu, @tot_app_cpu, @tot_steps); #Memory related Declaration my (@mem_datetime, @NPSS_mem, @NHS_mem, @NHA_mem, @DPSS_mem, @DHS_mem, @DHA_mem, @TAPP_CON_mem); #Battery related Declaration my (@bat_date_time, @bat_dev_con, @bat_app_con); #Frame related Declaration my (@frame_date_time, @frame_draw, @frame_prepare, @frame_process, @frame_execute); #Network related Declaration my (@net_date_time, @net_up_pkt, @net_up_data, @net_down_pkt, @net_down_data); #Screenshots my(@sc); #all Array size Declaration my ($user_cpu_size, $NPSS_mem_size, $bat_dev_con_size, $frame_draw_size, $net_up_pkt_size, $sc_size); my $Logs=""; my $OS; my $GraphLimit=10000; my $iosAutomation = 0; opendir my $dh, $resultFolder or die $!; my @folders = grep {-d "$resultFolder/$_" && ! /^\.{1,2}$/} readdir($dh); closedir $dh; print("device name-- $resultFolder\n"); my $curr_device = $resultFolder; if($resultFolder eq "temp"){ print("Directory structure is not created properly"); } if ($autoType =~ m/APPLE/ || $device_manu =~ m/Apple/) { $iosAutomation = 1; } if($iosAutomation == 1){ undef @cpu; undef @memory; undef @ios_cpu_date_time; undef @ios_mem_date_time; my $wifirecieved = 0; my $wifisent = 0; opendir(DIR, $curr_device); my @txts = grep(/\.txt$/,readdir(DIR)); closedir(DIR); my @txtArray = sort @txts; foreach my $file (@txtArray) { #print("File name is : $file\n"); if ($file =~ /ioscpupackage/) { #print("$file contains cpupackages\n"); $cpuFile = $file; } if ($file =~ /mem/) { #print("$file contains mempackage\n"); $memFile = $file; } if ($file =~ /wifirecievedLogFile/) { #print("$file contains wifirecievedLogFile\n"); $wifirecieved = $file; } if ($file =~ /wifisentLogFile/) { #print("$file contains wifisentLogFile\n"); $wifisent = $file; } } $cpuFile = "$curr_device/$cpuFile"; if (-e $cpuFile) { open my $IN, '<', $cpuFile or die $!; my $steps = 0; my $b = 0; my $NewData = 0; while (my $line = <$IN>) { my($date, $s_cpu) = $line =~ /(\d\d\d\d\d\d\d\d\d\d)\s\-\>\s(.*)/; #print("$date -- $s_cpu\n"); $s_cpu = sprintf("%.2f", $s_cpu); #print("$date -- $s_cpu\n"); $NewData = epoctoHumanReadableiosPerf($date); #print("$NewData -- $s_cpu\n"); if($steps == 0){ $ios_cpu_date_time[$steps] = "['Dates'"; $cpu[$steps] = "['System CPU (%)'"; } elsif($date){ $ios_cpu_date_time[$steps] = ','."'$NewData'"; $cpu[$steps] = ','.$s_cpu; } $steps++; } $ios_cpu_date_time[$steps++] = ']'; $cpu[$steps] = ']'; close($IN); } else { print"$curr_device CPU file does not exist\n"; } $memFile = "$curr_device/$memFile"; print("MEM FILE IOS $memFile"); if (-e $memFile) { open my $IN, '<', $memFile or die $!; my $steps = 0; my $b = 0; my $NewData = 0; while (my $line = <$IN>) { my($date, $mem) = $line =~ /(\d\d\d\d\d\d\d\d\d\d)\s\-\>\s(.*)/; #print("MEM :- $date -- $mem -- $steps\n"); $mem = sprintf("%.2f", $mem); $NewData = epoctoHumanReadableiosPerf($date); #print("MEM :- $NewData -- $mem -- $steps\n"); if($steps == 0){ $ios_mem_date_time[$steps] = "['Dates'"; $memory[$steps] = "['System MEM (MB)'"; } elsif($date){ $ios_mem_date_time[$steps] = ','."'$NewData'"; $memory[$steps] = ','.$mem; } $steps++; } $ios_mem_date_time[$steps++] = ']'; $memory[$steps] = ']'; close($IN); } else { print"$curr_device memory file does not exist\n"; } $wifirecieved = "$curr_device/$wifirecieved"; if (-e $wifirecieved) { open my $IN, '<', $wifirecieved or die $!; my $steps = 0; my $NewData = 0; while (my $line = <$IN>) { my($date, $wifir) = $line =~ /(\d\d\d\d\d\d\d\d\d\d)\s\-\>\s(.*)/; #print("WIFIRCVD :- $date -- $mem -- $steps\n"); $wifir = sprintf("%.2f", $wifir); $NewData = epoctoHumanReadableiosPerf($date); #print("WIFIRCVD :- $NewData -- $wifir -- $steps\n"); if($steps == 0){ $ios_wifi_date_time[$steps] = "['Dates'"; $wifircvd[$steps] = "['NETWORK RCVD Data(KB)'"; } elsif($date){ $ios_wifi_date_time[$steps] = ','."'$NewData'"; $wifircvd[$steps] = ','.$wifir; } $steps++; } $ios_wifi_date_time[$steps++] = ']'; $wifircvd[$steps] = ']'; close($IN); } else { print"$curr_device Wifi received file does not exist\n"; } $wifisent = "$curr_device/$wifisent"; if (-e $wifisent) { open my $IN, '<', $wifisent or die $!; my $steps = 0; my $NewData = 0; while (my $line = <$IN>) { my($date, $wifis) = $line =~ /(\d\d\d\d\d\d\d\d\d\d)\s\-\>\s(.*)/; $wifis = sprintf("%.2f", $wifis); $NewData = epoctoHumanReadableiosPerf($date); #print("WIFISENT :- $NewData -- $wifis -- $steps\n"); if($steps == 0){ $ios_wifi_date_time[$steps] = "['Dates'"; $wifisent[$steps] = "['NETWORK SENT Data(KB)'"; } elsif($date){ $ios_wifi_date_time[$steps] = ','."'$NewData'"; $wifisent[$steps] = ','.$wifis; } $steps++; } $ios_wifi_date_time[$steps++] = ']'; $wifisent[$steps] = ']'; close($IN); } else { print"$curr_device Wifi Sent file does not exist\n"; } } #-------------for ios device only ends here----------------------------------------------------------- else{ #cpu data collection starts here ---------------------------------------------------------------------------- undef @cpu_date_time; undef @user_cpu; undef @system_cpu; undef @app_cpu; undef @mem_datetime; undef @NPSS_mem; undef @NHS_mem; undef @NHA_mem; undef @DPSS_mem; undef @DHS_mem; undef @DHA_mem; undef @TAPP_CON_mem; undef @bat_date_time; undef @bat_dev_con; undef @bat_app_con; undef @frame_date_time; undef @frame_draw; undef @frame_prepare; undef @frame_process; undef @frame_execute; undef @net_date_time; undef @net_up_pkt; undef @net_up_data; undef @net_down_pkt; undef @net_down_data; $memFile = "mem.txt"; $cpuFile = "cpu.txt"; $batFile = "bat.txt"; $frameFile = "frame.txt"; $netFile = "data.txt"; $cpuFile = "$curr_device/$cpuFile"; if (-e $cpuFile) { open my $IN, '<', $cpuFile or die $!; my $steps = 0; while (my $line = <$IN>) { if($steps >$GraphLimit){ last; } if($line =~ m/DATE TIME/){ next; } my($date, $u_cpu, $s_cpu, $a_cpu) = $line =~ /(\d\d:\d\d:\d\d.\d\d\d) (.*?)% (.*?)% (.*?)%/; print("Data is $u_cpu --- $steps\n"); if($steps == 0){ $cpu_date_time[$steps] = "['Dates'"; $user_cpu[$steps] = "['User CPU (%)'"; $system_cpu[$steps] = "['System CPU (%)'"; $app_cpu[$steps] = "['App CPU (%)'"; $steps++; $cpu_date_time[$steps] = ','."'$date'"; $user_cpu[$steps] = ','.$u_cpu; $system_cpu[$steps] = ','.$s_cpu; $app_cpu[$steps] = ','.$a_cpu; } elsif($date){ print("Data is inside $u_cpu\n"); $cpu_date_time[$steps] = ','."'$date'"; $user_cpu[$steps] = ','.$u_cpu; $system_cpu[$steps] = ','.$s_cpu; $app_cpu[$steps] = ','.$a_cpu; } $steps++; } $cpu_date_time[$steps++] = ']'; $user_cpu[$steps] = ']'; $system_cpu[$steps] = ']'; $app_cpu[$steps] = ']'; close($IN); } else { print"$curr_device CPU file does not exist\n"; } #cpu data collection ends here ---------------------------------------------------------------------------- #Memory data collection starts here ---------------------------------------------------------------------------- $memFile = "$curr_device/$memFile"; if (-e $memFile) { open my $IN, '<', $memFile or die $!; my $steps = 0; while (my $line = <$IN>) { if($steps >$GraphLimit){ last; } if ($line =~ m/DATE TIME/) { next; } my($date, $NPSS_mem, $NHS_mem, $NHA_mem, $DPSS_mem, $DHS_mem, $DHA_mem, $APP_con_mem) = $line =~ /(\d\d:\d\d:\d\d.\d\d\d)\s(\d+\d*)\s(\d+\d*)\s(\d+\d*)\s(\d+\d*)\s(\d+\d*)\s(\d+\d*)\s(\d+\d*)/; if($steps == 0){ $mem_datetime[$steps] = "['Dates'"; $NPSS_mem[$steps] = "['Native Heap PSS (KB)'"; $NHS_mem[$steps] = "['Native Heap Size (KB)'"; $NHA_mem[$steps] = "['Native Heap Allocation (KB)'"; $DPSS_mem[$steps] = "['Dalvik Heap PSS (KB)'"; $DHS_mem[$steps] = "['Dalvik Heap Size (KB)'"; $DHA_mem[$steps] = "['Dalvik Heap Allocation (KB)'"; $TAPP_CON_mem[$steps] = "['Total App Consmuption (KB)'"; $steps++; $mem_datetime[$steps] = ','."'$date'"; $NPSS_mem[$steps] = ','.$NPSS_mem; $NHS_mem[$steps] = ','.$NHS_mem; $NHA_mem[$steps] = ','.$NHA_mem; $DPSS_mem[$steps] = ','.$DPSS_mem; $DHS_mem[$steps] = ','.$DHS_mem; $DHA_mem[$steps] = ','.$DHA_mem; $TAPP_CON_mem[$steps] = ','.$APP_con_mem; } else{ if($NPSS_mem eq '') { next; } else{ $mem_datetime[$steps] = ','."'$date'"; $NPSS_mem[$steps] = ','.$NPSS_mem; $NHS_mem[$steps] = ','.$NHS_mem; $NHA_mem[$steps] = ','.$NHA_mem; $DPSS_mem[$steps] = ','.$DPSS_mem; $DHS_mem[$steps] = ','.$DHS_mem; $DHA_mem[$steps] = ','.$DHA_mem; $TAPP_CON_mem[$steps] = ','.$APP_con_mem; } } $steps++; } $mem_datetime[$steps++] = ']'; $NPSS_mem[$steps] = ']'; $NHS_mem[$steps] = ']'; $NHA_mem[$steps] = ']'; $DPSS_mem[$steps] = ']'; $DHS_mem[$steps] = ']'; $DHA_mem[$steps] = ']'; $TAPP_CON_mem[$steps] = ']'; close($IN); } else { print"$curr_device memory file does not exist\n"; } #Memory data collection ends here ---------------------------------------------------------------------------- #Battery data collection starts here ------------------------------------------------------------------------- $batFile = "$curr_device/$batFile"; if (-e $batFile) { open my $IN, '<', $batFile or die $!; my $steps = 0; while (my $line = <$IN>) { if ($line =~ m/DATE TIME/) { next; } if($steps >$GraphLimit){ last; } my($date, $devConsume, $appConsume) = $line =~/(\d\d:\d\d:\d\d.\d\d\d)\s+(\d*.\d*)\s+(\d*.\d*)$/; if($steps == 0){ $bat_date_time[$steps] = "['Dates'"; $bat_dev_con[$steps] = "['Device Battery (mAh)'"; $bat_app_con[$steps] = "['App Battery (mAh)'"; $steps++; $bat_date_time[$steps] = ','."'$date'"; $bat_dev_con[$steps] = ','.$devConsume; $bat_app_con[$steps] = ','.$appConsume; } else{ if($appConsume eq '' or $devConsume eq '') { next; } $bat_date_time[$steps] = ','."'$date'"; $bat_dev_con[$steps] = ','.$devConsume; $bat_app_con[$steps] = ','.$appConsume; } $steps++; } $bat_date_time[$steps++]= ']'; $bat_dev_con[$steps] = ']'; $bat_app_con[$steps] = ']'; close($IN); } else { print"$curr_device battery file does not exist\n"; } #Battery data collection ends here ---------------------------------------------------------------------------- #Frame Rendering data collection starts here ------------------------------------------------------------------ $frameFile = "$curr_device/$frameFile"; if (-e $frameFile) { open my $IN, '<', $frameFile or die $!; my $steps = 0; while (my $line = <$IN>) { if($steps >$GraphLimit){ last; } if ($line =~ m/DATE TIME/) { next; } my($date, $draw, $prepare, $process, $execute) = $line =~/(\d\d:\d\d:\d\d.\d\d\d)\s(\d+\.{0,1}\d*)\s(\d+\.{0,1}\d*)\s(\d+\.{0,1}\d*)\s(\d+\.{0,1}\d*)/; if($steps == 0){ $frame_date_time[$steps]= "['Dates'"; $frame_draw[$steps] = "['Draw'"; $frame_prepare[$steps] = "['Prepare'"; $frame_process[$steps] = "['Process'"; $frame_execute[$steps] = "['Execute'"; $steps++; $frame_date_time[$steps]= ','."'$date'"; $frame_draw[$steps] = ','.$draw; $frame_prepare[$steps] = ','.$prepare; $frame_process[$steps] = ','.$process; $frame_execute[$steps] = ','.$execute; } else{ if($draw eq ''){ next; } $frame_date_time[$steps]= ','."'$date'"; $frame_draw[$steps] = ','.$draw; $frame_prepare[$steps] = ','.$prepare; $frame_process[$steps] = ','.$process; $frame_execute[$steps] = ','.$execute; } $steps++; } $frame_date_time[$steps++]= ']'; $frame_draw[$steps] = ']'; $frame_prepare[$steps] = ']'; $frame_process[$steps] = ']'; $frame_execute[$steps] = ']'; close($IN); } else { print"$curr_device frame file does not exist\n"; } #Frame Rendering data collection ends here ---------------------------------------------------------------------------- #Network data collection starts here ---------------------------------------------------------------------------- $netFile = "$curr_device/$netFile"; if (-e $netFile) { open my $IN, '<', $netFile or die $!; my $steps = 0; while (my $line = <$IN>) { if($steps >$GraphLimit){ last; } if ($line =~ m/DATE TIME/) { next; } my($date, $up_pkt, $up_data, $down_pkt, $down_data) = $line =~/(\d\d:\d\d:\d\d.\d\d\d)\s(\d+\d*)\s(\d+\d*)\s(\d+\d*)\s(\d+\d*)/; if($steps == 0){ $net_date_time[$steps] = "['Dates'"; $net_up_pkt[$steps] = "['Uploaded Packet (#)'"; $net_up_data[$steps] = "['Uploaded Data (bytes)'"; $net_down_pkt[$steps] = "['Downloaded Packet (#)'"; $net_down_data[$steps] = "['Downloaded Data (bytes)'"; $steps++; $net_date_time[$steps] = ','."'$date'"; $net_up_pkt[$steps] = ','.$up_pkt; $net_up_data[$steps] = ','.$up_data; $net_down_pkt[$steps] = ','.$down_pkt; $net_down_data[$steps] = ','.$down_data; } else{ $net_date_time[$steps] = ','."'$date'"; $net_up_pkt[$steps] = ','.$up_pkt; $net_up_data[$steps] = ','.$up_data; $net_down_pkt[$steps] = ','.$down_pkt; $net_down_data[$steps] = ','.$down_data; } $steps++; } $net_date_time[$steps++]= ']'; $net_up_pkt[$steps] = ']'; $net_up_data[$steps] = ']'; $net_down_pkt[$steps] = ']'; $net_down_data[$steps] = ']'; close($IN); } else { print"$curr_device Network file does not exist\n"; } } #Network data collection ends here ---------------------------------------------------------------------------- #-------------for ios device only starts from here ----------------------------------------------------------- my $htmlFile; $htmlFile = "$resultFolder/index.html"; open my $HTML, '>', $htmlFile or die $!; print $HTML <<'_END_HEADER_'; <!DOCTYPE html> <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]--> <html> <head> <!-- Basic Page NeedsHTML ================================================== --> <meta charset="utf-8"> <title>pCloudy - Report</title> <meta name="description" content=""> <meta name="author" content="Smart Software Testing Solutions Inc. US."> <!-- Mobile Specific Metas ================================================== --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta http-equiv="imagetoolbar" content="no" /> <meta name="MSSmartTagsPreventParsing" content="true" /> <!-- Favicons ========================================OS========== --> _END_HEADER_ print $HTML <<'_END_HEADER_'; <!-- Typography ================================================== --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <!-- material icons --> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <!-- font awesome icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.2.0/css/iziToast.min.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/izitoast/1.2.0/js/iziToast.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/bs/jqc-1.12.4/dt-1.10.15/fh-3.1.2/r-2.1.1/rg-1.0.0/sc-1.4.2/se-1.2.2/datatables.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs/jqc-1.12.4/dt-1.10.15/fh-3.1.2/r-2.1.1/rg-1.0.0/sc-1.4.2/se-1.2.2/datatables.min.css"/> <link href="https://cdnjs.cloudflare.com/ajax/libs/izimodal/1.5.1/css/iziModal.min.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/izimodal/1.5.1/js/iziModal.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.13/c3.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.13/c3.min.css"> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> _END_HEADER_ print $HTML <<'_END_HEADER_'; <style> .chart{ position: relative; margin:20px 0px 10px; } .panel.panel-payload { min-height: 120px; border-color: #eee; } .panel { margin-bottom: 20px; /* border-color: #ddd; */ color: #333; border-radius: 0; } .graph-label{ width:100%; text-align:center; font-weight:normal; color:#646464; margin:5px auto 10px; } .graph-label.general-graph-label{ font-weight:bold; text-transform: uppercase; } .graph-label.graph-label-heading{ font-weight:bold; margin:2px auto; } .graph-label.graph-label-sub-heading{ color:#696969; margin:2px auto; } .device-details-data{ height:260px; overflow-y:auto; } .general-middle-icon{ text-align: center; font-size: 2em; margin-bottom: 10px; } .general-main-data{ text-align: center; margin-bottom:10px; } .general-middle-icon i.fa.fa-check{ color:#66BB6A; } .general-middle-icon i.fa.fa-times{ color:#EF5350; } .pc-device-data{ padding:10px 30px; } .device-data-list-item{ width:100%; min-height:30px; display:flex; clear:both; border:1px solid #eee; border-top:0px; } .device-data-list-item > li{ width:50%; min-height:30px; float:left; padding:5px 2px 5px 10px; word-break: break-all; } .device-data-list-item > li:first-of-type{ font-weight:bold; } .device-data-list-item > li:last-of-type{ } .device-image-container{ width:100%; //max-width:300px; height:300px; //margin:0px auto; } .device-image-container > img{ margin:auto; display:block; max-width:300px; max-height:300px; } .block-graph { margin-bottom: 30px; background-color: #fff; -webkit-box-shadow: 0 2px rgba(0,0,0,0.01); box-shadow: 0 2px rgba(0,0,0,0.01); } .block-graph-header{ position:relative; padding: 15px 20px; -webkit-transition: opacity .2s ease-out; transition: opacity .2s ease-out; border-bottom: 1px solid #f9f9f9; margin: 0px 30px; background-color: #F7F4FF; } .block-graph-header .block-title{ } .block-title { font-size: 15px; margin: 0; font-weight: 600; text-transform: uppercase; line-height: 1.2; } .block-graph-content{ /*margin: 0 auto; padding: 20px 20px 1px;*/ margin: 0 30px; padding: 10px 0px 1px; max-width: 100%; overflow-x: visible; -webkit-transition: opacity .2s ease-out; transition: opacity .2s ease-out; } .block-graph-content > .row > div[class^='col-'] > div.c3{ /*max-width: 96%;*/ max-width: 100%; /*margin: 0 auto;*/ } .block-graph-content > .row > div[class^='col-'] > div.c3 > svg{ max-width: 100%; } .device-detail-header{ padding:15px 10px; background-color:teal; color:#fff; } /* css for block-tools */ .pc-block-tools{ display: block; float: none; margin-top: 0; position: absolute; padding: 0; text-align: right; left: 0px; top: 0px; height: 49px; width: 100%; font-size: 1.5em; } .pc-block-tools:hover{ cursor:pointer; } .pc-block-tools a{ cursor: pointer; color: #c4c4c4; margin-right: 15px; height: 49px; display: inline-block; line-height: 2.4em; } .pcy_report_log_container{ padding:5px 20px; } .pcy_report_log_list_item{ width:100%; color: #1a7eb9; } .pcy_report_log_list_item:hover{ color: #076298; font-weight: bold; cursor:pointer; } .pcy_report_snapshot_card_container, .pcy_report_video_card_container{ display:flex; flex-wrap:wrap; align-items:center; align-content: flex-start; } .pcy_report_snapshot_card_item{ padding:5px; } .pcy_report_snapshot_card_item_landscape img{ display: block; margin: auto; margin-top: 14%; width: 100%; } .pcy_report_snapshot_card_item_portrait img{ display: block; margin-left: auto; margin-right: auto; width: 40%; } .pcy_report_snapshot_card_item div{ width:100%; height:100%; position:relative; } .pcy_report_snapshot_card_item.pcy_report_snapshot_card_item_landscape div img{ width:100%; height: 200px; align-self:center; } .pcy_report_snapshot_card_item.pcy_report_snapshot_card_item_portrait div img{ width:100%; height: calc(100% - 30px); } .pcy_report_snapshot_card_item div span{ width: 100%; display: inline-block; margin-top: 10px; text-align: center; position:absolute; bottom:0; left:0; } .snapshotCardItem{ display: inline-block; padding:5px; max-width:174px; margin: 25px; text-align: center; /* border: 1px solid #ddd; */ } .snapshotCardItem > span{ width: 100%; display: inline-block; margin-top: 10px; text-align: center; /* border: 1px solid #f7f7f7; */ } .snapshotImageCard{ max-width:370px; max-height:650px; } .pcy_report_graph_app_name_header{ text-transform: uppercase; padding:10px 20px; text-align:center; } .pcy_report_no_snapshot_video_avail_card{ width: 200px;height: 200px;border: 1px solid #ececec;margin: 0 10px; } .pcy_report_no_snapshot_video_avail_card > ul{ width: 100%;height: 100%;text-align: center; } .pcy_report_no_snapshot_video_avail_card_img{ width: 100%;background-color:#f7f7f7; } .pcy_report_no_snapshot_video_avail_card_img i{ display: inline-block;width: 100%;font-size: 5em;color: #b7b7b7;line-height: 2.5em; } .pcy_report_no_snapshot_video_avail_card_text{ width:100%; } .pcy_report_no_snapshot_video_avail_card_text span{ display:inline-block;line-height:2.8em;width: 100%; } .pcy_report_video_card{ position:relative; width:250px; margin: 0px 10px; margin-bottom:10px; } .pcy_report_card_video_section{ width:100%; height:200px; background-color:#636363; text-align:center; } .pcy_report_card_video_section > i{ font-size:6em; line-height:2.5em; color:#9a9a9a; } .pcy_report_card_video_section:hover > i{ color:#c5c5c5; cursor:pointer; } .pcy_report_card_video_section:hover{ cursor:pointer; } .pcy_report_card_video_details{ width:100%; min-height:100px; border:1px solid #c1c1c1; border-top:0; } .pcy_report_card_video_info_section{ //background-color:#eee; } .pcy_report_card_video_info_section > p{ margin:0; padding:5px; word-wrap:break-word; min-height:70px; } .pcy_report_card_video_section_tool_container{ width:250px; height:30px; //background-color:#eee; } .pcy_report_card_video_section_tool_container > i{ padding: 2px 15px; font-size: 1.5em; color:#b5b5b5; float:right; } .pcy_report_card_video_section_tool_container > i:hover{ color:#969696; cursor:pointer; } .pcy_no_graph_data_available{ width:100%;height:100px; } .pcy_no_graph_data_available > p{ text-align:center;padding: 3% 0%;margin-bottom:0px;width: 100%; } .pcy_toggle_expand{ float:right; padding:5px 10px; } .pcy_multi_view_label { width: 50%; min-width:150px; display: block; margin: 0px auto; text-align: center; background-color: #FF5722; color: #fff; font-weight: bold; text-transform: uppercase; } .GraphNote{ margin: auto; display: table; } </style> _END_HEADER_ print $HTML <<'_END_HEADER_'; <script> $(document).ready(function(){ $('#jiraloginbutton').on('click',function(e){ $('#jiraCreateTaskPopup').iziModal('open'); if (typeof Cookies.get('atlasurl') != 'undefined') { var atlasurl = Cookies.get('atlasurl'); var atlastoken = Cookies.get('atlastoken'); var atlasname = Cookies.get('atlasname'); $.ajax({ type: 'POST', url: '../api/jira_api', data: {"filter":"projects","atlasurl":atlasurl,"atlastoken":atlasname+'='+atlastoken}, dataType: "json", success: function(data) { if(data.hasOwnProperty('errorMessages')) { errorToast(data.errorMessages[0]); }else{ $('#jiraprojects').children().remove(); for(var i=0; i<data.length;i++){ $('#jiraprojects').append('<option value="'+data[i].key+'">'+data[i].name+'</option>') } } }, error:function(error){ console.log(error); } }); } else { // Display error message or use localStorage errorToast('Authenticate with your jira credentials'); } }) }) var performArray = []; </script> </head> _END_HEADER_ print $HTML <<'_END_HEADER_'; <body class="pcy_disable_select"> <div class="chart"> <div class="block-graph"> <div class="block-graph-content"> <div class="row"> <div class="col-md-12"> <a class="pcy_toggle_expand" data-attr-current-state="collapsed">Expand all</a> </div> </div> </div> </div> </div> _END_HEADER_ print $HTML <<'_END_HEADER_'; <div class="pc-cpu-graph chart" id="chartCpuGraph"> <div class="block-graph"> <div class="block-graph-header"> <h3 class="block-title">CPU Chart</h3> <div class="pc-block-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="block-graph-content"> <div class="row"> <div class="col-md-12" > <div id="cpuChartData"> <!-- Dynamic content --> </div> </div> </div> </div> </div> </div> _END_HEADER_ print $HTML <<'_END_HEADER_'; <div class="pc-memory-graph chart" id="MemoryChart"> <div class="block-graph"> <div class="block-graph-header"> <h3 class="block-title">Memory Chart</h3> <div class="pc-block-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="block-graph-content"> <div class="row"> <div class="col-md-12"> <div id="memoryChartData"> <!-- Dynamic content --> </div> </div> </div> </div> </div> </div> <div class="pc-frame-graph chart" id="NetworkChart"> <div class="block-graph"> <div class="block-graph-header"> <h3 class="block-title">Network Chart</h3> <div class="pc-block-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="block-graph-content"> <div class="row"> <div class="col-md-12"> <div id="networkChartData"> <!-- Dynamic content --> </div> </div> </div> </div> </div> </div> _END_HEADER_ if($iosAutomation != 1){ print $HTML <<'_END_HEADER_'; <div class="pc-battery-graph chart" id="BatteryChart"> <div class="block-graph"> <div class="block-graph-header"> <h3 class="block-title">Battery Chart</h3> <div class="pc-block-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="block-graph-content"> <div class="row"> <div class="col-md-12"> <div id="batteryChartData"> <!-- Dynamic content --> </div> </div> </div> </div> </div> </div> <div class="pc-frame-graph chart" id="FrameTimeChart"> <div class="block-graph"> <div class="block-graph-header"> <h3 class="block-title">Frame Rendering Time</h3> <div class="pc-block-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="block-graph-content"> <div class="row"> <div class="col-md-12"> <div id="frameTimeChartData"> <!-- Dynamic content --> </div> </div> <!-- <span class="GraphNote"><b>Note:-</b> This graph represents limited performance data. You can download the complete raw data.</span> --> </div> </div> </div> </div> <div class="pc-logs chart" id="PerfDataContainer"> <div class="block-graph"> <!-- <div class="block-graph-header"> <h3 class="block-title">Download Comprehensive Performance Raw Data</h3> <div class="pc-block-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> --> <!-- <div class="block-graph-content"> <div class="row"> <div class="col-md-12"> <div id="createPerDataLink"> <ul class="pcy_report_log_container"> Dynamic content </ul> </div> </div> </div> </div> --> </div> </div> _END_HEADER_ } print $HTML <<'_END_HEADER_'; <script> $(document).ready(function(){ /*$('main').slimScroll({ color: '#000', height: '90vh', distance: '0px', alwaysVisible: true });*/ _END_HEADER_ if($iosAutomation == 1){ print $HTML <<'_END_HEADER_'; createiosCPUGraph(); createiosMemoryGraph(); createiosNetworkGraph(); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; createCPUGraph(); createMemoryGraph(); createNetworkGraph(); createBatteryGraph(); createFrameRenderGraph(); collapseAllForceRefresh(); createPerDataLink(); _END_HEADER_ } print $HTML <<'_END_HEADER_'; // toggle collapse $('.pc-block-tools').on('click', function () { var ibox = $(this).find('.collapse-link').closest('div.block-graph'); var button = $(this).find('i'); var content = ibox.children('.block-graph-content'); content.slideToggle(200); button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down'); ibox.toggleClass('').toggleClass('border-bottom'); setTimeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); }); $('.pcy_toggle_expand').on('click', function () { var allCollapsibles = $('.pc-block-tools .collapse-link'); var currentState = $('.pcy_toggle_expand').attr('data-attr-current-state'); if(allCollapsibles.length >= 1){ for(var i=0; i<=allCollapsibles.length;i++){ var ibox = $(allCollapsibles[i]).closest('div.block-graph'); var button = $(allCollapsibles[i]).find('i'); var content = ibox.children('.block-graph-content'); if(currentState === 'collapsed'){ $('.pcy_toggle_expand').html('Collapse All'); $('.pcy_toggle_expand').attr('data-attr-current-state','expanded'); content.slideDown(200); button.addClass('fa-chevron-up').removeClass('fa-chevron-down'); ibox.addClass('border-bottom'); setTimeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); } else{ $('.pcy_toggle_expand').html('Expand All'); $('.pcy_toggle_expand').attr('data-attr-current-state','collapsed'); content.slideUp(200); button.removeClass('fa-chevron-up').addClass('fa-chevron-down'); ibox.removeClass('border-bottom'); setTimeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); } } } }); }); function collapseAllForceRefresh(){ var allCollapsibles = $('.pc-block-tools .collapse-link'); if(allCollapsibles.length >= 1){ for(var i=0; i<=allCollapsibles.length;i++){ var ibox = $(allCollapsibles[i]).closest('div.block-graph'); var button = $(allCollapsibles[i]).find('i'); var content = ibox.children('.block-graph-content'); content.slideUp(200); button.removeClass('fa-chevron-up').addClass('fa-chevron-down'); ibox.addClass('border-bottom'); setTimeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); } } } function displayGeneralInfo(){ var link; if(reportLocation == cloudName){ serverUrl = 'local'; link = '..'; }else{ var sessionId = Cookies.get("PYPCLOUDY"); serverUrl = reportLocation+"/api/subclouds_viewandDownload_files?session="+sessionId; link = reportLocation; } $("#currentReport, #sess_name").html(reportAllData.session_details.sess_name); $("#sess_start_time").html(reportAllData.session_details.stime); $("#sess_end_time").html(reportAllData.session_details.etime); $("#sess_duration").html(reportAllData.session_details.du); $("#dev_image").attr('src', link + '/device_images/large/half/' + reportAllData.device_details.url); $("#dev_os_name").html(reportAllData.device_details.os); $("#dev_ver").html(reportAllData.device_details.ver); $("#dev_layout_size").html(reportAllData.device_details.screen_size); $("#dev_manufacturer").html(reportAllData.device_details.manu); $("#dev_model").html(reportAllData.device_details.model); $("#dev_dpi").html(reportAllData.device_details.hdpi); $("#dev_resolution").html(reportAllData.device_details.res); } _END_HEADER_ print $HTML <<'_END_HEADER_'; function createBatteryGraph(){ _END_HEADER_ $bat_dev_con_size= @bat_dev_con; if($bat_dev_con_size > 3){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#batteryChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S.%L', columns: [ _END_HEADER_ print $HTML "@bat_date_time"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@bat_dev_con"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@bat_app_con"; print $HTML <<'_END_HEADER_'; ] }, grid: { x: { show: true }, y: { show: true } }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S.%L', culling: { max: 4 } } }, y: { show: false } }, legend: { position: 'bottom' }, point: { focus: { expand: { enabled: true } } }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#batteryChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#batteryChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createiosNetworkGraph(){ _END_HEADER_ my $wifi_size= @wifircvd; if($wifi_size > 2){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#networkChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S', columns: [ _END_HEADER_ print $HTML "@ios_wifi_date_time"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@wifircvd"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@wifisent"; print $HTML <<'_END_HEADER_'; ] }, grid: { x: { show: true }, y: { show: true } }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S', culling: { max: 3 } } }, y: { show: false } }, legend: { position: 'bottom' }, point: { focus: { expand: { enabled: true } } }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#networkChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#networkChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createiosMemoryGraph(){ _END_HEADER_ my $user_iosmem_size = @memory; if($user_iosmem_size > 4){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#memoryChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S', columns: [ _END_HEADER_ print $HTML "@ios_mem_date_time"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@memory"; print $HTML <<'_END_HEADER_'; ] }, grid: { x: { show: true }, y: { show: true } }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S', culling: { max: 3 } } }, y: { show: false } }, legend: { position: 'bottom' }, point: { focus: { expand: { enabled: true } } }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#memoryChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#memoryChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createiosCPUGraph(){ _END_HEADER_ my $user_ioscpu_size= @cpu; if($user_ioscpu_size > 4){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#cpuChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S', columns: [ _END_HEADER_ print $HTML "@ios_cpu_date_time"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@cpu"; print $HTML <<'_END_HEADER_'; ] }, grid: { x: { show: true }, y: { show: true } }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S ', culling: { max: 3 } } }, y: { show: false } }, legend: { position: 'bottom' }, point: { focus: { expand: { enabled: true } } }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#cpuChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#cpuChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createCPUGraph(){ _END_HEADER_ $user_cpu_size= @user_cpu; my $user_app_size= @app_cpu; if($user_cpu_size > 2){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#cpuChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S.%L', columns: [ _END_HEADER_ print $HTML "@cpu_date_time"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@user_cpu"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@system_cpu"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@app_cpu"; print $HTML <<'_END_HEADER_'; ] }, grid: { x: { show: true }, y: { show: true } }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S.%L', culling: { max: 4 } } }, y: { show: false } }, legend: { position: 'bottom' }, point: { focus: { expand: { enabled: true } } }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#cpuChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#cpuChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createNetworkGraph(){ _END_HEADER_ $net_up_pkt_size= @net_up_pkt; if($net_up_pkt_size > 3){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#networkChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S.%L', columns: [ _END_HEADER_ print $HTML "@net_date_time"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@net_up_pkt"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@net_up_data"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@net_down_pkt"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@net_down_data"; print $HTML <<'_END_HEADER_'; ] }, grid: { x: { show: true }, y: { show: true } }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S.%L', culling: { max: 4 } } }, y: { show: false } }, legend: { position: 'bottom' }, point: { focus: { expand: { enabled: true } } }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#networkChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#networkChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createFrameRenderGraph(){ _END_HEADER_ $frame_draw_size= @frame_draw; if($frame_draw_size > 3){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#frameTimeChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S.%L', columns: [ _END_HEADER_ print $HTML "@frame_date_time"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@frame_draw"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@frame_prepare"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@frame_process"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@frame_execute"; print $HTML <<'_END_HEADER_'; ], type: 'bar', groups: [ ['Execute', 'Process', 'Prepare', 'Draw'] ] }, color: { pattern: ['#1f77b4', '#d62728' , '#2ca02c', '#ff7f0e'] }, grid: { x: { show: true }, y: { show: true } }, bar : { width : 5 }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S.%L', culling: { max: 4 } } }, y: { show: false } }, legend: { position: 'bottom' }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#frameTimeChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#frameTimeChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createMemoryGraph(){ _END_HEADER_ $NPSS_mem_size= @NPSS_mem; if($NPSS_mem_size > 3){ print $HTML <<'_END_HEADER_'; var chart = c3.generate({ bindto: d3.select("#memoryChartData"), padding: { top: 10, right: 40, bottom: 10, left: 40 }, data: { x: 'Dates', xFormat: '%H:%M:%S.%L', columns: [ _END_HEADER_ print $HTML "@mem_datetime"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@DHA_mem"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@DPSS_mem"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@DHS_mem"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@NHA_mem"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@NPSS_mem"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@NHS_mem"; print $HTML <<'_END_HEADER_'; , _END_HEADER_ print $HTML "@TAPP_CON_mem"; print $HTML <<'_END_HEADER_'; ] }, grid: { x: { show: true }, y: { show: true } }, axis: { x: { type: 'timeseries', localtime: true, tick: { format: '%H:%M:%S.%L', culling: { max: 4 } } }, y: { show: false } }, legend: { position: 'bottom' }, point: { focus: { expand: { enabled: true } } }, zoom: { enabled: true } }); _END_HEADER_ } else{ print $HTML <<'_END_HEADER_'; $("#memoryChartData").children().remove(); var noGraphDataAvailableCard = [ "<div class='pcy_no_graph_data_available'>", "<p>No data available.</p>", "</div>" ].join(''); $("#memoryChartData").last().append(noGraphDataAvailableCard); _END_HEADER_ } print $HTML <<'_END_HEADER_'; } function createPerDataLink(){ var result = "pass"; if(result){ $("#createPerDataLink .pcy_report_log_container").children().remove(); var logItem = [ _END_HEADER_ print $HTML "'<li class=\"pcy_report_log_dynamic_list_item\" data-attr-name=\"CPU raw data\"> <span style=\"display:inline-block;width:160px;\"> Cpu raw data </span> <a download target=\"_blank\" href=cpu.txt> cpu.txt </a></li><br>',"; print $HTML "'<li class=\"pcy_report_log_dynamic_list_item\" data-attr-name=\"MEMORY raw data\"> <span style=\"display:inline-block;width:160px;\"> Memory raw data </span> <a download target=\"_blank\" href=mem.txt> mem.txt </a></li><br>',"; print $HTML "'<li class=\"pcy_report_log_dynamic_list_item\" data-attr-name=\"BATTERY raw data\"> <span style=\"display:inline-block;width:160px;\"> Battery raw data </span> <a download target=\"_blank\" href=bat.txt> bat.txt </a></li><br>',"; print $HTML "'<li class=\"pcy_report_log_dynamic_list_item\" data-attr-name=\"NETWORK raw data\"> <span style=\"display:inline-block;width:160px;\"> Network raw data </span> <a download target=\"_blank\" href=net.txt> net.txt </a></li><br>',"; print $HTML "'<li class=\"pcy_report_log_dynamic_list_item\" data-attr-name=\"FRAME raw data\"> <span style=\"display:inline-block;width:160px;\"> Frame raw data </span> <a download target=\"_blank\" href=frame.txt>frame.txt </a></li><br>',"; print $HTML <<'_END_HEADER_'; ].join(''); $("#createPerDataLink .pcy_report_log_container").last().append(logItem); } else{ $("#createPerDataLink .pcy_report_log_container").children().remove(); var logItem = [ "<li class='pcy_report_log_list_item'>No Raw Performance Data Available</li>" ].join(''); $("#createPerDataLink .pcy_report_log_container").last().append(logItem); } } _END_HEADER_ print $HTML <<'_END_HEADER_'; $("#jiraCreateTaskPopup").iziModal({ title: 'Log a bug in JIRA', subtitle: 'Fill out the JIRA fields below.', headerColor: '#88A0B9', zindex:9999, height:500, width:600 }); </script> </body></html> _END_HEADER_ close($HTML); #=============================END INDEX HTML FILE==================================== sub timeDiff { my $st = shift; my $en = shift; $session_dur_minutes=0; #my($st_M, $st_d, $st_h, $st_m, $st_s, $st_ms) = $st=~ /^(.*?)-(.*?) (.*?):(.*?):(.*?)\.(.*?)\ /; #my($en_M, $en_d, $en_h, $en_m, $en_s, $en_ms) = $en=~ /^(.*?)-(.*?) (.*?):(.*?):(.*?)\.(.*?)\ /; my $stDate=&ParseDate($st); my $enDate=&ParseDate($en); my $delta=&DateCalc($stDate,$enDate); my $deltaStr=&Delta_Format($delta,1,"%st"); $session_dur_minutes = int($deltaStr/60); $session_dur_secs = int($deltaStr%60); return int($deltaStr); } sub epoctoHumanReadable { my $time = shift; my @months = ("Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec"); my ($sec, $min, $hour, $day,$month,$year) = (localtime($time))[0,1,2,3,4,5]; # You can use 'gmtime' for GMT/UTC dates instead of 'localtime' #print "Unix time ".$time." converts to ".$months[$month]." ".$day.", ".($year+1900); #print " ".$hour.":".$min.":".$sec."\n"; my $data=$months[$month]." ".$day.", ".($year+1900)." ".$hour.":".$min.":".$sec; #print("Change data is $data\n"); return $data; } sub epoctoHumanReadableiosPerf { my $time = shift; my @months = ("Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec"); my ($sec, $min, $hour, $day,$month,$year) = (localtime($time))[0,1,2,3,4,5]; my $data=$hour.":".$min.":".$sec; return $data; } #epoctoHumanReadable(1557992804);
pankyopkey/pCloudy-sample-projects
Java/Advanced(Continued...)/Chapter 15- JemeterTestNGwithpCloudyAppiumwithpCloudyReports (Android Native + TestNG)/generatePerformanceReport.pl
Perl
apache-2.0
56,041
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. 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 Search::Elasticsearch::Client::6_0::Scroll; use Moo; use Search::Elasticsearch::Util qw(parse_params throw); use namespace::clean; has '_buffer' => ( is => 'ro' ); with 'Search::Elasticsearch::Role::Is_Sync', 'Search::Elasticsearch::Client::6_0::Role::Scroll'; #=================================== sub BUILDARGS { #=================================== my ( $class, $params ) = parse_params(@_); my $es = delete $params->{es}; my $scroll = $params->{scroll} ||= '1m'; throw( 'Param', 'The (scroll_in_body) parameter has been replaced by (scroll_in_qs)' ) if exists $params->{scroll_in_body}; my $scroll_in_qs = delete $params->{scroll_in_qs}; my $results = $es->search($params); my $total = $results->{hits}{total}; if (ref $total) { $total = $total->{value} } return { es => $es, scroll => $scroll, scroll_in_qs => $scroll_in_qs, aggregations => $results->{aggregations}, facets => $results->{facets}, suggest => $results->{suggest}, took => $results->{took}, total_took => $results->{took}, total => $total, max_score => $results->{hits}{max_score}, _buffer => $results->{hits}{hits}, $total ? ( _scroll_id => $results->{_scroll_id} ) : ( is_finished => 1 ) }; } #=================================== sub next { #=================================== my ( $self, $n ) = @_; $n ||= 1; while ( $self->_has_scroll_id and $self->buffer_size < $n ) { $self->refill_buffer; } my @return = splice( @{ $self->_buffer }, 0, $n ); $self->finish if @return < $n; return wantarray ? @return : $return[-1]; } #=================================== sub drain_buffer { #=================================== my $self = shift; return splice( @{ $self->_buffer } ); } #=================================== sub buffer_size { 0 + @{ shift->_buffer } } #=================================== #=================================== sub refill_buffer { #=================================== my $self = shift; return 0 if $self->is_finished; my $buffer = $self->_buffer; my $scroll_id = $self->_scroll_id || return 0 + @$buffer; my $results = $self->scroll_request; my $hits = $results->{hits}{hits}; $self->_set_total_took( $self->total_took + $results->{took} ); if ( @$hits == 0 ) { $self->_clear_scroll_id; } else { $self->_set__scroll_id( $results->{_scroll_id} ); push @$buffer, @$hits; } $self->finish if @$buffer == 0; return 0 + @$buffer; } #=================================== sub finish { #=================================== my $self = shift; return if $self->is_finished || $self->_pid != $$; $self->_set_is_finished(1); @{ $self->_buffer } = (); my $scroll_id = $self->_scroll_id or return; $self->_clear_scroll_id; my %args = $self->scroll_in_qs ? ( scroll_id => $scroll_id ) : ( body => { scroll_id => $scroll_id } ); eval { $self->es->clear_scroll(%args) }; return 1; } 1; __END__ # ABSTRACT: A helper module for scrolled searches =head1 SYNOPSIS use Search::Elasticsearch; my $es = Search::Elasticsearch->new; my $scroll = $es->scroll_helper( index => 'my_index', body => { query => {...}, size => 1000, sort => '_doc' } ); say "Total hits: ". $scroll->total; while (my $doc = $scroll->next) { # do something } =head1 DESCRIPTION A I<scrolled search> is a search that allows you to keep pulling results until there are no more matching results, much like a cursor in an SQL database. Unlike paginating through results (with the C<from> parameter in L<search()|Search::Elasticsearch::Client::6_0::Direct/search()>), scrolled searches take a snapshot of the current state of the index. Even if you keep adding new documents to the index or updating existing documents, a scrolled search will only see the index as it was when the search began. This module is a helper utility that wraps the functionality of the L<search()|Search::Elasticsearch::Client::6_0::Direct/search()> and L<scroll()|Search::Elasticsearch::Client::6_0::Direct/scroll()> methods to make them easier to use. This class does L<Search::Elasticsearch::Client::6_0::Role::Scroll> and L<Search::Elasticsearch::Role::Is_Sync>. =head1 USE CASES There are two primary use cases: =head2 Pulling enough results Perhaps you want to group your results by some field, and you don't know exactly how many results you will need in order to return 10 grouped results. With a scrolled search you can keep pulling more results until you have enough. For instance, you can search emails in a mailing list, and return results grouped by C<thread_id>: my (%groups,@results); my $scroll = $es->scroll_helper( index => 'my_emails', type => 'email', body => { query => {... some query ... }} ); my $doc; while (@results < 10 and $doc = $scroll->next) { my $thread = $doc->{_source}{thread_id}; unless ($groups{$thread}) { $groups{$thread} = []; push @results, $groups{$thread}; } push @{$groups{$thread}},$doc; } =head2 Extracting all documents Often you will want to extract all (or a subset of) documents in an index. If you want to change your type mappings, you will need to reindex all of your data. Or perhaps you want to move a subset of the data in one index into a new dedicated index. In these cases, you don't care about sort order, you just want to retrieve all documents which match a query, and do something with them. For instance, to retrieve all the docs for a particular C<client_id>: my $scroll = $es->scroll_helper( index => 'my_index', size => 1000, body => { query => { match => { client_id => 123 } }, sort => '_doc' } ); while (my $doc = $scroll->next) { # do something } Very often the I<something> that you will want to do with these results involves bulk-indexing them into a new index. The easiest way to do this is to use the built-in L<Search::Elasticsearch::Client::6_0::Direct/reindex()> functionality provided by Elasticsearch. =head1 METHODS =head2 C<new()> use Search::Elasticsearch; my $es = Search::Elasticsearch->new(...); my $scroll = $es->scroll_helper( scroll => '1m', # optional scroll_in_qs => 0|1, # optional %search_params ); The L<Search::Elasticsearch::Client::6_0::Direct/scroll_helper()> method loads L<Search::Elasticsearch::Client::6_0::Scroll> class and calls L</new()>, passing in any arguments. You can specify a C<scroll> duration (which defaults to C<"1m">) and C<scroll_in_qs> (which defaults to C<false>). Any other parameters are passed directly to L<Search::Elasticsearch::Client::6_0::Direct/search()>. The C<scroll> duration tells Elasticearch how long it should keep the scroll alive. B<Note>: this duration doesn't need to be long enough to process all results, just long enough to process a single B<batch> of results. The expiry gets renewed for another C<scroll> period every time new a new batch of results is retrieved from the cluster. By default, the C<scroll_id> is passed as the C<body> to the L<scroll|Search::Elasticsearch::Client::6_0::Direct/scroll()> request. To send it in the query string instead, set C<scroll_in_qs> to a true value, but be aware: when querying very many indices, the scroll ID can become too long for intervening proxies. The C<scroll> request uses C<GET> by default. To use C<POST> instead, set L<send_get_body_as|Search::Elasticsearch::Transport/send_get_body_as> to C<POST>. =head2 C<next()> $doc = $scroll->next; @docs = $scroll->next($num); The C<next()> method returns the next result, or the next C<$num> results (pulling more results if required). If all results have been exhausted, it returns an empty list. =head2 C<drain_buffer()> @docs = $scroll->drain_buffer; The C<drain_buffer()> method returns all of the documents currently in the buffer, without fetching any more from the cluster. =head2 C<refill_buffer()> $total = $scroll->refill_buffer; The C<refill_buffer()> method fetches the next batch of results from the cluster, stores them in the buffer, and returns the total number of docs currently in the buffer. =head2 C<buffer_size()> $total = $scroll->buffer_size; The C<buffer_size()> method returns the total number of docs currently in the buffer. =head2 C<finish()> $scroll->finish; The C<finish()> method clears out the buffer, sets L</is_finished()> to C<true> and tries to clear the C<scroll_id> on Elasticsearch. This API is only supported since v0.90.6, but the call to C<clear_scroll> is wrapped in an C<eval> so the C<finish()> method can be safely called with any version of Elasticsearch. When the C<$scroll> instance goes out of scope, L</finish()> is called automatically if required. =head2 C<is_finished()> $bool = $scroll->is_finished; A flag which returns C<true> if all results have been processed or L</finish()> has been called. =head1 INFO ACCESSORS The information from the original search is returned via the following accessors: =head2 C<total> The total number of documents that matched your query. =head2 C<max_score> The maximum score of any documents in your query. =head2 C<aggregations> Any aggregations that were specified, or C<undef> =head2 C<facets> Any facets that were specified, or C<undef> =head2 C<suggest> Any suggestions that were specified, or C<undef> =head2 C<took> How long the original search took, in milliseconds =head2 C<took_total> How long the original search plus all subsequent batches took, in milliseconds. =head1 SEE ALSO =over =item * L<Search::Elasticsearch::Client::6_0::Direct/search()> =item * L<Search::Elasticsearch::Client::6_0::Direct/scroll()> =item * L<Search::Elasticsearch::Client::6_0::Direct/reindex()> =back
elastic/elasticsearch-perl
lib/Search/Elasticsearch/Client/6_0/Scroll.pm
Perl
apache-2.0
11,140
# # Copyright 2019 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # package network::atto::fibrebridge::snmp::plugin; use strict; use warnings; use base qw(centreon::plugins::script_snmp); sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $self->{version} = '1.0'; %{$self->{modes}} = ( 'hardware' => 'network::atto::fibrebridge::snmp::mode::hardware', 'fcport-usage' => 'network::atto::fibrebridge::snmp::mode::fcportusage', ); return $self; } 1; __END__ =head1 PLUGIN DESCRIPTION Check Atto FibreBridge (6500, 7500,...) in SNMP. =cut
Sims24/centreon-plugins
network/atto/fibrebridge/snmp/plugin.pm
Perl
apache-2.0
1,361