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
#!/usr/local/ensembl/bin/perl -w =pod =head1 NAME check_genetree_data.pl - QCs the Compara GeneTree data =head1 SYNOPSIS perl check_genetree_data.pl [options] Options: -h|--help Show brief help and exit. -m|--man Show detailed help -u|--url URL-style connection params to compara DB. -l|--long Run extended test suite. =head1 OPTIONS B<-h|--help> Print a brief help message and exits. B<-m|--man> Print man page and exit B<-u|--url> URL-style connection params to compara DB in following format: mysql://<user>:<pass>@<host>:<port>/<db_name> B<-l|--long> Run extended test suite. =head1 DESCRIPTION Add a description of each test here. Maintained by Albert Vilella <avilella@ebi.ac.uk> =cut use strict; use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor; use Bio::EnsEMBL::Hive::URLFactory; use Getopt::Long; use Pod::Usage; my $DEFAULT_URL = 'mysql://ensro@compara1:3306/avilella_ensembl_compara_48'; # Get options my $help=0; my $man=0; my( $url, $long, $V ); GetOptions ( "help|?" => \$help, "man" => \$man, "url=s" => \$url, "longtests=s" => \$long, "verbose" => \$V, # Not yet used ) or pod2usage(2); pod2usage(-verbose => 2) if $man; pod2usage(1) if $help; $url ||= $DEFAULT_URL; my $dba = Bio::EnsEMBL::Hive::URLFactory->fetch($url . ';type=compara'); my $doit = 0; $doit = 1 if ($long); $|=1; my ($sql, $sth); if ($doit) { # # Check data consistency between gene_count and number of homology entries # ########################################################################## # print "# Check data consistency between gene_count and number of homology entries\n"; # $sql = "select node_id,value,(value*(value-1))/2 from protein_tree_tag where tag='gene_count'"; # $sth = $dba->dbc->prepare($sql); # $sth->execute; # my $this_count = sprintf("%05d",1); # while (my $aref = $sth->fetchrow_arrayref) { # my ($node_id, $value, $homology_count) = @$aref; # my $sql2 = "select count(*) from homology where tree_node_id=$node_id"; # my $sth2 = $dba->dbc->prepare($sql2); # print STDERR "## Checking $node_id / gene_count = $value / $homology_count / [$this_count]\n"; # $this_count = sprintf("%05d",$this_count+1); # $sth2->execute; # my $count = $sth2->fetchrow_array; # if ($count !=0 && $count != $homology_count) { # print STDERR "ERROR: tree $node_id (gene_count = $value) gene_count != homologies : should have $homology_count homologies instead of $count\n"; # print STDERR "ERROR: USED SQL : $sql\n $sql2\n"; # } # $sth2->finish; # my $sql3 = "select count(*) from homology h, homology_member hm where h.homology_id=hm.homology_id and h.tree_node_id=$node_id"; # my $sth3 = $dba->dbc->prepare($sql3); # $sth3->execute; # $count = $sth3->fetchrow_array; # if ($count !=0 && $count != 2*$homology_count) { # print STDERR "ERROR: tree $node_id (gene_count = $value) gene_count != homology_member : should have $homology_count homologies instead of $count\n"; # print STDERR "ERROR: USED SQL : $sql\n $sql3\n"; # } # $sth3->finish; # } # $sth->finish; # Check for dangling internal nodes that have no children ###################################################### print "# Check for dangling internal nodes that have no children\n"; $sql = "select count(*) from protein_tree_node n1 left join protein_tree_node n2 on n1.node_id=n2.parent_id where n2.parent_id is NULL and n1.right_index-n1.left_index > 1"; $sth = $dba->dbc->prepare($sql); $sth->execute; while (my $aref = $sth->fetchrow_arrayref) { #should 0, if not delete culprit node_id in protein_tree_member my ($count) = @$aref; if ($count == 0) { print "PASSED: protein_tree_node is consistent - no dangling internal nodes\n"; } else { print STDERR "ERROR: protein_tree_node has dangling internal nodes with no children based on the left and right_index\n"; print STDERR "ERROR: USED SQL : $sql\n"; } } $sth->finish; ## This check is not relevant any more since we don't store all between_species_paralogs # # Check data consistency between pt* tables on node_id # ###################################################### # print "# Check data consistency between pt* tables on node_id\n"; # $sql = "select count(*) from protein_tree_member ptm left join protein_tree_node ptn on ptm.node_id=ptn.node_id where ptn.node_id is NULL"; # $sth = $dba->dbc->prepare($sql); # $sth->execute; # while (my $aref = $sth->fetchrow_arrayref) { # #should 0, if not delete culprit node_id in protein_tree_member # my ($count) = @$aref; # if ($count == 0) { # print "PASSED: protein_tree_member versus protein_tree_node is consistent\n"; # } else { # print STDERR "ERROR: protein_tree_member versus protein_tree_node is NOT consistent\n"; # print STDERR "ERROR: USED SQL : $sql\n"; # } # } # $sth->finish; # $sql = "select count(*) from protein_tree_tag ptt left join protein_tree_node ptn on ptt.node_id=ptn.node_id where ptn.node_id is NULL"; # $sth = $dba->dbc->prepare($sql); # $sth->execute; # while (my $aref = $sth->fetchrow_arrayref) { # #should be 0, if not delete culprit node_id in protein_tree_tag # my ($count) = @$aref; # if ($count == 0) { # print "PASSED: protein_tree_tag versus protein_tree_node is consistent\n"; # } else { # print STDERR "ERROR: protein_tree_tag versus protein_tree_node is NOT consistent\n"; # print STDERR "ERROR: USED SQL : $sql\n"; # } # } # $sth->finish; # # Check that the gene_count tags and the right-left index counts are equivalent # $sql = "select p1.*, ROUND((((p1.right_index-p1.left_index+1)/2)+1)/2) as p1_size, ptt1.value as gene_count from protein_tree_node p1, protein_tree_tag ptt1 where p1.parent_id=1 and p1.node_id=ptt1.node_id and ptt1.tag='gene_count' and ROUND((((p1.right_index-p1.left_index+1)/2)+1)/2)!=ptt1.value"; # $sth = $dba->dbc->prepare($sql); # $sth->execute; # while (my $aref = $sth->fetchrow_arrayref) { # #should be 0, if not delete culprit node_id in protein_tree_tag # my ($count) = @$aref; # if ($count == 0) { # print "PASSED: protein_tree_tag gene_count versus right_index left_index formula is consistent\n"; # } else { # print STDERR "ERROR: protein_tree_tag versus protein_tree_node is NOT consistent\n"; # print STDERR "ERROR: USED SQL : $sql\n"; # } # } # $sth->finish; # Check for unique member presence in ptm ######################################### print "# Check for unique member presence in ptm\n"; $sql = "select member_id from protein_tree_member group by member_id having count(*)>1"; #This should return 0 rows. $sth = $dba->dbc->prepare($sql); # If no duplicate, each select should return an empty row; $sth->execute; my $ok = 1; while (my $aref = $sth->fetchrow_arrayref) { my ($member_id) = @$aref; print STDERR "ERROR: some member duplicates in protein_tree_member! This can happen if there are remains of broken clusters in the db that you haven't deleted yet. Usually before merging to the compara production db\n"; print STDERR "ERROR: USED SQL : $sql\n"; $ok = 0; last; } print "PASSED: no member duplicates in protein_tree_member\n" if ($ok); ## # check for unique member presence in ptm but without considering singletons ## ############################################################################ ## ## $sql = 'select * from protein_tree_member ptm, protein_tree_node ptn where 0<abs(ptn.left_index-ptn.right_index) and ptn.node_id=ptm.node_id group by ptm.member_id having count(*)>1'; ## ## #This should return 0 rows. ## ## $sth = $dba->dbc->prepare($sql); ## ## # If no duplicate, each select should return an empty row; ## $sth->execute; ## ## $ok = 1; ## while (my $aref = $sth->fetchrow_arrayref) { ## my ($member_id) = @$aref; ## print STDERR "ERROR: some member duplicates (non-singletons) in protein_tree_member!\n"; ## print STDERR "ERROR: USED SQL : $sql\n"; ## $ok = 0; ## last; ## } ## print "PASSED: no member duplicates (non-singletons) in protein_tree_member\n" if ($ok); ## ## # Check data consistency between pt_node and homology with node_id ################################################################## print "# Check data consistency between pt_node and homology with node_id\n"; $sql = "select count(*) from homology h left join protein_tree_node ptn on h.ancestor_node_id=ptn.node_id where h.description!='other_paralog' AND ptn.node_id is NULL"; $sth = $dba->dbc->prepare($sql); $sth->execute; while (my $aref = $sth->fetchrow_arrayref) { #should be 0 my ($count) = @$aref; if ($count == 0) { print "PASSED: homology versus protein_tree_node is consistent\n"; } else { print STDERR "ERROR: homology versus protein_tree_node is NOT consistent\n"; print STDERR "ERROR: USED SQL : $sql\n"; } } $sth->finish; } # end of if ($doit) # Check for homology has no duplicates ###################################### print "# Check for homology has no duplicates\n"; my $mlsses; my $mlssa; $mlssa = $dba->get_MethodLinkSpeciesSetAdaptor; $mlsses = $mlssa->fetch_all_by_method_link_type('ENSEMBL_ORTHOLOGUES'); push @{$mlsses},@{$mlssa->fetch_all_by_method_link_type('ENSEMBL_PARALOGUES')}; $sql = "select hm1.member_id,hm2.member_id,h.method_link_species_set_id from homology_member hm1, homology_member hm2, homology h where h.homology_id=hm1.homology_id and hm1.homology_id=hm2.homology_id and hm1.member_id<hm2.member_id and h.method_link_species_set_id=? group by hm1.member_id,hm2.member_id having count(*)>1"; $sth = $dba->dbc->prepare($sql); while (my $mlss = shift @$mlsses) { # If no duplicate, each select should return an empty row; $sth->execute($mlss->dbID); my $ok = 1; while (my $aref = $sth->fetchrow_arrayref) { my ($member_id1, $member_id2,$mlss_id) = @$aref; print STDERR "ERROR: some homology duplicates in method_link_species_set_id=$mlss_id!\n"; print STDERR "ERROR: USED SQL : $sql\n"; $ok = 0; last; } print "PASSED: no homology duplicates in method_link_species_set_id=".$mlss->dbID."\n" if ($ok); } $sth->finish; # Check that one2one genes are not involved in any other orthology # (one2many or many2many) # check to be done by method_link_species_set with method_link_type # ENSEMBL_ORTHOLOGUES ################################################################## print "# Check that one2one genes are not involved in any other orthology\n"; $mlssa = $dba->get_MethodLinkSpeciesSetAdaptor; $mlsses = $mlssa->fetch_all_by_method_link_type('ENSEMBL_ORTHOLOGUES'); if ($doit) { # $sql = "select h.method_link_species_set_id,hm.member_id from homology h, homology_member hm where h.method_link_species_set_id=? and h.homology_id=hm.homology_id group by hm.member_id having count(*)>1 and group_concat(h.description) like '%ortholog_one2one%'"; $sql = "select h.method_link_species_set_id,hm.member_id from homology h, homology_member hm where h.method_link_species_set_id=? and h.homology_id=hm.homology_id group by hm.member_id having count(*)>1 and group_concat(h.description) ='ortholog_one2one'"; $sth = $dba->dbc->prepare($sql); while (my $mlss = shift @$mlsses) { # If no mistake in OrthoTree, each select should return an empty row; $sth->execute($mlss->dbID); my $ok = 1; while (my $aref = $sth->fetchrow_arrayref) { my ($mlss_id, $member_id) = @$aref; # print STDERR "ERROR: some [apparent_]one2one_ortholog also one2many or many2many in method_link_species_set_id=$mlss_id!\n"; print STDERR "ERROR: some one2one_ortholog also one2many or many2many in method_link_species_set_id=$mlss_id!\n"; print STDERR "ERROR: USED SQL : $sql\n"; $ok = 0; last; } # print "PASSED: [apparent_]one2one_ortholog are ok in method_link_species_set_id=".$mlss->dbID."\n" if ($ok); print "PASSED: one2one_ortholog are ok in method_link_species_set_id=".$mlss->dbID."\n" if ($ok); } $sth->finish; }
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-compara/scripts/pipeline/check_genetree_data.pl
Perl
apache-2.0
12,305
package Paws::CloudDirectory::TypedLinkAttributeDefinition; use Moose; has DefaultValue => (is => 'ro', isa => 'Paws::CloudDirectory::TypedAttributeValue'); has IsImmutable => (is => 'ro', isa => 'Bool'); has Name => (is => 'ro', isa => 'Str', required => 1); has RequiredBehavior => (is => 'ro', isa => 'Str', required => 1); has Rules => (is => 'ro', isa => 'Paws::CloudDirectory::RuleMap'); has Type => (is => 'ro', isa => 'Str', required => 1); 1; ### main pod documentation begin ### =head1 NAME Paws::CloudDirectory::TypedLinkAttributeDefinition =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::CloudDirectory::TypedLinkAttributeDefinition object: $service_obj->Method(Att1 => { DefaultValue => $value, ..., Type => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::CloudDirectory::TypedLinkAttributeDefinition object: $result = $service_obj->Method(...); $result->Att1->DefaultValue =head1 DESCRIPTION A typed link attribute definition. =head1 ATTRIBUTES =head2 DefaultValue => L<Paws::CloudDirectory::TypedAttributeValue> The default value of the attribute (if configured). =head2 IsImmutable => Bool Whether the attribute is mutable or not. =head2 B<REQUIRED> Name => Str The unique name of the typed link attribute. =head2 B<REQUIRED> RequiredBehavior => Str The required behavior of the C<TypedLinkAttributeDefinition>. =head2 Rules => L<Paws::CloudDirectory::RuleMap> Validation rules that are attached to the attribute definition. =head2 B<REQUIRED> Type => Str The type of the attribute. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::CloudDirectory> =head1 BUGS and CONTRIBUTIONS The source code is located here: https://github.com/pplu/aws-sdk-perl Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues =cut
ioanrogers/aws-sdk-perl
auto-lib/Paws/CloudDirectory/TypedLinkAttributeDefinition.pm
Perl
apache-2.0
2,216
#!/usr/bin/env perl =head1 LICENSE Copyright (c) 1999-2011 The European Bioinformatics Institute and Genome Research Limited. All rights reserved. This software is distributed under a modified Apache license. For license details, please see http://www.ensembl.org/info/about/code_licence.html =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <ensembl-dev@ebi.ac.uk>. Questions may also be sent to the Ensembl help desk at <helpdesk@ensembl.org>. =head1 NAME ensembl-efg create_probe_fasta.pl =head1 SYNOPSIS create_probe_fasta.pl [options] Options: Mandatory -instance|i Instance name -format|f Data format -group|g Group name =head1 OPTIONS =over 8 =item B<-instance|i> Mandatory: Instance name for the data set, this is the directory where the native data files are located =item B<-format|f> Mandatory: The format of the data files e.g. nimblegen =over 8 =item B<-group|g> Mandatory: The name of the experimental group =over 8 =item B<-data_root> The root data dir containing native data and pipeline data, default = $ENV{'EFG_DATA'} =item B<-debug> Turns on and defines the verbosity of debugging output, 1-3, default = 0 = off =over 8 =item B<-log_file|l> Defines the log file, default = "${instance}.log" =item B<-help> Print a brief help message and exits. =item B<-man> Prints the manual page and exits. =back =head1 DESCRIPTION B<This program> will read use the ensembl-efg API to parse array data failes and create fasta files for the remapping pipeline. =cut BEGIN{ if(! defined $ENV{'EFG_DATA'}){ if(-f "~/src/ensembl-efg/scripts/.efg"){ system (". ~/src/ensembl-efg/scripts/.efg"); }else{ die ("This script requires the .efg file available from ensembl-efg\n". "Please source it before running this script\n"); } } } use Getopt::Long; use Pod::Usage; use Bio::EnsEMBL::Funcgen::DBSQL::DBAdaptor; use Bio::EnsEMBL::Funcgen::Utils::Helper; GetOptions ( "pass|p=s" => \$pass, "port|l=s" => \$port, "host|h=s" => \$host, "user|u=s" => \$user, "dbname=s" => \$dbname, #"species|s=s" => \$species, #"data_version|d=s" => \$data_version, "array_name=s" => \$array_name, "input_dir=s" => \$input_dir, "output_dir=s" => \$output_dir, #should have MAGE flag here? or would this be format? "help|?" => \$help, "man|m" => \$man, "verbose=s" => \$verbose, ); if(! defined $input_dir || ! defined $array_name){ die("You must supply the following args -input_dir -array_name\n"); } print "Input Dir:\t$input_dir\nDesign Name:\t$design_name\nOutput Dir:\t$output_dir\n"; #check vars here =pod #SLURP PROBE POSITIONS my $file = $input_dir."/DesignFiles/${design_name}.pos"; open(IN, $file) || die ("Cannot open file:\t$file"); my @probe_pos; map (s/\r*\n//, @probe_pos = <IN>); close(IN); #REGION POSITIONS $file = $input_dir."/DesignFiles/${design_name}.ngd"; open(IN, $file) || die ("Cannot open file:\t$file"); my ($line, $seq_id, $build, $chr, $loc, $start, $stop, %regions); #Need to add build id mappins in Array/VendorDefs.pm while ($line = <IN>){ next if $. == 1;#can we just ignore this? doing the test each time will slow it down $line =~ s/\r*\n//; #What about strand? ($seq_id, $build, $chr, $loc) = split/\|/, $line; $seq_id =~ s/\s+[0-9]*$//; $chr =~ s/chr//; ($start, $stop) = split/-/, $loc; #Do we need seq_id check here for validity? #overkill? if(exists $regions{$seq_id}){ croak("Duplicate regions\n"); }else{ $chr = 23 if ($chr eq "X"); $chr = 24 if ($chr eq "Y"); $regions{$seq_id} = { start => $start, stop => $stop, chrom => $chr, build => $build, }; } } close(IN); =cut #Problem with NR probes in an array set(either by name or seq, not hashed on seq at present) #We could simply use a hash here to see whether we've seen the probe ID before #Or we can print all NR probes to file, sort and then remove replicates by looping and reprinting/skipping. #Go for hash at present as work with >14million probes with less than 2GB memory #Validate NDF files my $array = $ $file = $input_dir."/${design_name}.ndf";#He open(IN, $file) || die ("Cannot open file:\t$file"); $file = $output_dir."/${design_name}_probe.fasta"; open(FASTA, ">$file") || die ("Cannot open file:\t$file"); my ($xref_id, $seq, $probe_id, @features); my $length = 50;##HARDCODED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! while($line = <IN>){ next if $. == 1;#or should we have format check here for files $line =~ s/\r*\n//; $loc = ""; #PROBE_DESIGN_ID CONTAINER DESIGN_NOTE SELECTION_CRITERIA SEQ_ID PROBE_SEQUENCE MISMATCH MATCH_INDEX FEATURE_ID ROW_NUM COL_NUM PROBE_CLASS PROBE_ID POSITION DESIGN_ID X Y #Shall we use x and y here to creete a temp cel file for checking in R? #(undef, undef, undef, undef, $xref_id, $seq, undef, undef, # undef, undef, undef, undef, $probe_id) = split/\t/, $line; my @tmp = split/\t/, $line; #print "@tmp\n"; #next if $tmp[11] ne "experimental"; next if $tmp[1] !~ /BLOCK1/; #5 & 12 ###PROBE FEATURES #Put checks in here for build? #grep for features, need to handle more than one mapping # @features = grep (/\s+$probe_id\s+/, @probe_pos); # croak("Multiple probe_features: feature code needs altering") if (scalar(@features > 1)); #Need to handle controls/randoms here #won't have features but will have results!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #The format of the pos file looks like it should have all the data required, but # chromsome is missing, first undef :( # if(@features){ # foreach $feature(@features){ # #$feature =~ s/\r*\n//; # # #SEQ_ID CHROMOSOME PROBE_ID POSITION COUNT # ($seq_id, undef, undef, $start, undef) = split/\t/, $feature; # # if(exists $regions{$seq_id}){ # $loc .= $regions{$seq_id}{'chrom'}.":${start}-".($start + $length).";"; # } # else{ croak("No regions defined for $seq_id"); } # } # } #else{#CONTROL/RANDOM # #Enter placeholder features to enable result entries # print PROBE_FEATURE "\t0\t0\t0\t0\t0\t${pid}\t0\t0\tNA\n"; ## push @{$feature_map{$probe_id}}, $fid; # $fid++; #} #filter controls/randoms? Or would it be sensible to see where they map #Do we need to wrap seq here? #print FASTA ">${probe_id}\t$xref_id\t$loc\n$seq\n"; print FASTA ">probe:${design_name}:$tmp[12]\n$tmp[5]\n"; $loc = ""; } print "Processed ".($.- 1)." probes\n"; close(IN); close(FASTA);
adamsardar/perl-libs-custom
EnsemblAPI/ensembl-functgenomics/scripts/fasta/create_probe_fasta.pl
Perl
apache-2.0
6,583
package VMOMI::HostInternetScsiHbaDigestType; use parent 'VMOMI::SimpleType'; use strict; use warnings; 1;
stumpr/p5-vmomi
lib/VMOMI/HostInternetScsiHbaDigestType.pm
Perl
apache-2.0
109
package CoGe::Builder::Export::Gff; use Moose; extends 'CoGe::Builder::Buildable'; use CoGe::Accessory::IRODS qw(irods_get_base_path); use CoGe::Accessory::Utils qw(sanitize_name); use CoGe::Accessory::Web qw(download_url_for); use CoGe::Core::Genome qw(get_irods_metadata); use CoGe::Core::Storage qw(get_genome_cache_path get_gff_cache_path); use CoGe::Exception::MissingField; use CoGe::Exception::Generic; use File::Basename qw(basename); use File::Spec::Functions; use Data::Dumper; sub get_name { return "Generate/export gff"; #TODO add genome id and output types } sub build { my $self = shift; my $dest_type = $self->params->{dest_type}; $dest_type = "http" unless $dest_type; my $genome = $self->request->genome; my $genome_name = $self->params->{basename} = sanitize_name($genome->organism->name); # Parse output types my $outputs = $self->params->{output_types}; my %outputs; %outputs = map { lc($_) => 1 } @$outputs if $outputs; $outputs{'gff'} = 1 if (keys %outputs == 0); # default # Generate GFF/BED/TBL generation and export tasks foreach my $output_type (keys %outputs) { # Generate output filename based on params my $output_filename = get_gff_cache_path( gid => $genome->id, genome_name => $genome_name, output_type => $output_type, params => $self->params ); # Add task to generate output file(s) if ($output_type eq 'gff') { $self->add( $self->create_gff( %{$self->params}, output_file => $output_filename ) ); } if ($output_type eq 'bed') { $self->add( $self->create_bed( %{$self->params}, output_file => $output_filename ) ); } if ($output_type eq 'tbl') { $self->add( $self->create_tbl( %{$self->params}, output_file => $output_filename ) ); } # Add tasks to export/download output file(s) if ($dest_type eq "irods") { # irods export # Set IRODS destination path my $irods_base = $self->params->{dest_path}; $irods_base = irods_get_base_path($self->user->name) unless $irods_base; my $irods_dest = catfile($irods_base, basename($output_filename)); # Export file task $self->add_to_previous( $self->export_to_irods( src_file => $output_filename, dest_file => $irods_dest, overwrite => $self->params->{overwrite} ) ); # Set file metadata task my $md = get_irods_metadata($genome); my $md_file = catfile($self->staging_dir, 'irods_metadata.json'); CoGe::Accessory::TDS::write($md_file, $md); $self->add_to_previous( $self->irods_imeta( dest_file => $irods_dest, metadata_file => $md_file ) ); # Add to results $self->add_to_previous( $self->add_result( result => { type => 'irods', path => $irods_dest } ) ); } else { # http download $self->add_to_previous( $self->add_result( result => { type => 'url', path => download_url_for( wid => $self->workflow->id, file => $output_filename ) } ) ); } } return 1; } __PACKAGE__->meta->make_immutable; 1;
LyonsLab/coge
modules/Pipelines/lib/CoGe/Builder/Export/Gff.pm
Perl
bsd-2-clause
4,014
#!/usr/bin/env perl use strict; use warnings; use Encode qw(decode_utf8 encode_utf8); use Graph::Reader::UnicodeTree; use IO::Barf qw(barf); use File::Temp qw(tempfile); # Example data. my $data = decode_utf8(<<'END'); 1─┬─2 β”œβ”€3───4 β”œβ”€5 β”œβ”€6─┬─7 β”‚ β”œβ”€8 β”‚ └─9 └─10 END # Temporary file. my (undef, $tempfile) = tempfile(); # Save data to temp file. barf($tempfile, encode_utf8($data)); # Reader object. my $obj = Graph::Reader::UnicodeTree->new; # Get graph from file. my $g = $obj->read_graph($tempfile); # Clean temporary file. unlink $tempfile; # Print to output. print $g."\n"; # Output: # 1-10,1-2,1-3,1-5,1-6,3-4,6-7,6-8,6-9
tupinek/Graph-Reader-UnicodeTree
examples/ex1.pl
Perl
bsd-2-clause
699
#!perl use v5.20; use warnings; use SVG; require 'svg_creators.pl'; use lib './svg_creators'; use constant WIDTH_MM => 6.6; use constant HEIGHT_MM => 6.6; my $svg = SVG->new( width => mm_to_px( WIDTH_MM ), height => mm_to_px( HEIGHT_MM ), ); my $draw = $svg->group( id => 'draw', style => { stroke => 'black', 'stroke-width' => 0.3, fill => 'none', }, ); $draw->circle( cx => (WIDTH_MM / 2), cy => (WIDTH_MM / 2), r => mm_to_px( WIDTH_MM / 2 ), ); print $svg->xmlify;
frezik/race_record
svg_creators/button.pl
Perl
bsd-2-clause
554
package Zonemaster::LDNS::RR; use strict; use warnings; use Zonemaster::LDNS::RR::A; use Zonemaster::LDNS::RR::A6; use Zonemaster::LDNS::RR::AAAA; use Zonemaster::LDNS::RR::AFSDB; use Zonemaster::LDNS::RR::APL; use Zonemaster::LDNS::RR::ATMA; use Zonemaster::LDNS::RR::CAA; use Zonemaster::LDNS::RR::CDS; use Zonemaster::LDNS::RR::CERT; use Zonemaster::LDNS::RR::CNAME; use Zonemaster::LDNS::RR::DHCID; use Zonemaster::LDNS::RR::DLV; use Zonemaster::LDNS::RR::DNAME; use Zonemaster::LDNS::RR::DNSKEY; use Zonemaster::LDNS::RR::DS; use Zonemaster::LDNS::RR::EID; use Zonemaster::LDNS::RR::EUI48; use Zonemaster::LDNS::RR::EUI64; use Zonemaster::LDNS::RR::GID; use Zonemaster::LDNS::RR::GPOS; use Zonemaster::LDNS::RR::HINFO; use Zonemaster::LDNS::RR::HIP; use Zonemaster::LDNS::RR::IPSECKEY; use Zonemaster::LDNS::RR::ISDN; use Zonemaster::LDNS::RR::KEY; use Zonemaster::LDNS::RR::KX; use Zonemaster::LDNS::RR::L32; use Zonemaster::LDNS::RR::L64; use Zonemaster::LDNS::RR::LOC; use Zonemaster::LDNS::RR::LP; use Zonemaster::LDNS::RR::MAILA; use Zonemaster::LDNS::RR::MAILB; use Zonemaster::LDNS::RR::MB; use Zonemaster::LDNS::RR::MD; use Zonemaster::LDNS::RR::MF; use Zonemaster::LDNS::RR::MG; use Zonemaster::LDNS::RR::MINFO; use Zonemaster::LDNS::RR::MR; use Zonemaster::LDNS::RR::MX; use Zonemaster::LDNS::RR::NAPTR; use Zonemaster::LDNS::RR::NID; use Zonemaster::LDNS::RR::NIMLOC; use Zonemaster::LDNS::RR::NINFO; use Zonemaster::LDNS::RR::NS; use Zonemaster::LDNS::RR::NSAP; use Zonemaster::LDNS::RR::NSEC; use Zonemaster::LDNS::RR::NSEC3; use Zonemaster::LDNS::RR::NSEC3PARAM; use Zonemaster::LDNS::RR::NULL; use Zonemaster::LDNS::RR::NXT; use Zonemaster::LDNS::RR::PTR; use Zonemaster::LDNS::RR::PX; use Zonemaster::LDNS::RR::RKEY; use Zonemaster::LDNS::RR::RP; use Zonemaster::LDNS::RR::RRSIG; use Zonemaster::LDNS::RR::RT; use Zonemaster::LDNS::RR::SINK; use Zonemaster::LDNS::RR::SOA; use Zonemaster::LDNS::RR::SPF; use Zonemaster::LDNS::RR::SRV; use Zonemaster::LDNS::RR::SSHFP; use Zonemaster::LDNS::RR::TA; use Zonemaster::LDNS::RR::TALINK; use Zonemaster::LDNS::RR::TKEY; use Zonemaster::LDNS::RR::TLSA; use Zonemaster::LDNS::RR::TXT; use Zonemaster::LDNS::RR::TYPE; use Zonemaster::LDNS::RR::UID; use Zonemaster::LDNS::RR::UINFO; use Zonemaster::LDNS::RR::UNSPEC; use Zonemaster::LDNS::RR::URI; use Zonemaster::LDNS::RR::WKS; use Zonemaster::LDNS::RR::X25; use Carp; use overload '<=>' => \&do_compare, 'cmp' => \&do_compare, '""' => \&to_string; sub new { my ( $class, $string ) = @_; if ( $string ) { return $class->new_from_string( $string ); } else { croak "Must provide string to create RR"; } } sub name { my ( $self ) = @_; return $self->owner; } sub do_compare { my ( $self, $other, $swapped ) = @_; return $self->compare( $other ); } sub to_string { my ( $self ) = @_; return $self->string; } 1; =head1 NAME Zonemaster::LDNS::RR - common baseclass for all classes representing resource records. =head1 SYNOPSIS my $rr = Zonemaster::LDNS::RR->new('www.iis.se IN A 91.226.36.46'); =head1 OVERLOADS This class overloads stringify and comparisons ('""', '<=>' and 'cmp'). =head1 CLASS METHOD =over =item new($string) Creates a new RR object of a suitable subclass, given a string representing an RR in common presentation format. =back =head1 INSTANCE METHODS =over =item owner() =item name() These two both return the owner name of the RR. =item ttl() Returns the ttl of the RR. =item type() Return the type of the RR. =item class() Returns the class of the RR. =item string() Returns a string with the RR in presentation format. =item do_compare($other) Calls the XS C<compare> method with the arguments it needs, rather than the ones overloading gives. =item to_string Calls the XS C<string> method with the arguments it needs, rather than the ones overloading gives. Functionally identical to L<string()> from the Perl level, except for being a tiny little bit slower. =item rd_count() The number of RDATA objects in this RR. =item rdf($postion) The raw data of the RDATA object in the given position. The first item is in position 0. If an attempt is made to fetch RDATA from a position that doesn't have any, an exception will be thrown. =back
dotse/net-ldns
lib/Zonemaster/LDNS/RR.pm
Perl
bsd-2-clause
4,279
# # This file is part of MooseX-Types-ElasticSearch # # This software is Copyright (c) 2014 by Moritz Onken. # # This is free software, licensed under: # # The (three-clause) BSD License # package MooseX::Types::ElasticSearch; $MooseX::Types::ElasticSearch::VERSION = '0.0.4'; # ABSTRACT: Useful types for ElasticSearch use DateTime::Format::Epoch::Unix; use DateTime::Format::ISO8601; use Search::Elasticsearch; use MooseX::Types -declare => [ qw( Location QueryType SearchType ES ESDateTime ) ]; use MooseX::Types::Moose qw/Int Str ArrayRef HashRef Object/; coerce ArrayRef, from Str, via { [$_] }; subtype ES, as Object; coerce ES, from Str, via { my $server = $_; $server = "127.0.0.1$server" if ( $server =~ /^:/ ); return Search::Elasticsearch->new( nodes => $server, cxn => "HTTPTiny", ); }; coerce ES, from HashRef, via { return Search::Elasticsearch->new(%$_); }; coerce ES, from ArrayRef, via { my @servers = @$_; @servers = map { /^:/ ? "127.0.0.1$_" : $_ } @servers; return Search::Elasticsearch->new( nodes => \@servers, cxn => "HTTPTiny", ); }; enum QueryType, [qw(query_and_fetch query_then_fetch dfs_query_and_fetch dfs_query_then_fetch scan count)]; subtype SearchType, as QueryType; class_type ESDateTime; coerce ESDateTime, from Str, via { if ( $_ =~ /^\d+$/ ) { DateTime::Format::Epoch::Unix->parse_datetime($_); } else { DateTime::Format::ISO8601->parse_datetime($_); } }; subtype Location, as ArrayRef, where { @$_ == 2 }, message { "Location is an arrayref of longitude and latitude" }; coerce Location, from HashRef, via { [ $_->{lon} || $_->{longitude}, $_->{lat} || $_->{latitude} ] }; coerce Location, from Str, via { [ reverse split(/,/) ] }; 1; __END__ =pod =encoding UTF-8 =head1 NAME MooseX::Types::ElasticSearch - Useful types for ElasticSearch =head1 VERSION version 0.0.4 =head1 SYNOPSIS use MooseX::Types::ElasticSearch qw(:all); =head1 TYPES =head2 ES This type matches against an L<Elasticsearch> instance. It coerces from a C<Str>, C<ArrayRef> and C<HashRef>. If the string contains only the port number (e.g. C<":9200">), then C<127.0.0.1:9200> is assumed. =head2 Location ElasticSearch expects values for geo coordinates (C<geo_point>) as an C<ArrayRef> of longitude and latitude. This type coerces from C<Str> (C<"lat,lon">) and C<HashRef> (C<< { lat => 41.12, lon => -71.34 } >>). =head2 SearchType C<Enum> type. Valid values are: C<query_and_fetch query_then_fetch dfs_query_and_fetch dfs_query_then_fetch scan count>. The now deprecated C<QueryType> is also still available. =head2 ESDateTime ElasticSearch returns dates in the ISO8601 date format. This type coerces from C<Str> to L<DateTime> objects using L<DateTime::Format::ISO8601>. =head1 TODO B<More types> Please don't hesitate and send other useful types in. =head1 AUTHOR Moritz Onken =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2014 by Moritz Onken. This is free software, licensed under: The (three-clause) BSD License =cut
gitpan/MooseX-Types-ElasticSearch
lib/MooseX/Types/ElasticSearch.pm
Perl
bsd-3-clause
3,221
use utf8; package Billy::Schema::Result::Transaction; # Created by DBIx::Class::Schema::Loader # DO NOT MODIFY THE FIRST PART OF THIS FILE =head1 NAME Billy::Schema::Result::Transaction =cut use strict; use warnings; use Moose; use MooseX::NonMoose; use MooseX::MarkAsMethods autoclean => 1; extends 'DBIx::Class::Core'; =head1 COMPONENTS LOADED =over 4 =item * L<DBIx::Class::InflateColumn::DateTime> =back =cut __PACKAGE__->load_components("InflateColumn::DateTime"); =head1 TABLE: C<transaction> =cut __PACKAGE__->table("transaction"); =head1 ACCESSORS =head2 id data_type: 'integer' extra: {unsigned => 1} is_auto_increment: 1 is_nullable: 0 =head2 company_id data_type: 'char' is_foreign_key: 1 is_nullable: 0 size: 10 =head2 date data_type: 'date' datetime_undef_if_invalid: 1 is_nullable: 0 =head2 date_paid data_type: 'date' datetime_undef_if_invalid: 1 is_nullable: 1 =head2 amount data_type: 'integer' extra: {unsigned => 1} is_nullable: 0 =cut __PACKAGE__->add_columns( "id", { data_type => "integer", extra => { unsigned => 1 }, is_auto_increment => 1, is_nullable => 0, }, "company_id", { data_type => "char", is_foreign_key => 1, is_nullable => 0, size => 10 }, "date", { data_type => "date", datetime_undef_if_invalid => 1, is_nullable => 0 }, "date_paid", { data_type => "date", datetime_undef_if_invalid => 1, is_nullable => 1 }, "amount", { data_type => "integer", extra => { unsigned => 1 }, is_nullable => 0 }, ); =head1 PRIMARY KEY =over 4 =item * L</id> =back =cut __PACKAGE__->set_primary_key("id"); =head1 RELATIONS =head2 company Type: belongs_to Related object: L<Billy::Schema::Result::Company> =cut __PACKAGE__->belongs_to( "company", "Billy::Schema::Result::Company", { id => "company_id" }, { is_deferrable => 1, on_delete => "CASCADE", on_update => "CASCADE" }, ); # Created by DBIx::Class::Schema::Loader v0.07046 @ 2017-01-28 00:45:45 # DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:q6fwjFvvd7tpOrffbZhaDQ ## MODEL API ## ----------------------------------------------------------------------------- # Format date and date_paid as YYYY-MM-DD sub date_str { _format_date(shift->date) } sub date_paid_str { _format_date(shift->date_paid) } sub _format_date { my $date = shift; return sprintf("%d-%02d-%02d", $date->year, $date->month, $date->day); } # Kopeks to rubles sub amount_str { my $kop = shift->amount; return sprintf("%.2f", $kop / 100); } __PACKAGE__->meta->make_immutable; 1;
evbogdanov/billy
lib/Billy/Schema/Result/Transaction.pm
Perl
bsd-3-clause
2,568
#!/bin/perl # ====================================================== # Writer : Mico Cheng # Version : 2004080601 # Use for : lookup http access log to delete big size file # Host : x # ====================================================== if ($#ARGV != 1) { print "\n".'usage: pwp-bigsize-kill.pl'." '\x1b[4mpwp-dir\x1b[m'"." '\x1b[4msize(MB)\x1b[m'"."\n"; print "\nexample: pwp-bigsize-kill.pl /emc2_85_s1/home 30\n"; exit; } #-- Begin-- $http_log = "/etc/httpd/logs/access_log"; $pwp_dir = $ARGV[0]; $size *= 1000; open LOG,"$http_log" or die "can't open $http_log:$!\n"; while (<LOG>) { next if ($_ !~ /HTTP\/1.1. 200/); chomp; ($user) = ($_ =~ /GET \/~(.*?)\//); next if !(defined($user)); push @users, $user; } @users=uniq(@users); foreach $user (@users) { $check_dir = $pwp_dir."/".$user; print "checking $check_dir\n"; system "/bin/find $check_dir -size +$size","kb -type f -exec rm -f {} \;"; } #----Function--------- sub uniq { my %hash = map { ($_,0 ) } @_; return keys %hash; }
TonyChengTW/TBCMail
pwp-kill/pwp-bigsize-kill.pl
Perl
apache-2.0
1,070
package Google::Ads::AdWords::v201409::CampaignFeedError::Reason; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType CampaignFeedError.Reason from the namespace https://adwords.google.com/api/adwords/cm/v201409. Error reasons. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/CampaignFeedError/Reason.pm
Perl
apache-2.0
1,102
=head1 AmiGO::Worker::Visualize TODO: Return a blob that visualizes the ontology. TODO: Rationalize visual (so it's just an intelligent web wrapper) and add in QuickGO resource. variables: simple_terms, complex_terms, format, source =cut package AmiGO::Worker::Visualize; ## Use a slightly different base... use base ("AmiGO::Worker"); use AmiGO::KVStore::Filesystem::QuickGO; use AmiGO::KVStore::QuickGO; use AmiGO::External::QuickGO::OntGraphics; =item new Constructor. =cut sub new { ## my $class = shift; my $self = $class->SUPER::new(); my $term_list = shift || []; $self->{AV_TERMS} = undef; # $self->kvetch("FOO: " . $term_list); ## Fix just a string coming in. if( ref $term_list ne 'ARRAY' ){ $term_list = [$term_list]; } ## Double check. if( ! defined($term_list) || scalar(@$term_list) == 0 ){ die "terms must be defined in the term list: $!"; }else{ ## Sort # and create a serialization. $self->{AV_TERMS} = [sort @$term_list]; } # ## Build graph with term list. # ## Go through build graph routine only if there is something coming # ## in. # if( defined($term_list) && # scalar(@$term_list) != 0 ){ # my $graph = GOBO::DBIC::GODBModel::Graph->new(); # ## Convert string terms to DBIC terms. # my $terms = []; # foreach my $acc (@$term_list){ # my $term = $graph->get_term($acc); # if( defined $term ){ # push @$terms, $term; # } # } # } bless $self, $class; return $self; } ## NOTE: Just does one acc at a time. ## Connect to store, if fail, build url, get, and stuff in store. ## Return image blob or undef. sub quickgo { my $self = shift; my $acc = $self->{AV_TERMS}[0]; ## Toggle between SQLite3 and filesystem paths. my $qg = undef; if( 1 ){ $qg = AmiGO::KVStore::Filesystem::QuickGO->new(); }else{ $qg = AmiGO::KVStore::QuickGO->new(); } $self->kvetch("will use backend: $qg"); ## Try images from QuickGO. my $qg_data = $qg->get($acc); if( defined $qg_data ){ $self->kvetch("in cache: $acc"); }else{ $self->kvetch("not in cache: $acc"); ## Looks like it wasn't in the cache; go get it off of the ## internet. my $external_qg = AmiGO::External::QuickGO::OntGraphics->new(); $qg_data = $external_qg->get_graph_image($acc); ## If it looks like we can't get it here either, undef our return ## value and slink out. Otherwise, add to cache. if( ! defined $qg_data ){ $self->kvetch("problem getting img data"); return undef; }else{ $qg->put($acc, $qg_data); } } return $qg_data; } 1;
geneontology/amigo
perl/lib/AmiGO/Worker/Visualize.pm
Perl
bsd-3-clause
2,635
#!/usr/bin/env perl use strict; use warnings; use LWP::UserAgent; use JSON; use Data::Dumper; # initialize json, the user agent and the cdmi url my $json = new JSON; my $ua = LWP::UserAgent->new; my $cdmi_url = "https://www.kbase.us/services/cdmi_api"; # get all subsystem names / ids (which is the same thing) print "retrieving subsystem names...\n"; print "checking for file...\n"; my $subsystems = []; if (-f "ssnames") { open(FH, "<ssnames") or die "error opening existing subsystem names file: $@\n"; my $data; while (<FH>) { chomp; push(@$subsystems, $_); } close FH; print scalar(@$subsystems)." subsystem names loaded.\n"; } else { print "no file, getting from server...\n"; my $get_subsystems = get([ 0, 1000000, ["id"] ], "all_entities", "Subsystem"); @$subsystems = keys(%{$get_subsystems->[0]}); open(FH, ">ssnames") or die "error opening subsystem names file for writing: $@\n"; foreach my $sn (@$subsystems) { print FH "$sn\n"; } close FH; print "received ".scalar(@$subsystems)." names.\n"; } # get the superclass for each subsystem print "retrieving subsystem classifications...\n"; print "checking for file...\n"; my $s2c = {}; if (-f "ssclass") { open(FH, "<ssclass") or die "error opening subsystem classification file: $@\n"; my $count = 0; while (<FH>) { chomp; $count++; my ($k, $v1, $v2) = split /\t/; $k =~ s/_/ /g; $s2c->{$k} = [ $v1, $v2 ]; } close FH; print "loaded $count classifications.\n"; } else { print "no file, getting from server...\n"; my $sub2class = get([ $subsystems, [ "id" ], [], [ "id" ] ], "get_relationship", "IsInClass"); @$sub2class = $sub2class->[0]; # parse the superclass-subsystem mapping data into a hash open(FH, ">ssclass") or die "could not open subsystem class file for writing: $@\n"; my $count = 0; foreach my $item (@$sub2class) { foreach my $subitem (@$item) { $count ++; $s2c->{$subitem->[0]->{id}} = $subitem->[2]->{id}; print FH $subitem->[0]->{id} ."\t". $subitem->[2]->{id} . "\n"; } } close FH; print "received $count classifications.\n";} # get all roles that are in a subsystem print "retrieving roles...\n"; print "checking for file...\n"; my $roles = []; my $role2ssname = {}; if (-f "roles") { open(FH, "<roles") or die "error opening roles file: $@\n"; while (<FH>) { chomp; my ($r, $c) = split /\t/; push(@$roles, $r); $role2ssname->{$r} = $c; } close FH; print scalar(@$roles)." roles loaded.\n"; } else { print "no file, getting from server...\n"; $roles = get([ $subsystems, [ "id" ], [], [ "id" ] ], "get_relationship", "Includes"); $roles = $roles->[0]; foreach my $role (@$roles) { $role2ssname->{$role->[2]->{id}} = $role->[0]->{id}; } @$roles = sort(keys(%$role2ssname)); open(FH, ">roles") or die "could not open roles file for writing: $@\n"; foreach my $r (sort(keys(%$role2ssname))) { print FH $r."\t".$role2ssname->{$r}."\n"; } close FH; print "received ".scalar(@$roles)." roles.\n"; } # purge subsytems variable from memory $subsystems = undef; # create the id2subsystem table print "checking for id2subsystems file...\n"; my $role2ss = {}; if (-f "id2subsystems") { print "found. Loading role to subsystem mapping...\n"; open(FH, "<role2ss") or die "could not open role to subsystems mapping file: $@\n"; while (<FH>) { chomp; my ($k, $v) = split /\t/; $role2ss->{$k} = $v; } close FH; } else { print "not found, calculating...\n"; my $subsystem_table = []; my $count = 1; my $ssid = "SS000000"; my $lastss = $roles->[0]; my $ssids = {}; open(FH, ">role2ss") or die "could not open role to subsystems mapping file: $@\n"; foreach my $role (@$roles) { if ($lastss ne $role) { $count++; $lastss = $role; } my $c1 = "unclassified"; my $c2 = "unclassified"; if ($s2c->{$role2ssname->{$role}} && $s2c->{$role2ssname->{$role}} ne "NULL") { $c1 = $s2c->{$role2ssname->{$role}}; } push(@$subsystem_table, [ $c1, $role2ssname->{$role}, $role, substr($ssid, 0, 7 - length($count)) . $count ]); $ssids->{$role2ssname->{$role}} = substr($ssid, 0, 7 - length($count)) . $count; $role2ss->{$role} = substr($ssid, 0, 7 - length($count)) . $count; print FH $role ."\t". substr($ssid, 0, 7 - length($count)) . $count . "\n"; } close FH; print "done.\nwriting id2subsystems file...\n"; # write the id2subsystem table to a file if (open(FH, ">id2subsystems")) { foreach my $row (@$subsystem_table) { print FH join("\t", @$row)."\n"; } close FH; } else { die "oh noes: $@ $!\n"; } } # purge s2c variable from memory $s2c = undef; print "done.\n"; # build feature to role table print "building role to feature table...\n"; print "checking for file...\n"; my $r2f = {}; unless (-f "r2f") { `touch r2f`; print "no file, creating...\n"; } my $comp_roles = `wc -l r2f`; ($comp_roles) = $comp_roles =~ /(\d+)/; print "existing file contains $comp_roles out of ".scalar(@$roles)." roles.\n"; my $totnum = scalar(@$roles); my $currnum = $comp_roles; if ($comp_roles < $totnum) { print "file incomplete, continuing at role ".($comp_roles + 1).":\n"; my @rolechunk = splice @$roles, $comp_roles; open(FH, ">>r2f") or die "could not open role to function file for appending: $@\n"; foreach my $role (@rolechunk) { $currnum++; print "[ $currnum - $totnum ] ".$role."\n"; if ($role eq "hypothetical protein") { print FH $role."\t\n"; next; } my $features = get([ [ $role ], [ "id" ], [], [ "id" ] ], "get_relationship", "IsFunctionalIn"); $features = $features->[0]; print FH $role."\t".join("\t", map { $_->[2]->{id} } @$features)."\n"; } close FH; } else { print "file complete, loading...\n"; open(FH, "<r2f") or die "could not open role to feature file: $@\n"; my $rnum = 0; my $fnum = 0; while (<FH>) { chomp; my @row = split /\t/; $r2f->{shift @row} = \@row; $rnum++; $fnum += scalar(@row); } close FH; print "loaded $rnum roles with a total of $fnum features.\n"; } # purge the roles variable from memory $roles = undef; # get the organism names print "building organism name list...\n"; print "checking file...\n"; my $organisms = {}; if (-f "organisms") { open(FH, "organisms") or die "could not open organisms file: $@\n"; while (<FH>) { chomp; my ($k, $v) = split /\t/; $organisms->{$k} = $v; } close FH; print scalar(keys(%$organisms)) . " organism names loaded.\n"; } else { print "no file, getting from server...\n"; my $orgs = get([ 0, 1000000, ["id","scientific-name"] ], "all_entities", "Genome"); $orgs = $orgs->[0]; my $orgnames = {}; foreach my $key (keys(%$orgs)) { $orgnames->{$key} = $orgs->{$key}->{scientific_name}; } foreach my $key (keys(%$r2f)) { if (defined($r2f->{$key})) { foreach my $f (@{$r2f->{$key}}) { my ($id) = $f =~ /^(kb\|g\.\d+)/; next unless defined($id); $organisms->{$id} = $orgnames->{$id}; } } } open(FH, ">organisms") or die "could not open organisms file for writing: \n"; foreach my $key (keys(%$organisms)) { print FH $key."\t".$organisms->{$key}."\n"; } close FH; print "received ".scalar(keys(%$organisms))." organism names.\n"; } # build feature per organism list print "building active features per organism list...\n"; print "checking file...\n"; my $org2feature = {}; if (-f "org2feature") { print "found file, loading...\n"; open(FH, "<org2feature") or die "could not open org2feature file: $@\n"; my $ocount = 0; my $fcount = 0; while (<FH>) { chomp; my @row = split /\t/; $org2feature->{shift @row} = \@row; $ocount++; $fcount += scalar(@row); } close FH; print "read $fcount active features in $ocount organisms\n"; } else { print "no file, calculating...\n"; my $org2featureh = {}; foreach my $key (keys(%$organisms)) { $org2featureh->{$key} = {}; $org2feature->{$key} = []; } foreach my $key (keys(%$r2f)) { foreach my $f (@{$r2f->{$key}}) { my ($oid) = $f =~ /^(kb\|g\.\d+)/; next unless defined($oid); $org2featureh->{$oid}->{$f} = 1; } } open(FH, ">org2feature") or die "could not open org2feature file for writing: $@\n"; my $ocount = 0; my $fcount = 0; foreach my $key (keys(%$org2featureh)) { $ocount++; my @fs = keys(%{$org2featureh->{$key}}); $fcount += scalar(@fs); $org2feature->{$key} = \@fs; print FH $key."\t".join("\t",@fs)."\n"; } close FH; print "received $fcount active features in $ocount organisms\n"; } # get the sequences print "building sequence files...\n"; unless (-d "sequences") { `mkdir sequences`; } foreach my $org (keys(%$org2feature)) { my ($oid) = $org =~ /^kb\|g.(\d+)/; next unless defined($oid); unless (-f "sequences/$oid") { print "getting active sequences for ".$organisms->{$org}." ($org)\n"; my $sequences = get([ $org2feature->{$org}, [ "id" ], [], [ "id", "sequence" ] ], "get_relationship", "Produces"); $sequences = $sequences->[0]; open(FH, ">sequences/$oid") or die "could not open sequence file for writing: $@\n"; foreach my $sequence (@$sequences) { print FH $sequence->[0]->{id}."\t".$sequence->[2]->{id}."\t".$sequence->[2]->{sequence}."\n"; } close FH; print "received ".scalar(@$sequences)." sequences.\n"; } } # build md52seq print "checking md5 to sequence file...\n"; if (-f "md52seq") { print "already built.\n"; } else { print "needs to be built. Loading sequences for ".scalar(keys(%$organisms)) ." active genomes:\n"; my $md52seq = {}; my $curr = 1; my $tot = scalar(keys(%$organisms)); foreach my $key (keys(%$organisms)) { next unless $key; my ($num) = $key =~ /^kb\|g\.(\d+)$/; print "[ $curr - $tot ] ".$organisms->{$key}." ($num)\n"; unless (-f "sequences/$num") { print $key." ".$num." ".$organisms->{$key}."\n"; die; } $curr++; open(FH, "<sequences/$num") or die "could not open sequence file $num: $@\n"; while (<FH>) { chomp; my @row = split /\t/; $md52seq->{$row[1]} = $row[2]; } close FH; print scalar(keys(%$md52seq))." distinct sequences in memory\n"; } print "sequences loaded, starting file creation...\n"; open(FH, ">md52seq") or die "could not open md52seq file for writing: $@\n"; foreach my $key (sort(keys(%$md52seq))) { print FH $key."\t".$md52seq->{$key}."\n"; } close FH; print "done.\n"; } # load feature2seq_md5 print "loading feature to sequence id mapping...\n"; my $f2sid = {}; my $curr = 1; my $tot = scalar(keys(%$organisms)); foreach my $key (keys(%$organisms)) { next unless $key; my ($num) = $key =~ /^kb\|g\.(\d+)$/; print "[ $curr - $tot ] ".$organisms->{$key}." ($num)\n"; unless (-f "sequences/$num") { print $key." ".$num." ".$organisms->{$key}."\n"; die; } $curr++; open(FH, "<sequences/$num") or die "could not open sequence file $num: $@\n"; while (<FH>) { chomp; my @row = split /\t/; $f2sid->{$row[0]} = $row[1]; } close FH; print scalar(keys(%$f2sid))." features loaded\n"; } # build md52id2ontology # seq md5 | role ss | feature role | 'Subsystem' print "building md52id2ontology file...\n"; print "checking file...\n"; if (-f "md52id2ontology") { print "already built.\n"; } else { print "no file, building...\n"; open(FH, ">md52id2ontology") or die "could not open md52id2ontology file for writing: $@\n"; my $c = 1; my $t = scalar(keys(%$r2f)); foreach my $role (sort(keys(%$r2f))) { my $rows = {}; foreach my $feature (@{$r2f->{$role}}) { if (defined($feature) && defined($role) && defined($f2sid->{$feature}) && defined($role2ss->{$role})) { $rows->{$f2sid->{$feature}} = [ $f2sid->{$feature}, $role2ss->{$role}, $role, "Subsystem" ]; } else { print "no sequence available - feature: $feature role: $role\n"; } } foreach my $key (sort(keys(%$rows))) { print FH join("\t", @{$rows->{$key}})."\n"; } print "[ $c - $t ]\r"; $c++; } close FH; print "\ndone.\n"; } $f2sid = undef; # build md52id2func2org # seq md5 | feature id | feature role | feature org name | 'SEED' print "building md52id2func2org file...\n"; print "checking file...\n"; if (-f "md52id2func2org") { print "already built.\n"; } else { print "no file, building...\n"; print "calculating feature to role hash\n"; my $f2r = {}; foreach my $role (keys(%$r2f)) { foreach my $feature (@{$r2f->{$role}}) { if (defined($f2r->{$feature})) { push(@{$f2r->{$feature}}, $role); } else { $f2r->{$feature} = [ $role ]; } } } print "done.\n"; print "parsing organism sequence files...\n"; open(FB, ">md52id2func2org") or die "could not open md52id2func2org file for writing: $@\n"; $curr = 1; foreach my $key (keys(%$organisms)) { next unless $key; my ($num) = $key =~ /^kb\|g\.(\d+)$/; print "[ $curr - $tot ] ".$organisms->{$key}." ($num)\n"; unless (-f "sequences/$num") { print $key." ".$num." ".$organisms->{$key}."\n"; die; } $curr++; open(FH, "<sequences/$num") or die "could not open sequence file $num: $@\n"; while (<FH>) { chomp; my @row = split /\t/; my ($o) = $row[0] =~ /^(kb\|g\.\d+)/; foreach my $role (@{$f2r->{$row[0]}}) { print FB $row[1]."\t".$row[0]."\t".$role."\t".$organisms->{$o}."\tSEED\n"; } $f2sid->{$row[0]} = $row[1]; } close FH; print scalar(keys(%$f2sid))." features written\n"; } close FB; } print "done.\n"; print "all done.\nHave a nice day :)\n\n"; 1; # function to get data from the CDMI # setting verbose to true will dump the response to STDERR sub get { my ($params, $entity, $name, $verbose) = @_; my $data = { 'params' => $params, 'method' => "CDMI_EntityAPI.".$entity."_".$name, 'version' => "1.1" }; my $response = $ua->post($cdmi_url, Content => $json->encode($data))->content; eval { $response = $json->decode($response); }; if ($@) { print STDERR $response."\n"; } if ($verbose) { print STDERR Dumper($response)."\n"; } $response = $response->{result}; return $response; }
teharrison/MG-RAST
src/Babel/bin/seed_from_cdmi.pl
Perl
bsd-2-clause
14,321
#!/usr/bin/perl use strict; use warnings; my ( $encname ) = $ARGV[0] =~ m{/([^/.]+).tbl} or die "Cannot parse encoding name out of $ARGV[0]\n"; print <<"EOF"; static const struct StaticTableEncoding encoding_$encname = { { .decode = &decode_table }, { EOF while( <> ) { s/\s*#.*//; # strip comment s{^(\d+)/(\d+)}{sprintf "[0x%02x]", $1*16 + $2}e; # Convert 3/1 to [0x31] s{"(.)"}{sprintf "0x%04x", ord $1}e; # Convert "A" to 0x41 s{U\+}{0x}; # Convert U+0041 to 0x0041 s{$}{,}; # append comma print " $_"; } print <<"EOF"; } }; EOF
ajh/libvterm-rs
vendor/libvterm/tbl2inc_c.pl
Perl
mit
622
#!/usr/bin/perl use strict; use warnings; $ENV{PATH} = "/usr/bin:/bin:/usr/local/bin"; sub get_remote_concurrency { my $cur = `pgrep qmail-remote | wc -l`; $cur=~ s/\s+//g; return $cur; } my $max = `cat /var/qmail/control/concurrencyremote`; chomp $max; my $cur = get_remote_concurrency() or exit 1; exit 0 if $cur + 10 < $max; sleep 60; my $cur2 = get_remote_concurrency() or exit 1; exit 0 if $cur2 + 10 < $max; system 'date +"%a, %Y-%m-%d %H:%M:%S %Z"'; print <<EOT; Qmail remote concurrency is too close to $max! It is $cur2, and was $cur a sleep(60) ago. qmail-remote is wedged with a deadlock on tcpto so bring down qmail-send and start over. I'll bring qmail-send down for you now. # svc -t /var/service/qmail-send EOT exec("svc", "-t", "/var/service/qmail-send");
chtyim/infrastructure-puppet
modules/rootbin_asf/files/bin/check_qmail_concurrency.pl
Perl
apache-2.0
797
#!/usr/bin/perl use Getopt::Long qw(:config pass_through no_ignore_case permute); my $poll_target = undef; my $working_dir = undef; GetOptions('poll-target=s'=> \$poll_target, 'working-dir'=> \$working_dir ) or exit(1); if (defined $working_dir) { chdir($working_dir); } my $cnt = 1; print STDERR "Wait for file: $poll_target\n"; while (1) { if (-e $poll_target){ print STDERR "\n File found!!\n"; last; } else { sleep(10); print STDERR "."; } }
shyamjvs/cs626_project
stat_moses/tools/moses/contrib/mert-sge-nosync/training/sge-nosync/poll-decoder.pl
Perl
apache-2.0
494
package HTTP::Config; use strict; use warnings; use URI; our $VERSION = "6.11"; sub new { my $class = shift; return bless [], $class; } sub entries { my $self = shift; @$self; } sub empty { my $self = shift; not @$self; } sub add { if (@_ == 2) { my $self = shift; push(@$self, shift); return; } my($self, %spec) = @_; push(@$self, \%spec); return; } sub find2 { my($self, %spec) = @_; my @found; my @rest; ITEM: for my $item (@$self) { for my $k (keys %spec) { no warnings 'uninitialized'; if (!exists $item->{$k} || $spec{$k} ne $item->{$k}) { push(@rest, $item); next ITEM; } } push(@found, $item); } return \@found unless wantarray; return \@found, \@rest; } sub find { my $self = shift; my $f = $self->find2(@_); return @$f if wantarray; return $f->[0]; } sub remove { my($self, %spec) = @_; my($removed, $rest) = $self->find2(%spec); @$self = @$rest if @$removed; return @$removed; } my %MATCH = ( m_scheme => sub { my($v, $uri) = @_; return $uri->_scheme eq $v; # URI known to be canonical }, m_secure => sub { my($v, $uri) = @_; my $secure = $uri->can("secure") ? $uri->secure : $uri->_scheme eq "https"; return $secure == !!$v; }, m_host_port => sub { my($v, $uri) = @_; return unless $uri->can("host_port"); return $uri->host_port eq $v, 7; }, m_host => sub { my($v, $uri) = @_; return unless $uri->can("host"); return $uri->host eq $v, 6; }, m_port => sub { my($v, $uri) = @_; return unless $uri->can("port"); return $uri->port eq $v; }, m_domain => sub { my($v, $uri) = @_; return unless $uri->can("host"); my $h = $uri->host; $h = "$h.local" unless $h =~ /\./; $v = ".$v" unless $v =~ /^\./; return length($v), 5 if substr($h, -length($v)) eq $v; return 0; }, m_path => sub { my($v, $uri) = @_; return unless $uri->can("path"); return $uri->path eq $v, 4; }, m_path_prefix => sub { my($v, $uri) = @_; return unless $uri->can("path"); my $path = $uri->path; my $len = length($v); return $len, 3 if $path eq $v; return 0 if length($path) <= $len; $v .= "/" unless $v =~ m,/\z,,; return $len, 3 if substr($path, 0, length($v)) eq $v; return 0; }, m_path_match => sub { my($v, $uri) = @_; return unless $uri->can("path"); return $uri->path =~ $v; }, m_uri__ => sub { my($v, $k, $uri) = @_; return unless $uri->can($k); return 1 unless defined $v; return $uri->$k eq $v; }, m_method => sub { my($v, $uri, $request) = @_; return $request && $request->method eq $v; }, m_proxy => sub { my($v, $uri, $request) = @_; return $request && ($request->{proxy} || "") eq $v; }, m_code => sub { my($v, $uri, $request, $response) = @_; $v =~ s/xx\z//; return unless $response; return length($v), 2 if substr($response->code, 0, length($v)) eq $v; }, m_media_type => sub { # for request too?? my($v, $uri, $request, $response) = @_; return unless $response; return 1, 1 if $v eq "*/*"; my $ct = $response->content_type; return 2, 1 if $v =~ s,/\*\z,, && $ct =~ m,^\Q$v\E/,; return 3, 1 if $v eq "html" && $response->content_is_html; return 4, 1 if $v eq "xhtml" && $response->content_is_xhtml; return 10, 1 if $v eq $ct; return 0; }, m_header__ => sub { my($v, $k, $uri, $request, $response) = @_; return unless $request; return 1 if $request->header($k) eq $v; return 1 if $response && $response->header($k) eq $v; return 0; }, m_response_attr__ => sub { my($v, $k, $uri, $request, $response) = @_; return unless $response; return 1 if !defined($v) && exists $response->{$k}; return 0 unless exists $response->{$k}; return 1 if $response->{$k} eq $v; return 0; }, ); sub matching { my $self = shift; if (@_ == 1) { if ($_[0]->can("request")) { unshift(@_, $_[0]->request); unshift(@_, undef) unless defined $_[0]; } unshift(@_, $_[0]->uri_canonical) if $_[0] && $_[0]->can("uri_canonical"); } my($uri, $request, $response) = @_; $uri = URI->new($uri) unless ref($uri); my @m; ITEM: for my $item (@$self) { my $order; for my $ikey (keys %$item) { my $mkey = $ikey; my $k; $k = $1 if $mkey =~ s/__(.*)/__/; if (my $m = $MATCH{$mkey}) { #print "$ikey $mkey\n"; my($c, $o); my @arg = ( defined($k) ? $k : (), $uri, $request, $response ); my $v = $item->{$ikey}; $v = [$v] unless ref($v) eq "ARRAY"; for (@$v) { ($c, $o) = $m->($_, @arg); #print " - $_ ==> $c $o\n"; last if $c; } next ITEM unless $c; $order->[$o || 0] += $c; } } $order->[7] ||= 0; $item->{_order} = join(".", reverse map sprintf("%03d", $_ || 0), @$order); push(@m, $item); } @m = sort { $b->{_order} cmp $a->{_order} } @m; delete $_->{_order} for @m; return @m if wantarray; return $m[0]; } sub add_item { my $self = shift; my $item = shift; return $self->add(item => $item, @_); } sub remove_items { my $self = shift; return map $_->{item}, $self->remove(@_); } sub matching_items { my $self = shift; return map $_->{item}, $self->matching(@_); } 1; __END__ =head1 NAME HTTP::Config - Configuration for request and response objects =head1 SYNOPSIS use HTTP::Config; my $c = HTTP::Config->new; $c->add(m_domain => ".example.com", m_scheme => "http", verbose => 1); use HTTP::Request; my $request = HTTP::Request->new(GET => "http://www.example.com"); if (my @m = $c->matching($request)) { print "Yadayada\n" if $m[0]->{verbose}; } =head1 DESCRIPTION An C<HTTP::Config> object is a list of entries that can be matched against request or request/response pairs. Its purpose is to hold configuration data that can be looked up given a request or response object. Each configuration entry is a hash. Some keys specify matching to occur against attributes of request/response objects. Other keys can be used to hold user data. The following methods are provided: =over 4 =item $conf = HTTP::Config->new Constructs a new empty C<HTTP::Config> object and returns it. =item $conf->entries Returns the list of entries in the configuration object. In scalar context returns the number of entries. =item $conf->empty Return true if there are no entries in the configuration object. This is just a shorthand for C<< not $conf->entries >>. =item $conf->add( %matchspec, %other ) =item $conf->add( \%entry ) Adds a new entry to the configuration. You can either pass separate key/value pairs or a hash reference. =item $conf->remove( %spec ) Removes (and returns) the entries that have matches for all the key/value pairs in %spec. If %spec is empty this will match all entries; so it will empty the configuation object. =item $conf->matching( $uri, $request, $response ) =item $conf->matching( $uri ) =item $conf->matching( $request ) =item $conf->matching( $response ) Returns the entries that match the given $uri, $request and $response triplet. If called with a single $request object then the $uri is obtained by calling its 'uri_canonical' method. If called with a single $response object, then the request object is obtained by calling its 'request' method; and then the $uri is obtained as if a single $request was provided. The entries are returned with the most specific matches first. In scalar context returns the most specific match or C<undef> in none match. =item $conf->add_item( $item, %matchspec ) =item $conf->remove_items( %spec ) =item $conf->matching_items( $uri, $request, $response ) Wrappers that hides the entries themselves. =back =head2 Matching The following keys on a configuration entry specify matching. For all of these you can provide an array of values instead of a single value. The entry matches if at least one of the values in the array matches. Entries that require match against a response object attribute will never match unless a response object was provided. =over =item m_scheme => $scheme Matches if the URI uses the specified scheme; e.g. "http". =item m_secure => $bool If $bool is TRUE; matches if the URI uses a secure scheme. If $bool is FALSE; matches if the URI does not use a secure scheme. An example of a secure scheme is "https". =item m_host_port => "$hostname:$port" Matches if the URI's host_port method return the specified value. =item m_host => $hostname Matches if the URI's host method returns the specified value. =item m_port => $port Matches if the URI's port method returns the specified value. =item m_domain => ".$domain" Matches if the URI's host method return a value that within the given domain. The hostname "www.example.com" will for instance match the domain ".com". =item m_path => $path Matches if the URI's path method returns the specified value. =item m_path_prefix => $path Matches if the URI's path is the specified path or has the specified path as prefix. =item m_path_match => $Regexp Matches if the regular expression matches the URI's path. Eg. qr/\.html$/. =item m_method => $method Matches if the request method matches the specified value. Eg. "GET" or "POST". =item m_code => $digit =item m_code => $status_code Matches if the response status code matches. If a single digit is specified; matches for all response status codes beginning with that digit. =item m_proxy => $url Matches if the request is to be sent to the given Proxy server. =item m_media_type => "*/*" =item m_media_type => "text/*" =item m_media_type => "html" =item m_media_type => "xhtml" =item m_media_type => "text/html" Matches if the response media type matches. With a value of "html" matches if $response->content_is_html returns TRUE. With a value of "xhtml" matches if $response->content_is_xhtml returns TRUE. =item m_uri__I<$method> => undef Matches if the URI object provides the method. =item m_uri__I<$method> => $string Matches if the URI's $method method returns the given value. =item m_header__I<$field> => $string Matches if either the request or the response have a header $field with the given value. =item m_response_attr__I<$key> => undef =item m_response_attr__I<$key> => $string Matches if the response object has that key, or the entry has the given value. =back =head1 SEE ALSO L<URI>, L<HTTP::Request>, L<HTTP::Response> =head1 COPYRIGHT Copyright 2008, Gisle Aas This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
jkb78/extrajnm
local/lib/perl5/HTTP/Config.pm
Perl
mit
11,432
#!/usr/bin/perl # # Regenerate (overwriting only if changed): # # regnodes.h # # from information stored in # # regcomp.sym # regexp.h # # Accepts the standard regen_lib -q and -v args. # # This script is normally invoked from regen.pl. BEGIN { # Get function prototypes require 'regen_lib.pl'; } #use Fatal qw(open close rename chmod unlink); use strict; use warnings; open DESC, 'regcomp.sym'; my $ind = 0; my (@name,@rest,@type,@code,@args,@longj); my ($desc,$lastregop); while (<DESC>) { s/#.*$//; next if /^\s*$/; s/\s*\z//; if (/^-+\s*$/) { $lastregop= $ind; next; } unless ($lastregop) { $ind++; ($name[$ind], $desc, $rest[$ind]) = split /\t+/, $_, 3; ($type[$ind], $code[$ind], $args[$ind], $longj[$ind]) = split /[,\s]\s*/, $desc, 4; } else { my ($type,@lists)=split /\s*\t+\s*/, $_; die "No list? $type" if !@lists; foreach my $list (@lists) { my ($names,$special)=split /:/, $list , 2; $special ||= ""; foreach my $name (split /,/,$names) { my $real= $name eq 'resume' ? "resume_$type" : "${type}_$name"; my @suffix; if (!$special) { @suffix=(""); } elsif ($special=~/\d/) { @suffix=(1..$special); } elsif ($special eq 'FAIL') { @suffix=("","_fail"); } else { die "unknown :type ':$special'"; } foreach my $suffix (@suffix) { $ind++; $name[$ind]="$real$suffix"; $type[$ind]=$type; $rest[$ind]="state for $type"; } } } } } # use fixed width to keep the diffs between regcomp.pl recompiles # as small as possible. my ($width,$rwidth,$twidth)=(22,12,9); $lastregop ||= $ind; my $tot = $ind; close DESC; die "Too many regexp/state opcodes! Maximum is 256, but there are $lastregop in file!" if $lastregop>256; my $tmp_h = 'regnodes.h-new'; unlink $tmp_h if -f $tmp_h; my $out = safer_open($tmp_h); printf $out <<EOP, /* -*- buffer-read-only: t -*- !!!!!!! DO NOT EDIT THIS FILE !!!!!!! This file is built by regcomp.pl from regcomp.sym. Any changes made here will be lost! */ /* Regops and State definitions */ #define %*s\t%d #define %*s\t%d EOP -$width, REGNODE_MAX => $lastregop - 1, -$width, REGMATCH_STATE_MAX => $tot - 1 ; for ($ind=1; $ind <= $lastregop ; $ind++) { my $oind = $ind - 1; printf $out "#define\t%*s\t%d\t/* %#04x %s */\n", -$width, $name[$ind], $ind-1, $ind-1, $rest[$ind]; } print $out "\t/* ------------ States ------------- */\n"; for ( ; $ind <= $tot ; $ind++) { printf $out "#define\t%*s\t(REGNODE_MAX + %d)\t/* %s */\n", -$width, $name[$ind], $ind - $lastregop, $rest[$ind]; } print $out <<EOP; /* PL_regkind[] What type of regop or state is this. */ #ifndef DOINIT EXTCONST U8 PL_regkind[]; #else EXTCONST U8 PL_regkind[] = { EOP $ind = 0; while (++$ind <= $tot) { printf $out "\t%*s\t/* %*s */\n", -1-$twidth, "$type[$ind],", -$width, $name[$ind]; print $out "\t/* ------------ States ------------- */\n" if $ind == $lastregop and $lastregop != $tot; } print $out <<EOP; }; #endif /* regarglen[] - How large is the argument part of the node (in regnodes) */ #ifdef REG_COMP_C static const U8 regarglen[] = { EOP $ind = 0; while (++$ind <= $lastregop) { my $size = 0; $size = "EXTRA_SIZE(struct regnode_$args[$ind])" if $args[$ind]; printf $out "\t%*s\t/* %*s */\n", -37, "$size,",-$rwidth,$name[$ind]; } print $out <<EOP; }; /* reg_off_by_arg[] - Which argument holds the offset to the next node */ static const char reg_off_by_arg[] = { EOP $ind = 0; while (++$ind <= $lastregop) { my $size = $longj[$ind] || 0; printf $out "\t%d,\t/* %*s */\n", $size, -$rwidth, $name[$ind] } print $out <<EOP; }; #endif /* REG_COMP_C */ /* reg_name[] - Opcode/state names in string form, for debugging */ #ifndef DOINIT EXTCONST char * PL_reg_name[]; #else EXTCONST char * const PL_reg_name[] = { EOP $ind = 0; my $ofs = 1; my $sym = ""; while (++$ind <= $tot) { my $size = $longj[$ind] || 0; printf $out "\t%*s\t/* $sym%#04x */\n", -3-$width,qq("$name[$ind]",), $ind - $ofs; if ($ind == $lastregop and $lastregop != $tot) { print $out "\t/* ------------ States ------------- */\n"; $ofs = $lastregop; $sym = 'REGNODE_MAX +'; } } print $out <<EOP; }; #endif /* DOINIT */ /* PL_reg_extflags_name[] - Opcode/state names in string form, for debugging */ #ifndef DOINIT EXTCONST char * PL_reg_extflags_name[]; #else EXTCONST char * const PL_reg_extflags_name[] = { EOP open my $fh,"<","regexp.h" or die "Can't read regexp.h: $!"; my %rxfv; my $val = 0; my %reverse; while (<$fh>) { if (/#define\s+(RXf_\w+)\s+(0x[A-F\d]+)/i) { my $newval = eval $2; if($val & $newval) { die sprintf "Both $1 and $reverse{$newval} use %08X", $newval; } $val|=$newval; $rxfv{$1}= $newval; $reverse{$newval} = $1; } } my %vrxf=reverse %rxfv; printf $out "\t/* Bits in extflags defined: %032b */\n",$val; for (0..31) { my $n=$vrxf{2**$_}||"UNUSED_BIT_$_"; $n=~s/^RXf_(PMf_)?//; printf $out qq(\t%-20s/* 0x%08x */\n), qq("$n",),2**$_; } print $out <<EOP; }; #endif /* DOINIT */ /* ex: set ro: */ EOP safer_close($out); rename_if_different $tmp_h, 'regnodes.h';
Lh4cKg/sl4a
perl/src/regcomp.pl
Perl
apache-2.0
5,609
# Copyright (C) 2016 and later: Unicode, Inc. and others. # License & terms of use: http://www.unicode.org/copyright.html # *********************************************************************** # * COPYRIGHT: # * Copyright (c) 2004-2006, International Business Machines Corporation # * and others. All Rights Reserved. # *********************************************************************** # # This perl script checks for correct memory function usage in ICU library code. # It works with Linux builds of ICU using clang or gcc. # # To run it, # 1. Build ICU # 2. cd icu/source # 3. perl tools/memcheck/ICUMemCheck.pl # # All object files containing direct references to C or C++ runtime library memory # functions will be listed in the output. # # For ICU 58, the expected output is # common/uniset.o U operator delete(void*) # common/unifilt.o U operator delete(void*) # common/cmemory.o U malloc # common/cmemory.o U free # i18n/strrepl.o U operator delete(void*) # # cmemory.c Expected failures from uprv_malloc, uprv_free implementation. # uniset.cpp Fails because of SymbolTable::~SymbolTable() # unifilt.cpp Fails because of UnicodeMatcher::~UnicodeMatcher() # strrepl.cpp Fails because of UnicodeReplacer::~UnicodeReplacer() # # To verify that no additional problems exist in the .cpp files, #ifdef out the # offending destructors, rebuild icu, and re-run the tool. The problems should # be gone. # # The problem destructors all are for mix-in style interface classes. # These classes can not derive from UObject or UMemory because of multiple-inheritance # problems, so they don't get the ICU memory functions. The delete code # in the destructors will never be called because stand-alone instances of # the classes cannot exist. # $fileNames = `find common i18n io -name "*.o" -print`; foreach $f (split('\n', $fileNames)) { $symbols = `nm -u -C $f`; if ($symbols =~ /U +operator delete\(void\*\)/) { print "$f $&\n"; } if ($symbols =~ /U +operator delete\[\]\(void\*\)/) { print "$f $&\n"; } if ($symbols =~ /U +operator new\(unsigned int\)/) { print "$f $&\n"; } if ($symbols =~ /U +operator new\[\]\(unsigned int\)/) { print "$f $&\n"; } if ($symbols =~ /U +malloc.*/) { print "$f $&\n"; } if ($symbols =~ /(?m:U +free$)/) { print "$f $&\n"; } }
endlessm/chromium-browser
third_party/icu/source/tools/memcheck/ICUMemCheck.pl
Perl
bsd-3-clause
2,473
#!/usr/bin/env perl # # ==================================================================== # Written by Andy Polyakov <appro@openssl.org> for the OpenSSL # project. The module is, however, dual licensed under OpenSSL and # CRYPTOGAMS licenses depending on where you obtain it. For further # details see http://www.openssl.org/~appro/cryptogams/. # ==================================================================== # # May 2011 # # The module implements bn_GF2m_mul_2x2 polynomial multiplication # used in bn_gf2m.c. It's kind of low-hanging mechanical port from # C for the time being... Except that it has two code paths: pure # integer code suitable for any ARMv4 and later CPU and NEON code # suitable for ARMv7. Pure integer 1x1 multiplication subroutine runs # in ~45 cycles on dual-issue core such as Cortex A8, which is ~50% # faster than compiler-generated code. For ECDH and ECDSA verify (but # not for ECDSA sign) it means 25%-45% improvement depending on key # length, more for longer keys. Even though NEON 1x1 multiplication # runs in even less cycles, ~30, improvement is measurable only on # longer keys. One has to optimize code elsewhere to get NEON glow... # # April 2014 # # Double bn_GF2m_mul_2x2 performance by using algorithm from paper # referred below, which improves ECDH and ECDSA verify benchmarks # by 18-40%. # # CΓ’mara, D.; GouvΓͺa, C. P. L.; LΓ³pez, J. & Dahab, R.: Fast Software # Polynomial Multiplication on ARM Processors using the NEON Engine. # # http://conradoplg.cryptoland.net/files/2010/12/mocrysen13.pdf while (($output=shift) && ($output!~/^\w[\w\-]*\.\w+$/)) {} open STDOUT,">$output"; $code=<<___; #include "arm_arch.h" .text .code 32 ___ ################ # private interface to mul_1x1_ialu # $a="r1"; $b="r0"; ($a0,$a1,$a2,$a12,$a4,$a14)= ($hi,$lo,$t0,$t1, $i0,$i1 )=map("r$_",(4..9),12); $mask="r12"; $code.=<<___; .type mul_1x1_ialu,%function .align 5 mul_1x1_ialu: mov $a0,#0 bic $a1,$a,#3<<30 @ a1=a&0x3fffffff str $a0,[sp,#0] @ tab[0]=0 add $a2,$a1,$a1 @ a2=a1<<1 str $a1,[sp,#4] @ tab[1]=a1 eor $a12,$a1,$a2 @ a1^a2 str $a2,[sp,#8] @ tab[2]=a2 mov $a4,$a1,lsl#2 @ a4=a1<<2 str $a12,[sp,#12] @ tab[3]=a1^a2 eor $a14,$a1,$a4 @ a1^a4 str $a4,[sp,#16] @ tab[4]=a4 eor $a0,$a2,$a4 @ a2^a4 str $a14,[sp,#20] @ tab[5]=a1^a4 eor $a12,$a12,$a4 @ a1^a2^a4 str $a0,[sp,#24] @ tab[6]=a2^a4 and $i0,$mask,$b,lsl#2 str $a12,[sp,#28] @ tab[7]=a1^a2^a4 and $i1,$mask,$b,lsr#1 ldr $lo,[sp,$i0] @ tab[b & 0x7] and $i0,$mask,$b,lsr#4 ldr $t1,[sp,$i1] @ tab[b >> 3 & 0x7] and $i1,$mask,$b,lsr#7 ldr $t0,[sp,$i0] @ tab[b >> 6 & 0x7] eor $lo,$lo,$t1,lsl#3 @ stall mov $hi,$t1,lsr#29 ldr $t1,[sp,$i1] @ tab[b >> 9 & 0x7] and $i0,$mask,$b,lsr#10 eor $lo,$lo,$t0,lsl#6 eor $hi,$hi,$t0,lsr#26 ldr $t0,[sp,$i0] @ tab[b >> 12 & 0x7] and $i1,$mask,$b,lsr#13 eor $lo,$lo,$t1,lsl#9 eor $hi,$hi,$t1,lsr#23 ldr $t1,[sp,$i1] @ tab[b >> 15 & 0x7] and $i0,$mask,$b,lsr#16 eor $lo,$lo,$t0,lsl#12 eor $hi,$hi,$t0,lsr#20 ldr $t0,[sp,$i0] @ tab[b >> 18 & 0x7] and $i1,$mask,$b,lsr#19 eor $lo,$lo,$t1,lsl#15 eor $hi,$hi,$t1,lsr#17 ldr $t1,[sp,$i1] @ tab[b >> 21 & 0x7] and $i0,$mask,$b,lsr#22 eor $lo,$lo,$t0,lsl#18 eor $hi,$hi,$t0,lsr#14 ldr $t0,[sp,$i0] @ tab[b >> 24 & 0x7] and $i1,$mask,$b,lsr#25 eor $lo,$lo,$t1,lsl#21 eor $hi,$hi,$t1,lsr#11 ldr $t1,[sp,$i1] @ tab[b >> 27 & 0x7] tst $a,#1<<30 and $i0,$mask,$b,lsr#28 eor $lo,$lo,$t0,lsl#24 eor $hi,$hi,$t0,lsr#8 ldr $t0,[sp,$i0] @ tab[b >> 30 ] eorne $lo,$lo,$b,lsl#30 eorne $hi,$hi,$b,lsr#2 tst $a,#1<<31 eor $lo,$lo,$t1,lsl#27 eor $hi,$hi,$t1,lsr#5 eorne $lo,$lo,$b,lsl#31 eorne $hi,$hi,$b,lsr#1 eor $lo,$lo,$t0,lsl#30 eor $hi,$hi,$t0,lsr#2 mov pc,lr .size mul_1x1_ialu,.-mul_1x1_ialu ___ ################ # void bn_GF2m_mul_2x2(BN_ULONG *r, # BN_ULONG a1,BN_ULONG a0, # BN_ULONG b1,BN_ULONG b0); # r[3..0]=a1a0Β·b1b0 { $code.=<<___; .global bn_GF2m_mul_2x2 .type bn_GF2m_mul_2x2,%function .align 5 bn_GF2m_mul_2x2: #if __ARM_MAX_ARCH__>=7 ldr r12,.LOPENSSL_armcap .Lpic: ldr r12,[pc,r12] tst r12,#1 bne .LNEON #endif ___ $ret="r10"; # reassigned 1st argument $code.=<<___; stmdb sp!,{r4-r10,lr} mov $ret,r0 @ reassign 1st argument mov $b,r3 @ $b=b1 ldr r3,[sp,#32] @ load b0 mov $mask,#7<<2 sub sp,sp,#32 @ allocate tab[8] bl mul_1x1_ialu @ a1Β·b1 str $lo,[$ret,#8] str $hi,[$ret,#12] eor $b,$b,r3 @ flip b0 and b1 eor $a,$a,r2 @ flip a0 and a1 eor r3,r3,$b eor r2,r2,$a eor $b,$b,r3 eor $a,$a,r2 bl mul_1x1_ialu @ a0Β·b0 str $lo,[$ret] str $hi,[$ret,#4] eor $a,$a,r2 eor $b,$b,r3 bl mul_1x1_ialu @ (a1+a0)Β·(b1+b0) ___ @r=map("r$_",(6..9)); $code.=<<___; ldmia $ret,{@r[0]-@r[3]} eor $lo,$lo,$hi eor $hi,$hi,@r[1] eor $lo,$lo,@r[0] eor $hi,$hi,@r[2] eor $lo,$lo,@r[3] eor $hi,$hi,@r[3] str $hi,[$ret,#8] eor $lo,$lo,$hi add sp,sp,#32 @ destroy tab[8] str $lo,[$ret,#4] #if __ARM_ARCH__>=5 ldmia sp!,{r4-r10,pc} #else ldmia sp!,{r4-r10,lr} tst lr,#1 moveq pc,lr @ be binary compatible with V4, yet bx lr @ interoperable with Thumb ISA:-) #endif ___ } { my ($r,$t0,$t1,$t2,$t3)=map("q$_",(0..3,8..12)); my ($a,$b,$k48,$k32,$k16)=map("d$_",(26..31)); $code.=<<___; #if __ARM_MAX_ARCH__>=7 .arch armv7-a .fpu neon .align 5 .LNEON: ldr r12, [sp] @ 5th argument vmov.32 $a, r2, r1 vmov.32 $b, r12, r3 vmov.i64 $k48, #0x0000ffffffffffff vmov.i64 $k32, #0x00000000ffffffff vmov.i64 $k16, #0x000000000000ffff vext.8 $t0#lo, $a, $a, #1 @ A1 vmull.p8 $t0, $t0#lo, $b @ F = A1*B vext.8 $r#lo, $b, $b, #1 @ B1 vmull.p8 $r, $a, $r#lo @ E = A*B1 vext.8 $t1#lo, $a, $a, #2 @ A2 vmull.p8 $t1, $t1#lo, $b @ H = A2*B vext.8 $t3#lo, $b, $b, #2 @ B2 vmull.p8 $t3, $a, $t3#lo @ G = A*B2 vext.8 $t2#lo, $a, $a, #3 @ A3 veor $t0, $t0, $r @ L = E + F vmull.p8 $t2, $t2#lo, $b @ J = A3*B vext.8 $r#lo, $b, $b, #3 @ B3 veor $t1, $t1, $t3 @ M = G + H vmull.p8 $r, $a, $r#lo @ I = A*B3 veor $t0#lo, $t0#lo, $t0#hi @ t0 = (L) (P0 + P1) << 8 vand $t0#hi, $t0#hi, $k48 vext.8 $t3#lo, $b, $b, #4 @ B4 veor $t1#lo, $t1#lo, $t1#hi @ t1 = (M) (P2 + P3) << 16 vand $t1#hi, $t1#hi, $k32 vmull.p8 $t3, $a, $t3#lo @ K = A*B4 veor $t2, $t2, $r @ N = I + J veor $t0#lo, $t0#lo, $t0#hi veor $t1#lo, $t1#lo, $t1#hi veor $t2#lo, $t2#lo, $t2#hi @ t2 = (N) (P4 + P5) << 24 vand $t2#hi, $t2#hi, $k16 vext.8 $t0, $t0, $t0, #15 veor $t3#lo, $t3#lo, $t3#hi @ t3 = (K) (P6 + P7) << 32 vmov.i64 $t3#hi, #0 vext.8 $t1, $t1, $t1, #14 veor $t2#lo, $t2#lo, $t2#hi vmull.p8 $r, $a, $b @ D = A*B vext.8 $t3, $t3, $t3, #12 vext.8 $t2, $t2, $t2, #13 veor $t0, $t0, $t1 veor $t2, $t2, $t3 veor $r, $r, $t0 veor $r, $r, $t2 vst1.32 {$r}, [r0] ret @ bx lr #endif ___ } $code.=<<___; .size bn_GF2m_mul_2x2,.-bn_GF2m_mul_2x2 #if __ARM_MAX_ARCH__>=7 .align 5 .LOPENSSL_armcap: .word OPENSSL_armcap_P-(.Lpic+8) #endif .asciz "GF(2^m) Multiplication for ARMv4/NEON, CRYPTOGAMS by <appro\@openssl.org>" .align 5 #if __ARM_MAX_ARCH__>=7 .comm OPENSSL_armcap_P,4,4 #endif ___ foreach (split("\n",$code)) { s/\`([^\`]*)\`/eval $1/geo; s/\bq([0-9]+)#(lo|hi)/sprintf "d%d",2*$1+($2 eq "hi")/geo or s/\bret\b/bx lr/go or s/\bbx\s+lr\b/.word\t0xe12fff1e/go; # make it possible to compile with -march=armv4 print $_,"\n"; } close STDOUT; # enforce flush
srajko/nodegit
vendor/openssl/openssl/crypto/bn/asm/armv4-gf2m.pl
Perl
mit
7,341
#!/usr/bin/perl use Getopt::Long; use CGI qw/param/; my $HOME = "/Users/peng"; my $in_text = param ('in_text'); my $out_pdf = param ('out_pdf'); my $result = qx{$HOME/anaconda/bin/python $HOME/MIT-BroadFoundry/dnaplotlib/quick.py -input '$in_text' -output ../results/$out_pdf};
VoigtLab/dnaplotlib
other/web/cgi-bin/run_quick.pl
Perl
mit
285
use MooseX::Declare; =head2 PURPOSE Run tasks on worker nodes using task queue Use queues to communicate between master and nodes: WORKERS: REPORT STATUS TO MASTER MASTER: DIRECT WORKERS TO: - DEPLOY APPS - PROVIDE WORKFLOW STATUS - STOP/START WORKFLOWS =cut use strict; use warnings; class Queue::Listener with (Logger, Exchange, Agua::Common::Database, Agua::Common::Timer, Agua::Common::Project, Agua::Common::Stage, Agua::Common::Workflow, Agua::Common::Util) { #####////}}}}} { # Integers has 'log' => ( isa => 'Int', is => 'rw', default => 2 ); has 'printlog' => ( isa => 'Int', is => 'rw', default => 5 ); has 'maxjobs' => ( isa => 'Int', is => 'rw', default => 1 ); has 'sleep' => ( isa => 'Int', is => 'rw', default => 2 ); # Strings has 'metric' => ( isa => 'Str|Undef', is => 'rw', default => "cpus" ); has 'user' => ( isa => 'Str|Undef', is => 'rw', required => 0 ); has 'pass' => ( isa => 'Str|Undef', is => 'rw', required => 0 ); has 'host' => ( isa => 'Str|Undef', is => 'rw', required => 0 ); has 'vhost' => ( isa => 'Str|Undef', is => 'rw', required => 0 ); has 'modulestring' => ( isa => 'Str|Undef', is => 'rw', default => "Agua::Workflow" ); has 'rabbitmqctl' => ( isa => 'Str|Undef', is => 'rw', default => "/usr/sbin/rabbitmqctl" ); # Objects has 'modules' => ( isa => 'ArrayRef|Undef', is => 'rw', lazy => 1, builder => "setModules"); has 'conf' => ( isa => 'Conf::Yaml', is => 'rw', required => 0 ); has 'synapse' => ( isa => 'Synapse', is => 'rw', lazy => 1, builder => "setSynapse" ); has 'db' => ( isa => 'Agua::DBase::MySQL', is => 'rw', lazy => 1, builder => "setDbh" ); has 'jsonparser'=> ( isa => 'JSON', is => 'rw', lazy => 1, builder => "setJsonParser" ); has 'virtual' => ( isa => 'Any', is => 'rw', lazy => 1, builder => "setVirtual" ); has 'duplicate' => ( isa => 'HashRef|Undef', is => 'rw'); } #### EXTERNAL MODULES use FindBin qw($Bin); use Test::More; #### INTERNAL MODULES use Virtual::Openstack; use Synapse; use Time::Local; use Virtual; #####////}}}}} method BUILD ($args) { $self->initialise($args); } method initialise ($args) { #$self->logDebug("args", $args); #$self->manage(); } #### LISTEN method listen { $self->logDebug(""); my $taskqueues = ["update.job.status", "update.host.status"]; $self->receiveTask($taskqueues); } #### TOPICS method sendTopic ($data, $key) { $self->logDebug("data", $data); $self->logDebug("key", $key); my $exchange = $self->conf()->getKey("queue:topicexchange", undef); $self->logDebug("exchange", $exchange); my $host = $self->host() || $self->conf()->getKey("queue:host", undef); my $user = $self->user() || $self->conf()->getKey("queue:user", undef); my $pass = $self->pass() || $self->conf()->getKey("queue:pass", undef); my $vhost = $self->vhost() || $self->conf()->getKey("queue:vhost", undef); $self->logNote("host", $host); $self->logNote("user", $user); $self->logNote("pass", $pass); $self->logNote("vhost", $vhost); my $connection = Net::RabbitFoot->new()->load_xml_spec()->connect( host => $host, port => 5672, user => $user, pass => $pass, vhost => $vhost, ); $self->logNote("connection: $connection"); $self->logNote("DOING connection->open_channel"); my $channel = $connection->open_channel(); $self->channel($channel); $self->logNote("DOING channel->declare_exchange"); $channel->declare_exchange( exchange => $exchange, type => 'topic', ); my $json = $self->jsonparser()->encode($data); $self->logDebug("json", $json); $self->channel()->publish( exchange => $exchange, routing_key => $key, body => $json, ); print "[x] Sent topic with key '$key'\n"; $connection->close(); } method receiveTopic { $self->logDebug(""); #### OPEN CONNECTION my $connection = $self->newConnection(); my $channel = $connection->open_channel(); my $exchange = $self->conf()->getKey("queue:topicexchange", undef); $self->logDebug("exchange", $exchange); $channel->declare_exchange( exchange => $exchange, type => 'topic', ); my $result = $channel->declare_queue(exclusive => 1); my $queuename = $result->{method_frame}->{queue}; my $keystring = $self->conf()->getKey("queue:topickeys", undef); $self->logDebug("keystring", $keystring); my $keys; @$keys = split ",", $keystring; $self->logDebug("exchange", $exchange); for my $key ( @$keys ) { $channel->bind_queue( exchange => $exchange, queue => $queuename, routing_key => $key, ); } print " [*] Listening for topics: @$keys\n"; no warnings; my $handler = *handleTopic; use warnings; my $this = $self; $channel->consume( on_consume => sub { my $var = shift; my $body = $var->{body}->{payload}; my $excerpt = substr($body, 0, 200); #print " [x] Received message: $excerpt\n"; &$handler($this, $body); }, no_ack => 1, ); # Wait forever AnyEvent->condvar->recv; } method handleTopic ($json) { #$self->logDebug("json", substr($json, 0, 200)); my $data = $self->jsonparser()->decode($json); #$self->logDebug("data", $data); my $duplicate = $self->duplicate(); if ( defined $duplicate and not $self->deeplyIdentical($data, $duplicate) ) { #$self->logDebug("Skipping duplicate message"); return; } else { $self->duplicate($data); } my $mode = $data->{mode} || ""; #$self->logDebug("mode", $mode); if ( $self->can($mode) ) { $self->$mode($data); } else { print "mode not supported: $mode\n"; $self->logDebug("mode not supported: $mode"); } } #### TASKS method receiveTask ($taskqueues) { #$self->logDebug("taskqueues", $taskqueues); #### OPEN CONNECTION my $connection = $self->newConnection(); my $channel = $connection->open_channel(); foreach my $taskqueue ( @$taskqueues ) { #$self->logDebug("taskqueue", $taskqueue); #$self->channel($channel); $channel->declare_queue( queue => $taskqueue, durable => 1, ); #### GET HOST my $host = $self->conf()->getKey("queue:host", undef); print "[*] Waiting for tasks in host $host taskqueue '$taskqueue'\n"; $channel->qos(prefetch_count => 1,); no warnings; my $handler = *handleTask; use warnings; my $this = $self; $channel->consume( on_consume => sub { my $var = shift; #print "Listener::receiveTask DOING CALLBACK"; my $body = $var->{body}->{payload}; print " [x] Received task in host $host taskqueue '$taskqueue'\n"; #print "body: $body\n"; my @c = $body =~ /\./g; #### RUN TASK &$handler($this, $body); my $sleep = $self->sleep(); #print "Sleeping $sleep seconds\n"; sleep($sleep); #### SEND ACK AFTER TASK COMPLETED #print "Listener::receiveTask sending ack\n"; $channel->ack(); }, no_ack => 0, ); } #### SET self->connection $self->connection($connection); # Wait forever AnyEvent->condvar->recv; } method handleTask ($json) { #$self->logDebug("json", substr($json, 0, 200)); my $data = $self->jsonparser()->decode($json); #$self->logDebug("data", $data); #my $duplicate = $self->duplicate(); #if ( defined $duplicate and not $self->deeplyIdentical($data, $duplicate) ) { # $self->logDebug("Skipping duplicate message"); # return; #} #else { # $self->duplicate($data); #} my $mode = $data->{mode} || ""; #$self->logDebug("mode", $mode); if ( $self->can($mode) ) { $self->$mode($data); } else { print "mode not supported: $mode\n"; $self->logDebug("mode not supported: $mode"); } } method sendTask ($task) { $self->logDebug("task", $task); my $processid = $$; $self->logDebug("processid", $processid); $task->{processid} = $processid; #### SET QUEUE my $queuename = $self->setQueueName($task); $task->{queue} = $queuename; $self->logDebug("queuename", $queuename); #### ADD UNIQUE IDENTIFIERS $task = $self->addTaskIdentifiers($task); my $jsonparser = JSON->new(); my $json = $jsonparser->encode($task); $self->logDebug("json", $json); #### GET CONNECTION my $connection = $self->newConnection(); $self->logDebug("DOING connection->open_channel()"); my $channel = $connection->open_channel(); $self->channel($channel); #$self->logDebug("channel", $channel); $channel->declare_queue( queue => $queuename, durable => 1, ); #### BIND QUEUE TO EXCHANGE $channel->publish( exchange => '', routing_key => $queuename, body => $json, ); #### GET HOST my $host = $self->conf()->getKey("queue:host", undef); print " [x] Sent TASK in host $host taskqueue '$queuename': '$json'\n"; } method addTaskIdentifiers ($task) { #### SET TOKEN $task->{token} = $self->token(); #### SET SENDTYPE $task->{sendtype} = "task"; #### SET DATABASE $task->{database} = $self->db()->database() || ""; #### SET SOURCE ID $task->{sourceid} = $self->sourceid(); #### SET CALLBACK $task->{callback} = $self->callback(); $self->logDebug("Returning task", $task); return $task; } method setQueueName ($task) { #### VERIFY VALUES my $notdefined = $self->notDefined($task, ["username", "project", "workflow"]); $self->logCritical("not defined", $notdefined) and return if @$notdefined; my $username = $task->{username}; my $project = $task->{project}; my $workflow = $task->{workflow}; my $queue = "$username.$project.$workflow"; #$self->logDebug("queue", $queue); return $queue; } method notDefined ($hash, $fields) { return [] if not defined $hash or not defined $fields or not @$fields; my $notDefined = []; for ( my $i = 0; $i < @$fields; $i++ ) { push( @$notDefined, $$fields[$i]) if not defined $$hash{$$fields[$i]}; } return $notDefined; } #### UPDATE method updateJobStatus ($data) { $self->logNote("data", $data); $self->logDebug("data not defined") and return if not defined $data; $self->logDebug("sample not defined") and return if not defined $data->{sample}; $self->logDebug("$data->{host} $data->{sample} $data->{status}"); #### UPDATE queuesamples TABLE $self->updateQueueSample($data); #### UPDATE provenance TABLE $self->updateProvenance($data); } method updateHeartbeat ($data) { $self->logDebug("host $data->{host} $data->{ipaddress} [$data->{time}]"); #$self->logDebug("data", $data); my $keys = [ "host", "time" ]; my $notdefined = $self->notDefined($data, $keys); $self->logDebug("notdefined", $notdefined) and return if @$notdefined; #### ADD TO TABLE my $table = "heartbeat"; my $fields = $self->db()->fields($table); $self->_addToTable($table, $data, $keys, $fields); } method updateProvenance ($data) { #$self->logDebug("$data->{sample} $data->{status} $data->{time}"); my $keys = [ "username", "project", "workflow", "workflownumber", "sample" ]; my $notdefined = $self->notDefined($data, $keys); $self->logDebug("notdefined", $notdefined) and return if @$notdefined; #### ADD TO provenance TABLE my $table = "provenance"; my $fields = $self->db()->fields($table); my $success = $self->_addToTable($table, $data, $keys, $fields); #$self->logDebug("addToTable 'provenance' success", $success); } method updateQueueSample ($data) { #$self->logDebug("data", $data); #$self->logDebug("$data->{sample} $data->{status} $data->{time}"); #### UPDATE queuesample TABLE my $table = "queuesample"; my $keys = [ "sample" ]; $self->_removeFromTable($table, $data, $keys); $keys = ["username", "project", "workflow", "workflownumber", "sample", "status" ]; $self->_addToTable($table, $data, $keys); } #### DELETE method deleteInstance ($data) { #$self->logDebug("data", $data); my $host = $data->{host}; $self->logDebug("host", $host); my $username = $self->getUsernameFromInstance($host); $self->logDebug("username", $username); my $authfile = $self->printAuth($username); $self->logDebug("authfile", $authfile); my $success = $self->virtual()->deleteNode($authfile, $host); $self->logDebug("success", $success); $self->updateInstanceStatus($host, "deleted"); return $success; } method getTenant ($username) { my $query = qq{SELECT * FROM tenant WHERE username='$username'}; #$self->logDebug("query", $query); return $self->db()->queryhash($query); } method getAuthFile ($username, $tenant) { #$self->logDebug("username", $username); my $installdir = $self->conf()->getKey("agua", "INSTALLDIR"); my $targetdir = "$installdir/conf/.openstack"; `mkdir -p $targetdir` if not -d $targetdir; my $tenantname = $tenant->{os_tenant_name}; #$self->logDebug("tenantname", $tenantname); my $authfile = "$targetdir/$tenantname-openrc.sh"; #$self->logDebug("authfile", $authfile); return $authfile; } method getUsernameFromInstance ($host) { $self->logDebug("host", $host); my $query = qq{SELECT queue FROM instance WHERE LOWER(host) LIKE LOWER('$host') }; $self->logDebug("query", $query); my $queue = $self->db()->query($query); #$self->logDebug("queue", $queue); my ($username) = $queue =~ /^([^\.]+)\./; #$self->logDebug("username", $username); return $username; } method printAuth ($username) { #$self->logDebug("username", $username); #### SET TEMPLATE FILE my $installdir = $self->conf()->getKey("agua", "INSTALLDIR"); my $templatefile = "$installdir/bin/install/resources/openstack/openrc.sh"; #### GET OPENSTACK AUTH INFO my $tenant = $self->getTenant($username); #$self->logDebug("tenant", $tenant); #### GET AUTH FILE my $authfile = $self->getAuthFile($username, $tenant); #### PRINT FILE return $self->virtual()->printAuthFile($tenant, $templatefile, $authfile); } method updateInstanceStatus ($host, $status) { $self->logNote("host", $host); $self->logNote("status", $status); my $time = $self->getMysqlTime(); my $query = qq{UPDATE instance SET status='$status', TIME='$time' WHERE host='$host' }; $self->logDebug("query", $query); return $self->db()->do($query); } #### UTILS method exited ($nodename) { my $entries = $self->virtual()->getEntries($nodename); foreach my $entry ( @$entries ) { my $internalip = $entry->{internalip}; $self->logDebug("internalip", $internalip); my $status = $self->workflowStatus($internalip); if ( $status =~ /Done, exiting/ ) { my $id = $entry->{id}; $self->logDebug("DOING novaDelete($id)"); $self->virtual()->novaDelete($id); } } } method runCommand ($command) { $self->logDebug("command", $command); return `$command`; } method setJsonParser { return JSON->new->allow_nonref; } method setVirtual { my $virtualtype = $self->conf()->getKey("agua", "VIRTUALTYPE"); $self->logDebug("virtualtype", $virtualtype); #### RETURN IF TYPE NOT SUPPORTED $self->logDebug("virtual virtualtype not supported: $virtualtype") and return if $virtualtype !~ /^(openstack|vagrant)$/; #### CREATE DB OBJECT USING DBASE FACTORY my $virtual = Virtual->new( $virtualtype, { conf => $self->conf(), username => $self->username(), logfile => $self->logfile(), log => $self->log(), printlog => $self->printlog() } ) or die "Can't create virtual of type: $virtualtype. $!\n"; $self->logDebug("virtual: $virtual"); $self->virtual($virtual); } }
aguadev/aguadev
lib/Queue/Listener.pm
Perl
mit
15,200
#!/usr/bin/perl print "Content-type: text/html\n\n"; ($User,$Planet,$AuthCode,$TCount,$Mode,$InType)=split(/&/,$ENV{QUERY_STRING}); $user_information = "/home/admin/classic/se/User Information"; dbmopen(%authcode, "$user_information/accesscode", 0777); if(($AuthCode ne $authcode{$User}) || ($AuthCode eq "")){ print "<SCRIPT>alert(\"Security Failure. Please notify the GSD team immediately.\");history.back();</SCRIPT>"; die; } dbmclose(%authcode); $Font = qq!<font face=verdana size=-1>!; $Font2 = qq!<font face=verdana size=-2>!; $Back2 = qq!bgcolor="#666666"!; $Back = qq!bgcolor="#333333"!; $InType2 = $InType; $InType2 =~ tr/_/ /; $Path = "/home/shatteredempires/SENN"; if ($Mode == 2) { &ParseData; open (OUT, ">$Path/$User$InType"); print OUT "$User|$TCount|$InType\n"; print OUT "$data{'Information'}\n"; close (OUT); print qq!<script>window.close();</script>!; } else { $InType =~ tr/_/ /; print qq! <html> <title>SENN - Request for Information: $InType </title> <body bgcolor=black text=white>$Font <form method=post action="http://www.bluewand.com/cgi-bin/classic/SENNRequest.pl?$User&$Planet&$AuthCode&$TCount&2&$InType"> <font face=verdana size=-1> <table border=1 width=100% cellspacing=0 cellpadding=0 $Back> <TR><TD>$Font Incident:</TD><TD $Back2>$Font $InType2</TD></TR> <TR><TD>$Font Nation of Origin:</TD><TD $Back2>$Font $User</TD></TR> <TR><TD>$Font Target Nation:</TD><TD $Back2>$Font $TCount</TD></TR> <TR><TD colspan=2 $Back2>$Font2 SENN is requesting information pertaining to the following event: $InType2<BR> If you wish to comment on the actions of your nation, please enter it below. If you do not wish to comment, close the window.<BR> Please note, SENN is a part of Shattered EmpiresΒ©, and remarks deemed offensive will be acted upon.</TD></TR> <TR><TD colspan=2><center><textarea name="Information" wrap=virtual cols=40 rows=7></textarea></TD></TR> </table> <Center><input type=submit name=submit value="Submit Information"></center></form> </body>!; } sub ParseData { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg; $value =~ s/<!--(.|\n)*-->//g; $value =~ s/<([^>]|\n)*>//g; $data{$name} = $value; } }
cpraught/shattered-empires
SENNRequest.pl
Perl
mit
2,375
#! /usr/bin/perl -w # # See bottom of file for license and copyright information use strict; use warnings; use Cwd 'getcwd'; BEGIN { my $here = Cwd::abs_path; my $root = $here; push @INC, "$root/lib"; } eval "use CSS::Minifier"; if ($@) { print STDOUT $@; die; } sub minifyFile { my ($inSourceDir, $inSourceFile, $inOutputDir) = @_; my $inputFile = "$inSourceDir$inSourceFile"; my $outputFile = "$inOutputDir$inSourceFile"; $outputFile =~ s/^(.*?)(\.css)$/$1.min$2/; open(INFILE, $inputFile) or die; open(OUTFILE, '>' . $outputFile) or die; CSS::Minifier::minify(input => *INFILE, outfile => *OUTFILE); close(INFILE); close(OUTFILE); } my $SOURCE_DIR = '../templates/css_src/'; my $OUTPUT_DIR = '../templates/css/'; minifyFile($SOURCE_DIR, 'VisDoc.css', $OUTPUT_DIR); minifyFile($SOURCE_DIR, 'shCoreDefault.css', $OUTPUT_DIR); # VisDoc - Code documentation generator, http://visdoc.org # This software is licensed under the MIT License # # The MIT License # # Copyright (c) 2010 Arthur Clemens, VisDoc contributors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE.
ArthurClemens/VisDoc
code/perl/tools/minify_css.pl
Perl
mit
2,115
#!/usr/bin/env perl # SPDX-FileCopyrightText: 2021 Pragmatic Software <pragma78@gmail.com> # SPDX-License-Identifier: MIT use warnings; use strict; package Languages::python3; use parent 'Languages::_default'; sub initialize { my ($self, %conf) = @_; $self->{sourcefile} = 'prog.py3'; $self->{execfile} = 'prog.py3'; $self->{default_options} = ''; $self->{cmdline} = 'python3 $options $sourcefile'; $self->{cmdline_opening_comment} = "'''\n=============== CMDLINE ===============\n"; $self->{cmdline_closing_comment} = "=============== CMDLINE ===============\n'''\n"; $self->{output_opening_comment} = "'''\n=============== OUTPUT ===============\n"; $self->{output_closing_comment} = "=============== OUTPUT ===============\n'''\n"; } 1;
pragma-/pbot
applets/pbot-vm/host/lib/Languages/python3.pm
Perl
mit
786
package Dancer::Session::Simple; use strict; use warnings; use base 'Dancer::Session::Abstract'; my %sessions; # create a new session and return the newborn object # representing that session sub create { my ($class) = @_; my $self = Dancer::Session::Simple->new; $self->flush; return $self; } # Return the session object corresponding to the given id sub retrieve { my ($class, $id) = @_; return $sessions{$id}; } sub destroy { my ($self) = @_; undef $sessions{$self->id}; } sub flush { my $self = shift; $sessions{$self->id} = $self; return $self; } 1; __END__ =pod =head1 NAME Dancer::Session::Simple - in-memory session backend for Dancer =head1 DESCRIPTION This module implements a very simple session backend, holding all session data in memory. This means that sessions are volatile, and no longer exist when the process exits. This module is likely to be most useful for testing purposes. =head1 CONFIGURATION The setting B<session> should be set to C<Simple> in order to use this session engine in a Dancer application. =head1 AUTHOR This module has been written by David Precious, see the AUTHORS file for details. =head1 SEE ALSO See L<Dancer::Session> for details about session usage in route handlers. =head1 COPYRIGHT This module is copyright (c) 2010 David Precious <davidp@preshweb.co.uk> =head1 LICENSE This module is free software and is released under the same terms as Perl itself. =cut
dimpu/AravindCom
api/perl/MAP/Modules/Dancer-1.3124/lib/Dancer/Session/Simple.pm
Perl
mit
1,481
###################################################################### # # This is the first cos_list page to take advantage of the new # SGN database. It offers reduced functionality from its # predecessor because much of this functionality is now of # increased complexity and is folded into the individual EST # and unigene pages. So instead this page just links to them. # ###################################################################### use strict; use CXGN::Page; use CXGN::DB::Connection; # Set static values. my $at_page='http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&amp;db=Nucleotide&amp;dopt=GenBank&amp;list_uids='; my $map_link='/search/markers/markerinfo.pl?marker_id='; my $est_read_page='/search/est.pl?request_from=0&amp;request_type=automatic&amp;search=Search&amp;request_id='; my $cos_page='/search/markers/markerinfo.pl?marker_id='; # Create a new SGN webpage. our $page = CXGN::Page->new( "COS Marker List", "Robert Ahrens"); # Read data on the COS markers collection in from the sgn database. my $dbh = CXGN::DB::Connection->new(); my $cos_sth = $dbh->prepare("SELECT c.cos_id, c.cos_marker_id, c.marker_id, c.est_read_id, c.at_match, c.at_position, c.bac_id, ml.marker_id, s.trace_name FROM cos_markers AS c LEFT JOIN marker_experiment AS ml inner join marker_location using(location_id) ON c.marker_id=ml.marker_id LEFT JOIN seqread AS s ON c.est_read_id=s.read_id"); $cos_sth->execute; my @cos_list; my $old_cos_mrkr_id=0; while (my ($cos_id, $cos_mrkr_id, $mrkr_id, $est_read_id, $at_match, $at_posn, $bac_id, $mapped, $trace_name) = $cos_sth->fetchrow_array) { if ($cos_mrkr_id == $old_cos_mrkr_id) { # Skipping multiple mapped versions of the same marker. next; } else { $at_match =~ s/\.\S+//; push @cos_list, "<tr>\n<td><a href='$cos_page$mrkr_id'>$cos_id</a></td>\n" . ($trace_name ? "<td><a href='$est_read_page$trace_name'>$trace_name</a></td>\n" : "<td>No trace</td>\n") . "<td><a href=\"$at_page$bac_id\">$at_match</a></td>\n" . "<td>$at_posn</td>\n" . ($mapped ? "<td>mapped</td>\n" : "<td>not mapped</td>\n") . "</tr>\n"; $old_cos_mrkr_id = $cos_mrkr_id; } } $cos_sth->finish; # Print the page. $page->header("Conserved Ortholog Set Markers on SGN"); print "<center><h2>Conserved Ortholog Set Markers available on SGN</h2></center>\n"; print "\n<table summary=\"\" width=\"90%\" align=\"center\" border=\"2\">\n<tr>\n"; print "<td><b>CU ID \#</b></td>\n"; print "<td><b>Tomato EST Read</b></td>\n"; print "<td><b>A.t. Best BAC match</b></td>\n"; print "<td><b>A.t. position</b></td>\n"; print "<td><b>Mapped</b></td>\n"; print "</tr>\n"; print @cos_list; print "</table>\n\n"; print "<br /><br />\n"; $page->footer();
solgenomics/sgn
cgi-bin/search/markers/cos_list.pl
Perl
mit
2,741
package # Date::Manip::Offset::off355; # Copyright (c) 2008-2015 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Wed Nov 25 11:44:44 EST 2015 # Data version: tzdata2015g # Code version: tzcode2015g # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.org/tz use strict; use warnings; require 5.010000; our ($VERSION); $VERSION='6.52'; END { undef $VERSION; } our ($Offset,%Offset); END { undef $Offset; undef %Offset; } $Offset = '-05:50:27'; %Offset = ( 0 => [ 'america/menominee', ], ); 1;
jkb78/extrajnm
local/lib/perl5/Date/Manip/Offset/off355.pm
Perl
mit
856
package SimpleBot::Plugin::Topic; ## # Topic.pm # SimpleBot Plugin # Based on an original design by TMFKsoft and also used in the popular Techie-Bot, # these commands allow you set the room topic in pieces, so you can maintain # an overall persistent topic with several "columns" that you can set individually. # # !topic Minecraft Chat # !towner Eric # !tverb is # !tstatus Away # !tdivider | # !tstatic http://mywebsite.com # !ton # !toff # !trefresh # !treset ## use strict; use base qw( SimpleBot::Plugin ); use Time::HiRes qw/time/; use Tools; sub init { my $self = shift; $self->register_commands('topic', 'towner', 'tverb', 'tstatus', 'tdivider', 'tstatic', 'trefresh', 'treset', 'ton', 'toff'); } sub handler { # generic handler for all our sub-commands # topic|towner|tverb|tstatus|tdivider|tstatic|trefresh|treset|ton|toff my ($self, $cmd, $value, $args) = @_; my $username = lc($args->{who}); my $chan = nch($args->{channel}); $self->{data}->{channels} ||= {}; my $topic = $self->{data}->{channels}->{ sch($chan) } ||= {}; $topic->{topic} ||= $chan; $topic->{towner} ||= $username; $topic->{tverb} ||= 'is'; $topic->{tstatus} ||= 'Online'; $topic->{tdivider} ||= '|'; $topic->{tstatic} ||= 'http://'.$self->{params}->{server}; if ($cmd =~ /(topic|towner|tverb|tstatus|tdivider|tstatic)/) { $topic->{$cmd} = trim($value); } elsif ($cmd eq 'treset') { $self->irc_cmd( 'topic', nch($chan), ' ' ); return "Topic for $chan has been cleared."; } elsif ($cmd eq 'ton') { $topic->{tstatus} = 'Online'; } elsif ($cmd eq 'toff') { $topic->{tstatus} = 'Offline'; } my $sep = ' ' . $topic->{tdivider} . ' '; my $topic_line = join( $sep, $topic->{topic}, $topic->{towner} . ' ' . $topic->{tverb} . ' ' . $topic->{tstatus}, $topic->{tstatic} ); $self->irc_cmd( 'topic', nch($chan), $topic_line ); $self->dirty(1); # return "Topic for $chan has been updated."; return undef; } 1;
jhuckaby/simplebot
lib/Plugins/Topic.pm
Perl
mit
1,936
#!/usr/bin/perl use CGI qw(:standard); print header, start_html; sub findSum { $sum = 0; $size = @_; $i=0; while ($i < $size) { $sum += $_[$i]; $i++; } $sum; } print findSum(23, 17), "<br>"; print findSum(7, 5, 8, 3, 2), "<br>"; print findSum(11, 4, 17, 6, 25, 19), "<br>"; print hr; sub Add { my($x, $y, $z)= @_; print "You entered $_[0], $_[1], and $_[2], so you get "; return $x + $y + $z; } print Add(3, 9, 5); print hr; sub Sum { my ($y, $s) = @_; for ($i=0; $i < $s; $i++) { print $y->[$i] . " "; } } @x = ( 8, 4, 5, 7, 3, 2, 1, 9); # create an array $size = @x; # find the array size Sum(\@x, $size); #pass an array and a scalar print hr; sub findMax { if ($_[0] > $_[1]) { $_[0]; } else { $_[1]; } } print findMax(21, 39); print end_html;
nertwork/cypresspl
labs/lab8_1.pl
Perl
mit
773
# Copyright (c) 2010 - Action Without Borders # # 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. package Components; # Remember, these are preloaded and cached by mod_perl. Placing # them all here allows us to precompile ALL of these # modules before apache spawns child subprocesses. This means # that all forked children SHARE the code, saving vast amounts of # ram and speeding up module loading later use strict; use IF::Application; use IF::Component; BEGIN { my $frameworkRoot = IF::Application->systemConfigurationValueForKey("FRAMEWORK_ROOT"); open (DIR, "find $frameworkRoot/lib/IF/Component -name '*.pm' -print |") || die "Can't find any components in $frameworkRoot/lib/IF/Component"; my ($file,$pkg); while ($file = <DIR>) { next unless $file =~ /^.+\.pm$/; $file =~ s/$frameworkRoot\/lib\/IF\/Component\///g; $file =~ s/\.pm//; $file =~ s/\//::/g; $pkg = "IF::Component::".$file; #IF::Log::debug("use $pkg\n"); eval "use $pkg"; if ($@) { die "WARNING: failed to use $pkg: $@"; } } close(DIR); } 1;
quile/if-framework
framework/lib/IF/Components.pm
Perl
mit
2,155
sent('switch on the light'). sent('switch on the light in the kitchen'). sent('switch the fan off'). sent('dim the light in the living room'). sent('is the light switched on'). sent('is the light in the kitchen switched off').
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/regulus/Examples/Toy1/corpora/toy1_corpus.pl
Perl
mit
228
#!/usr/bin/env perl # File: Guest.pm # # Purpose: Collection of functions to interface with the PBot VM Guest and # execute VM commands. # SPDX-FileCopyrightText: 2022 Pragmatic Software <pragma78@gmail.com> # SPDX-License-Identifier: MIT package Guest; use 5.020; use warnings; use strict; use feature qw/signatures/; no warnings qw(experimental::signatures); use English; use Encode; use File::Basename; use JSON::XS; use IPC::Shareable; use Data::Dumper; sub read_input($input, $buffer, $tag) { my $line; my $total_read = 0; print STDERR "$tag waiting for input...\n"; my $ret = sysread($input, my $buf, 16384); if (not defined $ret) { print STDERR "Error reading $tag: $!\n"; return undef; } if ($ret == 0) { print STDERR "$tag input closed.\n"; return 0; } $total_read += $ret; print STDERR "$tag read $ret bytes [$total_read total] [$buf]\n"; $$buffer .= $buf; return undef if $$buffer !~ s/\s*:end:\s*$//m; $line = $$buffer; chomp $line; $$buffer = ''; $total_read = 0; print STDERR "-" x 40, "\n"; print STDERR "$tag got [$line]\n"; my $command = decode_json($line); $command->{arguments} //= ''; $command->{input} //= ''; print STDERR Dumper($command), "\n"; return $command; } sub process_command($command, $mod, $user, $tag) { my ($uid, $gid, $home) = (getpwnam $user)[2, 3, 7]; if (not $uid and not $gid) { print STDERR "Could not find user $user: $!\n"; return undef; } my $pid = fork; if (not defined $pid) { print STDERR "process_command: fork failed: $!\n"; return undef; } if ($pid == 0) { if ($command->{'persist-key'}) { system ("rm -rf \"/home/$user/$command->{'persist-key'}\" 1>&2"); system("mount /dev/vdb1 /root/factdata 1>&2"); system("mkdir -p \"/root/factdata/$command->{'persist-key'}\" 1>&2"); system("cp -R -p \"/root/factdata/$command->{'persist-key'}\" \"/home/$user/$command->{'persist-key'}\" 1>&2"); } my $dir = "/home/$user/$$"; system("mkdir -p $dir 1>&2"); system("chmod -R 755 $dir 1>&2"); system("chown -R $user $dir 1>&2"); system("chgrp -R $user $dir 1>&2"); system("pkill -u $user 1>&2"); system("date -s \@$command->{date} 1>&2"); $ENV{USER} = $user; $ENV{LOGNAME} = $user; $ENV{HOME} = $home; chdir("/home/$user/$$"); $GID = $gid; $EGID = "$gid $gid"; $EUID = $UID = $uid; my $result = run_command($command, $mod); print STDERR "=" x 40, "\n"; return $result; } else { # wait for child to finish waitpid($pid, 0); # clean up persistent factoid storage if ($command->{'persist-key'}) { system("cp -R -p \"/home/$user/$command->{'persist-key'}\" \"/root/factdata/$command->{'persist-key'}\""); system("umount /root/factdata"); system ("rm -rf \"/home/$user/$command->{'persist-key'}\""); } # kill any left-over processes started by $user system("pkill -u $user"); system("rm -rf /home/$user/$pid"); return 0; } } sub run_command($command, $mod) { local $SIG{CHLD} = 'DEFAULT'; $mod->preprocess; $mod->postprocess if not $mod->{error} and not $mod->{done}; if (exists $mod->{no_output} or not length $mod->{output}) { if ($command->{factoid}) { $mod->{output} = ''; } else { $mod->{output} .= "\n" if length $mod->{output}; if (not $mod->{error}) { $mod->{output} .= "Success (no output).\n"; } else { $mod->{output} .= "Exit $mod->{error}.\n"; } } } elsif ($mod->{error}) { $mod->{output} .= " [Exit $mod->{error}]"; } return $mod->{output}; } sub send_output($output, $result, $tag) { my $json = encode_json({ result => $result }); print $output "result:$json\n"; print $output "result:end\n"; } 1;
pragma-/pbot
applets/pbot-vm/guest/lib/Guest.pm
Perl
mit
4,162
package Globus::GRAM::JobState; =head1 NAME Globus::GRAM::JobState - GRAM Protocol JobState Constants =head1 DESCRIPTION The Globus::GRAM::JobState module defines symbolic names for the JobState constants in the GRAM Protocol. =head2 Methods =over 4 =item $value = Globus::GRAM::JobState::PENDING() Return the value of the PENDING constant. =cut sub PENDING { return 1; } =item $value = Globus::GRAM::JobState::ACTIVE() Return the value of the ACTIVE constant. =cut sub ACTIVE { return 2; } =item $value = Globus::GRAM::JobState::FAILED() Return the value of the FAILED constant. =cut sub FAILED { return 4; } =item $value = Globus::GRAM::JobState::DONE() Return the value of the DONE constant. =cut sub DONE { return 8; } =item $value = Globus::GRAM::JobState::SUSPENDED() Return the value of the SUSPENDED constant. =cut sub SUSPENDED { return 16; } =item $value = Globus::GRAM::JobState::UNSUBMITTED() Return the value of the UNSUBMITTED constant. =cut sub UNSUBMITTED { return 32; } =item $value = Globus::GRAM::JobState::STAGE_IN() Return the value of the STAGE_IN constant. =cut sub STAGE_IN { return 64; } =item $value = Globus::GRAM::JobState::STAGE_OUT() Return the value of the STAGE_OUT constant. =cut sub STAGE_OUT { return 128; } =item $value = Globus::GRAM::JobState::ALL() Return the value of the ALL constant. =cut sub ALL { return 0xFFFFF; } =back =cut 1;
eunsungc/gt6-RAMSES_8_5
gram/protocol/source/scripts/JobState.pm
Perl
apache-2.0
1,456
sub _get_raw_tests { my $self = shift; my $recurse = shift; my @argv = @_; my @tests; # Do globbing on Win32. @argv = map { glob "$_" } @argv if NEED_GLOB; my $extensions = $self->{extensions}; for my $arg (@argv) { if ( '-' eq $arg ) { push @argv => <STDIN>; chomp(@argv); next; } push @tests, sort -d $arg ? $recurse ? $self->_expand_dir_recursive( $arg, $extensions ) : map { glob( File::Spec->catfile( $arg, "*$_" ) ) } @{$extensions} : $arg; } return @tests; } sub _expand_dir_recursive { my ( $self, $dir, $extensions ) = @_; "/rwa/data/team/MISHNIK/perl/utils/lib/App/Prove/State.pm" line 357 of 518 --68%--
mishin/presentation
4_trans/glob.pl
Perl
apache-2.0
790
use strict; package CPAN::Reporter::PrereqCheck; our $VERSION = '1.2011'; # VERSION use ExtUtils::MakeMaker 6.36; use File::Spec; use CPAN::Version; _run() if ! caller(); sub _run { my %saw_mod; # read module and prereq string from STDIN local *DEVNULL; open DEVNULL, ">" . File::Spec->devnull; ## no critic # ensure actually installed, not ./inc/... or ./t/..., etc. local @INC = grep { $_ ne '.' } @INC; while ( <> ) { m/^(\S+)\s+([^\n]*)/; my ($mod, $need) = ($1, $2); die "Couldn't read module for '$_'" unless $mod; $need = 0 if not defined $need; # only evaluate a module once next if $saw_mod{$mod}++; # get installed version from file with EU::MM my($have, $inst_file, $dir, @packpath); if ( $mod eq "perl" ) { $have = $]; } else { @packpath = split( /::/, $mod ); $packpath[-1] .= ".pm"; if (@packpath == 1 && $packpath[0] eq "readline.pm") { unshift @packpath, "Term", "ReadLine"; # historical reasons } INCDIR: foreach my $dir (@INC) { my $pmfile = File::Spec->catfile($dir,@packpath); if (-f $pmfile){ $inst_file = $pmfile; last INCDIR; } } # get version from file or else report missing if ( defined $inst_file ) { $have = MM->parse_version($inst_file); $have = "0" if ! defined $have || $have eq 'undef'; # report broken if it can't be loaded # "select" to try to suppress spurious newlines select DEVNULL; ## no critic if ( ! _try_load( $mod, $have ) ) { select STDOUT; ## no critic print "$mod 0 broken\n"; next; } select STDOUT; ## no critic } else { print "$mod 0 n/a\n"; next; } } # complex requirements are comma separated my ( @requirements ) = split /\s*,\s*/, $need; my $passes = 0; RQ: for my $rq (@requirements) { if ($rq =~ s|>=\s*||) { # no-op -- just trimmed string } elsif ($rq =~ s|>\s*||) { if (CPAN::Version->vgt($have,$rq)){ $passes++; } next RQ; } elsif ($rq =~ s|!=\s*||) { if (CPAN::Version->vcmp($have,$rq)) { $passes++; # didn't match } next RQ; } elsif ($rq =~ s|<=\s*||) { if (! CPAN::Version->vgt($have,$rq)){ $passes++; } next RQ; } elsif ($rq =~ s|<\s*||) { if (CPAN::Version->vlt($have,$rq)){ $passes++; } next RQ; } # if made it here, then it's a normal >= comparison if (! CPAN::Version->vlt($have, $rq)){ $passes++; } } my $ok = $passes == @requirements ? 1 : 0; print "$mod $ok $have\n" } return; } sub _try_load { my ($module, $have) = @_; my @do_not_load = ( # should not be loaded directly qw/Term::ReadLine::Perl Term::ReadLine::Gnu MooseX::HasDefaults Readonly::XS POE::Loop::Event SOAP::Constants Moose::Meta::TypeConstraint::Parameterizable Moose::Meta::TypeConstraint::Parameterized/, 'Devel::Trepan', #"require Enbugger; require Devel::Trepan;" starts debugging session #removed modules qw/Pegex::Mo YAML::LibYAML/, #have additional prereqs qw/Log::Dispatch::Email::MailSender RDF::NS::Trine Plack::Handler::FCGI Web::Scraper::LibXML/, #modify @INC. 'lib' appearing in @INC will prevent correct #checking of modules with XS part, for ex. List::Util qw/ExtUtils::ParseXS ExtUtils::ParseXS::Utilities/, #require special conditions to run qw/mylib/, #do not return true value qw/perlsecret/, ); my %loading_conflicts = ( 'signatures' => ['Catalyst'], 'Dancer::Plugin::FlashMessage' => ['Dancer::Plugin::FlashNote'], 'Dancer::Plugin::Mongoose' => ['Dancer::Plugin::DBIC'], 'Dancer::Plugin::DBIC' => ['Dancer::Plugin::Mongoose'], ); #modules that conflict with each other my %load_before = ( 'Tk::Font' => 'Tk', 'Tk::Widget' => 'Tk', 'Tk::Label' => 'Tk', 'Class::MOP::Class' => 'Class::MOP', 'Moose::Meta::TypeConstraint::Role' => 'Moose', 'Moose::Meta::TypeConstraint::Union' => 'Moose', 'Moose::Meta::Attribute::Native' => 'Class::MOP', 'Test::More::Hooks' => 'Test::More', ); # M::I < 0.95 dies in require, so we can't check if it loads # Instead we just pretend that it works if ( $module eq 'Module::Install' && $have < 0.95 ) { return 1; } # circular dependency with Catalyst::Runtime, so this module # does not depends on it, but still does not work without it. elsif ( $module eq 'Catalyst::DispatchType::Regex' && $have <= 5.90032 ) { return 1; } elsif ( grep { $_ eq $module } @do_not_load ) { return 1; } # loading Acme modules like Acme::Bleach can do bad things, # so never try to load them; just pretend that they work elsif( $module =~ /^Acme::/ ) { return 1; } if ( exists $loading_conflicts{$module} ) { foreach my $mod1 ( @{ $loading_conflicts{$module} } ) { my $file = "$mod1.pm"; $file =~ s{::}{/}g; if (exists $INC{$file}) { return 1; } } } if (exists $load_before{$module}) { eval "require $load_before{$module};1;"; } my $file = "$module.pm"; $file =~ s{::}{/}g; return eval {require $file; 1}; ## no critic } 1; # ABSTRACT: Modulino for prerequisite tests __END__ =pod =encoding UTF-8 =head1 NAME CPAN::Reporter::PrereqCheck - Modulino for prerequisite tests =head1 VERSION version 1.2011 =head1 SYNOPSIS require CPAN::Reporter::PrereqCheck; my $prereq_check = $INC{'CPAN/Reporter/PrereqCheck.pm'}; my $result = qx/$perl $prereq_check < $prereq_file/; =head1 DESCRIPTION This modulino determines whether a list of prerequisite modules are available and, if so, their version number. It is designed to be run as a script in order to provide this information from the perspective of a subprocess, just like CPAN::Reporter's invocation of C<<< perl Makefile.PL >>> and so on. It reads a module name and prerequisite string pair from each line of input and prints out the module name, 0 or 1 depending on whether the prerequisite is satisfied, and the installed module version. If the module is not available, it will print "nE<sol>a" for the version. If the module is available but can't be loaded, it will print "broken" for the version. Modules without a version will be treated as being of version "0". No user serviceable parts are inside. This modulino is packaged for internal use by CPAN::Reporter. =head1 BUGS Please report any bugs or feature using the CPAN Request Tracker. Bugs can be submitted through the web interface at L<http://rt.cpan.org/Dist/Display.html?Queue=CPAN-Reporter> When submitting a bug or request, please include a test-file or a patch to an existing test-file that illustrates the bug or desired feature. =head1 SEE ALSO =over =item * L<CPAN::Reporter> -- main documentation =back =head1 AUTHOR David Golden <dagolden@cpan.org> =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2006 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut
gitpan/CPAN-Reporter
lib/CPAN/Reporter/PrereqCheck.pm
Perl
apache-2.0
7,822
=head1 LICENSE # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2022] EMBL-European Bioinformatics Institute # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::Analysis::RunnableDB::SelenoBuilder - =head1 SYNOPSIS my $exonerate4selenos = Bio::EnsEMBL::Analysis::RunnableDB::ExonerateForSelenos->new( -db => $refdb, -analysis => $analysis_obj, -input_id => $selenos_file_name ); $exonerate4selenos->fetch_input(); $exonerate4selenos->run(); $exonerate4selenos->output(); $exonerate4selenos->write_output(); #writes to DB =head1 DESCRIPTION This object wraps Bio::EnsEMBL::Analysis::Runnable::ExonerateTranscript It is meant to provide the interface for aligning cdnas of selenocysteine containing transcripts to the genome sequence and writing the results as genes. By the way Exonerate is run we do not cluster transcripts into genes and only write one transcript per gene. we then create a dbadaptor for the target database. =head1 METHODS =head1 APPENDIX The rest of the documentation details each of the object methods. Internal methods are usually preceded with a '_' =cut package Bio::EnsEMBL::Analysis::RunnableDB::SelenoBuilder; use warnings ; use strict; use Bio::SeqIO; use Bio::Seq; use Bio::EnsEMBL::SeqEdit; use Bio::EnsEMBL::Utils::Exception qw(throw warning); use Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild; use Bio::EnsEMBL::Analysis::Runnable::ExonerateTranscript; use Bio::EnsEMBL::Gene; use Bio::EnsEMBL::Analysis::Tools::Utilities qw(create_file_name write_seqfile); use Bio::EnsEMBL::Analysis::Config::SelenoBuild; use vars qw(@ISA); @ISA = qw (Bio::EnsEMBL::Analysis::RunnableDB::BaseGeneBuild); ############################################################ sub new { my ($class,@args) = @_; my $self = $class->SUPER::new(@args); $self->read_and_check_config($EXONERATE_CONFIG_BY_LOGIC); return $self; } sub fetch_input { my( $self) = @_; my $logic = $self->analysis->logic_name; $self->throw("No input id") unless defined($self->input_id); $self->fetch_sequence(); # my $discarded_db = $self->get_dbadaptor("DISCARDED_DB"); # print "DISCARDED GENE DB: ", $discarded_db->dbname,"\n"; # database where the genebuild produced genes are my $seleno_db = $self->get_dbadaptor("SELENO_DB") ; print "ENSEMBL DB : ", $seleno_db->dbname,"\n"; my $ref_db = $self->get_dbadaptor("REFERENCE_DB"); print $self->input_id,"\n"; #@input_id = split("-",$self->input_id); my $slice = $ref_db->get_SliceAdaptor->fetch_by_name($self->input_id); my $gene_slice = $seleno_db->get_SliceAdaptor->fetch_by_name($self->input_id); print $slice,"\n"; my @genes = @{$gene_slice->get_all_Genes}; ########################################## # set up the target (genome) ########################################## my $target_file = $self->QUERYSEQS."/".$slice->name; my $targetseqobj = Bio::Seq->new( -display_id =>$slice->name, -seq => $slice->seq); #write_seqfile($seqobj, # create_file_name($dna->display_name(), "fa", # "/tmp/")); my $seqout = Bio::SeqIO->new( -file => ">".$target_file, -format => 'fasta', ); $seqout->write_seq($targetseqobj); print "Fetching files:\n "; print $target_file,"\n", ########################################## # setup the runnables ########################################## my %parameters = %{$self->parameters_hash}; if (not exists($parameters{-options}) and defined $self->OPTIONS) { $parameters{-options} = $self->OPTIONS } if (not exists($parameters{-coverage_by_aligned}) and defined $self->COVERAGE_BY_ALIGNED) { $parameters{-coverage_by_aligned} = $self->COVERAGE_BY_ALIGNED; } if (defined $self->PROGRAM && defined $self->analysis->program_file) { if ($self->PROGRAM ne $self->analysis->program_file) { throw("CONFLICT: You have defined -program in your config file and ". "-program_file in your analysis table."); } } # my @runnables; foreach my $gene(@genes){ foreach my $transcript (@{$gene->get_all_Transcripts}){ foreach my $evidence (@{ $transcript->get_all_supporting_features }){ print "THIS IS YOUR EVIDENCE: ",$evidence->hseqname,"\n"; my $query_file = $self->QUERYSEQS."/".$evidence->hseqname; #print "DOING A NEW EXONERATE ALIGNMENT\n"; my $runnable = Bio::EnsEMBL::Analysis::Runnable::ExonerateTranscript ->new( -program => $self->PROGRAM ? $self->PROGRAM : $self->analysis->program_file, -analysis => $self->analysis, -target_file => $target_file, -query_type => $self->QUERYTYPE, -query_file => $query_file, -annotation_file => $self->QUERYANNOTATION ? $self->QUERYANNOTATION : undef, %parameters, ); $self->runnable($runnable); } } } } ############################################################ sub run{ my ($self) = @_; my @results; #print "THIS IS YOUR RUNNABLE: ",join(" : ",@{$self->runnable}),"\n"; throw("Can't run - no runnable objects") unless ($self->runnable); foreach my $runnable (@{$self->runnable}){ $runnable->run; # print "Storing output: ",@{$runnable->output},"\n"; push ( @results, @{$runnable->output} ); if ($self->filter) { my $filtered_transcripts = $self->filter->filter_results(\@results); @results = @$filtered_transcripts; } } my @genes = $self->make_genes(@results); print "YOU HAVE ",scalar(@genes)," genes\n"; $self->output(\@genes); } ############################################################ sub write_output{ my ($self,@output) = @_; my $outdb = $self->get_output_db; my $gene_adaptor = $outdb->get_GeneAdaptor; # unless (@output){ # @output = @{$self->output}; # } my @genes = $self->filter_redundant_transcript; print "this is genes: ",@genes, " with scalar: ",scalar(@genes),"\n"; my $fails = 0; my $total = 0; foreach my $gene (@genes){ if($gene == 0){ print "No genes output so nothing has been written\n"; }else{ print "this is your gene: ", $gene,"\n"; print "number of transcripts is : ",scalar(@{$gene->get_all_Transcripts}),"\n"; eval { $gene_adaptor->store($gene); }; if ($@){ warning("Unable to store gene!!\n$@"); $fails++; } $total++; } if ($fails > 0) { throw("Not all genes could be written successfully " . "($fails fails out of $total)"); } } } ############################################################ sub make_genes{ my ($self,@transcripts) = @_; my (@genes); my $slice_adaptor = $self->db->get_SliceAdaptor; my %genome_slices; foreach my $tran ( @transcripts ){ my $gene = Bio::EnsEMBL::Gene->new(); $gene->analysis($self->analysis); $gene->biotype($self->analysis->logic_name); ############################################################ # put a slice on the transcript my $slice_id = $tran->start_Exon->seqname; if (not exists $genome_slices{$slice_id}) { # assumes genome seqs were named in the Ensembl API Slice naming # convention, i.e. coord_syst:version:seq_reg_id:start:end:strand $genome_slices{$slice_id} = $slice_adaptor->fetch_by_name($slice_id); } my $slice = $genome_slices{$slice_id}; foreach my $exon (@{$tran->get_all_Exons}){ $exon->slice($slice); foreach my $evi (@{$exon->get_all_supporting_features}){ $evi->slice($slice); $evi->analysis($self->analysis); } } foreach my $evi (@{$tran->get_all_supporting_features}) { $evi->slice($slice); $evi->analysis($self->analysis); } if (!$slice){ my ($sf); if (@{$tran->get_all_supporting_features}) { ($sf) = @{$tran->get_all_supporting_features}; } else { my @exons = @{$tran->get_all_Exons}; ($sf) = @{$exons[0]->get_all_supporting_features}; } print $sf->hseqname."\t$slice_id\n"; } throw("Have no slice") if(!$slice); $tran->slice($slice); ######################################## # Add seleno location attrib my $sel_location = 0; my @seq_aas = split(//,$tran->translate->seq); foreach my $locat (@seq_aas){ $sel_location++; if($locat eq "*"){ print "YOU HAVE A SELENO IN LOCATION: ",$sel_location,"\n"; my $seq_edit = Bio::EnsEMBL::SeqEdit->new( -CODE => '_selenocysteine', -NAME => 'Selenocysteine', -DESC => 'Selenocysteine', -START => $sel_location, -END => $sel_location, -ALT_SEQ => 'U' ); my $attribute = $seq_edit->get_Attribute(); ##my $translation = $tran->translation(); $tran->add_Attributes($attribute); } } $gene->add_Transcript($tran); push( @genes, $gene); } return @genes; } ############################################################ sub get_chr_names{ my ($self) = @_; my @chr_names; my @chromosomes; my $chr_adaptor = $self->db->get_SliceAdaptor; #also fetching non-reference regions like DR52 for human by default. #specify in Exonerate2Genes config-file. if(defined($self->NONREF_REGIONS)){ @chromosomes = @{$chr_adaptor->fetch_all('toplevel', undef, 1)}; } else{ @chromosomes = @{$chr_adaptor->fetch_all('toplevel')}; } foreach my $chromosome ( @chromosomes ){ push( @chr_names, $chromosome->seq_region_name ); } return @chr_names; } ############################################################ sub filter_redundant_transcript{ my ($self) = @_; my @all_genes = @{$self->output}; if (scalar(@all_genes) == 0){ return 0; } my @all_transcripts; my @transcripts; foreach my $all_gene (@all_genes){ foreach my $all_transcript(@{$all_gene->get_all_Transcripts}){ push(@all_transcripts, $all_transcript); } } @all_transcripts = sort { $b->length <=> $a->length} @all_transcripts; foreach my $transcript (@all_transcripts){ my $transcript_exists = 0; if(@transcripts && scalar(@transcripts) > 0){ NEW: foreach my $new_trans(@transcripts){ my @exons = @{$transcript->get_all_Exons}; my @new_exons = @{$new_trans->get_all_Exons}; my @c_exons = @{$transcript->get_all_translateable_Exons}; my @new_c_exons = @{$new_trans->get_all_translateable_Exons}; print "Number of new coding exons: ",scalar(@new_c_exons),"\n"; print "Number of test coding exons: ",scalar(@c_exons),"\n"; # First we check that the transcripts have the exact same coding structure next NEW unless (scalar(@c_exons) == scalar(@new_c_exons)); for (my $i = 0; $i < scalar(@c_exons); $i++){ next NEW unless ($c_exons[$i]->start == $new_c_exons[$i]->start && $c_exons[$i]->end == $new_c_exons[$i]->end && $c_exons[$i]->strand == $new_c_exons[$i]->strand); } # Non we want to check that the rest of the non-coding exons are the same apart from the terminal exons next NEW unless (scalar(@exons) == scalar(@new_exons)); print "YOUR EXON STRAND: ",$exons[0]->strand,"\n"; if($exons[0]->strand == 1){ next NEW unless(#$exons[0]->start == $new_exons[0]->start && $exons[0]->end == $new_exons[0]->end && $exons[0]->strand == $new_exons[0]->strand && $exons[-1]->start == $new_exons[-1]->start && #$exons[-1]->end == $new_exons[-1]->end && $exons[-1]->strand == $new_exons[-1]->strand); if (scalar(@exons) > 2){ for (my $i = 1; $i < scalar(@exons)-1; $i++){ next NEW unless ($exons[$i]->start == $new_exons[$i]->start && $exons[$i]->end == $new_exons[$i]->end && $exons[$i]->strand == $new_exons[$i]->strand); } } }else{ next NEW unless($exons[0]->start == $new_exons[0]->start && #$exons[0]->end == $new_exons[0]->end && $exons[0]->strand == $new_exons[0]->strand && #$exons[-1]->start == $new_exons[-1]->start && $exons[-1]->end == $new_exons[-1]->end && $exons[-1]->strand == $new_exons[-1]->strand); if (scalar(@exons) > 2){ for (my $i = 1; $i < scalar(@exons)-1; $i++){ next NEW unless ($exons[$i]->start == $new_exons[$i]->start && $exons[$i]->end == $new_exons[$i]->end && $exons[$i]->strand == $new_exons[$i]->strand); } } } # If you reach here it means that both your transcripts share the same coding structure $transcript_exists = 1; # keep track of features already transferred, so that we do not duplicate #Transfer exons supporting features for (my $i = 0; $i < scalar(@exons); $i++){ my %unique_evidence; my %hold_evidence; SOURCE_FEAT: foreach my $feat ( @{$exons[$i]->get_all_supporting_features}){ next SOURCE_FEAT unless $feat->isa("Bio::EnsEMBL::FeaturePair"); # skip duplicated evidence objects next SOURCE_FEAT if ( $unique_evidence{ $feat } ); # skip duplicated evidence if ( $hold_evidence{ $feat->hseqname }{ $feat->start }{ $feat->end }{ $feat->hstart }{ $feat->hend } ){ #print STDERR "Skipping duplicated evidence\n"; next SOURCE_FEAT; } TARGET_FEAT: foreach my $tsf (@{$new_exons[$i]->get_all_supporting_features}){ next TARGET_FEAT unless $tsf->isa("Bio::EnsEMBL::FeaturePair"); if($feat->start == $tsf->start && $feat->end == $tsf->end && $feat->strand == $tsf->strand && $feat->hseqname eq $tsf->hseqname && $feat->hstart == $tsf->hstart && $feat->hend == $tsf->hend){ #print STDERR "feature already in target exon\n"; next SOURCE_FEAT; } } #print STDERR "from ".$source_exon->dbID." to ".$target_exon->dbID."\n"; #$self->print_FeaturePair($feat); # I may need to add a paranoid check to see that no exons longer than the current one are transferred $new_exons[$i]->add_supporting_features($feat); $unique_evidence{ $feat } = 1; $hold_evidence{ $feat->hseqname }{ $feat->start }{ $feat->end }{ $feat->hstart }{ $feat->hend } = 1; } } #Transfer transcript supporting features my %t_unique_evidence; my %t_hold_evidence; T_SOURCE_FEAT: foreach my $t_feat ( @{$transcript->get_all_supporting_features}){ next T_SOURCE_FEAT unless $t_feat->isa("Bio::EnsEMBL::FeaturePair"); # skip duplicated evidence objects next T_SOURCE_FEAT if ( $t_unique_evidence{ $t_feat } ); # skip duplicated evidence if ( $t_hold_evidence{ $t_feat->hseqname }{ $t_feat->start }{ $t_feat->end }{ $t_feat->hstart }{ $t_feat->hend } ){ #print STDERR "Skipping duplicated evidence\n"; next T_SOURCE_FEAT; } T_TARGET_FEAT: foreach my $t_tsf (@{$new_trans->get_all_supporting_features}){ next T_TARGET_FEAT unless $t_tsf->isa("Bio::EnsEMBL::FeaturePair"); if($t_feat->start == $t_tsf->start && $t_feat->end == $t_tsf->end && $t_feat->strand == $t_tsf->strand && $t_feat->hseqname eq $t_tsf->hseqname && $t_feat->hstart == $t_tsf->hstart && $t_feat->hend == $t_tsf->hend){ #print STDERR "feature already in target exon\n"; next T_SOURCE_FEAT; } } #print STDERR "from ".$source_exon->dbID." to ".$target_exon->dbID."\n"; #$self->print_FeaturePair($feat); # I may need to add a paranoid check to see that no exons longer than the current one are transferred $new_trans->add_supporting_features($t_feat); $t_unique_evidence{ $t_feat } = 1; $t_hold_evidence{ $t_feat->hseqname }{ $t_feat->start }{ $t_feat->end }{ $t_feat->hstart }{ $t_feat->hend } = 1; } } if($transcript_exists == 0){ push(@transcripts,$transcript); } }else{ push(@transcripts,$transcript); } } my $gene = new Bio::EnsEMBL::Gene; $gene->analysis($self->analysis); $gene->biotype($self->analysis->logic_name); foreach my $transcript (@transcripts){ foreach my $se(@{$transcript->get_all_supporting_features}){ $se->slice($transcript->slice); # print "YOU SP LOOKS LIKE: ",join(" - ",%{$se}),"\n"; } #print "Transcript Stable ID: ",$transcript->dbID,"\n"; $gene->add_Transcript($transcript); } return $gene; } ############################################################ sub get_output_db { my ($self) = @_; my $outdb; if ($self->OUTDB) { if ( ref($self->OUTDB)=~m/HASH/) { $outdb = new Bio::EnsEMBL::DBSQL::DBAdaptor(%{$self->OUTDB}, -dnadb => $self->db); }else{ $outdb = $self->get_dbadaptor($self->OUTDB); } } else { $outdb = $self->db; } return $outdb; } ############################################################ # # get/set methods # ############################################################ sub query_seqs { my ($self, @seqs) = @_; if( @seqs ) { unless ($seqs[0]->isa("Bio::PrimarySeqI") || $seqs[0]->isa("Bio::SeqI")){ throw("query seq must be a Bio::SeqI or Bio::PrimarySeqI"); } push( @{$self->{_query_seqs}}, @seqs); } return @{$self->{_query_seqs}}; } ############################################################ sub genomic { my ($self, $seq) = @_; if ($seq){ unless ($seq->isa("Bio::PrimarySeqI") || $seq->isa("Bio::SeqI")){ throw("query seq must be a Bio::SeqI or Bio::PrimarySeqI"); } $self->{_genomic} = $seq ; } return $self->{_genomic}; } ############################################################ sub database { my ($self, $database) = @_; if ($database) { $self->{_database} = $database; } return $self->{_database}; } ############################################################ sub filter { my ($self, $val) = @_; if ($val) { $self->{_transcript_filter} = $val; } return $self->{_transcript_filter}; } ############################################################# # Declare and set up config variables ############################################################# sub read_and_check_config { my $self = shift; $self->SUPER::read_and_check_config($EXONERATE_CONFIG_BY_LOGIC); ########## # CHECKS ########## my $logic = $self->analysis->logic_name; # check that compulsory options have values foreach my $config_var (qw(QUERYSEQS QUERYTYPE GENOMICSEQS)) { throw("You must define $config_var in config for logic '$logic'") if not defined $self->$config_var; } throw("QUERYANNOTATION '" . $self->QUERYANNOTATION . "' in config must be readable") if $self->QUERYANNOTATION and not -e $self->QUERYANNOTATION; # filter does not have to be defined, but if it is, it should # give details of an object and its parameters if ($self->FILTER) { if (not ref($self->FILTER) eq "HASH" or not exists($self->FILTER->{OBJECT}) or not exists($self->FILTER->{PARAMETERS})) { throw("FILTER in config fo '$logic' must be a hash ref with elements:\n" . " OBJECT : qualified name of the filter module;\n" . " PARAMETERS : anonymous hash of parameters to pass to the filter"); } else { my $module = $self->FILTER->{OBJECT}; my $pars = $self->FILTER->{PARAMETERS}; (my $class = $module) =~ s/::/\//g; eval{ require "$class.pm"; }; throw("Couldn't require ".$class." Exonerate2Genes:require_module $@") if($@); $self->filter($module->new(%{$pars})); } } } sub QUERYSEQS { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_QUERYSEQS'} = $value; } if (exists($self->{'_CONFIG_QUERYSEQS'})) { return $self->{'_CONFIG_QUERYSEQS'}; } else { return undef; } } sub QUERYTYPE { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_QUERYTYPE'} = $value; } if (exists($self->{'_CONFIG_QUERYTYPE'})) { return $self->{'_CONFIG_QUERYTYPE'}; } else { return undef; } } sub QUERYANNOTATION { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_QUERYANNOTATION'} = $value; } if (exists($self->{'_CONFIG_QUERYANNOTATION'})) { return $self->{'_CONFIG_QUERYANNOTATION'}; } else { return undef; } } sub GENOMICSEQS { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_GENOMICSEQS'} = $value; } if (exists($self->{'_CONFIG_GENOMICSEQS'})) { return $self->{'_CONFIG_GENOMICSEQS'}; } else { return undef; } } sub IIDREGEXP { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_IIDREGEXP'} = $value; } if (exists($self->{'_CONFIG_IIDREGEXP'})) { return $self->{'_CONFIG_IIDREGEXP'}; } else { return undef; } } sub OUTDB { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_OUTDB'} = $value; } if (exists($self->{'_CONFIG_OUTDB'})) { return $self->{'_CONFIG_OUTDB'}; } else { return undef; } } sub COVERAGE_BY_ALIGNED { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_COVERAGE'} = $value; } if (exists($self->{'_CONFIG_COVERAGE'})) { return $self->{'_CONFIG_COVERAGE'}; } else { return undef; } } sub FILTER { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_FILTER'} = $value; } if (exists($self->{'_CONFIG_FILTER'})) { return $self->{'_CONFIG_FILTER'}; } else { return undef; } } sub OPTIONS { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_OPTIONS'} = $value; } if (exists($self->{'_CONFIG_OPTIONS'})) { return $self->{'_CONFIG_OPTIONS'}; } else { return undef; } } sub NONREF_REGIONS { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_NONREF_REGIONS'} = $value; } if (exists($self->{'_CONFIG_NONREF_REGIONS'})) { return $self->{'_CONFIG_NONREF_REGIONS'}; } else { return undef; } } sub PROGRAM { my ($self,$value) = @_; if (defined $value) { $self->{'_CONFIG_PROGRAM'} = $value; } if (exists($self->{'_CONFIG_PROGRAM'})) { return $self->{'_CONFIG_PROGRAM'}; } else { return undef; } } ############################################### ### end of config ############################################### 1;
Ensembl/ensembl-analysis
modules/Bio/EnsEMBL/Analysis/RunnableDB/SelenoBuilder.pm
Perl
apache-2.0
25,088
:- module(match, [match/2]). %% Example match program %% Matches Pattern Pat in string T %%foo match(Pat,T) :- match1(Pat,T,Pat,T). match1([],_Ts,_P,_T). match1([A|_Ps],[B|_Ts],P,[_X|T]) :- A\==B, match1(P,T,P,T). match1([A|Ps],[A|Ts],P,T) :- match1(Ps,Ts,P,T).
leuschel/logen
tests/match.pl
Perl
apache-2.0
317
# # 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::quantum::dxi::ssh::mode::health; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use centreon::plugins::templates::catalog_functions qw(catalog_status_threshold); sub custom_status_output { my ($self, %options) = @_; return "status is '" . $self->{result_values}->{status} . "' [state = " . $self->{result_values}->{state} . "]"; } sub prefix_output { my ($self, %options) = @_; return "Health check '" . $options{instance_value}->{name} . "' "; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'global', type => 1, cb_prefix_output => 'prefix_output', message_multiple => 'All health check status are ok' }, ]; $self->{maps_counters}->{global} = [ { label => 'status', set => { key_values => [ { name => 'status' }, { name => 'state' }, { name => 'name' } ], closure_custom_output => $self->can('custom_status_output'), closure_custom_perfdata => sub { return 0; }, closure_custom_threshold_check => \&catalog_status_threshold, } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { 'warning-status:s' => { name => 'warning_status' }, 'critical-status:s' => { name => 'critical_status', default => '%{status} !~ /Ready|Success/i' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); $self->change_macros(macros => ['warning_status', 'critical_status']); } sub manage_selection { my ($self, %options) = @_; my $stdout = $options{custom}->execute_command(command => 'syscli --list healthcheckstatus'); # Output data: # Healthcheck Status # Total count = 2 # [HealthCheck = 1] # Healthcheck Name = De-Duplication # State = enabled # Started = Mon Dec 17 05:00:01 2018 # Finished = Mon Dec 17 05:02:01 2018 # Status = Success # [HealthCheck = 2] # Healthcheck Name = Integrity # State = disabled # Started = # Finished = # Status = Ready $self->{global} = {}; my $id; foreach (split(/\n/, $stdout)) { $id = $1 if (/.*\[HealthCheck\s=\s(.*)\]$/i); $self->{global}->{$id}->{status} = $1 if (/.*Status\s=\s(.*)$/i && defined($id) && $id ne ''); $self->{global}->{$id}->{state} = $1 if (/.*State\s=\s(.*)$/i && defined($id) && $id ne ''); $self->{global}->{$id}->{name} = $1 if (/.*Healthcheck\sName\s=\s(.*)$/i && defined($id) && $id ne ''); } } 1; __END__ =head1 MODE Check health status. =over 8 =item B<--warning-status> Set warning threshold for status (Default: ''). Can used special variables like: %{name}, %{status}, %{state} =item B<--critical-status> Set critical threshold for status (Default: '%{status} !~ /Ready|Success/i'). Can used special variables like: %{name}, %{status}, %{state} =back =cut
centreon/centreon-plugins
storage/quantum/dxi/ssh/mode/health.pm
Perl
apache-2.0
3,920
# Copyright 2020, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. package Google::Ads::GoogleAds::V9::Services::ChangeStatusService; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseService); sub get { my $self = shift; my $request_body = shift; my $http_method = 'GET'; my $request_path = 'v9/{+resourceName}'; my $response_type = 'Google::Ads::GoogleAds::V9::Resources::ChangeStatus'; return $self->SUPER::call($http_method, $request_path, $request_body, $response_type); } 1;
googleads/google-ads-perl
lib/Google/Ads/GoogleAds/V9/Services/ChangeStatusService.pm
Perl
apache-2.0
1,039
=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::Draw::GlyphSet::fg_regulatory_features; ### Draw regulatory features track use strict; use Role::Tiny::With; with 'EnsEMBL::Draw::Role::Default'; use base qw(EnsEMBL::Draw::GlyphSet); sub render_normal { my $self = shift; $self->{'my_config'}->set('drawing_style', ['Feature::MultiBlocks']); $self->{'my_config'}->set('display_structure', 1); $self->{'my_config'}->set('bumped', 1); $self->{'my_config'}->set('height', 12); my $data = $self->get_data; $self->draw_features($data); } sub get_data { my $self = shift; my $slice = $self->{'container'}; ## First, work out if we can even get any data! my $db_type = $self->my_config('db_type') || 'funcgen'; my $db; if (!$slice->isa('Bio::EnsEMBL::Compara::AlignSlice::Slice')) { $db = $slice->adaptor->db->get_db_adaptor($db_type); if (!$db) { warn "Cannot connect to $db_type db"; return []; } } my $rfa = $db->get_RegulatoryFeatureAdaptor; if (!$rfa) { warn ("Cannot get get adaptors: $rfa"); return []; } ## OK, looking good - fetch data from db my $cell_line = $self->my_config('cell_line'); my $config = $self->{'config'}; if ($cell_line) { my $ega = $db->get_EpigenomeAdaptor; my $epi = $ega->fetch_by_short_name($cell_line); $self->{'my_config'}->set('epigenome', $epi); } my $reg_feats = $rfa->fetch_all_by_Slice($self->{'container'}); my $drawable = []; my $entries = $self->{'legend'}{'fg_regulatory_features_legend'}{'entries'} || {}; my $activities = $self->{'legend'}{'fg_regulatory_features_legend'}{'activities'} || {}; foreach my $rf (@{$reg_feats||[]}) { my ($type, $activity) = $self->colour_key($rf); ## Create feature hash for drawing my $text = $self->my_colour($type,'text'); ## Determine colour and pattern my $key = $activity =~ /active/ ? $type : $activity; my $colour = $self->my_colour($key) || '#e1e1e1'; my ($pattern, $patterncolour, $bordercolour); if ($activity eq 'inactive') { $patterncolour = 'white'; $pattern = $self->{'container'}->length > 10000 ? 'hatch_thick' : 'hatch_thicker'; } elsif ($activity eq 'na') { $colour = 'white'; $bordercolour = 'grey50'; } ## Do legend colours and styles unless ($text =~ /unknown/i) { my $legend_params = {'colour' => $colour, 'border' => $bordercolour}; if ($activity eq 'active') { $legend_params->{'legend'} = $text; $entries->{$key} = $legend_params; } elsif ($activity eq 'inactive') { ## Only show one generic entry for all inactive features $legend_params->{'stripe'} = $patterncolour; $legend_params->{'colour'} = 'grey80'; $legend_params->{'legend'} = 'Activity in epigenome: Inactive'; $activities->{'inactive'} = $legend_params; } else { my $label = 'Activity in epigenome: '; $label .= $_ eq 'na' ? 'Insufficient evidence' : ucfirst($activity); $legend_params->{'legend'} = $label; $activities->{$activity} = $legend_params; } } ## Basic feature my $feature = { start => $rf->start, end => $rf->end, label => $text, colour => $colour, href => $self->href($rf), }; if ($pattern || $bordercolour) { $feature->{'pattern'} = $pattern; $feature->{'patterncolour'} = $patterncolour; $feature->{'bordercolour'} = $bordercolour; } ## Add flanks and motif features, except on Genoverse where it's currently way too slow if ($self->{'container'}->length < 1000000) { my $appearance = {'colour' => $colour}; if ($pattern) { $appearance->{'pattern'} = $pattern; $appearance->{'patterncolour'} = $patterncolour; } my ($extra_blocks, $flank_colour, $has_motifs) = $self->get_structure($rf, $type, $activity, $appearance); ## Extra legend items as required $entries->{'promoter_flanking'} = {'legend' => 'Promoter Flank', 'colour' => $flank_colour} if $flank_colour; $entries->{'x_motif'} = {'legend' => 'Motif feature', 'colour' => 'black', 'width' => 4} if $has_motifs; $feature->{extra_blocks} = $extra_blocks; } ## OK, done push @$drawable, $feature; } $self->{'legend'}{'fg_regulatory_features_legend'}{'priority'} ||= 1020; $self->{'legend'}{'fg_regulatory_features_legend'}{'legend'} ||= []; $self->{'legend'}{'fg_regulatory_features_legend'}{'entries'} = $entries; $self->{'legend'}{'fg_regulatory_features_legend'}{'activities'} = $activities; #use Data::Dumper; warn Dumper($drawable); return [{ features => $drawable, metadata => { force_strand => '-1', default_strand => 1, omit_feature_links => 1, display => 'normal' } }]; } sub features { my $self = shift; my $data = $self->get_data; return $data->[0]{'features'}; } sub get_structure { my ($self, $f, $type, $activity, $appearance) = @_; my $hub = $self->{'config'}{'hub'}; my $epigenome = $self->{'my_config'}->get('epigenome') || ''; my $slice = $self->{'container'}; my $start = $f->start; my $end = $f->end; my $bound_start = $f->bound_start; my $bound_end = $f->bound_end; my $has_flanking = 0; my $flank_different = 0; if ($type eq 'promoter' && $activity eq 'active') { $appearance->{'colour'} = $self->my_colour('promoter_flanking'); $flank_different = 1; } my $extra_blocks = []; if ($bound_start < $start || $bound_end > $end) { # Bound start/ends $bound_start = 0 if $bound_start < 0; push @$extra_blocks, { start => $bound_start, end => $start, %$appearance },{ start => $end, end => $bound_end, %$appearance }; $has_flanking = 1; } ## Add motif feature coordinates if any my $has_motifs = 0; if ($epigenome && $activity ne 'na' && $activity ne 'inactive') { my $mfs; ## Check the cache first my $cache_key = $f->stable_id; if ($self->feature_cache($cache_key)) { $mfs = $self->feature_cache($cache_key); } unless ($mfs) { $mfs = eval { $f->get_all_experimentally_verified_MotifFeatures; }; ## Cache motif features in case we need to draw another regfeats track $self->feature_cache($cache_key, $mfs); } ## Get peaks that overlap this epigenome foreach (@$mfs) { my $peaks = $_->get_all_overlapping_Peaks_by_Epigenome($epigenome); if (scalar @{$peaks||[]}) { push @$extra_blocks, { start => $_->start - $slice->start, end => $_->end - $slice->start, colour => 'black', }; $has_motifs = 1; } } } ## Need to pass colour back for use in legend my $flank_colour = ($has_flanking && $flank_different) ? $appearance->{'colour'} : undef; return ($extra_blocks, $flank_colour, $has_motifs); } sub colour_key { my ($self, $f) = @_; my $type = $f->feature_type->name; if($type =~ /CTCF/i) { $type = 'ctcf'; } elsif($type =~ /Enhancer/i) { $type = 'enhancer'; } elsif($type =~ /Open chromatin/i) { $type = 'open_chromatin'; } elsif($type =~ /TF binding site/i) { $type = 'tf_binding_site'; } elsif($type =~ /Promoter Flanking Region/i) { $type = 'promoter_flanking'; } elsif($type =~ /Promoter/i) { $type = 'promoter'; } else { $type = 'Unclassified'; } my $activity = 'active'; my $config = $self->{'config'}; my $epigenome = $self->{'my_config'}->get('epigenome'); if ($epigenome) { my $regact = $f->regulatory_activity_for_epigenome($epigenome); if ($regact) { $activity = $regact->activity; } } return (lc $type, lc $activity); } sub href { my ($self, $f) = @_; my $hub = $self->{'config'}->hub; my $page_species = $hub->referer->{'ENSEMBL_SPECIES'}; my @other_spp_params = grep {$_ =~ /^s[\d+]$/} $hub->param; my %other_spp; foreach (@other_spp_params) { ## If we're on an aligned species, swap parameters around if ($hub->param($_) eq $self->species) { $other_spp{$_} = $page_species; } else { $other_spp{$_} = $hub->param($_); } } return $self->_url({ species => $self->species, type => 'Regulation', rf => $f->stable_id, fdb => 'funcgen', cl => $self->my_config('cell_line'), %other_spp, }); } 1;
Ensembl/ensembl-webcode
modules/EnsEMBL/Draw/GlyphSet/fg_regulatory_features.pm
Perl
apache-2.0
9,378
# # 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. # # Author : CHEN JUN , aladdin.china@gmail.com package apps::kingdee::eas::mode::javaruntime; use base qw(centreon::plugins::mode); use strict; use warnings; use POSIX; use centreon::plugins::misc; 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 => { "urlpath:s" => { name => 'url_path', default => "/easportal/tools/nagios/checkjavaruntime.jsp" }, "warning:s" => { name => 'warning' }, "critical:s" => { name => 'critical' }, }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); $self->{output}->option_exit(); } if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); $self->{output}->option_exit(); } } sub run { my ($self, %options) = @_; my $webcontent = $options{custom}->request(path => $self->{option_results}->{url_path}); if ($webcontent !~ /VmName=/mi) { $self->{output}->output_add( severity => 'UNKNOWN', short_msg => "Cannot find java runtime status." ); $self->{output}->option_exit(); } my $vmname = $1 if $webcontent =~ /VmName=\'(.*?)\'/i; my $specversion = $1 if $webcontent =~ /SpecVersion=([\d\.]+)/i; my $vmversion = $1 if $webcontent =~ /VmVersion=(.*?)\s/i; my $vender = $1 if $webcontent =~ /VmVendor=\'(.*?)\'/i; my $uptime = $1 if $webcontent =~ /Uptime=(\d*)/i; #unit:ms my $startime = $1 if $webcontent =~ /StartTime=(\d*)/i; my $exit = $self->{perfdata}->threshold_check(value => $uptime / 1000, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => sprintf("Uptime: %s", centreon::plugins::misc::change_seconds(value => floor($uptime / 1000), start => 'd')) ); $self->{output}->output_add(severity => $exit, short_msg => sprintf("%s %s (build %s), %s", $vmname ,$specversion, $vmversion,$vender) ); $self->{output}->perfdata_add(label => "Uptime", unit => 's', value => sprintf("%d", floor($uptime / 1000)), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), ); $self->{output}->perfdata_add(label => "SpecVersion", unit => '', value => sprintf("%s", $specversion), ); $self->{output}->display(); $self->{output}->exit(); } 1; __END__ =head1 MODE Check EAS application java runtime status. =over 8 =item B<--urlpath> Set path to get status page. (Default: '/easportal/tools/nagios/checkjavaruntime.jsp') =item B<--warning> Warning Threshold for uptime (sec) =item B<--critical> Critical Threshold for uptime (sec) =back =cut
wilfriedcomte/centreon-plugins
apps/kingdee/eas/mode/javaruntime.pm
Perl
apache-2.0
4,627
use 5.10.0; use strict; use warnings; package Seq::Tracks::Base::Types; our $VERSION = '0.001'; # ABSTRACT: Defines general track information: valid track "types", # track casting (data) types # VERSION use Mouse 2; use Mouse::Util::TypeConstraints; use namespace::autoclean; use Scalar::Util qw/looks_like_number/; #What the types must be called in the config file # TODO: build these track maps automatically # by title casing the "type" field # And therefore maybe don't use these at all. state $refType = 'reference'; has refType => (is => 'ro', init_arg => undef, lazy => 1, default => sub{$refType}); state $scoreType = 'score'; has scoreType => (is => 'ro', init_arg => undef, lazy => 1, default => sub{$scoreType}); state $sparseType = 'sparse'; has sparseType => (is => 'ro', init_arg => undef, lazy => 1, default => sub{$sparseType}); state $regionType = 'region'; has regionType => (is => 'ro', init_arg => undef, lazy => 1, default => sub{$regionType}); state $geneType = 'gene'; has geneType => (is => 'ro', init_arg => undef, lazy => 1, default => sub{$geneType}); state $caddType = 'cadd'; has caddType => (is => 'ro', init_arg => undef, lazy => 1, default => sub{$caddType}); has trackTypes => (is => 'ro', init_arg => undef, lazy => 1, default => sub{ return [$refType, $scoreType, $sparseType, $regionType, $geneType, $caddType] }); enum TrackType => [$refType, $scoreType, $sparseType, $regionType, $geneType, $caddType]; #Convert types; Could move the conversion code elsewehre, #but I wanted types definition close to implementation enum DataType => ['float', 'int', 'number']; #idiomatic way to re-use a stack, gain some efficiency #expects ->convert('string or number', 'type') sub convert { goto &{$_[2]}; #2nd argument, with $self == $_[0] } #For numeric types we need to check if we were given a weird string #not certain if we should return, warn, or what #in bioinformatics it seems very common to use "NA" or a "." or "-" to #depict missing data #@param {Str | Num} $_[1] : the data #Note that if "-1.000000" is passed, it is NOT guaranteed to be returned as a float #Strangely enough, it seems to be handled internally as an int potentially #Or this could be dependent on msgpack-perl sub float { if (!looks_like_number($_[1] ) ) { return $_[1]; } return $_[1] + 0; } #@param {Str | Num} $_[1] : the data sub int { if (!looks_like_number($_[1] ) ) { return $_[1]; } #Truncates, doesn't round return CORE::int($_[1]); } # This is useful, because will convert a string like "1.000000" to an int # And this will be interpreted in msgpack as an int, rather than a long string # Similarly, all numbers *should* be storable within 9 bytes (float64), # whereas if we sprintf, they will be stored as strings sub number { if (!looks_like_number($_[1] ) ) { return $_[1]; } #Saves us up to 8 bytes, because otherwise msgpack will store everything #as a 9 byte double if(CORE::int($_[1]) == $_[1]) { return CORE::int($_[1]); } return 0 + $_[1]; } #moved away from this; the base build class shouldn't need to know #what types are allowed, that info is kep in the various track modules #this is a simple-minded way to enforce a bed-only format #this should not be used for things with single-field headers #like wig or multi-fasta (or fasta) # enum BedFieldType => ['chrom', 'chromStart', 'chromEnd']; no Mouse::Util::TypeConstraints; __PACKAGE__->meta->make_immutable; 1;
wingolab-org/seq2-annotator
lib/Seq/Tracks/Base/Types.pm
Perl
apache-2.0
3,467
use utf8; package Netdisco::DB::Result::DeviceRoute; # 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("device_route"); __PACKAGE__->add_columns( "ip", { data_type => "inet", is_nullable => 0 }, "network", { data_type => "cidr", is_nullable => 0 }, "creation", { data_type => "timestamp", default_value => \"current_timestamp", is_nullable => 1, original => { default_value => \"now()" }, }, "dest", { data_type => "inet", is_nullable => 0 }, "last_discover", { data_type => "timestamp", default_value => \"current_timestamp", is_nullable => 1, original => { default_value => \"now()" }, }, ); __PACKAGE__->set_primary_key("ip", "network", "dest"); # Created by DBIx::Class::Schema::Loader v0.07015 @ 2012-01-07 14:20:02 # DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:3jcvPP60E5BvwnUbXql7mQ # You can replace this text with custom code or comments, and it will be preserved on regeneration 1;
jeneric/netdisco-frontend-sandpit
Netdisco/lib/Netdisco/DB/Result/DeviceRoute.pm
Perl
bsd-3-clause
1,088
%% TESTING directive include... % #include('test_include.pl'). %% PROGRAM 1: %% two models one for ?- p. and another for ?- q. % p :- not q. % q :- not p. % ?- p. % ?- q. %% PROGRAM 1b: %% Previous program with predicate ASP. p(X) :- not q(X). q(X) :- not p(X). ?- q(X). %% PROGRAM 2: %% three models (normal prolog query) % pa(1,2). % pa(2,3). % pa(3,4). % ?- pa(X,Y). %% PROGRAM 3: %% Hamiltonian problem with a graph with two models %% The second model appear in the 7th answer... % reachable(V) :- % chosen(U, V), % reachable(U). % reachable(O) :- % chosen(V,O). % :- vertex(U), not reachable(U). % other(U,V) :- % vertex(U), vertex(V), vertex(W), % V \= W, chosen(U,W). % chosen(U,V) :- % vertex(U), vertex(V), % edgeh(U,V), not other(U,V). % :- chosen(U,W), chosen(V,W), U \= V. % vertex(0). % vertex(1). % vertex(2). % vertex(3). % vertex(4). % edgeh(0,1). % edgeh(1,2). % edgeh(2,3). % edgeh(3,4). % edgeh(4,0). % edgeh(4,1). % edgeh(4,2). % edgeh(4,3). % edgeh(0,2). % edgeh(2,1). % edgeh(1,3). % ?- reachable(0).
Xuaco/casp
src/server/test.pl
Perl
bsd-3-clause
1,085
package AsposeImagingCloud::Object::TextEffect; require 5.6.0; use strict; use warnings; use utf8; use JSON qw(decode_json); use Data::Dumper; use Module::Runtime qw(use_module); use Log::Any qw($log); use Date::Parse; use DateTime; use base "AsposeImagingCloud::Object::BaseObject"; # # # #NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. # my $swagger_types = { }; my $attribute_map = { }; # new object sub new { my ($class, %args) = @_; my $self = { }; return bless $self, $class; } # get swagger type of the attribute sub get_swagger_types { return $swagger_types; } # get attribute mappping sub get_attribute_map { return $attribute_map; } 1;
aspose-imaging/Aspose.Imaging-for-Cloud
SDKs/Aspose.Imaging-Cloud-SDK-for-Perl/lib/AsposeImagingCloud/Object/TextEffect.pm
Perl
mit
765
for $c (1..40) { for $b (1..$c-1) { for $a (1..$b-1) { if ($a * $a + $b * $b == $c * $c) { printf "%i, %i, %i\n", $a, $b, $c; } } } }
rtoal/ple
perl/triple.pl
Perl
mit
198
/************************************************************************* name: godis-vcr-text version: description: GoDiS VCR application specification file, text, windows author: Staffan Larsson ************************************************************************* :-ensure_loaded(app_search_paths). /*======================================================================== Select datatypes Speficies a list of datatypes to be loaded. Each item DataType in the list corresponds to a file DataType.pl in the search path. ========================================================================*/ selected_datatypes([string, move, atom, integer, bool, record, set, stack, stackset, queue, oqueue, pair, assocset, godis_datatypes]). /*======================================================================== Select modules Each module spec has the form Predicate:FileName, where Predicate is the unary predicate used to call the module, and FileName.pl is the a file in the search path containing the module specification ========================================================================*/ selected_modules([ input : input_textscore, interpret : interpret_simple, update : update, select : select, generate : generate_simple, output : output_simpletext ]). % dme_module/1 - spefifies which modules have unlimited access to TIS dme_modules([ update, select ]). /*======================================================================== Select resources Speficies a list of resources to be loaded. Each item ResourceFile in the list corresponds to a a file ResourceFile.pl in the search path. The file defines a resource object with the same name as the file. ========================================================================*/ selected_resources( [ device_vcr, lexicon_vcr_english, lexicon_vcr_svenska, domain_vcr % device_telephone, % lexicon_telephone_english, % domain_telephone ] ). selected_macro_file( godis_macros ). /*======================================================================== operations to execute on TIS reset ========================================================================*/ reset_operations( [ set( program_state, run), set( language, Lang ), set( lexicon, $$dash2underscore(lexicon-Domain-Lang) ), set( devices, record([vcr=device_vcr]) ), % telephone=device_telephone]) ), % set( devices, record([telephone=device_telephone]) ), set( domain, $$dash2underscore(domain-Domain) ), push(/private/agenda,greet), % push(/private/agenda,do(vcr_top)), % push( /shared/actions, vcr_top ) ]):- push(/private/agenda,do(top)), push( /shared/actions, top ) ]):- flag( language, Lang ), flag( domain, Domain ). /*======================================================================== Set flags ========================================================================*/ :- setflag(show_rules,yes). :- setflag(show_state,all). /*======================================================================== Run ========================================================================*/ quiet:- setflag(show_rules,no), setflag(show_state,no). verb:- setflag(show_rules,yes), setflag(show_state,all). run :- run(vcr-english). % reload update rules rur :- update:ensure_loaded(library(update_rules)). rsr :- select:ensure_loaded(library(selection_rules)). :- assert(hide_path('UNLIKELYPAHNAME')).
TeamSPoon/logicmoo_workspace
packs_sys/logicmoo_nlu/ext/SIRIDUS/UGOT-D31/godis-apps/domain-vcr/godis-vcr-text.pl
Perl
mit
3,587
package Google::Ads::AdWords::v201409::CriterionTypeGroup; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201409'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType CriterionTypeGroup from the namespace https://adwords.google.com/api/adwords/cm/v201409. The list of groupings of criteria types. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201409/CriterionTypeGroup.pm
Perl
apache-2.0
1,115
#!/usr/bin/perl # Only for APOL if ($#ARGV != 1) { print "Usage: ./migratesm_mail.pl <virtualuser file> <spool directory>\n"; print "Remember add a backslash \"\/\" at the end.\n"; print "eg: ./migratesm_mail.pl /etc/mail/virtualuser /var/spool/\n\n"; exit; } my ($ref, $path) = @ARGV; my $TOTAL = $OK = 0; my $log = "$0.log"; $log =~ s/\.pl//; $| = 1; if (!-d $path) { print "[ERROR] $path doesn't exist!\n"; exit; } if (substr($path, length($path) - 1, 1) ne "\/") { print "[ERROR] missing \"\/\" at the end!\n"; exit; } open(REF, "<$ref"); open(LOG, ">$log"); while(<REF>) { $TOTAL++; chomp; ($user, $file) = split(/\t/); $userpath = `/webmail/tools/userhome $user`; $mailpath = $userpath . "/@"; if (!-f "$userpath/.passwd") { print "[ERROR] $user doesn't exist in mail!\n"; next; } $ID = 0; $First = 1; $lastline = ""; open(IN, "<$path$file"); while($line = <IN>) { $From = 0; if ($First == 1) { $fname = "$mailpath/$ID"; open(OU, ">$fname"); $ID++; $First = 0; $From = 1; } if (($line =~ /^From /) && ($lastline eq "\n")) { close(OU); $fname = "$mailpath/$ID"; open(OU, ">$fname"); $ID++; $From = 1; } print OU "$line" if ($From == 0); $lastline = $line; } close(IN); close(OU); $fname = "$mailpath/.DIR"; system("/webmail/tools/builddir -m $mailpath"); print LOG "[$ID] mail(s) $user\n"; } print LOG "\n"; close(LOG); close(REF);
TonyChengTW/EZMail
migration/migratesm_mail.pl
Perl
apache-2.0
1,426
package Google::Ads::AdWords::v201406::AdGroupAd::ApprovalStatus; use strict; use warnings; sub get_xmlns { 'https://adwords.google.com/api/adwords/cm/v201406'}; # derivation by restriction use base qw( SOAP::WSDL::XSD::Typelib::Builtin::string); 1; __END__ =pod =head1 NAME =head1 DESCRIPTION Perl data type class for the XML Schema defined simpleType AdGroupAd.ApprovalStatus from the namespace https://adwords.google.com/api/adwords/cm/v201406. Represents the possible approval statuses. This clase is derived from SOAP::WSDL::XSD::Typelib::Builtin::string . SOAP::WSDL's schema implementation does not validate data, so you can use it exactly like it's base type. # Description of restrictions not implemented yet. =head1 METHODS =head2 new Constructor. =head2 get_value / set_value Getter and setter for the simpleType's value. =head1 OVERLOADING Depending on the simple type's base type, the following operations are overloaded Stringification Numerification Boolification Check L<SOAP::WSDL::XSD::Typelib::Builtin> for more information. =head1 AUTHOR Generated by SOAP::WSDL =cut
gitpan/GOOGLE-ADWORDS-PERL-CLIENT
lib/Google/Ads/AdWords/v201406/AdGroupAd/ApprovalStatus.pm
Perl
apache-2.0
1,130
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 6.2.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. return <<'END'; 1780 17DD 17E0 17E9 17F0 17F9 19E0 19FF END
Bjay1435/capstone
rootfs/usr/share/perl/5.18.2/unicore/lib/Sc/Khmr.pl
Perl
mit
463
#!/usr/bin/env perl # # Copyright 2014 Wei Shen (shenwei356#gmail.com). All rights reserved. # Use of this source code is governed by a MIT-license # that can be found in the LICENSE file. # https://github.com/shenwei356/bio_scripts/ use strict; use BioUtil::Misc; die "usage: $0 embossre.enz\n" unless @ARGV == 1; my $file = shift @ARGV; my $d = shift @ARGV; my $enzs = parse_embossre($file); for my $enz (sort keys %$enzs) { my $e = $$enzs{$enz}; next unless $$e{cuts_number} == 2 and $$e{c1} - $$e{c2} == 1 and substr ($$e{pattern}, $$e{c1} - 1, 1) =~ /[aN]/i; print "$enz\n"; } # there's no enzyme meeting this condition
shenwei356/bio_scripts
enzyme/restrict_with_T_tail.pl
Perl
mit
663
#!/usr/bin/perl use strict; my @dev_details = `ls -l /sys/block/ | grep sd | grep -v sda`; my @dev_names; while (@dev_details) { my $item = shift(@dev_details); if ($item =~ /sd([b-z])$/) { my $dev = $1; # get all devices push(@dev_names, $dev); print "dev: $dev\n"; } } my $scheduler = "noop"; my $num_devs = @dev_names; for (my $i = 1; $i <= $num_devs; $i++) { my $dev_idx = $i - 1; my $dev_file = "/dev/sd$dev_names[$dev_idx]"; system("echo $scheduler > /sys/block/sd$dev_names[$dev_idx]/queue/scheduler"); system("cat /sys/block/sd$dev_names[$dev_idx]/queue/scheduler"); system("echo 2 > /sys/block/sd$dev_names[$dev_idx]/queue/rq_affinity"); system("cat /sys/block/sd$dev_names[$dev_idx]/queue/rq_affinity"); }
icoming/FlashGraph
conf/set_scheduler.pl
Perl
apache-2.0
739
package Devel::GlobalDestruction; use strict; use warnings; our $VERSION = '0.13'; use Sub::Exporter::Progressive -setup => { exports => [ qw(in_global_destruction) ], groups => { default => [ -all ] }, }; # we run 5.14+ - everything is in core # if (defined ${^GLOBAL_PHASE}) { eval 'sub in_global_destruction () { ${^GLOBAL_PHASE} eq q[DESTRUCT] }; 1' or die $@; } # try to load the xs version if it was compiled # elsif (eval { require Devel::GlobalDestruction::XS; no warnings 'once'; *in_global_destruction = \&Devel::GlobalDestruction::XS::in_global_destruction; 1; }) { # the eval already installed everything, nothing to do } else { # internally, PL_main_cv is set to Nullcv immediately before entering # global destruction and we can use B to detect that. B::main_cv will # only ever be a B::CV or a B::SPECIAL that is a reference to 0 require B; eval 'sub in_global_destruction () { ${B::main_cv()} == 0 }; 1' or die $@; } 1; # keep require happy __END__ =head1 NAME Devel::GlobalDestruction - Provides function returning the equivalent of C<${^GLOBAL_PHASE} eq 'DESTRUCT'> for older perls. =head1 SYNOPSIS package Foo; use Devel::GlobalDestruction; use namespace::clean; # to avoid having an "in_global_destruction" method sub DESTROY { return if in_global_destruction; do_something_a_little_tricky(); } =head1 DESCRIPTION Perl's global destruction is a little tricky to deal with WRT finalizers because it's not ordered and objects can sometimes disappear. Writing defensive destructors is hard and annoying, and usually if global destruction is happening you only need the destructors that free up non process local resources to actually execute. For these constructors you can avoid the mess by simply bailing out if global destruction is in effect. =head1 EXPORTS This module uses L<Sub::Exporter::Progressive> so the exports may be renamed, aliased, etc. if L<Sub::Exporter> is present. =over 4 =item in_global_destruction Returns true if the interpreter is in global destruction. In perl 5.14+, this returns C<${^GLOBAL_PHASE} eq 'DESTRUCT'>, and on earlier perls, detects it using the value of C<PL_main_cv> or C<PL_dirty>. =back =head1 AUTHORS Yuval Kogman E<lt>nothingmuch@woobling.orgE<gt> Florian Ragwitz E<lt>rafl@debian.orgE<gt> Jesse Luehrs E<lt>doy@tozt.netE<gt> Peter Rabbitson E<lt>ribasushi@cpan.orgE<gt> Arthur Axel 'fREW' Schmidt E<lt>frioux@gmail.comE<gt> Elizabeth Mattijsen E<lt>liz@dijkmat.nlE<gt> Greham Knop E<lt>haarg@haarg.orgE<gt> =head1 COPYRIGHT Copyright (c) 2008 Yuval Kogman. All rights reserved This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut
ashkanx/binary-mt
scripts/local/lib/perl5/Devel/GlobalDestruction.pm
Perl
apache-2.0
2,775
=pod =for comment openssl_manual_section:7 =head1 NAME SSL - OpenSSL SSL/TLS library =head1 SYNOPSIS See the individual manual pages for details. =head1 DESCRIPTION The OpenSSL B<ssl> library implements the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols. It provides a rich API which is documented here. Then an B<SSL_CTX> object is created as a framework to establish TLS/SSL enabled connections (see L<SSL_CTX_new(3)>). Various options regarding certificates, algorithms etc. can be set in this object. When a network connection has been created, it can be assigned to an B<SSL> object. After the B<SSL> object has been created using L<SSL_new(3)>, L<SSL_set_fd(3)> or L<SSL_set_bio(3)> can be used to associate the network connection with the object. Then the TLS/SSL handshake is performed using L<SSL_accept(3)> or L<SSL_connect(3)> respectively. L<SSL_read(3)> and L<SSL_write(3)> are used to read and write data on the TLS/SSL connection. L<SSL_shutdown(3)> can be used to shut down the TLS/SSL connection. =head1 DATA STRUCTURES Currently the OpenSSL B<ssl> library functions deals with the following data structures: =over 4 =item B<SSL_METHOD> (SSL Method) That's a dispatch structure describing the internal B<ssl> library methods/functions which implement the various protocol versions (SSLv3 TLSv1, ...). It's needed to create an B<SSL_CTX>. =item B<SSL_CIPHER> (SSL Cipher) This structure holds the algorithm information for a particular cipher which are a core part of the SSL/TLS protocol. The available ciphers are configured on a B<SSL_CTX> basis and the actually used ones are then part of the B<SSL_SESSION>. =item B<SSL_CTX> (SSL Context) That's the global context structure which is created by a server or client once per program life-time and which holds mainly default values for the B<SSL> structures which are later created for the connections. =item B<SSL_SESSION> (SSL Session) This is a structure containing the current TLS/SSL session details for a connection: B<SSL_CIPHER>s, client and server certificates, keys, etc. =item B<SSL> (SSL Connection) That's the main SSL/TLS structure which is created by a server or client per established connection. This actually is the core structure in the SSL API. Under run-time the application usually deals with this structure which has links to mostly all other structures. =back =head1 HEADER FILES Currently the OpenSSL B<ssl> library provides the following C header files containing the prototypes for the data structures and functions: =over 4 =item B<ssl.h> That's the common header file for the SSL/TLS API. Include it into your program to make the API of the B<ssl> library available. It internally includes both more private SSL headers and headers from the B<crypto> library. Whenever you need hard-core details on the internals of the SSL API, look inside this header file. =item B<ssl2.h> Unused. Present for backwards compatibility only. =item B<ssl3.h> That's the sub header file dealing with the SSLv3 protocol only. I<Usually you don't have to include it explicitly because it's already included by ssl.h>. =item B<tls1.h> That's the sub header file dealing with the TLSv1 protocol only. I<Usually you don't have to include it explicitly because it's already included by ssl.h>. =back =head1 API FUNCTIONS Currently the OpenSSL B<ssl> library exports 214 API functions. They are documented in the following: =head2 Dealing with Protocol Methods Here we document the various API functions which deal with the SSL/TLS protocol methods defined in B<SSL_METHOD> structures. =over 4 =item const SSL_METHOD *B<TLS_method>(void); Constructor for the I<version-flexible> SSL_METHOD structure for clients, servers or both. See L<SSL_CTX_new(3)> for details. =item const SSL_METHOD *B<TLS_client_method>(void); Constructor for the I<version-flexible> SSL_METHOD structure for clients. =item const SSL_METHOD *B<TLS_server_method>(void); Constructor for the I<version-flexible> SSL_METHOD structure for servers. =item const SSL_METHOD *B<TLSv1_2_method>(void); Constructor for the TLSv1.2 SSL_METHOD structure for clients, servers or both. =item const SSL_METHOD *B<TLSv1_2_client_method>(void); Constructor for the TLSv1.2 SSL_METHOD structure for clients. =item const SSL_METHOD *B<TLSv1_2_server_method>(void); Constructor for the TLSv1.2 SSL_METHOD structure for servers. =item const SSL_METHOD *B<TLSv1_1_method>(void); Constructor for the TLSv1.1 SSL_METHOD structure for clients, servers or both. =item const SSL_METHOD *B<TLSv1_1_client_method>(void); Constructor for the TLSv1.1 SSL_METHOD structure for clients. =item const SSL_METHOD *B<TLSv1_1_server_method>(void); Constructor for the TLSv1.1 SSL_METHOD structure for servers. =item const SSL_METHOD *B<TLSv1_method>(void); Constructor for the TLSv1 SSL_METHOD structure for clients, servers or both. =item const SSL_METHOD *B<TLSv1_client_method>(void); Constructor for the TLSv1 SSL_METHOD structure for clients. =item const SSL_METHOD *B<TLSv1_server_method>(void); Constructor for the TLSv1 SSL_METHOD structure for servers. =item const SSL_METHOD *B<SSLv3_method>(void); Constructor for the SSLv3 SSL_METHOD structure for clients, servers or both. =item const SSL_METHOD *B<SSLv3_client_method>(void); Constructor for the SSLv3 SSL_METHOD structure for clients. =item const SSL_METHOD *B<SSLv3_server_method>(void); Constructor for the SSLv3 SSL_METHOD structure for servers. =back =head2 Dealing with Ciphers Here we document the various API functions which deal with the SSL/TLS ciphers defined in B<SSL_CIPHER> structures. =over 4 =item char *B<SSL_CIPHER_description>(SSL_CIPHER *cipher, char *buf, int len); Write a string to I<buf> (with a maximum size of I<len>) containing a human readable description of I<cipher>. Returns I<buf>. =item int B<SSL_CIPHER_get_bits>(SSL_CIPHER *cipher, int *alg_bits); Determine the number of bits in I<cipher>. Because of export crippled ciphers there are two bits: The bits the algorithm supports in general (stored to I<alg_bits>) and the bits which are actually used (the return value). =item const char *B<SSL_CIPHER_get_name>(SSL_CIPHER *cipher); Return the internal name of I<cipher> as a string. These are the various strings defined by the I<SSL3_TXT_xxx> and I<TLS1_TXT_xxx> definitions in the header files. =item const char *B<SSL_CIPHER_get_version>(SSL_CIPHER *cipher); Returns a string like "C<SSLv3>" or "C<TLSv1.2>" which indicates the SSL/TLS protocol version to which I<cipher> belongs (i.e. where it was defined in the specification the first time). =back =head2 Dealing with Protocol Contexts Here we document the various API functions which deal with the SSL/TLS protocol context defined in the B<SSL_CTX> structure. =over 4 =item int B<SSL_CTX_add_client_CA>(SSL_CTX *ctx, X509 *x); =item long B<SSL_CTX_add_extra_chain_cert>(SSL_CTX *ctx, X509 *x509); =item int B<SSL_CTX_add_session>(SSL_CTX *ctx, SSL_SESSION *c); =item int B<SSL_CTX_check_private_key>(const SSL_CTX *ctx); =item long B<SSL_CTX_ctrl>(SSL_CTX *ctx, int cmd, long larg, char *parg); =item void B<SSL_CTX_flush_sessions>(SSL_CTX *s, long t); =item void B<SSL_CTX_free>(SSL_CTX *a); =item char *B<SSL_CTX_get_app_data>(SSL_CTX *ctx); =item X509_STORE *B<SSL_CTX_get_cert_store>(SSL_CTX *ctx); =item STACK *B<SSL_CTX_get_ciphers>(const SSL_CTX *ctx); =item STACK *B<SSL_CTX_get_client_CA_list>(const SSL_CTX *ctx); =item int (*B<SSL_CTX_get_client_cert_cb>(SSL_CTX *ctx))(SSL *ssl, X509 **x509, EVP_PKEY **pkey); =item void B<SSL_CTX_get_default_read_ahead>(SSL_CTX *ctx); =item char *B<SSL_CTX_get_ex_data>(const SSL_CTX *s, int idx); =item int B<SSL_CTX_get_ex_new_index>(long argl, char *argp, int (*new_func);(void), int (*dup_func)(void), void (*free_func)(void)) =item void (*B<SSL_CTX_get_info_callback>(SSL_CTX *ctx))(SSL *ssl, int cb, int ret); =item int B<SSL_CTX_get_quiet_shutdown>(const SSL_CTX *ctx); =item void B<SSL_CTX_get_read_ahead>(SSL_CTX *ctx); =item int B<SSL_CTX_get_session_cache_mode>(SSL_CTX *ctx); =item long B<SSL_CTX_get_timeout>(const SSL_CTX *ctx); =item int (*B<SSL_CTX_get_verify_callback>(const SSL_CTX *ctx))(int ok, X509_STORE_CTX *ctx); =item int B<SSL_CTX_get_verify_mode>(SSL_CTX *ctx); =item int B<SSL_CTX_load_verify_locations>(SSL_CTX *ctx, const char *CAfile, const char *CApath); =item SSL_CTX *B<SSL_CTX_new>(const SSL_METHOD *meth); =item int SSL_CTX_up_ref(SSL_CTX *ctx); =item int B<SSL_CTX_remove_session>(SSL_CTX *ctx, SSL_SESSION *c); =item int B<SSL_CTX_sess_accept>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_accept_good>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_accept_renegotiate>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_cache_full>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_cb_hits>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_connect>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_connect_good>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_connect_renegotiate>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_get_cache_size>(SSL_CTX *ctx); =item SSL_SESSION *(*B<SSL_CTX_sess_get_get_cb>(SSL_CTX *ctx))(SSL *ssl, unsigned char *data, int len, int *copy); =item int (*B<SSL_CTX_sess_get_new_cb>(SSL_CTX *ctx)(SSL *ssl, SSL_SESSION *sess); =item void (*B<SSL_CTX_sess_get_remove_cb>(SSL_CTX *ctx)(SSL_CTX *ctx, SSL_SESSION *sess); =item int B<SSL_CTX_sess_hits>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_misses>(SSL_CTX *ctx); =item int B<SSL_CTX_sess_number>(SSL_CTX *ctx); =item void B<SSL_CTX_sess_set_cache_size>(SSL_CTX *ctx, t); =item void B<SSL_CTX_sess_set_get_cb>(SSL_CTX *ctx, SSL_SESSION *(*cb)(SSL *ssl, unsigned char *data, int len, int *copy)); =item void B<SSL_CTX_sess_set_new_cb>(SSL_CTX *ctx, int (*cb)(SSL *ssl, SSL_SESSION *sess)); =item void B<SSL_CTX_sess_set_remove_cb>(SSL_CTX *ctx, void (*cb)(SSL_CTX *ctx, SSL_SESSION *sess)); =item int B<SSL_CTX_sess_timeouts>(SSL_CTX *ctx); =item LHASH *B<SSL_CTX_sessions>(SSL_CTX *ctx); =item int B<SSL_CTX_set_app_data>(SSL_CTX *ctx, void *arg); =item void B<SSL_CTX_set_cert_store>(SSL_CTX *ctx, X509_STORE *cs); =item void B<SSL_CTX_set_cert_verify_cb>(SSL_CTX *ctx, int (*cb)(), char *arg) =item int B<SSL_CTX_set_cipher_list>(SSL_CTX *ctx, char *str); =item void B<SSL_CTX_set_client_CA_list>(SSL_CTX *ctx, STACK *list); =item void B<SSL_CTX_set_client_cert_cb>(SSL_CTX *ctx, int (*cb)(SSL *ssl, X509 **x509, EVP_PKEY **pkey)); =item int B<SSL_CTX_set_ct_validation_callback>(SSL_CTX *ctx, ssl_ct_validation_cb callback, void *arg); =item void B<SSL_CTX_set_default_passwd_cb>(SSL_CTX *ctx, int (*cb);(void)) =item void B<SSL_CTX_set_default_read_ahead>(SSL_CTX *ctx, int m); =item int B<SSL_CTX_set_default_verify_paths>(SSL_CTX *ctx); Use the default paths to locate trusted CA certificates. There is one default directory path and one default file path. Both are set via this call. =item int B<SSL_CTX_set_default_verify_dir>(SSL_CTX *ctx) Use the default directory path to locate trusted CA certificates. =item int B<SSL_CTX_set_default_verify_file>(SSL_CTX *ctx) Use the file path to locate trusted CA certificates. =item int B<SSL_CTX_set_ex_data>(SSL_CTX *s, int idx, char *arg); =item void B<SSL_CTX_set_info_callback>(SSL_CTX *ctx, void (*cb)(SSL *ssl, int cb, int ret)); =item void B<SSL_CTX_set_msg_callback>(SSL_CTX *ctx, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)); =item void B<SSL_CTX_set_msg_callback_arg>(SSL_CTX *ctx, void *arg); =item unsigned long B<SSL_CTX_clear_options>(SSL_CTX *ctx, unsigned long op); =item unsigned long B<SSL_CTX_get_options>(SSL_CTX *ctx); =item unsigned long B<SSL_CTX_set_options>(SSL_CTX *ctx, unsigned long op); =item void B<SSL_CTX_set_quiet_shutdown>(SSL_CTX *ctx, int mode); =item void B<SSL_CTX_set_read_ahead>(SSL_CTX *ctx, int m); =item void B<SSL_CTX_set_session_cache_mode>(SSL_CTX *ctx, int mode); =item int B<SSL_CTX_set_ssl_version>(SSL_CTX *ctx, const SSL_METHOD *meth); =item void B<SSL_CTX_set_timeout>(SSL_CTX *ctx, long t); =item long B<SSL_CTX_set_tmp_dh>(SSL_CTX* ctx, DH *dh); =item long B<SSL_CTX_set_tmp_dh_callback>(SSL_CTX *ctx, DH *(*cb)(void)); =item void B<SSL_CTX_set_verify>(SSL_CTX *ctx, int mode, int (*cb);(void)) =item int B<SSL_CTX_use_PrivateKey>(SSL_CTX *ctx, EVP_PKEY *pkey); =item int B<SSL_CTX_use_PrivateKey_ASN1>(int type, SSL_CTX *ctx, unsigned char *d, long len); =item int B<SSL_CTX_use_PrivateKey_file>(SSL_CTX *ctx, const char *file, int type); =item int B<SSL_CTX_use_RSAPrivateKey>(SSL_CTX *ctx, RSA *rsa); =item int B<SSL_CTX_use_RSAPrivateKey_ASN1>(SSL_CTX *ctx, unsigned char *d, long len); =item int B<SSL_CTX_use_RSAPrivateKey_file>(SSL_CTX *ctx, const char *file, int type); =item int B<SSL_CTX_use_certificate>(SSL_CTX *ctx, X509 *x); =item int B<SSL_CTX_use_certificate_ASN1>(SSL_CTX *ctx, int len, unsigned char *d); =item int B<SSL_CTX_use_certificate_file>(SSL_CTX *ctx, const char *file, int type); =item X509 *B<SSL_CTX_get0_certificate>(const SSL_CTX *ctx); =item EVP_PKEY *B<SSL_CTX_get0_privatekey>(const SSL_CTX *ctx); =item void B<SSL_CTX_set_psk_client_callback>(SSL_CTX *ctx, unsigned int (*callback)(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len)); =item int B<SSL_CTX_use_psk_identity_hint>(SSL_CTX *ctx, const char *hint); =item void B<SSL_CTX_set_psk_server_callback>(SSL_CTX *ctx, unsigned int (*callback)(SSL *ssl, const char *identity, unsigned char *psk, int max_psk_len)); =back =head2 Dealing with Sessions Here we document the various API functions which deal with the SSL/TLS sessions defined in the B<SSL_SESSION> structures. =over 4 =item int B<SSL_SESSION_cmp>(const SSL_SESSION *a, const SSL_SESSION *b); =item void B<SSL_SESSION_free>(SSL_SESSION *ss); =item char *B<SSL_SESSION_get_app_data>(SSL_SESSION *s); =item char *B<SSL_SESSION_get_ex_data>(const SSL_SESSION *s, int idx); =item int B<SSL_SESSION_get_ex_new_index>(long argl, char *argp, int (*new_func);(void), int (*dup_func)(void), void (*free_func)(void)) =item long B<SSL_SESSION_get_time>(const SSL_SESSION *s); =item long B<SSL_SESSION_get_timeout>(const SSL_SESSION *s); =item unsigned long B<SSL_SESSION_hash>(const SSL_SESSION *a); =item SSL_SESSION *B<SSL_SESSION_new>(void); =item int B<SSL_SESSION_print>(BIO *bp, const SSL_SESSION *x); =item int B<SSL_SESSION_print_fp>(FILE *fp, const SSL_SESSION *x); =item int B<SSL_SESSION_set_app_data>(SSL_SESSION *s, char *a); =item int B<SSL_SESSION_set_ex_data>(SSL_SESSION *s, int idx, char *arg); =item long B<SSL_SESSION_set_time>(SSL_SESSION *s, long t); =item long B<SSL_SESSION_set_timeout>(SSL_SESSION *s, long t); =back =head2 Dealing with Connections Here we document the various API functions which deal with the SSL/TLS connection defined in the B<SSL> structure. =over 4 =item int B<SSL_accept>(SSL *ssl); =item int B<SSL_add_dir_cert_subjects_to_stack>(STACK *stack, const char *dir); =item int B<SSL_add_file_cert_subjects_to_stack>(STACK *stack, const char *file); =item int B<SSL_add_client_CA>(SSL *ssl, X509 *x); =item char *B<SSL_alert_desc_string>(int value); =item char *B<SSL_alert_desc_string_long>(int value); =item char *B<SSL_alert_type_string>(int value); =item char *B<SSL_alert_type_string_long>(int value); =item int B<SSL_check_private_key>(const SSL *ssl); =item void B<SSL_clear>(SSL *ssl); =item long B<SSL_clear_num_renegotiations>(SSL *ssl); =item int B<SSL_connect>(SSL *ssl); =item int B<SSL_copy_session_id>(SSL *t, const SSL *f); Sets the session details for B<t> to be the same as in B<f>. Returns 1 on success or 0 on failure. =item long B<SSL_ctrl>(SSL *ssl, int cmd, long larg, char *parg); =item int B<SSL_do_handshake>(SSL *ssl); =item SSL *B<SSL_dup>(SSL *ssl); SSL_dup() allows applications to configure an SSL handle for use in multiple SSL connections, and then duplicate it prior to initiating each connection with the duplicated handle. Use of SSL_dup() avoids the need to repeat the configuration of the handles for each connection. This is used internally by L<BIO_s_accept(3)> to construct per-connection SSL handles after L<accept(2)>. For SSL_dup() to work, the connection MUST be in its initial state and MUST NOT have not yet have started the SSL handshake. For connections that are not in their initial state SSL_dup() just increments an internal reference count and returns the I<same> handle. It may be possible to use L<SSL_clear(3)> to recycle an SSL handle that is not in its initial state for re-use, but this is best avoided. Instead, save and restore the session, if desired, and construct a fresh handle for each connection. =item STACK *B<SSL_dup_CA_list>(STACK *sk); =item void B<SSL_free>(SSL *ssl); =item SSL_CTX *B<SSL_get_SSL_CTX>(const SSL *ssl); =item char *B<SSL_get_app_data>(SSL *ssl); =item X509 *B<SSL_get_certificate>(const SSL *ssl); =item const char *B<SSL_get_cipher>(const SSL *ssl); =item int B<SSL_is_dtls>(const SSL *ssl); =item int B<SSL_get_cipher_bits>(const SSL *ssl, int *alg_bits); =item char *B<SSL_get_cipher_list>(const SSL *ssl, int n); =item char *B<SSL_get_cipher_name>(const SSL *ssl); =item char *B<SSL_get_cipher_version>(const SSL *ssl); =item STACK *B<SSL_get_ciphers>(const SSL *ssl); =item STACK *B<SSL_get_client_CA_list>(const SSL *ssl); =item SSL_CIPHER *B<SSL_get_current_cipher>(SSL *ssl); =item long B<SSL_get_default_timeout>(const SSL *ssl); =item int B<SSL_get_error>(const SSL *ssl, int i); =item char *B<SSL_get_ex_data>(const SSL *ssl, int idx); =item int B<SSL_get_ex_data_X509_STORE_CTX_idx>(void); =item int B<SSL_get_ex_new_index>(long argl, char *argp, int (*new_func);(void), int (*dup_func)(void), void (*free_func)(void)) =item int B<SSL_get_fd>(const SSL *ssl); =item void (*B<SSL_get_info_callback>(const SSL *ssl);)() =item STACK *B<SSL_get_peer_cert_chain>(const SSL *ssl); =item X509 *B<SSL_get_peer_certificate>(const SSL *ssl); =item const STACK_OF(SCT) *B<SSL_get0_peer_scts>(SSL *s); =item EVP_PKEY *B<SSL_get_privatekey>(const SSL *ssl); =item int B<SSL_get_quiet_shutdown>(const SSL *ssl); =item BIO *B<SSL_get_rbio>(const SSL *ssl); =item int B<SSL_get_read_ahead>(const SSL *ssl); =item SSL_SESSION *B<SSL_get_session>(const SSL *ssl); =item char *B<SSL_get_shared_ciphers>(const SSL *ssl, char *buf, int len); =item int B<SSL_get_shutdown>(const SSL *ssl); =item const SSL_METHOD *B<SSL_get_ssl_method>(SSL *ssl); =item int B<SSL_get_state>(const SSL *ssl); =item long B<SSL_get_time>(const SSL *ssl); =item long B<SSL_get_timeout>(const SSL *ssl); =item int (*B<SSL_get_verify_callback>(const SSL *ssl))(int, X509_STORE_CTX *) =item int B<SSL_get_verify_mode>(const SSL *ssl); =item long B<SSL_get_verify_result>(const SSL *ssl); =item char *B<SSL_get_version>(const SSL *ssl); =item BIO *B<SSL_get_wbio>(const SSL *ssl); =item int B<SSL_in_accept_init>(SSL *ssl); =item int B<SSL_in_before>(SSL *ssl); =item int B<SSL_in_connect_init>(SSL *ssl); =item int B<SSL_in_init>(SSL *ssl); =item int B<SSL_is_init_finished>(SSL *ssl); =item STACK *B<SSL_load_client_CA_file>(const char *file); =item SSL *B<SSL_new>(SSL_CTX *ctx); =item int SSL_up_ref(SSL *s); =item long B<SSL_num_renegotiations>(SSL *ssl); =item int B<SSL_peek>(SSL *ssl, void *buf, int num); =item int B<SSL_pending>(const SSL *ssl); =item int B<SSL_read>(SSL *ssl, void *buf, int num); =item int B<SSL_renegotiate>(SSL *ssl); =item char *B<SSL_rstate_string>(SSL *ssl); =item char *B<SSL_rstate_string_long>(SSL *ssl); =item long B<SSL_session_reused>(SSL *ssl); =item void B<SSL_set_accept_state>(SSL *ssl); =item void B<SSL_set_app_data>(SSL *ssl, char *arg); =item void B<SSL_set_bio>(SSL *ssl, BIO *rbio, BIO *wbio); =item int B<SSL_set_cipher_list>(SSL *ssl, char *str); =item void B<SSL_set_client_CA_list>(SSL *ssl, STACK *list); =item void B<SSL_set_connect_state>(SSL *ssl); =item int B<SSL_set_ct_validation_callback>(SSL *ssl, ssl_ct_validation_cb callback, void *arg); =item int B<SSL_set_ex_data>(SSL *ssl, int idx, char *arg); =item int B<SSL_set_fd>(SSL *ssl, int fd); =item void B<SSL_set_info_callback>(SSL *ssl, void (*cb);(void)) =item void B<SSL_set_msg_callback>(SSL *ctx, void (*cb)(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg)); =item void B<SSL_set_msg_callback_arg>(SSL *ctx, void *arg); =item unsigned long B<SSL_clear_options>(SSL *ssl, unsigned long op); =item unsigned long B<SSL_get_options>(SSL *ssl); =item unsigned long B<SSL_set_options>(SSL *ssl, unsigned long op); =item void B<SSL_set_quiet_shutdown>(SSL *ssl, int mode); =item void B<SSL_set_read_ahead>(SSL *ssl, int yes); =item int B<SSL_set_rfd>(SSL *ssl, int fd); =item int B<SSL_set_session>(SSL *ssl, SSL_SESSION *session); =item void B<SSL_set_shutdown>(SSL *ssl, int mode); =item int B<SSL_set_ssl_method>(SSL *ssl, const SSL_METHOD *meth); =item void B<SSL_set_time>(SSL *ssl, long t); =item void B<SSL_set_timeout>(SSL *ssl, long t); =item void B<SSL_set_verify>(SSL *ssl, int mode, int (*callback);(void)) =item void B<SSL_set_verify_result>(SSL *ssl, long arg); =item int B<SSL_set_wfd>(SSL *ssl, int fd); =item int B<SSL_shutdown>(SSL *ssl); =item OSSL_HANDSHAKE_STATE B<SSL_get_state>(const SSL *ssl); Returns the current handshake state. =item char *B<SSL_state_string>(const SSL *ssl); =item char *B<SSL_state_string_long>(const SSL *ssl); =item long B<SSL_total_renegotiations>(SSL *ssl); =item int B<SSL_use_PrivateKey>(SSL *ssl, EVP_PKEY *pkey); =item int B<SSL_use_PrivateKey_ASN1>(int type, SSL *ssl, unsigned char *d, long len); =item int B<SSL_use_PrivateKey_file>(SSL *ssl, const char *file, int type); =item int B<SSL_use_RSAPrivateKey>(SSL *ssl, RSA *rsa); =item int B<SSL_use_RSAPrivateKey_ASN1>(SSL *ssl, unsigned char *d, long len); =item int B<SSL_use_RSAPrivateKey_file>(SSL *ssl, const char *file, int type); =item int B<SSL_use_certificate>(SSL *ssl, X509 *x); =item int B<SSL_use_certificate_ASN1>(SSL *ssl, int len, unsigned char *d); =item int B<SSL_use_certificate_file>(SSL *ssl, const char *file, int type); =item int B<SSL_version>(const SSL *ssl); =item int B<SSL_want>(const SSL *ssl); =item int B<SSL_want_nothing>(const SSL *ssl); =item int B<SSL_want_read>(const SSL *ssl); =item int B<SSL_want_write>(const SSL *ssl); =item int B<SSL_want_x509_lookup>(const SSL *ssl); =item int B<SSL_write>(SSL *ssl, const void *buf, int num); =item void B<SSL_set_psk_client_callback>(SSL *ssl, unsigned int (*callback)(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len)); =item int B<SSL_use_psk_identity_hint>(SSL *ssl, const char *hint); =item void B<SSL_set_psk_server_callback>(SSL *ssl, unsigned int (*callback)(SSL *ssl, const char *identity, unsigned char *psk, int max_psk_len)); =item const char *B<SSL_get_psk_identity_hint>(SSL *ssl); =item const char *B<SSL_get_psk_identity>(SSL *ssl); =back =head1 RETURN VALUES See the individual manual pages for details. =head1 SEE ALSO L<openssl(1)>, L<crypto(3)>, L<CRYPTO_get_ex_new_index(3)>, L<SSL_accept(3)>, L<SSL_clear(3)>, L<SSL_connect(3)>, L<SSL_CIPHER_get_name(3)>, L<SSL_COMP_add_compression_method(3)>, L<SSL_CTX_add_extra_chain_cert(3)>, L<SSL_CTX_add_session(3)>, L<SSL_CTX_ctrl(3)>, L<SSL_CTX_flush_sessions(3)>, L<SSL_CTX_get_verify_mode(3)>, L<SSL_CTX_load_verify_locations(3)> L<SSL_CTX_new(3)>, L<SSL_CTX_sess_number(3)>, L<SSL_CTX_sess_set_cache_size(3)>, L<SSL_CTX_sess_set_get_cb(3)>, L<SSL_CTX_sessions(3)>, L<SSL_CTX_set_cert_store(3)>, L<SSL_CTX_set_cert_verify_callback(3)>, L<SSL_CTX_set_cipher_list(3)>, L<SSL_CTX_set_client_CA_list(3)>, L<SSL_CTX_set_client_cert_cb(3)>, L<SSL_CTX_set_default_passwd_cb(3)>, L<SSL_CTX_set_generate_session_id(3)>, L<SSL_CTX_set_info_callback(3)>, L<SSL_CTX_set_max_cert_list(3)>, L<SSL_CTX_set_mode(3)>, L<SSL_CTX_set_msg_callback(3)>, L<SSL_CTX_set_options(3)>, L<SSL_CTX_set_quiet_shutdown(3)>, L<SSL_CTX_set_read_ahead(3)>, L<SSL_CTX_set_session_cache_mode(3)>, L<SSL_CTX_set_session_id_context(3)>, L<SSL_CTX_set_ssl_version(3)>, L<SSL_CTX_set_timeout(3)>, L<SSL_CTX_set_tmp_dh_callback(3)>, L<SSL_CTX_set_verify(3)>, L<SSL_CTX_use_certificate(3)>, L<SSL_alert_type_string(3)>, L<SSL_do_handshake(3)>, L<SSL_enable_ct(3)>, L<SSL_get_SSL_CTX(3)>, L<SSL_get_ciphers(3)>, L<SSL_get_client_CA_list(3)>, L<SSL_get_default_timeout(3)>, L<SSL_get_error(3)>, L<SSL_get_ex_data_X509_STORE_CTX_idx(3)>, L<SSL_get_fd(3)>, L<SSL_get_peer_cert_chain(3)>, L<SSL_get_rbio(3)>, L<SSL_get_session(3)>, L<SSL_get_verify_result(3)>, L<SSL_get_version(3)>, L<SSL_load_client_CA_file(3)>, L<SSL_new(3)>, L<SSL_pending(3)>, L<SSL_read(3)>, L<SSL_rstate_string(3)>, L<SSL_session_reused(3)>, L<SSL_set_bio(3)>, L<SSL_set_connect_state(3)>, L<SSL_set_fd(3)>, L<SSL_set_session(3)>, L<SSL_set_shutdown(3)>, L<SSL_shutdown(3)>, L<SSL_state_string(3)>, L<SSL_want(3)>, L<SSL_write(3)>, L<SSL_SESSION_free(3)>, L<SSL_SESSION_get_time(3)>, L<d2i_SSL_SESSION(3)>, L<SSL_CTX_set_psk_client_callback(3)>, L<SSL_CTX_use_psk_identity_hint(3)>, L<SSL_get_psk_identity(3)>, L<DTLSv1_listen(3)> =head1 HISTORY B<SSLv2_client_method>, B<SSLv2_server_method> and B<SSLv2_method> where removed in OpenSSL 1.1.0. The return type of B<SSL_copy_session_id> was changed from void to int in OpenSSL 1.1.0. =head1 COPYRIGHT Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. Licensed under the OpenSSL license (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at L<https://www.openssl.org/source/license.html>. =cut
GaloisInc/hacrypto
src/C/openssl/openssl-1.1.0b/doc/ssl/ssl.pod
Perl
bsd-3-clause
25,886
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. package AI::MXNetCAPI; use base qw(DynaLoader); bootstrap AI::MXNetCAPI; our $VERSION = '1.0102'; 1; __END__ =head1 NAME AI::MXNetCAPI - Swig interface to mxnet c api =head1 SYNOPSIS use AI::MXNetCAPI; =head1 DESCRIPTION This module provides interface to mxnet via its api. =head1 SEE ALSO L<AI::MXNet> =head1 AUTHOR Sergey Kolychev, <sergeykolychev.github@gmail.com> =head1 COPYRIGHT & LICENSE Copyright 2017 Sergey Kolychev. This library is licensed under Apache 2.0 license. See https://www.apache.org/licenses/LICENSE-2.0 for more information. =cut
saurabh3949/mxnet
perl-package/AI-MXNetCAPI/lib/AI/MXNetCAPI.pm
Perl
apache-2.0
1,355
package Digest::MD5; use strict; use vars qw($VERSION @ISA @EXPORT_OK); $VERSION = '2.36_01'; # $Date: 2005/11/30 13:46:47 $ require Exporter; *import = \&Exporter::import; @EXPORT_OK = qw(md5 md5_hex md5_base64); eval { require Digest::base; push(@ISA, 'Digest::base'); }; if ($@) { my $err = $@; *add_bits = sub { die $err }; } eval { require XSLoader; XSLoader::load('Digest::MD5', $VERSION); }; if ($@) { my $olderr = $@; eval { # Try to load the pure perl version require Digest::Perl::MD5; Digest::Perl::MD5->import(qw(md5 md5_hex md5_base64)); push(@ISA, "Digest::Perl::MD5"); # make OO interface work }; if ($@) { # restore the original error die $olderr; } } else { *reset = \&new; } 1; __END__ =head1 NAME Digest::MD5 - Perl interface to the MD5 Algorithm =head1 SYNOPSIS # Functional style use Digest::MD5 qw(md5 md5_hex md5_base64); $digest = md5($data); $digest = md5_hex($data); $digest = md5_base64($data); # OO style use Digest::MD5; $ctx = Digest::MD5->new; $ctx->add($data); $ctx->addfile(*FILE); $digest = $ctx->digest; $digest = $ctx->hexdigest; $digest = $ctx->b64digest; =head1 DESCRIPTION The C<Digest::MD5> module allows you to use the RSA Data Security Inc. MD5 Message Digest algorithm from within Perl programs. The algorithm takes as input a message of arbitrary length and produces as output a 128-bit "fingerprint" or "message digest" of the input. Note that the MD5 algorithm is not as strong as it used to be. It has since 2005 been easy to generate different messages that produce the same MD5 digest. It still seems hard to generate messages that produce a given digest, but it is probably wise to move to stronger algorithms for applications that depend on the digest to uniquely identify a message. The C<Digest::MD5> module provide a procedural interface for simple use, as well as an object oriented interface that can handle messages of arbitrary length and which can read files directly. =head1 FUNCTIONS The following functions are provided by the C<Digest::MD5> module. None of these functions are exported by default. =over 4 =item md5($data,...) This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form. The returned string will be 16 bytes long. The result of md5("a", "b", "c") will be exactly the same as the result of md5("abc"). =item md5_hex($data,...) Same as md5(), but will return the digest in hexadecimal form. The length of the returned string will be 32 and it will only contain characters from this set: '0'..'9' and 'a'..'f'. =item md5_base64($data,...) Same as md5(), but will return the digest as a base64 encoded string. The length of the returned string will be 22 and it will only contain characters from this set: 'A'..'Z', 'a'..'z', '0'..'9', '+' and '/'. Note that the base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded md5 digests you might want to append the redundant string "==" to the result. =back =head1 METHODS The object oriented interface to C<Digest::MD5> is described in this section. After a C<Digest::MD5> object has been created, you will add data to it and finally ask for the digest in a suitable format. A single object can be used to calculate multiple digests. The following methods are provided: =over 4 =item $md5 = Digest::MD5->new The constructor returns a new C<Digest::MD5> object which encapsulate the state of the MD5 message-digest algorithm. If called as an instance method (i.e. $md5->new) it will just reset the state the object to the state of a newly created object. No new object is created in this case. =item $md5->reset This is just an alias for $md5->new. =item $md5->clone This a copy of the $md5 object. It is useful when you do not want to destroy the digests state, but need an intermediate value of the digest, e.g. when calculating digests iteratively on a continuous data stream. Example: my $md5 = Digest::MD5->new; while (<>) { $md5->add($_); print "Line $.: ", $md5->clone->hexdigest, "\n"; } =item $md5->add($data,...) The $data provided as argument are appended to the message we calculate the digest for. The return value is the $md5 object itself. All these lines will have the same effect on the state of the $md5 object: $md5->add("a"); $md5->add("b"); $md5->add("c"); $md5->add("a")->add("b")->add("c"); $md5->add("a", "b", "c"); $md5->add("abc"); =item $md5->addfile($io_handle) The $io_handle will be read until EOF and its content appended to the message we calculate the digest for. The return value is the $md5 object itself. The addfile() method will croak() if it fails reading data for some reason. If it croaks it is unpredictable what the state of the $md5 object will be in. The addfile() method might have been able to read the file partially before it failed. It is probably wise to discard or reset the $md5 object if this occurs. In most cases you want to make sure that the $io_handle is in C<binmode> before you pass it as argument to the addfile() method. =item $md5->add_bits($data, $nbits) =item $md5->add_bits($bitstring) Since the MD5 algorithm is byte oriented you might only add bits as multiples of 8, so you probably want to just use add() instead. The add_bits() method is provided for compatibility with other digest implementations. See L<Digest> for description of the arguments that add_bits() take. =item $md5->digest Return the binary digest for the message. The returned string will be 16 bytes long. Note that the C<digest> operation is effectively a destructive, read-once operation. Once it has been performed, the C<Digest::MD5> object is automatically C<reset> and can be used to calculate another digest value. Call $md5->clone->digest if you want to calculate the digest without resetting the digest state. =item $md5->hexdigest Same as $md5->digest, but will return the digest in hexadecimal form. The length of the returned string will be 32 and it will only contain characters from this set: '0'..'9' and 'a'..'f'. =item $md5->b64digest Same as $md5->digest, but will return the digest as a base64 encoded string. The length of the returned string will be 22 and it will only contain characters from this set: 'A'..'Z', 'a'..'z', '0'..'9', '+' and '/'. The base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded md5 digests you might want to append the string "==" to the result. =back =head1 EXAMPLES The simplest way to use this library is to import the md5_hex() function (or one of its cousins): use Digest::MD5 qw(md5_hex); print "Digest is ", md5_hex("foobarbaz"), "\n"; The above example would print out the message: Digest is 6df23dc03f9b54cc38a0fc1483df6e21 The same checksum can also be calculated in OO style: use Digest::MD5; $md5 = Digest::MD5->new; $md5->add('foo', 'bar'); $md5->add('baz'); $digest = $md5->hexdigest; print "Digest is $digest\n"; With OO style you can break the message arbitrary. This means that we are no longer limited to have space for the whole message in memory, i.e. we can handle messages of any size. This is useful when calculating checksum for files: use Digest::MD5; my $file = shift || "/etc/passwd"; open(FILE, $file) or die "Can't open '$file': $!"; binmode(FILE); $md5 = Digest::MD5->new; while (<FILE>) { $md5->add($_); } close(FILE); print $md5->b64digest, " $file\n"; Or we can use the addfile method for more efficient reading of the file: use Digest::MD5; my $file = shift || "/etc/passwd"; open(FILE, $file) or die "Can't open '$file': $!"; binmode(FILE); print Digest::MD5->new->addfile(*FILE)->hexdigest, " $file\n"; Perl 5.8 support Unicode characters in strings. Since the MD5 algorithm is only defined for strings of bytes, it can not be used on strings that contains chars with ordinal number above 255. The MD5 functions and methods will croak if you try to feed them such input data: use Digest::MD5 qw(md5_hex); my $str = "abc\x{300}"; print md5_hex($str), "\n"; # croaks # Wide character in subroutine entry What you can do is calculate the MD5 checksum of the UTF-8 representation of such strings. This is achieved by filtering the string through encode_utf8() function: use Digest::MD5 qw(md5_hex); use Encode qw(encode_utf8); my $str = "abc\x{300}"; print md5_hex(encode_utf8($str)), "\n"; # 8c2d46911f3f5a326455f0ed7a8ed3b3 =head1 SEE ALSO L<Digest>, L<Digest::MD2>, L<Digest::SHA1>, L<Digest::HMAC> L<md5sum(1)> RFC 1321 http://en.wikipedia.org/wiki/MD5 The paper "How to Break MD5 and Other Hash Functions" by Xiaoyun Wang and Hongbo Yu. =head1 COPYRIGHT This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Copyright 1998-2003 Gisle Aas. Copyright 1995-1996 Neil Winton. Copyright 1991-1992 RSA Data Security, Inc. The MD5 algorithm is defined in RFC 1321. This implementation is derived from the reference C code in RFC 1321 which is covered by the following copyright statement: =over 4 =item Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights reserved. License to copy and use this software is granted provided that it is identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing this software or this function. License is also granted to make and use derivative works provided that such works are identified as "derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm" in all material mentioning or referencing the derived work. RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided "as is" without express or implied warranty of any kind. These notices must be retained in any copies of any part of this documentation and/or software. =back This copyright does not prohibit distribution of any version of Perl containing this extension under the terms of the GNU or Artistic licenses. =head1 AUTHORS The original C<MD5> interface was written by Neil Winton (C<N.Winton@axion.bt.co.uk>). The C<Digest::MD5> module is written by Gisle Aas <gisle@ActiveState.com>. =cut
leighpauls/k2cro4
third_party/cygwin/lib/perl5/5.10/i686-cygwin/Digest/MD5.pm
Perl
bsd-3-clause
10,594
=pod =head1 NAME d2i_X509_NAME, i2d_X509_NAME - X509_NAME encoding functions =head1 SYNOPSIS #include <openssl/x509.h> X509_NAME *d2i_X509_NAME(X509_NAME **a, unsigned char **pp, long length); int i2d_X509_NAME(X509_NAME *a, unsigned char **pp); =head1 DESCRIPTION These functions decode and encode an B<X509_NAME> structure which is the same as the B<Name> type defined in RFC2459 (and elsewhere) and used for example in certificate subject and issuer names. Othewise the functions behave in a similar way to d2i_X509() and i2d_X509() described in the L<d2i_X509(3)|d2i_X509(3)> manual page. =head1 SEE ALSO L<d2i_X509(3)|d2i_X509(3)> =head1 HISTORY TBA =cut
dkoontz/nodegit
vendor/openssl/openssl/doc/crypto/d2i_X509_NAME.pod
Perl
mit
676
:- encoding(utf8). :- module( dcg, [ '...'//0, '...'//1, % -Codes add_indent//1, % +Indent alpha//1, % ?Code alphanum//1, % ?Code atom_phrase/2, % :Dcg_0, ?Atom atom_phrase/3, % :Dcg_0, +Atom1, ?Atom2 dcg_atom//2, % :Dcg_1, ?Atom dcg_between//2, % +Low, +High dcg_between//3, % +Low, +High, ?Code dcg_boolean//1, % ?Boolean dcg_call//1, % :Dcg_0 dcg_call//2, % :Dcg_1, ?Arg1 dcg_call//3, % :Dcg_2, ?Arg1, ?Arg2 dcg_call//4, % :Dcg_3, ?Arg1, ?Arg2, ?Arg3 dcg_call//5, % :Dcg_4, ?Arg1, ?Arg2, ?Arg3, ?Arg4 dcg_call//6, % :Dcg_5, ?Arg1, ?Arg2, ?Arg3, ?Arg4, ?Arg5 dcg_char//1, % ?Char dcg_peek//1, % +Length dcg_pp_boolean//1, % +Boolean dcg_string//2, % :Dcg_1, ?String dcg_with_output_to/1, % :Dcg_0 dcg_with_output_to/2, % +Sink, :Dcg_0 default//2, % :Dcg_0, ?Default_0 digit_weight//1, % ?N ellipsis//2, % +Atom, +MaxLength error_location/2, % +SyntaxError, +Input, +Length error_location/3, % +SyntaxError, +Input, +Length indent//1, % +Indent must_see//1, % :Dcg_0 must_see_code//2, % +Code, :Skip_0 nl//0, nonblank//0, nonblanks//0, parsing//0, remainder_as_atom//1, % -Remainder remainder_as_string//1, % -Remainder string_phrase/2, % :Dcg_0, ?String string_phrase/3, % :Dcg_0, +String1, -String2 tab//1, % +N term//1, % +Term thousands//1, % +N ws//0 ] ). :- reexport(library(dcg/basics)). /** <module> Extended support for DCGs */ :- use_module(library(pure_input)). :- use_module(library(code_ext)). :- use_module(library(list_ext)). :- use_module(library(string_ext)). :- meta_predicate atom_phrase(//, ?), atom_phrase(//, ?, ?), dcg_atom(3, ?, ?, ?), dcg_call(//, ?, ?), dcg_call(3, ?, ?, ?), dcg_call(4, ?, ?, ?, ?), dcg_call(5, ?, ?, ?, ?, ?), dcg_call(6, ?, ?, ?, ?, ?, ?), dcg_call(7, ?, ?, ?, ?, ?, ?, ?), dcg_string(3, ?, ?, ?), dcg_with_output_to(//), dcg_with_output_to(+, //), default(//, //, ?, ?), must_see(//, ?, ?), must_see_code(+, //, ?, ?), string_phrase(//, ?), string_phrase(//, ?, ?). %! ...// . %! ...(-Codes:list(code))// . % % Wrapper around string//1. ... --> ...(_). ...(Codes) --> string(Codes). %! add_indent(+Indent:positive_integer)// . add_indent(N), "\n", indent(N) --> "\n", !, add_indent(N). add_indent(N), [Code] --> [Code], !, add_indent(N). add_indent(_) --> "". %! alpha// . %! alpha(?Code:code)// . alpha --> alpha(_). alpha(Code) --> dcg_between(0'a, 0'z, Code). alpha(Code) --> dcg_between(0'A, 0'Z, Code). %! alphanum(?Code:code)// . alphanum(Code) --> alpha(Code). alphanum(Code) --> digit(Code). %! atom_phrase(:Dcg_0, ?Atom:atom)// is nondet. %! atom_phrase(:Dcg_0, +Atom1:atomic, ?Atom2:atom)// is nondet. atom_phrase(Dcg_0, Atom) :- var(Atom), !, phrase(Dcg_0, Codes), atom_codes(Atom, Codes). atom_phrase(Dcg_0, Atom) :- atom_codes(Atom, Codes), phrase(Dcg_0, Codes). atom_phrase(Dcg_0, Atom1, Atom2) :- must_be(atom, Atom1), atom_codes(Atom1, Codes1), phrase(Dcg_0, Codes1, Codes2), atom_codes(Atom2, Codes2). %! dcg_atom(:Dcg_1, ?Atom:atom)// . % % This meta-DCG rule handles the translation between the word and the % character level of parsing/generating. % % Typically, grammar *A* specifies how words can be formed out of % characters. A character is a code, and a word is a list of codes. % Grammar *B* specifies how sentences can be built out of words. Now % the word is an atom, and the sentences in a list of atoms. % % This means that at some point, words in grammar *A*, i.e. lists of % codes, need to be translated to words in grammar *B*, i.e. atoms. % % This is where dcg_atom//2 comes in. We illustrate this with a % schematic example: % % ```prolog % sentence([W1,...,Wn]) --> % word2(W1), % ..., % word2(Wn). % % word2(W) --> % dcg_atom(word1, W). % % word1([C1, ..., Cn]) --> % char(C1), % ..., % char(Cn). % ``` % % @throws instantiation_error % @throws type_error dcg_atom(Dcg_1, Atom) --> {var(Atom)}, !, dcg_call(Dcg_1, Codes), {atom_codes(Atom, Codes)}. dcg_atom(Dcg_1, Atom) --> {atom_codes(Atom, Codes)}, dcg_call(Dcg_1, Codes). %! dcg_between(+Low:nonneg, +High:nonneg)// . %! dcg_between(+Low:nonneg, +High:nonneg, ?Code:nonneg)// . dcg_between(Low, High) --> dcg_between(Low, High, _). dcg_between(Low, High, Code) --> [Code], {between(Low, High, Code)}. %! dcg_boolean(+Boolean:boolean)// is det. %! dcg_boolean(-Boolean:boolean)// is det. dcg_boolean(false) --> "false". dcg_boolean(true) --> "true". %! dcg_call(:Dcg_0)// . %! dcg_call(:Dcg_1, ?Arg1)// . %! dcg_call(:Dcg_2, ?Arg1, ?Arg2)// . %! dcg_call(:Dcg_3, ?Arg1, ?Arg2, ?Arg3)// . %! dcg_call(:Dcg_4, ?Arg1, ?Arg2, ?Arg3, ?Arg4)// . %! dcg_call(:Dcg_5, ?Arg1, ?Arg2, ?Arg3, ?Arg4, ?Arg5)// . % % @see call/[1-8] dcg_call(Dcg_0, X, Y) :- call(Dcg_0, X, Y). dcg_call(Dcg_1, Arg1, X, Y) :- call(Dcg_1, Arg1, X, Y). dcg_call(Dcg_2, Arg1, Arg2, X, Y) :- call(Dcg_2, Arg1, Arg2, X, Y). dcg_call(Dcg_3, Arg1, Arg2, Arg3, X, Y) :- call(Dcg_3, Arg1, Arg2, Arg3, X, Y). dcg_call(Dcg_4, Arg1, Arg2, Arg3, Arg4, X, Y) :- call(Dcg_4, Arg1, Arg2, Arg3, Arg4, X, Y). dcg_call(Dcg_5, Arg1, Arg2, Arg3, Arg4, Arg5, X, Y) :- call(Dcg_5, Arg1, Arg2, Arg3, Arg4, Arg5, X, Y). %! dcg_char(+Char:char)//. %! dcg_char(-Char:char)//. dcg_char(Char) --> {var(Char)}, !, [Code], {char_code(Char, Code)}. dcg_char(Char) --> {char_code(Char, Code)}, [Code]. %! dcg_peek(+Length:nonneg)// . dcg_peek(Len, Codes, Codes) :- length(Prefix, Len), prefix(Prefix, Codes), string_codes(String, Prefix), format(user_output, "\n|~s|\n", [String]). %! dcg_pp_boolean(+Boolean:boolean)// is det. dcg_pp_boolean(false) --> !, "❌". dcg_pp_boolean(true) --> "βœ“". %! dcg_string(:Dcg_1, ?String)// . dcg_string(Dcg_1, String) --> {var(String)}, !, dcg_call(Dcg_1, Codes), {string_codes(String, Codes)}. dcg_string(Dcg_1, String) --> {string_codes(String, Codes)}, dcg_call(Dcg_1, Codes). %! dcg_with_output_to(:Dcg_0) is nondet. %! dcg_with_output_to(+Sink, :Dcg_0) is nondet. dcg_with_output_to(Dcg_0) :- dcg_with_output_to(current_output, Dcg_0). dcg_with_output_to(Sink, Dcg_0) :- phrase(Dcg_0, Codes), with_output_to(Sink, put_codes(Codes)). %! default(:Dcg_0, ?Default_0)// . default(Dcg_0, _) --> Dcg_0, !. default(_, Default_0) --> Default_0. %! digit_weight(?Weight:between(0,9))// . digit_weight(Weight) --> parsing, !, [Code], {code_type(Code, digit(Weight))}. digit_weight(Weight) --> {code_type(Code, digit(Weight))}, [Code]. %! ellipsis(+Original:text, +MaxLength:beteen(2,inf))// is det. % % @param MaxLength The maximum length of the generated ellipsed % string. ellipsis(Original, MaxLength) --> {string_ellipsis(Original, MaxLength, Ellipsed)}, atom(Ellipsed). %! error_location(+SyntaxError:compound, +Input:list(code)) is det. %! error_location(+SyntaxError:compound, +Input:list(code), +Length:nonneg) is det. error_location(Error, Input) :- error_location(Error, Input, 80). error_location(error(syntax_error(What),Location), Input, Length) :- subsumes_term(end_of_file-CharCount, Location), end_of_file-CharCount = Location, length(After, CharCount), % BUG: Should have detected determinism. once(append(Before, After, Input)), length(Before, BL), string_codes("…", Elipsis), string_codes("\n**here**\n", Here), ( BL =< Length -> BC = Before ; length(BC0, Length), % BUG: Should have detected determinism. once(append(_, BC0, Before)), append(Elipsis, BC0, BC) ), length(After, AL), ( AL =< Length -> AC = After ; length(AC0, Length), % BUG: Should have detected determinism. once(append(AC0, _, After)), append(AC0, Elipsis, AC) ), % BUG: Should have detected determinism. once(append(Here, AC, HAC)), append([0'\n|BC], HAC, ContextCodes), string_codes(Context, ContextCodes), !, syntax_error(error_location(What,Context)). error_location(Error, _, _) :- throw(Error). %! indent(+Indent:nonneg)// is det. indent(0) --> !, "". indent(N1) --> " ", !, {N2 is N1 - 1}, indent(N2). %! must_see(:Dcg_0)// . must_see(Dcg_0, X, Y) :- call(Dcg_0, X, Y), !. must_see(_:Dcg_0) --> { Dcg_0 =.. [Pred|_], format(string(Call), "~w", [Dcg_0]) }, syntax_error(expected(Pred,Call)). %! must_see_code(+Code, :Skip_0)// . must_see_code(Code, Skip_0) --> [Code], !, Skip_0. must_see_code(Code, _) --> {char_code(Char, Code)}, syntax_error(expected(Char)). %! nl// is det. nl --> "\n". %! nonblank// . % % Wrapper around nonblank//1 from library(dcg/basics). nonblank --> nonblank(_). %! nonblanks// . nonblanks --> nonblanks(_). %! parsing// is semidet. % % Succeeds if currently parsing a list of codes (rather than % generating a list of codes). parsing(H, H) :- nonvar(H). %! remainder_as_atom(-Atom:atom)// is det. remainder_as_atom(Atom) --> remainder(Codes), {atom_codes(Atom, Codes)}. %! remainder_as_string(-Remainder:string)// is det. remainder_as_string(String) --> remainder(Codes), {string_codes(String, Codes)}. %! string_phrase(:Dcg_0, ?String) is nondet. %! string_phrase(:Dcg_0, +String1, ?String2) is nondet. string_phrase(Dcg_0, String) :- var(String), !, phrase(Dcg_0, Codes), string_codes(String, Codes). string_phrase(Dcg_0, String) :- string_codes(String, Codes), phrase(Dcg_0, Codes). string_phrase(Dcg_0, String1, String2) :- string_codes(String1, Codes1), phrase(Dcg_0, Codes1, Codes2), string_codes(String2, Codes2). %! tab(+N:nonneg)// is det. tab(0) --> !, "". tab(N1) --> " ", {N2 is N1 - 1}, tab(N2). %! term(+Term)// is det. term(Term) --> {format(atom(Atom), "~w", [Term])}, atom(Atom). %! thousands(+N:integer)// is det. thousands(N) --> {format(atom(Atom), "~D", [N])}, atom(Atom). %! ws// is det. ws --> white. % NO-BREAK SPACE (0240, 0xA0) ws --> [160].
wouterbeek/Prolog_Library_Collection
prolog/dcg.pl
Perl
mit
10,519
#lang pollen β—Š(require pollen/unstable/convert) β—Šh2{Table of contents} β—Štoc[] β—Šheadappendix[ β—Šlink[#:href "//cdn-images.mailchimp.com/embedcode/classic-10_7.css" #:rel "stylesheet" #:type "text/css"] β—Šstyle[#:type "text/css"]{#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }} ] β—Šdiv[#:id "mc_embed_signup"]{ β—Šform[#:action "//telenet.us16.list-manage.com/subscribe/post?u=a12fcdf12f48c319029ffe244&amp;id=d25ea0e7ac" #:class "validate" #:id "mc-embedded-subscribe-form" #:method "post" #:name "mc-embedded-subscribe-form" #:novalidate "novalidate" #:target "_blank"]{ β—Šdiv[#:id "mc_embed_signup_scroll"]{ β—Šh2{Subscribe for updates about completed chapters} β—Šdiv[#:class "mc-field-group"]{ β—Šlabel[#:for "mce-EMAIL"]{Email Address } β—Šinput[#:class "required email" #:id "mce-EMAIL" #:name "EMAIL" #:type "email" #:value ""]{ }} β—Šdiv[#:class "clear" #:id "mce-responses"]{ β—Šdiv[#:class "response" #:id "mce-error-response" #:style "display:none"] β—Šdiv[#:class "response" #:id "mce-success-response" #:style "display:none"] } β—Šdiv[#:aria-hidden "true" #:style "position: absolute; left: -5000px;"]{β—Šinput[#:name "b_a12fcdf12f48c319029ffe244_d25ea0e7ac" #:tabindex "-1" #:type "text" #:value ""]} β—Šdiv[#:class "clear"]{β—Šinput[#:class "button" #:id "mc-embedded-subscribe" #:name "subscribe" #:type "submit" #:value "Subscribe"]} } } }
v-nys/programming-emu
index.html.pm
Perl
mit
1,458
:- module( ctriples_write_graph, [ ctriples_write_graph/3 % +Write:or([atom,stream]) % ?Graph:atom % +Options:list(compound) ] ). /** <module> C-Triples write: graph Writes the given graph (or all currently stored triples) to a source. @author Wouter Beek @version 2015/08 */ :- use_module(library(lists)). :- use_module(library(option)). :- use_module(library(semweb/rdf_db)). :- use_module(library(ctriples/ctriples_write_generics)). :- predicate_options(ctriples_write_graph/3, 3, [ pass_to(write_graph/2, 2) ]). :- predicate_options(write_graph/2, 2, [ pass_to(ctriples_write_begin/3, 3), pass_to(ctriples_write_end/2, 2), format(+oneof([quadruples,triples])) ]). %! ctriples_write_graph( %! +Source:or([atom,stream]), %! ?Graph:atom, %! +Options:list(compound) %! ) is det. % `Source` is either a file name or a write stream. % % The following options are supported: % - `bnode_base(+atom)` % Replace blank nodes with an IRI, defined as per % RDF 1.1 spec (see link below). % - `format(-oneof([quadruples,triples]))` % `quadruples` if at least one named graph occurs, `triples` otherwise. % - `number_of_triples(-nonneg)` % The number of triples that was written. % % @see http://www.w3.org/TR/2014/REC-rdf11-concepts-20140225/#section-skolemization % Input is a stream. ctriples_write_graph(Write, G, Opts):- is_stream(Write), !, with_output_to(Write, write_graph(G, Opts)). % Input is a file. % Open a stream in `write` mode. ctriples_write_graph(File, G, Opts):- is_absolute_file_name(File), !, setup_call_cleanup( open(File, write, Write), with_output_to(Write, write_graph(G, Opts)), close(Write) ). %! write_graph(?Graph:atom, +Options:list(compound)) is det. % This assumes that we can write to current output. write_graph(G, Opts):- ctriples_write_begin(State, BPrefix, Opts), % Decide whether triples or quadruples are written. ( option(format(CFormat), Opts), nonvar(CFormat) -> memberchk(CFormat, [quadruples,triples]) ; rdf_graph(G), G \== user, rdf(_, _, _, G:_) -> CFormat = quadruples ; CFormat = triples ), findall(S, rdf(S, _, _, G), Ss1), sort(Ss1, Ss2), forall( member(S, Ss2), write_subject(State, BPrefix, G, CFormat, S) ), ctriples_write_end(State, Opts). %! write_subject( %! +State:compound, %! +BNodePrefix:iri, %! ?Graph:atom, %! +CFormat:or([quadruples,triples]), %! +Subject:or([bnode,iri]) %! ) is det. % Writes all triples that occur with the given subject term, % possibly restricted to a given graph. % % Collects a sorted list of predicate-object pairs. % Then processes each pairs -- and thus each triple -- separately. % Format: C-Quads write_subject(State, BPrefix, G, quadruples, S):- findall(P-O-G, rdf(S, P, O, G:_), POGTriples1), sort(POGTriples1, POGTriples2), forall( member(P-O-G, POGTriples2), ( inc_number_of_triples(State), write_quadruple(S, P, O, G, BPrefix) ) ). % Format: C-Triples write_subject(State, BPrefix, G, triples, S):- findall(P-O, rdf(S, P, O, G:_), POPairs1), sort(POPairs1, POPairs2), forall( member(P-O, POPairs2), ( inc_number_of_triples(State), write_triple(S, P, O, BPrefix) ) ).
Anniepoo/plRdf
prolog/ctriples/ctriples_write_graph.pl
Perl
mit
3,350
=head1 NAME Mail::Header - manipulate MIME headers =head1 INHERITANCE =head1 SYNOPSIS use Mail::Header; my $head = Mail::Header->new; my $head = Mail::Header->new( \*STDIN ); my $head = Mail::Header->new( [<>], Modify => 0); =head1 DESCRIPTION Read, write, create, and manipulate MIME headers, the leading part of each modern e-mail message, but also used in other protocols like HTTP. The fields are kept in L<Mail::Field|Mail::Field> objects. Be aware that the header fields each have a name part, which shall be treated case-insensitive, and a content part, which may be folded over multiple lines. Mail::Header does not always follow the RFCs strict enough, does not help you with character encodings. It does not use weak references where it could (because those did not exist when the module was written) which costs some performance and make the implementation a little more complicated. The Mail::Message::Head implementation is much newer and therefore better. =head1 METHODS =head2 Constructors $obj-E<gt>B<dup> =over 4 Create a duplicate of the current object. =back $obj-E<gt>B<new>([ARG], [OPTIONS]) Mail::Header-E<gt>B<new>([ARG], [OPTIONS]) =over 4 ARG may be either a file descriptor (reference to a GLOB) or a reference to an array. If given the new object will be initialized with headers either from the array of read from the file descriptor. OPTIONS is a list of options given in the form of key-value pairs, just like a hash table. Valid options are Option --Default FoldLength 79 MailFrom 'KEEP' Modify true . FoldLength => INTEGER =over 4 The default length of line to be used when folding header lines. See L<fold_length()|Mail::Header/"Accessors">. =back . MailFrom => 'IGNORE'|'COERCE'|'KEEP'|'ERROR' =over 4 See method L<mail_from()|Mail::Header/"Accessors">. =back . Modify => BOOLEAN =over 4 If this value is I<true> then the headers will be re-formatted, otherwise the format of the header lines will remain unchanged. =back =back =head2 "Fake" constructors Be warned that the next constructors all require an already created header object, of which the original content will be destroyed. $obj-E<gt>B<empty> =over 4 Empty an existing C<Mail::Header> object of all lines. =back $obj-E<gt>B<extract>(ARRAY) =over 4 Extract a header from the given array into an existing Mail::Header object. C<extract> B<will modify> this array. Returns the object that the method was called on. =back $obj-E<gt>B<header>([ARRAY]) =over 4 C<header> does multiple operations. First it will extract a header from the ARRAY, if given. It will then reformat the header (if reformatting is permitted), and finally return a reference to an array which contains the header in a printable form. =back $obj-E<gt>B<header_hashref>([HASH]) =over 4 As L<header()|Mail::Header/""Fake" constructors">, but it will eventually set headers from a hash reference, and it will return the headers as a hash reference. example: $fields->{From} = 'Tobias Brox <tobix@cpan.org>'; $fields->{To} = ['you@somewhere', 'me@localhost']; $head->header_hashref($fields); =back $obj-E<gt>B<read>(FILEHANDLE) =over 4 Read a header from the given file descriptor into an existing Mail::Header object. =back =head2 Accessors $obj-E<gt>B<fold_length>([TAG], [LENGTH]) =over 4 Set the default fold length for all tags or just one. With no arguments the default fold length is returned. With two arguments it sets the fold length for the given tag and returns the previous value. If only C<LENGTH> is given it sets the default fold length for the current object. In the two argument form C<fold_length> may be called as a static method, setting default fold lengths for tags that will be used by B<all> C<Mail::Header> objects. See the C<fold> method for a description on how C<Mail::Header> uses these values. =back $obj-E<gt>B<mail_from>('IGNORE'|'COERCE'|'KEEP'|'ERROR') =over 4 This specifies what to do when a C<`From '> line is encountered. Valid values are C<IGNORE> - ignore and discard the header, C<ERROR> - invoke an error (call die), C<COERCE> - rename them as Mail-From and C<KEEP> - keep them. =back $obj-E<gt>B<modify>([VALUE]) =over 4 If C<VALUE> is I<false> then C<Mail::Header> will not do any automatic reformatting of the headers, other than to ensure that the line starts with the tags given. =back =head2 Processing $obj-E<gt>B<add>(TAG, LINE [, INDEX]) =over 4 Add a new line to the header. If TAG is C<undef> the the tag will be extracted from the beginning of the given line. If INDEX is given, the new line will be inserted into the header at the given point, otherwise the new line will be appended to the end of the header. =back $obj-E<gt>B<as_string> =over 4 Returns the header as a single string. =back $obj-E<gt>B<cleanup> =over 4 Remove any header line that, other than the tag, only contains whitespace =back $obj-E<gt>B<combine>(TAG [, WITH]) =over 4 Combine all instances of TAG into one. The lines will be joined together WITH, or a single space if not given. The new item will be positioned in the header where the first instance was, all other instances of TAG will be removed. =back $obj-E<gt>B<count>(TAG) =over 4 Returns the number of times the given atg appears in the header =back $obj-E<gt>B<delete>(TAG [, INDEX ]) =over 4 Delete a tag from the header. If an INDEX id is given, then the Nth instance of the tag will be removed. If no INDEX is given, then all instances of tag will be removed. =back $obj-E<gt>B<fold>([LENGTH]) =over 4 Fold the header. If LENGTH is not given, then C<Mail::Header> uses the following rules to determine what length to fold a line. =back $obj-E<gt>B<get>(TAG [, INDEX]) =over 4 Get the text from a line. If an INDEX is given, then the text of the Nth instance will be returned. If it is not given the return value depends on the context in which C<get> was called. In an array context a list of all the text from all the instances of the TAG will be returned. In a scalar context the text for the first instance will be returned. The lines are unfolded, but still terminated with a new-line (see C<chomp>) =back $obj-E<gt>B<print>([FILEHANDLE]) =over 4 Print the header to the given file descriptor, or C<STDOUT> if no file descriptor is given. =back $obj-E<gt>B<replace>(TAG, LINE [, INDEX ]) =over 4 Replace a line in the header. If TAG is C<undef> the the tag will be extracted from the beginning of the given line. If INDEX is given the new line will replace the Nth instance of that tag, otherwise the first instance of the tag is replaced. If the tag does not appear in the header then a new line will be appended to the header. =back $obj-E<gt>B<tags> =over 4 Returns an array of all the tags that exist in the header. Each tag will only appear in the list once. The order of the tags is not specified. =back $obj-E<gt>B<unfold>([TAG]) =over 4 Unfold all instances of the given tag so that they do not spread across multiple lines. If C<TAG> is not given then all lines are unfolded. The unfolding process is wrong but (for compatibility reasons) will not be repaired: only one blank at the start of the line should be removed, not all of them. =back =head1 SEE ALSO This module is part of the MailTools distribution, F<http://perl.overmeer.net/mailtools/>. =head1 AUTHORS The MailTools bundle was developed by Graham Barr. Later, Mark Overmeer took over maintenance without development. Mail::Cap by Gisle Aas E<lt>aas@oslonett.noE<gt>. Mail::Field::AddrList by Peter Orbaek E<lt>poe@cit.dkE<gt>. Mail::Mailer and Mail::Send by Tim Bunce E<lt>Tim.Bunce@ig.co.ukE<gt>. For other contributors see ChangeLog. =head1 LICENSE Copyrights 1995-2000 Graham Barr E<lt>gbarr@pobox.comE<gt> and 2001-2007 Mark Overmeer E<lt>perl@overmeer.netE<gt>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F<http://www.perl.com/perl/misc/Artistic.html>
carlgao/lenga
images/lenny64-peon/usr/share/perl5/Mail/Header.pod
Perl
mit
8,027
#!/usr/bin/perl use warnings; use strict; use feature 'say'; my $fname = shift; open my $fh, "<", $fname or die "Can't open $fname: $!"; my $input = <$fh>; chomp $input; my @digits = split //, $input; my ( $w, $h ) = ( 25, 6 ); my @layers; while (@digits) { my @layer; foreach my $y ( 0 .. $h - 1 ) { foreach my $x ( 0 .. $w - 1 ) { my $digit = shift @digits; $layer[$y][$x] = $digit; } } push @layers, \@layer; } my @image; foreach my $y ( 0 .. $h - 1 ) { foreach my $x ( 0 .. $w - 1 ) { foreach my $layer (@layers) { next if $layer->[$y][$x] == 2; $image[$y][$x] = $layer->[$y][$x]; last; } } } foreach my $row (@image) { say map { $_ == 0 ? '.' : '#' } @$row; }
bewuethr/advent_of_code
2019/day08/day08b.pl
Perl
mit
798
=head1 NAME MIME::Type - Definition of one MIME type =head1 INHERITANCE =head1 SYNOPSIS use MIME::Types; my $mimetypes = MIME::Types->new; my MIME::Type $plaintext = $mimetypes->type('text/plain'); print $plaintext->mediaType; # text print $plaintext->subType; # plain my @ext = $plaintext->extensions; print "@ext" # txt asc c cc h hh cpp print $plaintext->encoding # 8bit if($plaintext->isBinary) # false if($plaintext->isAscii) # true if($plaintext->equals('text/plain') {...} if($plaintext eq 'text/plain') # same print MIME::Type->simplified('x-appl/x-zip') # 'appl/zip' =head1 DESCRIPTION MIME types are used in MIME entities, for instance as part of e-mail and HTTP traffic. Sometimes real knowledge about a mime-type is need. Objects of C<MIME::Type> store the information on one such type. This module is built to conform to the MIME types of RFC's 2045 and 2231. It follows the official IANA registry at F<http://www.iana.org/assignments/media-types/> and the collection kept at F<http://www.ltsw.se/knbase/internet/mime.htp> =head1 OVERLOADED overload: B<string comparison> =over 4 When a MIME::Type object is compared to either a string or an other MIME::TYpe, the L<equals()|MIME::Type/"Knowledge"> method is called. Comparison is smart, which means that it extends common string comparison with some features which are defined in the related RFCs. =back overload: B<stringification> =over 4 The stringification (use of the object in a place where a string is required) will result in the type name, the same as L<type()|MIME::Type/"Attributes"> returns. example: use of stringification my $mime = MIME::Type->new('text/html'); print "$mime\n"; # explicit stringification print $mime; # implicit stringification =back =head1 METHODS =head2 Initiation MIME::Type-E<gt>B<new>(OPTIONS) =over 4 Create (I<instantiate>) a new MIME::Type object which manages one mime type. Option --Default encoding <depends on type> extensions [] simplified <derived from type> system undef type <required> . encoding => '7bit'|'8bit'|'base64'|'quoted-printable' =over 4 How must this data be encoded to be transported safely. The default depends on the type: mimes with as main type C<text/> will default to C<quoted-printable> and all other to C<base64>. =back . extensions => REF-ARRAY =over 4 An array of extensions which are using this mime. =back . simplified => STRING =over 4 The mime types main- and sub-label can both start with C<x->, to indicate that is a non-registered name. Of course, after registration this flag can disappear which adds to the confusion. The simplified string has the C<x-> thingies removed and are translated to lower-case. =back . system => REGEX =over 4 Regular expression which defines for which systems this rule is valid. The REGEX is matched on C<$^O>. =back . type => STRING =over 4 The type which is defined here. It consists of a I<type> and a I<sub-type>, both case-insensitive. This module will return lower-case, but accept upper-case. =back =back =head2 Attributes $obj-E<gt>B<encoding> =over 4 Returns the type of encoding which is required to transport data of this type safely. =back $obj-E<gt>B<extensions> =over 4 Returns a list of extensions which are known to be used for this mime type. =back $obj-E<gt>B<simplified>([STRING]) MIME::Type-E<gt>B<simplified>([STRING]) =over 4 Returns the simplified mime type for this object or the specified STRING. Mime type names can get officially registered. Until then, they have to carry an C<x-> preamble to indicate that. Of course, after recognition, the C<x-> can disappear. In many cases, we prefer the simplified version of the type. example: results of simplified() my $mime = MIME::Type->new(type => 'x-appl/x-zip'); print $mime->simplified; # 'appl/zip' print $mime->simplified('text/plain'); # 'text/plain' print MIME::Type->simplified('x-xyz/x-abc'); # 'xyz/abc' =back $obj-E<gt>B<system> =over 4 Returns the regular expression which can be used to determine whether this type is active on the system where you are working on. =back $obj-E<gt>B<type> =over 4 Returns the long type of this object, for instance C<'text/plain'> =back =head2 Knowledge $obj-E<gt>B<equals>(STRING|MIME) =over 4 Compare this mime-type object with a STRING or other object. In case of a STRING, simplification will take place. =back $obj-E<gt>B<isAscii> =over 4 Returns false when the encoding is base64, and true otherwise. All encodings except base64 are text encodings. =back $obj-E<gt>B<isBinary> =over 4 Returns true when the encoding is base64. =back $obj-E<gt>B<isRegistered> =over 4 Mime-types which are not registered by IANA nor defined in RFCs shall start with an C<x->. This counts for as well the media-type as the sub-type. In case either one of the types starts with C<x-> this method will return false. =back $obj-E<gt>B<isSignature> =over 4 Returns true when the type is in the list of known signatures. =back $obj-E<gt>B<mediaType> =over 4 The media type of the simplified mime. For C<'text/plain'> it will return C<'text'>. For historical reasons, the C<'mainType'> method still can be used to retreive the same value. However, that method is deprecated. =back $obj-E<gt>B<subType> =over 4 The sub type of the simplified mime. For C<'text/plain'> it will return C<'plain'>. =back =head1 DIAGNOSTICS Error: Type parameter is obligatory. =over 4 When a L<MIME::Type|MIME::Type> object is created, the type itself must be specified with the C<type> option flag. =back =head1 SEE ALSO This module is part of MIME-Types distribution version 1.24, built on May 23, 2008. Website: F<http://perl.overmeer.net/mimetypes/> =head1 LICENSE Copyrights 1999,2001-2008 by Mark Overmeer. For other contributors see ChangeLog. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F<http://www.perl.com/perl/misc/Artistic.html>
carlgao/lenga
images/lenny64-peon/usr/share/perl5/MIME/Type.pod
Perl
mit
6,115
:- module(entities, [entity_type/2, entity_prop/4 ]). :- use_module(library(semweb/rdf_db)). %% entity_type(+Class, -Type). % % Type is the normalized type for an RDF Class. entity_type(_, resource). entity_type(C, work) :- rdf_equal(C, 'http://dbpedia.org/ontology/Work'). entity_type(C, television) :- rdf_equal(C, 'http://dbpedia.org/ontology/TelevisionShow'). entity_type(C, writtenwork) :- rdf_equal(C, 'http://dbpedia.org/ontology/WrittenWork'). entity_type(C, person) :- rdf_equal(C, 'http://dbpedia.org/ontology/Person'). entity_type(C, person) :- rdf_equal(C, 'http://xmlns.com/foaf/0.1/Person'). entity_type(C, person) :- rdf_equal(C, 'http://dbpedia.org/class/yago/Person100007846'). entity_type(C, artist) :- rdf_equal(C, 'http://dbpedia.org/ontology/Artist'). entity_type(C, artist) :- rdf_equal(C, 'http://dbpedia.org/class/yago/Artist109812338'). entity_type(C, artist) :- rdf_equal(C, 'http://dbpedia.org/class/yago/Painter110391653'). entity_type(C, character) :- rdf_equal(C, 'http://dbpedia.org/ontology/FictionalCharacter'). entity_type(C, character) :- rdf_equal(C, 'http://dbpedia.org/class/yago/FictionalCharacter109587565'). entity_type(C, character) :- rdf_equal(C, 'http://dbpedia.org/class/yago/CGICharacters'). entity_type(C, presenter) :- rdf_equal(C, 'http://dbpedia.org/ontology/Presenter'). entity_type(C, museum) :- rdf_equal(C, 'http://dbpedia.org/ontology/Museum'). entity_type(C, museum) :- rdf_equal(C, 'http://schema.org/Museum'). entity_type(C, place) :- rdf_equal(C, 'http://dbpedia.org/ontology/Place'). entity_type(C, place) :- rdf_equal(C, 'http://schema.org/Place'). entity_type(C, artobject) :- rdf_equal(C, 'http://vocab.getty.edu/aat/300264092'). entity_type(C, film) :- rdf_equal(C, 'http://dbpedia.org/ontology/Film'). entity_type(C, film) :- rdf_equal(C, ' http://schema.org/Movie'). entity_type(C, organisation) :- rdf_equal(C, 'http://dbpedia.org/ontology/Company'). entity_type(C, organisation) :- rdf_equal(C, 'http://dbpedia.org/ontology/Organisation'). entity_type(C, organisation) :- rdf_equal(C, 'http://schema.org/Organization'). entity_type(C, politicalparty) :- rdf_equal(C, 'http://dbpedia.org/ontology/PoliticalParty'). entity_type(C, politician) :- rdf_equal(C, 'http://dbpedia.org/ontology/OfficeHolder'). entity_type(C, politician) :- rdf_equal(C, 'http://umbel.org/umbel/rc/Politician'). entity_type(C, politician) :- rdf_equal(C, 'http://dbpedia.org/class/yago/Officeholder110371450'). entity_type(C, politician) :- rdf_equal(C, 'http://dbpedia.org/class/yago/Politician110451263'). %% entity_prop(+Type, -Name, -PropertyURIs, -RecursivlyResolve) % % Name: atom indicating the key shown in the json file returned % PropertyURIs: list of all property URIs that are included under % this key % RecursivlyResolve: boolean indicating if the objects from the % resolved URI need to be resolved themselves as well entity_prop(resource, label, [rdfs:label], true). entity_prop(resource, thumb, [foaf:depiction], false). entity_prop(resource, comment, ['http://dbpedia.org/ontology/abstract', rdfs:comment], true). entity_prop(person, birthDate, ['http://dbpedia.org/ontology/birthDate'], false). entity_prop(person, deathDate, ['http://dbpedia.org/ontology/deathDate'], false). entity_prop(person, birthPlace, ['http://dbpedia.org/ontology/birthPlace'], true). entity_prop(person, deathPlace, ['http://dbpedia.org/ontology/deathPlace'], true). entity_prop(person, nationality, ['http://dbpedia.org/ontology/nationality'], true). entity_prop(person, profession, ['http://dbpedia.org/ontology/occupation'], true). entity_prop(character, creator, ['http://dbpedia.org/ontology/creator'], true). entity_prop(character, portrayedby, ['http://dbpedia.org/ontology/portrayer'], true). entity_prop(character, inSeries, ['http://dbpedia.org/ontology/series'], true). entity_prop(character, inBook, ['http://dbpedia.org/property/book(s)_'], true). % LN extension for people who held a role in their lifetimes (doesn't % seem to be always indicated by a specific type) entity_prop(person, predecessor, ['http://dbpedia.org/ontology/predecessor'], true). entity_prop(person, successor, ['http://dbpedia.org/ontology/successor'], true). %can we give alternative properties, there are often both English and Dutch/German, or only one or the other % from http://www.linkedtv.eu/wiki/index.php/Annotation_types_in_TKK entity_prop(television, creator, ['http://dbpedia.org/ontology/creator'], true). entity_prop(television, genre, ['http://dbpedia.org/ontology/genre'], false). entity_prop(television, network, ['http://dbpedia.org/ontology/network'], false). entity_prop(television, numberOfEpisodes, ['http://dbpedia.org/ontology/numberOfEpisodes'], false). entity_prop(television, numberOfSeasons, ['http://dbpedia.org/ontology/numberOfSeasons'], false). entity_prop(television, releaseDate, ['http://dbpedia.org/ontology/releaseDate'], false). entity_prop(television, starring, ['http://dbpedia.org/ontology/starring'], true). entity_prop(writtenwork, author, ['http://dbpedia.org/ontology/author'], true). entity_prop(writtenwork, genre, ['http://dbpedia.org/property/genre','http://dbpedia.org/ontology/literaryGenre'], true). entity_prop(writtenwork, pubDate, ['http://dbpedia.org/ontology/pubDate','http://dbpedia.org/property/releaseDate'], true). entity_prop(writtenwork, publisher, ['http://dbpedia.org/ontology/publisher'], true). entity_prop(writtenwork, precededBy, ['http://dbpedia.org/ontology/previousWork'], true). entity_prop(writtenwork, succeededBy, ['http://dbpedia.org/ontology/subsequentWork'], true). entity_prop(artist, style, ['http://dbpedia.org/ontology/movement'], true). entity_prop(presenter, activeSince, ['http://dbpedia.org/ontology/activeYearsStartYear'], false). entity_prop(presenter, knownFor, ['http://dbpedia.org/ontology/knownFor'], true). entity_prop(presenter, presents, ['http://dbpedia.org/ontology/presenter'], true). entity_prop(museum, locatedIn, ['http://dbpedia.org/ontology/location'], true). entity_prop(place, population, ['http://dbpedia.org/ontology/populationTotal'], false). entity_prop(place, latitude, ['http://www.w3.org/2003/01/geo/wgs84_pos#lat'], false). entity_prop(place, longitude, ['http://www.w3.org/2003/01/geo/wgs84_pos#long'], false). entity_prop(place, region, ['http://dbpedia.org/property/subdivisionName'], true). %more specific properties when the place is a building or other construction entity_prop(place, location, ['http://dbpedia.org/property/location'], true). entity_prop(place, owner, ['http://dbpedia.org/property/owner'], true). entity_prop(place, openingDate, ['http://dbpedia.org/property/openingDate'], false). entity_prop(place, architect, ['http://dbpedia.org/property/architect'], true). entity_prop(place, builtYear, ['http://dbpedia.org/property/completionDate'], false). entity_prop(place, architecture, ['http://dbpedia.org/property/architecturalStyle'], false). %more specific properties when the place is an administrative region entity_prop(place, localLeader, ['http://dbpedia.org/ontology/leaderName'], true). entity_prop(place, localLeaderTitle, ['http://dbpedia.org/ontology/leaderTitle'], false). entity_prop(place, localLeaderParty, ['http://dbpedia.org/ontology/leaderParty'], true). %this is based on http://www.linkedtv.eu/wiki/index.php/Creating_rich_descriptions_of_cultural_artefacts_out_of_a_TV_program#Vocabulary entity_prop(artobject, createdIn, ['http://simile.mit.edu/2003/10/ontologies/vraCore3#locationCreationSite'], true). entity_prop(artobject, createdBy, ['http://purl.org/dc/terms/creator'], true). entity_prop(artobject, currentlyFoundAt, ['http://www.cidoc-crm.org/rdfs/cidoc-crm#P55F.has_current_location'], true). entity_prop(artobject, hasStyle, ['http://simile.mit.edu/2003/10/ontologies/vraCore3#stylePeriod'], true). entity_prop(artobject, madeOf, ['http://www.cidoc-crm.org/rdfs/cidoc-crm#P45F.consists_of'], true). %time periods and price estimates need to access properties along a path, is that possible? % from http://www.linkedtv.eu/wiki/index.php/Annotation_types_in_RBB entity_prop(film, cinematography, ['http://dbpedia.org/ontology/cinematography'], true). entity_prop(film, director, ['http://dbpedia.org/ontology/director'], true). entity_prop(film, musicComposer, ['http://dbpedia.org/ontology/musicComposer'], true). entity_prop(film, starring, ['http://dbpedia.org/ontology/starring'], true). entity_prop(organisation, chairman, ['http://dbpedia.org/ontology/chairman'], true). entity_prop(organisation, focus, ['http://dbpedia.org/property/focus'], true). entity_prop(organisation, formationYear, ['http://dbpedia.org/ontology/formationYear'], false). entity_prop(organisation, founder, ['http://dbpedia.org/ontology/foundedBy'], true). entity_prop(organisation, foundingYear, ['http://dbpedia.org/ontology/foundingYear'], false). entity_prop(organisation, industry, ['http://dbpedia.org/ontology/industry'], true). entity_prop(organisation, location, ['http://dbpedia.org/ontology/location'], true). entity_prop(organisation, locationCity, ['http://dbpedia.org/ontology/locationCity'], true). entity_prop(organisation, numberEmployees, ['http://dbpedia.org/ontology/numberOfEmployees'], false). %entity_prop(politicalparty, headquarter, ['http://dbpedia.org/ontology/headquarter'], false). %entity_prop(politicalparty, deputyLeader, ['http://dbpedia.org/ontology/secondLeader'], false). %entity_prop(politicalparty, politicalLeaning, ['http://de.dbpedia.org/property/ausrichtung'], false). %entity_prop(politicalparty, leader, ['http://de.dbpedia.org/property/bundesgeschΓ€ftsfΓΌhrer'], false). %entity_prop(politicalparty, euParlament, ['http://de.dbpedia.org/property/euParlament'], false). %entity_prop(politicalparty, founding, ['http://de.dbpedia.org/property/grΓΌndung'], false). %entity_prop(politicalparty, foundingLocation, ['http://de.dbpedia.org/property/grΓΌndungsort'], true). %entity_prop(politicalparty, chairperson, ['http://de.dbpedia.org/property/parteivorsitzende'], true). entity_prop(politician, activeSince, ['http://dbpedia.org/ontology/activeYearsStartDate'], false). entity_prop(politician, activeUntil, ['http://dbpedia.org/ontology/activeYearsEndDate'], false). entity_prop(politician, office, ['http://dbpedia.org/ontology/office'], false). entity_prop(politician, party, ['http://dbpedia.org/ontology/party'], true). entity_prop(politician, officeholderBefore, ['http://dbpedia.org/property/before'], true). entity_prop(politician, officeholderAfter, ['http://dbpedia.org/property/after'], true).
michielhildebrand/linkedtv_entity_proxy
lib/entities.pl
Perl
mit
10,598
:- module( prolog_to_rdf, [ prolog_to_rdf/4 % +Graph:atom % +Module:atom % +Term:term % -Individual:iri ] ). /** <module> Prolog to RDF Automated conversion from Prolog terms to RDF triples. @author Wouter Beek @version 2014/01, 2014/11 */ :- use_module(library(apply)). :- use_module(library(semweb/rdf_db), except([rdf_node/1])). :- use_module(plc(dcg/dcg_atom)). :- use_module(plc(dcg/dcg_generics)). :- use_module(plXsd(xsd)). :- use_module(plRdf(api/rdf_build)). :- use_module(plRdf(api/rdfs_build)). :- use_module(plRdf(term/rdf_datatype)). :- use_module(plRdf(term/rdf_literal)). prolog_to_rdf(Graph, Module, Term, Individual):- % Namespace. ( rdf_current_prefix(Module, _), ! ; atomic_list_concat(['http://www.wouterbeek.com',Module,''], /, URL), rdf_register_prefix(Module, URL) ), % Class. Term =.. [Functor|Args], once(atom_phrase(atom_capitalize, Functor, ClassName)), rdf_global_id(Module:ClassName, Class), rdfs_assert_class(Class, Graph), % Individual. rdf_bnode(Individual), rdf_assert_instance(Individual, Class, Graph), % Propositions. Module:legend(Functor, ArgRequirements), maplist(prolog_to_rdf(Graph, Module, Individual), ArgRequirements, Args). prolog_to_rdf( Graph, Module, Individual1, PredicateName-PrologType-Optional, Value ):- rdf_global_id(Module:PredicateName, Predicate), ( PrologType =.. [list,InnerPrologType] -> is_list(Value), maplist( prolog_to_rdf( Graph, Module, Individual1, PredicateName-InnerPrologType-Optional ), Value ) ; PrologType = _/_ -> prolog_to_rdf(Graph, Module, Value, Individual2), rdf_assert(Individual1, Predicate, Individual2, Graph) ; rdf_datatype(Datatype, PrologType) -> rdf_assert_typed_literal(Individual1, Predicate, Value, Datatype, Graph) ; Optional = true ).
Anniepoo/plRdf
tmp/convert/prolog_to_rdf.pl
Perl
mit
1,977
% vim: set ft=prolog: % % see: https://www.tutorialspoint.com/prolog/index.htm female(pam). female(liz). female(pat). female(ann). male(jim). male(bob). male(tom). male(peter). parent(pam, bob). parent(tom, bob). parent(tom, liz). parent(bob, ann). parent(bob, pat). parent(pat, jim). parent(bob, peter). parent(peter, jim). mother(X, Y) :- parent(X, Y), female(X). father(X, Y) :- parent(X, Y), male(X). has_child(X) :- parent(X, _). sister(X, Y) :- parent(Z, X), parent(Z, Y), female(X), X \== Y. brother(X, Y) :- parent(Z, X), parent(Z, Y), male(X), X \== Y. grandparent(X, Y) :- parent(X, Z), parent(Z, Y). grandmother(X, Y) :- mother(X, Z), parent(Z, Y). grandfather(X, Y) :- father(X, Z), parent(Z, Y). wife(X, Y) :- parent(X, Z), parent(Y, Z), female(X), male(Y). uncle(X, Z) :- brother(X, Y), parent(Y, Z).
kkirstein/proglang-playground
Prolog/Tutorial/family_ext.pl
Perl
mit
819
# Time-stamp: "Sat Jul 14 00:27:32 2001 by Automatic Bizooty (__blocks2pm.plx)" $Text::\SEPA\Unicode\Unidecode::Char[0x73] = [ 'Sha ', 'Li ', 'Han ', 'Xian ', 'Jing ', 'Pai ', 'Fei ', 'Yao ', 'Ba ', 'Qi ', 'Ni ', 'Biao ', 'Yin ', 'Lai ', 'Xi ', 'Jian ', 'Qiang ', 'Kun ', 'Yan ', 'Guo ', 'Zong ', 'Mi ', 'Chang ', 'Yi ', 'Zhi ', 'Zheng ', 'Ya ', 'Meng ', 'Cai ', 'Cu ', 'She ', 'Kari ', 'Cen ', 'Luo ', 'Hu ', 'Zong ', 'Ji ', 'Wei ', 'Feng ', 'Wo ', 'Yuan ', 'Xing ', 'Zhu ', 'Mao ', 'Wei ', 'Yuan ', 'Xian ', 'Tuan ', 'Ya ', 'Nao ', 'Xie ', 'Jia ', 'Hou ', 'Bian ', 'You ', 'You ', 'Mei ', 'Zha ', 'Yao ', 'Sun ', 'Bo ', 'Ming ', 'Hua ', 'Yuan ', 'Sou ', 'Ma ', 'Yuan ', 'Dai ', 'Yu ', 'Shi ', 'Hao ', qq{[?] }, 'Yi ', 'Zhen ', 'Chuang ', 'Hao ', 'Man ', 'Jing ', 'Jiang ', 'Mu ', 'Zhang ', 'Chan ', 'Ao ', 'Ao ', 'Hao ', 'Cui ', 'Fen ', 'Jue ', 'Bi ', 'Bi ', 'Huang ', 'Pu ', 'Lin ', 'Yu ', 'Tong ', 'Yao ', 'Liao ', 'Shuo ', 'Xiao ', 'Swu ', 'Ton ', 'Xi ', 'Ge ', 'Juan ', 'Du ', 'Hui ', 'Kuai ', 'Xian ', 'Xie ', 'Ta ', 'Xian ', 'Xun ', 'Ning ', 'Pin ', 'Huo ', 'Nou ', 'Meng ', 'Lie ', 'Nao ', 'Guang ', 'Shou ', 'Lu ', 'Ta ', 'Xian ', 'Mi ', 'Rang ', 'Huan ', 'Nao ', 'Luo ', 'Xian ', 'Qi ', 'Jue ', 'Xuan ', 'Miao ', 'Zi ', 'Lu ', 'Lu ', 'Yu ', 'Su ', 'Wang ', 'Qiu ', 'Ga ', 'Ding ', 'Le ', 'Ba ', 'Ji ', 'Hong ', 'Di ', 'Quan ', 'Gan ', 'Jiu ', 'Yu ', 'Ji ', 'Yu ', 'Yang ', 'Ma ', 'Gong ', 'Wu ', 'Fu ', 'Wen ', 'Jie ', 'Ya ', 'Fen ', 'Bian ', 'Beng ', 'Yue ', 'Jue ', 'Yun ', 'Jue ', 'Wan ', 'Jian ', 'Mei ', 'Dan ', 'Pi ', 'Wei ', 'Huan ', 'Xian ', 'Qiang ', 'Ling ', 'Dai ', 'Yi ', 'An ', 'Ping ', 'Dian ', 'Fu ', 'Xuan ', 'Xi ', 'Bo ', 'Ci ', 'Gou ', 'Jia ', 'Shao ', 'Po ', 'Ci ', 'Ke ', 'Ran ', 'Sheng ', 'Shen ', 'Yi ', 'Zu ', 'Jia ', 'Min ', 'Shan ', 'Liu ', 'Bi ', 'Zhen ', 'Zhen ', 'Jue ', 'Fa ', 'Long ', 'Jin ', 'Jiao ', 'Jian ', 'Li ', 'Guang ', 'Xian ', 'Zhou ', 'Gong ', 'Yan ', 'Xiu ', 'Yang ', 'Xu ', 'Luo ', 'Su ', 'Zhu ', 'Qin ', 'Ken ', 'Xun ', 'Bao ', 'Er ', 'Xiang ', 'Yao ', 'Xia ', 'Heng ', 'Gui ', 'Chong ', 'Xu ', 'Ban ', 'Pei ', qq{[?] }, 'Dang ', 'Ei ', 'Hun ', 'Wen ', 'E ', 'Cheng ', 'Ti ', 'Wu ', 'Wu ', 'Cheng ', 'Jun ', 'Mei ', 'Bei ', 'Ting ', 'Xian ', 'Chuo ', ]; 1;
dmitrirussu/php-sepa-xml-generator
src/Unicode/data/perl_source/x73.pm
Perl
mit
2,212
use strict; use lib "../lib"; use lib "../../lib"; use Test::More "no_plan"; use Data::Dumper; use Eldhelm::Test::Mock::Worker; use MIME::Base64 qw(encode_base64 decode_base64); my $worker = Eldhelm::Test::Mock::Worker->new( config => { server => { serverHome => ".." } } ); $worker->{configPath} = "config_path_here"; $worker->runExternalScriptAsync("non_existing_test_external_script"); my $log = $worker->getLastLogEntry("error"); ok($log =~ /non_existing_test_external_script/, "error ok"); $worker->runExternalScriptAsync("test_external_script", { some_data_here => { deeply => "I have data!" } }); $log = $worker->getLastLogEntry("access"); ok($log =~ /test_external_script/, "access ok"); ok($log =~ /&$/, "Ends with &");
wastedabuser/eldhelm-platform
test/t/305_worker_external_script_async.pl
Perl
mit
742
package Mojo::Twist::File; use Mojo::Base -base; use Mojo::Twist::Date; use Encode (); use File::stat; use File::Basename (); use constant FILE_SLURP => eval { require File::Slurp; 1 }; sub path { my $self = shift; return $self->{path}; } sub created { my $self = shift; return $self->{created} if $self->{created}; my ($prefix) = File::Basename::basename($self->path) =~ m/^(.*?)-/; if ($prefix && Mojo::Twist::Date->is_date($prefix)) { $self->{created} = Mojo::Twist::Date->new(timestamp => $prefix); } else { $self->{created} = $self->modified; } return $self->{created}; } sub modified { my $self = shift; return Mojo::Twist::Date->new(epoch => $self->_stat->mtime); } sub filename { my $self = shift; return $self->{filename} if $self->{filename}; my $filename = File::Basename::basename($self->path); my ($prefix) = $filename =~ m/^(.*?)-/; if ($prefix && Mojo::Twist::Date->is_date($prefix)) { $filename =~ s/^$prefix-//; } $filename =~ s/\.[^\.]+$//; return $self->{filename} = $filename; } sub format { my $self = shift; return $self->{format} if $self->{format}; my $filename = File::Basename::basename($self->path); my $format = ''; if ($filename =~ m/\.([^\.]+)$/) { $format = $1; } return $self->{format} = $format; } sub slurp { my $self = shift; my $slurp = FILE_SLURP ? File::Slurp::read_file($self->path) : do { local $/; open my $fh, '<', $self->path or die $!; <$fh> }; return Encode::decode('UTF-8', $slurp); } sub _stat { my $self = shift; return stat $self->path; } 1;
gitpan/Mojo-Twist
lib/Mojo/Twist/File.pm
Perl
mit
1,612
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 12.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. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V14 32 127 162 164 165 167 172 173 175 176 10214 10222 10629 10631 END
operepo/ope
client_tools/svc/rc/usr/share/perl5/core_perl/unicore/lib/Ea/Na.pl
Perl
mit
554
=pod =head1 NAME EVP_KEYEXCH-ECDH - ECDH Key Exchange algorithm support =head1 DESCRIPTION Key exchange support for the B<ECDH> key type. =head2 ECDH Key Exchange parameters =over 4 =item "ecdh-cofactor-mode" (B<OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE>) <integer> Sets or gets the ECDH mode of operation for the associated key exchange ctx. In the context of an Elliptic Curve Diffie-Hellman key exchange, this parameter can be used to select between the plain Diffie-Hellman (DH) or Cofactor Diffie-Hellman (CDH) variants of the key exchange algorithm. When setting, the value should be 1, 0 or -1, respectively forcing cofactor mode on, off, or resetting it to the default for the private key associated with the given key exchange ctx. When getting, the value should be either 1 or 0, respectively signaling if the cofactor mode is on or off. See also L<provider-keymgmt(7)> for the related B<OSSL_PKEY_PARAM_USE_COFACTOR_ECDH> parameter that can be set on a per-key basis. =item "kdf-type" (B<OSSL_EXCHANGE_PARAM_KDF_TYPE>) <UTF8 string> Sets or gets the Key Derivation Function type to apply within the associated key exchange ctx. =item "kdf-digest" (B<OSSL_EXCHANGE_PARAM_KDF_DIGEST>) <UTF8 string> Sets or gets the Digest algorithm to be used as part of the Key Derivation Function associated with the given key exchange ctx. =item "kdf-digest-props" (B<OSSL_EXCHANGE_PARAM_KDF_DIGEST_PROPS>) <UTF8 string> Sets properties to be used upon look up of the implementation for the selected Digest algorithm for the Key Derivation Function associated with the given key exchange ctx. =item "kdf-outlen" (B<OSSL_EXCHANGE_PARAM_KDF_OUTLEN>) <unsigned integer> Sets or gets the desired size for the output of the chosen Key Derivation Function associated with the given key exchange ctx. The length of the "kdf-outlen" parameter should not exceed that of a B<size_t>. =item "kdf-ukm" (B<OSSL_EXCHANGE_PARAM_KDF_UKM>) <octet string> Sets the User Key Material to be used as part of the selected Key Derivation Function associated with the given key exchange ctx. =item "kdf-ukm" (B<OSSL_EXCHANGE_PARAM_KDF_UKM>) <octet string ptr> Gets a pointer to the User Key Material to be used as part of the selected Key Derivation Function associated with the given key exchange ctx. Providers usually do not need to support this gettable parameter as its sole purpose is to support functionality of the deprecated EVP_PKEY_CTX_get0_ecdh_kdf_ukm() function. =back =head1 EXAMPLES Keys for the host and peer must be generated as shown in L<EVP_PKEY-EC(7)/Examples> using the same curve name. The code to generate a shared secret for the normal case is identical to L<EVP_KEYEXCH-DH(7)/Examples>. To derive a shared secret on the host using the host's key and the peer's public key but also using X963KDF with a user key material: /* It is assumed that the host_key, peer_pub_key and ukm are set up */ void derive_secret(EVP_PKEY *host_key, EVP_PKEY *peer_key, unsigned char *ukm, size_t ukm_len) { unsigned char secret[64]; size_t out_len = sizeof(secret); size_t secret_len = out_len; unsigned int pad = 1; OSSL_PARAM params[6]; EVP_PKEY_CTX *dctx = EVP_PKEY_CTX_new_from_pkey(NULL, host_key, NULL); EVP_PKEY_derive_init(dctx); params[0] = OSSL_PARAM_construct_uint(OSSL_EXCHANGE_PARAM_PAD, &pad); params[1] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_TYPE, "X963KDF", 0); params[2] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_DIGEST, "SHA1", 0); params[3] = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN, &out_len); params[4] = OSSL_PARAM_construct_octet_string(OSSL_EXCHANGE_PARAM_KDF_UKM, ukm, ukm_len); params[5] = OSSL_PARAM_construct_end(); EVP_PKEY_CTX_set_params(dctx, params); EVP_PKEY_derive_set_peer(dctx, peer_pub_key); EVP_PKEY_derive(dctx, secret, &secret_len); ... OPENSSL_clear_free(secret, secret_len); EVP_PKEY_CTX_free(dctx); } =head1 SEE ALSO L<EVP_PKEY-EC(7)> L<EVP_PKEY(3)>, L<provider-keyexch(7)>, L<provider-keymgmt(7)>, L<OSSL_PROVIDER-default(7)>, L<OSSL_PROVIDER-FIPS(7)>, =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
openssl/openssl
doc/man7/EVP_KEYEXCH-ECDH.pod
Perl
apache-2.0
4,809
#!/usr/bin/perl ################################################################################ # 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. ################################################################################ # sort according to key and then min # use strict; use warnings; # Format: # Stats for xxxxxx.example.com/hammer-0: min: 100890982; max: 102994870; last: 102994870; duplicated: 0; dropped: 0; total: 2103889; my @lines = <>; chomp @lines; my @sorted = sort { my @aFields = split(/\s+/, $a); my @bFields = split(/\s+/, $b); my $keyCmp = $aFields[2] cmp $bFields[2]; if ($keyCmp != 0) { return $keyCmp; } my $aMin = $aFields[4]; chop $aMin; my $bMin = $bFields[4]; chop $bMin; return $aMin <=> $bMin; } @lines; print join("\n", @sorted), "\n"; exit 0;
mpercy/flume-load-gen
bin/sort_results.pl
Perl
apache-2.0
1,530
#!/usr/bin/perl -w use strict; use FileHandle; my $DEBUG = 0; if( $ARGV[0] eq '-d' ) { $DEBUG = 1; shift( @ARGV ); } my $SOURCEFILE = $ARGV[0]; my $OUTFILE = $ARGV[1]; if( ! $SOURCEFILE ) { die "ERROR: Must supply the output file name from Scrivener.\n\nUsage: splitHTMLBook.pl compiled-book.txt\n"; } if( ! -f $SOURCEFILE ) { die "ERROR: Unable to read file: $SOURCEFILE\n"; } print 'Source: ' . $SOURCEFILE . "\n"; print 'Output: ' . $OUTFILE . "\n"; if( -f $OUTFILE ) { print "WARNING: Overwriting existing temp file: $OUTFILE\n"; } my $fulltext; open( INPUT, "<${SOURCEFILE}" ) or die "Unable to read sourcefile: ${SOURCEFILE}\n"; while( <INPUT> ) { $fulltext .= $_; } close( INPUT ) or die; # Add linefeeds to the end (Scrivener strips it) for paragraph identification purposes $fulltext .= "\n\n\n"; # Prevent adding paragraphs to pre blocks $fulltext =~ s|(<pre [^>]*?>)(.*?)(</pre>)|$1 . &addBreak( $2 ) . $3|egs; # Add paragraphs to things inside an aside while( $fulltext =~ s|\n\n(<aside data-type="\w+">\s*)([\w]+.*?)\s*\n\n|\n\n$1<p>$2</p>\n\n|gs ) {} # Add paragraphs to things starting with an anchor while( $fulltext =~ s#\n\n(<a (href|data-type)="[\w]+.*?)\s*\n\n#\n\n<p>$1</p>\n\n#gs ) {} # Fix anchors? # F: <a href="#([\w\-\:\.]+)">([\w\s\-\:\.]+)</a> # R: <a data-type="xref" href='#$1'>#$1</a> # Add paragraphs to everything that looks like a paragraph while( $fulltext =~ s|\n\n([\w\.]+.*?)\s*\n\n|\n\n<p>$1</p>\n\n|gs ) {} while( $fulltext =~ s|(\s*)</aside></p>|</p>$1</aside>|gs ) {} # Add paragraphs to things that start with an internal anchor while( $fulltext =~ s|\n\n(<a href="#[\w]+.*?)\s*\n\n|\n\n<p>$1</p>\n\n|gs ) {} # Remove the pre-comments $fulltext =~ s|(<pre [^>]*?>)(.*?)(</pre>)|$1 . &removeBreak( $2 ) . $3|egs; # Output the file my $OUTPUTFH = FileHandle->new( $OUTFILE, 'w' ); print $OUTPUTFH $fulltext; $OUTPUTFH->close(); print "Finished parsing for paragraphs.\n" if $DEBUG; exit 0; sub addBreak { my $codeblock = shift; $codeblock =~ s|\n\n|\n<!-- PRE -->\n|gs; return $codeblock; } sub removeBreak { my $codeblock = shift; $codeblock =~ s|\n<!-- PRE -->\n|\n\n|gs; return $codeblock; }
jorhett/scrivener-htmlbook
markParagraphs.pl
Perl
apache-2.0
2,207
package VMOMI::BadUsernameSessionEvent; use parent 'VMOMI::SessionEvent'; use strict; use warnings; our @class_ancestors = ( 'SessionEvent', 'Event', 'DynamicData', ); our @class_members = ( ['ipAddress', undef, 0, ], ); sub get_class_ancestors { return @class_ancestors; } sub get_class_members { my $class = shift; my @super_members = $class->SUPER::get_class_members(); return (@super_members, @class_members); } 1;
stumpr/p5-vmomi
lib/VMOMI/BadUsernameSessionEvent.pm
Perl
apache-2.0
459
# # 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 centreon::common::protocols::ssh::custom::api; use strict; use warnings; use Libssh::Session qw(:all); 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' }, "port:s@" => { name => 'port' }, "timeout:s@" => { name => 'timeout' }, "ssh-username:s@" => { name => 'ssh_username' }, "ssh-password:s@" => { name => 'ssh_password' }, "ssh-dir:s@" => { name => 'ssh_dir' }, "ssh-identity:s@" => { name => 'ssh_identity' }, "ssh-skip-serverkey-issue" => { name => 'ssh_skip_serverkey_issue' }, }); } $options{options}->add_help(package => __PACKAGE__, sections => 'SSH OPTIONS', once => 1); $self->{output} = $options{output}; $self->{mode} = $options{mode}; $self->{ssh} = undef; return $self; } sub set_options { my ($self, %options) = @_; $self->{option_results} = $options{option_results}; } sub set_defaults { my ($self, %options) = @_; foreach (keys %{$options{default}}) { if ($_ eq $self->{mode}) { for (my $i = 0; $i < scalar(@{$options{default}->{$_}}); $i++) { foreach my $opt (keys %{$options{default}->{$_}[$i]}) { if (!defined($self->{option_results}->{$opt}[$i])) { $self->{option_results}->{$opt}[$i] = $options{default}->{$_}[$i]->{$opt}; } } } } } } sub check_options { my ($self, %options) = @_; $self->{hostname} = (defined($self->{option_results}->{hostname})) ? shift(@{$self->{option_results}->{hostname}}) : undef; $self->{port} = (defined($self->{option_results}->{port})) ? shift(@{$self->{option_results}->{port}}) : 22; $self->{timeout} = (defined($self->{option_results}->{timeout})) ? shift(@{$self->{option_results}->{timeout}}) : 10; $self->{ssh_username} = (defined($self->{option_results}->{ssh_username})) ? shift(@{$self->{option_results}->{ssh_username}}) : undef; $self->{ssh_password} = (defined($self->{option_results}->{ssh_password})) ? shift(@{$self->{option_results}->{ssh_password}}) : undef; $self->{ssh_dir} = (defined($self->{option_results}->{ssh_dir})) ? shift(@{$self->{option_results}->{ssh_dir}}) : undef; $self->{ssh_identity} = (defined($self->{option_results}->{ssh_identity})) ? shift(@{$self->{option_results}->{ssh_identity}}) : undef; $self->{ssh_skip_serverkey_issue} = defined($self->{option_results}->{ssh_skip_serverkey_issue}) ? 1 : 0; if (!defined($self->{hostname}) || $self->{hostname} eq '') { $self->{output}->add_option_msg(short_msg => "Please set option --hostname."); $self->{output}->option_exit(); } if (!defined($self->{hostname}) || scalar(@{$self->{option_results}->{hostname}}) == 0) { return 0; } return 1; } sub login { my ($self, %options) = @_; my $result = { status => 0, message => 'authentification succeeded' }; $self->{ssh} = Libssh::Session->new(); foreach (['hostname', 'host'], ['port', 'port'], ['timeout', 'timeout'], ['ssh_username', 'user'], ['ssh_dir', 'sshdir'], ['ssh_identity', 'identity']) { next if (!defined($self->{$_->[0]}) || $self->{$_->[0]} eq ''); if ($self->{ssh}->options($_->[1] => $self->{$_->[0]}) != SSH_OK) { $result->{message} = $self->{ssh}->error(); $result->{status} = 1; return $result; } } if ($self->{ssh}->connect(SkipKeyProblem => $self->{ssh_skip_serverkey_issue}) != SSH_OK) { $result->{message} = $self->{ssh}->error(); $result->{status} = 1; return $result; } if ($self->{ssh}->auth_publickey_auto() != SSH_AUTH_SUCCESS) { if (defined($self->{ssh_username}) && $self->{ssh_username} ne '' && defined($self->{ssh_password}) && $self->{ssh_password} ne '' && $self->{ssh}->auth_password(password => $self->{ssh_password}) == SSH_AUTH_SUCCESS) { return $result; } my $msg_error = $self->{ssh}->error(GetErrorSession => 1); $result->{message} = sprintf("auth issue: %s", defined($msg_error) && $msg_error ne '' ? $msg_error : 'pubkey issue'); $result->{status} = 1; } return $result; } 1; __END__ =head1 NAME SSH connector library =head1 SYNOPSIS my ssh connector =head1 SSH OPTIONS =over 8 =item B<--hostname> SSH server hostname (required). =item B<--port> SSH port. =item B<--timeout> Timeout in seconds for connection (Defaults: 10 seconds) =item B<--ssh-username> SSH username. =item B<--ssh-password> SSH password. =item B<--ssh-dir> Set the ssh directory. =item B<--ssh-identity> Set the identity file name (default: id_dsa and id_rsa are checked). =item B<--ssh-skip-serverkey-issue> Connection will be OK even if there is a problem (server known changed or server found other) with the ssh server. =back =head1 DESCRIPTION B<custom>. =cut
wilfriedcomte/centreon-plugins
centreon/common/protocols/ssh/custom/api.pm
Perl
apache-2.0
6,496
package Moose::Exception::OverrideConflictInSummation; our $VERSION = '2.1404'; use Moose; extends 'Moose::Exception'; use Moose::Util 'find_meta'; has 'role_application' => ( is => 'ro', isa => 'Moose::Meta::Role::Application::RoleSummation', required => 1 ); has 'role_names' => ( traits => ['Array'], is => 'bare', isa => 'ArrayRef[Str]', handles => { role_names => 'elements', }, required => 1, documentation => "This attribute is an ArrayRef containing role names, if you want metaobjects\n". "associated with these role names, then call method roles on the exception object.\n", ); has 'method_name' => ( is => 'ro', isa => 'Str', required => 1 ); has 'two_overrides_found' => ( is => 'ro', isa => 'Bool', required => 1, default => 0 ); sub roles { my $self = shift; my @role_names = $self->role_names; my @roles = map { find_meta($_) } @role_names; return @roles; } sub _build_message { my $self = shift; my @roles = $self->role_names; my $role_names = join "|", @roles; if( $self->two_overrides_found ) { return "We have encountered an 'override' method conflict ". "during composition (Two 'override' methods of the same name encountered). ". "This is a fatal error."; } else { return "Role '$role_names' has encountered an 'override' method conflict " . "during composition (A local method of the same name has been found). This " . "is a fatal error." ; } } 1;
ray66rus/vndrv
local/lib/perl5/x86_64-linux-thread-multi/Moose/Exception/OverrideConflictInSummation.pm
Perl
apache-2.0
1,653
#!/usr/bin/env perl # Copyright 2015 Frank Breedijk # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------------ # Gets rundata # ------------------------------------------------------------------------------ use strict; use CGI; use CGI::Carp qw(fatalsToBrowser); use JSON; use lib ".."; use SeccubusV2; use SeccubusRuns; my $query = CGI::new(); my $params = $query->Vars; my $workspace_id = $params->{workspaceId}; my $scan_id = $params->{scanId}; my $run_id = $params->{runId}; my $attachment_id = $params->{attachmentId}; # Return an error if the required parameters were not passed if (not (defined ($workspace_id))) { die("Parameter workspaceId is missing"); } elsif ( $workspace_id + 0 ne $workspace_id ) { die("WorkspaceId is not numeric"); } elsif (not (defined ($scan_id))) { die("Parameter scanId is missing"); } elsif ( $scan_id + 0 ne $scan_id ) { die("scanId is not numeric"); } elsif (not (defined ($run_id))) { die("Parameter runId is missing"); } elsif ( $run_id + 0 ne $run_id ) { die("runId is not numeric"); } elsif (not (defined ($attachment_id))) { die("Parameter attachmentId is missing"); } elsif ( $attachment_id + 0 ne $attachment_id ) { die("attachmentId is not numeric"); }; my $att = get_attachment($workspace_id, $scan_id, $run_id, $attachment_id); my $row = shift @$att; print "Content-type:application/x-download\n"; print "Content-Disposition:attachment;filename=$$row[0]\n\n"; print $$row[1]; exit;
vlamer/Seccubus_v2
json/getAttachment.pl
Perl
apache-2.0
2,012
=head1 TITLE Implicit counter in for statements, possibly $#. =head1 VERSION Maintainer: John McNamara <jmcnamara@cpan.org> Date: 16 Aug 2000 Last Modified: 27 Sep 2000 Mailing List: perl6-language-flow@perl.org Number: 120 Version: 5 Status: Frozen Frozen since: v3 =head1 ABSTRACT The syntax of the Perl style C<for> statement could be augmented by the introduction of an implicit counter variable. The deprecated variable C<$#> could be used for this purpose due to its mnemonic association with C<$#array>. Other alternatives are also proposed: an explicit counter returned by a function; an explicit counter defined after foreach; an explicit counter defined by a scoping statement. =head1 DESCRIPTION The use of C<for> and C<foreach> statements in conjunction with the range operator, C<..>, are generally seen as good idiomatic Perl: @array = qw(sun moon stars rain); foreach $item (@array) { print $item, "\n"; } as opposed to the "endearing attachment to C" style: for ($i = 0; $i <= $#array; $i++) { print $array[$i], "\n"; } In particular, the foreach statement provides a useful level of abstraction when iterating over an array of objects: foreach $object (@array) { $object->getline; $object->parseline; $object->printline; } However, the abstraction breaks down as soon as there is a need to access the index as well as the variable: for ($i = 0; $i <= $#array; $i++) { # Note $array[$i]->index = $i; $array[$i]->getline; $array[$i]->parseline; $array[$i]->printline; } # Note - same applies to: foreach $i (0..$#array) Here we are dealing with array variables and indexes instead of objects. The addition of an implicit counter variable in C<for> statements would lead to a more elegant syntax. It is proposed the deprecated variable C<$#> should be used for this purpose due to its mnemonic association with C<$#array>. For example: foreach $item (@array) { print $item, " is at index ", $#, "\n"; } =head1 ALTERNATIVE METHODS Following discussion of this proposal on perl6-language-flow the following suggestions were made: =head2 Alternative 1 : Explicit counter returned by a function This was proposed by Mike Pastore who suggested reusing pos() and by Hildo Biersma who suggested using position(): foreach $item (@array) { print $item, " is at index ", pos(@array), "\n"; } # or: foreach $item (@array) { $index = some_counter_function(); print $item, " is at index ", $index, "\n"; } =head2 Alternative 2 : Explicit counter defined after foreach This was proposed by Chris Madsen and Tim Jenness, Jonathan Scott Duff made a similar pythonesque suggestion: foreach $item, $index (@array) { print $item, " is at index ", $index, "\n"; } Glenn Linderman added this could also be used for hashes: foreach $item $key ( %hash ) { print "$item is indexed by $key\n"; } Ariel Scolnicov suggested a variation on this through an extension of the C<each()>: while (($item, $index) = each(@array)) { print $item, " is at index ", $index, "\n"; } With this in mind Johan Vromans suggested the use of C<keys()> and C<values()> on arrays. A variation on this is an explicit counter after C<@array>. This was alluded to by Jonathan Scott Duff: foreach $item (@array) $index { print $item, " is at index ", $index, "\n"; } =head2 Alternative 3 : Explicit counter defined by a scoping statement This was proposed by Nathan Torkington. This behaves somewhat similarly to Tie::Counter. foreach $item (@array) { my $index : static = 0; # initialized each time foreach loop starts print "$item is at index $index\n"; $index++; } # or: foreach $item (@array) { my $index : counter = 0; # initialized to 0 first time # incremented by 1 subsequently print "$item is at index $index\n"; } =head1 IMPLEMENTATION There was no discussion about how this might be implemented. It was pointed out by more than one person it would inevitably incur an overhead. =head1 REFERENCES perlvar Alex Rhomberg proposed an implicit counter variable on clpm: http://x53.deja.com/getdoc.xp?AN=557218804&fmt=text and http://x52.deja.com/threadmsg_ct.xp?AN=580369190.1&fmt=text Craig Berry suggested C<$#>: http://x52.deja.com/threadmsg_ct.xp?AN=580403316.1&fmt=text
autarch/perlweb
docs/dev/perl6/rfc/120.pod
Perl
apache-2.0
4,575
# # 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 snmp_standard::mode::isdnusage; use base qw(centreon::plugins::templates::counter); use strict; use warnings; use Digest::MD5 qw(md5_hex); sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'bearer', type => 0 }, { name => 'isdn', type => 1, cb_prefix_output => 'prefix_isdn_output', message_multiple => 'All isdn channels are ok' } ]; $self->{maps_counters}->{isdn} = [ { label => 'in-calls', set => { key_values => [ { name => 'in', diff => 1 }, { name => 'display' } ], output_template => 'Incoming calls : %s', perfdatas => [ { label => 'in_calls', value => 'in', template => '%s', min => 0, label_extra_instance => 1, instance_use => 'display' }, ], } }, { label => 'out-calls', set => { key_values => [ { name => 'out', diff => 1 }, { name => 'display' } ], output_template => 'Outgoing calls : %s', perfdatas => [ { label => 'out_calls', value => 'out', template => '%s', min => 0, label_extra_instance => 1, instance_use => 'display' }, ], } }, ]; $self->{maps_counters}->{bearer} = [ { label => 'current-calls', set => { key_values => [ { name => 'active' }, { name => 'total' } ], output_template => 'Current calls : %s', perfdatas => [ { label => 'current_calls', value => 'active', template => '%s', min => 0, max => 'total' }, ], } }, ]; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, statefile => 1); bless $self, $class; $options{options}->add_options(arguments => { 'filter-name:s' => { name => 'filter_name' }, }); return $self; } sub prefix_isdn_output { my ($self, %options) = @_; return "ISDN channel '" . $options{instance_value}->{display} . "' "; } my %map_bearer_state = ( 1 => 'idle', 2 => 'connecting', 3 => 'connected', 4 => 'active', ); my $mapping = { isdnSigStatsInCalls => { oid => '.1.3.6.1.2.1.10.20.1.3.3.1.1' }, isdnSigStatsOutCalls => { oid => '.1.3.6.1.2.1.10.20.1.3.3.1.3' }, }; my $oid_isdnBearerOperStatus = '.1.3.6.1.2.1.10.20.1.2.1.1.2'; my $oid_isdnSignalingIfIndex = '.1.3.6.1.2.1.10.20.1.3.2.1.2'; my $oid_isdnSignalingStatsEntry = '.1.3.6.1.2.1.10.20.1.3.3.1'; my $oid_ifDescr = '.1.3.6.1.2.1.2.2.1.2'; sub manage_selection { my ($self, %options) = @_; $self->{isdn} = {}; $self->{bearer} = { active => 0, total => 0 }; my $snmp_result = $options{snmp}->get_multiple_table( oids => [ { oid => $oid_isdnBearerOperStatus }, { oid => $oid_isdnSignalingIfIndex }, { oid => $oid_isdnSignalingStatsEntry }, ], nothing_quit => 1 ); # Get interface name foreach my $oid (keys %{$snmp_result->{$oid_isdnSignalingIfIndex}}) { $options{snmp}->load(oids => [$oid_ifDescr], instances => [$snmp_result->{$oid_isdnSignalingIfIndex}->{$oid}]); } my $result_ifdesc = $options{snmp}->get_leef(nothing_quit => 1); foreach my $oid (keys %{$snmp_result->{$oid_isdnSignalingIfIndex}}) { $oid =~ /^$oid_isdnSignalingIfIndex\.(.*)/; my $instance = $1; my $display = $result_ifdesc->{$oid_ifDescr . '.' . $snmp_result->{$oid_isdnSignalingIfIndex}->{$oid_isdnSignalingIfIndex . '.' . $instance}}; if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $display !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping '" . $display . "': no matching filter name.", debug => 1); next; } my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result->{$oid_isdnSignalingStatsEntry}, instance => $instance); $self->{isdn}->{$instance} = { in => $result->{isdnSigStatsInCalls}, out => $result->{isdnSigStatsOutCalls}, display => $display }; } foreach my $oid (keys %{$snmp_result->{$oid_isdnBearerOperStatus}}) { my $status = defined($map_bearer_state{$snmp_result->{$oid_isdnBearerOperStatus}->{$oid}}) ? $map_bearer_state{$snmp_result->{$oid_isdnBearerOperStatus}->{$oid}} : 'unknown'; $self->{bearer}->{total}++; $self->{bearer}->{active}++ if ($status =~ /active/); } $self->{cache_name} = "isdn_usage_" . $self->{mode} . '_' . $options{snmp}->get_hostname() . '_' . $options{snmp}->get_port() . '_' . (defined($self->{option_results}->{filter_counters}) ? md5_hex($self->{option_results}->{filter_counters}) : md5_hex('all')); } 1; __END__ =head1 MODE Check ISDN usages (ISDN-MIB). =over 8 =item B<--filter-counters> Only display some counters (regexp can be used). Example: --filter-counters='^current-calls$' =item B<--filter-name> Filter by name (regexp can be used). =item B<--warning-*> Threshold warning. Can be: 'in-calls', 'out-calls', 'current-calls'. =item B<--critical-*> Threshold critical. Can be: 'in-calls', 'out-calls', 'current-calls'. =back =cut
centreon/centreon-plugins
snmp_standard/mode/isdnusage.pm
Perl
apache-2.0
6,261
package GraphSummarizer; use strict; use warnings; use HTML::TokeParser; use HTML::TreeBuilder; use JSON; use Text::Trim; use utf8; # chunkify HTML content sub _chunkify_content { my $raw_content = shift; my $chunks = shift; # TODO: should this logic (how to transform a modality prior to its tokenization) be configurable ? my $chunkified_content = undef; if ( ! ref( $chunkified_content ) ) { $chunkified_content = $raw_content; } else { $chunkified_content = join( " " , @{ $raw_content } ); } # tidy up content - just in case # $chunkified_content = HTML::Tidy::tidy( $chunkified_content ); my $p = HTML::TokeParser->new( \$chunkified_content , ignore_elements => [qw(script style)] ) || die "Unable to parse raw HTML: $!"; $p->empty_element_tags(1); # configure its behaviour my @stream; my @stream_context; my %matching; my %matching_context; my $empty_context = ""; my $in_script = 0; my @context; # prepare regexes my %nodeid2re; my %nodeid2replacement; if ( defined( $chunks ) ) { foreach my $chunk (@{$chunks}) { if ( $chunk->{type} ne 'np' ) { next; } my $chunk_id = $chunk->id(); my $chunk_matcher = $chunk->chunk_matcher(); my $replacement_string = $chunk->placeholder(); $nodeid2re{ $chunk_id } = $chunk_matcher; $nodeid2replacement{ $chunk_id } = " $replacement_string "; } } while (my $token = $p->get_token) { my $type = $token->[0]; my $tag = $token->[1]; my $value = $token->[2]; if ( $tag eq 'script' ) { if ( $type eq 'S' ) { $in_script++; } else { $in_script--; } next; } if ( $in_script ) { next; } my $fragment = undef; if ( $type eq 'S' ) { $fragment = join("", "<", $tag, ">"); push @context, $tag; next; } elsif ( $type eq 'E' ) { $fragment = join("", "</", $tag, ">"); pop @context; next; } # should rename those variables :-P my $cleansed_text = $tag; if ( defined($cleansed_text) ) { $cleansed_text =~ s/\s+/ /g; trim($cleansed_text); $fragment = _render_html("<html><body>$cleansed_text</body></html>"); #$fragment = $cleansed_text; } if ( defined($fragment) && length($fragment) ) { foreach my $nodeid (keys( %nodeid2re )) { my $re = $nodeid2re{ $nodeid }; my $replacement = $nodeid2replacement{ $nodeid }; if ( $fragment =~ s/$re/$replacement/ig ) { # print STDERR "match for $chunk_matcher ($chunk_id) --> $token --> $replacement_string\n"; $matching{ $nodeid }++; $matching_context{ join("::", scalar(@context)?$context[$#context]:"", $nodeid) }++; } } # allow partial match ? # for now proceed with exact match, will look into partial match if we end up missing out on the extraction of too many # target-specific NPs push @stream, $fragment; push @stream_context, scalar(@context)?$context[$#context]:$empty_context; } } # TODO: can we remove this eventually ? # in case this was not HTML content if ( scalar(@stream) == 1 ) { @stream = split /\s+/, $chunkified_content; @stream_context = ( $empty_context ); } return (\@stream, \@stream_context, \%matching, \%matching_context); } sub _render_html { my $html_string = shift; my $text = ""; eval { my $tree = HTML::TreeBuilder->new; # empty tree $tree->utf8_mode(0); my $p = $tree->parse($html_string); $text = $p->as_trimmed_text; #$p->delete; $tree = $tree->delete; }; return $text; } # fine grain tokenization of content (assumes chunks/phrases have been properly abstracted out) sub _chunk_tokenize_content { my $mapped_content_stream = shift; my @tokenized_content; foreach my $content_element (@$mapped_content_stream) { if ( $content_element !~ m/^\</ ) { my @tokens = split /\s+/, $content_element; push @tokenized_content, @tokens; } else { push @tokenized_content, $content_element; } } return \@tokenized_content; } 1;
ypetinot/web-summarization
src/perl/GraphSummarizer.pm
Perl
apache-2.0
4,143
% Example from "regular directional types" paper gen([0,1]). gen([0|X]) :- gen(X). trans(X,Y) :- trans1(X,Y). trans([1|X],[0|Y]) :- trans2(X,Y). trans1([0,1|T],[1,0|T]). trans1([H|T],[H|T1]) :- trans1(T,T1). trans2([0],[1]). trans2([H|T],[H|T1]) :- trans2(T,T1). reachable(X) :- gen(X). reachable(X) :- reachable(Y), trans(Y,X).
leuschel/logen
old_logen/filter_prop/Tests/podelski.pl
Perl
apache-2.0
348
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =cut package EnsEMBL::Web::Component::Variation::LOVD; use strict; use warnings; no warnings "uninitialized"; use EnsEMBL::Web::Document::Table; use EnsEMBL::Web::File::Utils::URL qw(read_file); use parent qw(EnsEMBL::Web::Component::Variation); sub _init { my $self = shift; $self->cacheable( 1 ); $self->ajaxable( 1 ); } sub caption { return undef; } sub content { my $self = shift; my $hub = $self->hub; my $lovd = $hub->species_defs->LOVD_URL; return unless $lovd; ## Fetch LOVD data my $html; my $object = $self->object; my %mappings = %{$object->variation_feature_mapping}; my $column_set = []; my $all_rows = []; while (my ($key, $data) = each (%mappings)) { my $region = $mappings{$key}{'Chr'}; my $start = $mappings{$key}{'start'}; my $end = $mappings{$key}{'end'}; my $search = sprintf '%s?build=%s&position=chr%s:%s', $lovd, $hub->species_defs->UCSC_GOLDEN_PATH, $region, $start; $search .= '_'.$end if ($end != $start); my $response = read_file($search, {'hub' => $hub, 'nice' => 1}); if ($response->{'error'}) { #warn ">>> ERROR ".$response->{'error'}; $html = '<p>Error fetching LOVD data</p>'; } elsif ($response->{'content'}) { my ($columns, $rows) = $self->munge_content($response->{'content'}); $column_set = $columns; shift @$column_set; push @$all_rows, @$rows; } } if (scalar @$all_rows) { my $plural = scalar @$all_rows > 1 ? 'these positions' : 'this position'; $html .= "<p>The following data from LOVD (Leiden Open Variation Database) are also found at $plural:</p>"; my $params = { exportable => 0 }; $params->{'data_table'} = 1 if (scalar @$all_rows > 2); my $table = new EnsEMBL::Web::Document::Table($column_set, $all_rows, $params); $html .= $table->render; } else { $html .= '<p>No LOVD data was found for this variant</p>'; } return $html; } sub munge_content { my ($self, $content) = @_; my $html; my $columns = []; my $col_keys = []; my $rows = []; my $i = 0; foreach my $row ( split /\n|\r/, $content ) { $row =~ s/^"//; $row =~ s/"$//; my @cols = split(/"(\s+)"/, $row); if ($i == 0) { $col_keys = \@cols; foreach (@cols) { my $header = $_; $header =~ s/_/ /; $header = 'Location' if $_ eq 'g_position'; $header = 'Gene ID' if $_ eq 'gene_id'; $header = 'LOVD variant ID' if $_ eq 'variant_id'; $header = 'More information' if $_ eq 'url'; push @$columns, {'key' => $_, 'title' => $header}; } } else { my $row = {}; my $j = 0; foreach (@$col_keys) { my $data = $cols[$j]; my $display; if ($_ eq 'url') { $display = sprintf '<a href="%s">External link to LOVD</a>', $data; } elsif ($_ eq 'g_position') { (my $coords = $data) =~ s/^chr//; $coords =~ s/_/-/; my $url = $self->hub->url({'type'=>'Location','action'=>'View','r'=>$coords}); $display = sprintf '<a href="%s">%s</a>', $url, $coords; } elsif ($_ eq 'gene_id') { my $url = $self->hub->url({'type'=>'Gene','action'=>'Summary','g'=>$data}); $display = sprintf '<a href="%s">%s</a>', $url, $data; } else { $display = $data; } $row->{$_} = $display; $j++; } push @$rows, $row; } $i++; } return ($columns, $rows); } 1;
muffato/public-plugins
ensembl/modules/EnsEMBL/Web/Component/Variation/LOVD.pm
Perl
apache-2.0
4,278
# # 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::isam::snmp::mode::cpu; use base qw(centreon::plugins::templates::counter); use strict; use warnings; sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'cpu', type => 1, cb_prefix_output => 'prefix_cpu_output', message_multiple => 'All CPU usages are ok' } ]; $self->{maps_counters}->{cpu} = [ { label => 'usage', nlabel => 'cpu.utilization.percentage', set => { key_values => [ { name => 'usage' }, { name => 'display' }, ], output_template => 'Usage : %.2f %%', perfdatas => [ { label => 'cpu', value => 'usage', template => '%.2f', min => 0, max => 100, unit => '%', label_extra_instance => 1, instance_use => 'display' }, ], } }, ]; } sub prefix_cpu_output { my ($self, %options) = @_; return "CPU '" . $options{instance_value}->{display} . "' "; } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; $options{options}->add_options(arguments => { }); return $self; } my $mapping = { cpuLoadAverage => { oid => '.1.3.6.1.4.1.637.61.1.9.29.1.1.4' }, eqptSlotActualType => { oid => '.1.3.6.1.4.1.637.61.1.23.3.1.3' }, eqptBoardInventorySerialNumber => { oid => '.1.3.6.1.4.1.637.61.1.23.3.1.19' }, }; sub manage_selection { my ($self, %options) = @_; my $snmp_result = $options{snmp}->get_multiple_table(oids => [ { oid => $mapping->{cpuLoadAverage}->{oid} }, { oid => $mapping->{eqptSlotActualType}->{oid} }, { oid => $mapping->{eqptBoardInventorySerialNumber}->{oid} }, ], return_type => 1, nothing_quit => 1); $self->{cpu} = {}; foreach my $oid (keys %{$snmp_result}) { next if ($oid !~ /^$mapping->{cpuLoadAverage}->{oid}\.(.*)$/); my $instance = $1; my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $instance); my $name = $result->{eqptBoardInventorySerialNumber} . '_' . $result->{eqptSlotActualType}; $self->{cpu}->{$instance} = { display => $name, usage => $result->{cpuLoadAverage} }; } } 1; __END__ =head1 MODE Check CPU usages. =over 8 =item B<--warning-usage> Threshold warning. =item B<--critical-usage> Threshold critical. =back =cut
Tpo76/centreon-plugins
network/alcatel/isam/snmp/mode/cpu.pm
Perl
apache-2.0
3,549
# # 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::mode::listsnapmirrors; 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' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); } sub manage_selection { my ($self, %options) = @_; my $result = $options{custom}->get(path => '/snap-mirrors'); foreach my $snapmirror (@{$result}) { if (defined($self->{option_results}->{filter_name}) && $self->{option_results}->{filter_name} ne '' && $snapmirror->{source_location} !~ /$self->{option_results}->{filter_name}/) { $self->{output}->output_add(long_msg => "skipping '" . $snapmirror->{name} . "': no matching filter name.", debug => 1); next; } $self->{snapmirrors}->{$snapmirror->{key}} = { source_location => $snapmirror->{source_location}, destination_location => $snapmirror->{destination_location}, mirror_state => $snapmirror->{mirror_state}, is_healthy => $snapmirror->{is_healthy}, } } } sub run { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $snapmirror (sort keys %{$self->{snapmirrors}}) { $self->{output}->output_add(long_msg => sprintf("[source_location = %s] [destination_location = %s] [mirror_state = %s] [is_healthy = %s]", $self->{snapmirrors}->{$snapmirror}->{source_location}, $self->{snapmirrors}->{$snapmirror}->{destination_location}, $self->{snapmirrors}->{$snapmirror}->{mirror_state}, $self->{snapmirrors}->{$snapmirror}->{is_healthy})); } $self->{output}->output_add(severity => 'OK', short_msg => 'List snap mirrors:'); $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 => ['source_location', 'destination_location', 'mirror_state', 'is_healthy']); } sub disco_show { my ($self, %options) = @_; $self->manage_selection(%options); foreach my $snapmirror (sort keys %{$self->{snapmirrors}}) { $self->{output}->add_disco_entry( source_location => $self->{snapmirrors}->{$snapmirror}->{source_location}, destination_location => $self->{snapmirrors}->{$snapmirror}->{destination_location}, mirror_state => $self->{snapmirrors}->{$snapmirror}->{mirror_state}, is_healthy => $self->{snapmirrors}->{$snapmirror}->{is_healthy}, ); } } 1; __END__ =head1 MODE List snap mirrors. =over 8 =item B<--filter-name> Filter snapmirror name (can be a regexp). =back =cut
centreon/centreon-plugins
storage/netapp/ontap/oncommandapi/mode/listsnapmirrors.pm
Perl
apache-2.0
4,049
#!/usr/bin/perl # Copyright {2017} INRA (Institut National de Recherche Agronomique - FRANCE) # # 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. my $VERSION = '0.1'; my $lastModif = '12April2017'; use strict; use warnings; use DBI; use Bio::SeqIO; use Bio::SeqFeature::Generic; use Statistics::Descriptive; use Data::Dumper; use File::Basename; use Getopt::Long; ############################### #Custom Module use lib '/usr/lib/perl5'; ############################### my $datasetlist= $ARGV[0]; my $directory= $ARGV[1]; GetOptions("h|help" => \&help); &main($datasetlist,$directory); #********************************************************************************************* #*********************************** MAIN ****************************************** # ~/bin/dev/textMining_V5.pl -p 50 -s datasets.txt -dir ../WorkingDirectoryInsertionProcess/ #********************************************************************************************* sub main { my $self = {}; bless $self; my $dataset_list = shift; my $dir = shift; $self->{param}->{datasets}= $dataset_list; $self->{param}->{directory}= $dir; my @files = () ; open(GO, $dataset_list) or die "impossible d'ouvrir $dataset_list ! \n" ; while (<GO>){ if($_=~ m/^#/){ next; } else{ chomp; $_ =~ /([^\t]*)\t[^\t]*\t[^\t]*.*/ ; push(@files, "$1"); #$1 : SRP #$2 : study #$3 : specie } } close GO ; foreach my $file (@files){ chomp$file; my $srp=$file ; $self->{currentSRP}=$srp; #$gse=~s/(-A-.+)|(-GPL.+)//; #$gse=~s/a$|b$|c$|d$//; $self->{InfosFile} = $dir."/".$self->{currentSRP}."/Assembly_Trinity/".$self->{currentSRP}."_genes_counts.TMM.fpkm.matrix"; $self->readFileInfo(); my $wanted=20000; my $nbTranscrits=scalar(keys(%{$self->{Final}})); if($nbTranscrits<20000){ $wanted=$nbTranscrits; } my $newfile= $self->{param}->{directory}."/".$self->{currentSRP}."/".$self->{currentSRP}."/".$self->{currentSRP}."_20000genes_counts.TMM.fpkm.matrix"; open (FILE2,">$newfile"); my $m=0; foreach my $value ( sort {$b<=> $a} keys %{$self->{Final}} ) { if($m<$wanted){ $m+=1 } } close FILE2; } } #********************************************************************************************* #********************************************************************************************* #********************************************************************************************* ### ### read file describing the samples, conditions, terms associates to data mining ### sub readFileInfo{ my $self = shift; #~ -e $self->{InfosFile} or -e $self->{InfosFile} or $logger->logdie("Cannot find file: ".$self->{InfosFile}."\n"); open (FILE, "<$self->{InfosFile}"); my $n=0; $self->{CountAllTerms}=0; while (<FILE>){ chomp; if ($_ eq "" || $_ =~ m/^ /){ ### ne prends pas en compte les lignes vides $self->{Header}=$_; } else{ my @infos=split("\t",$_); my $gene= $infos[0]; my $nubVal=(scalar(@infos))-1; my $moySum=0; foreach ( my $i=1 ; $i < scalar(@infos) ; $i+=1){ $moySum+=$infos[$i]; } my $moyenne=$moySum/$nubVal; my $somme=0; foreach ( my $j=1 ; $j < scalar(@infos) ; $j+=1){ $somme+=(($infos[$j]-$moyenne)*($infos[$j]-$moyenne)); } my $ecart=sqrt($somme/16); $self->{Final}->{$ecart}=$_; } } close FILE; return 1; } sub help { my $prog = basename($0) ; print STDERR <<EOF ; #### $prog #### # AUTHOR: Ambre-Aurore Josselin # VERSION: $VERSION - $lastModif # PURPOSE: USAGE: $prog [OPTIONS] ### OPTIONS ### -v, --versbosity <integer> mode of verbosity (1-4) [default: 1] -h, --help print this help EOF exit(1) ; } __END__
inralpgp/fishandchips
Dataset_Insertion_Process/0-selection_20000/0-selection_20000.pl
Perl
apache-2.0
4,296
:- use_package(remote). :- include(port1). :- include(port2). main :- port1(Port), set_connection(Port, Connection), serve_connection(Connection). r(X):- port2(Port), p(X) @ a(localhost, Port). q(a).
leuschel/ecce
www/CiaoDE/ciao/library/p2p/test/test1/test1.pl
Perl
apache-2.0
209
#!/usr/bin/perl -w # POK header # # The following file is a part of the POK project. Any modification should # be made according to the POK licence. You CANNOT use this file or a part # of a file for your own project. # # For more information on the POK licence, please see our LICENCE FILE # # Please follow the coding guidelines described in doc/CODING_GUIDELINES # # Copyright (c) 2007-2009 POK team # # Created by julien on Sun Aug 10 12:45:15 2008 # #!/usr/bin/perl -w use strict; my $user; my $date; my $force; my $year; ##################################################### # COMMON FUNCTIONS ##################################################### sub has_header { my $filename = shift; my $c; my $i = 3; open (MYFILE, $filename); while ($i > 0) { $c = <MYFILE>; if ((defined ($c)) && ($c =~ m/.*POK header.*/)) { close (MYFILE); return 1; } $i--; } close (MYFILE); return 0; } sub get_file_content { my $filename = shift; my @c; my $t; return if ! -f $filename; open (MYFILE, $filename); while ($t = <MYFILE>) { push (@c,$t); } close (MYFILE); return @c; } sub treat_file { my $filename = shift; treat_c_file ($filename) if ($filename =~ m/\.c$/); treat_c_file ($filename) if ($filename =~ m/\.h$/); treat_latex_file ($filename) if ($filename =~ m/\.tex$/); treat_txt_file ($filename) if ($filename =~ m/\.txt$/); treat_perl_file ($filename) if ($filename =~ m/\.pl$/); treat_perl_file ($filename) if ($filename =~ m/\.pm$/); treat_aadl_file ($filename) if ($filename =~ m/\.aadl$/); } sub treat_dir { my $dirname = shift; my $e; my $cname; my @elts; opendir (MYDIR, $dirname) or die ("cannot open rootdir"); @elts = readdir (MYDIR); closedir (MYDIR); foreach $e (@elts) { next if ($e eq "."); next if ($e eq ".."); next if ($e =~ m/^\./); $cname = "$dirname/$e"; treat_file ($cname) if -f $cname; treat_dir ($cname) if -d $cname; } } ##################################################### # C FUNCTIONS ##################################################### sub add_c_header { my $filename = shift; my @contents; my $v; return if ! -f $filename; @contents = get_file_content ($filename); open (MYFILE, ">$filename"); seek (MYFILE,0,0); print MYFILE "/*\n"; print MYFILE " * POK header\n"; print MYFILE " * \n"; print MYFILE " * The following file is a part of the POK project. Any modification should\n"; print MYFILE " * made according to the POK licence. You CANNOT use this file or a part of\n"; print MYFILE " * this file is this part of a file for your own project\n"; print MYFILE " *\n"; print MYFILE " * For more information on the POK licence, please see our LICENCE FILE\n"; print MYFILE " *\n"; print MYFILE " * Please follow the coding guidelines described in doc/CODING_GUIDELINES\n"; print MYFILE " *\n"; print MYFILE " * Copyright (c) 2007-$year POK team \n"; print MYFILE " *\n"; print MYFILE " * Created by $user on $date \n"; print MYFILE " */\n\n"; foreach $v (@contents) { print MYFILE $v; } close (MYFILE); } sub remove_c_header { my $filename = shift; my @contents; my $v; my $i; return if ! -f $filename; @contents = get_file_content ($filename); $i = 16; unlink ($filename) or die ("cannot remove $filename"); open (MYFILE, ">$filename"); seek (MYFILE,0,0); foreach $v (@contents) { if ($i == 0) { print MYFILE $v; } else { $i--; } } close (MYFILE); } sub treat_c_file { my $filename = shift; if ((has_header ($filename) == 1) && ($force == 1)) { remove_c_header ($filename); } if (has_header ($filename) == 0) { add_c_header ($filename); } } ##################################################### # LaTeX FUNCTIONS ##################################################### sub add_latex_header { my $filename = shift; my @contents; my $v; return if ! -f $filename; @contents = get_file_content ($filename); open (MYFILE, ">$filename"); seek (MYFILE,0,0); print MYFILE "%\n"; print MYFILE "% POK header\n"; print MYFILE "% \n"; print MYFILE "% The following file is a part of the POK project. Any modification should\n"; print MYFILE "% be made according to the POK licence. You CANNOT use this file or a part\n"; print MYFILE "% of a file for your own project.\n"; print MYFILE "%\n"; print MYFILE "% For more information on the POK licence, please see our LICENCE FILE\n"; print MYFILE "%\n"; print MYFILE "% Please follow the coding guidelines described in doc/CODING_GUIDELINES\n"; print MYFILE "%\n"; print MYFILE "% Copyright (c) 2007-$year POK team \n"; print MYFILE "%\n"; print MYFILE "% Created by $user on $date \n"; print MYFILE "%\n\n\n"; foreach $v (@contents) { print MYFILE $v; } close (MYFILE); } sub treat_latex_file { my $filename = shift; if (has_header ($filename) == 0) { add_latex_header ($filename); } } ##################################################### # TEXT FUNCTIONS ##################################################### sub treat_txt_file { my $filename = shift; # Nothing to add at this moment } ##################################################### # PERL FUNCTIONS ##################################################### sub add_perl_header { my $filename = shift; my @contents; my $v; return if ! -f $filename; @contents = get_file_content ($filename); open (MYFILE, ">$filename"); seek (MYFILE,0,0); print MYFILE $contents[0]; print MYFILE "# POK header\n"; print MYFILE "# \n"; print MYFILE "# The following file is a part of the POK project. Any modification should\n"; print MYFILE "# be made according to the POK licence. You CANNOT use this file or a part \n"; print MYFILE "# of a file for your own project.\n"; print MYFILE "#\n"; print MYFILE "# For more information on the POK licence, please see our LICENCE FILE\n"; print MYFILE "#\n"; print MYFILE "# Please follow the coding guidelines described in doc/CODING_GUIDELINES\n"; print MYFILE "#\n"; print MYFILE "# Copyright (c) 2007-$year POK team \n"; print MYFILE "#\n"; print MYFILE "# Created by $user on $date \n"; print MYFILE "#\n\n\n"; foreach $v (@contents) { print MYFILE $v; } close (MYFILE); } sub treat_perl_file { my $filename = shift; if (has_header ($filename) == 0) { add_perl_header ($filename); } } ##################################################### # AADL FUNCTIONS ##################################################### sub add_aadl_header { my $filename = shift; my @contents; my $v; return if ! -f $filename; @contents = get_file_content ($filename); open (MYFILE, ">$filename"); seek (MYFILE,0,0); print MYFILE "--\n"; print MYFILE "-- POK header\n"; print MYFILE "-- \n"; print MYFILE "-- The following file is a part of the POK project. Any modification should\n"; print MYFILE "-- be made according to the POK licence. You CANNOT use this file or a part \n"; print MYFILE "-- of a file for your own project.\n"; print MYFILE "-- \n"; print MYFILE "-- For more information on the POK licence, please see our LICENCE FILE\n"; print MYFILE "--\n"; print MYFILE "-- Please follow the coding guidelines described in doc/CODING_GUIDELINES\n"; print MYFILE "--\n"; print MYFILE "-- Copyright (c) 2007-$year POK team \n"; print MYFILE "--\n"; print MYFILE "-- Created by $user on $date \n"; print MYFILE "--\n"; foreach $v (@contents) { print MYFILE $v; } close (MYFILE); } sub remove_aadl_header { my $filename = shift; my @contents; my $v; my $i; return if ! -f $filename; @contents = get_file_content ($filename); $i = 16; unlink ($filename) or die ("cannot remove $filename"); open (MYFILE, ">$filename"); seek (MYFILE,0,0); foreach $v (@contents) { if ($i == 0) { print MYFILE $v; } else { $i--; } } close (MYFILE); } sub treat_aadl_file { my $filename = shift; if ((has_header ($filename) == 1) && ($force == 1)) { remove_aadl_header ($filename); } if (has_header ($filename) == 0) { add_aadl_header ($filename); } } ##################################################### # MAIN ENTRYPOINT ##################################################### $user = $ENV{'USER'}; $date = gmtime(); my @date_array = gmtime(); $year = $date_array[5] + 1900; $force = 0; $force = 1 if (defined ($ARGV[0]) && ($ARGV[0] eq '--force')); treat_dir ($ENV{'PWD'});
phipse/pok
misc/update-headers.pl
Perl
bsd-2-clause
8,695
########################################################################### # # 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::luo - Locale data examples for the luo locale. =head1 DESCRIPTION This pod file contains examples of the locale data available for the Luo locale. =head2 Days =head3 Wide (format) Wuok Tich Tich Ariyo Tich Adek Tich Ang’wen Tich Abich Ngeso Jumapil =head3 Abbreviated (format) WUT TAR TAD TAN TAB NGS JMP =head3 Narrow (format) W T T T T N J =head3 Wide (stand-alone) Wuok Tich Tich Ariyo Tich Adek Tich Ang’wen Tich Abich Ngeso Jumapil =head3 Abbreviated (stand-alone) WUT TAR TAD TAN TAB NGS JMP =head3 Narrow (stand-alone) W T T T T N J =head2 Months =head3 Wide (format) Dwe mar Achiel Dwe mar Ariyo Dwe mar Adek Dwe mar Ang’wen Dwe mar Abich Dwe mar Auchiel Dwe mar Abiriyo Dwe mar Aboro Dwe mar Ochiko Dwe mar Apar Dwe mar gi achiel Dwe mar Apar gi ariyo =head3 Abbreviated (format) DAC DAR DAD DAN DAH DAU DAO DAB DOC DAP DGI DAG =head3 Narrow (format) C R D N B U B B C P C P =head3 Wide (stand-alone) Dwe mar Achiel Dwe mar Ariyo Dwe mar Adek Dwe mar Ang’wen Dwe mar Abich Dwe mar Auchiel Dwe mar Abiriyo Dwe mar Aboro Dwe mar Ochiko Dwe mar Apar Dwe mar gi achiel Dwe mar Apar gi ariyo =head3 Abbreviated (stand-alone) DAC DAR DAD DAN DAH DAU DAO DAB DOC DAP DGI DAG =head3 Narrow (stand-alone) C R D N B U B B C P C P =head2 Quarters =head3 Wide (format) nus mar nus 1 nus mar nus 2 nus mar nus 3 nus mar nus 4 =head3 Abbreviated (format) NMN1 NMN2 NMN3 NMN4 =head3 Narrow (format) 1 2 3 4 =head3 Wide (stand-alone) nus mar nus 1 nus mar nus 2 nus mar nus 3 nus mar nus 4 =head3 Abbreviated (stand-alone) NMN1 NMN2 NMN3 NMN4 =head3 Narrow (stand-alone) 1 2 3 4 =head2 Eras =head3 Wide (format) Kapok Kristo obiro Ka Kristo osebiro =head3 Abbreviated (format) BC AD =head3 Narrow (format) BC AD =head2 Date Formats =head3 Full 2008-02-05T18:30:30 = Tich Ariyo, 5 Dwe mar Ariyo 2008 1995-12-22T09:05:02 = Tich Abich, 22 Dwe mar Apar gi ariyo 1995 -0010-09-15T04:44:23 = Ngeso, 15 Dwe mar Ochiko -10 =head3 Long 2008-02-05T18:30:30 = 5 Dwe mar Ariyo 2008 1995-12-22T09:05:02 = 22 Dwe mar Apar gi ariyo 1995 -0010-09-15T04:44:23 = 15 Dwe mar Ochiko -10 =head3 Medium 2008-02-05T18:30:30 = 5 DAR 2008 1995-12-22T09:05:02 = 22 DAG 1995 -0010-09-15T04:44:23 = 15 DOC -10 =head3 Short 2008-02-05T18:30:30 = 05/02/2008 1995-12-22T09:05:02 = 22/12/1995 -0010-09-15T04:44:23 = 15/09/-10 =head2 Time Formats =head3 Full 2008-02-05T18:30:30 = 18:30:30 UTC 1995-12-22T09:05:02 = 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 = Tich Ariyo, 5 Dwe mar Ariyo 2008 18:30:30 UTC 1995-12-22T09:05:02 = Tich Abich, 22 Dwe mar Apar gi ariyo 1995 09:05:02 UTC -0010-09-15T04:44:23 = Ngeso, 15 Dwe mar Ochiko -10 04:44:23 UTC =head3 Long 2008-02-05T18:30:30 = 5 Dwe mar Ariyo 2008 18:30:30 UTC 1995-12-22T09:05:02 = 22 Dwe mar Apar gi ariyo 1995 09:05:02 UTC -0010-09-15T04:44:23 = 15 Dwe mar Ochiko -10 04:44:23 UTC =head3 Medium 2008-02-05T18:30:30 = 5 DAR 2008 18:30:30 1995-12-22T09:05:02 = 22 DAG 1995 09:05:02 -0010-09-15T04:44:23 = 15 DOC -10 04:44:23 =head3 Short 2008-02-05T18:30:30 = 05/02/2008 18:30 1995-12-22T09:05:02 = 22/12/1995 09:05 -0010-09-15T04:44:23 = 15/09/-10 04:44 =head2 Available Formats =head3 E (ccc) 2008-02-05T18:30:30 = TAR 1995-12-22T09:05:02 = TAB -0010-09-15T04:44:23 = NGS =head3 EHm (E HH:mm) 2008-02-05T18:30:30 = TAR 18:30 1995-12-22T09:05:02 = TAB 09:05 -0010-09-15T04:44:23 = NGS 04:44 =head3 EHms (E HH:mm:ss) 2008-02-05T18:30:30 = TAR 18:30:30 1995-12-22T09:05:02 = TAB 09:05:02 -0010-09-15T04:44:23 = NGS 04:44:23 =head3 Ed (d, E) 2008-02-05T18:30:30 = 5, TAR 1995-12-22T09:05:02 = 22, TAB -0010-09-15T04:44:23 = 15, NGS =head3 Ehm (E h:mm a) 2008-02-05T18:30:30 = TAR 6:30 PM 1995-12-22T09:05:02 = TAB 9:05 AM -0010-09-15T04:44:23 = NGS 4:44 AM =head3 Ehms (E h:mm:ss a) 2008-02-05T18:30:30 = TAR 6:30:30 PM 1995-12-22T09:05:02 = TAB 9:05:02 AM -0010-09-15T04:44:23 = NGS 4:44:23 AM =head3 Gy (G y) 2008-02-05T18:30:30 = AD 2008 1995-12-22T09:05:02 = AD 1995 -0010-09-15T04:44:23 = BC -10 =head3 GyMMM (G y MMM) 2008-02-05T18:30:30 = AD 2008 DAR 1995-12-22T09:05:02 = AD 1995 DAG -0010-09-15T04:44:23 = BC -10 DOC =head3 GyMMMEd (G y MMM d, E) 2008-02-05T18:30:30 = AD 2008 DAR 5, TAR 1995-12-22T09:05:02 = AD 1995 DAG 22, TAB -0010-09-15T04:44:23 = BC -10 DOC 15, NGS =head3 GyMMMd (G y MMM d) 2008-02-05T18:30:30 = AD 2008 DAR 5 1995-12-22T09:05:02 = AD 1995 DAG 22 -0010-09-15T04:44:23 = BC -10 DOC 15 =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, M/d) 2008-02-05T18:30:30 = TAR, 2/5 1995-12-22T09:05:02 = TAB, 12/22 -0010-09-15T04:44:23 = NGS, 9/15 =head3 MMM (LLL) 2008-02-05T18:30:30 = DAR 1995-12-22T09:05:02 = DAG -0010-09-15T04:44:23 = DOC =head3 MMMEd (E, MMM d) 2008-02-05T18:30:30 = TAR, DAR 5 1995-12-22T09:05:02 = TAB, DAG 22 -0010-09-15T04:44:23 = NGS, DOC 15 =head3 MMMMEd (E, MMMM d) 2008-02-05T18:30:30 = TAR, Dwe mar Ariyo 5 1995-12-22T09:05:02 = TAB, Dwe mar Apar gi ariyo 22 -0010-09-15T04:44:23 = NGS, Dwe mar Ochiko 15 =head3 MMMMd (MMMM d) 2008-02-05T18:30:30 = Dwe mar Ariyo 5 1995-12-22T09:05:02 = Dwe mar Apar gi ariyo 22 -0010-09-15T04:44:23 = Dwe mar Ochiko 15 =head3 MMMd (MMM d) 2008-02-05T18:30:30 = DAR 5 1995-12-22T09:05:02 = DAG 22 -0010-09-15T04:44:23 = DOC 15 =head3 Md (M/d) 2008-02-05T18:30:30 = 2/5 1995-12-22T09:05:02 = 12/22 -0010-09-15T04:44:23 = 9/15 =head3 d (d) 2008-02-05T18:30:30 = 5 1995-12-22T09:05:02 = 22 -0010-09-15T04:44:23 = 15 =head3 h (h a) 2008-02-05T18:30:30 = 6 PM 1995-12-22T09:05:02 = 9 AM -0010-09-15T04:44:23 = 4 AM =head3 hm (h:mm a) 2008-02-05T18:30:30 = 6:30 PM 1995-12-22T09:05:02 = 9:05 AM -0010-09-15T04:44:23 = 4:44 AM =head3 hms (h:mm:ss a) 2008-02-05T18:30:30 = 6:30:30 PM 1995-12-22T09:05:02 = 9:05:02 AM -0010-09-15T04:44:23 = 4:44:23 AM =head3 hmsv (h:mm:ss a v) 2008-02-05T18:30:30 = 6:30:30 PM UTC 1995-12-22T09:05:02 = 9:05:02 AM UTC -0010-09-15T04:44:23 = 4:44:23 AM UTC =head3 hmv (h:mm a v) 2008-02-05T18:30:30 = 6:30 PM UTC 1995-12-22T09:05:02 = 9:05 AM UTC -0010-09-15T04:44:23 = 4:44 AM UTC =head3 ms (mm:ss) 2008-02-05T18:30:30 = 30:30 1995-12-22T09:05:02 = 05:02 -0010-09-15T04:44:23 = 44:23 =head3 y (y) 2008-02-05T18:30:30 = 2008 1995-12-22T09:05:02 = 1995 -0010-09-15T04:44:23 = -10 =head3 yM (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, M/d/y) 2008-02-05T18:30:30 = TAR, 2/5/2008 1995-12-22T09:05:02 = TAB, 12/22/1995 -0010-09-15T04:44:23 = NGS, 9/15/-10 =head3 yMMM (MMM y) 2008-02-05T18:30:30 = DAR 2008 1995-12-22T09:05:02 = DAG 1995 -0010-09-15T04:44:23 = DOC -10 =head3 yMMMEd (E, MMM d, y) 2008-02-05T18:30:30 = TAR, DAR 5, 2008 1995-12-22T09:05:02 = TAB, DAG 22, 1995 -0010-09-15T04:44:23 = NGS, DOC 15, -10 =head3 yMMMM (MMMM y) 2008-02-05T18:30:30 = Dwe mar Ariyo 2008 1995-12-22T09:05:02 = Dwe mar Apar gi ariyo 1995 -0010-09-15T04:44:23 = Dwe mar Ochiko -10 =head3 yMMMd (y MMM d) 2008-02-05T18:30:30 = 2008 DAR 5 1995-12-22T09:05:02 = 1995 DAG 22 -0010-09-15T04:44:23 = -10 DOC 15 =head3 yMd (y-MM-dd) 2008-02-05T18:30:30 = 2008-02-05 1995-12-22T09:05:02 = 1995-12-22 -0010-09-15T04:44:23 = -10-09-15 =head3 yQQQ (QQQ y) 2008-02-05T18:30:30 = NMN1 2008 1995-12-22T09:05:02 = NMN4 1995 -0010-09-15T04:44:23 = NMN3 -10 =head3 yQQQQ (QQQQ y) 2008-02-05T18:30:30 = nus mar nus 1 2008 1995-12-22T09:05:02 = nus mar nus 4 1995 -0010-09-15T04:44:23 = nus mar nus 3 -10 =head2 Miscellaneous =head3 Prefers 24 hour time? Yes =head3 Local first day of the week 1 (Wuok Tich) =head1 SUPPORT See L<DateTime::Locale>. =cut
jkb78/extrajnm
local/lib/perl5/DateTime/Locale/luo.pod
Perl
mit
9,969
=pod =head1 NAME SSL_CTX_set_session_id_context, SSL_set_session_id_context - set context within which session can be reused (server side only) =head1 SYNOPSIS #include <openssl/ssl.h> int SSL_CTX_set_session_id_context(SSL_CTX *ctx, const unsigned char *sid_ctx, unsigned int sid_ctx_len); int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx, unsigned int sid_ctx_len); =head1 DESCRIPTION SSL_CTX_set_session_id_context() sets the context B<sid_ctx> of length B<sid_ctx_len> within which a session can be reused for the B<ctx> object. SSL_set_session_id_context() sets the context B<sid_ctx> of length B<sid_ctx_len> within which a session can be reused for the B<ssl> object. =head1 NOTES Sessions are generated within a certain context. When exporting/importing sessions with B<i2d_SSL_SESSION>/B<d2i_SSL_SESSION> it would be possible, to re-import a session generated from another context (e.g. another application), which might lead to malfunctions. Therefore each application must set its own session id context B<sid_ctx> which is used to distinguish the contexts and is stored in exported sessions. The B<sid_ctx> can be any kind of binary data with a given length, it is therefore possible to use e.g. the name of the application and/or the hostname and/or service name ... The session id context becomes part of the session. The session id context is set by the SSL/TLS server. The SSL_CTX_set_session_id_context() and SSL_set_session_id_context() functions are therefore only useful on the server side. OpenSSL clients will check the session id context returned by the server when reusing a session. The maximum length of the B<sid_ctx> is limited to B<SSL_MAX_SSL_SESSION_ID_LENGTH>. =head1 WARNINGS If the session id context is not set on an SSL/TLS server and client certificates are used, stored sessions will not be reused but a fatal error will be flagged and the handshake will fail. If a server returns a different session id context to an OpenSSL client when reusing a session, an error will be flagged and the handshake will fail. OpenSSL servers will always return the correct session id context, as an OpenSSL server checks the session id context itself before reusing a session as described above. =head1 RETURN VALUES SSL_CTX_set_session_id_context() and SSL_set_session_id_context() return the following values: =over 4 =item C<0> The length B<sid_ctx_len> of the session id context B<sid_ctx> exceeded the maximum allowed length of B<SSL_MAX_SSL_SESSION_ID_LENGTH>. The error is logged to the error stack. =item C<1> The operation succeeded. =back =head1 SEE ALSO L<ssl(3)|ssl(3)> =cut
openilabs/crypto
bernstein/openssl-1.0.1f/doc/ssl/SSL_CTX_set_session_id_context.pod
Perl
mit
2,729
#ExStart:1 use lib 'lib'; use strict; use warnings; use utf8; use File::Slurp; # From CPAN use JSON; use AsposeStorageCloud::StorageApi; use AsposeStorageCloud::ApiClient; use AsposeStorageCloud::Configuration; use AsposeWordsCloud::WordsApi; use AsposeWordsCloud::ApiClient; use AsposeWordsCloud::Configuration; my $configFile = '../Config/config.json'; my $configPropsText = read_file($configFile); my $configProps = decode_json($configPropsText); my $data_path = '../../../Data/'; my $out_path = $configProps->{'out_folder'}; $AsposeWordsCloud::Configuration::app_sid = $configProps->{'app_sid'}; $AsposeWordsCloud::Configuration::api_key = $configProps->{'api_key'}; $AsposeWordsCloud::Configuration::debug = 1; $AsposeStorageCloud::Configuration::app_sid = $configProps->{'app_sid'}; $AsposeStorageCloud::Configuration::api_key = $configProps->{'api_key'}; # Instantiate Aspose.Storage and Aspose.Words API SDK my $storageApi = AsposeStorageCloud::StorageApi->new(); my $wordsApi = AsposeWordsCloud::WordsApi->new(); # Set input file name my $name = 'SampleBlankWatermarkDocument.docx'; # Upload file to aspose cloud storage my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name); my $replaceTextRequest = AsposeWordsCloud::Object::ReplaceTextRequest->new('OldValue' => 'aspose', 'NewValue' => 'aspose.com'); # Invoke Aspose.Words Cloud SDK API to remove watermark image from a word document $response = $wordsApi->DeleteDocumentWatermark(name=> $name); if($response->{'Status'} eq 'OK'){ print "\nWatermark image has been removed successfully."; # Download updated document from storage server my $output_file = $out_path.$name; $response = $storageApi->GetDownload(Path => $name);; write_file($output_file, { binmode => ":raw" }, $response->{'Content'}); } #ExEnd:1
aspose-words/Aspose.Words-for-Cloud
Examples/Perl/Watermark/RemoveWatermark.pl
Perl
mit
1,810
########################################################################### ## Export of Script: PS Get IP Helpers with Network ## Script-Level: 3 ## Script-Category: ## Script-Language: Perl ########################################################################### # BEGIN-INTERNAL-SCRIPT-BLOCK # Script: # PS Get IP Helpers with Network # END-INTERNAL-SCRIPT-BLOCK # BEGIN-SCRIPT-BLOCK # # Script-Filter: # $Vendor eq "Cisco" # # Script-Login:false # # Script-Variables: # ## # END-SCRIPT-BLOCK use strict; use warnings; use NetMRI_Easy; my $easy = new NetMRI_Easy; my $device_id = $easy->device_id; my $device = $easy->device; print $device->DeviceID . " " . $device->DeviceName . "\n"; my %if_ids = map { $_->ifDescrRaw => $_->InterfaceID } $easy->broker->interface->index({ DeviceID => $device_id }); my $Configs=$easy->broker->device->running_config_text(DeviceID=>$device_id)->{running_config_text}; my @output = split /\n/,$Configs; my %helpers = (); my %subrange = (); our ($if_name); # Create the custom field called IP Helpers if it does not already exist # $easy->broker->custom_fields->create_field({ model => 'Interface', name => 'IP Helpers', type => 'string', }); $easy->broker->custom_fields->create_field({ model => 'Interface', name => 'Subnet', type => 'string', }); foreach my $line (@output) { chomp $line; if ($line =~ /^interface (\S+)/) { ($if_name) = $line =~ /^interface (\S+)/; $helpers{$if_name} = [()]; $subrange{$if_name} = [()]; } elsif ( $line =~ /ip dhcp relay address /i ) { my ($ip) = $line =~ /ip dhcp relay address (\S+)/; push @{$helpers{$if_name}}, $ip; } elsif ( $line =~ /ip helper-address /i ) { my ($ip) = $line =~ /ip helper-address (\S+)/; push @{$helpers{$if_name}}, $ip; } elsif ( $line =~ /ip address /i ) { my ($subnet) = $line =~ /ip address (.*)/; my $test = $line =~ /ip address (.+)/; print "$test test\n"; push @{$subrange{$if_name}}, $subnet; } } foreach my $i (keys %helpers) { my $id = $if_ids{$i}; if (! exists $if_ids{$i}) { print "Skipping interface $i, not in IDs table\n"; next; } my @helpers = @{$helpers{$i}}; if (! @helpers ) { print "Skipping interface $i no helpers\n"; next; } print "Interface (name/id) helpers => ($i,$id) " . join(",",@helpers) . "\n"; $easy->broker->interface->update({ # this uniquely identifies the interface in the NetMRI InterfaceID => $id, custom_ip_helpers => join(",",@helpers) }); } foreach my $i (keys %subrange) { my $id = $if_ids{$i}; if (! exists $if_ids{$i}) { print "Skipping interface $i, not in IDs table\n"; next; } my @subrange = @{$subrange{$i}}; if (! @subrange) { print "Skipping interface $i no helpers\n"; next; } print "Interface (name/id) helpers => ($i,$id) " . join(",",@subrange) . "\n"; $easy->broker->interface->update({ # this uniquely identifies the interface in the NetMRI InterfaceID => $id, custom_subnet => join(",",@subrange) }); }
infobloxopen/netmri-toolkit
Perl/PS Get IP Helpers with Network.pl
Perl
mit
4,215
package CoGe::Accessory::dialign_report::anchors; use strict; use warnings; #use File::Temp; use CoGe::Accessory::bl2seq_report; use CoGe::Accessory::chaos_report; use CoGe::Accessory::blastz_report; use CoGe::Accessory::dialign_report; use base qw(Class::Accessor); #use Data::Dumper; BEGIN { use vars qw($VERSION $DEBUG); $VERSION = "0.01"; } __PACKAGE__->mk_accessors(qw(file1 file2 run_anchor run_dialign base_name extension output_dir anchor_output anchor_file fasta_file dialign_file run_anchor_opts run_dialign_opts anchor_report_opts dialign_report_opts anchor_report dialign_report log_file DEBUG)); ############################################################################### # anchors -- Josh Kane UC Berkeley ############################################################################### sub new { my $proto = shift; my $opts = shift; $opts = {} unless $opts; my $class = ref($proto) || $proto; my $self = bless ({%$opts}, $class); $self->run_anchor("/opt/apache/coge/bin/lagan/chaos_coge") unless $self->run_anchor; $self->run_dialign("/opt/apache/coge/bin/dialign2_dir/dialign2-2_coge") unless $self->run_dialign; $self->output_dir("/opt/apache/coge/web/tmp") unless $self->output_dir; $self->run_anchor_opts("-v") unless $self->run_anchor_opts; $self->run_dialign_opts("-n") unless $self->run_dialign_opts; $self->extension("chaos") unless $self->extension; $self->run_program(); return $self; } sub run_program { my $self = shift; $self->generate_anchors; $self->run_dialign_with_anchors; return $self; } sub generate_anchors { my $self = shift; my $file1 = shift || $self->file1; my $file2 = shift || $self->file2; my $output_dir = $self->output_dir; my $run_anchor = $self->run_anchor; my $base_name = $self->base_name; my $anchor_opts = $self->run_anchor_opts; my $parser_opts = $self->anchor_report_opts; my $extension = $self->extension; $parser_opts = {} unless ref($parser_opts) =~ /hash/i; my ($query_start,$query_stop,$subject_start,$length,$score) = (0,0,0,0,0); my $anchor_file = ""; my $anchor_report = []; print STDERR "file1 is $file1, file2 is $file2\n" if $self->DEBUG; my $command; if ($extension=~/bl2/i) {$command = "$run_anchor -p blastn -i $file1 -j $file2 $anchor_opts > $output_dir/$base_name.$extension";} else{ $command = "$run_anchor $file1 $file2 $anchor_opts > $output_dir/$base_name.$extension";} print STDERR "call to $extension: $command\n" if $self->DEBUG; $self->write_log("running $command"); `$command`; $self->anchor_output("$output_dir/$base_name.$extension"); print STDERR "Anchor output: ",$self->anchor_output,"\n" if $self->DEBUG; `cat $file1 > $output_dir/$base_name.fasta`; `cat $file2 >> $output_dir/$base_name.fasta`; $self->fasta_file("$output_dir/$base_name.fasta"); $anchor_report = new CoGe::Accessory::chaos_report({file=>"$output_dir/$base_name.$extension", %$parser_opts}) if $extension=~/chaos/i; $anchor_report = new CoGe::Accessory::bl2seq_report({file=>"$output_dir/$base_name.$extension", %$parser_opts}) if $extension=~/bl2/i; $anchor_report = new CoGe::Accessory::blastz_report({file=>"$output_dir/$base_name.$extension", %$parser_opts}) if $extension=~/blastz/i; $self->anchor_report($anchor_report); foreach my $hsp (@{$anchor_report->hsps}) { next if $hsp->strand =~ /-/; $query_start = $hsp->query_start; $query_stop = $hsp->query_stop; $subject_start = $hsp->subject_start; $score = $hsp->score; $length = ($query_stop - $query_start) + 1; $anchor_file .= "1 2 $query_start $subject_start $length $score\n"; } print STDERR "Anchor file is: \n",$anchor_file,"\n" if $self->DEBUG; $self->write_log("creating dialign anchor file"); open(NEW,"> $output_dir/$base_name.anc"); print NEW $anchor_file; close NEW; $self->anchor_file("$output_dir/$base_name.anc"); print STDERR "Anchor file: ",$self->anchor_file,"\n" if $self->DEBUG; return $self; } sub run_dialign_with_anchors { my $self = shift; my $run_dialign = $self->run_dialign; my $dialign_opts = $self->run_dialign_opts; my $parser_opts = $self->dialign_report_opts; $parser_opts = {} unless ref($parser_opts) =~ /hash/i; my $base_name = $self->base_name; my $output_dir = $self->output_dir; my $command = "$run_dialign $dialign_opts -anc -fn $output_dir/$base_name.dialign $output_dir/$base_name.fasta"; print STDERR "call to dialign: $command\n" if $self->DEBUG; $self->write_log("running $command"); `$command`; #`mv $basename.ali $output_dir/$basename.ali`; #some move command to output_dir directory $self->dialign_file("$output_dir/$base_name.dialign"); my $dialign_report = new CoGe::Accessory::dialign_report({file=>"$output_dir/$base_name.dialign", %$parser_opts}); $self->dialign_report($dialign_report); return $self; } sub write_log { my $self = shift; my $message = shift; return unless $self->log_file; open (OUT, ">>".$self->log_file) || return; print OUT $message,"\n"; close OUT; } 1; __END__
asherkhb/coge
modules/Accessory/lib/CoGe/Accessory/dialign_report/anchors.pm
Perl
bsd-2-clause
5,009
package Bio::DB::Sam; our $VERSION = '1.41'; =head1 NAME Bio::DB::Sam -- Read SAM/BAM database files =head1 SYNOPSIS use Bio::DB::Sam; # high level API my $sam = Bio::DB::Sam->new(-bam =>"data/ex1.bam", -fasta=>"data/ex1.fa", ); my @targets = $sam->seq_ids; my @alignments = $sam->get_features_by_location(-seq_id => 'seq2', -start => 500, -end => 800); for my $a (@alignments) { # where does the alignment start in the reference sequence my $seqid = $a->seq_id; my $start = $a->start; my $end = $a->end; my $strand = $a->strand; my $cigar = $a->cigar_str; my $paired = $a->get_tag_values('PAIRED'); # where does the alignment start in the query sequence my $query_start = $a->query->start; my $query_end = $a->query->end; my $ref_dna = $a->dna; # reference sequence bases my $query_dna = $a->query->dna; # query sequence bases my @scores = $a->qscore; # per-base quality scores my $match_qual= $a->qual; # quality of the match } my @pairs = $sam->get_features_by_location(-type => 'read_pair', -seq_id => 'seq2', -start => 500, -end => 800); for my $pair (@pairs) { my $length = $pair->length; # insert length my ($first_mate,$second_mate) = $pair->get_SeqFeatures; my $f_start = $first_mate->start; my $s_start = $second_mate->start; } # low level API my $bam = Bio::DB::Bam->open('/path/to/bamfile'); my $header = $bam->header; my $target_count = $header->n_targets; my $target_names = $header->target_name; while (my $align = $bam->read1) { my $seqid = $target_names->[$align->tid]; my $start = $align->pos+1; my $end = $align->calend; my $cigar = $align->cigar_str; } my $index = Bio::DB::Bam->index_open('/path/to/bamfile'); my $index = Bio::DB::Bam->index_open_in_safewd('/path/to/bamfile'); my $callback = sub { my $alignment = shift; my $start = $alignment->start; my $end = $alignment->end; my $seqid = $target_names->[$alignment->tid]; print $alignment->qname," aligns to $seqid:$start..$end\n"; } my $header = $index->header; $index->fetch($bam,$header->parse_region('seq2'),$callback); =head1 DESCRIPTION This module provides a Perl interface to the libbam library for indexed and unindexed SAM/BAM sequence alignment databases. It provides support for retrieving information on individual alignments, read pairs, and alignment coverage information across large regions. It also provides callback functionality for calling SNPs and performing other base-by-base functions. Most operations are compatible with the BioPerl Bio::SeqFeatureI interface, allowing BAM files to be used as a backend to the GBrowse genome browser application (gmod.sourceforge.net). =head2 The high-level API The high-level API provides a BioPerl-compatible interface to indexed BAM files. The BAM database is treated as a collection of Bio::SeqFeatureI features, and can be searched for features by name, location, type and combinations of feature tags such as whether the alignment is part of a mate-pair. When opening a BAM database using the high-level API, you provide the pathnames of two files: the FASTA file that contains the reference genome sequence, and the BAM file that contains the query sequences and their alignments. If either of the two files needs to be indexed, the indexing will happen automatically. You can then query the database for alignment features by combinations of name, position, type, and feature tag. The high-level API provides access to up to four feature "types": * "match": The "raw" unpaired alignment between a read and the reference sequence. * "read_pair": Paired alignments; a single composite feature that contains two subfeatures for the alignments of each of the mates in a mate pair. * "coverage": A feature that spans a region of interest that contains numeric information on the coverage of reads across the region. * "region": A way of retrieving information about the reference sequence. Searching for features of type "region" will return a list of chromosomes or contigs in the reference sequence, rather than read alignments. * "chromosome": A synonym for "region". B<Features> can be en masse in a single call, retrieved in a memory-efficient streaming basis using an iterator, or interrogated using a filehandle that return a series of TAM-format lines. B<SAM alignment flags> can be retrieved using BioPerl's feature "tag" mechanism. For example, to interrogate the FIRST_MATE flag, one fetches the "FIRST_MATE" tag: warn "aye aye captain!" if $alignment->get_tag_values('FIRST_MATE'); The Bio::SeqFeatureI interface has been extended to retrieve all flags as a compact human-readable string, and to return the CIGAR alignment in a variety of formats. B<Split alignments>, such as reads that cover introns, are dealt with in one of two ways. The default is to leave split alignments alone: they can be detected by one or more "N" operations in the CIGAR string. Optionally, you can choose to have the API split these alignments across two or more subfeatures; the CIGAR strings of these split alignments will be adjusted accordingly. B<Interface to the pileup routines> The API provides you with access to the samtools "pileup" API. This gives you the ability to write a callback that will be invoked on every column of the alignment for the purpose of calculating coverage, quality score metrics, or SNP calling. B<Access to the reference sequence> When you create the Bio::DB::Sam object, you can pass the path to a FASTA file containing the reference sequence. Alternatively, you may pass an object that knows how to retrieve DNA sequences across a range via the seq() of fetch_seq() methods, as described under new(). If the SAM/BAM file has MD tags, then these tags will be used to reconstruct the reference sequence when necessary, in which case you can completely omit the -fasta argument. Note that not all SAM/BAM files have MD tags, and those that do may not use them correctly due to the newness of this part of the SAM spec. You may wish to populate these tags using samtools' "calmd" command. If the -fasta argument is omitted and no MD tags are present, then the reference sequence will be returned as 'N'. The B<main object classes> that you will be dealing with in the high-level API are as follows: * Bio::DB::Sam -- A collection of alignments and reference sequences. * Bio::DB::Bam::Alignment -- The alignment between a query and the reference. * Bio::DB::Bam::Query -- An object corresponding to the query sequence in which both (+) and (-) strand alignments are shown in the reference (+) strand. * Bio::DB::Bam::Target -- An interface to the query sequence in which (-) strand alignments are shown in reverse complement You may encounter other classes as well. These include: * Bio::DB::Sam::Segment -- This corresponds to a region on the reference sequence. * Bio::DB::Sam::Constants -- This defines CIGAR symbol constants and flags. * Bio::DB::Bam::AlignWrapper -- An alignment helper object that adds split alignment functionality. See Bio::DB::Bam::Alignment for the documentation on using it. * Bio::DB::Bam::ReadIterator -- An iterator that mediates the one-feature-at-a-time retrieval mechanism. * Bio::DB::Bam::FetchIterator -- Another iterator for feature-at-a-time retrieval. =head2 The low-level API The low-level API closely mirrors that of the libbam library. It provides the ability to open TAM and BAM files, read and write to them, build indexes, and perform searches across them. There is less overhead to using the API because there is very little Perl memory management, but the functions are less convenient to use. Some operations, such as writing BAM files, are only available through the low-level API. The classes you will be interacting with in the low-level API are as follows: * Bio::DB::Tam -- Methods that read and write TAM (text SAM) files. * Bio::DB::Bam -- Methods that read and write BAM (binary SAM) files. * Bio::DB::Bam::Header -- Methods for manipulating the BAM file header. * Bio::DB::Bam::Index -- Methods for retrieving data from indexed BAM files. * Bio::DB::Bam::Alignment -- Methods for manipulating alignment data. * Bio::DB::Bam::Pileup -- Methods for manipulating the pileup data structure. * Bio::DB::Sam::Fai -- Methods for creating and reading from indexed Fasta files. =head1 METHODS We cover the high-level API first. The high-level API code can be found in the files Bio/DB/Sam.pm, Bio/DB/Sam/*.pm, and Bio/DB/Bam/*.pm. =head2 Bio::DB::Sam Constructor and basic accessors =over 4 =item $sam = Bio::DB::Sam->new(%options) The Bio::DB::Sam object combines a Fasta file of the reference sequences with a BAM file to allow for convenient retrieval of human-readable sequence IDs and reference sequences. The new() constructor accepts a -name=>value style list of options as follows: Option Description ------ ------------- -bam Path to the BAM file that contains the alignments (required). When using samtools 0.1.6 or higher, an http: or ftp: URL is accepted. -fasta Path to the Fasta file that contains the reference sequences (optional). Alternatively, you may pass any object that supports a seq() or fetch_seq() method and takes the three arguments ($seq_id,$start,$end). -expand_flags A boolean value. If true then the standard alignment flags will be broken out as individual tags such as 'M_UNMAPPED' (default false). -split_splices A boolean value. If true, then alignments that are split across splices will be broken out into a single alignment containing two sub- alignments (default false). -split The same as -split_splices. -force_refseq Always use the reference sequence file to derive the reference sequence, even when the sequence can be derived from the MD tag. This is slower, but safer when working with BAM files derived from buggy aligners or when the reference contains non-canonical (modified) bases. -autoindex Create a BAM index file if one does not exist or the current one has a modification date earlier than the BAM file. An example of a typical new() constructor invocation is: $sam = Bio::DB::Sam->new(-fasta => '/home/projects/genomes/hu17.fa', -bam => '/home/projects/alignments/ej88.bam', -expand_flags => 1, -split_splices => 1); If the B<-fasta> argument is present, then you will be able to use the interface to fetch the reference sequence's bases. Otherwise, calls that return the reference sequence will return sequences consisting entirely of "N". B<-expand_flags> option, if true, has the effect of turning each of the standard SAM flags into a separately retrievable B<tag> in the Bio::SeqFeatureI interface. Otherwise, the standard flags will be concatenated in easily parseable form as a tag named "FLAGS". See get_all_tags() and get_tag_values() for more information. Any two-letter extension flags, such as H0 or H1, will always appear as separate tags regardless of the setting. B<-split_splices> has the effect of breaking up alignments that contain an "N" operation into subparts for more convenient manipulation. For example, if you have both paired reads and spliced alignments in the BAM file, the following code shows the subpart relationships: $pair = $sam->get_feature_by_name('E113:01:01:23'); @mates = $pair->get_SeqFeatures; @mate1_parts = $mates[0]->get_SeqFeatures; @mate2_parts = $mates[1]->get_SeqFeatures; Because there is some overhead to splitting up the spliced alignments, this option is false by default. B<Remote access> to BAM files located on an HTTP or FTP server is possible when using the Samtools library version 0.1.6 or higher. Simply replace the path to the BAM file with the appropriate URL. Note that incorrect URLs may lead to a core dump. It is not currently possible to refer to a remote FASTA file. These will have to be downloaded locally and indexed before using. =item $flag = $sam->expand_flags([$new_value]) Get or set the expand_flags option. This can be done after object creation and will have an immediate effect on all alignments fetched from the BAM file. =item $flag = $sam->split_splices([$new_value]) Get or set the split_splices option. This can be done after object creation and will affect all alignments fetched from the BAM file B<subsequently.> =item $header = $sam->header Return the Bio::DB::Bam::Header object associated with the BAM file. You can manipulate the header using the low-level API. =item $bam_path = $sam->bam_path Return the path of the bam file used to create the sam object. This makes the sam object more portable. =item $bam = $sam->bam Returns the low-level Bio::DB::Bam object associated with the opened file. =item $fai = $sam->fai Returns the Bio::DB::Sam::Fai object associated with the Fasta file. You can then manipuate this object with the low-level API. B<The index will be built automatically for you if it does not already exist.> If index building is necessarily, the process will need write privileges to the same directory in which the Fasta file resides.> If the process does not have write permission, then the call will fail. Unfortunately, the BAM library does not do great error recovery for this condition, and you may experience a core dump. This is not trappable via an eval {}. =item $bai = $sam->bam_index Return the Bio::DB::Bam::Index object associated with the BAM file. B<The BAM file index will be built automatically for you if it does not already exist.> In addition, if the BAM file is not already sorted by chromosome and coordinate, it will be sorted automatically, an operation that consumes significant time and disk space. The current process must have write permission to the directory in which the BAM file resides in order for this to work.> In case of a permissions problem, the Perl library will catch the error and die. You can trap it with an eval {}. =item $sam->clone Bio::DB::SAM objects are not stable across fork() operations. If you fork, you must call clone() either in the parent or the child process before attempting to call any methods. =back =head2 Getting information about reference sequences The Bio::DB::Sam object provides the following methods for getting information about the reference sequence(s) contained in the associated Fasta file. =over 4 =item @seq_ids = $sam->seq_ids Returns an unsorted list of the IDs of the reference sequences (known elsewhere in this document as seq_ids). This is the same as the identifier following the ">" sign in the Fasta file (e.g. "chr1"). =item $num_targets = $sam->n_targets Return the number of reference sequences. =item $length = $sam->length('seqid') Returns the length of the reference sequence named "seqid". =item $seq_id = $sam->target_name($tid) Translates a numeric target ID (TID) returned by the low-level API into a seq_id used by the high-level API. =item $length = $sam->target_len($tid) Translates a numeric target ID (TID) from the low-level API to a sequence length. =item $dna = $sam->seq($seqid,$start,$end) Returns the DNA across the region from start to end on reference seqid. Note that this is a string, not a Bio::PrimarySeq object. If no -fasta path was passed when the sam object was created, then you will receive a series of N nucleotides of the requested length. =back =head2 Creating and querying segments Bio::DB::Sam::Segment objects refer regions on the reference sequence. They can be used to retrieve the sequence of the reference, as well as alignments that overlap with the region. =over 4 =item $segment = $sam->segment($seqid,$start,$end); =item $segment = $sam->segment(-seq_id=>'chr1',-start=>5000,-end=>6000); Segments are created using the Bio:DB::Sam->segment() method. It can be called using one to three positional arguments corresponding to the seq_id of the reference sequence, and optionally the start and end positions of a subregion on the sequence. If the start and/or end are undefined, they will be replaced with the beginning and end of the sequence respectively. Alternatively, you may call segment() with named -seq_id, -start and -end arguments. All coordinates are 1-based. =item $seqid = $segment->seq_id Return the segment's sequence ID. =item $start = $segment->start Return the segment's start position. =item $end = $segment->end Return the segment's end position. =item $strand = $segment->strand Return the strand of the segment (always 0). =item $length = $segment->length Return the length of the segment. =item $dna = $segment->dna Return the DNA string for the reference sequence under this segment. =item $seq = $segment->seq Return a Bio::PrimarySeq object corresponding to the sequence of the reference under this segment. You can get the actual DNA string in this redundant-looking way: $dna = $segment->seq->seq The advantage of working with a Bio::PrimarySeq object is that you can perform operations on it, including taking its reverse complement and subsequences. =item @alignments = $segment->features(%args) Return alignments that overlap the segment in the associated BAM file. The optional %args list allows you to filter features by name, tag or other attributes. See the documentation of the Bio::DB::Sam->features() method for the full list of options. Here are some typical examples: # get all the overlapping alignments @all_alignments = $segment->features; # get an iterator across the alignments my $iterator = $segment->features(-iterator=>1); while (my $align = $iterator->next_seq) { do something } # get a TAM filehandle across the alignments my $fh = $segment->features(-fh=>1); while (<$fh>) { print } # get only the alignments with unmapped mates my @unmapped = $segment->features(-flags=>{M_UNMAPPED=>1}); # get coverage across this region my ($coverage) = $segment->features('coverage'); my @data_points = $coverage->coverage; # grep through features using a coderef my @reverse_alignments = $segment->features( -filter => sub { my $a = shift; return $a->strand < 0; }); =item $tag = $segment->primary_tag =item $tag = $segment->source_tag Return the strings "region" and "sam/bam" respectively. These methods allow the segment to be passed to BioPerl methods that expect Bio::SeqFeatureI objects. =item $segment->name, $segment->display_name, $segment->get_SeqFeatures, $segment->get_tag_values These methods are provided for Bio::SeqFeatureI compatibility and don't do anything of interest. =back =head2 Retrieving alignments, mate pairs and coverage information The features() method is an all-purpose tool for retrieving alignment information from the SAM/BAM database. In addition, the methods get_features_by_name(), get_features_by_location() and others provide convenient shortcuts to features(). These methods either return a list of features, an iterator across a list of features, or a filehandle opened on a pseudo-TAM file. =over 4 =item @features = $sam->features(%options) =item $iterator = $sam->features(-iterator=>1,%more_options) =item $filehandle = $sam->features(-fh=>1,%more_options) =item @features = $sam->features('type1','type2'...) This is the all-purpose interface for fetching alignments and other types of features from the database. Arguments are a -name=>value option list selected from the following list of options: Option Description ------ ------------- -type Filter on features of a given type. You may provide either a scalar typename, or a reference to an array of desired feature types. Valid types are "match", "read_pair", "coverage" and "chromosome." See below for a full explanation of feature types. -name Filter on reads with the designated name. Note that this can be a slow operation unless accompanied by the feature location as well. -seq_id Filter on features that align to seq_id between start -start and end. -start and -end must be used in conjunction -end with -seq_id. If -start and/or -end are absent, they will default to 1 and the end of the reference sequence, respectively. -flags Filter features that match a list of one or more flags. See below for the format. -attributes The same as -flags, for compatibility with other -tags APIs. -filter Filter on features with a coderef. The coderef will receive a single argument consisting of the feature and should return true to keep the feature, or false to discard it. -iterator Instead of returning a list of features, return an iterator across the results. To retrieve the results, call the iterator's next_seq() method repeatedly until it returns undef to indicate that no more matching features remain. -fh Instead of returning a list of features, return a filehandle. Read from the filehandle to retrieve each of the results in TAM format, one alignment per line read. This only works for features of type "match." The high-level API introduces the concept of a B<feature "type"> in order to provide several convenience functions. You specify types by using the optional B<-type> argument. The following types are currently supported: B<match>. The "match" type corresponds to the unprocessed SAM alignment. It will retrieve single reads, either mapped or unmapped. Each match feature's primary_tag() method will return the string "match." The features returned by this call are of type Bio::DB::Bam::AlignWrapper. B<read_pair>. The "paired_end" type causes the sam interface to find and merge together mate pairs. Fetching this type of feature will yield a series of Bio::SeqFeatureI objects, each as long as the total distance on the reference sequence spanned by the mate pairs. The top-level feature is of type Bio::SeqFeature::Lite; it contains two Bio::DB::Bam::AlignWrapper subparts. Call get_SeqFeatures() to get the two individual reads. Example: my @pairs = $sam->features(-type=>'read_pair'); my $p = $pairs[0]; my $i_length = $p->length; my @ends = $p->get_SeqFeatures; my $left = $ends[0]->start; my $right = $ends[1]->end; B<coverage>. The "coverage" type causes the sam interface to calculate coverage across the designated region. It only works properly if accompanied by the desired location of the coverage graph; -seq_id is a mandatory argument for coverage calculation, and -start and -end are optional. The call will return a single Bio::SeqFeatureI object whose primary_tag() is "coverage." To recover the coverage data, call the object's coverage() method to obtain an array (list context) or arrayref (scalar context) of coverage counts across the region of interest: my ($coverage) = $sam->features(-type=>'coverage',-seq_id=>'seq1'); my @data = $coverage->coverage; my $total; for (@data) { $total += $_ } my $average_coverage = $total/@data; By default the coverage graph will be at the base pair level. So for a region 5000 bp wide, coverage() will return an array or arrayref with exactly 5000 elements. However, you also have the option of calculating the coverage across larger bins. Simply append the number of intervals you are interested to the "coverage" typename. For example, fetching "coverage:500" will return a feature whose coverage() method will return the coverage across 500 intervals. B<chromosome> or B<region>. The "chromosome" or "region" type are interchangeable. They ask the sam interface to construct Bio::DB::Sam::Segment representing the reference sequences. These two calls give similar results: my $segment = $sam->segment('seq2',1=>500); my ($seg) = $sam->features(-type=>'chromosome', -seq_id=>'seq2',-start=>1,-end=>500); Due to an unresolved bug, you cannot fetch chromosome features in the same call with matches and other feature types call. Specifically, this works as expected: my @chromosomes = $sam->features (-type=>'chromosome'); But this doesn't (as of 18 June 2009): my @chromosomes_and_matches = $sam->features(-type=>['match','chromosome']); If no -type argument is provided, then features() defaults to finding features of type "match." You may call features() with a plain list of strings (positional arguments, not -type=>value arguments). This will be interpreted as a list of feature types to return: my ($coverage) = $sam->features('coverage') For a description of the methods available in the features returned from this call, please see L<Bio::SeqfeatureI> and L<Bio::DB::Bam::Alignment>. You can B<filter> "match" and "read_pair" features by name, location and/or flags. The name and flag filters are not very efficient. Unless they are combined with a location filter, they will initiate an exhaustive search of the BAM database. Name filters are case-insensitive, and allow you to use shell-style "*" and "?" wildcards. Flag filters created with the B<-flag>, B<-attribute> or B<-tag> options have the following syntax: -flag => { FLAG_NAME_1 => ['list','of','possible','values'], FLAG_NAME_2 => ['list','of','possible','values'], ... } The value of B<-flag> is a hash reference in which the keys are flag names and the values are array references containing lists of acceptable values. The list of values are OR'd with each other, and the flag names are AND'd with each other. The B<-filter> option provides a completely generic filtering interface. Provide a reference to a subroutine. It will be called once for each potential feature. Return true to keep the feature, or false to discard it. Here is an example of how to find all matches whose alignment quality scores are greater than 80. @features = $sam->features(-filter=>sub {shift->qual > 80} ); By default, features() returns a list of all matching features. You may instead request an iterator across the results list by passing -iterator=>1. This will give you an object that has a single method, next_seq(): my $high_qual = $sam->features(-filter => sub {shift->qual > 80}, -iterator=> 1 ); while (my $feature = $high_qual->next_seq) { # do something with the alignment } Similarly, by passing a true value to the argument B<-fh>, you can obtain a filehandle to a virtual TAM file. This only works with the "match" feature type: my $high_qual = $sam->features(-filter => sub {shift->qual > 80}, -fh => 1 ); while (my $tam_line = <$high_qual>) { chomp($tam_line); # do something with it } =item @features = $sam->get_features_by_name($name) Convenience method. The same as calling $sam->features(-name=>$name); =item $feature = $sam->get_feature_by_name($name) Convenience method. The same as ($sam->features(-name=>$name))[0]. =item @features = $sam->get_features_by_location($seqid,$start,$end) Convenience method. The same as calling $sam->features(-seq_id=>$seqid,-start=>$start,-end=>$end). =item @features = $sam->get_features_by_flag(%flags) Convenience method. The same as calling $sam->features(-flags=>\%flags). This method is also called get_features_by_attribute() and get_features_by_tag(). Example: @features = $sam->get_features_by_flag(H0=>1) =item $feature = $sam->get_feature_by_id($id) The high-level API assigns each feature a unique ID composed of its read name, position and strand and returns it when you call the feature's primary_id() method. Given that ID, this method returns the feature. =item $iterator = $sam->get_seq_stream(%options) Convenience method. This is the same as calling $sam->features(%options,-iterator=>1). =item $fh = $sam->get_seq_fh(%options) Convenience method. This is the same as calling $sam->features(%options,-fh=>1). =item $fh = $sam->tam_fh Convenience method. It is the same as calling $sam->features(-fh=>1). =item @types = $sam->types This method returns the list of feature types (e.g. "read_pair") returned by the current version of the interface. =back =head2 The generic fetch() and pileup() methods Lastly, the high-level API supports two methods for rapidly traversing indexed BAM databases. =over 4 =item $sam->fetch($region,$callback) This method, which is named after the native bam_fetch() function in the C interface, traverses the indicated region and invokes a callback code reference on each match. Specify a region using the BAM syntax "seqid:start-end", or either of the alternative syntaxes "seqid:start..end" and "seqid:start,end". If start and end are absent, then the entire reference sequence is traversed. If end is absent, then the end of the reference sequence is assumed. The callback will be called repeatedly with a Bio::DB::Bam::AlignWrapper on the argument list. Example: $sam->fetch('seq1:600-700', sub { my $a = shift; print $a->display_name,' ',$a->cigar_str,"\n"; }); Note that the fetch() operation works on reads that B<overlap> the indicated region. Therefore the callback may be called for reads that align to the reference at positions that start before or end after the indicated region. =item $sam->pileup($region,$callback [,$keep_level]) This method, which is named after the native bam_lpileupfile() function in the C interfaces, traverses the indicated region and generates a "pileup" of all the mapped reads that cover it. The user-provided callback function is then invoked on each position of the alignment along with a data structure that provides access to the individual aligned reads. As with fetch(), the region is specified as a string in the format "seqid:start-end", "seqid:start..end" or "seqid:start,end". The callback is a coderef that will be invoked with three arguments: the seq_id of the reference sequence, the current position on the reference (in 1-based coordinates!), and a reference to an array of Bio::DB::Bam::Pileup objects. Here is the typical call signature: sub { my ($seqid,$pos,$pileup) = @_; # do something } For example, if you call pileup on the region "seq1:501-600", then the callback will be invoked for all reads that overlap the indicated region. The first invocation of the callback will typically have a $pos argument somewhat to the left of the desired region and the last call will be somewhat to the right. You may wish to ignore positions that are outside of the requested region. Also be aware that the reference sequence position uses 1-based coordinates, which is different from the low-level interface, which use 0-based coordinates. The optional $keep_level argument, if true, asks the BAM library to keep track of the level of the read in the multiple alignment, an operation that generates some overhead. This is mostly useful for text alignment viewers, and so is off by default. The size of the $pileup array reference indicates the read coverage at that position. Here is a simple average coverage calculator: my $depth = 0; my $positions = 0; my $callback = sub { my ($seqid,$pos,$pileup) = @_; next unless $pos >= 501 && $pos <= 600; $positions++; $depth += @$pileup; } $sam->pileup('seq1:501-600',$callback); print "coverage = ",$depth/$positions; Each Bio::DB::Bam::Pileup object describes the position of a read in the alignment. Briefly, Bio::DB::Bam::Pileup has the following methods: $pileup->alignment The alignment at this level (a Bio::DB::Bam::AlignWrapper object). $pileup->qpos The position of the read base at the pileup site, in 0-based coordinates. $pileup->pos The position of the read base at the pileup site, in 1-based coordinates; $pileup->level The level of the read in the multiple alignment view. Note that this field is only valid when $keep_level is true. $pileup->indel Length of the indel at this position: 0 for no indel, positive for an insertion (relative to the reference), negative for a deletion (relative to the reference.) $pileup->is_del True if the base on the padded read is a deletion. $pileup->is_refskip True if the base on the padded read is a gap relative to the reference (denoted as < or > in the pileup) $pileup->is_head Undocumented field in the bam.h header file. $pileup->is_tail Undocumented field in the bam.h header file. See L</Examples> for a very simple SNP caller. =item $sam->fast_pileup($region,$callback [,$keep_level]) This is identical to pileup() except that the pileup object returns low-level Bio::DB::Bam::Alignment objects rather than the higher-level Bio::DB::Bam::AlignWrapper objects. This makes it roughly 50% faster, but you lose the align objects' seq_id() and get_tag_values() methods. As a compensation, the callback receives an additional argument corresponding to the Bio::DB::Sam object. You can use this to create AlignWrapper objects on an as needed basis: my $callback = sub { my($seqid,$pos,$pileup,$sam) = @_; for my $p (@$pileup) { my $alignment = $p->alignment; my $wrapper = Bio::DB::Bam::AlignWrapper->new($alignment,$sam); my $has_mate = $wrapper->get_tag_values('PAIRED'); } }; =item Bio::DB::Sam->max_pileup_cnt([$new_cnt]) =item $sam->max_pileup_cnt([$new_cnt]) The Samtools library caps pileups at a set level, defaulting to 8000. The callback will not be invoked on a single position more than the level set by the cap, even if there are more reads. Called with no arguments, this method returns the current cap value. Called with a numeric argument, it changes the cap. There is currently no way to specify an unlimited cap. This method can be called as an instance method or a class method. =item $sam->coverage2BedGraph([$fh]) This special-purpose method will compute a four-column BED graph of the coverage across the entire SAM/BAM file and print it to STDOUT. You may provide a filehandle to redirect output to a file or pipe. =back The next sections correspond to the low-level API, which let you create and manipulate Perl objects that correspond directly to data structures in the C interface. A major difference between the high and low level APIs is that in the high-level API, the reference sequence is identified using a human-readable seq_id. However, in the low-level API, the reference is identified using a numeric target ID ("tid"). The target ID is established during the creation of the BAM file and is a small 0-based integer index. The Bio::DB::Bam::Header object provides methods for converting from seq_ids to tids. =head2 Indexed Fasta Files These methods relate to the BAM library's indexed Fasta (".fai") files. =over 4 =item $fai = Bio::DB::Sam::Fai->load('/path/to/file.fa') Load an indexed Fasta file and return the object corresponding to it. If the index does not exist, it will be created automatically. Note that you pass the path to the Fasta file, not the index. For consistency with Bio::DB::Bam->open() this method is also called open(). =item $dna_string = $fai->fetch("seqid:start-end") Given a sequence ID contained in the Fasta file and optionally a subrange in the form "start-end", finds the indicated subsequence and returns it as a string. =back =head2 TAM Files These methods provide interfaces to the "TAM" text version of SAM files; they often have a .sam extension. =over 4 =item $tam = Bio::DB::Tam->open('/path/to/file.sam') Given the path to a SAM file, opens it for reading. The file can be compressed with gzip if desired. =item $header = $tam->header_read() Create and return a Bio::DB::Bam::Header object from the information contained within @SQ header lines of the Sam file. If there are no @SQ lines, then the header will not be useful, and you should call header_read2() to generate the missing information from the appropriate indexed Fasta file. Here is some code to illustrate the suggested logic: my $header = $tam->header_read; unless ($header->n_targets > 0) { $header = $tam->header_read2('/path/to/file.fa.fai'); } =item $header = $tam->header_read2('/path/to/file.fa.fai') Create and return a Bio::DB::Bam::Header object from the information contained within the indexed Fasta file of the reference sequences. Note that you have to pass the path to the .fai file, and not the .fa file. The header object contains information on the reference sequence names and lengths. =item $bytes = $tam->read1($header,$alignment) Given a Bio::DB::Bam::Header object, such as the one created by header_read2(), and a Bio::DB::Bam::Alignment object created by Bio::DB::Bam::Alignment->new(), reads one line of alignment information into the alignment object from the TAM file and returns a status code. The result code will be the number of bytes read. =back =head2 BAM Files These methods provide interfaces to the "BAM" binary version of SAM. They usually have a .bam extension. =over 4 =item $bam = Bio::DB::Bam->open('/path/to/file.bam' [,$mode]) Open up the BAM file at the indicated path. Mode, if present, must be one of the file stream open flags ("r", "w", "a", "r+", etc.). If absent, mode defaults to "r". Note that Bio::DB::Bam objects are not stable across fork() operations. If you fork, and intend to use the object in both parent and child, you must reopen the Bio::DB::Bam in either the child or the parent (but not both) before attempting to call any of the object's methods. The path may be an http: or ftp: URL, in which case a copy of the index file will be downloaded to the current working directory (see below) and all accesses will be performed on the remote BAM file. Example: $bam = Bio::DB::Bam->open('http://some.site.com/nextgen/chr1_bowtie.bam'); =item $header = $bam->header() Given an open BAM file, return a Bio::DB::Bam::Header object containing information about the reference sequence(s). Note that you must invoke header() at least once before calling read1(). =item $status_code = $bam->header_write($header) Given a Bio::DB::Bam::Header object and a BAM file opened in write mode, write the header to the file. If the write fails the process will be terminated at the C layer. The result code is (currently) always zero. =item $integer = $bam->tell() Return the current position of the BAM file read/write pointer. =item $bam->seek($integer,$pos) Set the current position of the BAM file read/write pointer. $pos is one of SEEK_SET, SEEK_CUR, SEEK_END. These constants can be obtained from the Fcntl module by importing the ":seek" group: use Fcntl ':seek'; =item $alignment = $bam->read1() Read one alignment from the BAM file and return it as a Bio::DB::Bam::Alignment object. Note that you must invoke header() at least once before calling read1(). =item $bytes = $bam->write1($alignment) Given a BAM file that has been opened in write mode and a Bio::DB::Bam::Alignment object, write the alignment to the BAM file and return the number of bytes successfully written. =item Bio::DB::Bam->sort_core($by_qname,$path,$prefix,$max_mem) Attempt to sort a BAM file by chromosomal location or name and create a new sorted BAM file. Arguments are as follows: Argument Description -------- ----------- $by_qname If true, sort by read name rather than chromosomal location. $path Path to the BAM file $prefix Prefix to use for the new sorted file. For example, passing "foo" will result in a BAM file named "foo.bam". $max_mem Maximum core memory to use for the sort. If the sort requires more than this amount of memory, intermediate sort files will be written to disk. The default, if not provided is 500M. =back =head2 BAM index methods The Bio::DB::Bam::Index object provides access to BAM index (.bai) files. =over 4 =item $status_code = Bio::DB::Bam->index_build('/path/to/file.bam') Given the path to a .bam file, this function attempts to build a ".bai" index. The process in which the .bam file exists must be writable by the current process and there must be sufficient disk space for the operation or the process will be terminated in the C library layer. The result code is currently always zero, but in the future may return a negative value to indicate failure. =item $index = Bio::DB::Bam->index('/path/to/file.bam',$reindex) Attempt to open the index for the indicated BAM file. If $reindex is true, and the index either does not exist or is out of date with respect to the BAM file (by checking modification dates), then attempt to rebuild the index. Will throw an exception if the index does not exist or if attempting to rebuild the index was unsuccessful. =item $index = Bio::DB::Bam->index_open('/path/to/file.bam') Attempt to open the index file for a BAM file, returning a Bio::DB::Bam::Index object. The filename path to use is the .bam file, not the .bai file. =item $index = Bio::DB::Bam->index_open_in_safewd('/path/to/file.bam' [,$mode]) When opening a remote BAM file, you may not wish for the index to be downloaded to the current working directory. This version of index_open copies the index into the directory indicated by the TMPDIR environment variable or the system-defined /tmp directory if not present. You may change the environment variable just before the call to change its behavior. =item $code = $index->fetch($bam,$tid,$start,$end,$callback [,$callback_data]) This is the low-level equivalent of the $sam->fetch() function described for the high-level API. Given a open BAM file object, the numeric ID of the reference sequence, start and end ranges on the reference, and a coderef, this function will traverse the region and repeatedly invoke the coderef with each Bio::DB::Bam::Alignment object that overlaps the region. Arguments: Argument Description -------- ----------- $bam The Bio::DB::Bam object that corresponds to the index object. $tid The target ID of the reference sequence. This can be obtained by calling $header->parse_region() with an appropriate opened Bio::DB::Bam::Header object. $start The start and end positions of the desired range on the reference sequence given by $tid, in 0-based $end coordinates. Like the $tid, these can be obtained from $header->parse_region(). $callback A coderef that will be called for each read overlapping the designated region. $callback_data Any arbitrary Perl data that you wish to pass to the $callback (optional). The coderef's call signature should look like this: my $callback = sub { my ($alignment,$data) = @_; ... } The first argument is a Bio::DB::Bam::Alignment object. The second is the callback data (if any) passed to fetch(). Fetch() returns an integer code, but its meaning is not described in the SAM/BAM C library documentation. =item $index->pileup($bam,$tid,$start,$end,$callback [,$callback_data]) This is the low-level version of the pileup() method, which allows you to invoke a coderef for every position in a BAM alignment. Arguments are: Argument Description -------- ----------- $bam The Bio::DB::Bam object that corresponds to the index object. $tid The target ID of the reference sequence. This can be obtained by calling $header->parse_region() with an appropriate opened Bio::DB::Bam::Header object. $start The start and end positions of the desired range on the reference sequence given by $tid, in 0-based $end coordinates. Like the $tid, these can be obtained from $header->parse_region(). $callback A coderef that will be called for each position of the alignment across the designated region. $callback_data Any arbitrary Perl data that you wish to pass to the $callback (optional). The callback will be invoked with four arguments corresponding to the numeric sequence ID of the reference sequence, the B<zero-based> position on the alignment, an arrayref of Bio::DB::Bam::Pileup objects, and the callback data, if any. A typical call signature will be this: $callback = sub { my ($tid,$pos,$pileups,$callback_data) = @_; for my $pileup (@$pileups) { # do something }; Note that the position argument is zero-based rather than 1-based, as it is in the high-level API. The Bio::DB::Bam::Pileup object was described earlier in the description of the high-level pileup() method. =item $coverage = $index->coverage($bam,$tid,$start,$end [,$bins [,maxcnt]]) Calculate coverage for the region on the target sequence given by $tid between positions $start and $end (zero-based coordinates). This method will return an array reference equal to the size of the region (by default). Each element of the array will be an integer indicating the number of reads aligning over that position. If you provide an option binsize in $bins, the array will be $bins elements in length, and each element will contain the average coverage over that region as a floating point number. By default, the underlying Samtools library caps coverage counting at a fixed value of 8000. You may change this default by providing an optional numeric sixth value, which changes the cap for the duration of the call, or by invoking Bio::DB::Sam->max_pileup_cnt($new_value), which changes the cap permanently. Unfortunately there is no way of specifying that you want an unlimited cap. =back =head2 BAM header methods The Bio::DB::Bam::Header object contains information regarding the reference sequence(s) used to construct the corresponding TAM or BAM file. It is most frequently used to translate between numeric target IDs and human-readable seq_ids. Headers can be created either from reading from a .fai file with the Bio::DB::Tam->header_read2() method, or by reading from a BAM file using Bio::DB::Bam->header(). You can also create header objects from scratch, although there is not much that you can do with such objects at this point. =over 4 =item $header = Bio::DB::Bam::Header->new() Return a new, empty, header object. =item $n_targets = $header->n_targets Return the number of reference sequences in the database. =item $name_arrayref = $header->target_name Return a reference to an array of reference sequence names, corresponding to the high-level API's seq_ids. To convert from a target ID to a seq_id, simply index into this array: $seq_id = $header->target_name->[$tid]; =item $length_arrayref = $header->target_len Return a reference to an array of reference sequence lengths. To get the length of the sequence corresponding to $tid, just index into the array returned by target_len(): $length = $header->target_len->[$tid]; =item $text = $header->text =item $header->text("new value") Read the text portion of the BAM header. The text can be replaced by providing the replacement string as an argument. Note that you should follow the header conventions when replacing the header text. No parsing or other error-checking is performed. =item ($tid,$start,$end) = $header->parse_region("seq_id:start-end") Given a string in the format "seqid:start-end" (using a human-readable seq_id and 1-based start and end coordinates), parse the string and return the target ID and start and end positions in 0-based coordinates. If the range is omitted, then the start and end coordinates of the entire sequence is returned. If only the end position is omitted, then the end of the sequence is assumed. =item $header->view1($alignment) This method will accept a Bio::DB::Bam::Alignment object, convert it to a line of TAM output, and write the output to STDOUT. In the low-level API there is currently no way to send the output to a different filehandle or capture it as a string. =back =head2 Bio::DB::Bam::Pileup methods An array of Bio::DB::Bam::Pileup object is passed to the pileup() callback for each position of a multi-read alignment. Each pileup object contains information about the alignment of a single read at a single position. =over 4 =item $alignment = $pileup->alignment Return the Bio::DB::Bam::Alignment object at this level. This provides you with access to the aligning read. =item $alignment = $pileup->b An alias for alignment(), provided for compatibility with the C API. =item $pos = $pileup->qpos The position of the aligning base in the read in zero-based coordinates. =item $pos = $pileup->pos The position of the aligning base in 1-based coordinates. =item $level = $pileup->level The "level" of the read in the BAM-generated text display of the alignment. =item $indel = $pileup->indel Length of the indel at this position: 0 for no indel, positive for an insertion (relative to the reference), negative for a deletion (relative to the reference sequence.) =item $flag = $pileup->is_del True if the base on the padded read is a deletion. =item $flag = $pileup->is_refskip True if the base on the padded read is a gap relative to the reference (denoted as < or > in the pileup) =item $flag = $pileup->is_head =item $flag = $pileup->is_del These fields are undocumented in the BAM documentation, but are exported to the Perl API just in case. =back =head2 The alignment objects Please see L<Bio::DB::Bam::Alignment> for documentation of the Bio::DB::Bam::Alignment and Bio::DB::Bam::AlignWrapper objects. =cut use strict; use warnings; use Carp 'croak'; use Bio::SeqFeature::Lite; use Bio::PrimarySeq; use base 'DynaLoader'; bootstrap Bio::DB::Sam; use Bio::DB::Bam::Alignment; use Bio::DB::Sam::Segment; use Bio::DB::Bam::AlignWrapper; use Bio::DB::Bam::PileupWrapper; use Bio::DB::Bam::FetchIterator; use Bio::DB::Bam::ReadIterator; use constant DUMP_INTERVAL => 1_000_000; sub new { my $class = shift; my %args = $_[0] =~ /^-/ ? @_ : (-bam=>shift); my $bam_path = $args{-bam} or croak "-bam argument required"; my $fa_path = $args{-fasta}; my $expand_flags = $args{-expand_flags}; my $split_splices = $args{-split} || $args{-split_splices}; my $autoindex = $args{-autoindex}; my $force_refseq = $args{-force_refseq}; # file existence checks unless ($class->is_remote($bam_path)) { -e $bam_path or croak "$bam_path does not exist"; -r _ or croak "is not readable"; } my $bam = Bio::DB::Bam->open($bam_path) or croak "$bam_path open: $!"; my $fai = $class->new_dna_accessor($fa_path) if $fa_path; my $self = bless { fai => $fai, bam => $bam, bam_path => $bam_path, fa_path => $fa_path, expand_flags => $expand_flags, split_splices => $split_splices, autoindex => $autoindex, force_refseq => $force_refseq, },ref $class || $class; $self->header; # catch it return $self; } sub bam { shift->{bam} } sub is_remote { my $self = shift; my $path = shift; return $path =~ /^(http|ftp):/; } sub clone { my $self = shift; $self->{bam} = Bio::DB::Bam->open($self->{bam_path}) if $self->{bam_path}; $self->{fai} = $self->new_dna_accessor($self->{fa_path}) if $self->{fa_path}; } sub header { my $self = shift; return $self->{header} ||= $self->{bam}->header; } sub bam_path { my $self = shift; return $self->{bam_path}; } sub fai { shift->{fai} } sub new_dna_accessor { my $self = shift; my $accessor = shift; return unless $accessor; if (-e $accessor) { # a file, assume it is a fasta file -r _ or croak "$accessor is not readable"; my $a = Bio::DB::Sam::Fai->open($accessor) or croak "$accessor open: $!" or croak "Can't open FASTA file $accessor: $!"; return $a; } if (ref $accessor && $self->can_do_seq($accessor)) { return $accessor; # already built } return; } sub can_do_seq { my $self = shift; my $obj = shift; return UNIVERSAL::can($obj,'seq') || UNIVERSAL::can($obj,'fetch_sequence'); } sub seq { my $self = shift; my ($seqid,$start,$end) = @_; my $fai = $self->fai or return 'N' x ($end-$start+1); return $fai->can('seq') ? $fai->seq($seqid,$start,$end) :$fai->can('fetch_sequence') ? $fai->fetch_sequence($seqid,$start,$end) :'N' x ($end-$start+1); } sub expand_flags { my $self = shift; my $d = $self->{expand_flags}; $self->{expand_flags} = shift if @_; $d; } sub split_splices { my $self = shift; my $d = $self->{split_splices}; $self->{split_splices} = shift if @_; $d; } sub autoindex { my $self = shift; my $d = $self->{autoindex}; $self->{autoindex} = shift if @_; $d; } sub force_refseq { my $self = shift; my $d = $self->{force_refseq}; $self->{force_refseq} = shift if @_; $d; } sub reset_read { my $self = shift; $self->{bam}->header; } sub n_targets { shift->header->n_targets; } sub target_name { my $self = shift; my $tid = shift; $self->{target_name} ||= $self->header->target_name; return $self->{target_name}->[$tid]; } sub target_len { my $self = shift; my $tid = shift; $self->{target_len} ||= $self->header->target_len; return $self->{target_len}->[$tid]; } sub seq_ids { my $self = shift; return @{$self->header->target_name}; } sub _cache_targets { my $self = shift; return $self->{targets} if exists $self->{targets}; my @targets = map {lc $_} @{$self->header->target_name}; my @lengths = @{$self->header->target_len}; my %targets; @targets{@targets} = @lengths; # just you try to figure out what this is doing! return $self->{targets} = \%targets; } sub length { my $self = shift; my $target_name = shift; return $self->_cache_targets->{lc $target_name}; } sub _fetch { my $self = shift; my $region = shift; my $callback = shift; my $header = $self->{bam}->header; $region =~ s/\.\.|,/-/; my ($seqid,$start,$end) = $header->parse_region($region); return unless defined $seqid; my $index = $self->bam_index; $index->fetch($self->{bam},$seqid,$start,$end,$callback,$self); } sub fetch { my $self = shift; my $region = shift; my $callback = shift; my $code = sub { my ($align,$self) = @_; $callback->(Bio::DB::Bam::AlignWrapper->new($align,$self)); }; $self->_fetch($region,$code); } sub pileup { my $self = shift; my ($region,$callback,$keep_level) = @_; my $header = $self->header; $region =~ s/\.\.|,/-/; my ($seqid,$start,$end) = $header->parse_region($region); return unless defined $seqid; my $refnames = $self->header->target_name; my $code = sub { my ($tid,$pos,$pileup) = @_; my $seqid = $refnames->[$tid]; my @p = map { Bio::DB::Bam::PileupWrapper->new($_,$self) } @$pileup; $callback->($seqid,$pos+1,\@p); }; my $index = $self->bam_index; if ($keep_level) { $index->lpileup($self->{bam},$seqid,$start,$end,$code); } else { $index->pileup($self->{bam},$seqid,$start,$end,$code); } } sub fast_pileup { my $self = shift; my ($region,$callback,$keep_level) = @_; my $header = $self->header; $region =~ s/\.\.|,/-/; my ($seqid,$start,$end) = $header->parse_region($region); return unless defined $seqid; my $refnames = $self->header->target_name; my $code = sub { my ($tid,$pos,$pileup) = @_; my $seqid = $refnames->[$tid]; $callback->($seqid,$pos+1,$pileup,$self); }; my $index = $self->bam_index; if ($keep_level) { $index->lpileup($self->{bam},$seqid,$start,$end,$code); } else { $index->pileup($self->{bam},$seqid,$start,$end,$code); } } # segment returns a segment across the reference # it will not work on a arbitrary aligned feature sub segment { my $self = shift; my ($seqid,$start,$end) = @_; if ($_[0] =~ /^-/) { my %args = @_; $seqid = $args{-seq_id} || $args{-name}; $start = $args{-start}; $end = $args{-stop} || $args{-end}; } else { ($seqid,$start,$end) = @_; } my $targets = $self->_cache_targets; return unless exists $targets->{lc $seqid}; $start = 1 unless defined $start; $end = $targets->{lc $seqid} unless defined $end; $start = 1 if $start < 1; $end = $targets->{lc $seqid} if $end > $targets->{lc $seqid}; return Bio::DB::Sam::Segment->new($self,$seqid,$start,$end); } sub get_features_by_location { my $self = shift; my %args; if ($_[0] =~ /^-/) { # named args %args = @_; } else { # positional args $args{-seq_id} = shift; $args{-start} = shift; $args{-end} = shift; } $self->features(%args); } sub get_features_by_attribute { my $self = shift; my %attributes = ref($_[0]) ? %{$_[0]} : @_; $self->features(-attributes=>\%attributes); } sub get_features_by_tag { shift->get_features_by_attribute(@_); } sub get_features_by_flag { shift->get_features_by_attribute(@_); } sub get_feature_by_name { my $self = shift; my %args; if ($_[0] =~ /^-/) { %args = @_; } else { $args{-name} = shift; } $self->features(%args); } sub get_features_by_name { shift->get_feature_by_name(@_) } sub get_feature_by_id { my $self = shift; my $id = shift; my ($name,$tid,$start,$end,$strand,$type) = map {s/%3B/;/ig;$_} split ';',$id; return unless $name && defined $tid; $type ||= 'match'; my $seqid = $self->target_name($tid); my @features = $self->features(-name=>$name, -type => $type, -seq_id=>$seqid, -start=>$start, -end=>$end, -strand=>$strand); return unless @features; return $features[0]; } sub get_seq_stream { my $self = shift; $self->features(@_,-iterator=>1); } sub get_seq_fh { my $self = shift; $self->features(@_,-fh=>1); } sub types { return qw(match read_pair coverage region chromosome); } sub features { my $self = shift; my %args; if (defined $_[0] && $_[0] !~ /^-/) { $args{-type} = \@_; } else { %args = @_; } my $seqid = $args{-seq_id} || $args{-seqid}; my $start = $args{-start}; my $end = $args{-end} || $args{-stop}; my $types = $args{-type} || $args{-types} || []; my $attributes = $args{-attributes} || $args{-tags} || $args{-flags}; my $iterator = $args{-iterator}; my $fh = $args{-fh}; my $filter = $args{-filter}; my $max = $args{-max_features}; $types = [$types] unless ref $types; $types = [$args{-class}] if !@$types && defined $args{-class}; my $use_index = defined $seqid; # we do some special casing to retrieve target (reference) sequences # if they are requested if (defined($args{-name}) && (!@$types || $types->[0]=~/region|chromosome/) && !defined $seqid) { my @results = $self->_segment_search(lc $args{-name}); return @results if @results; } elsif (@$types && $types->[0] =~ /region|chromosome/) { return map {$self->segment($_)} $self->seq_ids; } my %seenit; my @types = grep {!$seenit{$_}++} ref $types ? @$types : $types; @types = 'match' unless @types; # the filter is intended to be inserted into a closure # it will return undef from the closure unless the filter # criteria are satisfied if (!$filter) { $filter = ''; $filter .= $self->_filter_by_name(lc $args{-name}) if defined $args{-name}; $filter .= $self->_filter_by_attribute($attributes) if defined $attributes; } # Special cases for unmunged data if (@types == 1 && $types[0] =~ /^match/) { # if iterator is requested, and no indexing is possible, # then we directly iterate through the database using read1() if ($iterator && !$use_index) { $self->reset_read; my $code = eval "sub {my \$a=shift;$filter;1}"; die $@ if $@; return Bio::DB::Bam::ReadIterator->new($self,$self->{bam},$code); } # TAM filehandle retrieval is requested elsif ($fh) { return $self->_features_fh($seqid,$start,$end,$filter); } } # otherwise we're going to do a little magic my ($features,@result); for my $t (@types) { if ($t =~ /^(match|read_pair)/) { # fetch the features if type is 'match' or 'read_pair' $features = $self->_filter_features($seqid,$start,$end,$filter,undef,$max); # for "match" just return the alignments if ($t =~ /^(match)/) { push @result,@$features; } # otherwise aggregate mate pairs into two-level features elsif ($t =~ /^read_pair/) { $self->_build_mates($features,\@result); } next; } # create a coverage graph if type is 'coverage' # specify coverage:N, to create a map of N bins # units are coverage per bp # resulting array will be stored in the "coverage" attribute if ($t =~ /^coverage:?(\d*)/) { my $bins = $1; push @result,$self->_coverage($seqid,$start,$end,$bins,$filter); } } return $iterator ? Bio::DB::Bam::FetchIterator->new(\@result,$self->last_feature_count) : @result; } sub coverage2BedGraph { my $self = shift; my $fh = shift; $fh ||= \*STDOUT; my $header = $self->header; my $index = $self->bam_index; my $seqids = $header->target_name; my $lengths = $header->target_len; my $b = $self->bam; for my $tid (0..$header->n_targets-1) { my $seqid = $seqids->[$tid]; my $len = $lengths->[$tid]; my $sec_start = -1; my $last_val = -1; for (my $start=0;$start <= $len;$start += DUMP_INTERVAL) { my $end = $start+DUMP_INTERVAL; $end = $len if $end > $len; my $coverage = $index->coverage($b,$tid,$start,$end); for (my $i=0; $i<@$coverage; $i++) { if($last_val == -1) { $sec_start = 0; $last_val = $coverage->[$i]; } if($last_val != $coverage->[$i]) { print $fh $seqid,"\t",$sec_start,"\t",$start+$i,"\t",$last_val,"\n" unless $last_val == 0; $sec_start = $start+$i; $last_val = $coverage->[$i]; } elsif($start+$i == $len-1) { print $fh $seqid,"\t",$sec_start,"\t",$start+$i,"\t",$last_val,"\n" unless $last_val == 0; } } } } } sub _filter_features { my $self = shift; my ($seqid,$start,$end,$filter,$do_tam_fh,$max_features) = @_; my @result; my $action = $do_tam_fh ? '\$self->header->view1($a)' : $self->_push_features($max_features); my $user_code; if (ref ($filter) eq 'CODE') { $user_code = $filter; $filter = ''; } my $callback = defined($seqid) ? <<INDEXED : <<NONINDEXED; sub { my \$a = shift; $filter return unless defined \$a->start; $action; } INDEXED sub { my \$a = shift; $filter $action; } NONINDEXED ; my $code = eval $callback; die $@ if $@; if ($user_code) { my $new_callback = sub { my $a = shift; $code->($a) if $user_code->($a); }; $self->_features($seqid,$start,$end,$new_callback); } else { $self->_features($seqid,$start,$end,$code); } return \@result; } sub _push_features { my $self = shift; my $max = shift; # simple case -- no max specified. Will push onto an array called # @result. return 'push @result,Bio::DB::Bam::AlignWrapper->new($a,$self)' unless $max; $self->{_result_count} = 0; # otherwise we implement a simple subsampling my $code=<<END; my \$count = ++\$self->{_result_count}; if (\@result < $max) { push \@result,Bio::DB::Bam::AlignWrapper->new(\$a,\$self); } else { \$result[rand \@result] = Bio::DB::Bam::AlignWrapper->new(\$a,\$self) if rand() < $max/\$count; } END return $code; } sub last_feature_count { shift->{_result_count}||0 } sub _features { my $self = shift; my ($seqid,$start,$end,$callback) = @_; if (defined $seqid) { my $region = $seqid; if (defined $start) { $region .= ":$start"; $region .= "-$end" if defined $end; } $self->_fetch($region,$callback); } else { $self->reset_read; while (my $b = $self->{bam}->read1) { $callback->($b); } } } # build mate pairs sub _build_mates { my $self = shift; my ($src,$dest) = @_; my %read_pairs; for my $a (@$src) { my $name = $a->display_name; unless ($read_pairs{$name}) { my $isize = $a->isize; my $start = $isize >= 0 ? $a->start : $a->end+$isize+1; my $end = $isize <= 0 ? $a->end : $a->start+$isize-1; $read_pairs{$name} = Bio::SeqFeature::Lite->new( -display_name => $name, -seq_id => $a->seq_id, -start => $start, -end => $end, -type => 'read_pair', -class => 'read_pair', ); } my $d = $self->{split_splices}; if ($d) { my @parts = $a->get_SeqFeatures; if (!@parts) { $read_pairs{$name}->add_SeqFeature($a); } else { for my $x (@parts){ $read_pairs{$name}->add_SeqFeature($x); } } } else { $read_pairs{$name}->add_SeqFeature($a); } } for my $name (keys %read_pairs) { my $f = $read_pairs{$name}; my $primary_id = join(';', map {s/;/%3B/g; $_} ($f->display_name, ($f->get_SeqFeatures)[0]->tid, $f->start, $f->end, $f->strand, $f->type, ) ); $read_pairs{$name}->primary_id($primary_id); } push @$dest,values %read_pairs; } sub _coverage { my $self = shift; my ($seqid,$start,$end,$bins,$filter) = @_; # Currently filter is ignored. In reality, we should # turn filter into a callback and invoke it on each # position in the pileup. croak "cannot calculate coverage unless a -seq_id is provided" unless defined $seqid; my $region = $seqid; if (defined $start) { $region .= ":$start"; $region .= "-$end" if defined $end; } my $header = $self->{bam}->header; my ($id,$s,$e) = $header->parse_region($region); return unless defined $id; # parse_region may return a very high value if no end specified $end = $e >= 1<<29 ? $header->target_len->[$id] : $e; $start = $s+1; $bins ||= $end-$start+1; my $index = $self->bam_index; my $coverage = $index->coverage($self->{bam}, $id,$s,$e, $bins); return Bio::SeqFeature::Coverage->new( -display_name => "$seqid coverage", -seq_id => $seqid, -start => $start, -end => $end, -strand => 0, -type => "coverage:$bins", -class => "coverage:$bins", -attributes => { coverage => [$coverage] } ); } sub _segment_search { my $self = shift; my $name = shift; my $targets = $self->_cache_targets; return $self->segment($name) if $targets->{$name}; if (my $regexp = $self->_glob_match($name)) { my @results = grep {/^$regexp$/i} keys %$targets; return map {$self->segment($_)} @results; } return; } sub bam_index { my $self = shift; return $self->{bai} ||= Bio::DB::Bam->index($self->{bam_path},$self->autoindex); } sub _features_fh { my $self = shift; my ($seqid,$start,$end,$filter) = @_; my $result = open my $fh,"-|"; if (!$result) { # in child $self->_filter_features($seqid,$start,$end,$filter,'do_fh'); # will print TAM to stdout exit 0; } return $fh; } sub tam_fh { my $self = shift; return $self->features(-fh=>1); } sub max_pileup_cnt { my $self = shift; return Bio::DB::Bam->max_pileup_cnt(@_); } # return a fragment of code that will be placed in the eval "" filter # to eliminate alignments that don't match by name sub _filter_by_name { my $self = shift; my $name = shift; my $frag = "my \$name=\$a->qname; defined \$name or return; "; if (my $regexp = $self->_glob_match($name)) { $frag .= "return unless \$name =~ /^$regexp\$/i;\n"; } else { $frag .= "return unless lc \$name eq '$name';\n"; } } # return a fragment of code that will be placed in the eval "" filter # to eliminate alignments that don't match by attribute sub _filter_by_attribute { my $self = shift; my $attributes = shift; my $result; for my $tag (keys %$attributes) { $result .= "my \$value = lc \$a->get_tag_values('$tag');\n"; $result .= "return unless defined \$value;\n"; my @comps = ref $attributes->{$tag} eq 'ARRAY' ? @{$attributes->{$tag}} : $attributes->{$tag}; my @matches; for my $c (@comps) { if ($c =~ /^[+-]?[\deE.]+$/) { # numeric-looking argument push @matches,"CORE::length \$value && \$value == $c"; } elsif (my $regexp = $self->_glob_match($c)) { push @matches,"\$value =~ /^$regexp\$/i"; } else { push @matches,"\$value eq lc '$c'"; } } $result .= "return unless " . join (' OR ',@matches) . ";\n"; } return $result; } # turn a glob expression into a regexp sub _glob_match { my $self = shift; my $term = shift; return unless $term =~ /(?:^|[^\\])[*?]/; $term =~ s/(^|[^\\])([+\[\]^{}\$|\(\).])/$1\\$2/g; $term =~ s/(^|[^\\])\*/$1.*/g; $term =~ s/(^|[^\\])\?/$1./g; return $term; } package Bio::DB::Sam::Fai; sub open { shift->load(@_) } sub seq { my $self = shift; my ($seqid,$start,$end) = @_; my $region = $seqid; $region .= ":$start" if defined $start; $region .= "-$end" if defined $end; return $self->fetch($region) } package Bio::SeqFeature::Coverage; use base 'Bio::SeqFeature::Lite'; sub coverage { my $self = shift; my ($coverage) = $self->get_tag_values('coverage'); return wantarray ? @$coverage : $coverage; } sub source { my $self = shift; my $type = $self->type; my ($base,$width) = split ':',$type; return $width; } sub method { my $self = shift; my $type = $self->type; my ($base,$width) = split ':',$type; return $base; } sub gff3_string { my $self = shift; my $gff3 = $self->SUPER::gff3_string; my $coverage = $self->escape(join(',',$self->coverage)); $gff3 =~ s/coverage=[^;]+/coverage=$coverage/g; return $gff3; } package Bio::DB::Bam; use File::Spec; use Cwd; use Carp 'croak'; sub index { my $self = shift; my $path = shift; my $autoindex = shift; return $self->index_open_in_safewd($path) if Bio::DB::Sam->is_remote($path); if ($autoindex) { $self->reindex($path) unless -e "${path}.bai" && mtime($path) <= mtime("${path}.bai"); } croak "No index file for $path; try opening file with -autoindex" unless -e "${path}.bai"; return $self->index_open($path); } sub reindex { my $self = shift; my $path = shift; # if bam file is not sorted, then index_build will exit. # we spawn a shell to intercept this eventuality print STDERR "[bam_index_build] creating index for $path\n" if -t STDOUT; my $result = open my $fh,"-|"; die "Couldn't fork $!" unless defined $result; if ($result == 0) { # in child # dup stderr to stdout so that we can intercept messages from library open STDERR,">&STDOUT"; $self->index_build($path); exit 0; } my $mesg = <$fh>; $mesg ||= ''; close $fh; if ($mesg =~ /not sorted/i) { print STDERR "[bam_index_build] sorting by coordinate...\n" if -t STDOUT; $self->sort_core(0,$path,"$path.sorted"); rename "$path.sorted.bam",$path; $self->index_build($path); } elsif ($mesg) { die $mesg; } } # same as index_open(), but changes current wd to TMPDIR to accomodate # the C library when it tries to download the index file from remote # locations. sub index_open_in_safewd { my $self = shift; my $dir = getcwd; my $tmpdir = File::Spec->tmpdir; chdir($tmpdir); my $result = $self->index_open(@_); chdir $dir; $result; } sub mtime { my $path = shift; (stat($path))[9]; } 1; __END__ =head1 EXAMPLES For illustrative purposes only, here is an extremely stupid SNP caller that tallies up bases that are q>20 and calls a SNP if there are at least 4 non-N/non-indel bases at the position and at least 25% of them are a non-reference base. my @SNPs; # this will be list of SNPs my $snp_caller = sub { my ($seqid,$pos,$p) = @_; my $refbase = $sam->segment($seqid,$pos,$pos)->dna; my ($total,$different); for my $pileup (@$p) { my $b = $pileup->alignment; next if $pileup->indel or $pileup->is_refskip; # don't deal with these ;-) my $qbase = substr($b->qseq,$pileup->qpos,1); next if $qbase =~ /[nN]/; my $qscore = $b->qscore->[$pileup->qpos]; next unless $qscore > 25; $total++; $different++ if $refbase ne $qbase; } if ($total >= 4 && $different/$total >= 0.25) { push @SNPs,"$seqid:$pos"; } }; $sam->pileup('seq1',$snp_caller); print "Found SNPs: @SNPs\n"; =head1 GBrowse Compatibility The Bio::DB::Sam interface can be used as a backend to GBrowse (gmod.sourceforge.net/gbrowse). GBrowse can calculate and display coverage graphs across large regions, alignment cartoons across intermediate size regions, and detailed base-pair level alignments across small regions. Here is a typical configuration for a BAM database that contains information from a shotgun genomic sequencing project. Some notes: * It is important to set "search options = none" in order to avoid GBrowse trying to scan through the BAM database to match read names. This is a time-consuming operation. * The callback to "bgcolor" renders pairs whose mates are unmapped in red. * The callback to "balloon hover" causes a balloon to pop up with the read name when the user hovers over each paired read. Otherwise the default behavior would be to provide information about the pair as a whole. * When the user zooms out to 1001 bp or greaterp, the track switches to a coverage graph. [bamtest:database] db_adaptor = Bio::DB::Sam db_args = -bam /var/www/gbrowse2/databases/bamtest/ex1.bam search options= default [Pair] feature = read_pair glyph = segments database = bamtest draw_target = 1 show_mismatch = 1 bgcolor = sub { my $f = shift; return $f->get_tag_values('M_UNMAPPED') ? 'red' : 'green'; } fgcolor = green height = 3 label = sub {shift->display_name} label density = 50 bump = fast connector = dashed balloon hover = sub { my $f = shift; return '' unless $f->type eq 'match'; return 'Read: '.$f->display_name.' : '.$f->flag_str; } key = Read Pairs [Pair:1000] feature = coverage:1001 glyph = wiggle_xyplot height = 50 min_score = 0 autoscale = local To show alignment data correctly when the user is zoomed in, you should also provide a pointer to the FASTA file containing the reference genome. In this case, modify the db_args line to read: db_args = -bam /var/www/gbrowse2/databases/bamtest/ex1.bam -fasta /var/www/gbrowse2/databases/bamtest/ex1.fa =head1 SEE ALSO L<Bio::Perl>, L<Bio::DB::Bam::Alignment>, L<Bio::DB::Bam::Constants> =head1 AUTHOR Lincoln Stein E<lt>lincoln.stein@oicr.on.caE<gt>. E<lt>lincoln.stein@bmail.comE<gt> Copyright (c) 2009 Ontario Institute for Cancer Research. This package and its accompanying libraries is free software; you can redistribute it and/or modify it under the terms of the GPL (either version 1, or at your option, any later version) or the Artistic License 2.0. Refer to LICENSE for the full license text. In addition, please see DISCLAIMER.txt for disclaimers of warranty. =cut
irusri/GenIECMS
plugins/jbrowse/extlib/lib/perl5/x86_64-linux-gnu-thread-multi/Bio/DB/Sam.pm
Perl
bsd-3-clause
77,872
#!/bin/env perl ###################################################################### # Copyright (c) 2012, Yahoo! Inc. All rights reserved. # # This program is free software. You may copy or redistribute it under # the same terms as Perl itself. Please see the LICENSE.Artistic file # included with this project for the terms of the Artistic License # under which this project is licensed. ###################################################################### # # generate table of handlers for the rest interface # # $ gen_handler_table.pl < workerCC.cc > cc_handlers.conf # use warnings; use strict; $/ = undef; my $handlers = { 'global' => ['do_get_global_status_v1', 'do_create_global_status_v1', 'do_update_global_status_v1'] }; foreach my $x (split(/;/, <>)) { if ($x =~ /(?:WORKER_REGISTER\(\s*\S+\s*,\s*|this->register_handler\(\s*\")([^")\s]+)/s ) { my $handler = $1; $handler =~ /^do_\w+_(\w+)_\w+_\w+/; push @{$handlers->{$1}}, $handler; } } print <<EOM; { // this list is automatically generated during the build. "handlers" : [ EOM my $first = 1; foreach my $key (keys %$handlers) { foreach my $handler (sort @{$handlers->{$key}}) { print !$first ? ",\n" : ""; print " \"$handler\""; $first = 0; } } print "\n"; print " ]\n"; print "}\n";
yahoo/gearbox
common/build/gen_handler_table.pl
Perl
bsd-3-clause
1,389
#!/usr/bin/perl # Generate ZSH completion use strict; use warnings; my $curl = $ARGV[0] || 'curl'; my $regex = '\s+(?:(-[^\s]+),\s)?(--[^\s]+)\s([^\s.]+)?\s+(.*)'; my @opts = parse_main_opts('--help', $regex); my $opts_str; $opts_str .= qq{ $_ \\\n} foreach (@opts); chomp $opts_str; my $tmpl = <<"EOS"; #compdef curl # curl zsh completion local curcontext="\$curcontext" state state_descr line typeset -A opt_args local rc=1 _arguments -C -S \\ $opts_str '*:URL:_urls' && rc=0 return rc EOS print $tmpl; sub parse_main_opts { my ($cmd, $regex) = @_; my @list; my @lines = call_curl($cmd); foreach my $line (@lines) { my ($short, $long, $arg, $desc) = ($line =~ /^$regex/) or next; my $option = ''; $desc =~ s/'/'\\''/g if defined $desc; $desc =~ s/\[/\\\[/g if defined $desc; $desc =~ s/\]/\\\]/g if defined $desc; $option .= '{' . trim($short) . ',' if defined $short; $option .= trim($long) if defined $long; $option .= '}' if defined $short; $option .= '\'[' . trim($desc) . ']\'' if defined $desc; $option .= ":'$arg'" if defined $arg; $option .= ':_files' if defined $arg and ($arg eq '<file>' || $arg eq '<filename>' || $arg eq '<dir>'); push @list, $option; } # Sort longest first, because zsh won't complete an option listed # after one that's a prefix of it. @list = sort { $a =~ /([^=]*)/; my $ma = $1; $b =~ /([^=]*)/; my $mb = $1; length($mb) <=> length($ma) } @list; return @list; } sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s }; sub call_curl { my ($cmd) = @_; my $output = `"$curl" $cmd`; if ($? == -1) { die "Could not run curl: $!"; } elsif ((my $exit_code = $? >> 8) != 0) { die "curl returned $exit_code with output:\n$output"; } return split /\n/, $output; }
chrismaeda/ChatScript
SRC/curl/curl-7.56.1/scripts/zsh.pl
Perl
mit
1,953
package TryUser; use Try::Tiny; sub test_try { try { } } sub test_catch { try { } catch { } } sub test_finally { try { } finally { } } 1;
gitpan/Try-Tiny
t/lib/TryUser.pm
Perl
mit
141
# $Id: RFC1035.pm,v 2.102 2008/05/23 21:30:10 abigail Exp $ package Regexp::Common::URI::RFC1035; use strict; local $^W = 1; use Regexp::Common qw /pattern clean no_defaults/; use vars qw /$VERSION @EXPORT @EXPORT_OK %EXPORT_TAGS @ISA/; use Exporter (); @ISA = qw /Exporter/; ($VERSION) = q $Revision: 2.102 $ =~ /[\d.]+/g; my %vars; BEGIN { $vars {low} = [qw /$digit $letter $let_dig $let_dig_hyp $ldh_str/]; $vars {parts} = [qw /$label $subdomain/]; $vars {domain} = [qw /$domain/]; } use vars map {@$_} values %vars; @EXPORT = qw /$host/; @EXPORT_OK = map {@$_} values %vars; %EXPORT_TAGS = (%vars, ALL => [@EXPORT_OK]); # RFC 1035. $digit = "[0-9]"; $letter = "[A-Za-z]"; $let_dig = "[A-Za-z0-9]"; $let_dig_hyp = "[-A-Za-z0-9]"; $ldh_str = "(?:[-A-Za-z0-9]+)"; $label = "(?:$letter(?:(?:$ldh_str){0,61}$let_dig)?)"; $subdomain = "(?:$label(?:[.]$label)*)"; $domain = "(?: |(?:$subdomain))"; 1; __END__ =pod =head1 NAME Regexp::Common::URI::RFC1035 -- Definitions from RFC1035; =head1 SYNOPSIS use Regexp::Common::URI::RFC1035 qw /:ALL/; =head1 DESCRIPTION This package exports definitions from RFC1035. It's intended usage is for Regexp::Common::URI submodules only. Its interface might change without notice. =head1 REFERENCES =over 4 =item B<[RFC 1035]> Mockapetris, P.: I<DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION>. November 1987. =back =head1 HISTORY $Log: RFC1035.pm,v $ Revision 2.102 2008/05/23 21:30:10 abigail Changed email address Revision 2.101 2008/05/23 21:28:02 abigail Changed license Revision 2.100 2003/02/10 21:03:25 abigail Definitions of RFC 1035 =head1 AUTHOR Damian Conway (damian@conway.org) =head1 MAINTAINANCE This package is maintained by Abigail S<(I<regexp-common@abigail.be>)>. =head1 BUGS AND IRRITATIONS Bound to be plenty. =head1 COPYRIGHT This software is Copyright (c) 2001 - 2008, Damian Conway and Abigail. This module is free software, and maybe used under any of the following licenses: 1) The Perl Artistic License. See the file COPYRIGHT.AL. 2) The Perl Artistic License 2.0. See the file COPYRIGHT.AL2. 3) The BSD Licence. See the file COPYRIGHT.BSD. 4) The MIT Licence. See the file COPYRIGHT.MIT. =cut
schwern/Regexp-Common
lib/Regexp/Common/URI/RFC1035.pm
Perl
mit
2,356